2005-02-10 Andrew Cagney <cagney@gnu.org>
[external/binutils.git] / gdb / event-top.c
1 /* Top level stuff for GDB, the GNU debugger.
2
3    Copyright 1999, 2000, 2001, 2002, 2004, 2005 Free Software
4    Foundation, Inc.
5
6    Written by Elena Zannoni <ezannoni@cygnus.com> of Cygnus Solutions.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place - Suite 330,
23    Boston, MA 02111-1307, USA. */
24
25 #include "defs.h"
26 #include "top.h"
27 #include "inferior.h"
28 #include "target.h"
29 #include "terminal.h"           /* for job_control */
30 #include "event-loop.h"
31 #include "event-top.h"
32 #include "interps.h"
33 #include <signal.h>
34 #include "exceptions.h"
35
36 /* For dont_repeat() */
37 #include "gdbcmd.h"
38
39 /* readline include files */
40 #include "readline/readline.h"
41 #include "readline/history.h"
42
43 /* readline defines this.  */
44 #undef savestring
45
46 static void rl_callback_read_char_wrapper (gdb_client_data client_data);
47 static void command_line_handler (char *rl);
48 static void command_line_handler_continuation (struct continuation_arg *arg);
49 static void change_line_handler (void);
50 static void change_annotation_level (void);
51 static void command_handler (char *command);
52 static void async_do_nothing (gdb_client_data arg);
53 static void async_disconnect (gdb_client_data arg);
54 static void async_stop_sig (gdb_client_data arg);
55 static void async_float_handler (gdb_client_data arg);
56
57 /* Signal handlers. */
58 static void handle_sigquit (int sig);
59 static void handle_sighup (int sig);
60 static void handle_sigfpe (int sig);
61 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
62 static void handle_sigwinch (int sig);
63 #endif
64
65 /* Functions to be invoked by the event loop in response to
66    signals. */
67 static void async_do_nothing (gdb_client_data);
68 static void async_disconnect (gdb_client_data);
69 static void async_float_handler (gdb_client_data);
70 static void async_stop_sig (gdb_client_data);
71
72 /* Readline offers an alternate interface, via callback
73    functions. These are all included in the file callback.c in the
74    readline distribution.  This file provides (mainly) a function, which
75    the event loop uses as callback (i.e. event handler) whenever an event
76    is detected on the standard input file descriptor.
77    readline_callback_read_char is called (by the GDB event loop) whenever
78    there is a new character ready on the input stream. This function
79    incrementally builds a buffer internal to readline where it
80    accumulates the line read up to the point of invocation.  In the
81    special case in which the character read is newline, the function
82    invokes a GDB supplied callback routine, which does the processing of
83    a full command line.  This latter routine is the asynchronous analog
84    of the old command_line_input in gdb. Instead of invoking (and waiting
85    for) readline to read the command line and pass it back to
86    command_loop for processing, the new command_line_handler function has
87    the command line already available as its parameter.  INPUT_HANDLER is
88    to be set to the function that readline will invoke when a complete
89    line of input is ready.  CALL_READLINE is to be set to the function
90    that readline offers as callback to the event_loop. */
91
92 void (*input_handler) (char *);
93 void (*call_readline) (gdb_client_data);
94
95 /* Important variables for the event loop. */
96
97 /* This is used to determine if GDB is using the readline library or
98    its own simplified form of readline. It is used by the asynchronous
99    form of the set editing command.
100    ezannoni: as of 1999-04-29 I expect that this
101    variable will not be used after gdb is changed to use the event
102    loop as default engine, and event-top.c is merged into top.c. */
103 int async_command_editing_p;
104
105 /* This variable contains the new prompt that the user sets with the
106    set prompt command. */
107 char *new_async_prompt;
108
109 /* This is the annotation suffix that will be used when the
110    annotation_level is 2. */
111 char *async_annotation_suffix;
112
113 /* This is used to display the notification of the completion of an
114    asynchronous execution command. */
115 int exec_done_display_p = 0;
116
117 /* This is the file descriptor for the input stream that GDB uses to
118    read commands from. */
119 int input_fd;
120
121 /* This is the prompt stack. Prompts will be pushed on the stack as
122    needed by the different 'kinds' of user inputs GDB is asking
123    for. See event-loop.h. */
124 struct prompts the_prompts;
125
126 /* signal handling variables */
127 /* Each of these is a pointer to a function that the event loop will
128    invoke if the corresponding signal has received. The real signal
129    handlers mark these functions as ready to be executed and the event
130    loop, in a later iteration, calls them. See the function
131    invoke_async_signal_handler. */
132 void *sigint_token;
133 #ifdef SIGHUP
134 void *sighup_token;
135 #endif
136 void *sigquit_token;
137 void *sigfpe_token;
138 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
139 void *sigwinch_token;
140 #endif
141 #ifdef STOP_SIGNAL
142 void *sigtstp_token;
143 #endif
144
145 /* Structure to save a partially entered command.  This is used when
146    the user types '\' at the end of a command line. This is necessary
147    because each line of input is handled by a different call to
148    command_line_handler, and normally there is no state retained
149    between different calls. */
150 int more_to_come = 0;
151
152 struct readline_input_state
153   {
154     char *linebuffer;
155     char *linebuffer_ptr;
156   }
157 readline_input_state;
158
159 /* This hook is called by rl_callback_read_char_wrapper after each
160    character is processed.  */
161 void (*after_char_processing_hook) ();
162 \f
163
164 /* Wrapper function for calling into the readline library. The event
165    loop expects the callback function to have a paramter, while readline 
166    expects none. */
167 static void
168 rl_callback_read_char_wrapper (gdb_client_data client_data)
169 {
170   rl_callback_read_char ();
171   if (after_char_processing_hook)
172     (*after_char_processing_hook) ();
173 }
174
175 /* Initialize all the necessary variables, start the event loop,
176    register readline, and stdin, start the loop. */
177 void
178 cli_command_loop (void)
179 {
180   int length;
181   char *a_prompt;
182   char *gdb_prompt = get_prompt ();
183
184   /* If we are using readline, set things up and display the first
185      prompt, otherwise just print the prompt. */
186   if (async_command_editing_p)
187     {
188       /* Tell readline what the prompt to display is and what function it
189          will need to call after a whole line is read. This also displays
190          the first prompt. */
191       length = strlen (PREFIX (0)) + strlen (gdb_prompt) + strlen (SUFFIX (0)) + 1;
192       a_prompt = (char *) xmalloc (length);
193       strcpy (a_prompt, PREFIX (0));
194       strcat (a_prompt, gdb_prompt);
195       strcat (a_prompt, SUFFIX (0));
196       rl_callback_handler_install (a_prompt, input_handler);
197     }
198   else
199     display_gdb_prompt (0);
200
201   /* Now it's time to start the event loop. */
202   start_event_loop ();
203 }
204
205 /* Change the function to be invoked every time there is a character
206    ready on stdin. This is used when the user sets the editing off,
207    therefore bypassing readline, and letting gdb handle the input
208    itself, via gdb_readline2. Also it is used in the opposite case in
209    which the user sets editing on again, by restoring readline
210    handling of the input. */
211 static void
212 change_line_handler (void)
213 {
214   /* NOTE: this operates on input_fd, not instream. If we are reading
215      commands from a file, instream will point to the file. However in
216      async mode, we always read commands from a file with editing
217      off. This means that the 'set editing on/off' will have effect
218      only on the interactive session. */
219
220   if (async_command_editing_p)
221     {
222       /* Turn on editing by using readline. */
223       call_readline = rl_callback_read_char_wrapper;
224       input_handler = command_line_handler;
225     }
226   else
227     {
228       /* Turn off editing by using gdb_readline2. */
229       rl_callback_handler_remove ();
230       call_readline = gdb_readline2;
231
232       /* Set up the command handler as well, in case we are called as
233          first thing from .gdbinit. */
234       input_handler = command_line_handler;
235     }
236 }
237
238 /* Displays the prompt. The prompt that is displayed is the current
239    top of the prompt stack, if the argument NEW_PROMPT is
240    0. Otherwise, it displays whatever NEW_PROMPT is. This is used
241    after each gdb command has completed, and in the following cases:
242    1. when the user enters a command line which is ended by '\'
243    indicating that the command will continue on the next line.
244    In that case the prompt that is displayed is the empty string.
245    2. When the user is entering 'commands' for a breakpoint, or
246    actions for a tracepoint. In this case the prompt will be '>'
247    3. Other????
248    FIXME: 2. & 3. not implemented yet for async. */
249 void
250 display_gdb_prompt (char *new_prompt)
251 {
252   int prompt_length = 0;
253   char *gdb_prompt = get_prompt ();
254
255   /* Each interpreter has its own rules on displaying the command
256      prompt.  */
257   if (!current_interp_display_prompt_p ())
258     return;
259
260   if (target_executing && sync_execution)
261     {
262       /* This is to trick readline into not trying to display the
263          prompt.  Even though we display the prompt using this
264          function, readline still tries to do its own display if we
265          don't call rl_callback_handler_install and
266          rl_callback_handler_remove (which readline detects because a
267          global variable is not set). If readline did that, it could
268          mess up gdb signal handlers for SIGINT.  Readline assumes
269          that between calls to rl_set_signals and rl_clear_signals gdb
270          doesn't do anything with the signal handlers. Well, that's
271          not the case, because when the target executes we change the
272          SIGINT signal handler. If we allowed readline to display the
273          prompt, the signal handler change would happen exactly
274          between the calls to the above two functions.
275          Calling rl_callback_handler_remove(), does the job. */
276
277       rl_callback_handler_remove ();
278       return;
279     }
280
281   if (!new_prompt)
282     {
283       /* Just use the top of the prompt stack. */
284       prompt_length = strlen (PREFIX (0)) +
285         strlen (SUFFIX (0)) +
286         strlen (gdb_prompt) + 1;
287
288       new_prompt = (char *) alloca (prompt_length);
289
290       /* Prefix needs to have new line at end. */
291       strcpy (new_prompt, PREFIX (0));
292       strcat (new_prompt, gdb_prompt);
293       /* Suffix needs to have a new line at end and \032 \032 at
294          beginning. */
295       strcat (new_prompt, SUFFIX (0));
296     }
297
298   if (async_command_editing_p)
299     {
300       rl_callback_handler_remove ();
301       rl_callback_handler_install (new_prompt, input_handler);
302     }
303   /* new_prompt at this point can be the top of the stack or the one passed in */
304   else if (new_prompt)
305     {
306       /* Don't use a _filtered function here.  It causes the assumed
307          character position to be off, since the newline we read from
308          the user is not accounted for.  */
309       fputs_unfiltered (new_prompt, gdb_stdout);
310       gdb_flush (gdb_stdout);
311     }
312 }
313
314 /* Used when the user requests a different annotation level, with
315    'set annotate'. It pushes a new prompt (with prefix and suffix) on top
316    of the prompt stack, if the annotation level desired is 2, otherwise
317    it pops the top of the prompt stack when we want the annotation level
318    to be the normal ones (1 or 0). */
319 static void
320 change_annotation_level (void)
321 {
322   char *prefix, *suffix;
323
324   if (!PREFIX (0) || !PROMPT (0) || !SUFFIX (0))
325     {
326       /* The prompt stack has not been initialized to "", we are
327          using gdb w/o the --async switch */
328       warning (_("Command has same effect as set annotate"));
329       return;
330     }
331
332   if (annotation_level > 1)
333     {
334       if (!strcmp (PREFIX (0), "") && !strcmp (SUFFIX (0), ""))
335         {
336           /* Push a new prompt if the previous annotation_level was not >1. */
337           prefix = (char *) alloca (strlen (async_annotation_suffix) + 10);
338           strcpy (prefix, "\n\032\032pre-");
339           strcat (prefix, async_annotation_suffix);
340           strcat (prefix, "\n");
341
342           suffix = (char *) alloca (strlen (async_annotation_suffix) + 6);
343           strcpy (suffix, "\n\032\032");
344           strcat (suffix, async_annotation_suffix);
345           strcat (suffix, "\n");
346
347           push_prompt (prefix, (char *) 0, suffix);
348         }
349     }
350   else
351     {
352       if (strcmp (PREFIX (0), "") && strcmp (SUFFIX (0), ""))
353         {
354           /* Pop the top of the stack, we are going back to annotation < 1. */
355           pop_prompt ();
356         }
357     }
358 }
359
360 /* Pushes a new prompt on the prompt stack. Each prompt has three
361    parts: prefix, prompt, suffix. Usually prefix and suffix are empty
362    strings, except when the annotation level is 2. Memory is allocated
363    within savestring for the new prompt. */
364 void
365 push_prompt (char *prefix, char *prompt, char *suffix)
366 {
367   the_prompts.top++;
368   PREFIX (0) = savestring (prefix, strlen (prefix));
369
370   /* Note that this function is used by the set annotate 2
371      command. This is why we take care of saving the old prompt
372      in case a new one is not specified. */
373   if (prompt)
374     PROMPT (0) = savestring (prompt, strlen (prompt));
375   else
376     PROMPT (0) = savestring (PROMPT (-1), strlen (PROMPT (-1)));
377
378   SUFFIX (0) = savestring (suffix, strlen (suffix));
379 }
380
381 /* Pops the top of the prompt stack, and frees the memory allocated for it. */
382 void
383 pop_prompt (void)
384 {
385   /* If we are not during a 'synchronous' execution command, in which
386      case, the top prompt would be empty. */
387   if (strcmp (PROMPT (0), ""))
388     /* This is for the case in which the prompt is set while the
389        annotation level is 2. The top prompt will be changed, but when
390        we return to annotation level < 2, we want that new prompt to be
391        in effect, until the user does another 'set prompt'. */
392     if (strcmp (PROMPT (0), PROMPT (-1)))
393       {
394         xfree (PROMPT (-1));
395         PROMPT (-1) = savestring (PROMPT (0), strlen (PROMPT (0)));
396       }
397
398   xfree (PREFIX (0));
399   xfree (PROMPT (0));
400   xfree (SUFFIX (0));
401   the_prompts.top--;
402 }
403
404 /* When there is an event ready on the stdin file desriptor, instead
405    of calling readline directly throught the callback function, or
406    instead of calling gdb_readline2, give gdb a chance to detect
407    errors and do something. */
408 void
409 stdin_event_handler (int error, gdb_client_data client_data)
410 {
411   if (error)
412     {
413       printf_unfiltered ("error detected on stdin\n");
414       delete_file_handler (input_fd);
415       discard_all_continuations ();
416       /* If stdin died, we may as well kill gdb. */
417       quit_command ((char *) 0, stdin == instream);
418     }
419   else
420     (*call_readline) (client_data);
421 }
422
423 /* Re-enable stdin after the end of an execution command in
424    synchronous mode, or after an error from the target, and we aborted
425    the exec operation. */
426
427 void
428 async_enable_stdin (void *dummy)
429 {
430   /* See NOTE in async_disable_stdin() */
431   /* FIXME: cagney/1999-09-27: Call this before clearing
432      sync_execution.  Current target_terminal_ours() implementations
433      check for sync_execution before switching the terminal. */
434   target_terminal_ours ();
435   pop_prompt ();
436   sync_execution = 0;
437 }
438
439 /* Disable reads from stdin (the console) marking the command as
440    synchronous. */
441
442 void
443 async_disable_stdin (void)
444 {
445   sync_execution = 1;
446   push_prompt ("", "", "");
447   /* FIXME: cagney/1999-09-27: At present this call is technically
448      redundant since infcmd.c and infrun.c both already call
449      target_terminal_inferior().  As the terminal handling (in
450      sync/async mode) is refined, the duplicate calls can be
451      eliminated (Here or in infcmd.c/infrun.c). */
452   target_terminal_inferior ();
453   /* Add the reinstate of stdin to the list of cleanups to be done
454      in case the target errors out and dies. These cleanups are also
455      done in case of normal successful termination of the execution
456      command, by complete_execution(). */
457   make_exec_error_cleanup (async_enable_stdin, NULL);
458 }
459 \f
460
461 /* Handles a gdb command. This function is called by
462    command_line_handler, which has processed one or more input lines
463    into COMMAND. */
464 /* NOTE: 1999-04-30 This is the asynchronous version of the command_loop
465    function.  The command_loop function will be obsolete when we
466    switch to use the event loop at every execution of gdb. */
467 static void
468 command_handler (char *command)
469 {
470   struct cleanup *old_chain;
471   int stdin_is_tty = ISATTY (stdin);
472   struct continuation_arg *arg1;
473   struct continuation_arg *arg2;
474   long time_at_cmd_start;
475 #ifdef HAVE_SBRK
476   long space_at_cmd_start = 0;
477 #endif
478   extern int display_time;
479   extern int display_space;
480
481   quit_flag = 0;
482   if (instream == stdin && stdin_is_tty)
483     reinitialize_more_filter ();
484   old_chain = make_cleanup (null_cleanup, 0);
485
486   /* If readline returned a NULL command, it means that the 
487      connection with the terminal is gone. This happens at the
488      end of a testsuite run, after Expect has hung up 
489      but GDB is still alive. In such a case, we just quit gdb
490      killing the inferior program too. */
491   if (command == 0)
492     quit_command ((char *) 0, stdin == instream);
493
494   time_at_cmd_start = get_run_time ();
495
496   if (display_space)
497     {
498 #ifdef HAVE_SBRK
499       char *lim = (char *) sbrk (0);
500       space_at_cmd_start = lim - lim_at_start;
501 #endif
502     }
503
504   execute_command (command, instream == stdin);
505
506   /* Set things up for this function to be compete later, once the
507      execution has completed, if we are doing an execution command,
508      otherwise, just go ahead and finish. */
509   if (target_can_async_p () && target_executing)
510     {
511       arg1 =
512         (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg));
513       arg2 =
514         (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg));
515       arg1->next = arg2;
516       arg2->next = NULL;
517       arg1->data.longint = time_at_cmd_start;
518 #ifdef HAVE_SBRK
519       arg2->data.longint = space_at_cmd_start;
520 #endif
521       add_continuation (command_line_handler_continuation, arg1);
522     }
523
524   /* Do any commands attached to breakpoint we stopped at. Only if we
525      are always running synchronously. Or if we have just executed a
526      command that doesn't start the target. */
527   if (!target_can_async_p () || !target_executing)
528     {
529       bpstat_do_actions (&stop_bpstat);
530       do_cleanups (old_chain);
531
532       if (display_time)
533         {
534           long cmd_time = get_run_time () - time_at_cmd_start;
535
536           printf_unfiltered ("Command execution time: %ld.%06ld\n",
537                              cmd_time / 1000000, cmd_time % 1000000);
538         }
539
540       if (display_space)
541         {
542 #ifdef HAVE_SBRK
543           char *lim = (char *) sbrk (0);
544           long space_now = lim - lim_at_start;
545           long space_diff = space_now - space_at_cmd_start;
546
547           printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
548                              space_now,
549                              (space_diff >= 0 ? '+' : '-'),
550                              space_diff);
551 #endif
552         }
553     }
554 }
555
556 /* Do any commands attached to breakpoint we stopped at. Only if we
557    are always running synchronously. Or if we have just executed a
558    command that doesn't start the target. */
559 void
560 command_line_handler_continuation (struct continuation_arg *arg)
561 {
562   extern int display_time;
563   extern int display_space;
564
565   long time_at_cmd_start  = arg->data.longint;
566   long space_at_cmd_start = arg->next->data.longint;
567
568   bpstat_do_actions (&stop_bpstat);
569   /*do_cleanups (old_chain); *//*?????FIXME????? */
570
571   if (display_time)
572     {
573       long cmd_time = get_run_time () - time_at_cmd_start;
574
575       printf_unfiltered ("Command execution time: %ld.%06ld\n",
576                          cmd_time / 1000000, cmd_time % 1000000);
577     }
578   if (display_space)
579     {
580 #ifdef HAVE_SBRK
581       char *lim = (char *) sbrk (0);
582       long space_now = lim - lim_at_start;
583       long space_diff = space_now - space_at_cmd_start;
584
585       printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
586                          space_now,
587                          (space_diff >= 0 ? '+' : '-'),
588                          space_diff);
589 #endif
590     }
591 }
592
593 /* Handle a complete line of input. This is called by the callback
594    mechanism within the readline library.  Deal with incomplete commands
595    as well, by saving the partial input in a global buffer.  */
596
597 /* NOTE: 1999-04-30 This is the asynchronous version of the
598    command_line_input function. command_line_input will become
599    obsolete once we use the event loop as the default mechanism in
600    GDB. */
601 static void
602 command_line_handler (char *rl)
603 {
604   static char *linebuffer = 0;
605   static unsigned linelength = 0;
606   char *p;
607   char *p1;
608   extern char *line;
609   extern int linesize;
610   char *nline;
611   char got_eof = 0;
612
613
614   int repeat = (instream == stdin);
615
616   if (annotation_level > 1 && instream == stdin)
617     {
618       printf_unfiltered ("\n\032\032post-");
619       puts_unfiltered (async_annotation_suffix);
620       printf_unfiltered ("\n");
621     }
622
623   if (linebuffer == 0)
624     {
625       linelength = 80;
626       linebuffer = (char *) xmalloc (linelength);
627     }
628
629   p = linebuffer;
630
631   if (more_to_come)
632     {
633       strcpy (linebuffer, readline_input_state.linebuffer);
634       p = readline_input_state.linebuffer_ptr;
635       xfree (readline_input_state.linebuffer);
636       more_to_come = 0;
637       pop_prompt ();
638     }
639
640 #ifdef STOP_SIGNAL
641   if (job_control)
642     signal (STOP_SIGNAL, handle_stop_sig);
643 #endif
644
645   /* Make sure that all output has been output.  Some machines may let
646      you get away with leaving out some of the gdb_flush, but not all.  */
647   wrap_here ("");
648   gdb_flush (gdb_stdout);
649   gdb_flush (gdb_stderr);
650
651   if (source_file_name != NULL)
652     ++source_line_number;
653
654   /* If we are in this case, then command_handler will call quit 
655      and exit from gdb. */
656   if (!rl || rl == (char *) EOF)
657     {
658       got_eof = 1;
659       command_handler (0);
660     }
661   if (strlen (rl) + 1 + (p - linebuffer) > linelength)
662     {
663       linelength = strlen (rl) + 1 + (p - linebuffer);
664       nline = (char *) xrealloc (linebuffer, linelength);
665       p += nline - linebuffer;
666       linebuffer = nline;
667     }
668   p1 = rl;
669   /* Copy line.  Don't copy null at end.  (Leaves line alone
670      if this was just a newline)  */
671   while (*p1)
672     *p++ = *p1++;
673
674   xfree (rl);                   /* Allocated in readline.  */
675
676   if (p > linebuffer && *(p - 1) == '\\')
677     {
678       p--;                      /* Put on top of '\'.  */
679
680       readline_input_state.linebuffer = savestring (linebuffer,
681                                                     strlen (linebuffer));
682       readline_input_state.linebuffer_ptr = p;
683
684       /* We will not invoke a execute_command if there is more
685          input expected to complete the command. So, we need to
686          print an empty prompt here. */
687       more_to_come = 1;
688       push_prompt ("", "", "");
689       display_gdb_prompt (0);
690       return;
691     }
692
693 #ifdef STOP_SIGNAL
694   if (job_control)
695     signal (STOP_SIGNAL, SIG_DFL);
696 #endif
697
698 #define SERVER_COMMAND_LENGTH 7
699   server_command =
700     (p - linebuffer > SERVER_COMMAND_LENGTH)
701     && strncmp (linebuffer, "server ", SERVER_COMMAND_LENGTH) == 0;
702   if (server_command)
703     {
704       /* Note that we don't set `line'.  Between this and the check in
705          dont_repeat, this insures that repeating will still do the
706          right thing.  */
707       *p = '\0';
708       command_handler (linebuffer + SERVER_COMMAND_LENGTH);
709       display_gdb_prompt (0);
710       return;
711     }
712
713   /* Do history expansion if that is wished.  */
714   if (history_expansion_p && instream == stdin
715       && ISATTY (instream))
716     {
717       char *history_value;
718       int expanded;
719
720       *p = '\0';                /* Insert null now.  */
721       expanded = history_expand (linebuffer, &history_value);
722       if (expanded)
723         {
724           /* Print the changes.  */
725           printf_unfiltered ("%s\n", history_value);
726
727           /* If there was an error, call this function again.  */
728           if (expanded < 0)
729             {
730               xfree (history_value);
731               return;
732             }
733           if (strlen (history_value) > linelength)
734             {
735               linelength = strlen (history_value) + 1;
736               linebuffer = (char *) xrealloc (linebuffer, linelength);
737             }
738           strcpy (linebuffer, history_value);
739           p = linebuffer + strlen (linebuffer);
740           xfree (history_value);
741         }
742     }
743
744   /* If we just got an empty line, and that is supposed
745      to repeat the previous command, return the value in the
746      global buffer.  */
747   if (repeat && p == linebuffer && *p != '\\')
748     {
749       command_handler (line);
750       display_gdb_prompt (0);
751       return;
752     }
753
754   for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
755   if (repeat && !*p1)
756     {
757       command_handler (line);
758       display_gdb_prompt (0);
759       return;
760     }
761
762   *p = 0;
763
764   /* Add line to history if appropriate.  */
765   if (instream == stdin
766       && ISATTY (stdin) && *linebuffer)
767     add_history (linebuffer);
768
769   /* Note: lines consisting solely of comments are added to the command
770      history.  This is useful when you type a command, and then
771      realize you don't want to execute it quite yet.  You can comment
772      out the command and then later fetch it from the value history
773      and remove the '#'.  The kill ring is probably better, but some
774      people are in the habit of commenting things out.  */
775   if (*p1 == '#')
776     *p1 = '\0';                 /* Found a comment. */
777
778   /* Save into global buffer if appropriate.  */
779   if (repeat)
780     {
781       if (linelength > linesize)
782         {
783           line = xrealloc (line, linelength);
784           linesize = linelength;
785         }
786       strcpy (line, linebuffer);
787       if (!more_to_come)
788         {
789           command_handler (line);
790           display_gdb_prompt (0);
791         }
792       return;
793     }
794
795   command_handler (linebuffer);
796   display_gdb_prompt (0);
797   return;
798 }
799
800 /* Does reading of input from terminal w/o the editing features
801    provided by the readline library. */
802
803 /* NOTE: 1999-04-30 Asynchronous version of gdb_readline. gdb_readline
804    will become obsolete when the event loop is made the default
805    execution for gdb. */
806 void
807 gdb_readline2 (gdb_client_data client_data)
808 {
809   int c;
810   char *result;
811   int input_index = 0;
812   int result_size = 80;
813   static int done_once = 0;
814
815   /* Unbuffer the input stream, so that, later on, the calls to fgetc
816      fetch only one char at the time from the stream. The fgetc's will
817      get up to the first newline, but there may be more chars in the
818      stream after '\n'. If we buffer the input and fgetc drains the
819      stream, getting stuff beyond the newline as well, a select, done
820      afterwards will not trigger. */
821   if (!done_once && !ISATTY (instream))
822     {
823       setbuf (instream, NULL);
824       done_once = 1;
825     }
826
827   result = (char *) xmalloc (result_size);
828
829   /* We still need the while loop here, even though it would seem
830      obvious to invoke gdb_readline2 at every character entered.  If
831      not using the readline library, the terminal is in cooked mode,
832      which sends the characters all at once. Poll will notice that the
833      input fd has changed state only after enter is pressed. At this
834      point we still need to fetch all the chars entered. */
835
836   while (1)
837     {
838       /* Read from stdin if we are executing a user defined command.
839          This is the right thing for prompt_for_continue, at least.  */
840       c = fgetc (instream ? instream : stdin);
841
842       if (c == EOF)
843         {
844           if (input_index > 0)
845             /* The last line does not end with a newline.  Return it, and
846                if we are called again fgetc will still return EOF and
847                we'll return NULL then.  */
848             break;
849           xfree (result);
850           (*input_handler) (0);
851         }
852
853       if (c == '\n')
854         {
855           if (input_index > 0 && result[input_index - 1] == '\r')
856             input_index--;
857           break;
858         }
859
860       result[input_index++] = c;
861       while (input_index >= result_size)
862         {
863           result_size *= 2;
864           result = (char *) xrealloc (result, result_size);
865         }
866     }
867
868   result[input_index++] = '\0';
869   (*input_handler) (result);
870 }
871 \f
872
873 /* Initialization of signal handlers and tokens.  There is a function
874    handle_sig* for each of the signals GDB cares about. Specifically:
875    SIGINT, SIGFPE, SIGQUIT, SIGTSTP, SIGHUP, SIGWINCH.  These
876    functions are the actual signal handlers associated to the signals
877    via calls to signal().  The only job for these functions is to
878    enqueue the appropriate event/procedure with the event loop.  Such
879    procedures are the old signal handlers. The event loop will take
880    care of invoking the queued procedures to perform the usual tasks
881    associated with the reception of the signal. */
882 /* NOTE: 1999-04-30 This is the asynchronous version of init_signals.
883    init_signals will become obsolete as we move to have to event loop
884    as the default for gdb. */
885 void
886 async_init_signals (void)
887 {
888   signal (SIGINT, handle_sigint);
889   sigint_token =
890     create_async_signal_handler (async_request_quit, NULL);
891
892   /* If SIGTRAP was set to SIG_IGN, then the SIG_IGN will get passed
893      to the inferior and breakpoints will be ignored.  */
894 #ifdef SIGTRAP
895   signal (SIGTRAP, SIG_DFL);
896 #endif
897
898   /* If we initialize SIGQUIT to SIG_IGN, then the SIG_IGN will get
899      passed to the inferior, which we don't want.  It would be
900      possible to do a "signal (SIGQUIT, SIG_DFL)" after we fork, but
901      on BSD4.3 systems using vfork, that can affect the
902      GDB process as well as the inferior (the signal handling tables
903      might be in memory, shared between the two).  Since we establish
904      a handler for SIGQUIT, when we call exec it will set the signal
905      to SIG_DFL for us.  */
906   signal (SIGQUIT, handle_sigquit);
907   sigquit_token =
908     create_async_signal_handler (async_do_nothing, NULL);
909 #ifdef SIGHUP
910   if (signal (SIGHUP, handle_sighup) != SIG_IGN)
911     sighup_token =
912       create_async_signal_handler (async_disconnect, NULL);
913   else
914     sighup_token =
915       create_async_signal_handler (async_do_nothing, NULL);
916 #endif
917   signal (SIGFPE, handle_sigfpe);
918   sigfpe_token =
919     create_async_signal_handler (async_float_handler, NULL);
920
921 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
922   signal (SIGWINCH, handle_sigwinch);
923   sigwinch_token =
924     create_async_signal_handler (SIGWINCH_HANDLER, NULL);
925 #endif
926 #ifdef STOP_SIGNAL
927   sigtstp_token =
928     create_async_signal_handler (async_stop_sig, NULL);
929 #endif
930
931 }
932
933 void
934 mark_async_signal_handler_wrapper (void *token)
935 {
936   mark_async_signal_handler ((struct async_signal_handler *) token);
937 }
938
939 /* Tell the event loop what to do if SIGINT is received. 
940    See event-signal.c. */
941 void
942 handle_sigint (int sig)
943 {
944   signal (sig, handle_sigint);
945
946   /* If immediate_quit is set, we go ahead and process the SIGINT right
947      away, even if we usually would defer this to the event loop. The
948      assumption here is that it is safe to process ^C immediately if
949      immediate_quit is set. If we didn't, SIGINT would be really
950      processed only the next time through the event loop.  To get to
951      that point, though, the command that we want to interrupt needs to
952      finish first, which is unacceptable. */
953   if (immediate_quit)
954     async_request_quit (0);
955   else
956     /* If immediate quit is not set, we process SIGINT the next time
957        through the loop, which is fine. */
958     mark_async_signal_handler_wrapper (sigint_token);
959 }
960
961 /* Do the quit. All the checks have been done by the caller. */
962 void
963 async_request_quit (gdb_client_data arg)
964 {
965   quit_flag = 1;
966   quit ();
967 }
968
969 /* Tell the event loop what to do if SIGQUIT is received. 
970    See event-signal.c. */
971 static void
972 handle_sigquit (int sig)
973 {
974   mark_async_signal_handler_wrapper (sigquit_token);
975   signal (sig, handle_sigquit);
976 }
977
978 /* Called by the event loop in response to a SIGQUIT. */
979 static void
980 async_do_nothing (gdb_client_data arg)
981 {
982   /* Empty function body. */
983 }
984
985 #ifdef SIGHUP
986 /* Tell the event loop what to do if SIGHUP is received. 
987    See event-signal.c. */
988 static void
989 handle_sighup (int sig)
990 {
991   mark_async_signal_handler_wrapper (sighup_token);
992   signal (sig, handle_sighup);
993 }
994
995 /* Called by the event loop to process a SIGHUP */
996 static void
997 async_disconnect (gdb_client_data arg)
998 {
999   catch_errors (quit_cover, NULL,
1000                 "Could not kill the program being debugged",
1001                 RETURN_MASK_ALL);
1002   signal (SIGHUP, SIG_DFL);     /*FIXME: ??????????? */
1003   kill (getpid (), SIGHUP);
1004 }
1005 #endif
1006
1007 #ifdef STOP_SIGNAL
1008 void
1009 handle_stop_sig (int sig)
1010 {
1011   mark_async_signal_handler_wrapper (sigtstp_token);
1012   signal (sig, handle_stop_sig);
1013 }
1014
1015 static void
1016 async_stop_sig (gdb_client_data arg)
1017 {
1018   char *prompt = get_prompt ();
1019 #if STOP_SIGNAL == SIGTSTP
1020   signal (SIGTSTP, SIG_DFL);
1021 #if HAVE_SIGPROCMASK
1022   {
1023     sigset_t zero;
1024
1025     sigemptyset (&zero);
1026     sigprocmask (SIG_SETMASK, &zero, 0);
1027   }
1028 #elif HAVE_SIGSETMASK
1029   sigsetmask (0);
1030 #endif
1031   kill (getpid (), SIGTSTP);
1032   signal (SIGTSTP, handle_stop_sig);
1033 #else
1034   signal (STOP_SIGNAL, handle_stop_sig);
1035 #endif
1036   printf_unfiltered ("%s", prompt);
1037   gdb_flush (gdb_stdout);
1038
1039   /* Forget about any previous command -- null line now will do nothing.  */
1040   dont_repeat ();
1041 }
1042 #endif /* STOP_SIGNAL */
1043
1044 /* Tell the event loop what to do if SIGFPE is received. 
1045    See event-signal.c. */
1046 static void
1047 handle_sigfpe (int sig)
1048 {
1049   mark_async_signal_handler_wrapper (sigfpe_token);
1050   signal (sig, handle_sigfpe);
1051 }
1052
1053 /* Event loop will call this functin to process a SIGFPE. */
1054 static void
1055 async_float_handler (gdb_client_data arg)
1056 {
1057   /* This message is based on ANSI C, section 4.7. Note that integer
1058      divide by zero causes this, so "float" is a misnomer. */
1059   error (_("Erroneous arithmetic operation."));
1060 }
1061
1062 /* Tell the event loop what to do if SIGWINCH is received. 
1063    See event-signal.c. */
1064 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1065 static void
1066 handle_sigwinch (int sig)
1067 {
1068   mark_async_signal_handler_wrapper (sigwinch_token);
1069   signal (sig, handle_sigwinch);
1070 }
1071 #endif
1072 \f
1073
1074 /* Called by do_setshow_command.  */
1075 void
1076 set_async_editing_command (char *args, int from_tty, struct cmd_list_element *c)
1077 {
1078   change_line_handler ();
1079 }
1080
1081 /* Called by do_setshow_command.  */
1082 void
1083 set_async_annotation_level (char *args, int from_tty, struct cmd_list_element *c)
1084 {
1085   change_annotation_level ();
1086 }
1087
1088 /* Called by do_setshow_command.  */
1089 void
1090 set_async_prompt (char *args, int from_tty, struct cmd_list_element *c)
1091 {
1092   PROMPT (0) = savestring (new_async_prompt, strlen (new_async_prompt));
1093 }
1094
1095 /* Set things up for readline to be invoked via the alternate
1096    interface, i.e. via a callback function (rl_callback_read_char),
1097    and hook up instream to the event loop. */
1098 void
1099 gdb_setup_readline (void)
1100 {
1101   /* This function is a noop for the sync case.  The assumption is
1102      that the sync setup is ALL done in gdb_init, and we would only
1103      mess it up here.  The sync stuff should really go away over
1104      time.  */
1105
1106   gdb_stdout = stdio_fileopen (stdout);
1107   gdb_stderr = stdio_fileopen (stderr);
1108   gdb_stdlog = gdb_stderr;  /* for moment */
1109   gdb_stdtarg = gdb_stderr; /* for moment */
1110
1111   /* If the input stream is connected to a terminal, turn on
1112      editing.  */
1113   if (ISATTY (instream))
1114     {
1115       /* Tell gdb that we will be using the readline library. This
1116          could be overwritten by a command in .gdbinit like 'set
1117          editing on' or 'off'.  */
1118       async_command_editing_p = 1;
1119           
1120       /* When a character is detected on instream by select or poll,
1121          readline will be invoked via this callback function.  */
1122       call_readline = rl_callback_read_char_wrapper;
1123     }
1124   else
1125     {
1126       async_command_editing_p = 0;
1127       call_readline = gdb_readline2;
1128     }
1129   
1130   /* When readline has read an end-of-line character, it passes the
1131      complete line to gdb for processing. command_line_handler is the
1132      function that does this.  */
1133   input_handler = command_line_handler;
1134       
1135   /* Tell readline to use the same input stream that gdb uses. */
1136   rl_instream = instream;
1137
1138   /* Get a file descriptor for the input stream, so that we can
1139      register it with the event loop.  */
1140   input_fd = fileno (instream);
1141
1142   /* Now we need to create the event sources for the input file
1143      descriptor.  */
1144   /* At this point in time, this is the only event source that we
1145      register with the even loop. Another source is going to be the
1146      target program (inferior), but that must be registered only when
1147      it actually exists (I.e. after we say 'run' or after we connect
1148      to a remote target.  */
1149   add_file_handler (input_fd, stdin_event_handler, 0);
1150 }
1151
1152 /* Disable command input through the standard CLI channels.  Used in
1153    the suspend proc for interpreters that use the standard gdb readline
1154    interface, like the cli & the mi.  */
1155 void
1156 gdb_disable_readline (void)
1157 {
1158   /* FIXME - It is too heavyweight to delete and remake these every
1159      time you run an interpreter that needs readline.  It is probably
1160      better to have the interpreters cache these, which in turn means
1161      that this needs to be moved into interpreter specific code.  */
1162
1163 #if 0
1164   ui_file_delete (gdb_stdout);
1165   ui_file_delete (gdb_stderr);
1166   gdb_stdlog = NULL;
1167   gdb_stdtarg = NULL;
1168 #endif
1169
1170   rl_callback_handler_remove ();
1171   delete_file_handler (input_fd);
1172 }