]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/event-top.c
Reduce explicit use of gdb_stdout
[thirdparty/binutils-gdb.git] / gdb / event-top.c
1 /* Top level stuff for GDB, the GNU debugger.
2
3 Copyright (C) 1999-2022 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 printf_unfiltered ("%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 /* Give observers a chance of changing the prompt. E.g., the python
443 `gdb.prompt_hook' is installed as an observer. */
444 gdb::observers::before_prompt.notify (get_prompt ().c_str ());
445
446 const std::string &prompt = get_prompt ();
447
448 if (annotation_level >= 2)
449 {
450 /* Prefix needs to have new line at end. */
451 const char prefix[] = "\n\032\032pre-prompt\n";
452
453 /* Suffix needs to have a new line at end and \032 \032 at
454 beginning. */
455 const char suffix[] = "\n\032\032prompt\n";
456
457 return std::string (prefix) + prompt.c_str () + suffix;
458 }
459
460 return prompt;
461 }
462
463 /* See top.h. */
464
465 struct ui *main_ui;
466 struct ui *current_ui;
467 struct ui *ui_list;
468
469 /* Get a pointer to the current UI's line buffer. This is used to
470 construct a whole line of input from partial input. */
471
472 static struct buffer *
473 get_command_line_buffer (void)
474 {
475 return &current_ui->line_buffer;
476 }
477
478 /* When there is an event ready on the stdin file descriptor, instead
479 of calling readline directly throught the callback function, or
480 instead of calling gdb_readline_no_editing_callback, give gdb a
481 chance to detect errors and do something. */
482
483 void
484 stdin_event_handler (int error, gdb_client_data client_data)
485 {
486 struct ui *ui = (struct ui *) client_data;
487
488 if (error)
489 {
490 /* Switch to the main UI, so diagnostics always go there. */
491 current_ui = main_ui;
492
493 delete_file_handler (ui->input_fd);
494 if (main_ui == ui)
495 {
496 /* If stdin died, we may as well kill gdb. */
497 fprintf_unfiltered (gdb_stderr, _("error detected on stdin\n"));
498 quit_command ((char *) 0, 0);
499 }
500 else
501 {
502 /* Simply delete the UI. */
503 delete ui;
504 }
505 }
506 else
507 {
508 /* Switch to the UI whose input descriptor woke up the event
509 loop. */
510 current_ui = ui;
511
512 /* This makes sure a ^C immediately followed by further input is
513 always processed in that order. E.g,. with input like
514 "^Cprint 1\n", the SIGINT handler runs, marks the async
515 signal handler, and then select/poll may return with stdin
516 ready, instead of -1/EINTR. The
517 gdb.base/double-prompt-target-event-error.exp test exercises
518 this. */
519 QUIT;
520
521 do
522 {
523 call_stdin_event_handler_again_p = 0;
524 ui->call_readline (client_data);
525 }
526 while (call_stdin_event_handler_again_p != 0);
527 }
528 }
529
530 /* See top.h. */
531
532 void
533 ui_register_input_event_handler (struct ui *ui)
534 {
535 add_file_handler (ui->input_fd, stdin_event_handler, ui,
536 string_printf ("ui-%d", ui->num), true);
537 }
538
539 /* See top.h. */
540
541 void
542 ui_unregister_input_event_handler (struct ui *ui)
543 {
544 delete_file_handler (ui->input_fd);
545 }
546
547 /* Re-enable stdin after the end of an execution command in
548 synchronous mode, or after an error from the target, and we aborted
549 the exec operation. */
550
551 void
552 async_enable_stdin (void)
553 {
554 struct ui *ui = current_ui;
555
556 if (ui->prompt_state == PROMPT_BLOCKED)
557 {
558 target_terminal::ours ();
559 ui_register_input_event_handler (ui);
560 ui->prompt_state = PROMPT_NEEDED;
561 }
562 }
563
564 /* Disable reads from stdin (the console) marking the command as
565 synchronous. */
566
567 void
568 async_disable_stdin (void)
569 {
570 struct ui *ui = current_ui;
571
572 ui->prompt_state = PROMPT_BLOCKED;
573 delete_file_handler (ui->input_fd);
574 }
575 \f
576
577 /* Handle a gdb command line. This function is called when
578 handle_line_of_input has concatenated one or more input lines into
579 a whole command. */
580
581 void
582 command_handler (const char *command)
583 {
584 struct ui *ui = current_ui;
585 const char *c;
586
587 if (ui->instream == ui->stdin_stream)
588 reinitialize_more_filter ();
589
590 scoped_command_stats stat_reporter (true);
591
592 /* Do not execute commented lines. */
593 for (c = command; *c == ' ' || *c == '\t'; c++)
594 ;
595 if (c[0] != '#')
596 {
597 execute_command (command, ui->instream == ui->stdin_stream);
598
599 /* Do any commands attached to breakpoint we stopped at. */
600 bpstat_do_actions ();
601 }
602 }
603
604 /* Append RL, an input line returned by readline or one of its
605 emulations, to CMD_LINE_BUFFER. Returns the command line if we
606 have a whole command line ready to be processed by the command
607 interpreter or NULL if the command line isn't complete yet (input
608 line ends in a backslash). */
609
610 static char *
611 command_line_append_input_line (struct buffer *cmd_line_buffer, const char *rl)
612 {
613 char *cmd;
614 size_t len;
615
616 len = strlen (rl);
617
618 if (len > 0 && rl[len - 1] == '\\')
619 {
620 /* Don't copy the backslash and wait for more. */
621 buffer_grow (cmd_line_buffer, rl, len - 1);
622 cmd = NULL;
623 }
624 else
625 {
626 /* Copy whole line including terminating null, and we're
627 done. */
628 buffer_grow (cmd_line_buffer, rl, len + 1);
629 cmd = cmd_line_buffer->buffer;
630 }
631
632 return cmd;
633 }
634
635 /* Handle a line of input coming from readline.
636
637 If the read line ends with a continuation character (backslash),
638 save the partial input in CMD_LINE_BUFFER (except the backslash),
639 and return NULL. Otherwise, save the partial input and return a
640 pointer to CMD_LINE_BUFFER's buffer (null terminated), indicating a
641 whole command line is ready to be executed.
642
643 Returns EOF on end of file.
644
645 If REPEAT, handle command repetitions:
646
647 - If the input command line is NOT empty, the command returned is
648 saved using save_command_line () so that it can be repeated later.
649
650 - OTOH, if the input command line IS empty, return the saved
651 command instead of the empty input line.
652 */
653
654 char *
655 handle_line_of_input (struct buffer *cmd_line_buffer,
656 const char *rl, int repeat,
657 const char *annotation_suffix)
658 {
659 struct ui *ui = current_ui;
660 int from_tty = ui->instream == ui->stdin_stream;
661 char *p1;
662 char *cmd;
663
664 if (rl == NULL)
665 return (char *) EOF;
666
667 cmd = command_line_append_input_line (cmd_line_buffer, rl);
668 if (cmd == NULL)
669 return NULL;
670
671 /* We have a complete command line now. Prepare for the next
672 command, but leave ownership of memory to the buffer . */
673 cmd_line_buffer->used_size = 0;
674
675 if (from_tty && annotation_level > 1)
676 {
677 printf_unfiltered (("\n\032\032post-"));
678 puts_unfiltered (annotation_suffix);
679 printf_unfiltered (("\n"));
680 }
681
682 #define SERVER_COMMAND_PREFIX "server "
683 server_command = startswith (cmd, SERVER_COMMAND_PREFIX);
684 if (server_command)
685 {
686 /* Note that we don't call `save_command_line'. Between this
687 and the check in dont_repeat, this insures that repeating
688 will still do the right thing. */
689 return cmd + strlen (SERVER_COMMAND_PREFIX);
690 }
691
692 /* Do history expansion if that is wished. */
693 if (history_expansion_p && from_tty && input_interactive_p (current_ui))
694 {
695 char *cmd_expansion;
696 int expanded;
697
698 expanded = history_expand (cmd, &cmd_expansion);
699 gdb::unique_xmalloc_ptr<char> history_value (cmd_expansion);
700 if (expanded)
701 {
702 size_t len;
703
704 /* Print the changes. */
705 printf_unfiltered ("%s\n", history_value.get ());
706
707 /* If there was an error, call this function again. */
708 if (expanded < 0)
709 return cmd;
710
711 /* history_expand returns an allocated string. Just replace
712 our buffer with it. */
713 len = strlen (history_value.get ());
714 xfree (buffer_finish (cmd_line_buffer));
715 cmd_line_buffer->buffer = history_value.get ();
716 cmd_line_buffer->buffer_size = len + 1;
717 cmd = history_value.release ();
718 }
719 }
720
721 /* If we just got an empty line, and that is supposed to repeat the
722 previous command, return the previously saved command. */
723 for (p1 = cmd; *p1 == ' ' || *p1 == '\t'; p1++)
724 ;
725 if (repeat && *p1 == '\0')
726 return get_saved_command_line ();
727
728 /* Add command to history if appropriate. Note: lines consisting
729 solely of comments are also added to the command history. This
730 is useful when you type a command, and then realize you don't
731 want to execute it quite yet. You can comment out the command
732 and then later fetch it from the value history and remove the
733 '#'. The kill ring is probably better, but some people are in
734 the habit of commenting things out. */
735 if (*cmd != '\0' && from_tty && input_interactive_p (current_ui))
736 gdb_add_history (cmd);
737
738 /* Save into global buffer if appropriate. */
739 if (repeat)
740 {
741 save_command_line (cmd);
742 return get_saved_command_line ();
743 }
744 else
745 return cmd;
746 }
747
748 /* Handle a complete line of input. This is called by the callback
749 mechanism within the readline library. Deal with incomplete
750 commands as well, by saving the partial input in a global
751 buffer.
752
753 NOTE: This is the asynchronous version of the command_line_input
754 function. */
755
756 void
757 command_line_handler (gdb::unique_xmalloc_ptr<char> &&rl)
758 {
759 struct buffer *line_buffer = get_command_line_buffer ();
760 struct ui *ui = current_ui;
761 char *cmd;
762
763 cmd = handle_line_of_input (line_buffer, rl.get (), 1, "prompt");
764 if (cmd == (char *) EOF)
765 {
766 /* stdin closed. The connection with the terminal is gone.
767 This happens at the end of a testsuite run, after Expect has
768 hung up but GDB is still alive. In such a case, we just quit
769 gdb killing the inferior program too. */
770 printf_unfiltered ("quit\n");
771 execute_command ("quit", 1);
772 }
773 else if (cmd == NULL)
774 {
775 /* We don't have a full line yet. Print an empty prompt. */
776 display_gdb_prompt ("");
777 }
778 else
779 {
780 ui->prompt_state = PROMPT_NEEDED;
781
782 command_handler (cmd);
783
784 if (ui->prompt_state != PROMPTED)
785 display_gdb_prompt (0);
786 }
787 }
788
789 /* Does reading of input from terminal w/o the editing features
790 provided by the readline library. Calls the line input handler
791 once we have a whole input line. */
792
793 void
794 gdb_readline_no_editing_callback (gdb_client_data client_data)
795 {
796 int c;
797 char *result;
798 struct buffer line_buffer;
799 static int done_once = 0;
800 struct ui *ui = current_ui;
801
802 buffer_init (&line_buffer);
803
804 /* Unbuffer the input stream, so that, later on, the calls to fgetc
805 fetch only one char at the time from the stream. The fgetc's will
806 get up to the first newline, but there may be more chars in the
807 stream after '\n'. If we buffer the input and fgetc drains the
808 stream, getting stuff beyond the newline as well, a select, done
809 afterwards will not trigger. */
810 if (!done_once && !ISATTY (ui->instream))
811 {
812 setbuf (ui->instream, NULL);
813 done_once = 1;
814 }
815
816 /* We still need the while loop here, even though it would seem
817 obvious to invoke gdb_readline_no_editing_callback at every
818 character entered. If not using the readline library, the
819 terminal is in cooked mode, which sends the characters all at
820 once. Poll will notice that the input fd has changed state only
821 after enter is pressed. At this point we still need to fetch all
822 the chars entered. */
823
824 while (1)
825 {
826 /* Read from stdin if we are executing a user defined command.
827 This is the right thing for prompt_for_continue, at least. */
828 c = fgetc (ui->instream != NULL ? ui->instream : ui->stdin_stream);
829
830 if (c == EOF)
831 {
832 if (line_buffer.used_size > 0)
833 {
834 /* The last line does not end with a newline. Return it, and
835 if we are called again fgetc will still return EOF and
836 we'll return NULL then. */
837 break;
838 }
839 xfree (buffer_finish (&line_buffer));
840 ui->input_handler (NULL);
841 return;
842 }
843
844 if (c == '\n')
845 {
846 if (line_buffer.used_size > 0
847 && line_buffer.buffer[line_buffer.used_size - 1] == '\r')
848 line_buffer.used_size--;
849 break;
850 }
851
852 buffer_grow_char (&line_buffer, c);
853 }
854
855 buffer_grow_char (&line_buffer, '\0');
856 result = buffer_finish (&line_buffer);
857 ui->input_handler (gdb::unique_xmalloc_ptr<char> (result));
858 }
859 \f
860
861 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
862 otherwise, return false. */
863
864 static bool
865 unblock_signal (int sig)
866 {
867 #if HAVE_SIGPROCMASK
868 sigset_t sigset;
869 sigemptyset (&sigset);
870 sigaddset (&sigset, sig);
871 gdb_sigmask (SIG_UNBLOCK, &sigset, 0);
872 return true;
873 #endif
874
875 return false;
876 }
877
878 /* Called to handle fatal signals. SIG is the signal number. */
879
880 static void ATTRIBUTE_NORETURN
881 handle_fatal_signal (int sig)
882 {
883 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
884 const auto sig_write = [] (const char *msg) -> void
885 {
886 gdb_stderr->write_async_safe (msg, strlen (msg));
887 };
888
889 if (bt_on_fatal_signal)
890 {
891 sig_write ("\n\n");
892 sig_write (_("Fatal signal: "));
893 sig_write (strsignal (sig));
894 sig_write ("\n");
895
896 gdb_internal_backtrace ();
897
898 sig_write (_("A fatal error internal to GDB has been detected, "
899 "further\ndebugging is not possible. GDB will now "
900 "terminate.\n\n"));
901 sig_write (_("This is a bug, please report it."));
902 if (REPORT_BUGS_TO[0] != '\0')
903 {
904 sig_write (_(" For instructions, see:\n"));
905 sig_write (REPORT_BUGS_TO);
906 sig_write (".");
907 }
908 sig_write ("\n\n");
909
910 gdb_stderr->flush ();
911 }
912 #endif
913
914 /* If possible arrange for SIG to have its default behaviour (which
915 should be to terminate the current process), unblock SIG, and reraise
916 the signal. This ensures GDB terminates with the expected signal. */
917 if (signal (sig, SIG_DFL) != SIG_ERR
918 && unblock_signal (sig))
919 raise (sig);
920
921 /* The above failed, so try to use SIGABRT to terminate GDB. */
922 #ifdef SIGABRT
923 signal (SIGABRT, SIG_DFL);
924 #endif
925 abort (); /* ARI: abort */
926 }
927
928 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
929 always installs a global SIGSEGV handler, and then lets threads
930 indicate their interest in handling the signal by setting this
931 thread-local variable.
932
933 This is a static variable instead of extern because on various platforms
934 (notably Cygwin) extern thread_local variables cause link errors. So
935 instead, we have scoped_segv_handler_restore, which also makes it impossible
936 to accidentally forget to restore it to the original value. */
937
938 static thread_local void (*thread_local_segv_handler) (int);
939
940 static void handle_sigsegv (int sig);
941
942 /* Install the SIGSEGV handler. */
943 static void
944 install_handle_sigsegv ()
945 {
946 #if defined (HAVE_SIGACTION)
947 struct sigaction sa;
948 sa.sa_handler = handle_sigsegv;
949 sigemptyset (&sa.sa_mask);
950 #ifdef HAVE_SIGALTSTACK
951 sa.sa_flags = SA_ONSTACK;
952 #else
953 sa.sa_flags = 0;
954 #endif
955 sigaction (SIGSEGV, &sa, nullptr);
956 #else
957 signal (SIGSEGV, handle_sigsegv);
958 #endif
959 }
960
961 /* Handler for SIGSEGV. */
962
963 static void
964 handle_sigsegv (int sig)
965 {
966 install_handle_sigsegv ();
967
968 if (thread_local_segv_handler == nullptr)
969 handle_fatal_signal (sig);
970 thread_local_segv_handler (sig);
971 }
972
973 \f
974
975 /* The serial event associated with the QUIT flag. set_quit_flag sets
976 this, and check_quit_flag clears it. Used by interruptible_select
977 to be able to do interruptible I/O with no race with the SIGINT
978 handler. */
979 static struct serial_event *quit_serial_event;
980
981 /* Initialization of signal handlers and tokens. There are a number of
982 different strategies for handling different signals here.
983
984 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
985 handle_sig* for each of these signals. These functions are the actual
986 signal handlers associated to the signals via calls to signal(). The
987 only job for these functions is to enqueue the appropriate
988 event/procedure with the event loop. The event loop will take care of
989 invoking the queued procedures to perform the usual tasks associated
990 with the reception of the signal.
991
992 For SIGSEGV the handle_sig* function does all the work for handling this
993 signal.
994
995 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
996 terminate immediately. */
997 void
998 gdb_init_signals (void)
999 {
1000 initialize_async_signal_handlers ();
1001
1002 quit_serial_event = make_serial_event ();
1003
1004 sigint_token =
1005 create_async_signal_handler (async_request_quit, NULL, "sigint");
1006 signal (SIGINT, handle_sigint);
1007
1008 async_sigterm_token
1009 = create_async_signal_handler (async_sigterm_handler, NULL, "sigterm");
1010 signal (SIGTERM, handle_sigterm);
1011
1012 #ifdef SIGQUIT
1013 sigquit_token =
1014 create_async_signal_handler (async_do_nothing, NULL, "sigquit");
1015 signal (SIGQUIT, handle_sigquit);
1016 #endif
1017
1018 #ifdef SIGHUP
1019 if (signal (SIGHUP, handle_sighup) != SIG_IGN)
1020 sighup_token =
1021 create_async_signal_handler (async_disconnect, NULL, "sighup");
1022 else
1023 sighup_token =
1024 create_async_signal_handler (async_do_nothing, NULL, "sighup");
1025 #endif
1026
1027 #ifdef SIGTSTP
1028 sigtstp_token =
1029 create_async_signal_handler (async_sigtstp_handler, NULL, "sigtstp");
1030 #endif
1031
1032 #ifdef SIGFPE
1033 signal (SIGFPE, handle_fatal_signal);
1034 #endif
1035
1036 #ifdef SIGBUS
1037 signal (SIGBUS, handle_fatal_signal);
1038 #endif
1039
1040 #ifdef SIGABRT
1041 signal (SIGABRT, handle_fatal_signal);
1042 #endif
1043
1044 install_handle_sigsegv ();
1045 }
1046
1047 /* See defs.h. */
1048
1049 void
1050 quit_serial_event_set (void)
1051 {
1052 serial_event_set (quit_serial_event);
1053 }
1054
1055 /* See defs.h. */
1056
1057 void
1058 quit_serial_event_clear (void)
1059 {
1060 serial_event_clear (quit_serial_event);
1061 }
1062
1063 /* Return the selectable file descriptor of the serial event
1064 associated with the quit flag. */
1065
1066 static int
1067 quit_serial_event_fd (void)
1068 {
1069 return serial_event_fd (quit_serial_event);
1070 }
1071
1072 /* See defs.h. */
1073
1074 void
1075 default_quit_handler (void)
1076 {
1077 if (check_quit_flag ())
1078 {
1079 if (target_terminal::is_ours ())
1080 quit ();
1081 else
1082 target_pass_ctrlc ();
1083 }
1084 }
1085
1086 /* See defs.h. */
1087 quit_handler_ftype *quit_handler = default_quit_handler;
1088
1089 /* Handle a SIGINT. */
1090
1091 void
1092 handle_sigint (int sig)
1093 {
1094 signal (sig, handle_sigint);
1095
1096 /* We could be running in a loop reading in symfiles or something so
1097 it may be quite a while before we get back to the event loop. So
1098 set quit_flag to 1 here. Then if QUIT is called before we get to
1099 the event loop, we will unwind as expected. */
1100 set_quit_flag ();
1101
1102 /* In case nothing calls QUIT before the event loop is reached, the
1103 event loop handles it. */
1104 mark_async_signal_handler (sigint_token);
1105 }
1106
1107 /* See gdb_select.h. */
1108
1109 int
1110 interruptible_select (int n,
1111 fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
1112 struct timeval *timeout)
1113 {
1114 fd_set my_readfds;
1115 int fd;
1116 int res;
1117
1118 if (readfds == NULL)
1119 {
1120 readfds = &my_readfds;
1121 FD_ZERO (&my_readfds);
1122 }
1123
1124 fd = quit_serial_event_fd ();
1125 FD_SET (fd, readfds);
1126 if (n <= fd)
1127 n = fd + 1;
1128
1129 do
1130 {
1131 res = gdb_select (n, readfds, writefds, exceptfds, timeout);
1132 }
1133 while (res == -1 && errno == EINTR);
1134
1135 if (res == 1 && FD_ISSET (fd, readfds))
1136 {
1137 errno = EINTR;
1138 return -1;
1139 }
1140 return res;
1141 }
1142
1143 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1144
1145 static void
1146 async_sigterm_handler (gdb_client_data arg)
1147 {
1148 quit_force (NULL, 0);
1149 }
1150
1151 /* See defs.h. */
1152 volatile int sync_quit_force_run;
1153
1154 /* Quit GDB if SIGTERM is received.
1155 GDB would quit anyway, but this way it will clean up properly. */
1156 void
1157 handle_sigterm (int sig)
1158 {
1159 signal (sig, handle_sigterm);
1160
1161 sync_quit_force_run = 1;
1162 set_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 fputs_filtered ("Could not kill the program being debugged",
1222 gdb_stderr);
1223 exception_print (gdb_stderr, exception);
1224 }
1225
1226 for (inferior *inf : all_inferiors ())
1227 {
1228 switch_to_inferior_no_thread (inf);
1229 try
1230 {
1231 pop_all_targets ();
1232 }
1233 catch (const gdb_exception &exception)
1234 {
1235 }
1236 }
1237
1238 signal (SIGHUP, SIG_DFL); /*FIXME: ??????????? */
1239 raise (SIGHUP);
1240 }
1241 #endif
1242
1243 #ifdef SIGTSTP
1244 void
1245 handle_sigtstp (int sig)
1246 {
1247 mark_async_signal_handler (sigtstp_token);
1248 signal (sig, handle_sigtstp);
1249 }
1250
1251 static void
1252 async_sigtstp_handler (gdb_client_data arg)
1253 {
1254 const std::string &prompt = get_prompt ();
1255
1256 signal (SIGTSTP, SIG_DFL);
1257 unblock_signal (SIGTSTP);
1258 raise (SIGTSTP);
1259 signal (SIGTSTP, handle_sigtstp);
1260 printf_unfiltered ("%s", prompt.c_str ());
1261 gdb_flush (gdb_stdout);
1262
1263 /* Forget about any previous command -- null line now will do
1264 nothing. */
1265 dont_repeat ();
1266 }
1267 #endif /* SIGTSTP */
1268
1269 \f
1270
1271 /* Set things up for readline to be invoked via the alternate
1272 interface, i.e. via a callback function
1273 (gdb_rl_callback_read_char), and hook up instream to the event
1274 loop. */
1275
1276 void
1277 gdb_setup_readline (int editing)
1278 {
1279 struct ui *ui = current_ui;
1280
1281 /* This function is a noop for the sync case. The assumption is
1282 that the sync setup is ALL done in gdb_init, and we would only
1283 mess it up here. The sync stuff should really go away over
1284 time. */
1285 if (!batch_silent)
1286 gdb_stdout = new stdio_file (ui->outstream);
1287 gdb_stderr = new stderr_file (ui->errstream);
1288 gdb_stdlog = gdb_stderr; /* for moment */
1289 gdb_stdtarg = gdb_stderr; /* for moment */
1290 gdb_stdtargerr = gdb_stderr; /* for moment */
1291
1292 /* If the input stream is connected to a terminal, turn on editing.
1293 However, that is only allowed on the main UI, as we can only have
1294 one instance of readline. */
1295 if (ISATTY (ui->instream) && editing && ui == main_ui)
1296 {
1297 /* Tell gdb that we will be using the readline library. This
1298 could be overwritten by a command in .gdbinit like 'set
1299 editing on' or 'off'. */
1300 ui->command_editing = 1;
1301
1302 /* When a character is detected on instream by select or poll,
1303 readline will be invoked via this callback function. */
1304 ui->call_readline = gdb_rl_callback_read_char_wrapper;
1305
1306 /* Tell readline to use the same input stream that gdb uses. */
1307 rl_instream = ui->instream;
1308 }
1309 else
1310 {
1311 ui->command_editing = 0;
1312 ui->call_readline = gdb_readline_no_editing_callback;
1313 }
1314
1315 /* Now create the event source for this UI's input file descriptor.
1316 Another source is going to be the target program (inferior), but
1317 that must be registered only when it actually exists (I.e. after
1318 we say 'run' or after we connect to a remote target. */
1319 ui_register_input_event_handler (ui);
1320 }
1321
1322 /* Disable command input through the standard CLI channels. Used in
1323 the suspend proc for interpreters that use the standard gdb readline
1324 interface, like the cli & the mi. */
1325
1326 void
1327 gdb_disable_readline (void)
1328 {
1329 struct ui *ui = current_ui;
1330
1331 /* FIXME - It is too heavyweight to delete and remake these every
1332 time you run an interpreter that needs readline. It is probably
1333 better to have the interpreters cache these, which in turn means
1334 that this needs to be moved into interpreter specific code. */
1335
1336 #if 0
1337 ui_file_delete (gdb_stdout);
1338 ui_file_delete (gdb_stderr);
1339 gdb_stdlog = NULL;
1340 gdb_stdtarg = NULL;
1341 gdb_stdtargerr = NULL;
1342 #endif
1343
1344 if (ui->command_editing)
1345 gdb_rl_callback_handler_remove ();
1346 delete_file_handler (ui->input_fd);
1347 }
1348
1349 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler)
1350 {
1351 m_old_handler = thread_local_segv_handler;
1352 thread_local_segv_handler = new_handler;
1353 }
1354
1355 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1356 {
1357 thread_local_segv_handler = m_old_handler;
1358 }
1359
1360 static const char debug_event_loop_off[] = "off";
1361 static const char debug_event_loop_all_except_ui[] = "all-except-ui";
1362 static const char debug_event_loop_all[] = "all";
1363
1364 static const char *debug_event_loop_enum[] = {
1365 debug_event_loop_off,
1366 debug_event_loop_all_except_ui,
1367 debug_event_loop_all,
1368 nullptr
1369 };
1370
1371 static const char *debug_event_loop_value = debug_event_loop_off;
1372
1373 static void
1374 set_debug_event_loop_command (const char *args, int from_tty,
1375 cmd_list_element *c)
1376 {
1377 if (debug_event_loop_value == debug_event_loop_off)
1378 debug_event_loop = debug_event_loop_kind::OFF;
1379 else if (debug_event_loop_value == debug_event_loop_all_except_ui)
1380 debug_event_loop = debug_event_loop_kind::ALL_EXCEPT_UI;
1381 else if (debug_event_loop_value == debug_event_loop_all)
1382 debug_event_loop = debug_event_loop_kind::ALL;
1383 else
1384 gdb_assert_not_reached ("Invalid debug event look kind value.");
1385 }
1386
1387 static void
1388 show_debug_event_loop_command (struct ui_file *file, int from_tty,
1389 struct cmd_list_element *cmd, const char *value)
1390 {
1391 fprintf_filtered (file, _("Event loop debugging is %s.\n"), value);
1392 }
1393
1394 void _initialize_event_top ();
1395 void
1396 _initialize_event_top ()
1397 {
1398 add_setshow_enum_cmd ("event-loop", class_maintenance,
1399 debug_event_loop_enum,
1400 &debug_event_loop_value,
1401 _("Set event-loop debugging."),
1402 _("Show event-loop debugging."),
1403 _("\
1404 Control whether to show event loop-related debug messages."),
1405 set_debug_event_loop_command,
1406 show_debug_event_loop_command,
1407 &setdebuglist, &showdebuglist);
1408
1409 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance,
1410 &bt_on_fatal_signal, _("\
1411 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1412 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1413 Use \"on\" to enable, \"off\" to disable.\n\
1414 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1415 signal from within GDB itself. This is a mechanism to help diagnose\n\
1416 crashes within GDB, not a mechanism for debugging inferiors."),
1417 gdb_internal_backtrace_set_cmd,
1418 show_bt_on_fatal_signal,
1419 &maintenance_set_cmdlist,
1420 &maintenance_show_cmdlist);
1421 }