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