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