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 bool 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
= false;
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
= true;
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 struct ui
*ui
= current_ui
;
801 buffer_init (&line_buffer
);
803 FILE *stream
= ui
->instream
!= nullptr ? ui
->instream
: ui
->stdin_stream
;
804 gdb_assert (stream
!= nullptr);
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.
813 This unbuffering was, at one point, not applied if the input stream
814 was a tty, however, the buffering can cause problems, even for a tty,
815 in some cases. Please ensure that any changes in this area run the MI
816 tests with the FORCE_SEPARATE_MI_TTY=1 flag being passed. */
817 setbuf (stream
, NULL
);
819 /* We still need the while loop here, even though it would seem
820 obvious to invoke gdb_readline_no_editing_callback at every
821 character entered. If not using the readline library, the
822 terminal is in cooked mode, which sends the characters all at
823 once. Poll will notice that the input fd has changed state only
824 after enter is pressed. At this point we still need to fetch all
825 the chars entered. */
829 /* Read from stdin if we are executing a user defined command.
830 This is the right thing for prompt_for_continue, at least. */
835 if (line_buffer
.used_size
> 0)
837 /* The last line does not end with a newline. Return it, and
838 if we are called again fgetc will still return EOF and
839 we'll return NULL then. */
842 xfree (buffer_finish (&line_buffer
));
843 ui
->input_handler (NULL
);
849 if (line_buffer
.used_size
> 0
850 && line_buffer
.buffer
[line_buffer
.used_size
- 1] == '\r')
851 line_buffer
.used_size
--;
855 buffer_grow_char (&line_buffer
, c
);
858 buffer_grow_char (&line_buffer
, '\0');
859 result
= buffer_finish (&line_buffer
);
860 ui
->input_handler (gdb::unique_xmalloc_ptr
<char> (result
));
864 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
865 otherwise, return false. */
868 unblock_signal (int sig
)
872 sigemptyset (&sigset
);
873 sigaddset (&sigset
, sig
);
874 gdb_sigmask (SIG_UNBLOCK
, &sigset
, 0);
881 /* Called to handle fatal signals. SIG is the signal number. */
883 static void ATTRIBUTE_NORETURN
884 handle_fatal_signal (int sig
)
886 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
887 const auto sig_write
= [] (const char *msg
) -> void
889 gdb_stderr
->write_async_safe (msg
, strlen (msg
));
892 if (bt_on_fatal_signal
)
895 sig_write (_("Fatal signal: "));
896 sig_write (strsignal (sig
));
899 gdb_internal_backtrace ();
901 sig_write (_("A fatal error internal to GDB has been detected, "
902 "further\ndebugging is not possible. GDB will now "
904 sig_write (_("This is a bug, please report it."));
905 if (REPORT_BUGS_TO
[0] != '\0')
907 sig_write (_(" For instructions, see:\n"));
908 sig_write (REPORT_BUGS_TO
);
913 gdb_stderr
->flush ();
917 /* If possible arrange for SIG to have its default behaviour (which
918 should be to terminate the current process), unblock SIG, and reraise
919 the signal. This ensures GDB terminates with the expected signal. */
920 if (signal (sig
, SIG_DFL
) != SIG_ERR
921 && unblock_signal (sig
))
924 /* The above failed, so try to use SIGABRT to terminate GDB. */
926 signal (SIGABRT
, SIG_DFL
);
928 abort (); /* ARI: abort */
931 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
932 always installs a global SIGSEGV handler, and then lets threads
933 indicate their interest in handling the signal by setting this
934 thread-local variable.
936 This is a static variable instead of extern because on various platforms
937 (notably Cygwin) extern thread_local variables cause link errors. So
938 instead, we have scoped_segv_handler_restore, which also makes it impossible
939 to accidentally forget to restore it to the original value. */
941 static thread_local
void (*thread_local_segv_handler
) (int);
943 static void handle_sigsegv (int sig
);
945 /* Install the SIGSEGV handler. */
947 install_handle_sigsegv ()
949 #if defined (HAVE_SIGACTION)
951 sa
.sa_handler
= handle_sigsegv
;
952 sigemptyset (&sa
.sa_mask
);
953 #ifdef HAVE_SIGALTSTACK
954 sa
.sa_flags
= SA_ONSTACK
;
958 sigaction (SIGSEGV
, &sa
, nullptr);
960 signal (SIGSEGV
, handle_sigsegv
);
964 /* Handler for SIGSEGV. */
967 handle_sigsegv (int sig
)
969 install_handle_sigsegv ();
971 if (thread_local_segv_handler
== nullptr)
972 handle_fatal_signal (sig
);
973 thread_local_segv_handler (sig
);
978 /* The serial event associated with the QUIT flag. set_quit_flag sets
979 this, and check_quit_flag clears it. Used by interruptible_select
980 to be able to do interruptible I/O with no race with the SIGINT
982 static struct serial_event
*quit_serial_event
;
984 /* Initialization of signal handlers and tokens. There are a number of
985 different strategies for handling different signals here.
987 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
988 handle_sig* for each of these signals. These functions are the actual
989 signal handlers associated to the signals via calls to signal(). The
990 only job for these functions is to enqueue the appropriate
991 event/procedure with the event loop. The event loop will take care of
992 invoking the queued procedures to perform the usual tasks associated
993 with the reception of the signal.
995 For SIGSEGV the handle_sig* function does all the work for handling this
998 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
999 terminate immediately. */
1001 gdb_init_signals (void)
1003 initialize_async_signal_handlers ();
1005 quit_serial_event
= make_serial_event ();
1008 create_async_signal_handler (async_request_quit
, NULL
, "sigint");
1009 signal (SIGINT
, handle_sigint
);
1012 = create_async_signal_handler (async_sigterm_handler
, NULL
, "sigterm");
1013 signal (SIGTERM
, handle_sigterm
);
1017 create_async_signal_handler (async_do_nothing
, NULL
, "sigquit");
1018 signal (SIGQUIT
, handle_sigquit
);
1022 if (signal (SIGHUP
, handle_sighup
) != SIG_IGN
)
1024 create_async_signal_handler (async_disconnect
, NULL
, "sighup");
1027 create_async_signal_handler (async_do_nothing
, NULL
, "sighup");
1032 create_async_signal_handler (async_sigtstp_handler
, NULL
, "sigtstp");
1036 signal (SIGFPE
, handle_fatal_signal
);
1040 signal (SIGBUS
, handle_fatal_signal
);
1044 signal (SIGABRT
, handle_fatal_signal
);
1047 install_handle_sigsegv ();
1053 quit_serial_event_set (void)
1055 serial_event_set (quit_serial_event
);
1061 quit_serial_event_clear (void)
1063 serial_event_clear (quit_serial_event
);
1066 /* Return the selectable file descriptor of the serial event
1067 associated with the quit flag. */
1070 quit_serial_event_fd (void)
1072 return serial_event_fd (quit_serial_event
);
1078 default_quit_handler (void)
1080 if (check_quit_flag ())
1082 if (target_terminal::is_ours ())
1085 target_pass_ctrlc ();
1090 quit_handler_ftype
*quit_handler
= default_quit_handler
;
1092 /* Handle a SIGINT. */
1095 handle_sigint (int sig
)
1097 signal (sig
, handle_sigint
);
1099 /* We could be running in a loop reading in symfiles or something so
1100 it may be quite a while before we get back to the event loop. So
1101 set quit_flag to 1 here. Then if QUIT is called before we get to
1102 the event loop, we will unwind as expected. */
1105 /* In case nothing calls QUIT before the event loop is reached, the
1106 event loop handles it. */
1107 mark_async_signal_handler (sigint_token
);
1110 /* See gdb_select.h. */
1113 interruptible_select (int n
,
1114 fd_set
*readfds
, fd_set
*writefds
, fd_set
*exceptfds
,
1115 struct timeval
*timeout
)
1121 if (readfds
== NULL
)
1123 readfds
= &my_readfds
;
1124 FD_ZERO (&my_readfds
);
1127 fd
= quit_serial_event_fd ();
1128 FD_SET (fd
, readfds
);
1134 res
= gdb_select (n
, readfds
, writefds
, exceptfds
, timeout
);
1136 while (res
== -1 && errno
== EINTR
);
1138 if (res
== 1 && FD_ISSET (fd
, readfds
))
1146 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1149 async_sigterm_handler (gdb_client_data arg
)
1151 quit_force (NULL
, 0);
1155 volatile int sync_quit_force_run
;
1157 /* Quit GDB if SIGTERM is received.
1158 GDB would quit anyway, but this way it will clean up properly. */
1160 handle_sigterm (int sig
)
1162 signal (sig
, handle_sigterm
);
1164 sync_quit_force_run
= 1;
1167 mark_async_signal_handler (async_sigterm_token
);
1170 /* Do the quit. All the checks have been done by the caller. */
1172 async_request_quit (gdb_client_data arg
)
1174 /* If the quit_flag has gotten reset back to 0 by the time we get
1175 back here, that means that an exception was thrown to unwind the
1176 current command before we got back to the event loop. So there
1177 is no reason to call quit again here. */
1182 /* Tell the event loop what to do if SIGQUIT is received.
1183 See event-signal.c. */
1185 handle_sigquit (int sig
)
1187 mark_async_signal_handler (sigquit_token
);
1188 signal (sig
, handle_sigquit
);
1192 #if defined (SIGQUIT) || defined (SIGHUP)
1193 /* Called by the event loop in response to a SIGQUIT or an
1196 async_do_nothing (gdb_client_data arg
)
1198 /* Empty function body. */
1203 /* Tell the event loop what to do if SIGHUP is received.
1204 See event-signal.c. */
1206 handle_sighup (int sig
)
1208 mark_async_signal_handler (sighup_token
);
1209 signal (sig
, handle_sighup
);
1212 /* Called by the event loop to process a SIGHUP. */
1214 async_disconnect (gdb_client_data arg
)
1222 catch (const gdb_exception
&exception
)
1224 fputs_filtered ("Could not kill the program being debugged",
1226 exception_print (gdb_stderr
, exception
);
1229 for (inferior
*inf
: all_inferiors ())
1231 switch_to_inferior_no_thread (inf
);
1236 catch (const gdb_exception
&exception
)
1241 signal (SIGHUP
, SIG_DFL
); /*FIXME: ??????????? */
1248 handle_sigtstp (int sig
)
1250 mark_async_signal_handler (sigtstp_token
);
1251 signal (sig
, handle_sigtstp
);
1255 async_sigtstp_handler (gdb_client_data arg
)
1257 const std::string
&prompt
= get_prompt ();
1259 signal (SIGTSTP
, SIG_DFL
);
1260 unblock_signal (SIGTSTP
);
1262 signal (SIGTSTP
, handle_sigtstp
);
1263 printf_unfiltered ("%s", prompt
.c_str ());
1264 gdb_flush (gdb_stdout
);
1266 /* Forget about any previous command -- null line now will do
1270 #endif /* SIGTSTP */
1274 /* Set things up for readline to be invoked via the alternate
1275 interface, i.e. via a callback function
1276 (gdb_rl_callback_read_char), and hook up instream to the event
1280 gdb_setup_readline (int editing
)
1282 struct ui
*ui
= current_ui
;
1284 /* This function is a noop for the sync case. The assumption is
1285 that the sync setup is ALL done in gdb_init, and we would only
1286 mess it up here. The sync stuff should really go away over
1289 gdb_stdout
= new stdio_file (ui
->outstream
);
1290 gdb_stderr
= new stderr_file (ui
->errstream
);
1291 gdb_stdlog
= gdb_stderr
; /* for moment */
1292 gdb_stdtarg
= gdb_stderr
; /* for moment */
1293 gdb_stdtargerr
= gdb_stderr
; /* for moment */
1295 /* If the input stream is connected to a terminal, turn on editing.
1296 However, that is only allowed on the main UI, as we can only have
1297 one instance of readline. */
1298 if (ISATTY (ui
->instream
) && editing
&& ui
== main_ui
)
1300 /* Tell gdb that we will be using the readline library. This
1301 could be overwritten by a command in .gdbinit like 'set
1302 editing on' or 'off'. */
1303 ui
->command_editing
= 1;
1305 /* When a character is detected on instream by select or poll,
1306 readline will be invoked via this callback function. */
1307 ui
->call_readline
= gdb_rl_callback_read_char_wrapper
;
1309 /* Tell readline to use the same input stream that gdb uses. */
1310 rl_instream
= ui
->instream
;
1314 ui
->command_editing
= 0;
1315 ui
->call_readline
= gdb_readline_no_editing_callback
;
1318 /* Now create the event source for this UI's input file descriptor.
1319 Another source is going to be the target program (inferior), but
1320 that must be registered only when it actually exists (I.e. after
1321 we say 'run' or after we connect to a remote target. */
1322 ui_register_input_event_handler (ui
);
1325 /* Disable command input through the standard CLI channels. Used in
1326 the suspend proc for interpreters that use the standard gdb readline
1327 interface, like the cli & the mi. */
1330 gdb_disable_readline (void)
1332 struct ui
*ui
= current_ui
;
1334 /* FIXME - It is too heavyweight to delete and remake these every
1335 time you run an interpreter that needs readline. It is probably
1336 better to have the interpreters cache these, which in turn means
1337 that this needs to be moved into interpreter specific code. */
1340 ui_file_delete (gdb_stdout
);
1341 ui_file_delete (gdb_stderr
);
1344 gdb_stdtargerr
= NULL
;
1347 if (ui
->command_editing
)
1348 gdb_rl_callback_handler_remove ();
1349 delete_file_handler (ui
->input_fd
);
1352 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler
)
1354 m_old_handler
= thread_local_segv_handler
;
1355 thread_local_segv_handler
= new_handler
;
1358 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1360 thread_local_segv_handler
= m_old_handler
;
1363 static const char debug_event_loop_off
[] = "off";
1364 static const char debug_event_loop_all_except_ui
[] = "all-except-ui";
1365 static const char debug_event_loop_all
[] = "all";
1367 static const char *debug_event_loop_enum
[] = {
1368 debug_event_loop_off
,
1369 debug_event_loop_all_except_ui
,
1370 debug_event_loop_all
,
1374 static const char *debug_event_loop_value
= debug_event_loop_off
;
1377 set_debug_event_loop_command (const char *args
, int from_tty
,
1378 cmd_list_element
*c
)
1380 if (debug_event_loop_value
== debug_event_loop_off
)
1381 debug_event_loop
= debug_event_loop_kind::OFF
;
1382 else if (debug_event_loop_value
== debug_event_loop_all_except_ui
)
1383 debug_event_loop
= debug_event_loop_kind::ALL_EXCEPT_UI
;
1384 else if (debug_event_loop_value
== debug_event_loop_all
)
1385 debug_event_loop
= debug_event_loop_kind::ALL
;
1387 gdb_assert_not_reached ("Invalid debug event look kind value.");
1391 show_debug_event_loop_command (struct ui_file
*file
, int from_tty
,
1392 struct cmd_list_element
*cmd
, const char *value
)
1394 fprintf_filtered (file
, _("Event loop debugging is %s.\n"), value
);
1397 void _initialize_event_top ();
1399 _initialize_event_top ()
1401 add_setshow_enum_cmd ("event-loop", class_maintenance
,
1402 debug_event_loop_enum
,
1403 &debug_event_loop_value
,
1404 _("Set event-loop debugging."),
1405 _("Show event-loop debugging."),
1407 Control whether to show event loop-related debug messages."),
1408 set_debug_event_loop_command
,
1409 show_debug_event_loop_command
,
1410 &setdebuglist
, &showdebuglist
);
1412 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance
,
1413 &bt_on_fatal_signal
, _("\
1414 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1415 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1416 Use \"on\" to enable, \"off\" to disable.\n\
1417 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1418 signal from within GDB itself. This is a mechanism to help diagnose\n\
1419 crashes within GDB, not a mechanism for debugging inferiors."),
1420 gdb_internal_backtrace_set_cmd
,
1421 show_bt_on_fatal_signal
,
1422 &maintenance_set_cmdlist
,
1423 &maintenance_show_cmdlist
);