Automatic date update in version.in
[binutils-gdb.git] / gdb / event-top.c
blob6a2a75fe3dc8e1c56a8a987c8dddbffcf0e0be73
1 /* Top level stuff for GDB, the GNU debugger.
3 Copyright (C) 1999-2024 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/>. */
22 #include "top.h"
23 #include "ui.h"
24 #include "inferior.h"
25 #include "infrun.h"
26 #include "target.h"
27 #include "terminal.h"
28 #include "gdbsupport/event-loop.h"
29 #include "event-top.h"
30 #include "interps.h"
31 #include <signal.h>
32 #include "cli/cli-script.h"
33 #include "main.h"
34 #include "gdbthread.h"
35 #include "observable.h"
36 #include "gdbcmd.h"
37 #include "annotate.h"
38 #include "maint.h"
39 #include "ser-event.h"
40 #include "gdbsupport/gdb_select.h"
41 #include "gdbsupport/gdb-sigmask.h"
42 #include "async-event.h"
43 #include "bt-utils.h"
44 #include "pager.h"
46 /* readline include files. */
47 #include "readline/readline.h"
48 #include "readline/history.h"
50 #ifdef TUI
51 #include "tui/tui.h"
52 #endif
54 /* readline defines this. */
55 #undef savestring
57 static std::string top_level_prompt ();
59 /* Signal handlers. */
60 #ifdef SIGQUIT
61 static void handle_sigquit (int sig);
62 #endif
63 #ifdef SIGHUP
64 static void handle_sighup (int sig);
65 #endif
67 /* Functions to be invoked by the event loop in response to
68 signals. */
69 #if defined (SIGQUIT) || defined (SIGHUP)
70 static void async_do_nothing (gdb_client_data);
71 #endif
72 #ifdef SIGHUP
73 static void async_disconnect (gdb_client_data);
74 #endif
75 #ifdef SIGTSTP
76 static void async_sigtstp_handler (gdb_client_data);
77 #endif
78 static void async_sigterm_handler (gdb_client_data arg);
80 /* Instead of invoking (and waiting for) readline to read the command
81 line and pass it back for processing, we use readline's alternate
82 interface, via callback functions, so that the event loop can react
83 to other event sources while we wait for input. */
85 /* Important variables for the event loop. */
87 /* This is used to determine if GDB is using the readline library or
88 its own simplified form of readline. It is used by the asynchronous
89 form of the set editing command.
90 ezannoni: as of 1999-04-29 I expect that this
91 variable will not be used after gdb is changed to use the event
92 loop as default engine, and event-top.c is merged into top.c. */
93 bool set_editing_cmd_var;
95 /* This is used to display the notification of the completion of an
96 asynchronous execution command. */
97 bool exec_done_display_p = false;
99 /* Used by the stdin event handler to compensate for missed stdin events.
100 Setting this to a non-zero value inside an stdin callback makes the callback
101 run again. */
102 int call_stdin_event_handler_again_p;
104 /* When true GDB will produce a minimal backtrace when a fatal signal is
105 reached (within GDB code). */
106 static bool bt_on_fatal_signal = GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON;
108 /* Implement 'maintenance show backtrace-on-fatal-signal'. */
110 static void
111 show_bt_on_fatal_signal (struct ui_file *file, int from_tty,
112 struct cmd_list_element *cmd, const char *value)
114 gdb_printf (file, _("Backtrace on a fatal signal is %s.\n"), value);
117 /* Signal handling variables. */
118 /* Each of these is a pointer to a function that the event loop will
119 invoke if the corresponding signal has received. The real signal
120 handlers mark these functions as ready to be executed and the event
121 loop, in a later iteration, calls them. See the function
122 invoke_async_signal_handler. */
123 static struct async_signal_handler *sigint_token;
124 #ifdef SIGHUP
125 static struct async_signal_handler *sighup_token;
126 #endif
127 #ifdef SIGQUIT
128 static struct async_signal_handler *sigquit_token;
129 #endif
130 #ifdef SIGTSTP
131 static struct async_signal_handler *sigtstp_token;
132 #endif
133 static struct async_signal_handler *async_sigterm_token;
135 /* This hook is called by gdb_rl_callback_read_char_wrapper after each
136 character is processed. */
137 void (*after_char_processing_hook) (void);
139 #if RL_VERSION_MAJOR == 7
140 extern "C" void _rl_signal_handler (int);
141 #endif
143 /* Wrapper function for calling into the readline library. This takes
144 care of a couple things:
146 - The event loop expects the callback function to have a parameter,
147 while readline expects none.
149 - Propagation of GDB exceptions/errors thrown from INPUT_HANDLER
150 across readline requires special handling.
152 On the exceptions issue:
154 DWARF-based unwinding cannot cross code built without -fexceptions.
155 Any exception that tries to propagate through such code will fail
156 and the result is a call to std::terminate. While some ABIs, such
157 as x86-64, require all code to be built with exception tables,
158 others don't.
160 This is a problem when GDB calls some non-EH-aware C library code,
161 that calls into GDB again through a callback, and that GDB callback
162 code throws a C++ exception. Turns out this is exactly what
163 happens with GDB's readline callback.
165 In such cases, we must catch and save any C++ exception that might
166 be thrown from the GDB callback before returning to the
167 non-EH-aware code. When the non-EH-aware function itself returns
168 back to GDB, we then rethrow the original C++ exception.
170 In the readline case however, the right thing to do is to longjmp
171 out of the callback, rather than do a normal return -- there's no
172 way for the callback to return to readline an indication that an
173 error happened, so a normal return would have rl_callback_read_char
174 potentially continue processing further input, redisplay the
175 prompt, etc. Instead of raw setjmp/longjmp however, we use our
176 sjlj-based TRY/CATCH mechanism, which knows to handle multiple
177 levels of active setjmp/longjmp frames, needed in order to handle
178 the readline callback recursing, as happens with e.g., secondary
179 prompts / queries, through gdb_readline_wrapper. This must be
180 noexcept in order to avoid problems with mixing sjlj and
181 (sjlj-based) C++ exceptions. */
183 static struct gdb_exception
184 gdb_rl_callback_read_char_wrapper_noexcept () noexcept
186 struct gdb_exception gdb_expt;
188 /* C++ exceptions can't normally be thrown across readline (unless
189 it is built with -fexceptions, but it won't by default on many
190 ABIs). So we instead wrap the readline call with a sjlj-based
191 TRY/CATCH, and rethrow the GDB exception once back in GDB. */
192 TRY_SJLJ
194 rl_callback_read_char ();
195 #if RL_VERSION_MAJOR >= 8
196 /* It can happen that readline (while in rl_callback_read_char)
197 received a signal, but didn't handle it yet. Make sure it's handled
198 now. If we don't do that we run into two related problems:
199 - we have to wait for another event triggering
200 rl_callback_read_char before the signal is handled
201 - there's no guarantee that the signal will be processed before the
202 event. */
203 while (rl_pending_signal () != 0)
204 /* Do this in a while loop, in case rl_check_signals also leaves a
205 pending signal. I'm not sure if that's possible, but it seems
206 better to handle the scenario than to assert. */
207 rl_check_signals ();
208 #elif RL_VERSION_MAJOR == 7
209 /* Unfortunately, rl_check_signals is not available. Use private
210 function _rl_signal_handler instead. */
212 while (rl_pending_signal () != 0)
213 _rl_signal_handler (rl_pending_signal ());
214 #else
215 #error "Readline major version >= 7 expected"
216 #endif
217 if (after_char_processing_hook)
218 (*after_char_processing_hook) ();
220 CATCH_SJLJ (ex, RETURN_MASK_ALL)
222 gdb_expt = std::move (ex);
224 END_CATCH_SJLJ
226 return gdb_expt;
229 static void
230 gdb_rl_callback_read_char_wrapper (gdb_client_data client_data)
232 struct gdb_exception gdb_expt
233 = gdb_rl_callback_read_char_wrapper_noexcept ();
235 /* Rethrow using the normal EH mechanism. */
236 if (gdb_expt.reason < 0)
237 throw_exception (std::move (gdb_expt));
240 /* GDB's readline callback handler. Calls the current INPUT_HANDLER,
241 and propagates GDB exceptions/errors thrown from INPUT_HANDLER back
242 across readline. See gdb_rl_callback_read_char_wrapper. This must
243 be noexcept in order to avoid problems with mixing sjlj and
244 (sjlj-based) C++ exceptions. */
246 static void
247 gdb_rl_callback_handler (char *rl) noexcept
249 /* This is static to avoid undefined behavior when calling longjmp
250 -- gdb_exception has a destructor with side effects. */
251 static struct gdb_exception gdb_rl_expt;
252 struct ui *ui = current_ui;
254 /* In bracketed paste mode, pasting a complete line can result in a
255 literal newline appearing at the end of LINE. However, we never
256 want this in gdb. */
257 if (rl != nullptr)
259 size_t len = strlen (rl);
260 while (len > 0 && (rl[len - 1] == '\r' || rl[len - 1] == '\n'))
261 --len;
262 rl[len] = '\0';
267 /* Ensure the exception is reset on each call. */
268 gdb_rl_expt = {};
269 ui->input_handler (gdb::unique_xmalloc_ptr<char> (rl));
271 catch (gdb_exception &ex)
273 gdb_rl_expt = std::move (ex);
276 /* If we caught a GDB exception, longjmp out of the readline
277 callback. There's no other way for the callback to signal to
278 readline that an error happened. A normal return would have
279 readline potentially continue processing further input, redisplay
280 the prompt, etc. (This is what GDB historically did when it was
281 a C program.) Note that since we're long jumping, local variable
282 dtors are NOT run automatically. */
283 if (gdb_rl_expt.reason < 0)
284 throw_exception_sjlj (gdb_rl_expt);
287 /* Change the function to be invoked every time there is a character
288 ready on stdin. This is used when the user sets the editing off,
289 therefore bypassing readline, and letting gdb handle the input
290 itself, via gdb_readline_no_editing_callback. Also it is used in
291 the opposite case in which the user sets editing on again, by
292 restoring readline handling of the input.
294 NOTE: this operates on input_fd, not instream. If we are reading
295 commands from a file, instream will point to the file. However, we
296 always read commands from a file with editing off. This means that
297 the 'set editing on/off' will have effect only on the interactive
298 session. */
300 void
301 change_line_handler (int editing)
303 struct ui *ui = current_ui;
305 /* We can only have one instance of readline, so we only allow
306 editing on the main UI. */
307 if (ui != main_ui)
308 return;
310 /* Don't try enabling editing if the interpreter doesn't support it
311 (e.g., MI). */
312 if (!top_level_interpreter ()->supports_command_editing ()
313 || !command_interp ()->supports_command_editing ())
314 return;
316 if (editing)
318 gdb_assert (ui == main_ui);
320 /* Turn on editing by using readline. */
321 ui->call_readline = gdb_rl_callback_read_char_wrapper;
323 else
325 /* Turn off editing by using gdb_readline_no_editing_callback. */
326 if (ui->command_editing)
327 gdb_rl_callback_handler_remove ();
328 ui->call_readline = gdb_readline_no_editing_callback;
330 ui->command_editing = editing;
333 /* The functions below are wrappers for rl_callback_handler_remove and
334 rl_callback_handler_install that keep track of whether the callback
335 handler is installed in readline. This is necessary because after
336 handling a target event of a background execution command, we may
337 need to reinstall the callback handler if it was removed due to a
338 secondary prompt. See gdb_readline_wrapper_line. We don't
339 unconditionally install the handler for every target event because
340 that also clears the line buffer, thus installing it while the user
341 is typing would lose input. */
343 /* Whether we've registered a callback handler with readline. */
344 static bool callback_handler_installed;
346 /* See event-top.h, and above. */
348 void
349 gdb_rl_callback_handler_remove (void)
351 gdb_assert (current_ui == main_ui);
353 rl_callback_handler_remove ();
354 callback_handler_installed = false;
357 /* See event-top.h, and above. Note this wrapper doesn't have an
358 actual callback parameter because we always install
359 INPUT_HANDLER. */
361 void
362 gdb_rl_callback_handler_install (const char *prompt)
364 gdb_assert (current_ui == main_ui);
366 /* Calling rl_callback_handler_install resets readline's input
367 buffer. Calling this when we were already processing input
368 therefore loses input. */
369 gdb_assert (!callback_handler_installed);
371 rl_callback_handler_install (prompt, gdb_rl_callback_handler);
372 callback_handler_installed = true;
375 /* See event-top.h, and above. */
377 void
378 gdb_rl_callback_handler_reinstall (void)
380 gdb_assert (current_ui == main_ui);
382 if (!callback_handler_installed)
384 /* Passing NULL as prompt argument tells readline to not display
385 a prompt. */
386 gdb_rl_callback_handler_install (NULL);
390 /* Displays the prompt. If the argument NEW_PROMPT is NULL, the
391 prompt that is displayed is the current top level prompt.
392 Otherwise, it displays whatever NEW_PROMPT is as a local/secondary
393 prompt.
395 This is used after each gdb command has completed, and in the
396 following cases:
398 1. When the user enters a command line which is ended by '\'
399 indicating that the command will continue on the next line. In
400 that case the prompt that is displayed is the empty string.
402 2. When the user is entering 'commands' for a breakpoint, or
403 actions for a tracepoint. In this case the prompt will be '>'
405 3. On prompting for pagination. */
407 void
408 display_gdb_prompt (const char *new_prompt)
410 std::string actual_gdb_prompt;
412 annotate_display_prompt ();
414 /* Reset the nesting depth used when trace-commands is set. */
415 reset_command_nest_depth ();
417 /* Do not call the python hook on an explicit prompt change as
418 passed to this function, as this forms a secondary/local prompt,
419 IE, displayed but not set. */
420 if (! new_prompt)
422 struct ui *ui = current_ui;
424 if (ui->prompt_state == PROMPTED)
425 internal_error (_("double prompt"));
426 else if (ui->prompt_state == PROMPT_BLOCKED)
428 /* This is to trick readline into not trying to display the
429 prompt. Even though we display the prompt using this
430 function, readline still tries to do its own display if
431 we don't call rl_callback_handler_install and
432 rl_callback_handler_remove (which readline detects
433 because a global variable is not set). If readline did
434 that, it could mess up gdb signal handlers for SIGINT.
435 Readline assumes that between calls to rl_set_signals and
436 rl_clear_signals gdb doesn't do anything with the signal
437 handlers. Well, that's not the case, because when the
438 target executes we change the SIGINT signal handler. If
439 we allowed readline to display the prompt, the signal
440 handler change would happen exactly between the calls to
441 the above two functions. Calling
442 rl_callback_handler_remove(), does the job. */
444 if (current_ui->command_editing)
445 gdb_rl_callback_handler_remove ();
446 return;
448 else if (ui->prompt_state == PROMPT_NEEDED)
450 /* Display the top level prompt. */
451 actual_gdb_prompt = top_level_prompt ();
452 ui->prompt_state = PROMPTED;
455 else
456 actual_gdb_prompt = new_prompt;
458 if (current_ui->command_editing)
460 gdb_rl_callback_handler_remove ();
461 gdb_rl_callback_handler_install (actual_gdb_prompt.c_str ());
463 /* new_prompt at this point can be the top of the stack or the one
464 passed in. It can't be NULL. */
465 else
467 /* Don't use a _filtered function here. It causes the assumed
468 character position to be off, since the newline we read from
469 the user is not accounted for. */
470 printf_unfiltered ("%s", actual_gdb_prompt.c_str ());
471 gdb_flush (gdb_stdout);
475 /* Notify the 'before_prompt' observer, and run any additional actions
476 that must be done before we display the prompt. */
477 static void
478 notify_before_prompt (const char *prompt)
480 /* Give observers a chance of changing the prompt. E.g., the python
481 `gdb.prompt_hook' is installed as an observer. */
482 gdb::observers::before_prompt.notify (prompt);
484 /* As we are about to display the prompt, and so GDB might be sitting
485 idle for some time, close all the cached BFDs. This ensures that
486 when we next start running a user command all BFDs will be reopened
487 as needed, and as a result, we will see any on-disk changes. */
488 bfd_cache_close_all ();
491 /* Return the top level prompt, as specified by "set prompt", possibly
492 overridden by the python gdb.prompt_hook hook, and then composed
493 with the prompt prefix and suffix (annotations). */
495 static std::string
496 top_level_prompt (void)
498 notify_before_prompt (get_prompt ().c_str ());
500 const std::string &prompt = get_prompt ();
502 if (annotation_level >= 2)
504 /* Prefix needs to have new line at end. */
505 const char prefix[] = "\n\032\032pre-prompt\n";
507 /* Suffix needs to have a new line at end and \032 \032 at
508 beginning. */
509 const char suffix[] = "\n\032\032prompt\n";
511 return std::string (prefix) + prompt.c_str () + suffix;
514 return prompt;
517 /* Get a reference to the current UI's line buffer. This is used to
518 construct a whole line of input from partial input. */
520 static std::string &
521 get_command_line_buffer (void)
523 return current_ui->line_buffer;
526 /* Re-enable stdin after the end of an execution command in
527 synchronous mode, or after an error from the target, and we aborted
528 the exec operation. */
530 void
531 async_enable_stdin (void)
533 struct ui *ui = current_ui;
535 if (ui->prompt_state == PROMPT_BLOCKED
536 && !ui->keep_prompt_blocked)
538 target_terminal::ours ();
539 ui->register_file_handler ();
540 ui->prompt_state = PROMPT_NEEDED;
544 /* Disable reads from stdin (the console) marking the command as
545 synchronous. */
547 void
548 async_disable_stdin (void)
550 struct ui *ui = current_ui;
552 ui->prompt_state = PROMPT_BLOCKED;
553 ui->unregister_file_handler ();
557 /* Handle a gdb command line. This function is called when
558 handle_line_of_input has concatenated one or more input lines into
559 a whole command. */
561 void
562 command_handler (const char *command)
564 struct ui *ui = current_ui;
565 const char *c;
567 if (ui->instream == ui->stdin_stream)
568 reinitialize_more_filter ();
570 scoped_command_stats stat_reporter (true);
572 /* Do not execute commented lines. */
573 for (c = command; *c == ' ' || *c == '\t'; c++)
575 if (c[0] != '#')
577 execute_command (command, ui->instream == ui->stdin_stream);
579 /* Do any commands attached to breakpoint we stopped at. */
580 bpstat_do_actions ();
584 /* Append RL, an input line returned by readline or one of its emulations, to
585 CMD_LINE_BUFFER. Return true if we have a whole command line ready to be
586 processed by the command interpreter or false if the command line isn't
587 complete yet (input line ends in a backslash). */
589 static bool
590 command_line_append_input_line (std::string &cmd_line_buffer, const char *rl)
592 size_t len = strlen (rl);
594 if (len > 0 && rl[len - 1] == '\\')
596 /* Don't copy the backslash and wait for more. */
597 cmd_line_buffer.append (rl, len - 1);
598 return false;
600 else
602 /* Copy whole line including terminating null, and we're
603 done. */
604 cmd_line_buffer.append (rl, len + 1);
605 return true;
609 /* Handle a line of input coming from readline.
611 If the read line ends with a continuation character (backslash), return
612 nullptr. Otherwise, return a pointer to the command line, indicating a whole
613 command line is ready to be executed.
615 The returned pointer may or may not point to CMD_LINE_BUFFER's internal
616 buffer.
618 Return EOF on end of file.
620 If REPEAT, handle command repetitions:
622 - If the input command line is NOT empty, the command returned is
623 saved using save_command_line () so that it can be repeated later.
625 - OTOH, if the input command line IS empty, return the saved
626 command instead of the empty input line.
629 const char *
630 handle_line_of_input (std::string &cmd_line_buffer,
631 const char *rl, int repeat,
632 const char *annotation_suffix)
634 struct ui *ui = current_ui;
635 int from_tty = ui->instream == ui->stdin_stream;
637 if (rl == NULL)
638 return (char *) EOF;
640 bool complete = command_line_append_input_line (cmd_line_buffer, rl);
641 if (!complete)
642 return NULL;
644 if (from_tty && annotation_level > 1)
645 printf_unfiltered (("\n\032\032post-%s\n"), annotation_suffix);
647 #define SERVER_COMMAND_PREFIX "server "
648 server_command = startswith (cmd_line_buffer.c_str (), SERVER_COMMAND_PREFIX);
649 if (server_command)
651 /* Note that we don't call `save_command_line'. Between this
652 and the check in dont_repeat, this insures that repeating
653 will still do the right thing. */
654 return cmd_line_buffer.c_str () + strlen (SERVER_COMMAND_PREFIX);
657 /* Do history expansion if that is wished. */
658 if (history_expansion_p && from_tty && current_ui->input_interactive_p ())
660 char *cmd_expansion;
661 int expanded;
663 /* Note: here, we pass a pointer to the std::string's internal buffer as
664 a `char *`. At the time of writing, readline's history_expand does
665 not modify the passed-in string. Ideally, readline should be modified
666 to make that parameter `const char *`. */
667 expanded = history_expand (&cmd_line_buffer[0], &cmd_expansion);
668 gdb::unique_xmalloc_ptr<char> history_value (cmd_expansion);
669 if (expanded)
671 /* Print the changes. */
672 printf_unfiltered ("%s\n", history_value.get ());
674 /* If there was an error, call this function again. */
675 if (expanded < 0)
676 return cmd_line_buffer.c_str ();
678 cmd_line_buffer = history_value.get ();
682 /* If we just got an empty line, and that is supposed to repeat the
683 previous command, return the previously saved command. */
684 const char *p1;
685 for (p1 = cmd_line_buffer.c_str (); *p1 == ' ' || *p1 == '\t'; p1++)
687 if (repeat && *p1 == '\0')
688 return get_saved_command_line ();
690 /* Add command to history if appropriate. Note: lines consisting
691 solely of comments are also added to the command history. This
692 is useful when you type a command, and then realize you don't
693 want to execute it quite yet. You can comment out the command
694 and then later fetch it from the value history and remove the
695 '#'. The kill ring is probably better, but some people are in
696 the habit of commenting things out. */
697 if (cmd_line_buffer[0] != '\0' && from_tty && current_ui->input_interactive_p ())
698 gdb_add_history (cmd_line_buffer.c_str ());
700 /* Save into global buffer if appropriate. */
701 if (repeat)
703 save_command_line (cmd_line_buffer.c_str ());
705 /* It is important that we return a pointer to the saved command line
706 here, for the `cmd_start == saved_command_line` check in
707 execute_command to work. */
708 return get_saved_command_line ();
711 return cmd_line_buffer.c_str ();
714 /* See event-top.h. */
716 void
717 gdb_rl_deprep_term_function (void)
719 #ifdef RL_STATE_EOF
720 std::optional<scoped_restore_tmpl<int>> restore_eof_found;
722 if (RL_ISSTATE (RL_STATE_EOF))
724 printf_unfiltered ("quit\n");
725 restore_eof_found.emplace (&rl_eof_found, 0);
728 #endif /* RL_STATE_EOF */
730 rl_deprep_terminal ();
733 /* Handle a complete line of input. This is called by the callback
734 mechanism within the readline library. Deal with incomplete
735 commands as well, by saving the partial input in a global
736 buffer.
738 NOTE: This is the asynchronous version of the command_line_input
739 function. */
741 void
742 command_line_handler (gdb::unique_xmalloc_ptr<char> &&rl)
744 std::string &line_buffer = get_command_line_buffer ();
745 struct ui *ui = current_ui;
747 const char *cmd = handle_line_of_input (line_buffer, rl.get (), 1, "prompt");
748 if (cmd == (char *) EOF)
750 /* stdin closed. The connection with the terminal is gone.
751 This happens at the end of a testsuite run, after Expect has
752 hung up but GDB is still alive. In such a case, we just quit
753 gdb killing the inferior program too. This also happens if the
754 user sends EOF, which is usually bound to ctrl+d. */
756 #ifndef RL_STATE_EOF
757 /* When readline is using bracketed paste mode, then, when eof is
758 received, readline will emit the control sequence to leave
759 bracketed paste mode.
761 This control sequence ends with \r, which means that the "quit" we
762 are about to print will overwrite the prompt on this line.
764 The solution to this problem is to actually print the "quit"
765 message from gdb_rl_deprep_term_function (see above), however, we
766 can only do that if we can know, in that function, when eof was
767 received.
769 Unfortunately, with older versions of readline, it is not possible
770 in the gdb_rl_deprep_term_function to know if eof was received or
771 not, and, as GDB can be built against the system readline, which
772 could be older than the readline in GDB's repository, then we
773 can't be sure that we can work around this prompt corruption in
774 the gdb_rl_deprep_term_function function.
776 If we get here, RL_STATE_EOF is not defined. This indicates that
777 we are using an older readline, and couldn't print the quit
778 message in gdb_rl_deprep_term_function. So, what we do here is
779 check to see if bracketed paste mode is on or not. If it's on
780 then we print a \n and then the quit, this means the user will
781 see:
783 (gdb)
784 quit
786 Rather than the usual:
788 (gdb) quit
790 Which we will get with a newer readline, but this really is the
791 best we can do with older versions of readline. */
792 const char *value = rl_variable_value ("enable-bracketed-paste");
793 if (value != nullptr && strcmp (value, "on") == 0
794 && ((rl_readline_version >> 8) & 0xff) > 0x07)
795 printf_unfiltered ("\n");
796 printf_unfiltered ("quit\n");
797 #endif
799 execute_command ("quit", 1);
801 else if (cmd == NULL)
803 /* We don't have a full line yet. Print an empty prompt. */
804 display_gdb_prompt ("");
806 else
808 ui->prompt_state = PROMPT_NEEDED;
810 /* Ensure the UI's line buffer is empty for the next command. */
811 SCOPE_EXIT { line_buffer.clear (); };
813 command_handler (cmd);
815 if (ui->prompt_state != PROMPTED)
816 display_gdb_prompt (0);
820 /* Does reading of input from terminal w/o the editing features
821 provided by the readline library. Calls the line input handler
822 once we have a whole input line. */
824 void
825 gdb_readline_no_editing_callback (gdb_client_data client_data)
827 int c;
828 std::string line_buffer;
829 struct ui *ui = current_ui;
831 FILE *stream = ui->instream != nullptr ? ui->instream : ui->stdin_stream;
832 gdb_assert (stream != nullptr);
834 /* We still need the while loop here, even though it would seem
835 obvious to invoke gdb_readline_no_editing_callback at every
836 character entered. If not using the readline library, the
837 terminal is in cooked mode, which sends the characters all at
838 once. Poll will notice that the input fd has changed state only
839 after enter is pressed. At this point we still need to fetch all
840 the chars entered. */
842 while (1)
844 /* Read from stdin if we are executing a user defined command.
845 This is the right thing for prompt_for_continue, at least. */
846 c = fgetc (stream);
848 if (c == EOF)
850 if (!line_buffer.empty ())
852 /* The last line does not end with a newline. Return it, and
853 if we are called again fgetc will still return EOF and
854 we'll return NULL then. */
855 break;
857 ui->input_handler (NULL);
858 return;
861 if (c == '\n')
863 if (!line_buffer.empty () && line_buffer.back () == '\r')
864 line_buffer.pop_back ();
865 break;
868 line_buffer += c;
871 ui->input_handler (make_unique_xstrdup (line_buffer.c_str ()));
875 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
876 otherwise, return false. */
878 static bool
879 unblock_signal (int sig)
881 #if HAVE_SIGPROCMASK
882 sigset_t sigset;
883 sigemptyset (&sigset);
884 sigaddset (&sigset, sig);
885 gdb_sigmask (SIG_UNBLOCK, &sigset, 0);
886 return true;
887 #endif
889 return false;
892 /* Called to handle fatal signals. SIG is the signal number. */
894 static void ATTRIBUTE_NORETURN
895 handle_fatal_signal (int sig)
897 #ifdef TUI
898 tui_disable ();
899 #endif
901 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
902 const auto sig_write = [] (const char *msg) -> void
904 gdb_stderr->write_async_safe (msg, strlen (msg));
907 if (bt_on_fatal_signal)
909 sig_write ("\n\n");
910 sig_write (_("Fatal signal: "));
911 sig_write (strsignal (sig));
912 sig_write ("\n");
914 gdb_internal_backtrace ();
916 sig_write (_("A fatal error internal to GDB has been detected, "
917 "further\ndebugging is not possible. GDB will now "
918 "terminate.\n\n"));
919 sig_write (_("This is a bug, please report it."));
920 if (REPORT_BUGS_TO[0] != '\0')
922 sig_write (_(" For instructions, see:\n"));
923 sig_write (REPORT_BUGS_TO);
924 sig_write (".");
926 sig_write ("\n\n");
928 gdb_stderr->flush ();
930 #endif
932 /* If possible arrange for SIG to have its default behaviour (which
933 should be to terminate the current process), unblock SIG, and reraise
934 the signal. This ensures GDB terminates with the expected signal. */
935 if (signal (sig, SIG_DFL) != SIG_ERR
936 && unblock_signal (sig))
937 raise (sig);
939 /* The above failed, so try to use SIGABRT to terminate GDB. */
940 #ifdef SIGABRT
941 signal (SIGABRT, SIG_DFL);
942 #endif
943 abort (); /* ARI: abort */
946 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
947 always installs a global SIGSEGV handler, and then lets threads
948 indicate their interest in handling the signal by setting this
949 thread-local variable.
951 This is a static variable instead of extern because on various platforms
952 (notably Cygwin) extern thread_local variables cause link errors. So
953 instead, we have scoped_segv_handler_restore, which also makes it impossible
954 to accidentally forget to restore it to the original value. */
956 static thread_local void (*thread_local_segv_handler) (int);
958 static void handle_sigsegv (int sig);
960 /* Install the SIGSEGV handler. */
961 static void
962 install_handle_sigsegv ()
964 #if defined (HAVE_SIGACTION)
965 struct sigaction sa;
966 sa.sa_handler = handle_sigsegv;
967 sigemptyset (&sa.sa_mask);
968 #ifdef HAVE_SIGALTSTACK
969 sa.sa_flags = SA_ONSTACK;
970 #else
971 sa.sa_flags = 0;
972 #endif
973 sigaction (SIGSEGV, &sa, nullptr);
974 #else
975 signal (SIGSEGV, handle_sigsegv);
976 #endif
979 /* Handler for SIGSEGV. */
981 static void
982 handle_sigsegv (int sig)
984 install_handle_sigsegv ();
986 if (thread_local_segv_handler == nullptr)
987 handle_fatal_signal (sig);
988 thread_local_segv_handler (sig);
993 /* The serial event associated with the QUIT flag. set_quit_flag sets
994 this, and check_quit_flag clears it. Used by interruptible_select
995 to be able to do interruptible I/O with no race with the SIGINT
996 handler. */
997 static struct serial_event *quit_serial_event;
999 /* Initialization of signal handlers and tokens. There are a number of
1000 different strategies for handling different signals here.
1002 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
1003 handle_sig* for each of these signals. These functions are the actual
1004 signal handlers associated to the signals via calls to signal(). The
1005 only job for these functions is to enqueue the appropriate
1006 event/procedure with the event loop. The event loop will take care of
1007 invoking the queued procedures to perform the usual tasks associated
1008 with the reception of the signal.
1010 For SIGSEGV the handle_sig* function does all the work for handling this
1011 signal.
1013 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
1014 terminate immediately. */
1015 void
1016 gdb_init_signals (void)
1018 initialize_async_signal_handlers ();
1020 quit_serial_event = make_serial_event ();
1022 sigint_token =
1023 create_async_signal_handler (async_request_quit, NULL, "sigint");
1024 install_sigint_handler (handle_sigint);
1026 async_sigterm_token
1027 = create_async_signal_handler (async_sigterm_handler, NULL, "sigterm");
1028 signal (SIGTERM, handle_sigterm);
1030 #ifdef SIGQUIT
1031 sigquit_token =
1032 create_async_signal_handler (async_do_nothing, NULL, "sigquit");
1033 signal (SIGQUIT, handle_sigquit);
1034 #endif
1036 #ifdef SIGHUP
1037 if (signal (SIGHUP, handle_sighup) != SIG_IGN)
1038 sighup_token =
1039 create_async_signal_handler (async_disconnect, NULL, "sighup");
1040 else
1041 sighup_token =
1042 create_async_signal_handler (async_do_nothing, NULL, "sighup");
1043 #endif
1045 #ifdef SIGTSTP
1046 sigtstp_token =
1047 create_async_signal_handler (async_sigtstp_handler, NULL, "sigtstp");
1048 #endif
1050 #ifdef SIGFPE
1051 signal (SIGFPE, handle_fatal_signal);
1052 #endif
1054 #ifdef SIGBUS
1055 signal (SIGBUS, handle_fatal_signal);
1056 #endif
1058 #ifdef SIGABRT
1059 signal (SIGABRT, handle_fatal_signal);
1060 #endif
1062 install_handle_sigsegv ();
1065 /* See defs.h. */
1067 void
1068 quit_serial_event_set (void)
1070 serial_event_set (quit_serial_event);
1073 /* See defs.h. */
1075 void
1076 quit_serial_event_clear (void)
1078 serial_event_clear (quit_serial_event);
1081 /* Return the selectable file descriptor of the serial event
1082 associated with the quit flag. */
1084 static int
1085 quit_serial_event_fd (void)
1087 return serial_event_fd (quit_serial_event);
1090 /* See defs.h. */
1092 void
1093 default_quit_handler (void)
1095 if (check_quit_flag ())
1097 if (target_terminal::is_ours ())
1098 quit ();
1099 else
1100 target_pass_ctrlc ();
1104 /* See defs.h. */
1105 quit_handler_ftype *quit_handler = default_quit_handler;
1107 /* Handle a SIGINT. */
1109 void
1110 handle_sigint (int sig)
1112 signal (sig, handle_sigint);
1114 /* We could be running in a loop reading in symfiles or something so
1115 it may be quite a while before we get back to the event loop. So
1116 set quit_flag to 1 here. Then if QUIT is called before we get to
1117 the event loop, we will unwind as expected. */
1118 set_quit_flag ();
1120 /* In case nothing calls QUIT before the event loop is reached, the
1121 event loop handles it. */
1122 mark_async_signal_handler (sigint_token);
1125 /* See gdb_select.h. */
1128 interruptible_select (int n,
1129 fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
1130 struct timeval *timeout)
1132 fd_set my_readfds;
1133 int fd;
1134 int res;
1136 if (readfds == NULL)
1138 readfds = &my_readfds;
1139 FD_ZERO (&my_readfds);
1142 fd = quit_serial_event_fd ();
1143 FD_SET (fd, readfds);
1144 if (n <= fd)
1145 n = fd + 1;
1149 res = gdb_select (n, readfds, writefds, exceptfds, timeout);
1151 while (res == -1 && errno == EINTR);
1153 if (res == 1 && FD_ISSET (fd, readfds))
1155 errno = EINTR;
1156 return -1;
1158 return res;
1161 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1163 static void
1164 async_sigterm_handler (gdb_client_data arg)
1166 quit_force (NULL, 0);
1169 /* See defs.h. */
1170 volatile bool sync_quit_force_run;
1172 /* See defs.h. */
1173 void
1174 set_force_quit_flag ()
1176 sync_quit_force_run = true;
1177 set_quit_flag ();
1180 /* Quit GDB if SIGTERM is received.
1181 GDB would quit anyway, but this way it will clean up properly. */
1182 void
1183 handle_sigterm (int sig)
1185 signal (sig, handle_sigterm);
1187 set_force_quit_flag ();
1189 mark_async_signal_handler (async_sigterm_token);
1192 /* Do the quit. All the checks have been done by the caller. */
1193 void
1194 async_request_quit (gdb_client_data arg)
1196 /* If the quit_flag has gotten reset back to 0 by the time we get
1197 back here, that means that an exception was thrown to unwind the
1198 current command before we got back to the event loop. So there
1199 is no reason to call quit again here. */
1200 QUIT;
1203 #ifdef SIGQUIT
1204 /* Tell the event loop what to do if SIGQUIT is received.
1205 See event-signal.c. */
1206 static void
1207 handle_sigquit (int sig)
1209 mark_async_signal_handler (sigquit_token);
1210 signal (sig, handle_sigquit);
1212 #endif
1214 #if defined (SIGQUIT) || defined (SIGHUP)
1215 /* Called by the event loop in response to a SIGQUIT or an
1216 ignored SIGHUP. */
1217 static void
1218 async_do_nothing (gdb_client_data arg)
1220 /* Empty function body. */
1222 #endif
1224 #ifdef SIGHUP
1225 /* Tell the event loop what to do if SIGHUP is received.
1226 See event-signal.c. */
1227 static void
1228 handle_sighup (int sig)
1230 mark_async_signal_handler (sighup_token);
1231 signal (sig, handle_sighup);
1234 /* Called by the event loop to process a SIGHUP. */
1235 static void
1236 async_disconnect (gdb_client_data arg)
1241 quit_cover ();
1244 catch (const gdb_exception &exception)
1246 gdb_puts ("Could not kill the program being debugged",
1247 gdb_stderr);
1248 exception_print (gdb_stderr, exception);
1249 if (exception.reason == RETURN_FORCED_QUIT)
1250 throw;
1253 for (inferior *inf : all_inferiors ())
1257 inf->pop_all_targets ();
1259 catch (const gdb_exception &exception)
1264 signal (SIGHUP, SIG_DFL); /*FIXME: ??????????? */
1265 raise (SIGHUP);
1267 #endif
1269 #ifdef SIGTSTP
1270 void
1271 handle_sigtstp (int sig)
1273 mark_async_signal_handler (sigtstp_token);
1274 signal (sig, handle_sigtstp);
1277 static void
1278 async_sigtstp_handler (gdb_client_data arg)
1280 const std::string &prompt = get_prompt ();
1282 signal (SIGTSTP, SIG_DFL);
1283 unblock_signal (SIGTSTP);
1284 raise (SIGTSTP);
1285 signal (SIGTSTP, handle_sigtstp);
1286 printf_unfiltered ("%s", prompt.c_str ());
1287 gdb_flush (gdb_stdout);
1289 /* Forget about any previous command -- null line now will do
1290 nothing. */
1291 dont_repeat ();
1293 #endif /* SIGTSTP */
1297 /* Set things up for readline to be invoked via the alternate
1298 interface, i.e. via a callback function
1299 (gdb_rl_callback_read_char), and hook up instream to the event
1300 loop. */
1302 void
1303 gdb_setup_readline (int editing)
1305 struct ui *ui = current_ui;
1307 /* If the input stream is connected to a terminal, turn on editing.
1308 However, that is only allowed on the main UI, as we can only have
1309 one instance of readline. Also, INSTREAM might be nullptr when
1310 executing a user-defined command. */
1311 if (ui->instream != nullptr && ISATTY (ui->instream)
1312 && editing && ui == main_ui)
1314 /* Tell gdb that we will be using the readline library. This
1315 could be overwritten by a command in .gdbinit like 'set
1316 editing on' or 'off'. */
1317 ui->command_editing = 1;
1319 /* When a character is detected on instream by select or poll,
1320 readline will be invoked via this callback function. */
1321 ui->call_readline = gdb_rl_callback_read_char_wrapper;
1323 /* Tell readline to use the same input stream that gdb uses. */
1324 rl_instream = ui->instream;
1326 else
1328 ui->command_editing = 0;
1329 ui->call_readline = gdb_readline_no_editing_callback;
1332 /* Now create the event source for this UI's input file descriptor.
1333 Another source is going to be the target program (inferior), but
1334 that must be registered only when it actually exists (I.e. after
1335 we say 'run' or after we connect to a remote target. */
1336 ui->register_file_handler ();
1339 /* Disable command input through the standard CLI channels. Used in
1340 the suspend proc for interpreters that use the standard gdb readline
1341 interface, like the cli & the mi. */
1343 void
1344 gdb_disable_readline (void)
1346 struct ui *ui = current_ui;
1348 if (ui->command_editing)
1349 gdb_rl_callback_handler_remove ();
1350 ui->unregister_file_handler ();
1353 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler)
1355 m_old_handler = thread_local_segv_handler;
1356 thread_local_segv_handler = new_handler;
1359 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1361 thread_local_segv_handler = m_old_handler;
1364 static const char debug_event_loop_off[] = "off";
1365 static const char debug_event_loop_all_except_ui[] = "all-except-ui";
1366 static const char debug_event_loop_all[] = "all";
1368 static const char *debug_event_loop_enum[] = {
1369 debug_event_loop_off,
1370 debug_event_loop_all_except_ui,
1371 debug_event_loop_all,
1372 nullptr
1375 static const char *debug_event_loop_value = debug_event_loop_off;
1377 static void
1378 set_debug_event_loop_command (const char *args, int from_tty,
1379 cmd_list_element *c)
1381 if (debug_event_loop_value == debug_event_loop_off)
1382 debug_event_loop = debug_event_loop_kind::OFF;
1383 else if (debug_event_loop_value == debug_event_loop_all_except_ui)
1384 debug_event_loop = debug_event_loop_kind::ALL_EXCEPT_UI;
1385 else if (debug_event_loop_value == debug_event_loop_all)
1386 debug_event_loop = debug_event_loop_kind::ALL;
1387 else
1388 gdb_assert_not_reached ("Invalid debug event look kind value.");
1391 static void
1392 show_debug_event_loop_command (struct ui_file *file, int from_tty,
1393 struct cmd_list_element *cmd, const char *value)
1395 gdb_printf (file, _("Event loop debugging is %s.\n"), value);
1398 void _initialize_event_top ();
1399 void
1400 _initialize_event_top ()
1402 add_setshow_enum_cmd ("event-loop", class_maintenance,
1403 debug_event_loop_enum,
1404 &debug_event_loop_value,
1405 _("Set event-loop debugging."),
1406 _("Show event-loop debugging."),
1407 _("\
1408 Control whether to show event loop-related debug messages."),
1409 set_debug_event_loop_command,
1410 show_debug_event_loop_command,
1411 &setdebuglist, &showdebuglist);
1413 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance,
1414 &bt_on_fatal_signal, _("\
1415 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1416 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1417 Use \"on\" to enable, \"off\" to disable.\n\
1418 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1419 signal from within GDB itself. This is a mechanism to help diagnose\n\
1420 crashes within GDB, not a mechanism for debugging inferiors."),
1421 gdb_internal_backtrace_set_cmd,
1422 show_bt_on_fatal_signal,
1423 &maintenance_set_cmdlist,
1424 &maintenance_show_cmdlist);