Add accessors for symbol's artificial field
[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 delete_file_handler (ui->input_fd);
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_input_event_handler (struct ui *ui)
535 {
536 add_file_handler (ui->input_fd, stdin_event_handler, ui,
537 string_printf ("ui-%d", ui->num), true);
538 }
539
540 /* See top.h. */
541
542 void
543 ui_unregister_input_event_handler (struct ui *ui)
544 {
545 delete_file_handler (ui->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_input_event_handler (ui);
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 delete_file_handler (ui->input_fd);
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 && input_interactive_p (current_ui))
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 && input_interactive_p (current_ui))
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 /* Handle a complete line of input. This is called by the callback
746 mechanism within the readline library. Deal with incomplete
747 commands as well, by saving the partial input in a global
748 buffer.
749
750 NOTE: This is the asynchronous version of the command_line_input
751 function. */
752
753 void
754 command_line_handler (gdb::unique_xmalloc_ptr<char> &&rl)
755 {
756 struct buffer *line_buffer = get_command_line_buffer ();
757 struct ui *ui = current_ui;
758 char *cmd;
759
760 cmd = handle_line_of_input (line_buffer, rl.get (), 1, "prompt");
761 if (cmd == (char *) EOF)
762 {
763 /* stdin closed. The connection with the terminal is gone.
764 This happens at the end of a testsuite run, after Expect has
765 hung up but GDB is still alive. In such a case, we just quit
766 gdb killing the inferior program too. This also happens if the
767 user sends EOF, which is usually bound to ctrl+d.
768
769 What we want to do in this case is print "quit" after the GDB
770 prompt, as if the user had just typed "quit" and pressed return.
771
772 This used to work just fine, but unfortunately, doesn't play well
773 with readline's bracketed paste mode. By the time we get here,
774 readline has already sent the control sequence to leave bracketed
775 paste mode, and this sequence ends with a '\r' character. As a
776 result, if bracketed paste mode is on, and we print quit here,
777 then this will overwrite the prompt.
778
779 To work around this issue, when bracketed paste mode is enabled,
780 we first print '\n' to move to the next line, and then print the
781 quit. This isn't ideal, but avoids corrupting the prompt. */
782 const char *value = rl_variable_value ("enable-bracketed-paste");
783 if (value != nullptr && strcmp (value, "on") == 0)
784 printf_unfiltered ("\n");
785 printf_unfiltered ("quit\n");
786 execute_command ("quit", 1);
787 }
788 else if (cmd == NULL)
789 {
790 /* We don't have a full line yet. Print an empty prompt. */
791 display_gdb_prompt ("");
792 }
793 else
794 {
795 ui->prompt_state = PROMPT_NEEDED;
796
797 command_handler (cmd);
798
799 if (ui->prompt_state != PROMPTED)
800 display_gdb_prompt (0);
801 }
802 }
803
804 /* Does reading of input from terminal w/o the editing features
805 provided by the readline library. Calls the line input handler
806 once we have a whole input line. */
807
808 void
809 gdb_readline_no_editing_callback (gdb_client_data client_data)
810 {
811 int c;
812 char *result;
813 struct buffer line_buffer;
814 struct ui *ui = current_ui;
815
816 buffer_init (&line_buffer);
817
818 FILE *stream = ui->instream != nullptr ? ui->instream : ui->stdin_stream;
819 gdb_assert (stream != nullptr);
820
821 /* Unbuffer the input stream, so that, later on, the calls to fgetc
822 fetch only one char at the time from the stream. The fgetc's will
823 get up to the first newline, but there may be more chars in the
824 stream after '\n'. If we buffer the input and fgetc drains the
825 stream, getting stuff beyond the newline as well, a select, done
826 afterwards will not trigger.
827
828 This unbuffering was, at one point, not applied if the input stream
829 was a tty, however, the buffering can cause problems, even for a tty,
830 in some cases. Please ensure that any changes in this area run the MI
831 tests with the FORCE_SEPARATE_MI_TTY=1 flag being passed. */
832 setbuf (stream, NULL);
833
834 /* We still need the while loop here, even though it would seem
835 obvious to invoke gdb_readline_no_editing_callback at every
836 character entered. If not using the readline library, the
837 terminal is in cooked mode, which sends the characters all at
838 once. Poll will notice that the input fd has changed state only
839 after enter is pressed. At this point we still need to fetch all
840 the chars entered. */
841
842 while (1)
843 {
844 /* Read from stdin if we are executing a user defined command.
845 This is the right thing for prompt_for_continue, at least. */
846 c = fgetc (stream);
847
848 if (c == EOF)
849 {
850 if (line_buffer.used_size > 0)
851 {
852 /* The last line does not end with a newline. Return it, and
853 if we are called again fgetc will still return EOF and
854 we'll return NULL then. */
855 break;
856 }
857 xfree (buffer_finish (&line_buffer));
858 ui->input_handler (NULL);
859 return;
860 }
861
862 if (c == '\n')
863 {
864 if (line_buffer.used_size > 0
865 && line_buffer.buffer[line_buffer.used_size - 1] == '\r')
866 line_buffer.used_size--;
867 break;
868 }
869
870 buffer_grow_char (&line_buffer, c);
871 }
872
873 buffer_grow_char (&line_buffer, '\0');
874 result = buffer_finish (&line_buffer);
875 ui->input_handler (gdb::unique_xmalloc_ptr<char> (result));
876 }
877 \f
878
879 /* Attempt to unblock signal SIG, return true if the signal was unblocked,
880 otherwise, return false. */
881
882 static bool
883 unblock_signal (int sig)
884 {
885 #if HAVE_SIGPROCMASK
886 sigset_t sigset;
887 sigemptyset (&sigset);
888 sigaddset (&sigset, sig);
889 gdb_sigmask (SIG_UNBLOCK, &sigset, 0);
890 return true;
891 #endif
892
893 return false;
894 }
895
896 /* Called to handle fatal signals. SIG is the signal number. */
897
898 static void ATTRIBUTE_NORETURN
899 handle_fatal_signal (int sig)
900 {
901 #ifdef GDB_PRINT_INTERNAL_BACKTRACE
902 const auto sig_write = [] (const char *msg) -> void
903 {
904 gdb_stderr->write_async_safe (msg, strlen (msg));
905 };
906
907 if (bt_on_fatal_signal)
908 {
909 sig_write ("\n\n");
910 sig_write (_("Fatal signal: "));
911 sig_write (strsignal (sig));
912 sig_write ("\n");
913
914 gdb_internal_backtrace ();
915
916 sig_write (_("A fatal error internal to GDB has been detected, "
917 "further\ndebugging is not possible. GDB will now "
918 "terminate.\n\n"));
919 sig_write (_("This is a bug, please report it."));
920 if (REPORT_BUGS_TO[0] != '\0')
921 {
922 sig_write (_(" For instructions, see:\n"));
923 sig_write (REPORT_BUGS_TO);
924 sig_write (".");
925 }
926 sig_write ("\n\n");
927
928 gdb_stderr->flush ();
929 }
930 #endif
931
932 /* If possible arrange for SIG to have its default behaviour (which
933 should be to terminate the current process), unblock SIG, and reraise
934 the signal. This ensures GDB terminates with the expected signal. */
935 if (signal (sig, SIG_DFL) != SIG_ERR
936 && unblock_signal (sig))
937 raise (sig);
938
939 /* The above failed, so try to use SIGABRT to terminate GDB. */
940 #ifdef SIGABRT
941 signal (SIGABRT, SIG_DFL);
942 #endif
943 abort (); /* ARI: abort */
944 }
945
946 /* The SIGSEGV handler for this thread, or NULL if there is none. GDB
947 always installs a global SIGSEGV handler, and then lets threads
948 indicate their interest in handling the signal by setting this
949 thread-local variable.
950
951 This is a static variable instead of extern because on various platforms
952 (notably Cygwin) extern thread_local variables cause link errors. So
953 instead, we have scoped_segv_handler_restore, which also makes it impossible
954 to accidentally forget to restore it to the original value. */
955
956 static thread_local void (*thread_local_segv_handler) (int);
957
958 static void handle_sigsegv (int sig);
959
960 /* Install the SIGSEGV handler. */
961 static void
962 install_handle_sigsegv ()
963 {
964 #if defined (HAVE_SIGACTION)
965 struct sigaction sa;
966 sa.sa_handler = handle_sigsegv;
967 sigemptyset (&sa.sa_mask);
968 #ifdef HAVE_SIGALTSTACK
969 sa.sa_flags = SA_ONSTACK;
970 #else
971 sa.sa_flags = 0;
972 #endif
973 sigaction (SIGSEGV, &sa, nullptr);
974 #else
975 signal (SIGSEGV, handle_sigsegv);
976 #endif
977 }
978
979 /* Handler for SIGSEGV. */
980
981 static void
982 handle_sigsegv (int sig)
983 {
984 install_handle_sigsegv ();
985
986 if (thread_local_segv_handler == nullptr)
987 handle_fatal_signal (sig);
988 thread_local_segv_handler (sig);
989 }
990
991 \f
992
993 /* The serial event associated with the QUIT flag. set_quit_flag sets
994 this, and check_quit_flag clears it. Used by interruptible_select
995 to be able to do interruptible I/O with no race with the SIGINT
996 handler. */
997 static struct serial_event *quit_serial_event;
998
999 /* Initialization of signal handlers and tokens. There are a number of
1000 different strategies for handling different signals here.
1001
1002 For SIGINT, SIGTERM, SIGQUIT, SIGHUP, SIGTSTP, there is a function
1003 handle_sig* for each of these signals. These functions are the actual
1004 signal handlers associated to the signals via calls to signal(). The
1005 only job for these functions is to enqueue the appropriate
1006 event/procedure with the event loop. The event loop will take care of
1007 invoking the queued procedures to perform the usual tasks associated
1008 with the reception of the signal.
1009
1010 For SIGSEGV the handle_sig* function does all the work for handling this
1011 signal.
1012
1013 For SIGFPE, SIGBUS, and SIGABRT, these signals will all cause GDB to
1014 terminate immediately. */
1015 void
1016 gdb_init_signals (void)
1017 {
1018 initialize_async_signal_handlers ();
1019
1020 quit_serial_event = make_serial_event ();
1021
1022 sigint_token =
1023 create_async_signal_handler (async_request_quit, NULL, "sigint");
1024 signal (SIGINT, handle_sigint);
1025
1026 async_sigterm_token
1027 = create_async_signal_handler (async_sigterm_handler, NULL, "sigterm");
1028 signal (SIGTERM, handle_sigterm);
1029
1030 #ifdef SIGQUIT
1031 sigquit_token =
1032 create_async_signal_handler (async_do_nothing, NULL, "sigquit");
1033 signal (SIGQUIT, handle_sigquit);
1034 #endif
1035
1036 #ifdef SIGHUP
1037 if (signal (SIGHUP, handle_sighup) != SIG_IGN)
1038 sighup_token =
1039 create_async_signal_handler (async_disconnect, NULL, "sighup");
1040 else
1041 sighup_token =
1042 create_async_signal_handler (async_do_nothing, NULL, "sighup");
1043 #endif
1044
1045 #ifdef SIGTSTP
1046 sigtstp_token =
1047 create_async_signal_handler (async_sigtstp_handler, NULL, "sigtstp");
1048 #endif
1049
1050 #ifdef SIGFPE
1051 signal (SIGFPE, handle_fatal_signal);
1052 #endif
1053
1054 #ifdef SIGBUS
1055 signal (SIGBUS, handle_fatal_signal);
1056 #endif
1057
1058 #ifdef SIGABRT
1059 signal (SIGABRT, handle_fatal_signal);
1060 #endif
1061
1062 install_handle_sigsegv ();
1063 }
1064
1065 /* See defs.h. */
1066
1067 void
1068 quit_serial_event_set (void)
1069 {
1070 serial_event_set (quit_serial_event);
1071 }
1072
1073 /* See defs.h. */
1074
1075 void
1076 quit_serial_event_clear (void)
1077 {
1078 serial_event_clear (quit_serial_event);
1079 }
1080
1081 /* Return the selectable file descriptor of the serial event
1082 associated with the quit flag. */
1083
1084 static int
1085 quit_serial_event_fd (void)
1086 {
1087 return serial_event_fd (quit_serial_event);
1088 }
1089
1090 /* See defs.h. */
1091
1092 void
1093 default_quit_handler (void)
1094 {
1095 if (check_quit_flag ())
1096 {
1097 if (target_terminal::is_ours ())
1098 quit ();
1099 else
1100 target_pass_ctrlc ();
1101 }
1102 }
1103
1104 /* See defs.h. */
1105 quit_handler_ftype *quit_handler = default_quit_handler;
1106
1107 /* Handle a SIGINT. */
1108
1109 void
1110 handle_sigint (int sig)
1111 {
1112 signal (sig, handle_sigint);
1113
1114 /* We could be running in a loop reading in symfiles or something so
1115 it may be quite a while before we get back to the event loop. So
1116 set quit_flag to 1 here. Then if QUIT is called before we get to
1117 the event loop, we will unwind as expected. */
1118 set_quit_flag ();
1119
1120 /* In case nothing calls QUIT before the event loop is reached, the
1121 event loop handles it. */
1122 mark_async_signal_handler (sigint_token);
1123 }
1124
1125 /* See gdb_select.h. */
1126
1127 int
1128 interruptible_select (int n,
1129 fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
1130 struct timeval *timeout)
1131 {
1132 fd_set my_readfds;
1133 int fd;
1134 int res;
1135
1136 if (readfds == NULL)
1137 {
1138 readfds = &my_readfds;
1139 FD_ZERO (&my_readfds);
1140 }
1141
1142 fd = quit_serial_event_fd ();
1143 FD_SET (fd, readfds);
1144 if (n <= fd)
1145 n = fd + 1;
1146
1147 do
1148 {
1149 res = gdb_select (n, readfds, writefds, exceptfds, timeout);
1150 }
1151 while (res == -1 && errno == EINTR);
1152
1153 if (res == 1 && FD_ISSET (fd, readfds))
1154 {
1155 errno = EINTR;
1156 return -1;
1157 }
1158 return res;
1159 }
1160
1161 /* Handle GDB exit upon receiving SIGTERM if target_can_async_p (). */
1162
1163 static void
1164 async_sigterm_handler (gdb_client_data arg)
1165 {
1166 quit_force (NULL, 0);
1167 }
1168
1169 /* See defs.h. */
1170 volatile int sync_quit_force_run;
1171
1172 /* Quit GDB if SIGTERM is received.
1173 GDB would quit anyway, but this way it will clean up properly. */
1174 void
1175 handle_sigterm (int sig)
1176 {
1177 signal (sig, handle_sigterm);
1178
1179 sync_quit_force_run = 1;
1180 set_quit_flag ();
1181
1182 mark_async_signal_handler (async_sigterm_token);
1183 }
1184
1185 /* Do the quit. All the checks have been done by the caller. */
1186 void
1187 async_request_quit (gdb_client_data arg)
1188 {
1189 /* If the quit_flag has gotten reset back to 0 by the time we get
1190 back here, that means that an exception was thrown to unwind the
1191 current command before we got back to the event loop. So there
1192 is no reason to call quit again here. */
1193 QUIT;
1194 }
1195
1196 #ifdef SIGQUIT
1197 /* Tell the event loop what to do if SIGQUIT is received.
1198 See event-signal.c. */
1199 static void
1200 handle_sigquit (int sig)
1201 {
1202 mark_async_signal_handler (sigquit_token);
1203 signal (sig, handle_sigquit);
1204 }
1205 #endif
1206
1207 #if defined (SIGQUIT) || defined (SIGHUP)
1208 /* Called by the event loop in response to a SIGQUIT or an
1209 ignored SIGHUP. */
1210 static void
1211 async_do_nothing (gdb_client_data arg)
1212 {
1213 /* Empty function body. */
1214 }
1215 #endif
1216
1217 #ifdef SIGHUP
1218 /* Tell the event loop what to do if SIGHUP is received.
1219 See event-signal.c. */
1220 static void
1221 handle_sighup (int sig)
1222 {
1223 mark_async_signal_handler (sighup_token);
1224 signal (sig, handle_sighup);
1225 }
1226
1227 /* Called by the event loop to process a SIGHUP. */
1228 static void
1229 async_disconnect (gdb_client_data arg)
1230 {
1231
1232 try
1233 {
1234 quit_cover ();
1235 }
1236
1237 catch (const gdb_exception &exception)
1238 {
1239 gdb_puts ("Could not kill the program being debugged",
1240 gdb_stderr);
1241 exception_print (gdb_stderr, exception);
1242 }
1243
1244 for (inferior *inf : all_inferiors ())
1245 {
1246 switch_to_inferior_no_thread (inf);
1247 try
1248 {
1249 pop_all_targets ();
1250 }
1251 catch (const gdb_exception &exception)
1252 {
1253 }
1254 }
1255
1256 signal (SIGHUP, SIG_DFL); /*FIXME: ??????????? */
1257 raise (SIGHUP);
1258 }
1259 #endif
1260
1261 #ifdef SIGTSTP
1262 void
1263 handle_sigtstp (int sig)
1264 {
1265 mark_async_signal_handler (sigtstp_token);
1266 signal (sig, handle_sigtstp);
1267 }
1268
1269 static void
1270 async_sigtstp_handler (gdb_client_data arg)
1271 {
1272 const std::string &prompt = get_prompt ();
1273
1274 signal (SIGTSTP, SIG_DFL);
1275 unblock_signal (SIGTSTP);
1276 raise (SIGTSTP);
1277 signal (SIGTSTP, handle_sigtstp);
1278 printf_unfiltered ("%s", prompt.c_str ());
1279 gdb_flush (gdb_stdout);
1280
1281 /* Forget about any previous command -- null line now will do
1282 nothing. */
1283 dont_repeat ();
1284 }
1285 #endif /* SIGTSTP */
1286
1287 \f
1288
1289 /* Set things up for readline to be invoked via the alternate
1290 interface, i.e. via a callback function
1291 (gdb_rl_callback_read_char), and hook up instream to the event
1292 loop. */
1293
1294 void
1295 gdb_setup_readline (int editing)
1296 {
1297 struct ui *ui = current_ui;
1298
1299 /* This function is a noop for the sync case. The assumption is
1300 that the sync setup is ALL done in gdb_init, and we would only
1301 mess it up here. The sync stuff should really go away over
1302 time. */
1303 if (!batch_silent)
1304 gdb_stdout = new pager_file (new stdio_file (ui->outstream));
1305 gdb_stderr = new stderr_file (ui->errstream);
1306 gdb_stdlog = new timestamped_file (gdb_stderr);
1307 gdb_stdtarg = gdb_stderr; /* for moment */
1308 gdb_stdtargerr = gdb_stderr; /* for moment */
1309
1310 /* If the input stream is connected to a terminal, turn on editing.
1311 However, that is only allowed on the main UI, as we can only have
1312 one instance of readline. */
1313 if (ISATTY (ui->instream) && editing && ui == main_ui)
1314 {
1315 /* Tell gdb that we will be using the readline library. This
1316 could be overwritten by a command in .gdbinit like 'set
1317 editing on' or 'off'. */
1318 ui->command_editing = 1;
1319
1320 /* When a character is detected on instream by select or poll,
1321 readline will be invoked via this callback function. */
1322 ui->call_readline = gdb_rl_callback_read_char_wrapper;
1323
1324 /* Tell readline to use the same input stream that gdb uses. */
1325 rl_instream = ui->instream;
1326 }
1327 else
1328 {
1329 ui->command_editing = 0;
1330 ui->call_readline = gdb_readline_no_editing_callback;
1331 }
1332
1333 /* Now create the event source for this UI's input file descriptor.
1334 Another source is going to be the target program (inferior), but
1335 that must be registered only when it actually exists (I.e. after
1336 we say 'run' or after we connect to a remote target. */
1337 ui_register_input_event_handler (ui);
1338 }
1339
1340 /* Disable command input through the standard CLI channels. Used in
1341 the suspend proc for interpreters that use the standard gdb readline
1342 interface, like the cli & the mi. */
1343
1344 void
1345 gdb_disable_readline (void)
1346 {
1347 struct ui *ui = current_ui;
1348
1349 /* FIXME - It is too heavyweight to delete and remake these every
1350 time you run an interpreter that needs readline. It is probably
1351 better to have the interpreters cache these, which in turn means
1352 that this needs to be moved into interpreter specific code. */
1353
1354 #if 0
1355 ui_file_delete (gdb_stdout);
1356 ui_file_delete (gdb_stderr);
1357 gdb_stdlog = NULL;
1358 gdb_stdtarg = NULL;
1359 gdb_stdtargerr = NULL;
1360 #endif
1361
1362 if (ui->command_editing)
1363 gdb_rl_callback_handler_remove ();
1364 delete_file_handler (ui->input_fd);
1365 }
1366
1367 scoped_segv_handler_restore::scoped_segv_handler_restore (segv_handler_t new_handler)
1368 {
1369 m_old_handler = thread_local_segv_handler;
1370 thread_local_segv_handler = new_handler;
1371 }
1372
1373 scoped_segv_handler_restore::~scoped_segv_handler_restore()
1374 {
1375 thread_local_segv_handler = m_old_handler;
1376 }
1377
1378 static const char debug_event_loop_off[] = "off";
1379 static const char debug_event_loop_all_except_ui[] = "all-except-ui";
1380 static const char debug_event_loop_all[] = "all";
1381
1382 static const char *debug_event_loop_enum[] = {
1383 debug_event_loop_off,
1384 debug_event_loop_all_except_ui,
1385 debug_event_loop_all,
1386 nullptr
1387 };
1388
1389 static const char *debug_event_loop_value = debug_event_loop_off;
1390
1391 static void
1392 set_debug_event_loop_command (const char *args, int from_tty,
1393 cmd_list_element *c)
1394 {
1395 if (debug_event_loop_value == debug_event_loop_off)
1396 debug_event_loop = debug_event_loop_kind::OFF;
1397 else if (debug_event_loop_value == debug_event_loop_all_except_ui)
1398 debug_event_loop = debug_event_loop_kind::ALL_EXCEPT_UI;
1399 else if (debug_event_loop_value == debug_event_loop_all)
1400 debug_event_loop = debug_event_loop_kind::ALL;
1401 else
1402 gdb_assert_not_reached ("Invalid debug event look kind value.");
1403 }
1404
1405 static void
1406 show_debug_event_loop_command (struct ui_file *file, int from_tty,
1407 struct cmd_list_element *cmd, const char *value)
1408 {
1409 gdb_printf (file, _("Event loop debugging is %s.\n"), value);
1410 }
1411
1412 void _initialize_event_top ();
1413 void
1414 _initialize_event_top ()
1415 {
1416 add_setshow_enum_cmd ("event-loop", class_maintenance,
1417 debug_event_loop_enum,
1418 &debug_event_loop_value,
1419 _("Set event-loop debugging."),
1420 _("Show event-loop debugging."),
1421 _("\
1422 Control whether to show event loop-related debug messages."),
1423 set_debug_event_loop_command,
1424 show_debug_event_loop_command,
1425 &setdebuglist, &showdebuglist);
1426
1427 add_setshow_boolean_cmd ("backtrace-on-fatal-signal", class_maintenance,
1428 &bt_on_fatal_signal, _("\
1429 Set whether to produce a backtrace if GDB receives a fatal signal."), _("\
1430 Show whether GDB will produce a backtrace if it receives a fatal signal."), _("\
1431 Use \"on\" to enable, \"off\" to disable.\n\
1432 If enabled, GDB will produce a minimal backtrace if it encounters a fatal\n\
1433 signal from within GDB itself. This is a mechanism to help diagnose\n\
1434 crashes within GDB, not a mechanism for debugging inferiors."),
1435 gdb_internal_backtrace_set_cmd,
1436 show_bt_on_fatal_signal,
1437 &maintenance_set_cmdlist,
1438 &maintenance_show_cmdlist);
1439 }