Updated Bulgarian translation for the binutils/ directory
[binutils-gdb.git] / gdb / event-top.c
blobcdc7874b7fad8435d10eb553e74ef410d8642979
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 "exceptions.h"
23 #include "gdbsupport/job-control.h"
24 #include "run-on-main-thread.h"
25 #include "top.h"
26 #include "ui.h"
27 #include "inferior.h"
28 #include "infrun.h"
29 #include "target.h"
30 #include "terminal.h"
31 #include "gdbsupport/event-loop.h"
32 #include "event-top.h"
33 #include "interps.h"
34 #include <signal.h>
35 #include "cli/cli-script.h"
36 #include "main.h"
37 #include "gdbthread.h"
38 #include "observable.h"
39 #include "cli/cli-cmds.h"
40 #include "annotate.h"
41 #include "maint.h"
42 #include "ser-event.h"
43 #include "gdbsupport/gdb_select.h"
44 #include "gdbsupport/gdb-sigmask.h"
45 #include "async-event.h"
46 #include "bt-utils.h"
47 #include "pager.h"
49 /* readline include files. */
50 #include "readline/readline.h"
51 #include "readline/history.h"
53 #ifdef TUI
54 #include "tui/tui.h"
55 #endif
57 /* readline defines this. */
58 #undef savestring
60 static std::string top_level_prompt ();
62 /* Signal handlers. */
63 #ifdef SIGQUIT
64 static void handle_sigquit (int sig);
65 #endif
66 #ifdef SIGHUP
67 static void handle_sighup (int sig);
68 #endif
70 /* Functions to be invoked by the event loop in response to
71 signals. */
72 #if defined (SIGQUIT) || defined (SIGHUP)
73 static void async_do_nothing (gdb_client_data);
74 #endif
75 #ifdef SIGHUP
76 static void async_disconnect (gdb_client_data);
77 #endif
78 #ifdef SIGTSTP
79 static void async_sigtstp_handler (gdb_client_data);
80 #endif
81 static void async_sigterm_handler (gdb_client_data arg);
83 /* Instead of invoking (and waiting for) readline to read the command
84 line and pass it back for processing, we use readline's alternate
85 interface, via callback functions, so that the event loop can react
86 to other event sources while we wait for input. */
88 /* Important variables for the event loop. */
90 /* This is used to determine if GDB is using the readline library or
91 its own simplified form of readline. It is used by the asynchronous
92 form of the set editing command.
93 ezannoni: as of 1999-04-29 I expect that this
94 variable will not be used after gdb is changed to use the event
95 loop as default engine, and event-top.c is merged into top.c. */
96 bool set_editing_cmd_var;
98 /* This is used to display the notification of the completion of an
99 asynchronous execution command. */
100 bool exec_done_display_p = false;
102 /* Used by the stdin event handler to compensate for missed stdin events.
103 Setting this to a non-zero value inside an stdin callback makes the callback
104 run again. */
105 int call_stdin_event_handler_again_p;
107 /* When true GDB will produce a minimal backtrace when a fatal signal is
108 reached (within GDB code). */
109 static bool bt_on_fatal_signal = GDB_PRINT_INTERNAL_BACKTRACE_INIT_ON;
111 /* Implement 'maintenance show backtrace-on-fatal-signal'. */
113 static void
114 show_bt_on_fatal_signal (struct ui_file *file, int from_tty,
115 struct cmd_list_element *cmd, const char *value)
117 gdb_printf (file, _("Backtrace on a fatal signal is %s.\n"), value);
120 /* Signal handling variables. */
121 /* Each of these is a pointer to a function that the event loop will
122 invoke if the corresponding signal has received. The real signal
123 handlers mark these functions as ready to be executed and the event
124 loop, in a later iteration, calls them. See the function
125 invoke_async_signal_handler. */
126 static struct async_signal_handler *sigint_token;
127 #ifdef SIGHUP
128 static struct async_signal_handler *sighup_token;
129 #endif
130 #ifdef SIGQUIT
131 static struct async_signal_handler *sigquit_token;
132 #endif
133 #ifdef SIGTSTP
134 static struct async_signal_handler *sigtstp_token;
135 #endif
136 static struct async_signal_handler *async_sigterm_token;
138 /* This hook is called by gdb_rl_callback_read_char_wrapper after each
139 character is processed. */
140 void (*after_char_processing_hook) (void);
142 #if RL_VERSION_MAJOR == 7
143 extern "C" void _rl_signal_handler (int);
144 #endif
146 /* Wrapper function for calling into the readline library. This takes
147 care of a couple things:
149 - The event loop expects the callback function to have a parameter,
150 while readline expects none.
152 - Propagation of GDB exceptions/errors thrown from INPUT_HANDLER
153 across readline requires special handling.
155 On the exceptions issue:
157 DWARF-based unwinding cannot cross code built without -fexceptions.
158 Any exception that tries to propagate through such code will fail
159 and the result is a call to std::terminate. While some ABIs, such
160 as x86-64, require all code to be built with exception tables,
161 others don't.
163 This is a problem when GDB calls some non-EH-aware C library code,
164 that calls into GDB again through a callback, and that GDB callback
165 code throws a C++ exception. Turns out this is exactly what
166 happens with GDB's readline callback.
168 In such cases, we must catch and save any C++ exception that might
169 be thrown from the GDB callback before returning to the
170 non-EH-aware code. When the non-EH-aware function itself returns
171 back to GDB, we then rethrow the original C++ exception.
173 In the readline case however, the right thing to do is to longjmp
174 out of the callback, rather than do a normal return -- there's no
175 way for the callback to return to readline an indication that an
176 error happened, so a normal return would have rl_callback_read_char
177 potentially continue processing further input, redisplay the
178 prompt, etc. Instead of raw setjmp/longjmp however, we use our
179 sjlj-based TRY/CATCH mechanism, which knows to handle multiple
180 levels of active setjmp/longjmp frames, needed in order to handle
181 the readline callback recursing, as happens with e.g., secondary
182 prompts / queries, through gdb_readline_wrapper. This must be
183 noexcept in order to avoid problems with mixing sjlj and
184 (sjlj-based) C++ exceptions. */
186 static struct gdb_exception
187 gdb_rl_callback_read_char_wrapper_noexcept () noexcept
189 struct gdb_exception gdb_expt;
191 /* C++ exceptions can't normally be thrown across readline (unless
192 it is built with -fexceptions, but it won't by default on many
193 ABIs). So we instead wrap the readline call with a sjlj-based
194 TRY/CATCH, and rethrow the GDB exception once back in GDB. */
195 TRY_SJLJ
197 rl_callback_read_char ();
198 #if RL_VERSION_MAJOR >= 8
199 /* It can happen that readline (while in rl_callback_read_char)
200 received a signal, but didn't handle it yet. Make sure it's handled
201 now. If we don't do that we run into two related problems:
202 - we have to wait for another event triggering
203 rl_callback_read_char before the signal is handled
204 - there's no guarantee that the signal will be processed before the
205 event. */
206 while (rl_pending_signal () != 0)
207 /* Do this in a while loop, in case rl_check_signals also leaves a
208 pending signal. I'm not sure if that's possible, but it seems
209 better to handle the scenario than to assert. */
210 rl_check_signals ();
211 #elif RL_VERSION_MAJOR == 7
212 /* Unfortunately, rl_check_signals is not available. Use private
213 function _rl_signal_handler instead. */
215 while (rl_pending_signal () != 0)
216 _rl_signal_handler (rl_pending_signal ());
217 #else
218 #error "Readline major version >= 7 expected"
219 #endif
220 if (after_char_processing_hook)
221 (*after_char_processing_hook) ();
223 CATCH_SJLJ (ex, RETURN_MASK_ALL)
225 gdb_expt = std::move (ex);
227 END_CATCH_SJLJ
229 return gdb_expt;
232 static void
233 gdb_rl_callback_read_char_wrapper (gdb_client_data client_data)
235 struct gdb_exception gdb_expt
236 = gdb_rl_callback_read_char_wrapper_noexcept ();
238 /* Rethrow using the normal EH mechanism. */
239 if (gdb_expt.reason < 0)
240 throw_exception (std::move (gdb_expt));
243 /* GDB's readline callback handler. Calls the current INPUT_HANDLER,
244 and propagates GDB exceptions/errors thrown from INPUT_HANDLER back
245 across readline. See gdb_rl_callback_read_char_wrapper. This must
246 be noexcept in order to avoid problems with mixing sjlj and
247 (sjlj-based) C++ exceptions. */
249 static void
250 gdb_rl_callback_handler (char *rl) noexcept
252 /* This is static to avoid undefined behavior when calling longjmp
253 -- gdb_exception has a destructor with side effects. */
254 static struct gdb_exception gdb_rl_expt;
255 struct ui *ui = current_ui;
257 /* In bracketed paste mode, pasting a complete line can result in a
258 literal newline appearing at the end of LINE. However, we never
259 want this in gdb. */
260 if (rl != nullptr)
262 size_t len = strlen (rl);
263 while (len > 0 && (rl[len - 1] == '\r' || rl[len - 1] == '\n'))
264 --len;
265 rl[len] = '\0';
270 /* Ensure the exception is reset on each call. */
271 gdb_rl_expt = {};
272 ui->input_handler (gdb::unique_xmalloc_ptr<char> (rl));
274 catch (gdb_exception &ex)
276 gdb_rl_expt = std::move (ex);
279 /* If we caught a GDB exception, longjmp out of the readline
280 callback. There's no other way for the callback to signal to
281 readline that an error happened. A normal return would have
282 readline potentially continue processing further input, redisplay
283 the prompt, etc. (This is what GDB historically did when it was
284 a C program.) Note that since we're long jumping, local variable
285 dtors are NOT run automatically. */
286 if (gdb_rl_expt.reason < 0)
287 throw_exception_sjlj (gdb_rl_expt);
290 /* Change the function to be invoked every time there is a character
291 ready on stdin. This is used when the user sets the editing off,
292 therefore bypassing readline, and letting gdb handle the input
293 itself, via gdb_readline_no_editing_callback. Also it is used in
294 the opposite case in which the user sets editing on again, by
295 restoring readline handling of the input.
297 NOTE: this operates on input_fd, not instream. If we are reading
298 commands from a file, instream will point to the file. However, we
299 always read commands from a file with editing off. This means that
300 the 'set editing on/off' will have effect only on the interactive
301 session. */
303 void
304 change_line_handler (int editing)
306 struct ui *ui = current_ui;
308 /* We can only have one instance of readline, so we only allow
309 editing on the main UI. */
310 if (ui != main_ui)
311 return;
313 /* Don't try enabling editing if the interpreter doesn't support it
314 (e.g., MI). */
315 if (!top_level_interpreter ()->supports_command_editing ()
316 || !command_interp ()->supports_command_editing ())
317 return;
319 if (editing)
321 gdb_assert (ui == main_ui);
323 /* Turn on editing by using readline. */
324 ui->call_readline = gdb_rl_callback_read_char_wrapper;
326 else
328 /* Turn off editing by using gdb_readline_no_editing_callback. */
329 if (ui->command_editing)
330 gdb_rl_callback_handler_remove ();
331 ui->call_readline = gdb_readline_no_editing_callback;
333 ui->command_editing = editing;
336 /* The functions below are wrappers for rl_callback_handler_remove and
337 rl_callback_handler_install that keep track of whether the callback
338 handler is installed in readline. This is necessary because after
339 handling a target event of a background execution command, we may
340 need to reinstall the callback handler if it was removed due to a
341 secondary prompt. See gdb_readline_wrapper_line. We don't
342 unconditionally install the handler for every target event because
343 that also clears the line buffer, thus installing it while the user
344 is typing would lose input. */
346 /* Whether we've registered a callback handler with readline. */
347 static bool callback_handler_installed;
349 /* See event-top.h, and above. */
351 void
352 gdb_rl_callback_handler_remove (void)
354 gdb_assert (current_ui == main_ui);
356 rl_callback_handler_remove ();
357 callback_handler_installed = false;
360 /* See event-top.h, and above. Note this wrapper doesn't have an
361 actual callback parameter because we always install
362 INPUT_HANDLER. */
364 void
365 gdb_rl_callback_handler_install (const char *prompt)
367 gdb_assert (current_ui == main_ui);
369 /* Calling rl_callback_handler_install resets readline's input
370 buffer. Calling this when we were already processing input
371 therefore loses input. */
372 gdb_assert (!callback_handler_installed);
374 rl_callback_handler_install (prompt, gdb_rl_callback_handler);
375 callback_handler_installed = true;
378 /* See event-top.h, and above. */
380 void
381 gdb_rl_callback_handler_reinstall (void)
383 gdb_assert (current_ui == main_ui);
385 if (!callback_handler_installed)
387 /* Passing NULL as prompt argument tells readline to not display
388 a prompt. */
389 gdb_rl_callback_handler_install (NULL);
393 /* Displays the prompt. If the argument NEW_PROMPT is NULL, the
394 prompt that is displayed is the current top level prompt.
395 Otherwise, it displays whatever NEW_PROMPT is as a local/secondary
396 prompt.
398 This is used after each gdb command has completed, and in the
399 following cases:
401 1. When the user enters a command line which is ended by '\'
402 indicating that the command will continue on the next line. In
403 that case the prompt that is displayed is the empty string.
405 2. When the user is entering 'commands' for a breakpoint, or
406 actions for a tracepoint. In this case the prompt will be '>'
408 3. On prompting for pagination. */
410 void
411 display_gdb_prompt (const char *new_prompt)
413 std::string actual_gdb_prompt;
415 annotate_display_prompt ();
417 /* Reset the nesting depth used when trace-commands is set. */
418 reset_command_nest_depth ();
420 /* Do not call the python hook on an explicit prompt change as
421 passed to this function, as this forms a secondary/local prompt,
422 IE, displayed but not set. */
423 if (! new_prompt)
425 struct ui *ui = current_ui;
427 if (ui->prompt_state == PROMPTED)
428 internal_error (_("double prompt"));
429 else if (ui->prompt_state == PROMPT_BLOCKED)
431 /* This is to trick readline into not trying to display the
432 prompt. Even though we display the prompt using this
433 function, readline still tries to do its own display if
434 we don't call rl_callback_handler_install and
435 rl_callback_handler_remove (which readline detects
436 because a global variable is not set). If readline did
437 that, it could mess up gdb signal handlers for SIGINT.
438 Readline assumes that between calls to rl_set_signals and
439 rl_clear_signals gdb doesn't do anything with the signal
440 handlers. Well, that's not the case, because when the
441 target executes we change the SIGINT signal handler. If
442 we allowed readline to display the prompt, the signal
443 handler change would happen exactly between the calls to
444 the above two functions. Calling
445 rl_callback_handler_remove(), does the job. */
447 if (current_ui->command_editing)
448 gdb_rl_callback_handler_remove ();
449 return;
451 else if (ui->prompt_state == PROMPT_NEEDED)
453 /* Display the top level prompt. */
454 actual_gdb_prompt = top_level_prompt ();
455 ui->prompt_state = PROMPTED;
458 else
459 actual_gdb_prompt = new_prompt;
461 if (current_ui->command_editing)
463 gdb_rl_callback_handler_remove ();
464 gdb_rl_callback_handler_install (actual_gdb_prompt.c_str ());
466 /* new_prompt at this point can be the top of the stack or the one
467 passed in. It can't be NULL. */
468 else
470 /* Don't use a _filtered function here. It causes the assumed
471 character position to be off, since the newline we read from
472 the user is not accounted for. */
473 printf_unfiltered ("%s", actual_gdb_prompt.c_str ());
474 gdb_flush (gdb_stdout);
478 /* Notify the 'before_prompt' observer, and run any additional actions
479 that must be done before we display the prompt. */
480 static void
481 notify_before_prompt (const char *prompt)
483 /* Give observers a chance of changing the prompt. E.g., the python
484 `gdb.prompt_hook' is installed as an observer. */
485 gdb::observers::before_prompt.notify (prompt);
487 /* As we are about to display the prompt, and so GDB might be sitting
488 idle for some time, close all the cached BFDs. This ensures that
489 when we next start running a user command all BFDs will be reopened
490 as needed, and as a result, we will see any on-disk changes. */
491 bfd_cache_close_all ();
494 /* Return the top level prompt, as specified by "set prompt", possibly
495 overridden by the python gdb.prompt_hook hook, and then composed
496 with the prompt prefix and suffix (annotations). */
498 static std::string
499 top_level_prompt (void)
501 notify_before_prompt (get_prompt ().c_str ());
503 const std::string &prompt = get_prompt ();
505 if (annotation_level >= 2)
507 /* Prefix needs to have new line at end. */
508 const char prefix[] = "\n\032\032pre-prompt\n";
510 /* Suffix needs to have a new line at end and \032 \032 at
511 beginning. */
512 const char suffix[] = "\n\032\032prompt\n";
514 return std::string (prefix) + prompt.c_str () + suffix;
517 return prompt;
520 /* Get a reference to the current UI's line buffer. This is used to
521 construct a whole line of input from partial input. */
523 static std::string &
524 get_command_line_buffer (void)
526 return current_ui->line_buffer;
529 /* Re-enable stdin after the end of an execution command in
530 synchronous mode, or after an error from the target, and we aborted
531 the exec operation. */
533 void
534 async_enable_stdin (void)
536 struct ui *ui = current_ui;
538 if (ui->prompt_state == PROMPT_BLOCKED
539 && !ui->keep_prompt_blocked)
541 target_terminal::ours ();
542 ui->register_file_handler ();
543 ui->prompt_state = PROMPT_NEEDED;
547 /* Disable reads from stdin (the console) marking the command as
548 synchronous. */
550 void
551 async_disable_stdin (void)
553 struct ui *ui = current_ui;
555 ui->prompt_state = PROMPT_BLOCKED;
556 ui->unregister_file_handler ();
560 /* Handle a gdb command line. This function is called when
561 handle_line_of_input has concatenated one or more input lines into
562 a whole command. */
564 void
565 command_handler (const char *command)
567 struct ui *ui = current_ui;
568 const char *c;
570 if (ui->instream == ui->stdin_stream)
571 reinitialize_more_filter ();
573 scoped_command_stats stat_reporter (true);
575 /* Do not execute commented lines. */
576 for (c = command; *c == ' ' || *c == '\t'; c++)
578 if (c[0] != '#')
580 execute_command (command, ui->instream == ui->stdin_stream);
582 /* Do any commands attached to breakpoint we stopped at. */
583 bpstat_do_actions ();
587 /* Append RL, an input line returned by readline or one of its emulations, to
588 CMD_LINE_BUFFER. Return true if we have a whole command line ready to be
589 processed by the command interpreter or false if the command line isn't
590 complete yet (input line ends in a backslash). */
592 static bool
593 command_line_append_input_line (std::string &cmd_line_buffer, const char *rl)
595 size_t len = strlen (rl);
597 if (len > 0 && rl[len - 1] == '\\')
599 /* Don't copy the backslash and wait for more. */
600 cmd_line_buffer.append (rl, len - 1);
601 return false;
603 else
605 /* Copy whole line including terminating null, and we're
606 done. */
607 cmd_line_buffer.append (rl, len + 1);
608 return true;
612 /* Handle a line of input coming from readline.
614 If the read line ends with a continuation character (backslash), return
615 nullptr. Otherwise, return a pointer to the command line, indicating a whole
616 command line is ready to be executed.
618 The returned pointer may or may not point to CMD_LINE_BUFFER's internal
619 buffer.
621 Return EOF on end of file.
623 If REPEAT, handle command repetitions:
625 - If the input command line is NOT empty, the command returned is
626 saved using save_command_line () so that it can be repeated later.
628 - OTOH, if the input command line IS empty, return the saved
629 command instead of the empty input line.
632 const char *
633 handle_line_of_input (std::string &cmd_line_buffer,
634 const char *rl, int repeat,
635 const char *annotation_suffix)
637 struct ui *ui = current_ui;
638 int from_tty = ui->instream == ui->stdin_stream;
640 if (rl == NULL)
641 return (char *) EOF;
643 bool complete = command_line_append_input_line (cmd_line_buffer, rl);
644 if (!complete)
645 return NULL;
647 if (from_tty && annotation_level > 1)
648 printf_unfiltered (("\n\032\032post-%s\n"), annotation_suffix);
650 #define SERVER_COMMAND_PREFIX "server "
651 server_command = startswith (cmd_line_buffer.c_str (), SERVER_COMMAND_PREFIX);
652 if (server_command)
654 /* Note that we don't call `save_command_line'. Between this
655 and the check in dont_repeat, this insures that repeating
656 will still do the right thing. */
657 return cmd_line_buffer.c_str () + strlen (SERVER_COMMAND_PREFIX);
660 /* Do history expansion if that is wished. */
661 if (history_expansion_p && from_tty && current_ui->input_interactive_p ())
663 char *cmd_expansion;
664 int expanded;
666 /* Note: here, we pass a pointer to the std::string's internal buffer as
667 a `char *`. At the time of writing, readline's history_expand does
668 not modify the passed-in string. Ideally, readline should be modified
669 to make that parameter `const char *`. */
670 expanded = history_expand (&cmd_line_buffer[0], &cmd_expansion);
671 gdb::unique_xmalloc_ptr<char> history_value (cmd_expansion);
672 if (expanded)
674 /* Print the changes. */
675 printf_unfiltered ("%s\n", history_value.get ());
677 /* If there was an error, call this function again. */
678 if (expanded < 0)
679 return cmd_line_buffer.c_str ();
681 cmd_line_buffer = history_value.get ();
685 /* If we just got an empty line, and that is supposed to repeat the
686 previous command, return the previously saved command. */
687 const char *p1;
688 for (p1 = cmd_line_buffer.c_str (); *p1 == ' ' || *p1 == '\t'; p1++)
690 if (repeat && *p1 == '\0')
691 return get_saved_command_line ();
693 /* Add command to history if appropriate. Note: lines consisting
694 solely of comments are also added to the command history. This
695 is useful when you type a command, and then realize you don't
696 want to execute it quite yet. You can comment out the command
697 and then later fetch it from the value history and remove the
698 '#'. The kill ring is probably better, but some people are in
699 the habit of commenting things out. */
700 if (cmd_line_buffer[0] != '\0' && from_tty && current_ui->input_interactive_p ())
701 gdb_add_history (cmd_line_buffer.c_str ());
703 /* Save into global buffer if appropriate. */
704 if (repeat)
706 save_command_line (cmd_line_buffer.c_str ());
708 /* It is important that we return a pointer to the saved command line
709 here, for the `cmd_start == saved_command_line` check in
710 execute_command to work. */
711 return get_saved_command_line ();
714 return cmd_line_buffer.c_str ();
717 /* See event-top.h. */
719 void
720 gdb_rl_deprep_term_function (void)
722 #ifdef RL_STATE_EOF
723 std::optional<scoped_restore_tmpl<int>> restore_eof_found;
725 if (RL_ISSTATE (RL_STATE_EOF))
727 printf_unfiltered ("quit\n");
728 restore_eof_found.emplace (&rl_eof_found, 0);
731 #endif /* RL_STATE_EOF */
733 rl_deprep_terminal ();
736 /* Handle a complete line of input. This is called by the callback
737 mechanism within the readline library. Deal with incomplete
738 commands as well, by saving the partial input in a global
739 buffer.
741 NOTE: This is the asynchronous version of the command_line_input
742 function. */
744 void
745 command_line_handler (gdb::unique_xmalloc_ptr<char> &&rl)
747 std::string &line_buffer = get_command_line_buffer ();
748 struct ui *ui = current_ui;
750 const char *cmd = handle_line_of_input (line_buffer, rl.get (), 1, "prompt");
751 if (cmd == (char *) EOF)
753 /* stdin closed. The connection with the terminal is gone.
754 This happens at the end of a testsuite run, after Expect has
755 hung up but GDB is still alive. In such a case, we just quit
756 gdb killing the inferior program too. This also happens if the
757 user sends EOF, which is usually bound to ctrl+d. */
759 #ifndef RL_STATE_EOF
760 /* When readline is using bracketed paste mode, then, when eof is
761 received, readline will emit the control sequence to leave
762 bracketed paste mode.
764 This control sequence ends with \r, which means that the "quit" we
765 are about to print will overwrite the prompt on this line.
767 The solution to this problem is to actually print the "quit"
768 message from gdb_rl_deprep_term_function (see above), however, we
769 can only do that if we can know, in that function, when eof was
770 received.
772 Unfortunately, with older versions of readline, it is not possible
773 in the gdb_rl_deprep_term_function to know if eof was received or
774 not, and, as GDB can be built against the system readline, which
775 could be older than the readline in GDB's repository, then we
776 can't be sure that we can work around this prompt corruption in
777 the gdb_rl_deprep_term_function function.
779 If we get here, RL_STATE_EOF is not defined. This indicates that
780 we are using an older readline, and couldn't print the quit
781 message in gdb_rl_deprep_term_function. So, what we do here is
782 check to see if bracketed paste mode is on or not. If it's on
783 then we print a \n and then the quit, this means the user will
784 see:
786 (gdb)
787 quit
789 Rather than the usual:
791 (gdb) quit
793 Which we will get with a newer readline, but this really is the
794 best we can do with older versions of readline. */
795 const char *value = rl_variable_value ("enable-bracketed-paste");
796 if (value != nullptr && strcmp (value, "on") == 0
797 && ((rl_readline_version >> 8) & 0xff) > 0x07)
798 printf_unfiltered ("\n");
799 printf_unfiltered ("quit\n");
800 #endif
802 execute_command ("quit", 1);
804 else if (cmd == NULL)
806 /* We don't have a full line yet. Print an empty prompt. */
807 display_gdb_prompt ("");
809 else
811 ui->prompt_state = PROMPT_NEEDED;
813 /* Ensure the UI's line buffer is empty for the next command. */
814 SCOPE_EXIT { line_buffer.clear (); };
816 command_handler (cmd);
818 if (ui->prompt_state != PROMPTED)
819 display_gdb_prompt (0);
823 /* Does reading of input from terminal w/o the editing features
824 provided by the readline library. Calls the line input handler
825 once we have a whole input line. */
827 void
828 gdb_readline_no_editing_callback (gdb_client_data client_data)
830 int c;
831 std::string line_buffer;
832 struct ui *ui = current_ui;
834 FILE *stream = ui->instream != nullptr ? ui->instream : ui->stdin_stream;
835 gdb_assert (stream != nullptr);
837 /* We still need the while loop here, even though it would seem
838 obvious to invoke gdb_readline_no_editing_callback at every
839 character entered. If not using the readline library, the
840 terminal is in cooked mode, which sends the characters all at
841 once. Poll will notice that the input fd has changed state only
842 after enter is pressed. At this point we still need to fetch all
843 the chars entered. */
845 while (1)
847 /* Read from stdin if we are executing a user defined command.
848 This is the right thing for prompt_for_continue, at least. */
849 c = fgetc (stream);
851 if (c == EOF)
853 if (!line_buffer.empty ())
855 /* The last line does not end with a newline. Return it, and
856 if we are called again fgetc will still return EOF and
857 we'll return NULL then. */
858 break;
860 ui->input_handler (NULL);
861 return;
864 if (c == '\n')
866 if (!line_buffer.empty () && line_buffer.back () == '\r')
867 line_buffer.pop_back ();
868 break;
871 line_buffer += c;
874 ui->input_handler (make_unique_xstrdup (line_buffer.c_str ()));
878 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
879 otherwise, return false. */
881 static bool
882 unblock_signal (int sig)
884 #if HAVE_SIGPROCMASK
885 sigset_t sigset;
886 sigemptyset (&sigset);
887 sigaddset (&sigset, sig);
888 gdb_sigmask (SIG_UNBLOCK, &sigset, 0);
889 return true;
890 #endif
892 return false;
895 /* Called to handle fatal signals. SIG is the signal number. */
897 [[noreturn]] static void
898 handle_fatal_signal (int sig)
900 #ifdef TUI
901 tui_disable ();
902 #endif
904 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
905 const auto sig_write = [] (const char *msg) -> void
907 gdb_stderr->write_async_safe (msg, strlen (msg));
910 if (bt_on_fatal_signal)
912 sig_write ("\n\n");
913 sig_write (_("Fatal signal: "));
914 sig_write (strsignal (sig));
915 sig_write ("\n");
917 gdb_internal_backtrace ();
919 sig_write (_("A fatal error internal to GDB has been detected, "
920 "further\ndebugging is not possible. GDB will now "
921 "terminate.\n\n"));
922 sig_write (_("This is a bug, please report it."));
923 if (REPORT_BUGS_TO[0] != '\0')
925 sig_write (_(" For instructions, see:\n"));
926 sig_write (REPORT_BUGS_TO);
927 sig_write (".");
929 sig_write ("\n\n");
931 gdb_stderr->flush ();
933 #endif
935 /* If possible arrange for SIG to have its default behaviour (which
936 should be to terminate the current process), unblock SIG, and reraise
937 the signal. This ensures GDB terminates with the expected signal. */
938 if (signal (sig, SIG_DFL) != SIG_ERR
939 && unblock_signal (sig))
940 raise (sig);
942 /* The above failed, so try to use SIGABRT to terminate GDB. */
943 #ifdef SIGABRT
944 signal (SIGABRT, SIG_DFL);
945 #endif
946 abort (); /* ARI: abort */
949 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
950 always installs a global SIGSEGV handler, and then lets threads
951 indicate their interest in handling the signal by setting this
952 thread-local variable.
954 This is a static variable instead of extern because on various platforms
955 (notably Cygwin) extern thread_local variables cause link errors. So
956 instead, we have scoped_segv_handler_restore, which also makes it impossible
957 to accidentally forget to restore it to the original value. */
959 static thread_local void (*thread_local_segv_handler) (int);
961 static void handle_sigsegv (int sig);
963 /* Install the SIGSEGV handler. */
964 static void
965 install_handle_sigsegv ()
967 #if defined (HAVE_SIGACTION)
968 struct sigaction sa;
969 sa.sa_handler = handle_sigsegv;
970 sigemptyset (&sa.sa_mask);
971 #ifdef HAVE_SIGALTSTACK
972 sa.sa_flags = SA_ONSTACK;
973 #else
974 sa.sa_flags = 0;
975 #endif
976 sigaction (SIGSEGV, &sa, nullptr);
977 #else
978 signal (SIGSEGV, handle_sigsegv);
979 #endif
982 /* Handler for SIGSEGV. */
984 static void
985 handle_sigsegv (int sig)
987 install_handle_sigsegv ();
989 if (thread_local_segv_handler == nullptr)
990 handle_fatal_signal (sig);
991 thread_local_segv_handler (sig);
996 /* The serial event associated with the QUIT flag. set_quit_flag sets
997 this, and check_quit_flag clears it. Used by interruptible_select
998 to be able to do interruptible I/O with no race with the SIGINT
999 handler. */
1000 static struct serial_event *quit_serial_event;
1002 /* Initialization of signal handlers and tokens. There are a number of
1003 different strategies for handling different signals here.
1005 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
1006 handle_sig* for each of these signals. These functions are the actual
1007 signal handlers associated to the signals via calls to signal(). The
1008 only job for these functions is to enqueue the appropriate
1009 event/procedure with the event loop. The event loop will take care of
1010 invoking the queued procedures to perform the usual tasks associated
1011 with the reception of the signal.
1013 For SIGSEGV the handle_sig* function does all the work for handling this
1014 signal.
1016 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
1017 terminate immediately. */
1018 void
1019 gdb_init_signals (void)
1021 initialize_async_signal_handlers ();
1023 quit_serial_event = make_serial_event ();
1025 sigint_token =
1026 create_async_signal_handler (async_request_quit, NULL, "sigint");
1027 install_sigint_handler (handle_sigint);
1029 async_sigterm_token
1030 = create_async_signal_handler (async_sigterm_handler, NULL, "sigterm");
1031 signal (SIGTERM, handle_sigterm);
1033 #ifdef SIGQUIT
1034 sigquit_token =
1035 create_async_signal_handler (async_do_nothing, NULL, "sigquit");
1036 signal (SIGQUIT, handle_sigquit);
1037 #endif
1039 #ifdef SIGHUP
1040 if (signal (SIGHUP, handle_sighup) != SIG_IGN)
1041 sighup_token =
1042 create_async_signal_handler (async_disconnect, NULL, "sighup");
1043 else
1044 sighup_token =
1045 create_async_signal_handler (async_do_nothing, NULL, "sighup");
1046 #endif
1048 #ifdef SIGTSTP
1049 sigtstp_token =
1050 create_async_signal_handler (async_sigtstp_handler, NULL, "sigtstp");
1051 #endif
1053 #ifdef SIGFPE
1054 signal (SIGFPE, handle_fatal_signal);
1055 #endif
1057 #ifdef SIGBUS
1058 signal (SIGBUS, handle_fatal_signal);
1059 #endif
1061 #ifdef SIGABRT
1062 signal (SIGABRT, handle_fatal_signal);
1063 #endif
1065 install_handle_sigsegv ();
1068 /* See event-top.h. */
1070 void
1071 quit (void)
1073 if (sync_quit_force_run)
1075 sync_quit_force_run = false;
1076 throw_forced_quit ("SIGTERM");
1079 #ifdef __MSDOS__
1080 /* No steenking SIGINT will ever be coming our way when the
1081 program is resumed. Don't lie. */
1082 throw_quit ("Quit");
1083 #else
1084 if (job_control
1085 /* If there is no terminal switching for this target, then we can't
1086 possibly get screwed by the lack of job control. */
1087 || !target_supports_terminal_ours ())
1088 throw_quit ("Quit");
1089 else
1090 throw_quit ("Quit (expect signal SIGINT when the program is resumed)");
1091 #endif
1094 /* See event-top.h. */
1096 void
1097 maybe_quit ()
1099 if (!is_main_thread ())
1100 return;
1102 if (sync_quit_force_run)
1103 quit ();
1105 quit_handler ();
1108 /* See event-top.h. */
1110 void
1111 quit_serial_event_set ()
1113 serial_event_set (quit_serial_event);
1116 /* See event-top.h. */
1118 void
1119 quit_serial_event_clear (void)
1121 serial_event_clear (quit_serial_event);
1124 /* Return the selectable file descriptor of the serial event
1125 associated with the quit flag. */
1127 static int
1128 quit_serial_event_fd (void)
1130 return serial_event_fd (quit_serial_event);
1133 /* See defs.h. */
1135 void
1136 default_quit_handler (void)
1138 if (check_quit_flag ())
1140 if (target_terminal::is_ours ())
1141 quit ();
1142 else
1143 target_pass_ctrlc ();
1147 /* See defs.h. */
1148 quit_handler_ftype *quit_handler = default_quit_handler;
1150 /* Handle a SIGINT. */
1152 void
1153 handle_sigint (int sig)
1155 signal (sig, handle_sigint);
1157 /* We could be running in a loop reading in symfiles or something so
1158 it may be quite a while before we get back to the event loop. So
1159 set quit_flag to true here. Then if QUIT is called before we get to
1160 the event loop, we will unwind as expected. */
1161 set_quit_flag ();
1163 /* In case nothing calls QUIT before the event loop is reached, the
1164 event loop handles it. */
1165 mark_async_signal_handler (sigint_token);
1168 /* See gdb_select.h. */
1171 interruptible_select (int n,
1172 fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
1173 struct timeval *timeout)
1175 fd_set my_readfds;
1176 int fd;
1177 int res;
1179 if (readfds == NULL)
1181 readfds = &my_readfds;
1182 FD_ZERO (&my_readfds);
1185 fd = quit_serial_event_fd ();
1186 FD_SET (fd, readfds);
1187 if (n <= fd)
1188 n = fd + 1;
1192 res = gdb_select (n, readfds, writefds, exceptfds, timeout);
1194 while (res == -1 && errno == EINTR);
1196 if (res == 1 && FD_ISSET (fd, readfds))
1198 errno = EINTR;
1199 return -1;
1201 return res;
1204 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1206 static void
1207 async_sigterm_handler (gdb_client_data arg)
1209 quit_force (NULL, 0);
1212 /* See defs.h. */
1213 volatile bool sync_quit_force_run;
1215 /* See defs.h. */
1216 void
1217 set_force_quit_flag ()
1219 sync_quit_force_run = true;
1220 set_quit_flag ();
1223 /* Quit GDB if SIGTERM is received.
1224 GDB would quit anyway, but this way it will clean up properly. */
1225 void
1226 handle_sigterm (int sig)
1228 signal (sig, handle_sigterm);
1230 set_force_quit_flag ();
1232 mark_async_signal_handler (async_sigterm_token);
1235 /* Do the quit. All the checks have been done by the caller. */
1236 void
1237 async_request_quit (gdb_client_data arg)
1239 /* If the quit_flag has gotten reset back to false by the time we get
1240 back here, that means that an exception was thrown to unwind the
1241 current command before we got back to the event loop. So there
1242 is no reason to call quit again here. */
1243 QUIT;
1246 #ifdef SIGQUIT
1247 /* Tell the event loop what to do if SIGQUIT is received.
1248 See event-signal.c. */
1249 static void
1250 handle_sigquit (int sig)
1252 mark_async_signal_handler (sigquit_token);
1253 signal (sig, handle_sigquit);
1255 #endif
1257 #if defined (SIGQUIT) || defined (SIGHUP)
1258 /* Called by the event loop in response to a SIGQUIT or an
1259 ignored SIGHUP. */
1260 static void
1261 async_do_nothing (gdb_client_data arg)
1263 /* Empty function body. */
1265 #endif
1267 #ifdef SIGHUP
1268 /* Tell the event loop what to do if SIGHUP is received.
1269 See event-signal.c. */
1270 static void
1271 handle_sighup (int sig)
1273 mark_async_signal_handler (sighup_token);
1274 signal (sig, handle_sighup);
1277 /* Called by the event loop to process a SIGHUP. */
1278 static void
1279 async_disconnect (gdb_client_data arg)
1284 quit_cover ();
1287 catch (const gdb_exception &exception)
1289 gdb_puts ("Could not kill the program being debugged",
1290 gdb_stderr);
1291 exception_print (gdb_stderr, exception);
1292 if (exception.reason == RETURN_FORCED_QUIT)
1293 throw;
1296 for (inferior *inf : all_inferiors ())
1300 inf->pop_all_targets ();
1302 catch (const gdb_exception &exception)
1307 signal (SIGHUP, SIG_DFL); /*FIXME: ??????????? */
1308 raise (SIGHUP);
1310 #endif
1312 #ifdef SIGTSTP
1313 void
1314 handle_sigtstp (int sig)
1316 mark_async_signal_handler (sigtstp_token);
1317 signal (sig, handle_sigtstp);
1320 static void
1321 async_sigtstp_handler (gdb_client_data arg)
1323 const std::string &prompt = get_prompt ();
1325 signal (SIGTSTP, SIG_DFL);
1326 unblock_signal (SIGTSTP);
1327 raise (SIGTSTP);
1328 signal (SIGTSTP, handle_sigtstp);
1329 printf_unfiltered ("%s", prompt.c_str ());
1330 gdb_flush (gdb_stdout);
1332 /* Forget about any previous command -- null line now will do
1333 nothing. */
1334 dont_repeat ();
1336 #endif /* SIGTSTP */
1340 /* Set things up for readline to be invoked via the alternate
1341 interface, i.e. via a callback function
1342 (gdb_rl_callback_read_char), and hook up instream to the event
1343 loop. */
1345 void
1346 gdb_setup_readline (int editing)
1348 struct ui *ui = current_ui;
1350 /* If the input stream is connected to a terminal, turn on editing.
1351 However, that is only allowed on the main UI, as we can only have
1352 one instance of readline. Also, INSTREAM might be nullptr when
1353 executing a user-defined command. */
1354 if (ui->instream != nullptr && ISATTY (ui->instream)
1355 && editing && ui == main_ui)
1357 /* Tell gdb that we will be using the readline library. This
1358 could be overwritten by a command in .gdbinit like 'set
1359 editing on' or 'off'. */
1360 ui->command_editing = 1;
1362 /* When a character is detected on instream by select or poll,
1363 readline will be invoked via this callback function. */
1364 ui->call_readline = gdb_rl_callback_read_char_wrapper;
1366 /* Tell readline to use the same input stream that gdb uses. */
1367 rl_instream = ui->instream;
1369 else
1371 ui->command_editing = 0;
1372 ui->call_readline = gdb_readline_no_editing_callback;
1375 /* Now create the event source for this UI's input file descriptor.
1376 Another source is going to be the target program (inferior), but
1377 that must be registered only when it actually exists (I.e. after
1378 we say 'run' or after we connect to a remote target. */
1379 ui->register_file_handler ();
1382 /* Disable command input through the standard CLI channels. Used in
1383 the suspend proc for interpreters that use the standard gdb readline
1384 interface, like the cli & the mi. */
1386 void
1387 gdb_disable_readline (void)
1389 struct ui *ui = current_ui;
1391 if (ui->command_editing)
1392 gdb_rl_callback_handler_remove ();
1393 ui->unregister_file_handler ();
1396 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler)
1398 m_old_handler = thread_local_segv_handler;
1399 thread_local_segv_handler = new_handler;
1402 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1404 thread_local_segv_handler = m_old_handler;
1407 static const char debug_event_loop_off[] = "off";
1408 static const char debug_event_loop_all_except_ui[] = "all-except-ui";
1409 static const char debug_event_loop_all[] = "all";
1411 static const char *debug_event_loop_enum[] = {
1412 debug_event_loop_off,
1413 debug_event_loop_all_except_ui,
1414 debug_event_loop_all,
1415 nullptr
1418 static const char *debug_event_loop_value = debug_event_loop_off;
1420 static void
1421 set_debug_event_loop_command (const char *args, int from_tty,
1422 cmd_list_element *c)
1424 if (debug_event_loop_value == debug_event_loop_off)
1425 debug_event_loop = debug_event_loop_kind::OFF;
1426 else if (debug_event_loop_value == debug_event_loop_all_except_ui)
1427 debug_event_loop = debug_event_loop_kind::ALL_EXCEPT_UI;
1428 else if (debug_event_loop_value == debug_event_loop_all)
1429 debug_event_loop = debug_event_loop_kind::ALL;
1430 else
1431 gdb_assert_not_reached ("Invalid debug event look kind value.");
1434 static void
1435 show_debug_event_loop_command (struct ui_file *file, int from_tty,
1436 struct cmd_list_element *cmd, const char *value)
1438 gdb_printf (file, _("Event loop debugging is %s.\n"), value);
1441 void _initialize_event_top ();
1442 void
1443 _initialize_event_top ()
1445 add_setshow_enum_cmd ("event-loop", class_maintenance,
1446 debug_event_loop_enum,
1447 &debug_event_loop_value,
1448 _("Set event-loop debugging."),
1449 _("Show event-loop debugging."),
1450 _("\
1451 Control whether to show event loop-related debug messages."),
1452 set_debug_event_loop_command,
1453 show_debug_event_loop_command,
1454 &setdebuglist, &showdebuglist);
1456 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance,
1457 &bt_on_fatal_signal, _("\
1458 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1459 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1460 Use \"on\" to enable, \"off\" to disable.\n\
1461 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1462 signal from within GDB itself. This is a mechanism to help diagnose\n\
1463 crashes within GDB, not a mechanism for debugging inferiors."),
1464 gdb_internal_backtrace_set_cmd,
1465 show_bt_on_fatal_signal,
1466 &maintenance_set_cmdlist,
1467 &maintenance_show_cmdlist);