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