Set development and experimental to false. Update version number to 2.40. Add relea...
[binutils-gdb.git] / gdb / event-top.c
blobfa86a89e4a191f526c6e92712615cffb2a18a5b9
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/>. */
22 #include "defs.h"
23 #include "top.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" /* for reset_command_nest_depth */
33 #include "main.h"
34 #include "gdbthread.h"
35 #include "observable.h"
36 #include "gdbcmd.h" /* for dont_repeat() */
37 #include "annotate.h"
38 #include "maint.h"
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"
44 #include "bt-utils.h"
45 #include "pager.h"
47 /* readline include files. */
48 #include "readline/readline.h"
49 #include "readline/history.h"
51 /* readline defines this. */
52 #undef savestring
54 static std::string top_level_prompt ();
56 /* Signal handlers. */
57 #ifdef SIGQUIT
58 static void handle_sigquit (int sig);
59 #endif
60 #ifdef SIGHUP
61 static void handle_sighup (int sig);
62 #endif
64 /* Functions to be invoked by the event loop in response to
65 signals. */
66 #if defined (SIGQUIT) || defined (SIGHUP)
67 static void async_do_nothing (gdb_client_data);
68 #endif
69 #ifdef SIGHUP
70 static void async_disconnect (gdb_client_data);
71 #endif
72 #ifdef SIGTSTP
73 static void async_sigtstp_handler (gdb_client_data);
74 #endif
75 static void async_sigterm_handler (gdb_client_data arg);
77 /* Instead of invoking (and waiting for) readline to read the command
78 line and pass it back for processing, we use readline's alternate
79 interface, via callback functions, so that the event loop can react
80 to other event sources while we wait for input. */
82 /* Important variables for the event loop. */
84 /* This is used to determine if GDB is using the readline library or
85 its own simplified form of readline. It is used by the asynchronous
86 form of the set editing command.
87 ezannoni: as of 1999-04-29 I expect that this
88 variable will not be used after gdb is changed to use the event
89 loop as default engine, and event-top.c is merged into top.c. */
90 bool set_editing_cmd_var;
92 /* This is used to display the notification of the completion of an
93 asynchronous execution command. */
94 bool exec_done_display_p = false;
96 /* Used by the stdin event handler to compensate for missed stdin events.
97 Setting this to a non-zero value inside an stdin callback makes the callback
98 run again. */
99 int call_stdin_event_handler_again_p;
101 /* When true GDB will produce a minimal backtrace when a fatal signal is
102 reached (within GDB code). */
103 static bool bt_on_fatal_signal = GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON;
105 /* Implement 'maintenance show backtrace-on-fatal-signal'. */
107 static void
108 show_bt_on_fatal_signal (struct ui_file *file, int from_tty,
109 struct cmd_list_element *cmd, const char *value)
111 gdb_printf (file, _("Backtrace on a fatal signal is %s.\n"), value);
114 /* Signal handling variables. */
115 /* Each of these is a pointer to a function that the event loop will
116 invoke if the corresponding signal has received. The real signal
117 handlers mark these functions as ready to be executed and the event
118 loop, in a later iteration, calls them. See the function
119 invoke_async_signal_handler. */
120 static struct async_signal_handler *sigint_token;
121 #ifdef SIGHUP
122 static struct async_signal_handler *sighup_token;
123 #endif
124 #ifdef SIGQUIT
125 static struct async_signal_handler *sigquit_token;
126 #endif
127 #ifdef SIGTSTP
128 static struct async_signal_handler *sigtstp_token;
129 #endif
130 static struct async_signal_handler *async_sigterm_token;
132 /* This hook is called by gdb_rl_callback_read_char_wrapper after each
133 character is processed. */
134 void (*after_char_processing_hook) (void);
137 /* Wrapper function for calling into the readline library. This takes
138 care of a couple things:
140 - The event loop expects the callback function to have a parameter,
141 while readline expects none.
143 - Propagation of GDB exceptions/errors thrown from INPUT_HANDLER
144 across readline requires special handling.
146 On the exceptions issue:
148 DWARF-based unwinding cannot cross code built without -fexceptions.
149 Any exception that tries to propagate through such code will fail
150 and the result is a call to std::terminate. While some ABIs, such
151 as x86-64, require all code to be built with exception tables,
152 others don't.
154 This is a problem when GDB calls some non-EH-aware C library code,
155 that calls into GDB again through a callback, and that GDB callback
156 code throws a C++ exception. Turns out this is exactly what
157 happens with GDB's readline callback.
159 In such cases, we must catch and save any C++ exception that might
160 be thrown from the GDB callback before returning to the
161 non-EH-aware code. When the non-EH-aware function itself returns
162 back to GDB, we then rethrow the original C++ exception.
164 In the readline case however, the right thing to do is to longjmp
165 out of the callback, rather than do a normal return -- there's no
166 way for the callback to return to readline an indication that an
167 error happened, so a normal return would have rl_callback_read_char
168 potentially continue processing further input, redisplay the
169 prompt, etc. Instead of raw setjmp/longjmp however, we use our
170 sjlj-based TRY/CATCH mechanism, which knows to handle multiple
171 levels of active setjmp/longjmp frames, needed in order to handle
172 the readline callback recursing, as happens with e.g., secondary
173 prompts / queries, through gdb_readline_wrapper. This must be
174 noexcept in order to avoid problems with mixing sjlj and
175 (sjlj-based) C++ exceptions. */
177 static struct gdb_exception
178 gdb_rl_callback_read_char_wrapper_noexcept () noexcept
180 struct gdb_exception gdb_expt;
182 /* C++ exceptions can't normally be thrown across readline (unless
183 it is built with -fexceptions, but it won't by default on many
184 ABIs). So we instead wrap the readline call with a sjlj-based
185 TRY/CATCH, and rethrow the GDB exception once back in GDB. */
186 TRY_SJLJ
188 rl_callback_read_char ();
189 #if RL_VERSION_MAJOR >= 8
190 /* It can happen that readline (while in rl_callback_read_char)
191 received a signal, but didn't handle it yet. Make sure it's handled
192 now. If we don't do that we run into two related problems:
193 - we have to wait for another event triggering
194 rl_callback_read_char before the signal is handled
195 - there's no guarantee that the signal will be processed before the
196 event. */
197 while (rl_pending_signal () != 0)
198 /* Do this in a while loop, in case rl_check_signals also leaves a
199 pending signal. I'm not sure if that's possible, but it seems
200 better to handle the scenario than to assert. */
201 rl_check_signals ();
202 #else
203 /* Unfortunately, rl_check_signals is not available. */
204 #endif
205 if (after_char_processing_hook)
206 (*after_char_processing_hook) ();
208 CATCH_SJLJ (ex, RETURN_MASK_ALL)
210 gdb_expt = std::move (ex);
212 END_CATCH_SJLJ
214 return gdb_expt;
217 static void
218 gdb_rl_callback_read_char_wrapper (gdb_client_data client_data)
220 struct gdb_exception gdb_expt
221 = gdb_rl_callback_read_char_wrapper_noexcept ();
223 /* Rethrow using the normal EH mechanism. */
224 if (gdb_expt.reason < 0)
225 throw_exception (std::move (gdb_expt));
228 /* GDB's readline callback handler. Calls the current INPUT_HANDLER,
229 and propagates GDB exceptions/errors thrown from INPUT_HANDLER back
230 across readline. See gdb_rl_callback_read_char_wrapper. This must
231 be noexcept in order to avoid problems with mixing sjlj and
232 (sjlj-based) C++ exceptions. */
234 static void
235 gdb_rl_callback_handler (char *rl) noexcept
237 /* This is static to avoid undefined behavior when calling longjmp
238 -- gdb_exception has a destructor with side effects. */
239 static struct gdb_exception gdb_rl_expt;
240 struct ui *ui = current_ui;
244 /* Ensure the exception is reset on each call. */
245 gdb_rl_expt = {};
246 ui->input_handler (gdb::unique_xmalloc_ptr<char> (rl));
248 catch (gdb_exception &ex)
250 gdb_rl_expt = std::move (ex);
253 /* If we caught a GDB exception, longjmp out of the readline
254 callback. There's no other way for the callback to signal to
255 readline that an error happened. A normal return would have
256 readline potentially continue processing further input, redisplay
257 the prompt, etc. (This is what GDB historically did when it was
258 a C program.) Note that since we're long jumping, local variable
259 dtors are NOT run automatically. */
260 if (gdb_rl_expt.reason < 0)
261 throw_exception_sjlj (gdb_rl_expt);
264 /* Change the function to be invoked every time there is a character
265 ready on stdin. This is used when the user sets the editing off,
266 therefore bypassing readline, and letting gdb handle the input
267 itself, via gdb_readline_no_editing_callback. Also it is used in
268 the opposite case in which the user sets editing on again, by
269 restoring readline handling of the input.
271 NOTE: this operates on input_fd, not instream. If we are reading
272 commands from a file, instream will point to the file. However, we
273 always read commands from a file with editing off. This means that
274 the 'set editing on/off' will have effect only on the interactive
275 session. */
277 void
278 change_line_handler (int editing)
280 struct ui *ui = current_ui;
282 /* We can only have one instance of readline, so we only allow
283 editing on the main UI. */
284 if (ui != main_ui)
285 return;
287 /* Don't try enabling editing if the interpreter doesn't support it
288 (e.g., MI). */
289 if (!interp_supports_command_editing (top_level_interpreter ())
290 || !interp_supports_command_editing (command_interp ()))
291 return;
293 if (editing)
295 gdb_assert (ui == main_ui);
297 /* Turn on editing by using readline. */
298 ui->call_readline = gdb_rl_callback_read_char_wrapper;
300 else
302 /* Turn off editing by using gdb_readline_no_editing_callback. */
303 if (ui->command_editing)
304 gdb_rl_callback_handler_remove ();
305 ui->call_readline = gdb_readline_no_editing_callback;
307 ui->command_editing = editing;
310 /* The functions below are wrappers for rl_callback_handler_remove and
311 rl_callback_handler_install that keep track of whether the callback
312 handler is installed in readline. This is necessary because after
313 handling a target event of a background execution command, we may
314 need to reinstall the callback handler if it was removed due to a
315 secondary prompt. See gdb_readline_wrapper_line. We don't
316 unconditionally install the handler for every target event because
317 that also clears the line buffer, thus installing it while the user
318 is typing would lose input. */
320 /* Whether we've registered a callback handler with readline. */
321 static bool callback_handler_installed;
323 /* See event-top.h, and above. */
325 void
326 gdb_rl_callback_handler_remove (void)
328 gdb_assert (current_ui == main_ui);
330 rl_callback_handler_remove ();
331 callback_handler_installed = false;
334 /* See event-top.h, and above. Note this wrapper doesn't have an
335 actual callback parameter because we always install
336 INPUT_HANDLER. */
338 void
339 gdb_rl_callback_handler_install (const char *prompt)
341 gdb_assert (current_ui == main_ui);
343 /* Calling rl_callback_handler_install resets readline's input
344 buffer. Calling this when we were already processing input
345 therefore loses input. */
346 gdb_assert (!callback_handler_installed);
348 rl_callback_handler_install (prompt, gdb_rl_callback_handler);
349 callback_handler_installed = true;
352 /* See event-top.h, and above. */
354 void
355 gdb_rl_callback_handler_reinstall (void)
357 gdb_assert (current_ui == main_ui);
359 if (!callback_handler_installed)
361 /* Passing NULL as prompt argument tells readline to not display
362 a prompt. */
363 gdb_rl_callback_handler_install (NULL);
367 /* Displays the prompt. If the argument NEW_PROMPT is NULL, the
368 prompt that is displayed is the current top level prompt.
369 Otherwise, it displays whatever NEW_PROMPT is as a local/secondary
370 prompt.
372 This is used after each gdb command has completed, and in the
373 following cases:
375 1. When the user enters a command line which is ended by '\'
376 indicating that the command will continue on the next line. In
377 that case the prompt that is displayed is the empty string.
379 2. When the user is entering 'commands' for a breakpoint, or
380 actions for a tracepoint. In this case the prompt will be '>'
382 3. On prompting for pagination. */
384 void
385 display_gdb_prompt (const char *new_prompt)
387 std::string actual_gdb_prompt;
389 annotate_display_prompt ();
391 /* Reset the nesting depth used when trace-commands is set. */
392 reset_command_nest_depth ();
394 /* Do not call the python hook on an explicit prompt change as
395 passed to this function, as this forms a secondary/local prompt,
396 IE, displayed but not set. */
397 if (! new_prompt)
399 struct ui *ui = current_ui;
401 if (ui->prompt_state == PROMPTED)
402 internal_error (_("double prompt"));
403 else if (ui->prompt_state == PROMPT_BLOCKED)
405 /* This is to trick readline into not trying to display the
406 prompt. Even though we display the prompt using this
407 function, readline still tries to do its own display if
408 we don't call rl_callback_handler_install and
409 rl_callback_handler_remove (which readline detects
410 because a global variable is not set). If readline did
411 that, it could mess up gdb signal handlers for SIGINT.
412 Readline assumes that between calls to rl_set_signals and
413 rl_clear_signals gdb doesn't do anything with the signal
414 handlers. Well, that's not the case, because when the
415 target executes we change the SIGINT signal handler. If
416 we allowed readline to display the prompt, the signal
417 handler change would happen exactly between the calls to
418 the above two functions. Calling
419 rl_callback_handler_remove(), does the job. */
421 if (current_ui->command_editing)
422 gdb_rl_callback_handler_remove ();
423 return;
425 else if (ui->prompt_state == PROMPT_NEEDED)
427 /* Display the top level prompt. */
428 actual_gdb_prompt = top_level_prompt ();
429 ui->prompt_state = PROMPTED;
432 else
433 actual_gdb_prompt = new_prompt;
435 if (current_ui->command_editing)
437 gdb_rl_callback_handler_remove ();
438 gdb_rl_callback_handler_install (actual_gdb_prompt.c_str ());
440 /* new_prompt at this point can be the top of the stack or the one
441 passed in. It can't be NULL. */
442 else
444 /* Don't use a _filtered function here. It causes the assumed
445 character position to be off, since the newline we read from
446 the user is not accounted for. */
447 printf_unfiltered ("%s", actual_gdb_prompt.c_str ());
448 gdb_flush (gdb_stdout);
452 /* Return the top level prompt, as specified by "set prompt", possibly
453 overridden by the python gdb.prompt_hook hook, and then composed
454 with the prompt prefix and suffix (annotations). */
456 static std::string
457 top_level_prompt (void)
459 /* Give observers a chance of changing the prompt. E.g., the python
460 `gdb.prompt_hook' is installed as an observer. */
461 gdb::observers::before_prompt.notify (get_prompt ().c_str ());
463 const std::string &prompt = get_prompt ();
465 if (annotation_level >= 2)
467 /* Prefix needs to have new line at end. */
468 const char prefix[] = "\n\032\032pre-prompt\n";
470 /* Suffix needs to have a new line at end and \032 \032 at
471 beginning. */
472 const char suffix[] = "\n\032\032prompt\n";
474 return std::string (prefix) + prompt.c_str () + suffix;
477 return prompt;
480 /* See top.h. */
482 struct ui *main_ui;
483 struct ui *current_ui;
484 struct ui *ui_list;
486 /* Get a reference to the current UI's line buffer. This is used to
487 construct a whole line of input from partial input. */
489 static std::string &
490 get_command_line_buffer (void)
492 return current_ui->line_buffer;
495 /* When there is an event ready on the stdin file descriptor, instead
496 of calling readline directly throught the callback function, or
497 instead of calling gdb_readline_no_editing_callback, give gdb a
498 chance to detect errors and do something. */
500 static void
501 stdin_event_handler (int error, gdb_client_data client_data)
503 struct ui *ui = (struct ui *) client_data;
505 if (error)
507 /* Switch to the main UI, so diagnostics always go there. */
508 current_ui = main_ui;
510 ui->unregister_file_handler ();
511 if (main_ui == ui)
513 /* If stdin died, we may as well kill gdb. */
514 gdb_printf (gdb_stderr, _("error detected on stdin\n"));
515 quit_command ((char *) 0, 0);
517 else
519 /* Simply delete the UI. */
520 delete ui;
523 else
525 /* Switch to the UI whose input descriptor woke up the event
526 loop. */
527 current_ui = ui;
529 /* This makes sure a ^C immediately followed by further input is
530 always processed in that order. E.g,. with input like
531 "^Cprint 1\n", the SIGINT handler runs, marks the async
532 signal handler, and then select/poll may return with stdin
533 ready, instead of -1/EINTR. The
534 gdb.base/double-prompt-target-event-error.exp test exercises
535 this. */
536 QUIT;
540 call_stdin_event_handler_again_p = 0;
541 ui->call_readline (client_data);
543 while (call_stdin_event_handler_again_p != 0);
547 /* See top.h. */
549 void
550 ui::register_file_handler ()
552 if (input_fd != -1)
553 add_file_handler (input_fd, stdin_event_handler, this,
554 string_printf ("ui-%d", num), true);
557 /* See top.h. */
559 void
560 ui::unregister_file_handler ()
562 if (input_fd != -1)
563 delete_file_handler (input_fd);
566 /* Re-enable stdin after the end of an execution command in
567 synchronous mode, or after an error from the target, and we aborted
568 the exec operation. */
570 void
571 async_enable_stdin (void)
573 struct ui *ui = current_ui;
575 if (ui->prompt_state == PROMPT_BLOCKED)
577 target_terminal::ours ();
578 ui->register_file_handler ();
579 ui->prompt_state = PROMPT_NEEDED;
583 /* Disable reads from stdin (the console) marking the command as
584 synchronous. */
586 void
587 async_disable_stdin (void)
589 struct ui *ui = current_ui;
591 ui->prompt_state = PROMPT_BLOCKED;
592 ui->unregister_file_handler ();
596 /* Handle a gdb command line. This function is called when
597 handle_line_of_input has concatenated one or more input lines into
598 a whole command. */
600 void
601 command_handler (const char *command)
603 struct ui *ui = current_ui;
604 const char *c;
606 if (ui->instream == ui->stdin_stream)
607 reinitialize_more_filter ();
609 scoped_command_stats stat_reporter (true);
611 /* Do not execute commented lines. */
612 for (c = command; *c == ' ' || *c == '\t'; c++)
614 if (c[0] != '#')
616 execute_command (command, ui->instream == ui->stdin_stream);
618 /* Do any commands attached to breakpoint we stopped at. */
619 bpstat_do_actions ();
623 /* Append RL, an input line returned by readline or one of its emulations, to
624 CMD_LINE_BUFFER. Return true if we have a whole command line ready to be
625 processed by the command interpreter or false if the command line isn't
626 complete yet (input line ends in a backslash). */
628 static bool
629 command_line_append_input_line (std::string &cmd_line_buffer, const char *rl)
631 size_t len = strlen (rl);
633 if (len > 0 && rl[len - 1] == '\\')
635 /* Don't copy the backslash and wait for more. */
636 cmd_line_buffer.append (rl, len - 1);
637 return false;
639 else
641 /* Copy whole line including terminating null, and we're
642 done. */
643 cmd_line_buffer.append (rl, len + 1);
644 return true;
648 /* Handle a line of input coming from readline.
650 If the read line ends with a continuation character (backslash), return
651 nullptr. Otherwise, return a pointer to the command line, indicating a whole
652 command line is ready to be executed.
654 The returned pointer may or may not point to CMD_LINE_BUFFER's internal
655 buffer.
657 Return EOF on end of file.
659 If REPEAT, handle command repetitions:
661 - If the input command line is NOT empty, the command returned is
662 saved using save_command_line () so that it can be repeated later.
664 - OTOH, if the input command line IS empty, return the saved
665 command instead of the empty input line.
668 const char *
669 handle_line_of_input (std::string &cmd_line_buffer,
670 const char *rl, int repeat,
671 const char *annotation_suffix)
673 struct ui *ui = current_ui;
674 int from_tty = ui->instream == ui->stdin_stream;
676 if (rl == NULL)
677 return (char *) EOF;
679 bool complete = command_line_append_input_line (cmd_line_buffer, rl);
680 if (!complete)
681 return NULL;
683 if (from_tty && annotation_level > 1)
684 printf_unfiltered (("\n\032\032post-%s\n"), annotation_suffix);
686 #define SERVER_COMMAND_PREFIX "server "
687 server_command = startswith (cmd_line_buffer.c_str (), SERVER_COMMAND_PREFIX);
688 if (server_command)
690 /* Note that we don't call `save_command_line'. Between this
691 and the check in dont_repeat, this insures that repeating
692 will still do the right thing. */
693 return cmd_line_buffer.c_str () + strlen (SERVER_COMMAND_PREFIX);
696 /* Do history expansion if that is wished. */
697 if (history_expansion_p && from_tty && current_ui->input_interactive_p ())
699 char *cmd_expansion;
700 int expanded;
702 /* Note: here, we pass a pointer to the std::string's internal buffer as
703 a `char *`. At the time of writing, readline's history_expand does
704 not modify the passed-in string. Ideally, readline should be modified
705 to make that parameter `const char *`. */
706 expanded = history_expand (&cmd_line_buffer[0], &cmd_expansion);
707 gdb::unique_xmalloc_ptr<char> history_value (cmd_expansion);
708 if (expanded)
710 /* Print the changes. */
711 printf_unfiltered ("%s\n", history_value.get ());
713 /* If there was an error, call this function again. */
714 if (expanded < 0)
715 return cmd_line_buffer.c_str ();
717 cmd_line_buffer = history_value.get ();
721 /* If we just got an empty line, and that is supposed to repeat the
722 previous command, return the previously saved command. */
723 const char *p1;
724 for (p1 = cmd_line_buffer.c_str (); *p1 == ' ' || *p1 == '\t'; p1++)
726 if (repeat && *p1 == '\0')
727 return get_saved_command_line ();
729 /* Add command to history if appropriate. Note: lines consisting
730 solely of comments are also added to the command history. This
731 is useful when you type a command, and then realize you don't
732 want to execute it quite yet. You can comment out the command
733 and then later fetch it from the value history and remove the
734 '#'. The kill ring is probably better, but some people are in
735 the habit of commenting things out. */
736 if (cmd_line_buffer[0] != '\0' && from_tty && current_ui->input_interactive_p ())
737 gdb_add_history (cmd_line_buffer.c_str ());
739 /* Save into global buffer if appropriate. */
740 if (repeat)
742 save_command_line (cmd_line_buffer.c_str ());
744 /* It is important that we return a pointer to the saved command line
745 here, for the `cmd_start == saved_command_line` check in
746 execute_command to work. */
747 return get_saved_command_line ();
750 return cmd_line_buffer.c_str ();
753 /* See event-top.h. */
755 void
756 gdb_rl_deprep_term_function (void)
758 #ifdef RL_STATE_EOF
759 gdb::optional<scoped_restore_tmpl<int>> restore_eof_found;
761 if (RL_ISSTATE (RL_STATE_EOF))
763 printf_unfiltered ("quit\n");
764 restore_eof_found.emplace (&rl_eof_found, 0);
767 #endif /* RL_STATE_EOF */
769 rl_deprep_terminal ();
772 /* Handle a complete line of input. This is called by the callback
773 mechanism within the readline library. Deal with incomplete
774 commands as well, by saving the partial input in a global
775 buffer.
777 NOTE: This is the asynchronous version of the command_line_input
778 function. */
780 void
781 command_line_handler (gdb::unique_xmalloc_ptr<char> &&rl)
783 std::string &line_buffer = get_command_line_buffer ();
784 struct ui *ui = current_ui;
786 const char *cmd = handle_line_of_input (line_buffer, rl.get (), 1, "prompt");
787 if (cmd == (char *) EOF)
789 /* stdin closed. The connection with the terminal is gone.
790 This happens at the end of a testsuite run, after Expect has
791 hung up but GDB is still alive. In such a case, we just quit
792 gdb killing the inferior program too. This also happens if the
793 user sends EOF, which is usually bound to ctrl+d. */
795 #ifndef RL_STATE_EOF
796 /* When readline is using bracketed paste mode, then, when eof is
797 received, readline will emit the control sequence to leave
798 bracketed paste mode.
800 This control sequence ends with \r, which means that the "quit" we
801 are about to print will overwrite the prompt on this line.
803 The solution to this problem is to actually print the "quit"
804 message from gdb_rl_deprep_term_function (see above), however, we
805 can only do that if we can know, in that function, when eof was
806 received.
808 Unfortunately, with older versions of readline, it is not possible
809 in the gdb_rl_deprep_term_function to know if eof was received or
810 not, and, as GDB can be built against the system readline, which
811 could be older than the readline in GDB's repository, then we
812 can't be sure that we can work around this prompt corruption in
813 the gdb_rl_deprep_term_function function.
815 If we get here, RL_STATE_EOF is not defined. This indicates that
816 we are using an older readline, and couldn't print the quit
817 message in gdb_rl_deprep_term_function. So, what we do here is
818 check to see if bracketed paste mode is on or not. If it's on
819 then we print a \n and then the quit, this means the user will
820 see:
822 (gdb)
823 quit
825 Rather than the usual:
827 (gdb) quit
829 Which we will get with a newer readline, but this really is the
830 best we can do with older versions of readline. */
831 const char *value = rl_variable_value ("enable-bracketed-paste");
832 if (value != nullptr && strcmp (value, "on") == 0
833 && ((rl_readline_version >> 8) & 0xff) > 0x07)
834 printf_unfiltered ("\n");
835 printf_unfiltered ("quit\n");
836 #endif
838 execute_command ("quit", 1);
840 else if (cmd == NULL)
842 /* We don't have a full line yet. Print an empty prompt. */
843 display_gdb_prompt ("");
845 else
847 ui->prompt_state = PROMPT_NEEDED;
849 /* Ensure the UI's line buffer is empty for the next command. */
850 SCOPE_EXIT { line_buffer.clear (); };
852 command_handler (cmd);
854 if (ui->prompt_state != PROMPTED)
855 display_gdb_prompt (0);
859 /* Does reading of input from terminal w/o the editing features
860 provided by the readline library. Calls the line input handler
861 once we have a whole input line. */
863 void
864 gdb_readline_no_editing_callback (gdb_client_data client_data)
866 int c;
867 char *result;
868 struct buffer line_buffer;
869 struct ui *ui = current_ui;
871 buffer_init (&line_buffer);
873 FILE *stream = ui->instream != nullptr ? ui->instream : ui->stdin_stream;
874 gdb_assert (stream != nullptr);
876 /* We still need the while loop here, even though it would seem
877 obvious to invoke gdb_readline_no_editing_callback at every
878 character entered. If not using the readline library, the
879 terminal is in cooked mode, which sends the characters all at
880 once. Poll will notice that the input fd has changed state only
881 after enter is pressed. At this point we still need to fetch all
882 the chars entered. */
884 while (1)
886 /* Read from stdin if we are executing a user defined command.
887 This is the right thing for prompt_for_continue, at least. */
888 c = fgetc (stream);
890 if (c == EOF)
892 if (line_buffer.used_size > 0)
894 /* The last line does not end with a newline. Return it, and
895 if we are called again fgetc will still return EOF and
896 we'll return NULL then. */
897 break;
899 xfree (buffer_finish (&line_buffer));
900 ui->input_handler (NULL);
901 return;
904 if (c == '\n')
906 if (line_buffer.used_size > 0
907 && line_buffer.buffer[line_buffer.used_size - 1] == '\r')
908 line_buffer.used_size--;
909 break;
912 buffer_grow_char (&line_buffer, c);
915 buffer_grow_char (&line_buffer, '\0');
916 result = buffer_finish (&line_buffer);
917 ui->input_handler (gdb::unique_xmalloc_ptr<char> (result));
921 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
922 otherwise, return false. */
924 static bool
925 unblock_signal (int sig)
927 #if HAVE_SIGPROCMASK
928 sigset_t sigset;
929 sigemptyset (&sigset);
930 sigaddset (&sigset, sig);
931 gdb_sigmask (SIG_UNBLOCK, &sigset, 0);
932 return true;
933 #endif
935 return false;
938 /* Called to handle fatal signals. SIG is the signal number. */
940 static void ATTRIBUTE_NORETURN
941 handle_fatal_signal (int sig)
943 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
944 const auto sig_write = [] (const char *msg) -> void
946 gdb_stderr->write_async_safe (msg, strlen (msg));
949 if (bt_on_fatal_signal)
951 sig_write ("\n\n");
952 sig_write (_("Fatal signal: "));
953 sig_write (strsignal (sig));
954 sig_write ("\n");
956 gdb_internal_backtrace ();
958 sig_write (_("A fatal error internal to GDB has been detected, "
959 "further\ndebugging is not possible. GDB will now "
960 "terminate.\n\n"));
961 sig_write (_("This is a bug, please report it."));
962 if (REPORT_BUGS_TO[0] != '\0')
964 sig_write (_(" For instructions, see:\n"));
965 sig_write (REPORT_BUGS_TO);
966 sig_write (".");
968 sig_write ("\n\n");
970 gdb_stderr->flush ();
972 #endif
974 /* If possible arrange for SIG to have its default behaviour (which
975 should be to terminate the current process), unblock SIG, and reraise
976 the signal. This ensures GDB terminates with the expected signal. */
977 if (signal (sig, SIG_DFL) != SIG_ERR
978 && unblock_signal (sig))
979 raise (sig);
981 /* The above failed, so try to use SIGABRT to terminate GDB. */
982 #ifdef SIGABRT
983 signal (SIGABRT, SIG_DFL);
984 #endif
985 abort (); /* ARI: abort */
988 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
989 always installs a global SIGSEGV handler, and then lets threads
990 indicate their interest in handling the signal by setting this
991 thread-local variable.
993 This is a static variable instead of extern because on various platforms
994 (notably Cygwin) extern thread_local variables cause link errors. So
995 instead, we have scoped_segv_handler_restore, which also makes it impossible
996 to accidentally forget to restore it to the original value. */
998 static thread_local void (*thread_local_segv_handler) (int);
1000 static void handle_sigsegv (int sig);
1002 /* Install the SIGSEGV handler. */
1003 static void
1004 install_handle_sigsegv ()
1006 #if defined (HAVE_SIGACTION)
1007 struct sigaction sa;
1008 sa.sa_handler = handle_sigsegv;
1009 sigemptyset (&sa.sa_mask);
1010 #ifdef HAVE_SIGALTSTACK
1011 sa.sa_flags = SA_ONSTACK;
1012 #else
1013 sa.sa_flags = 0;
1014 #endif
1015 sigaction (SIGSEGV, &sa, nullptr);
1016 #else
1017 signal (SIGSEGV, handle_sigsegv);
1018 #endif
1021 /* Handler for SIGSEGV. */
1023 static void
1024 handle_sigsegv (int sig)
1026 install_handle_sigsegv ();
1028 if (thread_local_segv_handler == nullptr)
1029 handle_fatal_signal (sig);
1030 thread_local_segv_handler (sig);
1035 /* The serial event associated with the QUIT flag. set_quit_flag sets
1036 this, and check_quit_flag clears it. Used by interruptible_select
1037 to be able to do interruptible I/O with no race with the SIGINT
1038 handler. */
1039 static struct serial_event *quit_serial_event;
1041 /* Initialization of signal handlers and tokens. There are a number of
1042 different strategies for handling different signals here.
1044 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
1045 handle_sig* for each of these signals. These functions are the actual
1046 signal handlers associated to the signals via calls to signal(). The
1047 only job for these functions is to enqueue the appropriate
1048 event/procedure with the event loop. The event loop will take care of
1049 invoking the queued procedures to perform the usual tasks associated
1050 with the reception of the signal.
1052 For SIGSEGV the handle_sig* function does all the work for handling this
1053 signal.
1055 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
1056 terminate immediately. */
1057 void
1058 gdb_init_signals (void)
1060 initialize_async_signal_handlers ();
1062 quit_serial_event = make_serial_event ();
1064 sigint_token =
1065 create_async_signal_handler (async_request_quit, NULL, "sigint");
1066 install_sigint_handler (handle_sigint);
1068 async_sigterm_token
1069 = create_async_signal_handler (async_sigterm_handler, NULL, "sigterm");
1070 signal (SIGTERM, handle_sigterm);
1072 #ifdef SIGQUIT
1073 sigquit_token =
1074 create_async_signal_handler (async_do_nothing, NULL, "sigquit");
1075 signal (SIGQUIT, handle_sigquit);
1076 #endif
1078 #ifdef SIGHUP
1079 if (signal (SIGHUP, handle_sighup) != SIG_IGN)
1080 sighup_token =
1081 create_async_signal_handler (async_disconnect, NULL, "sighup");
1082 else
1083 sighup_token =
1084 create_async_signal_handler (async_do_nothing, NULL, "sighup");
1085 #endif
1087 #ifdef SIGTSTP
1088 sigtstp_token =
1089 create_async_signal_handler (async_sigtstp_handler, NULL, "sigtstp");
1090 #endif
1092 #ifdef SIGFPE
1093 signal (SIGFPE, handle_fatal_signal);
1094 #endif
1096 #ifdef SIGBUS
1097 signal (SIGBUS, handle_fatal_signal);
1098 #endif
1100 #ifdef SIGABRT
1101 signal (SIGABRT, handle_fatal_signal);
1102 #endif
1104 install_handle_sigsegv ();
1107 /* See defs.h. */
1109 void
1110 quit_serial_event_set (void)
1112 serial_event_set (quit_serial_event);
1115 /* See defs.h. */
1117 void
1118 quit_serial_event_clear (void)
1120 serial_event_clear (quit_serial_event);
1123 /* Return the selectable file descriptor of the serial event
1124 associated with the quit flag. */
1126 static int
1127 quit_serial_event_fd (void)
1129 return serial_event_fd (quit_serial_event);
1132 /* See defs.h. */
1134 void
1135 default_quit_handler (void)
1137 if (check_quit_flag ())
1139 if (target_terminal::is_ours ())
1140 quit ();
1141 else
1142 target_pass_ctrlc ();
1146 /* See defs.h. */
1147 quit_handler_ftype *quit_handler = default_quit_handler;
1149 /* Handle a SIGINT. */
1151 void
1152 handle_sigint (int sig)
1154 signal (sig, handle_sigint);
1156 /* We could be running in a loop reading in symfiles or something so
1157 it may be quite a while before we get back to the event loop. So
1158 set quit_flag to 1 here. Then if QUIT is called before we get to
1159 the event loop, we will unwind as expected. */
1160 set_quit_flag ();
1162 /* In case nothing calls QUIT before the event loop is reached, the
1163 event loop handles it. */
1164 mark_async_signal_handler (sigint_token);
1167 /* See gdb_select.h. */
1170 interruptible_select (int n,
1171 fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
1172 struct timeval *timeout)
1174 fd_set my_readfds;
1175 int fd;
1176 int res;
1178 if (readfds == NULL)
1180 readfds = &my_readfds;
1181 FD_ZERO (&my_readfds);
1184 fd = quit_serial_event_fd ();
1185 FD_SET (fd, readfds);
1186 if (n <= fd)
1187 n = fd + 1;
1191 res = gdb_select (n, readfds, writefds, exceptfds, timeout);
1193 while (res == -1 && errno == EINTR);
1195 if (res == 1 && FD_ISSET (fd, readfds))
1197 errno = EINTR;
1198 return -1;
1200 return res;
1203 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1205 static void
1206 async_sigterm_handler (gdb_client_data arg)
1208 quit_force (NULL, 0);
1211 /* See defs.h. */
1212 volatile int sync_quit_force_run;
1214 /* Quit GDB if SIGTERM is received.
1215 GDB would quit anyway, but this way it will clean up properly. */
1216 void
1217 handle_sigterm (int sig)
1219 signal (sig, handle_sigterm);
1221 sync_quit_force_run = 1;
1222 set_quit_flag ();
1224 mark_async_signal_handler (async_sigterm_token);
1227 /* Do the quit. All the checks have been done by the caller. */
1228 void
1229 async_request_quit (gdb_client_data arg)
1231 /* If the quit_flag has gotten reset back to 0 by the time we get
1232 back here, that means that an exception was thrown to unwind the
1233 current command before we got back to the event loop. So there
1234 is no reason to call quit again here. */
1235 QUIT;
1238 #ifdef SIGQUIT
1239 /* Tell the event loop what to do if SIGQUIT is received.
1240 See event-signal.c. */
1241 static void
1242 handle_sigquit (int sig)
1244 mark_async_signal_handler (sigquit_token);
1245 signal (sig, handle_sigquit);
1247 #endif
1249 #if defined (SIGQUIT) || defined (SIGHUP)
1250 /* Called by the event loop in response to a SIGQUIT or an
1251 ignored SIGHUP. */
1252 static void
1253 async_do_nothing (gdb_client_data arg)
1255 /* Empty function body. */
1257 #endif
1259 #ifdef SIGHUP
1260 /* Tell the event loop what to do if SIGHUP is received.
1261 See event-signal.c. */
1262 static void
1263 handle_sighup (int sig)
1265 mark_async_signal_handler (sighup_token);
1266 signal (sig, handle_sighup);
1269 /* Called by the event loop to process a SIGHUP. */
1270 static void
1271 async_disconnect (gdb_client_data arg)
1276 quit_cover ();
1279 catch (const gdb_exception &exception)
1281 gdb_puts ("Could not kill the program being debugged",
1282 gdb_stderr);
1283 exception_print (gdb_stderr, exception);
1286 for (inferior *inf : all_inferiors ())
1290 inf->pop_all_targets ();
1292 catch (const gdb_exception &exception)
1297 signal (SIGHUP, SIG_DFL); /*FIXME: ??????????? */
1298 raise (SIGHUP);
1300 #endif
1302 #ifdef SIGTSTP
1303 void
1304 handle_sigtstp (int sig)
1306 mark_async_signal_handler (sigtstp_token);
1307 signal (sig, handle_sigtstp);
1310 static void
1311 async_sigtstp_handler (gdb_client_data arg)
1313 const std::string &prompt = get_prompt ();
1315 signal (SIGTSTP, SIG_DFL);
1316 unblock_signal (SIGTSTP);
1317 raise (SIGTSTP);
1318 signal (SIGTSTP, handle_sigtstp);
1319 printf_unfiltered ("%s", prompt.c_str ());
1320 gdb_flush (gdb_stdout);
1322 /* Forget about any previous command -- null line now will do
1323 nothing. */
1324 dont_repeat ();
1326 #endif /* SIGTSTP */
1330 /* Set things up for readline to be invoked via the alternate
1331 interface, i.e. via a callback function
1332 (gdb_rl_callback_read_char), and hook up instream to the event
1333 loop. */
1335 void
1336 gdb_setup_readline (int editing)
1338 struct ui *ui = current_ui;
1340 /* If the input stream is connected to a terminal, turn on editing.
1341 However, that is only allowed on the main UI, as we can only have
1342 one instance of readline. Also, INSTREAM might be nullptr when
1343 executing a user-defined command. */
1344 if (ui->instream != nullptr && ISATTY (ui->instream)
1345 && editing && ui == main_ui)
1347 /* Tell gdb that we will be using the readline library. This
1348 could be overwritten by a command in .gdbinit like 'set
1349 editing on' or 'off'. */
1350 ui->command_editing = 1;
1352 /* When a character is detected on instream by select or poll,
1353 readline will be invoked via this callback function. */
1354 ui->call_readline = gdb_rl_callback_read_char_wrapper;
1356 /* Tell readline to use the same input stream that gdb uses. */
1357 rl_instream = ui->instream;
1359 else
1361 ui->command_editing = 0;
1362 ui->call_readline = gdb_readline_no_editing_callback;
1365 /* Now create the event source for this UI's input file descriptor.
1366 Another source is going to be the target program (inferior), but
1367 that must be registered only when it actually exists (I.e. after
1368 we say 'run' or after we connect to a remote target. */
1369 ui->register_file_handler ();
1372 /* Disable command input through the standard CLI channels. Used in
1373 the suspend proc for interpreters that use the standard gdb readline
1374 interface, like the cli & the mi. */
1376 void
1377 gdb_disable_readline (void)
1379 struct ui *ui = current_ui;
1381 if (ui->command_editing)
1382 gdb_rl_callback_handler_remove ();
1383 ui->unregister_file_handler ();
1386 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler)
1388 m_old_handler = thread_local_segv_handler;
1389 thread_local_segv_handler = new_handler;
1392 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1394 thread_local_segv_handler = m_old_handler;
1397 static const char debug_event_loop_off[] = "off";
1398 static const char debug_event_loop_all_except_ui[] = "all-except-ui";
1399 static const char debug_event_loop_all[] = "all";
1401 static const char *debug_event_loop_enum[] = {
1402 debug_event_loop_off,
1403 debug_event_loop_all_except_ui,
1404 debug_event_loop_all,
1405 nullptr
1408 static const char *debug_event_loop_value = debug_event_loop_off;
1410 static void
1411 set_debug_event_loop_command (const char *args, int from_tty,
1412 cmd_list_element *c)
1414 if (debug_event_loop_value == debug_event_loop_off)
1415 debug_event_loop = debug_event_loop_kind::OFF;
1416 else if (debug_event_loop_value == debug_event_loop_all_except_ui)
1417 debug_event_loop = debug_event_loop_kind::ALL_EXCEPT_UI;
1418 else if (debug_event_loop_value == debug_event_loop_all)
1419 debug_event_loop = debug_event_loop_kind::ALL;
1420 else
1421 gdb_assert_not_reached ("Invalid debug event look kind value.");
1424 static void
1425 show_debug_event_loop_command (struct ui_file *file, int from_tty,
1426 struct cmd_list_element *cmd, const char *value)
1428 gdb_printf (file, _("Event loop debugging is %s.\n"), value);
1431 void _initialize_event_top ();
1432 void
1433 _initialize_event_top ()
1435 add_setshow_enum_cmd ("event-loop", class_maintenance,
1436 debug_event_loop_enum,
1437 &debug_event_loop_value,
1438 _("Set event-loop debugging."),
1439 _("Show event-loop debugging."),
1440 _("\
1441 Control whether to show event loop-related debug messages."),
1442 set_debug_event_loop_command,
1443 show_debug_event_loop_command,
1444 &setdebuglist, &showdebuglist);
1446 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance,
1447 &bt_on_fatal_signal, _("\
1448 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1449 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1450 Use \"on\" to enable, \"off\" to disable.\n\
1451 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1452 signal from within GDB itself. This is a mechanism to help diagnose\n\
1453 crashes within GDB, not a mechanism for debugging inferiors."),
1454 gdb_internal_backtrace_set_cmd,
1455 show_bt_on_fatal_signal,
1456 &maintenance_set_cmdlist,
1457 &maintenance_show_cmdlist);