1 /* Top level stuff for GDB, the GNU debugger.
3 Copyright (C) 1999-2022 Free Software Foundation, Inc.
5 Written by Elena Zannoni <ezannoni@cygnus.com> of Cygnus Solutions.
7 This file is part of GDB.
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.
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.
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/>. */
28 #include "gdbsupport/event-loop.h"
29 #include "event-top.h"
32 #include "cli/cli-script.h" /* for reset_command_nest_depth */
34 #include "gdbthread.h"
35 #include "observable.h"
36 #include "gdbcmd.h" /* for dont_repeat() */
39 #include "gdbsupport/buffer.h"
40 #include "ser-event.h"
41 #include "gdbsupport/gdb_select.h"
42 #include "gdbsupport/gdb-sigmask.h"
43 #include "async-event.h"
46 /* readline include files. */
47 #include "readline/readline.h"
48 #include "readline/history.h"
50 /* readline defines this. */
53 static std::string
top_level_prompt ();
55 /* Signal handlers. */
57 static void handle_sigquit (int sig
);
60 static void handle_sighup (int sig
);
63 /* Functions to be invoked by the event loop in response to
65 #if defined (SIGQUIT) || defined (SIGHUP)
66 static void async_do_nothing (gdb_client_data
);
69 static void async_disconnect (gdb_client_data
);
72 static void async_sigtstp_handler (gdb_client_data
);
74 static void async_sigterm_handler (gdb_client_data arg
);
76 /* Instead of invoking (and waiting for) readline to read the command
77 line and pass it back for processing, we use readline's alternate
78 interface, via callback functions, so that the event loop can react
79 to other event sources while we wait for input. */
81 /* Important variables for the event loop. */
83 /* This is used to determine if GDB is using the readline library or
84 its own simplified form of readline. It is used by the asynchronous
85 form of the set editing command.
86 ezannoni: as of 1999-04-29 I expect that this
87 variable will not be used after gdb is changed to use the event
88 loop as default engine, and event-top.c is merged into top.c. */
89 bool set_editing_cmd_var
;
91 /* This is used to display the notification of the completion of an
92 asynchronous execution command. */
93 bool exec_done_display_p
= false;
95 /* Used by the stdin event handler to compensate for missed stdin events.
96 Setting this to a non-zero value inside an stdin callback makes the callback
98 int call_stdin_event_handler_again_p
;
100 /* When true GDB will produce a minimal backtrace when a fatal signal is
101 reached (within GDB code). */
102 static bool bt_on_fatal_signal
= GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON
;
104 /* Implement 'maintenance show backtrace-on-fatal-signal'. */
107 show_bt_on_fatal_signal (struct ui_file
*file
, int from_tty
,
108 struct cmd_list_element
*cmd
, const char *value
)
110 fprintf_filtered (file
, _("Backtrace on a fatal signal is %s.\n"), value
);
113 /* Signal handling variables. */
114 /* Each of these is a pointer to a function that the event loop will
115 invoke if the corresponding signal has received. The real signal
116 handlers mark these functions as ready to be executed and the event
117 loop, in a later iteration, calls them. See the function
118 invoke_async_signal_handler. */
119 static struct async_signal_handler
*sigint_token
;
121 static struct async_signal_handler
*sighup_token
;
124 static struct async_signal_handler
*sigquit_token
;
127 static struct async_signal_handler
*sigtstp_token
;
129 static struct async_signal_handler
*async_sigterm_token
;
131 /* This hook is called by gdb_rl_callback_read_char_wrapper after each
132 character is processed. */
133 void (*after_char_processing_hook
) (void);
136 /* Wrapper function for calling into the readline library. This takes
137 care of a couple things:
139 - The event loop expects the callback function to have a parameter,
140 while readline expects none.
142 - Propagation of GDB exceptions/errors thrown from INPUT_HANDLER
143 across readline requires special handling.
145 On the exceptions issue:
147 DWARF-based unwinding cannot cross code built without -fexceptions.
148 Any exception that tries to propagate through such code will fail
149 and the result is a call to std::terminate. While some ABIs, such
150 as x86-64, require all code to be built with exception tables,
153 This is a problem when GDB calls some non-EH-aware C library code,
154 that calls into GDB again through a callback, and that GDB callback
155 code throws a C++ exception. Turns out this is exactly what
156 happens with GDB's readline callback.
158 In such cases, we must catch and save any C++ exception that might
159 be thrown from the GDB callback before returning to the
160 non-EH-aware code. When the non-EH-aware function itself returns
161 back to GDB, we then rethrow the original C++ exception.
163 In the readline case however, the right thing to do is to longjmp
164 out of the callback, rather than do a normal return -- there's no
165 way for the callback to return to readline an indication that an
166 error happened, so a normal return would have rl_callback_read_char
167 potentially continue processing further input, redisplay the
168 prompt, etc. Instead of raw setjmp/longjmp however, we use our
169 sjlj-based TRY/CATCH mechanism, which knows to handle multiple
170 levels of active setjmp/longjmp frames, needed in order to handle
171 the readline callback recursing, as happens with e.g., secondary
172 prompts / queries, through gdb_readline_wrapper. This must be
173 noexcept in order to avoid problems with mixing sjlj and
174 (sjlj-based) C++ exceptions. */
176 static struct gdb_exception
177 gdb_rl_callback_read_char_wrapper_noexcept () noexcept
179 struct gdb_exception gdb_expt
;
181 /* C++ exceptions can't normally be thrown across readline (unless
182 it is built with -fexceptions, but it won't by default on many
183 ABIs). So we instead wrap the readline call with a sjlj-based
184 TRY/CATCH, and rethrow the GDB exception once back in GDB. */
187 rl_callback_read_char ();
188 if (after_char_processing_hook
)
189 (*after_char_processing_hook
) ();
191 CATCH_SJLJ (ex
, RETURN_MASK_ALL
)
193 gdb_expt
= std::move (ex
);
201 gdb_rl_callback_read_char_wrapper (gdb_client_data client_data
)
203 struct gdb_exception gdb_expt
204 = gdb_rl_callback_read_char_wrapper_noexcept ();
206 /* Rethrow using the normal EH mechanism. */
207 if (gdb_expt
.reason
< 0)
208 throw_exception (std::move (gdb_expt
));
211 /* GDB's readline callback handler. Calls the current INPUT_HANDLER,
212 and propagates GDB exceptions/errors thrown from INPUT_HANDLER back
213 across readline. See gdb_rl_callback_read_char_wrapper. This must
214 be noexcept in order to avoid problems with mixing sjlj and
215 (sjlj-based) C++ exceptions. */
218 gdb_rl_callback_handler (char *rl
) noexcept
220 /* This is static to avoid undefined behavior when calling longjmp
221 -- gdb_exception has a destructor with side effects. */
222 static struct gdb_exception gdb_rl_expt
;
223 struct ui
*ui
= current_ui
;
227 /* Ensure the exception is reset on each call. */
229 ui
->input_handler (gdb::unique_xmalloc_ptr
<char> (rl
));
231 catch (gdb_exception
&ex
)
233 gdb_rl_expt
= std::move (ex
);
236 /* If we caught a GDB exception, longjmp out of the readline
237 callback. There's no other way for the callback to signal to
238 readline that an error happened. A normal return would have
239 readline potentially continue processing further input, redisplay
240 the prompt, etc. (This is what GDB historically did when it was
241 a C program.) Note that since we're long jumping, local variable
242 dtors are NOT run automatically. */
243 if (gdb_rl_expt
.reason
< 0)
244 throw_exception_sjlj (gdb_rl_expt
);
247 /* Change the function to be invoked every time there is a character
248 ready on stdin. This is used when the user sets the editing off,
249 therefore bypassing readline, and letting gdb handle the input
250 itself, via gdb_readline_no_editing_callback. Also it is used in
251 the opposite case in which the user sets editing on again, by
252 restoring readline handling of the input.
254 NOTE: this operates on input_fd, not instream. If we are reading
255 commands from a file, instream will point to the file. However, we
256 always read commands from a file with editing off. This means that
257 the 'set editing on/off' will have effect only on the interactive
261 change_line_handler (int editing
)
263 struct ui
*ui
= current_ui
;
265 /* We can only have one instance of readline, so we only allow
266 editing on the main UI. */
270 /* Don't try enabling editing if the interpreter doesn't support it
272 if (!interp_supports_command_editing (top_level_interpreter ())
273 || !interp_supports_command_editing (command_interp ()))
278 gdb_assert (ui
== main_ui
);
280 /* Turn on editing by using readline. */
281 ui
->call_readline
= gdb_rl_callback_read_char_wrapper
;
285 /* Turn off editing by using gdb_readline_no_editing_callback. */
286 if (ui
->command_editing
)
287 gdb_rl_callback_handler_remove ();
288 ui
->call_readline
= gdb_readline_no_editing_callback
;
290 ui
->command_editing
= editing
;
293 /* The functions below are wrappers for rl_callback_handler_remove and
294 rl_callback_handler_install that keep track of whether the callback
295 handler is installed in readline. This is necessary because after
296 handling a target event of a background execution command, we may
297 need to reinstall the callback handler if it was removed due to a
298 secondary prompt. See gdb_readline_wrapper_line. We don't
299 unconditionally install the handler for every target event because
300 that also clears the line buffer, thus installing it while the user
301 is typing would lose input. */
303 /* Whether we've registered a callback handler with readline. */
304 static int callback_handler_installed
;
306 /* See event-top.h, and above. */
309 gdb_rl_callback_handler_remove (void)
311 gdb_assert (current_ui
== main_ui
);
313 rl_callback_handler_remove ();
314 callback_handler_installed
= 0;
317 /* See event-top.h, and above. Note this wrapper doesn't have an
318 actual callback parameter because we always install
322 gdb_rl_callback_handler_install (const char *prompt
)
324 gdb_assert (current_ui
== main_ui
);
326 /* Calling rl_callback_handler_install resets readline's input
327 buffer. Calling this when we were already processing input
328 therefore loses input. */
329 gdb_assert (!callback_handler_installed
);
331 rl_callback_handler_install (prompt
, gdb_rl_callback_handler
);
332 callback_handler_installed
= 1;
335 /* See event-top.h, and above. */
338 gdb_rl_callback_handler_reinstall (void)
340 gdb_assert (current_ui
== main_ui
);
342 if (!callback_handler_installed
)
344 /* Passing NULL as prompt argument tells readline to not display
346 gdb_rl_callback_handler_install (NULL
);
350 /* Displays the prompt. If the argument NEW_PROMPT is NULL, the
351 prompt that is displayed is the current top level prompt.
352 Otherwise, it displays whatever NEW_PROMPT is as a local/secondary
355 This is used after each gdb command has completed, and in the
358 1. When the user enters a command line which is ended by '\'
359 indicating that the command will continue on the next line. In
360 that case the prompt that is displayed is the empty string.
362 2. When the user is entering 'commands' for a breakpoint, or
363 actions for a tracepoint. In this case the prompt will be '>'
365 3. On prompting for pagination. */
368 display_gdb_prompt (const char *new_prompt
)
370 std::string actual_gdb_prompt
;
372 annotate_display_prompt ();
374 /* Reset the nesting depth used when trace-commands is set. */
375 reset_command_nest_depth ();
377 /* Do not call the python hook on an explicit prompt change as
378 passed to this function, as this forms a secondary/local prompt,
379 IE, displayed but not set. */
382 struct ui
*ui
= current_ui
;
384 if (ui
->prompt_state
== PROMPTED
)
385 internal_error (__FILE__
, __LINE__
, _("double prompt"));
386 else if (ui
->prompt_state
== PROMPT_BLOCKED
)
388 /* This is to trick readline into not trying to display the
389 prompt. Even though we display the prompt using this
390 function, readline still tries to do its own display if
391 we don't call rl_callback_handler_install and
392 rl_callback_handler_remove (which readline detects
393 because a global variable is not set). If readline did
394 that, it could mess up gdb signal handlers for SIGINT.
395 Readline assumes that between calls to rl_set_signals and
396 rl_clear_signals gdb doesn't do anything with the signal
397 handlers. Well, that's not the case, because when the
398 target executes we change the SIGINT signal handler. If
399 we allowed readline to display the prompt, the signal
400 handler change would happen exactly between the calls to
401 the above two functions. Calling
402 rl_callback_handler_remove(), does the job. */
404 if (current_ui
->command_editing
)
405 gdb_rl_callback_handler_remove ();
408 else if (ui
->prompt_state
== PROMPT_NEEDED
)
410 /* Display the top level prompt. */
411 actual_gdb_prompt
= top_level_prompt ();
412 ui
->prompt_state
= PROMPTED
;
416 actual_gdb_prompt
= new_prompt
;
418 if (current_ui
->command_editing
)
420 gdb_rl_callback_handler_remove ();
421 gdb_rl_callback_handler_install (actual_gdb_prompt
.c_str ());
423 /* new_prompt at this point can be the top of the stack or the one
424 passed in. It can't be NULL. */
427 /* Don't use a _filtered function here. It causes the assumed
428 character position to be off, since the newline we read from
429 the user is not accounted for. */
430 printf_unfiltered ("%s", actual_gdb_prompt
.c_str ());
431 gdb_flush (gdb_stdout
);
435 /* Return the top level prompt, as specified by "set prompt", possibly
436 overridden by the python gdb.prompt_hook hook, and then composed
437 with the prompt prefix and suffix (annotations). */
440 top_level_prompt (void)
442 /* Give observers a chance of changing the prompt. E.g., the python
443 `gdb.prompt_hook' is installed as an observer. */
444 gdb::observers::before_prompt
.notify (get_prompt ().c_str ());
446 const std::string
&prompt
= get_prompt ();
448 if (annotation_level
>= 2)
450 /* Prefix needs to have new line at end. */
451 const char prefix
[] = "\n\032\032pre-prompt\n";
453 /* Suffix needs to have a new line at end and \032 \032 at
455 const char suffix
[] = "\n\032\032prompt\n";
457 return std::string (prefix
) + prompt
.c_str () + suffix
;
466 struct ui
*current_ui
;
469 /* Get a pointer to the current UI's line buffer. This is used to
470 construct a whole line of input from partial input. */
472 static struct buffer
*
473 get_command_line_buffer (void)
475 return ¤t_ui
->line_buffer
;
478 /* When there is an event ready on the stdin file descriptor, instead
479 of calling readline directly throught the callback function, or
480 instead of calling gdb_readline_no_editing_callback, give gdb a
481 chance to detect errors and do something. */
484 stdin_event_handler (int error
, gdb_client_data client_data
)
486 struct ui
*ui
= (struct ui
*) client_data
;
490 /* Switch to the main UI, so diagnostics always go there. */
491 current_ui
= main_ui
;
493 delete_file_handler (ui
->input_fd
);
496 /* If stdin died, we may as well kill gdb. */
497 fprintf_unfiltered (gdb_stderr
, _("error detected on stdin\n"));
498 quit_command ((char *) 0, 0);
502 /* Simply delete the UI. */
508 /* Switch to the UI whose input descriptor woke up the event
512 /* This makes sure a ^C immediately followed by further input is
513 always processed in that order. E.g,. with input like
514 "^Cprint 1\n", the SIGINT handler runs, marks the async
515 signal handler, and then select/poll may return with stdin
516 ready, instead of -1/EINTR. The
517 gdb.base/double-prompt-target-event-error.exp test exercises
523 call_stdin_event_handler_again_p
= 0;
524 ui
->call_readline (client_data
);
526 while (call_stdin_event_handler_again_p
!= 0);
533 ui_register_input_event_handler (struct ui
*ui
)
535 add_file_handler (ui
->input_fd
, stdin_event_handler
, ui
,
536 string_printf ("ui-%d", ui
->num
), true);
542 ui_unregister_input_event_handler (struct ui
*ui
)
544 delete_file_handler (ui
->input_fd
);
547 /* Re-enable stdin after the end of an execution command in
548 synchronous mode, or after an error from the target, and we aborted
549 the exec operation. */
552 async_enable_stdin (void)
554 struct ui
*ui
= current_ui
;
556 if (ui
->prompt_state
== PROMPT_BLOCKED
)
558 target_terminal::ours ();
559 ui_register_input_event_handler (ui
);
560 ui
->prompt_state
= PROMPT_NEEDED
;
564 /* Disable reads from stdin (the console) marking the command as
568 async_disable_stdin (void)
570 struct ui
*ui
= current_ui
;
572 ui
->prompt_state
= PROMPT_BLOCKED
;
573 delete_file_handler (ui
->input_fd
);
577 /* Handle a gdb command line. This function is called when
578 handle_line_of_input has concatenated one or more input lines into
582 command_handler (const char *command
)
584 struct ui
*ui
= current_ui
;
587 if (ui
->instream
== ui
->stdin_stream
)
588 reinitialize_more_filter ();
590 scoped_command_stats
stat_reporter (true);
592 /* Do not execute commented lines. */
593 for (c
= command
; *c
== ' ' || *c
== '\t'; c
++)
597 execute_command (command
, ui
->instream
== ui
->stdin_stream
);
599 /* Do any commands attached to breakpoint we stopped at. */
600 bpstat_do_actions ();
604 /* Append RL, an input line returned by readline or one of its
605 emulations, to CMD_LINE_BUFFER. Returns the command line if we
606 have a whole command line ready to be processed by the command
607 interpreter or NULL if the command line isn't complete yet (input
608 line ends in a backslash). */
611 command_line_append_input_line (struct buffer
*cmd_line_buffer
, const char *rl
)
618 if (len
> 0 && rl
[len
- 1] == '\\')
620 /* Don't copy the backslash and wait for more. */
621 buffer_grow (cmd_line_buffer
, rl
, len
- 1);
626 /* Copy whole line including terminating null, and we're
628 buffer_grow (cmd_line_buffer
, rl
, len
+ 1);
629 cmd
= cmd_line_buffer
->buffer
;
635 /* Handle a line of input coming from readline.
637 If the read line ends with a continuation character (backslash),
638 save the partial input in CMD_LINE_BUFFER (except the backslash),
639 and return NULL. Otherwise, save the partial input and return a
640 pointer to CMD_LINE_BUFFER's buffer (null terminated), indicating a
641 whole command line is ready to be executed.
643 Returns EOF on end of file.
645 If REPEAT, handle command repetitions:
647 - If the input command line is NOT empty, the command returned is
648 saved using save_command_line () so that it can be repeated later.
650 - OTOH, if the input command line IS empty, return the saved
651 command instead of the empty input line.
655 handle_line_of_input (struct buffer
*cmd_line_buffer
,
656 const char *rl
, int repeat
,
657 const char *annotation_suffix
)
659 struct ui
*ui
= current_ui
;
660 int from_tty
= ui
->instream
== ui
->stdin_stream
;
667 cmd
= command_line_append_input_line (cmd_line_buffer
, rl
);
671 /* We have a complete command line now. Prepare for the next
672 command, but leave ownership of memory to the buffer . */
673 cmd_line_buffer
->used_size
= 0;
675 if (from_tty
&& annotation_level
> 1)
677 printf_unfiltered (("\n\032\032post-"));
678 puts_unfiltered (annotation_suffix
);
679 printf_unfiltered (("\n"));
682 #define SERVER_COMMAND_PREFIX "server "
683 server_command
= startswith (cmd
, SERVER_COMMAND_PREFIX
);
686 /* Note that we don't call `save_command_line'. Between this
687 and the check in dont_repeat, this insures that repeating
688 will still do the right thing. */
689 return cmd
+ strlen (SERVER_COMMAND_PREFIX
);
692 /* Do history expansion if that is wished. */
693 if (history_expansion_p
&& from_tty
&& input_interactive_p (current_ui
))
698 expanded
= history_expand (cmd
, &cmd_expansion
);
699 gdb::unique_xmalloc_ptr
<char> history_value (cmd_expansion
);
704 /* Print the changes. */
705 printf_unfiltered ("%s\n", history_value
.get ());
707 /* If there was an error, call this function again. */
711 /* history_expand returns an allocated string. Just replace
712 our buffer with it. */
713 len
= strlen (history_value
.get ());
714 xfree (buffer_finish (cmd_line_buffer
));
715 cmd_line_buffer
->buffer
= history_value
.get ();
716 cmd_line_buffer
->buffer_size
= len
+ 1;
717 cmd
= history_value
.release ();
721 /* If we just got an empty line, and that is supposed to repeat the
722 previous command, return the previously saved command. */
723 for (p1
= cmd
; *p1
== ' ' || *p1
== '\t'; p1
++)
725 if (repeat
&& *p1
== '\0')
726 return get_saved_command_line ();
728 /* Add command to history if appropriate. Note: lines consisting
729 solely of comments are also added to the command history. This
730 is useful when you type a command, and then realize you don't
731 want to execute it quite yet. You can comment out the command
732 and then later fetch it from the value history and remove the
733 '#'. The kill ring is probably better, but some people are in
734 the habit of commenting things out. */
735 if (*cmd
!= '\0' && from_tty
&& input_interactive_p (current_ui
))
736 gdb_add_history (cmd
);
738 /* Save into global buffer if appropriate. */
741 save_command_line (cmd
);
742 return get_saved_command_line ();
748 /* Handle a complete line of input. This is called by the callback
749 mechanism within the readline library. Deal with incomplete
750 commands as well, by saving the partial input in a global
753 NOTE: This is the asynchronous version of the command_line_input
757 command_line_handler (gdb::unique_xmalloc_ptr
<char> &&rl
)
759 struct buffer
*line_buffer
= get_command_line_buffer ();
760 struct ui
*ui
= current_ui
;
763 cmd
= handle_line_of_input (line_buffer
, rl
.get (), 1, "prompt");
764 if (cmd
== (char *) EOF
)
766 /* stdin closed. The connection with the terminal is gone.
767 This happens at the end of a testsuite run, after Expect has
768 hung up but GDB is still alive. In such a case, we just quit
769 gdb killing the inferior program too. */
770 printf_unfiltered ("quit\n");
771 execute_command ("quit", 1);
773 else if (cmd
== NULL
)
775 /* We don't have a full line yet. Print an empty prompt. */
776 display_gdb_prompt ("");
780 ui
->prompt_state
= PROMPT_NEEDED
;
782 command_handler (cmd
);
784 if (ui
->prompt_state
!= PROMPTED
)
785 display_gdb_prompt (0);
789 /* Does reading of input from terminal w/o the editing features
790 provided by the readline library. Calls the line input handler
791 once we have a whole input line. */
794 gdb_readline_no_editing_callback (gdb_client_data client_data
)
798 struct buffer line_buffer
;
799 static int done_once
= 0;
800 struct ui
*ui
= current_ui
;
802 buffer_init (&line_buffer
);
804 /* Unbuffer the input stream, so that, later on, the calls to fgetc
805 fetch only one char at the time from the stream. The fgetc's will
806 get up to the first newline, but there may be more chars in the
807 stream after '\n'. If we buffer the input and fgetc drains the
808 stream, getting stuff beyond the newline as well, a select, done
809 afterwards will not trigger. */
810 if (!done_once
&& !ISATTY (ui
->instream
))
812 setbuf (ui
->instream
, NULL
);
816 /* We still need the while loop here, even though it would seem
817 obvious to invoke gdb_readline_no_editing_callback at every
818 character entered. If not using the readline library, the
819 terminal is in cooked mode, which sends the characters all at
820 once. Poll will notice that the input fd has changed state only
821 after enter is pressed. At this point we still need to fetch all
822 the chars entered. */
826 /* Read from stdin if we are executing a user defined command.
827 This is the right thing for prompt_for_continue, at least. */
828 c
= fgetc (ui
->instream
!= NULL
? ui
->instream
: ui
->stdin_stream
);
832 if (line_buffer
.used_size
> 0)
834 /* The last line does not end with a newline. Return it, and
835 if we are called again fgetc will still return EOF and
836 we'll return NULL then. */
839 xfree (buffer_finish (&line_buffer
));
840 ui
->input_handler (NULL
);
846 if (line_buffer
.used_size
> 0
847 && line_buffer
.buffer
[line_buffer
.used_size
- 1] == '\r')
848 line_buffer
.used_size
--;
852 buffer_grow_char (&line_buffer
, c
);
855 buffer_grow_char (&line_buffer
, '\0');
856 result
= buffer_finish (&line_buffer
);
857 ui
->input_handler (gdb::unique_xmalloc_ptr
<char> (result
));
861 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
862 otherwise, return false. */
865 unblock_signal (int sig
)
869 sigemptyset (&sigset
);
870 sigaddset (&sigset
, sig
);
871 gdb_sigmask (SIG_UNBLOCK
, &sigset
, 0);
878 /* Called to handle fatal signals. SIG is the signal number. */
880 static void ATTRIBUTE_NORETURN
881 handle_fatal_signal (int sig
)
883 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
884 const auto sig_write
= [] (const char *msg
) -> void
886 gdb_stderr
->write_async_safe (msg
, strlen (msg
));
889 if (bt_on_fatal_signal
)
892 sig_write (_("Fatal signal: "));
893 sig_write (strsignal (sig
));
896 gdb_internal_backtrace ();
898 sig_write (_("A fatal error internal to GDB has been detected, "
899 "further\ndebugging is not possible. GDB will now "
901 sig_write (_("This is a bug, please report it."));
902 if (REPORT_BUGS_TO
[0] != '\0')
904 sig_write (_(" For instructions, see:\n"));
905 sig_write (REPORT_BUGS_TO
);
910 gdb_stderr
->flush ();
914 /* If possible arrange for SIG to have its default behaviour (which
915 should be to terminate the current process), unblock SIG, and reraise
916 the signal. This ensures GDB terminates with the expected signal. */
917 if (signal (sig
, SIG_DFL
) != SIG_ERR
918 && unblock_signal (sig
))
921 /* The above failed, so try to use SIGABRT to terminate GDB. */
923 signal (SIGABRT
, SIG_DFL
);
925 abort (); /* ARI: abort */
928 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
929 always installs a global SIGSEGV handler, and then lets threads
930 indicate their interest in handling the signal by setting this
931 thread-local variable.
933 This is a static variable instead of extern because on various platforms
934 (notably Cygwin) extern thread_local variables cause link errors. So
935 instead, we have scoped_segv_handler_restore, which also makes it impossible
936 to accidentally forget to restore it to the original value. */
938 static thread_local
void (*thread_local_segv_handler
) (int);
940 static void handle_sigsegv (int sig
);
942 /* Install the SIGSEGV handler. */
944 install_handle_sigsegv ()
946 #if defined (HAVE_SIGACTION)
948 sa
.sa_handler
= handle_sigsegv
;
949 sigemptyset (&sa
.sa_mask
);
950 #ifdef HAVE_SIGALTSTACK
951 sa
.sa_flags
= SA_ONSTACK
;
955 sigaction (SIGSEGV
, &sa
, nullptr);
957 signal (SIGSEGV
, handle_sigsegv
);
961 /* Handler for SIGSEGV. */
964 handle_sigsegv (int sig
)
966 install_handle_sigsegv ();
968 if (thread_local_segv_handler
== nullptr)
969 handle_fatal_signal (sig
);
970 thread_local_segv_handler (sig
);
975 /* The serial event associated with the QUIT flag. set_quit_flag sets
976 this, and check_quit_flag clears it. Used by interruptible_select
977 to be able to do interruptible I/O with no race with the SIGINT
979 static struct serial_event
*quit_serial_event
;
981 /* Initialization of signal handlers and tokens. There are a number of
982 different strategies for handling different signals here.
984 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
985 handle_sig* for each of these signals. These functions are the actual
986 signal handlers associated to the signals via calls to signal(). The
987 only job for these functions is to enqueue the appropriate
988 event/procedure with the event loop. The event loop will take care of
989 invoking the queued procedures to perform the usual tasks associated
990 with the reception of the signal.
992 For SIGSEGV the handle_sig* function does all the work for handling this
995 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
996 terminate immediately. */
998 gdb_init_signals (void)
1000 initialize_async_signal_handlers ();
1002 quit_serial_event
= make_serial_event ();
1005 create_async_signal_handler (async_request_quit
, NULL
, "sigint");
1006 signal (SIGINT
, handle_sigint
);
1009 = create_async_signal_handler (async_sigterm_handler
, NULL
, "sigterm");
1010 signal (SIGTERM
, handle_sigterm
);
1014 create_async_signal_handler (async_do_nothing
, NULL
, "sigquit");
1015 signal (SIGQUIT
, handle_sigquit
);
1019 if (signal (SIGHUP
, handle_sighup
) != SIG_IGN
)
1021 create_async_signal_handler (async_disconnect
, NULL
, "sighup");
1024 create_async_signal_handler (async_do_nothing
, NULL
, "sighup");
1029 create_async_signal_handler (async_sigtstp_handler
, NULL
, "sigtstp");
1033 signal (SIGFPE
, handle_fatal_signal
);
1037 signal (SIGBUS
, handle_fatal_signal
);
1041 signal (SIGABRT
, handle_fatal_signal
);
1044 install_handle_sigsegv ();
1050 quit_serial_event_set (void)
1052 serial_event_set (quit_serial_event
);
1058 quit_serial_event_clear (void)
1060 serial_event_clear (quit_serial_event
);
1063 /* Return the selectable file descriptor of the serial event
1064 associated with the quit flag. */
1067 quit_serial_event_fd (void)
1069 return serial_event_fd (quit_serial_event
);
1075 default_quit_handler (void)
1077 if (check_quit_flag ())
1079 if (target_terminal::is_ours ())
1082 target_pass_ctrlc ();
1087 quit_handler_ftype
*quit_handler
= default_quit_handler
;
1089 /* Handle a SIGINT. */
1092 handle_sigint (int sig
)
1094 signal (sig
, handle_sigint
);
1096 /* We could be running in a loop reading in symfiles or something so
1097 it may be quite a while before we get back to the event loop. So
1098 set quit_flag to 1 here. Then if QUIT is called before we get to
1099 the event loop, we will unwind as expected. */
1102 /* In case nothing calls QUIT before the event loop is reached, the
1103 event loop handles it. */
1104 mark_async_signal_handler (sigint_token
);
1107 /* See gdb_select.h. */
1110 interruptible_select (int n
,
1111 fd_set
*readfds
, fd_set
*writefds
, fd_set
*exceptfds
,
1112 struct timeval
*timeout
)
1118 if (readfds
== NULL
)
1120 readfds
= &my_readfds
;
1121 FD_ZERO (&my_readfds
);
1124 fd
= quit_serial_event_fd ();
1125 FD_SET (fd
, readfds
);
1131 res
= gdb_select (n
, readfds
, writefds
, exceptfds
, timeout
);
1133 while (res
== -1 && errno
== EINTR
);
1135 if (res
== 1 && FD_ISSET (fd
, readfds
))
1143 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1146 async_sigterm_handler (gdb_client_data arg
)
1148 quit_force (NULL
, 0);
1152 volatile int sync_quit_force_run
;
1154 /* Quit GDB if SIGTERM is received.
1155 GDB would quit anyway, but this way it will clean up properly. */
1157 handle_sigterm (int sig
)
1159 signal (sig
, handle_sigterm
);
1161 sync_quit_force_run
= 1;
1164 mark_async_signal_handler (async_sigterm_token
);
1167 /* Do the quit. All the checks have been done by the caller. */
1169 async_request_quit (gdb_client_data arg
)
1171 /* If the quit_flag has gotten reset back to 0 by the time we get
1172 back here, that means that an exception was thrown to unwind the
1173 current command before we got back to the event loop. So there
1174 is no reason to call quit again here. */
1179 /* Tell the event loop what to do if SIGQUIT is received.
1180 See event-signal.c. */
1182 handle_sigquit (int sig
)
1184 mark_async_signal_handler (sigquit_token
);
1185 signal (sig
, handle_sigquit
);
1189 #if defined (SIGQUIT) || defined (SIGHUP)
1190 /* Called by the event loop in response to a SIGQUIT or an
1193 async_do_nothing (gdb_client_data arg
)
1195 /* Empty function body. */
1200 /* Tell the event loop what to do if SIGHUP is received.
1201 See event-signal.c. */
1203 handle_sighup (int sig
)
1205 mark_async_signal_handler (sighup_token
);
1206 signal (sig
, handle_sighup
);
1209 /* Called by the event loop to process a SIGHUP. */
1211 async_disconnect (gdb_client_data arg
)
1219 catch (const gdb_exception
&exception
)
1221 fputs_filtered ("Could not kill the program being debugged",
1223 exception_print (gdb_stderr
, exception
);
1226 for (inferior
*inf
: all_inferiors ())
1228 switch_to_inferior_no_thread (inf
);
1233 catch (const gdb_exception
&exception
)
1238 signal (SIGHUP
, SIG_DFL
); /*FIXME: ??????????? */
1245 handle_sigtstp (int sig
)
1247 mark_async_signal_handler (sigtstp_token
);
1248 signal (sig
, handle_sigtstp
);
1252 async_sigtstp_handler (gdb_client_data arg
)
1254 const std::string
&prompt
= get_prompt ();
1256 signal (SIGTSTP
, SIG_DFL
);
1257 unblock_signal (SIGTSTP
);
1259 signal (SIGTSTP
, handle_sigtstp
);
1260 printf_unfiltered ("%s", prompt
.c_str ());
1261 gdb_flush (gdb_stdout
);
1263 /* Forget about any previous command -- null line now will do
1267 #endif /* SIGTSTP */
1271 /* Set things up for readline to be invoked via the alternate
1272 interface, i.e. via a callback function
1273 (gdb_rl_callback_read_char), and hook up instream to the event
1277 gdb_setup_readline (int editing
)
1279 struct ui
*ui
= current_ui
;
1281 /* This function is a noop for the sync case. The assumption is
1282 that the sync setup is ALL done in gdb_init, and we would only
1283 mess it up here. The sync stuff should really go away over
1286 gdb_stdout
= new stdio_file (ui
->outstream
);
1287 gdb_stderr
= new stderr_file (ui
->errstream
);
1288 gdb_stdlog
= gdb_stderr
; /* for moment */
1289 gdb_stdtarg
= gdb_stderr
; /* for moment */
1290 gdb_stdtargerr
= gdb_stderr
; /* for moment */
1292 /* If the input stream is connected to a terminal, turn on editing.
1293 However, that is only allowed on the main UI, as we can only have
1294 one instance of readline. */
1295 if (ISATTY (ui
->instream
) && editing
&& ui
== main_ui
)
1297 /* Tell gdb that we will be using the readline library. This
1298 could be overwritten by a command in .gdbinit like 'set
1299 editing on' or 'off'. */
1300 ui
->command_editing
= 1;
1302 /* When a character is detected on instream by select or poll,
1303 readline will be invoked via this callback function. */
1304 ui
->call_readline
= gdb_rl_callback_read_char_wrapper
;
1306 /* Tell readline to use the same input stream that gdb uses. */
1307 rl_instream
= ui
->instream
;
1311 ui
->command_editing
= 0;
1312 ui
->call_readline
= gdb_readline_no_editing_callback
;
1315 /* Now create the event source for this UI's input file descriptor.
1316 Another source is going to be the target program (inferior), but
1317 that must be registered only when it actually exists (I.e. after
1318 we say 'run' or after we connect to a remote target. */
1319 ui_register_input_event_handler (ui
);
1322 /* Disable command input through the standard CLI channels. Used in
1323 the suspend proc for interpreters that use the standard gdb readline
1324 interface, like the cli & the mi. */
1327 gdb_disable_readline (void)
1329 struct ui
*ui
= current_ui
;
1331 /* FIXME - It is too heavyweight to delete and remake these every
1332 time you run an interpreter that needs readline. It is probably
1333 better to have the interpreters cache these, which in turn means
1334 that this needs to be moved into interpreter specific code. */
1337 ui_file_delete (gdb_stdout
);
1338 ui_file_delete (gdb_stderr
);
1341 gdb_stdtargerr
= NULL
;
1344 if (ui
->command_editing
)
1345 gdb_rl_callback_handler_remove ();
1346 delete_file_handler (ui
->input_fd
);
1349 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler
)
1351 m_old_handler
= thread_local_segv_handler
;
1352 thread_local_segv_handler
= new_handler
;
1355 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1357 thread_local_segv_handler
= m_old_handler
;
1360 static const char debug_event_loop_off
[] = "off";
1361 static const char debug_event_loop_all_except_ui
[] = "all-except-ui";
1362 static const char debug_event_loop_all
[] = "all";
1364 static const char *debug_event_loop_enum
[] = {
1365 debug_event_loop_off
,
1366 debug_event_loop_all_except_ui
,
1367 debug_event_loop_all
,
1371 static const char *debug_event_loop_value
= debug_event_loop_off
;
1374 set_debug_event_loop_command (const char *args
, int from_tty
,
1375 cmd_list_element
*c
)
1377 if (debug_event_loop_value
== debug_event_loop_off
)
1378 debug_event_loop
= debug_event_loop_kind::OFF
;
1379 else if (debug_event_loop_value
== debug_event_loop_all_except_ui
)
1380 debug_event_loop
= debug_event_loop_kind::ALL_EXCEPT_UI
;
1381 else if (debug_event_loop_value
== debug_event_loop_all
)
1382 debug_event_loop
= debug_event_loop_kind::ALL
;
1384 gdb_assert_not_reached ("Invalid debug event look kind value.");
1388 show_debug_event_loop_command (struct ui_file
*file
, int from_tty
,
1389 struct cmd_list_element
*cmd
, const char *value
)
1391 fprintf_filtered (file
, _("Event loop debugging is %s.\n"), value
);
1394 void _initialize_event_top ();
1396 _initialize_event_top ()
1398 add_setshow_enum_cmd ("event-loop", class_maintenance
,
1399 debug_event_loop_enum
,
1400 &debug_event_loop_value
,
1401 _("Set event-loop debugging."),
1402 _("Show event-loop debugging."),
1404 Control whether to show event loop-related debug messages."),
1405 set_debug_event_loop_command
,
1406 show_debug_event_loop_command
,
1407 &setdebuglist
, &showdebuglist
);
1409 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance
,
1410 &bt_on_fatal_signal
, _("\
1411 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1412 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1413 Use \"on\" to enable, \"off\" to disable.\n\
1414 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1415 signal from within GDB itself. This is a mechanism to help diagnose\n\
1416 crashes within GDB, not a mechanism for debugging inferiors."),
1417 gdb_internal_backtrace_set_cmd
,
1418 show_bt_on_fatal_signal
,
1419 &maintenance_set_cmdlist
,
1420 &maintenance_show_cmdlist
);