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