1 /* Top level stuff for GDB, the GNU debugger.
2 
3    Copyright (C) 1999-2024 Free Software Foundation, Inc.
4 
5    Written by Elena Zannoni <ezannoni@cygnus.com> of Cygnus Solutions.
6 
7    This file is part of GDB.
8 
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21 
22 #include "gdbsupport/job-control.h"
23 #include "run-on-main-thread.h"
24 #include "top.h"
25 #include "ui.h"
26 #include "inferior.h"
27 #include "infrun.h"
28 #include "target.h"
29 #include "terminal.h"
30 #include "gdbsupport/event-loop.h"
31 #include "event-top.h"
32 #include "interps.h"
33 #include <signal.h>
34 #include "cli/cli-script.h"
35 #include "main.h"
36 #include "gdbthread.h"
37 #include "observable.h"
38 #include "cli/cli-cmds.h"
39 #include "annotate.h"
40 #include "maint.h"
41 #include "ser-event.h"
42 #include "gdbsupport/gdb_select.h"
43 #include "gdbsupport/gdb-sigmask.h"
44 #include "async-event.h"
45 #include "bt-utils.h"
46 #include "pager.h"
47 
48 /* readline include files.  */
49 #include "readline/readline.h"
50 #include "readline/history.h"
51 
52 #ifdef TUI
53 #include "tui/tui.h"
54 #endif
55 
56 /* readline defines this.  */
57 #undef savestring
58 
59 static std::string top_level_prompt ();
60 
61 /* Signal handlers.  */
62 #ifdef SIGQUIT
63 static void handle_sigquit (int sig);
64 #endif
65 #ifdef SIGHUP
66 static void handle_sighup (int sig);
67 #endif
68 
69 /* Functions to be invoked by the event loop in response to
70    signals.  */
71 #if defined (SIGQUIT) || defined (SIGHUP)
72 static void async_do_nothing (gdb_client_data);
73 #endif
74 #ifdef SIGHUP
75 static void async_disconnect (gdb_client_data);
76 #endif
77 #ifdef SIGTSTP
78 static void async_sigtstp_handler (gdb_client_data);
79 #endif
80 static void async_sigterm_handler (gdb_client_data arg);
81 
82 /* Instead of invoking (and waiting for) readline to read the command
83    line and pass it back for processing, we use readline's alternate
84    interface, via callback functions, so that the event loop can react
85    to other event sources while we wait for input.  */
86 
87 /* Important variables for the event loop.  */
88 
89 /* This is used to determine if GDB is using the readline library or
90    its own simplified form of readline.  It is used by the asynchronous
91    form of the set editing command.
92    ezannoni: as of 1999-04-29 I expect that this
93    variable will not be used after gdb is changed to use the event
94    loop as default engine, and event-top.c is merged into top.c.  */
95 bool set_editing_cmd_var;
96 
97 /* This is used to display the notification of the completion of an
98    asynchronous execution command.  */
99 bool exec_done_display_p = false;
100 
101 /* Used by the stdin event handler to compensate for missed stdin events.
102    Setting this to a non-zero value inside an stdin callback makes the callback
103    run again.  */
104 int call_stdin_event_handler_again_p;
105 
106 /* When true GDB will produce a minimal backtrace when a fatal signal is
107    reached (within GDB code).  */
108 static bool bt_on_fatal_signal = GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON;
109 
110 /* Implement 'maintenance show backtrace-on-fatal-signal'.  */
111 
112 static void
show_bt_on_fatal_signal(struct ui_file * file,int from_tty,struct cmd_list_element * cmd,const char * value)113 show_bt_on_fatal_signal (struct ui_file *file, int from_tty,
114                                struct cmd_list_element *cmd, const char *value)
115 {
116   gdb_printf (file, _("Backtrace on a fatal signal is %s.\n"), value);
117 }
118 
119 /* Signal handling variables.  */
120 /* Each of these is a pointer to a function that the event loop will
121    invoke if the corresponding signal has received.  The real signal
122    handlers mark these functions as ready to be executed and the event
123    loop, in a later iteration, calls them.  See the function
124    invoke_async_signal_handler.  */
125 static struct async_signal_handler *sigint_token;
126 #ifdef SIGHUP
127 static struct async_signal_handler *sighup_token;
128 #endif
129 #ifdef SIGQUIT
130 static struct async_signal_handler *sigquit_token;
131 #endif
132 #ifdef SIGTSTP
133 static struct async_signal_handler *sigtstp_token;
134 #endif
135 static struct async_signal_handler *async_sigterm_token;
136 
137 /* This hook is called by gdb_rl_callback_read_char_wrapper after each
138    character is processed.  */
139 void (*after_char_processing_hook) (void);
140 
141 #if RL_VERSION_MAJOR == 7
142 extern "C" void _rl_signal_handler (int);
143 #endif
144 
145 /* Wrapper function for calling into the readline library.  This takes
146    care of a couple things:
147 
148    - The event loop expects the callback function to have a parameter,
149      while readline expects none.
150 
151    - Propagation of GDB exceptions/errors thrown from INPUT_HANDLER
152      across readline requires special handling.
153 
154    On the exceptions issue:
155 
156    DWARF-based unwinding cannot cross code built without -fexceptions.
157    Any exception that tries to propagate through such code will fail
158    and the result is a call to std::terminate.  While some ABIs, such
159    as x86-64, require all code to be built with exception tables,
160    others don't.
161 
162    This is a problem when GDB calls some non-EH-aware C library code,
163    that calls into GDB again through a callback, and that GDB callback
164    code throws a C++ exception.  Turns out this is exactly what
165    happens with GDB's readline callback.
166 
167    In such cases, we must catch and save any C++ exception that might
168    be thrown from the GDB callback before returning to the
169    non-EH-aware code.  When the non-EH-aware function itself returns
170    back to GDB, we then rethrow the original C++ exception.
171 
172    In the readline case however, the right thing to do is to longjmp
173    out of the callback, rather than do a normal return -- there's no
174    way for the callback to return to readline an indication that an
175    error happened, so a normal return would have rl_callback_read_char
176    potentially continue processing further input, redisplay the
177    prompt, etc.  Instead of raw setjmp/longjmp however, we use our
178    sjlj-based TRY/CATCH mechanism, which knows to handle multiple
179    levels of active setjmp/longjmp frames, needed in order to handle
180    the readline callback recursing, as happens with e.g., secondary
181    prompts / queries, through gdb_readline_wrapper.  This must be
182    noexcept in order to avoid problems with mixing sjlj and
183    (sjlj-based) C++ exceptions.  */
184 
185 static struct gdb_exception
gdb_rl_callback_read_char_wrapper_noexcept()186 gdb_rl_callback_read_char_wrapper_noexcept () noexcept
187 {
188   struct gdb_exception gdb_expt;
189 
190   /* C++ exceptions can't normally be thrown across readline (unless
191      it is built with -fexceptions, but it won't by default on many
192      ABIs).  So we instead wrap the readline call with a sjlj-based
193      TRY/CATCH, and rethrow the GDB exception once back in GDB.  */
194   TRY_SJLJ
195     {
196       rl_callback_read_char ();
197 #if RL_VERSION_MAJOR >= 8
198       /* It can happen that readline (while in rl_callback_read_char)
199            received a signal, but didn't handle it yet.  Make sure it's handled
200            now.  If we don't do that we run into two related problems:
201            - we have to wait for another event triggering
202              rl_callback_read_char before the signal is handled
203            - there's no guarantee that the signal will be processed before the
204              event.  */
205       while (rl_pending_signal () != 0)
206           /* Do this in a while loop, in case rl_check_signals also leaves a
207              pending signal.  I'm not sure if that's possible, but it seems
208              better to handle the scenario than to assert.  */
209           rl_check_signals ();
210 #elif RL_VERSION_MAJOR == 7
211       /* Unfortunately, rl_check_signals is not available.  Use private
212            function _rl_signal_handler instead.  */
213 
214       while (rl_pending_signal () != 0)
215           _rl_signal_handler (rl_pending_signal ());
216 #else
217 #error "Readline major version >= 7 expected"
218 #endif
219       if (after_char_processing_hook)
220           (*after_char_processing_hook) ();
221     }
222   CATCH_SJLJ (ex, RETURN_MASK_ALL)
223     {
224       gdb_expt = std::move (ex);
225     }
226   END_CATCH_SJLJ
227 
228   return gdb_expt;
229 }
230 
231 static void
gdb_rl_callback_read_char_wrapper(gdb_client_data client_data)232 gdb_rl_callback_read_char_wrapper (gdb_client_data client_data)
233 {
234   struct gdb_exception gdb_expt
235     = gdb_rl_callback_read_char_wrapper_noexcept ();
236 
237   /* Rethrow using the normal EH mechanism.  */
238   if (gdb_expt.reason < 0)
239     throw_exception (std::move (gdb_expt));
240 }
241 
242 /* GDB's readline callback handler.  Calls the current INPUT_HANDLER,
243    and propagates GDB exceptions/errors thrown from INPUT_HANDLER back
244    across readline.  See gdb_rl_callback_read_char_wrapper.  This must
245    be noexcept in order to avoid problems with mixing sjlj and
246    (sjlj-based) C++ exceptions.  */
247 
248 static void
gdb_rl_callback_handler(char * rl)249 gdb_rl_callback_handler (char *rl) noexcept
250 {
251   /* This is static to avoid undefined behavior when calling longjmp
252      -- gdb_exception has a destructor with side effects.  */
253   static struct gdb_exception gdb_rl_expt;
254   struct ui *ui = current_ui;
255 
256   /* In bracketed paste mode, pasting a complete line can result in a
257      literal newline appearing at the end of LINE.  However, we never
258      want this in gdb.  */
259   if (rl != nullptr)
260     {
261       size_t len = strlen (rl);
262       while (len > 0 && (rl[len - 1] == '\r' || rl[len - 1] == '\n'))
263           --len;
264       rl[len] = '\0';
265     }
266 
267   try
268     {
269       /* Ensure the exception is reset on each call.  */
270       gdb_rl_expt = {};
271       ui->input_handler (gdb::unique_xmalloc_ptr<char> (rl));
272     }
273   catch (gdb_exception &ex)
274     {
275       gdb_rl_expt = std::move (ex);
276     }
277 
278   /* If we caught a GDB exception, longjmp out of the readline
279      callback.  There's no other way for the callback to signal to
280      readline that an error happened.  A normal return would have
281      readline potentially continue processing further input, redisplay
282      the prompt, etc.  (This is what GDB historically did when it was
283      a C program.)  Note that since we're long jumping, local variable
284      dtors are NOT run automatically.  */
285   if (gdb_rl_expt.reason < 0)
286     throw_exception_sjlj (gdb_rl_expt);
287 }
288 
289 /* Change the function to be invoked every time there is a character
290    ready on stdin.  This is used when the user sets the editing off,
291    therefore bypassing readline, and letting gdb handle the input
292    itself, via gdb_readline_no_editing_callback.  Also it is used in
293    the opposite case in which the user sets editing on again, by
294    restoring readline handling of the input.
295 
296    NOTE: this operates on input_fd, not instream.  If we are reading
297    commands from a file, instream will point to the file.  However, we
298    always read commands from a file with editing off.  This means that
299    the 'set editing on/off' will have effect only on the interactive
300    session.  */
301 
302 void
change_line_handler(int editing)303 change_line_handler (int editing)
304 {
305   struct ui *ui = current_ui;
306 
307   /* We can only have one instance of readline, so we only allow
308      editing on the main UI.  */
309   if (ui != main_ui)
310     return;
311 
312   /* Don't try enabling editing if the interpreter doesn't support it
313      (e.g., MI).  */
314   if (!top_level_interpreter ()->supports_command_editing ()
315       || !command_interp ()->supports_command_editing ())
316     return;
317 
318   if (editing)
319     {
320       gdb_assert (ui == main_ui);
321 
322       /* Turn on editing by using readline.  */
323       ui->call_readline = gdb_rl_callback_read_char_wrapper;
324     }
325   else
326     {
327       /* Turn off editing by using gdb_readline_no_editing_callback.  */
328       if (ui->command_editing)
329           gdb_rl_callback_handler_remove ();
330       ui->call_readline = gdb_readline_no_editing_callback;
331     }
332   ui->command_editing = editing;
333 }
334 
335 /* The functions below are wrappers for rl_callback_handler_remove and
336    rl_callback_handler_install that keep track of whether the callback
337    handler is installed in readline.  This is necessary because after
338    handling a target event of a background execution command, we may
339    need to reinstall the callback handler if it was removed due to a
340    secondary prompt.  See gdb_readline_wrapper_line.  We don't
341    unconditionally install the handler for every target event because
342    that also clears the line buffer, thus installing it while the user
343    is typing would lose input.  */
344 
345 /* Whether we've registered a callback handler with readline.  */
346 static bool callback_handler_installed;
347 
348 /* See event-top.h, and above.  */
349 
350 void
gdb_rl_callback_handler_remove(void)351 gdb_rl_callback_handler_remove (void)
352 {
353   gdb_assert (current_ui == main_ui);
354 
355   rl_callback_handler_remove ();
356   callback_handler_installed = false;
357 }
358 
359 /* See event-top.h, and above.  Note this wrapper doesn't have an
360    actual callback parameter because we always install
361    INPUT_HANDLER.  */
362 
363 void
gdb_rl_callback_handler_install(const char * prompt)364 gdb_rl_callback_handler_install (const char *prompt)
365 {
366   gdb_assert (current_ui == main_ui);
367 
368   /* Calling rl_callback_handler_install resets readline's input
369      buffer.  Calling this when we were already processing input
370      therefore loses input.  */
371   gdb_assert (!callback_handler_installed);
372 
373   rl_callback_handler_install (prompt, gdb_rl_callback_handler);
374   callback_handler_installed = true;
375 }
376 
377 /* See event-top.h, and above.  */
378 
379 void
gdb_rl_callback_handler_reinstall(void)380 gdb_rl_callback_handler_reinstall (void)
381 {
382   gdb_assert (current_ui == main_ui);
383 
384   if (!callback_handler_installed)
385     {
386       /* Passing NULL as prompt argument tells readline to not display
387            a prompt.  */
388       gdb_rl_callback_handler_install (NULL);
389     }
390 }
391 
392 /* Displays the prompt.  If the argument NEW_PROMPT is NULL, the
393    prompt that is displayed is the current top level prompt.
394    Otherwise, it displays whatever NEW_PROMPT is as a local/secondary
395    prompt.
396 
397    This is used after each gdb command has completed, and in the
398    following cases:
399 
400    1. When the user enters a command line which is ended by '\'
401    indicating that the command will continue on the next line.  In
402    that case the prompt that is displayed is the empty string.
403 
404    2. When the user is entering 'commands' for a breakpoint, or
405    actions for a tracepoint.  In this case the prompt will be '>'
406 
407    3. On prompting for pagination.  */
408 
409 void
display_gdb_prompt(const char * new_prompt)410 display_gdb_prompt (const char *new_prompt)
411 {
412   std::string actual_gdb_prompt;
413 
414   annotate_display_prompt ();
415 
416   /* Reset the nesting depth used when trace-commands is set.  */
417   reset_command_nest_depth ();
418 
419   /* Do not call the python hook on an explicit prompt change as
420      passed to this function, as this forms a secondary/local prompt,
421      IE, displayed but not set.  */
422   if (! new_prompt)
423     {
424       struct ui *ui = current_ui;
425 
426       if (ui->prompt_state == PROMPTED)
427           internal_error (_("double prompt"));
428       else if (ui->prompt_state == PROMPT_BLOCKED)
429           {
430             /* This is to trick readline into not trying to display the
431                prompt.  Even though we display the prompt using this
432                function, readline still tries to do its own display if
433                we don't call rl_callback_handler_install and
434                rl_callback_handler_remove (which readline detects
435                because a global variable is not set).  If readline did
436                that, it could mess up gdb signal handlers for SIGINT.
437                Readline assumes that between calls to rl_set_signals and
438                rl_clear_signals gdb doesn't do anything with the signal
439                handlers.  Well, that's not the case, because when the
440                target executes we change the SIGINT signal handler.  If
441                we allowed readline to display the prompt, the signal
442                handler change would happen exactly between the calls to
443                the above two functions.  Calling
444                rl_callback_handler_remove(), does the job.  */
445 
446             if (current_ui->command_editing)
447               gdb_rl_callback_handler_remove ();
448             return;
449           }
450       else if (ui->prompt_state == PROMPT_NEEDED)
451           {
452             /* Display the top level prompt.  */
453             actual_gdb_prompt = top_level_prompt ();
454             ui->prompt_state = PROMPTED;
455           }
456     }
457   else
458     actual_gdb_prompt = new_prompt;
459 
460   if (current_ui->command_editing)
461     {
462       gdb_rl_callback_handler_remove ();
463       gdb_rl_callback_handler_install (actual_gdb_prompt.c_str ());
464     }
465   /* new_prompt at this point can be the top of the stack or the one
466      passed in.  It can't be NULL.  */
467   else
468     {
469       /* Don't use a _filtered function here.  It causes the assumed
470            character position to be off, since the newline we read from
471            the user is not accounted for.  */
472       printf_unfiltered ("%s", actual_gdb_prompt.c_str ());
473       gdb_flush (gdb_stdout);
474     }
475 }
476 
477 /* Notify the 'before_prompt' observer, and run any additional actions
478    that must be done before we display the prompt.  */
479 static void
notify_before_prompt(const char * prompt)480 notify_before_prompt (const char *prompt)
481 {
482   /* Give observers a chance of changing the prompt.  E.g., the python
483      `gdb.prompt_hook' is installed as an observer.  */
484   gdb::observers::before_prompt.notify (prompt);
485 
486   /* As we are about to display the prompt, and so GDB might be sitting
487      idle for some time, close all the cached BFDs.  This ensures that
488      when we next start running a user command all BFDs will be reopened
489      as needed, and as a result, we will see any on-disk changes.  */
490   bfd_cache_close_all ();
491 }
492 
493 /* Return the top level prompt, as specified by "set prompt", possibly
494    overridden by the python gdb.prompt_hook hook, and then composed
495    with the prompt prefix and suffix (annotations).  */
496 
497 static std::string
top_level_prompt(void)498 top_level_prompt (void)
499 {
500   notify_before_prompt (get_prompt ().c_str ());
501 
502   const std::string &prompt = get_prompt ();
503 
504   if (annotation_level >= 2)
505     {
506       /* Prefix needs to have new line at end.  */
507       const char prefix[] = "\n\032\032pre-prompt\n";
508 
509       /* Suffix needs to have a new line at end and \032 \032 at
510            beginning.  */
511       const char suffix[] = "\n\032\032prompt\n";
512 
513       return std::string (prefix) + prompt.c_str () + suffix;
514     }
515 
516   return prompt;
517 }
518 
519 /* Get a reference to the current UI's line buffer.  This is used to
520    construct a whole line of input from partial input.  */
521 
522 static std::string &
get_command_line_buffer(void)523 get_command_line_buffer (void)
524 {
525   return current_ui->line_buffer;
526 }
527 
528 /* Re-enable stdin after the end of an execution command in
529    synchronous mode, or after an error from the target, and we aborted
530    the exec operation.  */
531 
532 void
async_enable_stdin(void)533 async_enable_stdin (void)
534 {
535   struct ui *ui = current_ui;
536 
537   if (ui->prompt_state == PROMPT_BLOCKED
538       && !ui->keep_prompt_blocked)
539     {
540       target_terminal::ours ();
541       ui->register_file_handler ();
542       ui->prompt_state = PROMPT_NEEDED;
543     }
544 }
545 
546 /* Disable reads from stdin (the console) marking the command as
547    synchronous.  */
548 
549 void
async_disable_stdin(void)550 async_disable_stdin (void)
551 {
552   struct ui *ui = current_ui;
553 
554   ui->prompt_state = PROMPT_BLOCKED;
555   ui->unregister_file_handler ();
556 }
557 
558 
559 /* Handle a gdb command line.  This function is called when
560    handle_line_of_input has concatenated one or more input lines into
561    a whole command.  */
562 
563 void
command_handler(const char * command)564 command_handler (const char *command)
565 {
566   struct ui *ui = current_ui;
567   const char *c;
568 
569   if (ui->instream == ui->stdin_stream)
570     reinitialize_more_filter ();
571 
572   scoped_command_stats stat_reporter (true);
573 
574   /* Do not execute commented lines.  */
575   for (c = command; *c == ' ' || *c == '\t'; c++)
576     ;
577   if (c[0] != '#')
578     {
579       execute_command (command, ui->instream == ui->stdin_stream);
580 
581       /* Do any commands attached to breakpoint we stopped at.  */
582       bpstat_do_actions ();
583     }
584 }
585 
586 /* Append RL, an input line returned by readline or one of its emulations, to
587    CMD_LINE_BUFFER.  Return true if we have a whole command line ready to be
588    processed by the command interpreter or false if the command line isn't
589    complete yet (input line ends in a backslash).  */
590 
591 static bool
command_line_append_input_line(std::string & cmd_line_buffer,const char * rl)592 command_line_append_input_line (std::string &cmd_line_buffer, const char *rl)
593 {
594   size_t len = strlen (rl);
595 
596   if (len > 0 && rl[len - 1] == '\\')
597     {
598       /* Don't copy the backslash and wait for more.  */
599       cmd_line_buffer.append (rl, len - 1);
600       return false;
601     }
602   else
603     {
604       /* Copy whole line including terminating null, and we're
605            done.  */
606       cmd_line_buffer.append (rl, len + 1);
607       return true;
608     }
609 }
610 
611 /* Handle a line of input coming from readline.
612 
613    If the read line ends with a continuation character (backslash), return
614    nullptr.  Otherwise, return a pointer to the command line, indicating a whole
615    command line is ready to be executed.
616 
617    The returned pointer may or may not point to CMD_LINE_BUFFER's internal
618    buffer.
619 
620    Return EOF on end of file.
621 
622    If REPEAT, handle command repetitions:
623 
624      - If the input command line is NOT empty, the command returned is
625        saved using save_command_line () so that it can be repeated later.
626 
627      - OTOH, if the input command line IS empty, return the saved
628        command instead of the empty input line.
629 */
630 
631 const char *
handle_line_of_input(std::string & cmd_line_buffer,const char * rl,int repeat,const char * annotation_suffix)632 handle_line_of_input (std::string &cmd_line_buffer,
633                           const char *rl, int repeat,
634                           const char *annotation_suffix)
635 {
636   struct ui *ui = current_ui;
637   int from_tty = ui->instream == ui->stdin_stream;
638 
639   if (rl == NULL)
640     return (char *) EOF;
641 
642   bool complete = command_line_append_input_line (cmd_line_buffer, rl);
643   if (!complete)
644     return NULL;
645 
646   if (from_tty && annotation_level > 1)
647     printf_unfiltered (("\n\032\032post-%s\n"), annotation_suffix);
648 
649 #define SERVER_COMMAND_PREFIX "server "
650   server_command = startswith (cmd_line_buffer.c_str (), SERVER_COMMAND_PREFIX);
651   if (server_command)
652     {
653       /* Note that we don't call `save_command_line'.  Between this
654            and the check in dont_repeat, this insures that repeating
655            will still do the right thing.  */
656       return cmd_line_buffer.c_str () + strlen (SERVER_COMMAND_PREFIX);
657     }
658 
659   /* Do history expansion if that is wished.  */
660   if (history_expansion_p && from_tty && current_ui->input_interactive_p ())
661     {
662       char *cmd_expansion;
663       int expanded;
664 
665       /* Note: here, we pass a pointer to the std::string's internal buffer as
666            a `char *`.  At the time of writing, readline's history_expand does
667            not modify the passed-in string.  Ideally, readline should be modified
668            to make that parameter `const char *`.  */
669       expanded = history_expand (&cmd_line_buffer[0], &cmd_expansion);
670       gdb::unique_xmalloc_ptr<char> history_value (cmd_expansion);
671       if (expanded)
672           {
673             /* Print the changes.  */
674             printf_unfiltered ("%s\n", history_value.get ());
675 
676             /* If there was an error, call this function again.  */
677             if (expanded < 0)
678               return cmd_line_buffer.c_str ();
679 
680             cmd_line_buffer = history_value.get ();
681           }
682     }
683 
684   /* If we just got an empty line, and that is supposed to repeat the
685      previous command, return the previously saved command.  */
686   const char *p1;
687   for (p1 = cmd_line_buffer.c_str (); *p1 == ' ' || *p1 == '\t'; p1++)
688     ;
689   if (repeat && *p1 == '\0')
690     return get_saved_command_line ();
691 
692   /* Add command to history if appropriate.  Note: lines consisting
693      solely of comments are also added to the command history.  This
694      is useful when you type a command, and then realize you don't
695      want to execute it quite yet.  You can comment out the command
696      and then later fetch it from the value history and remove the
697      '#'.  The kill ring is probably better, but some people are in
698      the habit of commenting things out.  */
699   if (cmd_line_buffer[0] != '\0' && from_tty && current_ui->input_interactive_p ())
700     gdb_add_history (cmd_line_buffer.c_str ());
701 
702   /* Save into global buffer if appropriate.  */
703   if (repeat)
704     {
705       save_command_line (cmd_line_buffer.c_str ());
706 
707       /* It is important that we return a pointer to the saved command line
708            here, for the `cmd_start == saved_command_line` check in
709            execute_command to work.  */
710       return get_saved_command_line ();
711     }
712 
713   return cmd_line_buffer.c_str ();
714 }
715 
716 /* See event-top.h.  */
717 
718 void
gdb_rl_deprep_term_function(void)719 gdb_rl_deprep_term_function (void)
720 {
721 #ifdef RL_STATE_EOF
722   std::optional<scoped_restore_tmpl<int>> restore_eof_found;
723 
724   if (RL_ISSTATE (RL_STATE_EOF))
725     {
726       printf_unfiltered ("quit\n");
727       restore_eof_found.emplace (&rl_eof_found, 0);
728     }
729 
730 #endif /* RL_STATE_EOF */
731 
732   rl_deprep_terminal ();
733 }
734 
735 /* Handle a complete line of input.  This is called by the callback
736    mechanism within the readline library.  Deal with incomplete
737    commands as well, by saving the partial input in a global
738    buffer.
739 
740    NOTE: This is the asynchronous version of the command_line_input
741    function.  */
742 
743 void
command_line_handler(gdb::unique_xmalloc_ptr<char> && rl)744 command_line_handler (gdb::unique_xmalloc_ptr<char> &&rl)
745 {
746   std::string &line_buffer = get_command_line_buffer ();
747   struct ui *ui = current_ui;
748 
749   const char *cmd = handle_line_of_input (line_buffer, rl.get (), 1, "prompt");
750   if (cmd == (char *) EOF)
751     {
752       /* stdin closed.  The connection with the terminal is gone.
753            This happens at the end of a testsuite run, after Expect has
754            hung up but GDB is still alive.  In such a case, we just quit
755            gdb killing the inferior program too.  This also happens if the
756            user sends EOF, which is usually bound to ctrl+d.  */
757 
758 #ifndef RL_STATE_EOF
759       /* When readline is using bracketed paste mode, then, when eof is
760            received, readline will emit the control sequence to leave
761            bracketed paste mode.
762 
763            This control sequence ends with \r, which means that the "quit" we
764            are about to print will overwrite the prompt on this line.
765 
766            The solution to this problem is to actually print the "quit"
767            message from gdb_rl_deprep_term_function (see above), however, we
768            can only do that if we can know, in that function, when eof was
769            received.
770 
771            Unfortunately, with older versions of readline, it is not possible
772            in the gdb_rl_deprep_term_function to know if eof was received or
773            not, and, as GDB can be built against the system readline, which
774            could be older than the readline in GDB's repository, then we
775            can't be sure that we can work around this prompt corruption in
776            the gdb_rl_deprep_term_function function.
777 
778            If we get here, RL_STATE_EOF is not defined.  This indicates that
779            we are using an older readline, and couldn't print the quit
780            message in gdb_rl_deprep_term_function.  So, what we do here is
781            check to see if bracketed paste mode is on or not.  If it's on
782            then we print a \n and then the quit, this means the user will
783            see:
784 
785            (gdb)
786            quit
787 
788            Rather than the usual:
789 
790            (gdb) quit
791 
792            Which we will get with a newer readline, but this really is the
793            best we can do with older versions of readline.  */
794       const char *value = rl_variable_value ("enable-bracketed-paste");
795       if (value != nullptr && strcmp (value, "on") == 0
796             && ((rl_readline_version >> 8) & 0xff) > 0x07)
797           printf_unfiltered ("\n");
798       printf_unfiltered ("quit\n");
799 #endif
800 
801       execute_command ("quit", 1);
802     }
803   else if (cmd == NULL)
804     {
805       /* We don't have a full line yet.  Print an empty prompt.  */
806       display_gdb_prompt ("");
807     }
808   else
809     {
810       ui->prompt_state = PROMPT_NEEDED;
811 
812       /* Ensure the UI's line buffer is empty for the next command.  */
813       SCOPE_EXIT { line_buffer.clear (); };
814 
815       command_handler (cmd);
816 
817       if (ui->prompt_state != PROMPTED)
818           display_gdb_prompt (0);
819     }
820 }
821 
822 /* Does reading of input from terminal w/o the editing features
823    provided by the readline library.  Calls the line input handler
824    once we have a whole input line.  */
825 
826 void
gdb_readline_no_editing_callback(gdb_client_data client_data)827 gdb_readline_no_editing_callback (gdb_client_data client_data)
828 {
829   int c;
830   std::string line_buffer;
831   struct ui *ui = current_ui;
832 
833   FILE *stream = ui->instream != nullptr ? ui->instream : ui->stdin_stream;
834   gdb_assert (stream != nullptr);
835 
836   /* We still need the while loop here, even though it would seem
837      obvious to invoke gdb_readline_no_editing_callback at every
838      character entered.  If not using the readline library, the
839      terminal is in cooked mode, which sends the characters all at
840      once.  Poll will notice that the input fd has changed state only
841      after enter is pressed.  At this point we still need to fetch all
842      the chars entered.  */
843 
844   while (1)
845     {
846       /* Read from stdin if we are executing a user defined command.
847            This is the right thing for prompt_for_continue, at least.  */
848       c = fgetc (stream);
849 
850       if (c == EOF)
851           {
852             if (!line_buffer.empty ())
853               {
854                 /* The last line does not end with a newline.  Return it, and
855                      if we are called again fgetc will still return EOF and
856                      we'll return NULL then.  */
857                 break;
858               }
859             ui->input_handler (NULL);
860             return;
861           }
862 
863       if (c == '\n')
864           {
865             if (!line_buffer.empty () && line_buffer.back () == '\r')
866               line_buffer.pop_back ();
867             break;
868           }
869 
870       line_buffer += c;
871     }
872 
873   ui->input_handler (make_unique_xstrdup (line_buffer.c_str ()));
874 }
875 
876 
877 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
878    otherwise, return false.  */
879 
880 static bool
unblock_signal(int sig)881 unblock_signal (int sig)
882 {
883 #if HAVE_SIGPROCMASK
884   sigset_t sigset;
885   sigemptyset (&sigset);
886   sigaddset (&sigset, sig);
887   gdb_sigmask (SIG_UNBLOCK, &sigset, 0);
888   return true;
889 #endif
890 
891   return false;
892 }
893 
894 /* Called to handle fatal signals.  SIG is the signal number.  */
895 
896 static void ATTRIBUTE_NORETURN
handle_fatal_signal(int sig)897 handle_fatal_signal (int sig)
898 {
899 #ifdef TUI
900   tui_disable ();
901 #endif
902 
903 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
904   const auto sig_write = [] (const char *msg) -> void
905   {
906     gdb_stderr->write_async_safe (msg, strlen (msg));
907   };
908 
909   if (bt_on_fatal_signal)
910     {
911       sig_write ("\n\n");
912       sig_write (_("Fatal signal: "));
913       sig_write (strsignal (sig));
914       sig_write ("\n");
915 
916       gdb_internal_backtrace ();
917 
918       sig_write (_("A fatal error internal to GDB has been detected, "
919                        "further\ndebugging is not possible.  GDB will now "
920                        "terminate.\n\n"));
921       sig_write (_("This is a bug, please report it."));
922       if (REPORT_BUGS_TO[0] != '\0')
923           {
924             sig_write (_("  For instructions, see:\n"));
925             sig_write (REPORT_BUGS_TO);
926             sig_write (".");
927           }
928       sig_write ("\n\n");
929 
930       gdb_stderr->flush ();
931     }
932 #endif
933 
934   /* If possible arrange for SIG to have its default behaviour (which
935      should be to terminate the current process), unblock SIG, and reraise
936      the signal.  This ensures GDB terminates with the expected signal.  */
937   if (signal (sig, SIG_DFL) != SIG_ERR
938       && unblock_signal (sig))
939     raise (sig);
940 
941   /* The above failed, so try to use SIGABRT to terminate GDB.  */
942 #ifdef SIGABRT
943   signal (SIGABRT, SIG_DFL);
944 #endif
945   abort ();                   /* ARI: abort */
946 }
947 
948 /* The SIGSEGV handler for this thread, or NULL if there is none.  GDB
949    always installs a global SIGSEGV handler, and then lets threads
950    indicate their interest in handling the signal by setting this
951    thread-local variable.
952 
953    This is a static variable instead of extern because on various platforms
954    (notably Cygwin) extern thread_local variables cause link errors.  So
955    instead, we have scoped_segv_handler_restore, which also makes it impossible
956    to accidentally forget to restore it to the original value.  */
957 
958 static thread_local void (*thread_local_segv_handler) (int);
959 
960 static void handle_sigsegv (int sig);
961 
962 /* Install the SIGSEGV handler.  */
963 static void
install_handle_sigsegv()964 install_handle_sigsegv ()
965 {
966 #if defined (HAVE_SIGACTION)
967   struct sigaction sa;
968   sa.sa_handler = handle_sigsegv;
969   sigemptyset (&sa.sa_mask);
970 #ifdef HAVE_SIGALTSTACK
971   sa.sa_flags = SA_ONSTACK;
972 #else
973   sa.sa_flags = 0;
974 #endif
975   sigaction (SIGSEGV, &sa, nullptr);
976 #else
977   signal (SIGSEGV, handle_sigsegv);
978 #endif
979 }
980 
981 /* Handler for SIGSEGV.  */
982 
983 static void
handle_sigsegv(int sig)984 handle_sigsegv (int sig)
985 {
986   install_handle_sigsegv ();
987 
988   if (thread_local_segv_handler == nullptr)
989     handle_fatal_signal (sig);
990   thread_local_segv_handler (sig);
991 }
992 
993 
994 
995 /* The serial event associated with the QUIT flag.  set_quit_flag sets
996    this, and check_quit_flag clears it.  Used by interruptible_select
997    to be able to do interruptible I/O with no race with the SIGINT
998    handler.  */
999 static struct serial_event *quit_serial_event;
1000 
1001 /* Initialization of signal handlers and tokens.  There are a number of
1002    different strategies for handling different signals here.
1003 
1004    For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
1005    handle_sig* for each of these signals.  These functions are the actual
1006    signal handlers associated to the signals via calls to signal().  The
1007    only job for these functions is to enqueue the appropriate
1008    event/procedure with the event loop.  The event loop will take care of
1009    invoking the queued procedures to perform the usual tasks associated
1010    with the reception of the signal.
1011 
1012    For SIGSEGV the handle_sig* function does all the work for handling this
1013    signal.
1014 
1015    For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
1016    terminate immediately.  */
1017 void
gdb_init_signals(void)1018 gdb_init_signals (void)
1019 {
1020   initialize_async_signal_handlers ();
1021 
1022   quit_serial_event = make_serial_event ();
1023 
1024   sigint_token =
1025     create_async_signal_handler (async_request_quit, NULL, "sigint");
1026   install_sigint_handler (handle_sigint);
1027 
1028   async_sigterm_token
1029     = create_async_signal_handler (async_sigterm_handler, NULL, "sigterm");
1030   signal (SIGTERM, handle_sigterm);
1031 
1032 #ifdef SIGQUIT
1033   sigquit_token =
1034     create_async_signal_handler (async_do_nothing, NULL, "sigquit");
1035   signal (SIGQUIT, handle_sigquit);
1036 #endif
1037 
1038 #ifdef SIGHUP
1039   if (signal (SIGHUP, handle_sighup) != SIG_IGN)
1040     sighup_token =
1041       create_async_signal_handler (async_disconnect, NULL, "sighup");
1042   else
1043     sighup_token =
1044       create_async_signal_handler (async_do_nothing, NULL, "sighup");
1045 #endif
1046 
1047 #ifdef SIGTSTP
1048   sigtstp_token =
1049     create_async_signal_handler (async_sigtstp_handler, NULL, "sigtstp");
1050 #endif
1051 
1052 #ifdef SIGFPE
1053   signal (SIGFPE, handle_fatal_signal);
1054 #endif
1055 
1056 #ifdef SIGBUS
1057   signal (SIGBUS, handle_fatal_signal);
1058 #endif
1059 
1060 #ifdef SIGABRT
1061   signal (SIGABRT, handle_fatal_signal);
1062 #endif
1063 
1064   install_handle_sigsegv ();
1065 }
1066 
1067 /* See event-top.h.  */
1068 
1069 void
quit(void)1070 quit (void)
1071 {
1072   if (sync_quit_force_run)
1073     {
1074       sync_quit_force_run = false;
1075       throw_forced_quit ("SIGTERM");
1076     }
1077 
1078 #ifdef __MSDOS__
1079   /* No steenking SIGINT will ever be coming our way when the
1080      program is resumed.  Don't lie.  */
1081   throw_quit ("Quit");
1082 #else
1083   if (job_control
1084       /* If there is no terminal switching for this target, then we can't
1085            possibly get screwed by the lack of job control.  */
1086       || !target_supports_terminal_ours ())
1087     throw_quit ("Quit");
1088   else
1089     throw_quit ("Quit (expect signal SIGINT when the program is resumed)");
1090 #endif
1091 }
1092 
1093 /* See event-top.h.  */
1094 
1095 void
maybe_quit()1096 maybe_quit ()
1097 {
1098   if (!is_main_thread ())
1099     return;
1100 
1101   if (sync_quit_force_run)
1102     quit ();
1103 
1104   quit_handler ();
1105 }
1106 
1107 /* See event-top.h.  */
1108 
1109 void
quit_serial_event_set()1110 quit_serial_event_set ()
1111 {
1112   serial_event_set (quit_serial_event);
1113 }
1114 
1115 /* See event-top.h.  */
1116 
1117 void
quit_serial_event_clear(void)1118 quit_serial_event_clear (void)
1119 {
1120   serial_event_clear (quit_serial_event);
1121 }
1122 
1123 /* Return the selectable file descriptor of the serial event
1124    associated with the quit flag.  */
1125 
1126 static int
quit_serial_event_fd(void)1127 quit_serial_event_fd (void)
1128 {
1129   return serial_event_fd (quit_serial_event);
1130 }
1131 
1132 /* See defs.h.  */
1133 
1134 void
default_quit_handler(void)1135 default_quit_handler (void)
1136 {
1137   if (check_quit_flag ())
1138     {
1139       if (target_terminal::is_ours ())
1140           quit ();
1141       else
1142           target_pass_ctrlc ();
1143     }
1144 }
1145 
1146 /* See defs.h.  */
1147 quit_handler_ftype *quit_handler = default_quit_handler;
1148 
1149 /* Handle a SIGINT.  */
1150 
1151 void
handle_sigint(int sig)1152 handle_sigint (int sig)
1153 {
1154   signal (sig, handle_sigint);
1155 
1156   /* We could be running in a loop reading in symfiles or something so
1157      it may be quite a while before we get back to the event loop.  So
1158      set quit_flag to true here.  Then if QUIT is called before we get to
1159      the event loop, we will unwind as expected.  */
1160   set_quit_flag ();
1161 
1162   /* In case nothing calls QUIT before the event loop is reached, the
1163      event loop handles it.  */
1164   mark_async_signal_handler (sigint_token);
1165 }
1166 
1167 /* See gdb_select.h.  */
1168 
1169 int
interruptible_select(int n,fd_set * readfds,fd_set * writefds,fd_set * exceptfds,struct timeval * timeout)1170 interruptible_select (int n,
1171                           fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
1172                           struct timeval *timeout)
1173 {
1174   fd_set my_readfds;
1175   int fd;
1176   int res;
1177 
1178   if (readfds == NULL)
1179     {
1180       readfds = &my_readfds;
1181       FD_ZERO (&my_readfds);
1182     }
1183 
1184   fd = quit_serial_event_fd ();
1185   FD_SET (fd, readfds);
1186   if (n <= fd)
1187     n = fd + 1;
1188 
1189   do
1190     {
1191       res = gdb_select (n, readfds, writefds, exceptfds, timeout);
1192     }
1193   while (res == -1 && errno == EINTR);
1194 
1195   if (res == 1 && FD_ISSET (fd, readfds))
1196     {
1197       errno = EINTR;
1198       return -1;
1199     }
1200   return res;
1201 }
1202 
1203 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p ().  */
1204 
1205 static void
async_sigterm_handler(gdb_client_data arg)1206 async_sigterm_handler (gdb_client_data arg)
1207 {
1208   quit_force (NULL, 0);
1209 }
1210 
1211 /* See defs.h.  */
1212 volatile bool sync_quit_force_run;
1213 
1214 /* See defs.h.  */
1215 void
set_force_quit_flag()1216 set_force_quit_flag ()
1217 {
1218   sync_quit_force_run = true;
1219   set_quit_flag ();
1220 }
1221 
1222 /* Quit GDB if SIGTERM is received.
1223    GDB would quit anyway, but this way it will clean up properly.  */
1224 void
handle_sigterm(int sig)1225 handle_sigterm (int sig)
1226 {
1227   signal (sig, handle_sigterm);
1228 
1229   set_force_quit_flag ();
1230 
1231   mark_async_signal_handler (async_sigterm_token);
1232 }
1233 
1234 /* Do the quit.  All the checks have been done by the caller.  */
1235 void
async_request_quit(gdb_client_data arg)1236 async_request_quit (gdb_client_data arg)
1237 {
1238   /* If the quit_flag has gotten reset back to false by the time we get
1239      back here, that means that an exception was thrown to unwind the
1240      current command before we got back to the event loop.  So there
1241      is no reason to call quit again here.  */
1242   QUIT;
1243 }
1244 
1245 #ifdef SIGQUIT
1246 /* Tell the event loop what to do if SIGQUIT is received.
1247    See event-signal.c.  */
1248 static void
handle_sigquit(int sig)1249 handle_sigquit (int sig)
1250 {
1251   mark_async_signal_handler (sigquit_token);
1252   signal (sig, handle_sigquit);
1253 }
1254 #endif
1255 
1256 #if defined (SIGQUIT) || defined (SIGHUP)
1257 /* Called by the event loop in response to a SIGQUIT or an
1258    ignored SIGHUP.  */
1259 static void
async_do_nothing(gdb_client_data arg)1260 async_do_nothing (gdb_client_data arg)
1261 {
1262   /* Empty function body.  */
1263 }
1264 #endif
1265 
1266 #ifdef SIGHUP
1267 /* Tell the event loop what to do if SIGHUP is received.
1268    See event-signal.c.  */
1269 static void
handle_sighup(int sig)1270 handle_sighup (int sig)
1271 {
1272   mark_async_signal_handler (sighup_token);
1273   signal (sig, handle_sighup);
1274 }
1275 
1276 /* Called by the event loop to process a SIGHUP.  */
1277 static void
async_disconnect(gdb_client_data arg)1278 async_disconnect (gdb_client_data arg)
1279 {
1280 
1281   try
1282     {
1283       quit_cover ();
1284     }
1285 
1286   catch (const gdb_exception &exception)
1287     {
1288       gdb_puts ("Could not kill the program being debugged",
1289                     gdb_stderr);
1290       exception_print (gdb_stderr, exception);
1291       if (exception.reason == RETURN_FORCED_QUIT)
1292           throw;
1293     }
1294 
1295   for (inferior *inf : all_inferiors ())
1296     {
1297       try
1298           {
1299             inf->pop_all_targets ();
1300           }
1301       catch (const gdb_exception &exception)
1302           {
1303           }
1304     }
1305 
1306   signal (SIGHUP, SIG_DFL);   /*FIXME: ???????????  */
1307   raise (SIGHUP);
1308 }
1309 #endif
1310 
1311 #ifdef SIGTSTP
1312 void
handle_sigtstp(int sig)1313 handle_sigtstp (int sig)
1314 {
1315   mark_async_signal_handler (sigtstp_token);
1316   signal (sig, handle_sigtstp);
1317 }
1318 
1319 static void
async_sigtstp_handler(gdb_client_data arg)1320 async_sigtstp_handler (gdb_client_data arg)
1321 {
1322   const std::string &prompt = get_prompt ();
1323 
1324   signal (SIGTSTP, SIG_DFL);
1325   unblock_signal (SIGTSTP);
1326   raise (SIGTSTP);
1327   signal (SIGTSTP, handle_sigtstp);
1328   printf_unfiltered ("%s", prompt.c_str ());
1329   gdb_flush (gdb_stdout);
1330 
1331   /* Forget about any previous command -- null line now will do
1332      nothing.  */
1333   dont_repeat ();
1334 }
1335 #endif /* SIGTSTP */
1336 
1337 
1338 
1339 /* Set things up for readline to be invoked via the alternate
1340    interface, i.e. via a callback function
1341    (gdb_rl_callback_read_char), and hook up instream to the event
1342    loop.  */
1343 
1344 void
gdb_setup_readline(int editing)1345 gdb_setup_readline (int editing)
1346 {
1347   struct ui *ui = current_ui;
1348 
1349   /* If the input stream is connected to a terminal, turn on editing.
1350      However, that is only allowed on the main UI, as we can only have
1351      one instance of readline.  Also, INSTREAM might be nullptr when
1352      executing a user-defined command.  */
1353   if (ui->instream != nullptr && ISATTY (ui->instream)
1354       && editing && ui == main_ui)
1355     {
1356       /* Tell gdb that we will be using the readline library.  This
1357            could be overwritten by a command in .gdbinit like 'set
1358            editing on' or 'off'.  */
1359       ui->command_editing = 1;
1360 
1361       /* When a character is detected on instream by select or poll,
1362            readline will be invoked via this callback function.  */
1363       ui->call_readline = gdb_rl_callback_read_char_wrapper;
1364 
1365       /* Tell readline to use the same input stream that gdb uses.  */
1366       rl_instream = ui->instream;
1367     }
1368   else
1369     {
1370       ui->command_editing = 0;
1371       ui->call_readline = gdb_readline_no_editing_callback;
1372     }
1373 
1374   /* Now create the event source for this UI's input file descriptor.
1375      Another source is going to be the target program (inferior), but
1376      that must be registered only when it actually exists (I.e. after
1377      we say 'run' or after we connect to a remote target.  */
1378   ui->register_file_handler ();
1379 }
1380 
1381 /* Disable command input through the standard CLI channels.  Used in
1382    the suspend proc for interpreters that use the standard gdb readline
1383    interface, like the cli & the mi.  */
1384 
1385 void
gdb_disable_readline(void)1386 gdb_disable_readline (void)
1387 {
1388   struct ui *ui = current_ui;
1389 
1390   if (ui->command_editing)
1391     gdb_rl_callback_handler_remove ();
1392   ui->unregister_file_handler ();
1393 }
1394 
scoped_segv_handler_restore(segv_handler_t new_handler)1395 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler)
1396 {
1397   m_old_handler = thread_local_segv_handler;
1398   thread_local_segv_handler = new_handler;
1399 }
1400 
~scoped_segv_handler_restore()1401 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1402 {
1403   thread_local_segv_handler = m_old_handler;
1404 }
1405 
1406 static const char debug_event_loop_off[] = "off";
1407 static const char debug_event_loop_all_except_ui[] = "all-except-ui";
1408 static const char debug_event_loop_all[] = "all";
1409 
1410 static const char *debug_event_loop_enum[] = {
1411   debug_event_loop_off,
1412   debug_event_loop_all_except_ui,
1413   debug_event_loop_all,
1414   nullptr
1415 };
1416 
1417 static const char *debug_event_loop_value = debug_event_loop_off;
1418 
1419 static void
set_debug_event_loop_command(const char * args,int from_tty,cmd_list_element * c)1420 set_debug_event_loop_command (const char *args, int from_tty,
1421                                     cmd_list_element *c)
1422 {
1423   if (debug_event_loop_value == debug_event_loop_off)
1424     debug_event_loop = debug_event_loop_kind::OFF;
1425   else if (debug_event_loop_value == debug_event_loop_all_except_ui)
1426     debug_event_loop = debug_event_loop_kind::ALL_EXCEPT_UI;
1427   else if (debug_event_loop_value == debug_event_loop_all)
1428     debug_event_loop = debug_event_loop_kind::ALL;
1429   else
1430     gdb_assert_not_reached ("Invalid debug event look kind value.");
1431 }
1432 
1433 static void
show_debug_event_loop_command(struct ui_file * file,int from_tty,struct cmd_list_element * cmd,const char * value)1434 show_debug_event_loop_command (struct ui_file *file, int from_tty,
1435                                      struct cmd_list_element *cmd, const char *value)
1436 {
1437   gdb_printf (file, _("Event loop debugging is %s.\n"), value);
1438 }
1439 
1440 void _initialize_event_top ();
1441 void
_initialize_event_top()1442 _initialize_event_top ()
1443 {
1444   add_setshow_enum_cmd ("event-loop", class_maintenance,
1445                               debug_event_loop_enum,
1446                               &debug_event_loop_value,
1447                               _("Set event-loop debugging."),
1448                               _("Show event-loop debugging."),
1449                               _("\
1450 Control whether to show event loop-related debug messages."),
1451                               set_debug_event_loop_command,
1452                               show_debug_event_loop_command,
1453                               &setdebuglist, &showdebuglist);
1454 
1455   add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance,
1456                                  &bt_on_fatal_signal, _("\
1457 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1458 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1459 Use \"on\" to enable, \"off\" to disable.\n\
1460 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1461 signal from within GDB itself.  This is a mechanism to help diagnose\n\
1462 crashes within GDB, not a mechanism for debugging inferiors."),
1463                                  gdb_internal_backtrace_set_cmd,
1464                                  show_bt_on_fatal_signal,
1465                                  &maintenance_set_cmdlist,
1466                                  &maintenance_show_cmdlist);
1467 }
1468