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