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