1 /* Top level stuff for GDB, the GNU debugger.
3 Copyright (C) 1999-2021 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 fprintf_unfiltered (gdb_stdout
, "%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)
444 /* Give observers a chance of changing the prompt. E.g., the python
445 `gdb.prompt_hook' is installed as an observer. */
446 gdb::observers::before_prompt
.notify (get_prompt ());
448 prompt
= get_prompt ();
450 if (annotation_level
>= 2)
452 /* Prefix needs to have new line at end. */
453 const char prefix
[] = "\n\032\032pre-prompt\n";
455 /* Suffix needs to have a new line at end and \032 \032 at
457 const char suffix
[] = "\n\032\032prompt\n";
459 return std::string (prefix
) + prompt
+ suffix
;
468 struct ui
*current_ui
;
471 /* Get a pointer to the current UI's line buffer. This is used to
472 construct a whole line of input from partial input. */
474 static struct buffer
*
475 get_command_line_buffer (void)
477 return ¤t_ui
->line_buffer
;
480 /* When there is an event ready on the stdin file descriptor, instead
481 of calling readline directly throught the callback function, or
482 instead of calling gdb_readline_no_editing_callback, give gdb a
483 chance to detect errors and do something. */
486 stdin_event_handler (int error
, gdb_client_data client_data
)
488 struct ui
*ui
= (struct ui
*) client_data
;
492 /* Switch to the main UI, so diagnostics always go there. */
493 current_ui
= main_ui
;
495 delete_file_handler (ui
->input_fd
);
498 /* If stdin died, we may as well kill gdb. */
499 printf_unfiltered (_("error detected on stdin\n"));
500 quit_command ((char *) 0, 0);
504 /* Simply delete the UI. */
510 /* Switch to the UI whose input descriptor woke up the event
514 /* This makes sure a ^C immediately followed by further input is
515 always processed in that order. E.g,. with input like
516 "^Cprint 1\n", the SIGINT handler runs, marks the async
517 signal handler, and then select/poll may return with stdin
518 ready, instead of -1/EINTR. The
519 gdb.base/double-prompt-target-event-error.exp test exercises
525 call_stdin_event_handler_again_p
= 0;
526 ui
->call_readline (client_data
);
528 while (call_stdin_event_handler_again_p
!= 0);
535 ui_register_input_event_handler (struct ui
*ui
)
537 add_file_handler (ui
->input_fd
, stdin_event_handler
, ui
,
538 string_printf ("ui-%d", ui
->num
), true);
544 ui_unregister_input_event_handler (struct ui
*ui
)
546 delete_file_handler (ui
->input_fd
);
549 /* Re-enable stdin after the end of an execution command in
550 synchronous mode, or after an error from the target, and we aborted
551 the exec operation. */
554 async_enable_stdin (void)
556 struct ui
*ui
= current_ui
;
558 if (ui
->prompt_state
== PROMPT_BLOCKED
)
560 target_terminal::ours ();
561 ui_register_input_event_handler (ui
);
562 ui
->prompt_state
= PROMPT_NEEDED
;
566 /* Disable reads from stdin (the console) marking the command as
570 async_disable_stdin (void)
572 struct ui
*ui
= current_ui
;
574 ui
->prompt_state
= PROMPT_BLOCKED
;
575 delete_file_handler (ui
->input_fd
);
579 /* Handle a gdb command line. This function is called when
580 handle_line_of_input has concatenated one or more input lines into
584 command_handler (const char *command
)
586 struct ui
*ui
= current_ui
;
589 if (ui
->instream
== ui
->stdin_stream
)
590 reinitialize_more_filter ();
592 scoped_command_stats
stat_reporter (true);
594 /* Do not execute commented lines. */
595 for (c
= command
; *c
== ' ' || *c
== '\t'; c
++)
599 execute_command (command
, ui
->instream
== ui
->stdin_stream
);
601 /* Do any commands attached to breakpoint we stopped at. */
602 bpstat_do_actions ();
606 /* Append RL, an input line returned by readline or one of its
607 emulations, to CMD_LINE_BUFFER. Returns the command line if we
608 have a whole command line ready to be processed by the command
609 interpreter or NULL if the command line isn't complete yet (input
610 line ends in a backslash). */
613 command_line_append_input_line (struct buffer
*cmd_line_buffer
, const char *rl
)
620 if (len
> 0 && rl
[len
- 1] == '\\')
622 /* Don't copy the backslash and wait for more. */
623 buffer_grow (cmd_line_buffer
, rl
, len
- 1);
628 /* Copy whole line including terminating null, and we're
630 buffer_grow (cmd_line_buffer
, rl
, len
+ 1);
631 cmd
= cmd_line_buffer
->buffer
;
637 /* Handle a line of input coming from readline.
639 If the read line ends with a continuation character (backslash),
640 save the partial input in CMD_LINE_BUFFER (except the backslash),
641 and return NULL. Otherwise, save the partial input and return a
642 pointer to CMD_LINE_BUFFER's buffer (null terminated), indicating a
643 whole command line is ready to be executed.
645 Returns EOF on end of file.
647 If REPEAT, handle command repetitions:
649 - If the input command line is NOT empty, the command returned is
650 saved using save_command_line () so that it can be repeated later.
652 - OTOH, if the input command line IS empty, return the saved
653 command instead of the empty input line.
657 handle_line_of_input (struct buffer
*cmd_line_buffer
,
658 const char *rl
, int repeat
,
659 const char *annotation_suffix
)
661 struct ui
*ui
= current_ui
;
662 int from_tty
= ui
->instream
== ui
->stdin_stream
;
669 cmd
= command_line_append_input_line (cmd_line_buffer
, rl
);
673 /* We have a complete command line now. Prepare for the next
674 command, but leave ownership of memory to the buffer . */
675 cmd_line_buffer
->used_size
= 0;
677 if (from_tty
&& annotation_level
> 1)
679 printf_unfiltered (("\n\032\032post-"));
680 puts_unfiltered (annotation_suffix
);
681 printf_unfiltered (("\n"));
684 #define SERVER_COMMAND_PREFIX "server "
685 server_command
= startswith (cmd
, SERVER_COMMAND_PREFIX
);
688 /* Note that we don't call `save_command_line'. Between this
689 and the check in dont_repeat, this insures that repeating
690 will still do the right thing. */
691 return cmd
+ strlen (SERVER_COMMAND_PREFIX
);
694 /* Do history expansion if that is wished. */
695 if (history_expansion_p
&& from_tty
&& input_interactive_p (current_ui
))
700 expanded
= history_expand (cmd
, &cmd_expansion
);
701 gdb::unique_xmalloc_ptr
<char> history_value (cmd_expansion
);
706 /* Print the changes. */
707 printf_unfiltered ("%s\n", history_value
.get ());
709 /* If there was an error, call this function again. */
713 /* history_expand returns an allocated string. Just replace
714 our buffer with it. */
715 len
= strlen (history_value
.get ());
716 xfree (buffer_finish (cmd_line_buffer
));
717 cmd_line_buffer
->buffer
= history_value
.get ();
718 cmd_line_buffer
->buffer_size
= len
+ 1;
719 cmd
= history_value
.release ();
723 /* If we just got an empty line, and that is supposed to repeat the
724 previous command, return the previously saved command. */
725 for (p1
= cmd
; *p1
== ' ' || *p1
== '\t'; p1
++)
727 if (repeat
&& *p1
== '\0')
728 return get_saved_command_line ();
730 /* Add command to history if appropriate. Note: lines consisting
731 solely of comments are also added to the command history. This
732 is useful when you type a command, and then realize you don't
733 want to execute it quite yet. You can comment out the command
734 and then later fetch it from the value history and remove the
735 '#'. The kill ring is probably better, but some people are in
736 the habit of commenting things out. */
737 if (*cmd
!= '\0' && from_tty
&& input_interactive_p (current_ui
))
738 gdb_add_history (cmd
);
740 /* Save into global buffer if appropriate. */
743 save_command_line (cmd
);
744 return get_saved_command_line ();
750 /* Handle a complete line of input. This is called by the callback
751 mechanism within the readline library. Deal with incomplete
752 commands as well, by saving the partial input in a global
755 NOTE: This is the asynchronous version of the command_line_input
759 command_line_handler (gdb::unique_xmalloc_ptr
<char> &&rl
)
761 struct buffer
*line_buffer
= get_command_line_buffer ();
762 struct ui
*ui
= current_ui
;
765 cmd
= handle_line_of_input (line_buffer
, rl
.get (), 1, "prompt");
766 if (cmd
== (char *) EOF
)
768 /* stdin closed. The connection with the terminal is gone.
769 This happens at the end of a testsuite run, after Expect has
770 hung up but GDB is still alive. In such a case, we just quit
771 gdb killing the inferior program too. */
772 printf_unfiltered ("quit\n");
773 execute_command ("quit", 1);
775 else if (cmd
== NULL
)
777 /* We don't have a full line yet. Print an empty prompt. */
778 display_gdb_prompt ("");
782 ui
->prompt_state
= PROMPT_NEEDED
;
784 command_handler (cmd
);
786 if (ui
->prompt_state
!= PROMPTED
)
787 display_gdb_prompt (0);
791 /* Does reading of input from terminal w/o the editing features
792 provided by the readline library. Calls the line input handler
793 once we have a whole input line. */
796 gdb_readline_no_editing_callback (gdb_client_data client_data
)
800 struct buffer line_buffer
;
801 static int done_once
= 0;
802 struct ui
*ui
= current_ui
;
804 buffer_init (&line_buffer
);
806 /* Unbuffer the input stream, so that, later on, the calls to fgetc
807 fetch only one char at the time from the stream. The fgetc's will
808 get up to the first newline, but there may be more chars in the
809 stream after '\n'. If we buffer the input and fgetc drains the
810 stream, getting stuff beyond the newline as well, a select, done
811 afterwards will not trigger. */
812 if (!done_once
&& !ISATTY (ui
->instream
))
814 setbuf (ui
->instream
, NULL
);
818 /* We still need the while loop here, even though it would seem
819 obvious to invoke gdb_readline_no_editing_callback at every
820 character entered. If not using the readline library, the
821 terminal is in cooked mode, which sends the characters all at
822 once. Poll will notice that the input fd has changed state only
823 after enter is pressed. At this point we still need to fetch all
824 the chars entered. */
828 /* Read from stdin if we are executing a user defined command.
829 This is the right thing for prompt_for_continue, at least. */
830 c
= fgetc (ui
->instream
!= NULL
? ui
->instream
: ui
->stdin_stream
);
834 if (line_buffer
.used_size
> 0)
836 /* The last line does not end with a newline. Return it, and
837 if we are called again fgetc will still return EOF and
838 we'll return NULL then. */
841 xfree (buffer_finish (&line_buffer
));
842 ui
->input_handler (NULL
);
848 if (line_buffer
.used_size
> 0
849 && line_buffer
.buffer
[line_buffer
.used_size
- 1] == '\r')
850 line_buffer
.used_size
--;
854 buffer_grow_char (&line_buffer
, c
);
857 buffer_grow_char (&line_buffer
, '\0');
858 result
= buffer_finish (&line_buffer
);
859 ui
->input_handler (gdb::unique_xmalloc_ptr
<char> (result
));
863 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
864 otherwise, return false. */
867 unblock_signal (int sig
)
871 sigemptyset (&sigset
);
872 sigaddset (&sigset
, sig
);
873 gdb_sigmask (SIG_UNBLOCK
, &sigset
, 0);
880 /* Called to handle fatal signals. SIG is the signal number. */
882 static void ATTRIBUTE_NORETURN
883 handle_fatal_signal (int sig
)
885 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
886 const auto sig_write
= [] (const char *msg
) -> void
888 gdb_stderr
->write_async_safe (msg
, strlen (msg
));
891 if (bt_on_fatal_signal
)
894 sig_write (_("Fatal signal: "));
895 sig_write (strsignal (sig
));
898 gdb_internal_backtrace ();
900 sig_write (_("A fatal error internal to GDB has been detected, "
901 "further\ndebugging is not possible. GDB will now "
903 sig_write (_("This is a bug, please report it."));
904 if (REPORT_BUGS_TO
[0] != '\0')
906 sig_write (_(" For instructions, see:\n"));
907 sig_write (REPORT_BUGS_TO
);
912 gdb_stderr
->flush ();
916 /* If possible arrange for SIG to have its default behaviour (which
917 should be to terminate the current process), unblock SIG, and reraise
918 the signal. This ensures GDB terminates with the expected signal. */
919 if (signal (sig
, SIG_DFL
) != SIG_ERR
920 && unblock_signal (sig
))
923 /* The above failed, so try to use SIGABRT to terminate GDB. */
925 signal (SIGABRT
, SIG_DFL
);
927 abort (); /* ARI: abort */
930 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
931 always installs a global SIGSEGV handler, and then lets threads
932 indicate their interest in handling the signal by setting this
933 thread-local variable.
935 This is a static variable instead of extern because on various platforms
936 (notably Cygwin) extern thread_local variables cause link errors. So
937 instead, we have scoped_segv_handler_restore, which also makes it impossible
938 to accidentally forget to restore it to the original value. */
940 static thread_local
void (*thread_local_segv_handler
) (int);
942 static void handle_sigsegv (int sig
);
944 /* Install the SIGSEGV handler. */
946 install_handle_sigsegv ()
948 #if defined (HAVE_SIGACTION)
950 sa
.sa_handler
= handle_sigsegv
;
951 sigemptyset (&sa
.sa_mask
);
952 #ifdef HAVE_SIGALTSTACK
953 sa
.sa_flags
= SA_ONSTACK
;
957 sigaction (SIGSEGV
, &sa
, nullptr);
959 signal (SIGSEGV
, handle_sigsegv
);
963 /* Handler for SIGSEGV. */
966 handle_sigsegv (int sig
)
968 install_handle_sigsegv ();
970 if (thread_local_segv_handler
== nullptr)
971 handle_fatal_signal (sig
);
972 thread_local_segv_handler (sig
);
977 /* The serial event associated with the QUIT flag. set_quit_flag sets
978 this, and check_quit_flag clears it. Used by interruptible_select
979 to be able to do interruptible I/O with no race with the SIGINT
981 static struct serial_event
*quit_serial_event
;
983 /* Initialization of signal handlers and tokens. There are a number of
984 different strategies for handling different signals here.
986 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
987 handle_sig* for each of these signals. These functions are the actual
988 signal handlers associated to the signals via calls to signal(). The
989 only job for these functions is to enqueue the appropriate
990 event/procedure with the event loop. The event loop will take care of
991 invoking the queued procedures to perform the usual tasks associated
992 with the reception of the signal.
994 For SIGSEGV the handle_sig* function does all the work for handling this
997 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
998 terminate immediately. */
1000 gdb_init_signals (void)
1002 initialize_async_signal_handlers ();
1004 quit_serial_event
= make_serial_event ();
1007 create_async_signal_handler (async_request_quit
, NULL
, "sigint");
1008 signal (SIGINT
, handle_sigint
);
1011 = create_async_signal_handler (async_sigterm_handler
, NULL
, "sigterm");
1012 signal (SIGTERM
, handle_sigterm
);
1016 create_async_signal_handler (async_do_nothing
, NULL
, "sigquit");
1017 signal (SIGQUIT
, handle_sigquit
);
1021 if (signal (SIGHUP
, handle_sighup
) != SIG_IGN
)
1023 create_async_signal_handler (async_disconnect
, NULL
, "sighup");
1026 create_async_signal_handler (async_do_nothing
, NULL
, "sighup");
1031 create_async_signal_handler (async_sigtstp_handler
, NULL
, "sigtstp");
1035 signal (SIGFPE
, handle_fatal_signal
);
1039 signal (SIGBUS
, handle_fatal_signal
);
1043 signal (SIGABRT
, handle_fatal_signal
);
1046 install_handle_sigsegv ();
1052 quit_serial_event_set (void)
1054 serial_event_set (quit_serial_event
);
1060 quit_serial_event_clear (void)
1062 serial_event_clear (quit_serial_event
);
1065 /* Return the selectable file descriptor of the serial event
1066 associated with the quit flag. */
1069 quit_serial_event_fd (void)
1071 return serial_event_fd (quit_serial_event
);
1077 default_quit_handler (void)
1079 if (check_quit_flag ())
1081 if (target_terminal::is_ours ())
1084 target_pass_ctrlc ();
1089 quit_handler_ftype
*quit_handler
= default_quit_handler
;
1091 /* Handle a SIGINT. */
1094 handle_sigint (int sig
)
1096 signal (sig
, handle_sigint
);
1098 /* We could be running in a loop reading in symfiles or something so
1099 it may be quite a while before we get back to the event loop. So
1100 set quit_flag to 1 here. Then if QUIT is called before we get to
1101 the event loop, we will unwind as expected. */
1104 /* In case nothing calls QUIT before the event loop is reached, the
1105 event loop handles it. */
1106 mark_async_signal_handler (sigint_token
);
1109 /* See gdb_select.h. */
1112 interruptible_select (int n
,
1113 fd_set
*readfds
, fd_set
*writefds
, fd_set
*exceptfds
,
1114 struct timeval
*timeout
)
1120 if (readfds
== NULL
)
1122 readfds
= &my_readfds
;
1123 FD_ZERO (&my_readfds
);
1126 fd
= quit_serial_event_fd ();
1127 FD_SET (fd
, readfds
);
1133 res
= gdb_select (n
, readfds
, writefds
, exceptfds
, timeout
);
1135 while (res
== -1 && errno
== EINTR
);
1137 if (res
== 1 && FD_ISSET (fd
, readfds
))
1145 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1148 async_sigterm_handler (gdb_client_data arg
)
1150 quit_force (NULL
, 0);
1154 volatile int sync_quit_force_run
;
1156 /* Quit GDB if SIGTERM is received.
1157 GDB would quit anyway, but this way it will clean up properly. */
1159 handle_sigterm (int sig
)
1161 signal (sig
, handle_sigterm
);
1163 sync_quit_force_run
= 1;
1166 mark_async_signal_handler (async_sigterm_token
);
1169 /* Do the quit. All the checks have been done by the caller. */
1171 async_request_quit (gdb_client_data arg
)
1173 /* If the quit_flag has gotten reset back to 0 by the time we get
1174 back here, that means that an exception was thrown to unwind the
1175 current command before we got back to the event loop. So there
1176 is no reason to call quit again here. */
1181 /* Tell the event loop what to do if SIGQUIT is received.
1182 See event-signal.c. */
1184 handle_sigquit (int sig
)
1186 mark_async_signal_handler (sigquit_token
);
1187 signal (sig
, handle_sigquit
);
1191 #if defined (SIGQUIT) || defined (SIGHUP)
1192 /* Called by the event loop in response to a SIGQUIT or an
1195 async_do_nothing (gdb_client_data arg
)
1197 /* Empty function body. */
1202 /* Tell the event loop what to do if SIGHUP is received.
1203 See event-signal.c. */
1205 handle_sighup (int sig
)
1207 mark_async_signal_handler (sighup_token
);
1208 signal (sig
, handle_sighup
);
1211 /* Called by the event loop to process a SIGHUP. */
1213 async_disconnect (gdb_client_data arg
)
1221 catch (const gdb_exception
&exception
)
1223 fputs_filtered ("Could not kill the program being debugged",
1225 exception_print (gdb_stderr
, exception
);
1228 for (inferior
*inf
: all_inferiors ())
1230 switch_to_inferior_no_thread (inf
);
1235 catch (const gdb_exception
&exception
)
1240 signal (SIGHUP
, SIG_DFL
); /*FIXME: ??????????? */
1247 handle_sigtstp (int sig
)
1249 mark_async_signal_handler (sigtstp_token
);
1250 signal (sig
, handle_sigtstp
);
1254 async_sigtstp_handler (gdb_client_data arg
)
1256 char *prompt
= get_prompt ();
1258 signal (SIGTSTP
, SIG_DFL
);
1259 unblock_signal (SIGTSTP
);
1261 signal (SIGTSTP
, handle_sigtstp
);
1262 printf_unfiltered ("%s", prompt
);
1263 gdb_flush (gdb_stdout
);
1265 /* Forget about any previous command -- null line now will do
1269 #endif /* SIGTSTP */
1273 /* Set things up for readline to be invoked via the alternate
1274 interface, i.e. via a callback function
1275 (gdb_rl_callback_read_char), and hook up instream to the event
1279 gdb_setup_readline (int editing
)
1281 struct ui
*ui
= current_ui
;
1283 /* This function is a noop for the sync case. The assumption is
1284 that the sync setup is ALL done in gdb_init, and we would only
1285 mess it up here. The sync stuff should really go away over
1288 gdb_stdout
= new stdio_file (ui
->outstream
);
1289 gdb_stderr
= new stderr_file (ui
->errstream
);
1290 gdb_stdlog
= gdb_stderr
; /* for moment */
1291 gdb_stdtarg
= gdb_stderr
; /* for moment */
1292 gdb_stdtargerr
= gdb_stderr
; /* for moment */
1294 /* If the input stream is connected to a terminal, turn on editing.
1295 However, that is only allowed on the main UI, as we can only have
1296 one instance of readline. */
1297 if (ISATTY (ui
->instream
) && editing
&& ui
== main_ui
)
1299 /* Tell gdb that we will be using the readline library. This
1300 could be overwritten by a command in .gdbinit like 'set
1301 editing on' or 'off'. */
1302 ui
->command_editing
= 1;
1304 /* When a character is detected on instream by select or poll,
1305 readline will be invoked via this callback function. */
1306 ui
->call_readline
= gdb_rl_callback_read_char_wrapper
;
1308 /* Tell readline to use the same input stream that gdb uses. */
1309 rl_instream
= ui
->instream
;
1313 ui
->command_editing
= 0;
1314 ui
->call_readline
= gdb_readline_no_editing_callback
;
1317 /* Now create the event source for this UI's input file descriptor.
1318 Another source is going to be the target program (inferior), but
1319 that must be registered only when it actually exists (I.e. after
1320 we say 'run' or after we connect to a remote target. */
1321 ui_register_input_event_handler (ui
);
1324 /* Disable command input through the standard CLI channels. Used in
1325 the suspend proc for interpreters that use the standard gdb readline
1326 interface, like the cli & the mi. */
1329 gdb_disable_readline (void)
1331 struct ui
*ui
= current_ui
;
1333 /* FIXME - It is too heavyweight to delete and remake these every
1334 time you run an interpreter that needs readline. It is probably
1335 better to have the interpreters cache these, which in turn means
1336 that this needs to be moved into interpreter specific code. */
1339 ui_file_delete (gdb_stdout
);
1340 ui_file_delete (gdb_stderr
);
1343 gdb_stdtargerr
= NULL
;
1346 if (ui
->command_editing
)
1347 gdb_rl_callback_handler_remove ();
1348 delete_file_handler (ui
->input_fd
);
1351 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler
)
1353 m_old_handler
= thread_local_segv_handler
;
1354 thread_local_segv_handler
= new_handler
;
1357 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1359 thread_local_segv_handler
= m_old_handler
;
1362 static const char debug_event_loop_off
[] = "off";
1363 static const char debug_event_loop_all_except_ui
[] = "all-except-ui";
1364 static const char debug_event_loop_all
[] = "all";
1366 static const char *debug_event_loop_enum
[] = {
1367 debug_event_loop_off
,
1368 debug_event_loop_all_except_ui
,
1369 debug_event_loop_all
,
1373 static const char *debug_event_loop_value
= debug_event_loop_off
;
1376 set_debug_event_loop_command (const char *args
, int from_tty
,
1377 cmd_list_element
*c
)
1379 if (debug_event_loop_value
== debug_event_loop_off
)
1380 debug_event_loop
= debug_event_loop_kind::OFF
;
1381 else if (debug_event_loop_value
== debug_event_loop_all_except_ui
)
1382 debug_event_loop
= debug_event_loop_kind::ALL_EXCEPT_UI
;
1383 else if (debug_event_loop_value
== debug_event_loop_all
)
1384 debug_event_loop
= debug_event_loop_kind::ALL
;
1386 gdb_assert_not_reached ("Invalid debug event look kind value.");
1390 show_debug_event_loop_command (struct ui_file
*file
, int from_tty
,
1391 struct cmd_list_element
*cmd
, const char *value
)
1393 fprintf_filtered (file
, _("Event loop debugging is %s.\n"), value
);
1396 void _initialize_event_top ();
1398 _initialize_event_top ()
1400 add_setshow_enum_cmd ("event-loop", class_maintenance
,
1401 debug_event_loop_enum
,
1402 &debug_event_loop_value
,
1403 _("Set event-loop debugging."),
1404 _("Show event-loop debugging."),
1406 Control whether to show event loop-related debug messages."),
1407 set_debug_event_loop_command
,
1408 show_debug_event_loop_command
,
1409 &setdebuglist
, &showdebuglist
);
1411 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance
,
1412 &bt_on_fatal_signal
, _("\
1413 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1414 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1415 Use \"on\" to enable, \"off\" to disable.\n\
1416 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1417 signal from within GDB itself. This is a mechanism to help diagnose\n\
1418 crashes within GDB, not a mechanism for debugging inferiors."),
1419 gdb_internal_backtrace_set_cmd
,
1420 show_bt_on_fatal_signal
,
1421 &maintenance_set_cmdlist
,
1422 &maintenance_show_cmdlist
);