OSDN Git Service

Remove obsolete MacOS support.
[pf3gnuchains/pf3gnuchains3x.git] / gdb / event-top.c
1 /* Top level stuff for GDB, the GNU debugger.
2    Copyright 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
3    Written by Elena Zannoni <ezannoni@cygnus.com> of Cygnus Solutions.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA. */
21
22 #include "defs.h"
23 #include "top.h"
24 #include "inferior.h"
25 #include "target.h"
26 #include "terminal.h"           /* for job_control */
27 #include "event-loop.h"
28 #include "event-top.h"
29 #include <signal.h>
30
31 /* For dont_repeat() */
32 #include "gdbcmd.h"
33
34 /* readline include files */
35 #include <readline/readline.h>
36 #include <readline/history.h>
37
38 /* readline defines this.  */
39 #undef savestring
40
41 extern void _initialize_event_loop (void);
42
43 static void rl_callback_read_char_wrapper (gdb_client_data client_data);
44 static void command_line_handler (char *rl);
45 static void command_line_handler_continuation (struct continuation_arg *arg);
46 static void change_line_handler (void);
47 static void change_annotation_level (void);
48 static void command_handler (char *command);
49 void cli_command_loop (void);
50 static void async_do_nothing (gdb_client_data arg);
51 static void async_disconnect (gdb_client_data arg);
52 static void async_stop_sig (gdb_client_data arg);
53 static void async_float_handler (gdb_client_data arg);
54
55 /* Signal handlers. */
56 static void handle_sigquit (int sig);
57 static void handle_sighup (int sig);
58 static void handle_sigfpe (int sig);
59 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
60 static void handle_sigwinch (int sig);
61 #endif
62
63 /* Functions to be invoked by the event loop in response to
64    signals. */
65 static void async_do_nothing (gdb_client_data);
66 static void async_disconnect (gdb_client_data);
67 static void async_float_handler (gdb_client_data);
68 static void async_stop_sig (gdb_client_data);
69
70 /* Readline offers an alternate interface, via callback
71    functions. These are all included in the file callback.c in the
72    readline distribution.  This file provides (mainly) a function, which
73    the event loop uses as callback (i.e. event handler) whenever an event
74    is detected on the standard input file descriptor.
75    readline_callback_read_char is called (by the GDB event loop) whenever
76    there is a new character ready on the input stream. This function
77    incrementally builds a buffer internal to readline where it
78    accumulates the line read up to the point of invocation.  In the
79    special case in which the character read is newline, the function
80    invokes a GDB supplied callback routine, which does the processing of
81    a full command line.  This latter routine is the asynchronous analog
82    of the old command_line_input in gdb. Instead of invoking (and waiting
83    for) readline to read the command line and pass it back to
84    command_loop for processing, the new command_line_handler function has
85    the command line already available as its parameter.  INPUT_HANDLER is
86    to be set to the function that readline will invoke when a complete
87    line of input is ready.  CALL_READLINE is to be set to the function
88    that readline offers as callback to the event_loop. */
89
90 void (*input_handler) (char *);
91 void (*call_readline) (gdb_client_data);
92
93 /* Important variables for the event loop. */
94
95 /* This is used to determine if GDB is using the readline library or
96    its own simplified form of readline. It is used by the asynchronous
97    form of the set editing command.
98    ezannoni: as of 1999-04-29 I expect that this
99    variable will not be used after gdb is changed to use the event
100    loop as default engine, and event-top.c is merged into top.c. */
101 int async_command_editing_p;
102
103 /* This variable contains the new prompt that the user sets with the
104    set prompt command. */
105 char *new_async_prompt;
106
107 /* This is the annotation suffix that will be used when the
108    annotation_level is 2. */
109 char *async_annotation_suffix;
110
111 /* This is used to display the notification of the completion of an
112    asynchronous execution command. */
113 int exec_done_display_p = 0;
114
115 /* This is the file descriptor for the input stream that GDB uses to
116    read commands from. */
117 int input_fd;
118
119 /* This is the prompt stack. Prompts will be pushed on the stack as
120    needed by the different 'kinds' of user inputs GDB is asking
121    for. See event-loop.h. */
122 struct prompts the_prompts;
123
124 /* signal handling variables */
125 /* Each of these is a pointer to a function that the event loop will
126    invoke if the corresponding signal has received. The real signal
127    handlers mark these functions as ready to be executed and the event
128    loop, in a later iteration, calls them. See the function
129    invoke_async_signal_handler. */
130 void *sigint_token;
131 #ifdef SIGHUP
132 void *sighup_token;
133 #endif
134 void *sigquit_token;
135 void *sigfpe_token;
136 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
137 void *sigwinch_token;
138 #endif
139 #ifdef STOP_SIGNAL
140 void *sigtstp_token;
141 #endif
142
143 /* Structure to save a partially entered command.  This is used when
144    the user types '\' at the end of a command line. This is necessary
145    because each line of input is handled by a different call to
146    command_line_handler, and normally there is no state retained
147    between different calls. */
148 int more_to_come = 0;
149
150 struct readline_input_state
151   {
152     char *linebuffer;
153     char *linebuffer_ptr;
154   }
155 readline_input_state;
156
157 /* This hook is called by rl_callback_read_char_wrapper after each
158    character is processed.  */
159 void (*after_char_processing_hook) ();
160 \f
161
162 /* Wrapper function for calling into the readline library. The event
163    loop expects the callback function to have a paramter, while readline 
164    expects none. */
165 static void
166 rl_callback_read_char_wrapper (gdb_client_data client_data)
167 {
168   rl_callback_read_char ();
169   if (after_char_processing_hook)
170     (*after_char_processing_hook) ();
171 }
172
173 /* Initialize all the necessary variables, start the event loop,
174    register readline, and stdin, start the loop. */
175 void
176 cli_command_loop (void)
177 {
178   int length;
179   char *a_prompt;
180   char *gdb_prompt = get_prompt ();
181
182   /* If we are using readline, set things up and display the first
183      prompt, otherwise just print the prompt. */
184   if (async_command_editing_p)
185     {
186       /* Tell readline what the prompt to display is and what function it
187          will need to call after a whole line is read. This also displays
188          the first prompt. */
189       length = strlen (PREFIX (0)) + strlen (gdb_prompt) + strlen (SUFFIX (0)) + 1;
190       a_prompt = (char *) xmalloc (length);
191       strcpy (a_prompt, PREFIX (0));
192       strcat (a_prompt, gdb_prompt);
193       strcat (a_prompt, SUFFIX (0));
194       rl_callback_handler_install (a_prompt, input_handler);
195     }
196   else
197     display_gdb_prompt (0);
198
199   /* Now it's time to start the event loop. */
200   start_event_loop ();
201 }
202
203 /* Change the function to be invoked every time there is a character
204    ready on stdin. This is used when the user sets the editing off,
205    therefore bypassing readline, and letting gdb handle the input
206    itself, via gdb_readline2. Also it is used in the opposite case in
207    which the user sets editing on again, by restoring readline
208    handling of the input. */
209 static void
210 change_line_handler (void)
211 {
212   /* NOTE: this operates on input_fd, not instream. If we are reading
213      commands from a file, instream will point to the file. However in
214      async mode, we always read commands from a file with editing
215      off. This means that the 'set editing on/off' will have effect
216      only on the interactive session. */
217
218   if (async_command_editing_p)
219     {
220       /* Turn on editing by using readline. */
221       call_readline = rl_callback_read_char_wrapper;
222       input_handler = command_line_handler;
223     }
224   else
225     {
226       /* Turn off editing by using gdb_readline2. */
227       rl_callback_handler_remove ();
228       call_readline = gdb_readline2;
229
230       /* Set up the command handler as well, in case we are called as
231          first thing from .gdbinit. */
232       input_handler = command_line_handler;
233     }
234 }
235
236 /* Displays the prompt. The prompt that is displayed is the current
237    top of the prompt stack, if the argument NEW_PROMPT is
238    0. Otherwise, it displays whatever NEW_PROMPT is. This is used
239    after each gdb command has completed, and in the following cases:
240    1. when the user enters a command line which is ended by '\'
241    indicating that the command will continue on the next line.
242    In that case the prompt that is displayed is the empty string.
243    2. When the user is entering 'commands' for a breakpoint, or
244    actions for a tracepoint. In this case the prompt will be '>'
245    3. Other????
246    FIXME: 2. & 3. not implemented yet for async. */
247 void
248 display_gdb_prompt (char *new_prompt)
249 {
250   int prompt_length = 0;
251   char *gdb_prompt = get_prompt ();
252
253 #ifdef UI_OUT
254   /* When an alternative interpreter has been installed, do not
255      display the comand prompt. */
256   if (interpreter_p)
257     return;
258 #endif
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       extern char **environ;
500       char *lim = (char *) sbrk (0);
501
502       space_at_cmd_start = (long) (lim - (char *) &environ);
503 #endif
504     }
505
506   execute_command (command, instream == stdin);
507
508   /* Set things up for this function to be compete later, once the
509      execution has completed, if we are doing an execution command,
510      otherwise, just go ahead and finish. */
511   if (target_can_async_p () && target_executing)
512     {
513       arg1 =
514         (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg));
515       arg2 =
516         (struct continuation_arg *) xmalloc (sizeof (struct continuation_arg));
517       arg1->next = arg2;
518       arg2->next = NULL;
519       arg1->data.integer = time_at_cmd_start;
520       arg2->data.integer = space_at_cmd_start;
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           extern char **environ;
544           char *lim = (char *) sbrk (0);
545           long space_now = lim - (char *) &environ;
546           long space_diff = space_now - space_at_cmd_start;
547
548           printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
549                              space_now,
550                              (space_diff >= 0 ? '+' : '-'),
551                              space_diff);
552 #endif
553         }
554     }
555 }
556
557 /* Do any commands attached to breakpoint we stopped at. Only if we
558    are always running synchronously. Or if we have just executed a
559    command that doesn't start the target. */
560 void
561 command_line_handler_continuation (struct continuation_arg *arg)
562 {
563   extern int display_time;
564   extern int display_space;
565
566   long time_at_cmd_start  = arg->data.longint;
567   long space_at_cmd_start = arg->next->data.longint;
568
569   bpstat_do_actions (&stop_bpstat);
570   /*do_cleanups (old_chain); *//*?????FIXME????? */
571
572   if (display_time)
573     {
574       long cmd_time = get_run_time () - time_at_cmd_start;
575
576       printf_unfiltered ("Command execution time: %ld.%06ld\n",
577                          cmd_time / 1000000, cmd_time % 1000000);
578     }
579   if (display_space)
580     {
581 #ifdef HAVE_SBRK
582       extern char **environ;
583       char *lim = (char *) sbrk (0);
584       long space_now = lim - (char *) &environ;
585       long space_diff = space_now - space_at_cmd_start;
586
587       printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
588                          space_now,
589                          (space_diff >= 0 ? '+' : '-'),
590                          space_diff);
591 #endif
592     }
593 }
594
595 /* Handle a complete line of input. This is called by the callback
596    mechanism within the readline library.  Deal with incomplete commands
597    as well, by saving the partial input in a global buffer.  */
598
599 /* NOTE: 1999-04-30 This is the asynchronous version of the
600    command_line_input function. command_line_input will become
601    obsolete once we use the event loop as the default mechanism in
602    GDB. */
603 static void
604 command_line_handler (char *rl)
605 {
606   static char *linebuffer = 0;
607   static unsigned linelength = 0;
608   register char *p;
609   char *p1;
610   extern char *line;
611   extern int linesize;
612   char *nline;
613   char got_eof = 0;
614
615
616   int repeat = (instream == stdin);
617
618   if (annotation_level > 1 && instream == stdin)
619     {
620       printf_unfiltered ("\n\032\032post-");
621       printf_unfiltered (async_annotation_suffix);
622       printf_unfiltered ("\n");
623     }
624
625   if (linebuffer == 0)
626     {
627       linelength = 80;
628       linebuffer = (char *) xmalloc (linelength);
629     }
630
631   p = linebuffer;
632
633   if (more_to_come)
634     {
635       strcpy (linebuffer, readline_input_state.linebuffer);
636       p = readline_input_state.linebuffer_ptr;
637       xfree (readline_input_state.linebuffer);
638       more_to_come = 0;
639       pop_prompt ();
640     }
641
642 #ifdef STOP_SIGNAL
643   if (job_control)
644     signal (STOP_SIGNAL, handle_stop_sig);
645 #endif
646
647   /* Make sure that all output has been output.  Some machines may let
648      you get away with leaving out some of the gdb_flush, but not all.  */
649   wrap_here ("");
650   gdb_flush (gdb_stdout);
651   gdb_flush (gdb_stderr);
652
653   if (source_file_name != NULL)
654     {
655       ++source_line_number;
656       sprintf (source_error,
657                "%s%s:%d: Error in sourced command file:\n",
658                source_pre_error,
659                source_file_name,
660                source_line_number);
661       error_pre_print = source_error;
662     }
663
664   /* If we are in this case, then command_handler will call quit 
665      and exit from gdb. */
666   if (!rl || rl == (char *) EOF)
667     {
668       got_eof = 1;
669       command_handler (0);
670     }
671   if (strlen (rl) + 1 + (p - linebuffer) > linelength)
672     {
673       linelength = strlen (rl) + 1 + (p - linebuffer);
674       nline = (char *) xrealloc (linebuffer, linelength);
675       p += nline - linebuffer;
676       linebuffer = nline;
677     }
678   p1 = rl;
679   /* Copy line.  Don't copy null at end.  (Leaves line alone
680      if this was just a newline)  */
681   while (*p1)
682     *p++ = *p1++;
683
684   xfree (rl);                   /* Allocated in readline.  */
685
686   if (*(p - 1) == '\\')
687     {
688       p--;                      /* Put on top of '\'.  */
689
690       if (*p == '\\')
691         {
692           readline_input_state.linebuffer = savestring (linebuffer,
693                                                         strlen (linebuffer));
694           readline_input_state.linebuffer_ptr = p;
695
696           /* We will not invoke a execute_command if there is more
697              input expected to complete the command. So, we need to
698              print an empty prompt here. */
699           more_to_come = 1;
700           push_prompt ("", "", "");
701           display_gdb_prompt (0);
702           return;
703         }
704     }
705
706 #ifdef STOP_SIGNAL
707   if (job_control)
708     signal (STOP_SIGNAL, SIG_DFL);
709 #endif
710
711 #define SERVER_COMMAND_LENGTH 7
712   server_command =
713     (p - linebuffer > SERVER_COMMAND_LENGTH)
714     && STREQN (linebuffer, "server ", SERVER_COMMAND_LENGTH);
715   if (server_command)
716     {
717       /* Note that we don't set `line'.  Between this and the check in
718          dont_repeat, this insures that repeating will still do the
719          right thing.  */
720       *p = '\0';
721       command_handler (linebuffer + SERVER_COMMAND_LENGTH);
722       display_gdb_prompt (0);
723       return;
724     }
725
726   /* Do history expansion if that is wished.  */
727   if (history_expansion_p && instream == stdin
728       && ISATTY (instream))
729     {
730       char *history_value;
731       int expanded;
732
733       *p = '\0';                /* Insert null now.  */
734       expanded = history_expand (linebuffer, &history_value);
735       if (expanded)
736         {
737           /* Print the changes.  */
738           printf_unfiltered ("%s\n", history_value);
739
740           /* If there was an error, call this function again.  */
741           if (expanded < 0)
742             {
743               xfree (history_value);
744               return;
745             }
746           if (strlen (history_value) > linelength)
747             {
748               linelength = strlen (history_value) + 1;
749               linebuffer = (char *) xrealloc (linebuffer, linelength);
750             }
751           strcpy (linebuffer, history_value);
752           p = linebuffer + strlen (linebuffer);
753           xfree (history_value);
754         }
755     }
756
757   /* If we just got an empty line, and that is supposed
758      to repeat the previous command, return the value in the
759      global buffer.  */
760   if (repeat && p == linebuffer && *p != '\\')
761     {
762       command_handler (line);
763       display_gdb_prompt (0);
764       return;
765     }
766
767   for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
768   if (repeat && !*p1)
769     {
770       command_handler (line);
771       display_gdb_prompt (0);
772       return;
773     }
774
775   *p = 0;
776
777   /* Add line to history if appropriate.  */
778   if (instream == stdin
779       && ISATTY (stdin) && *linebuffer)
780     add_history (linebuffer);
781
782   /* Note: lines consisting solely of comments are added to the command
783      history.  This is useful when you type a command, and then
784      realize you don't want to execute it quite yet.  You can comment
785      out the command and then later fetch it from the value history
786      and remove the '#'.  The kill ring is probably better, but some
787      people are in the habit of commenting things out.  */
788   if (*p1 == '#')
789     *p1 = '\0';                 /* Found a comment. */
790
791   /* Save into global buffer if appropriate.  */
792   if (repeat)
793     {
794       if (linelength > linesize)
795         {
796           line = xrealloc (line, linelength);
797           linesize = linelength;
798         }
799       strcpy (line, linebuffer);
800       if (!more_to_come)
801         {
802           command_handler (line);
803           display_gdb_prompt (0);
804         }
805       return;
806     }
807
808   command_handler (linebuffer);
809   display_gdb_prompt (0);
810   return;
811 }
812
813 /* Does reading of input from terminal w/o the editing features
814    provided by the readline library. */
815
816 /* NOTE: 1999-04-30 Asynchronous version of gdb_readline. gdb_readline
817    will become obsolete when the event loop is made the default
818    execution for gdb. */
819 void
820 gdb_readline2 (gdb_client_data client_data)
821 {
822   int c;
823   char *result;
824   int input_index = 0;
825   int result_size = 80;
826   static int done_once = 0;
827
828   /* Unbuffer the input stream, so that, later on, the calls to fgetc
829      fetch only one char at the time from the stream. The fgetc's will
830      get up to the first newline, but there may be more chars in the
831      stream after '\n'. If we buffer the input and fgetc drains the
832      stream, getting stuff beyond the newline as well, a select, done
833      afterwards will not trigger. */
834   if (!done_once && !ISATTY (instream))
835     {
836       setbuf (instream, NULL);
837       done_once = 1;
838     }
839
840   result = (char *) xmalloc (result_size);
841
842   /* We still need the while loop here, even though it would seem
843      obvious to invoke gdb_readline2 at every character entered.  If
844      not using the readline library, the terminal is in cooked mode,
845      which sends the characters all at once. Poll will notice that the
846      input fd has changed state only after enter is pressed. At this
847      point we still need to fetch all the chars entered. */
848
849   while (1)
850     {
851       /* Read from stdin if we are executing a user defined command.
852          This is the right thing for prompt_for_continue, at least.  */
853       c = fgetc (instream ? instream : stdin);
854
855       if (c == EOF)
856         {
857           if (input_index > 0)
858             /* The last line does not end with a newline.  Return it, and
859                if we are called again fgetc will still return EOF and
860                we'll return NULL then.  */
861             break;
862           xfree (result);
863           (*input_handler) (0);
864         }
865
866       if (c == '\n')
867 #ifndef CRLF_SOURCE_FILES
868         break;
869 #else
870         {
871           if (input_index > 0 && result[input_index - 1] == '\r')
872             input_index--;
873           break;
874         }
875 #endif
876
877       result[input_index++] = c;
878       while (input_index >= result_size)
879         {
880           result_size *= 2;
881           result = (char *) xrealloc (result, result_size);
882         }
883     }
884
885   result[input_index++] = '\0';
886   (*input_handler) (result);
887 }
888 \f
889
890 /* Initialization of signal handlers and tokens.  There is a function
891    handle_sig* for each of the signals GDB cares about. Specifically:
892    SIGINT, SIGFPE, SIGQUIT, SIGTSTP, SIGHUP, SIGWINCH.  These
893    functions are the actual signal handlers associated to the signals
894    via calls to signal().  The only job for these functions is to
895    enqueue the appropriate event/procedure with the event loop.  Such
896    procedures are the old signal handlers. The event loop will take
897    care of invoking the queued procedures to perform the usual tasks
898    associated with the reception of the signal. */
899 /* NOTE: 1999-04-30 This is the asynchronous version of init_signals.
900    init_signals will become obsolete as we move to have to event loop
901    as the default for gdb. */
902 void
903 async_init_signals (void)
904 {
905   signal (SIGINT, handle_sigint);
906   sigint_token =
907     create_async_signal_handler (async_request_quit, NULL);
908
909   /* If SIGTRAP was set to SIG_IGN, then the SIG_IGN will get passed
910      to the inferior and breakpoints will be ignored.  */
911 #ifdef SIGTRAP
912   signal (SIGTRAP, SIG_DFL);
913 #endif
914
915   /* If we initialize SIGQUIT to SIG_IGN, then the SIG_IGN will get
916      passed to the inferior, which we don't want.  It would be
917      possible to do a "signal (SIGQUIT, SIG_DFL)" after we fork, but
918      on BSD4.3 systems using vfork, that can affect the
919      GDB process as well as the inferior (the signal handling tables
920      might be in memory, shared between the two).  Since we establish
921      a handler for SIGQUIT, when we call exec it will set the signal
922      to SIG_DFL for us.  */
923   signal (SIGQUIT, handle_sigquit);
924   sigquit_token =
925     create_async_signal_handler (async_do_nothing, NULL);
926 #ifdef SIGHUP
927   if (signal (SIGHUP, handle_sighup) != SIG_IGN)
928     sighup_token =
929       create_async_signal_handler (async_disconnect, NULL);
930   else
931     sighup_token =
932       create_async_signal_handler (async_do_nothing, NULL);
933 #endif
934   signal (SIGFPE, handle_sigfpe);
935   sigfpe_token =
936     create_async_signal_handler (async_float_handler, NULL);
937
938 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
939   signal (SIGWINCH, handle_sigwinch);
940   sigwinch_token =
941     create_async_signal_handler (SIGWINCH_HANDLER, NULL);
942 #endif
943 #ifdef STOP_SIGNAL
944   sigtstp_token =
945     create_async_signal_handler (async_stop_sig, NULL);
946 #endif
947
948 }
949
950 void
951 mark_async_signal_handler_wrapper (void *token)
952 {
953   mark_async_signal_handler ((struct async_signal_handler *) token);
954 }
955
956 /* Tell the event loop what to do if SIGINT is received. 
957    See event-signal.c. */
958 void
959 handle_sigint (int sig)
960 {
961   signal (sig, handle_sigint);
962
963   /* If immediate_quit is set, we go ahead and process the SIGINT right
964      away, even if we usually would defer this to the event loop. The
965      assumption here is that it is safe to process ^C immediately if
966      immediate_quit is set. If we didn't, SIGINT would be really
967      processed only the next time through the event loop.  To get to
968      that point, though, the command that we want to interrupt needs to
969      finish first, which is unacceptable. */
970   if (immediate_quit)
971     async_request_quit (0);
972   else
973     /* If immediate quit is not set, we process SIGINT the next time
974        through the loop, which is fine. */
975     mark_async_signal_handler_wrapper (sigint_token);
976 }
977
978 /* Do the quit. All the checks have been done by the caller. */
979 void
980 async_request_quit (gdb_client_data arg)
981 {
982   quit_flag = 1;
983 #ifdef REQUEST_QUIT
984   REQUEST_QUIT;
985 #else
986   quit ();
987 #endif
988 }
989
990 /* Tell the event loop what to do if SIGQUIT is received. 
991    See event-signal.c. */
992 static void
993 handle_sigquit (int sig)
994 {
995   mark_async_signal_handler_wrapper (sigquit_token);
996   signal (sig, handle_sigquit);
997 }
998
999 /* Called by the event loop in response to a SIGQUIT. */
1000 static void
1001 async_do_nothing (gdb_client_data arg)
1002 {
1003   /* Empty function body. */
1004 }
1005
1006 #ifdef SIGHUP
1007 /* Tell the event loop what to do if SIGHUP is received. 
1008    See event-signal.c. */
1009 static void
1010 handle_sighup (int sig)
1011 {
1012   mark_async_signal_handler_wrapper (sighup_token);
1013   signal (sig, handle_sighup);
1014 }
1015
1016 /* Called by the event loop to process a SIGHUP */
1017 static void
1018 async_disconnect (gdb_client_data arg)
1019 {
1020   catch_errors (quit_cover, NULL,
1021                 "Could not kill the program being debugged",
1022                 RETURN_MASK_ALL);
1023   signal (SIGHUP, SIG_DFL);     /*FIXME: ??????????? */
1024   kill (getpid (), SIGHUP);
1025 }
1026 #endif
1027
1028 #ifdef STOP_SIGNAL
1029 void
1030 handle_stop_sig (int sig)
1031 {
1032   mark_async_signal_handler_wrapper (sigtstp_token);
1033   signal (sig, handle_stop_sig);
1034 }
1035
1036 static void
1037 async_stop_sig (gdb_client_data arg)
1038 {
1039   char *prompt = get_prompt ();
1040 #if STOP_SIGNAL == SIGTSTP
1041   signal (SIGTSTP, SIG_DFL);
1042 #if HAVE_SIGPROCMASK
1043   {
1044     sigset_t zero;
1045
1046     sigemptyset (&zero);
1047     sigprocmask (SIG_SETMASK, &zero, 0);
1048   }
1049 #elif HAVE_SIGSETMASK
1050   sigsetmask (0);
1051 #endif
1052   kill (getpid (), SIGTSTP);
1053   signal (SIGTSTP, handle_stop_sig);
1054 #else
1055   signal (STOP_SIGNAL, handle_stop_sig);
1056 #endif
1057   printf_unfiltered ("%s", prompt);
1058   gdb_flush (gdb_stdout);
1059
1060   /* Forget about any previous command -- null line now will do nothing.  */
1061   dont_repeat ();
1062 }
1063 #endif /* STOP_SIGNAL */
1064
1065 /* Tell the event loop what to do if SIGFPE is received. 
1066    See event-signal.c. */
1067 static void
1068 handle_sigfpe (int sig)
1069 {
1070   mark_async_signal_handler_wrapper (sigfpe_token);
1071   signal (sig, handle_sigfpe);
1072 }
1073
1074 /* Event loop will call this functin to process a SIGFPE. */
1075 static void
1076 async_float_handler (gdb_client_data arg)
1077 {
1078   /* This message is based on ANSI C, section 4.7. Note that integer
1079      divide by zero causes this, so "float" is a misnomer. */
1080   error ("Erroneous arithmetic operation.");
1081 }
1082
1083 /* Tell the event loop what to do if SIGWINCH is received. 
1084    See event-signal.c. */
1085 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1086 static void
1087 handle_sigwinch (int sig)
1088 {
1089   mark_async_signal_handler_wrapper (sigwinch_token);
1090   signal (sig, handle_sigwinch);
1091 }
1092 #endif
1093 \f
1094
1095 /* Called by do_setshow_command.  */
1096 /* ARGSUSED */
1097 void
1098 set_async_editing_command (char *args, int from_tty, struct cmd_list_element *c)
1099 {
1100   change_line_handler ();
1101 }
1102
1103 /* Called by do_setshow_command.  */
1104 /* ARGSUSED */
1105 void
1106 set_async_annotation_level (char *args, int from_tty, struct cmd_list_element *c)
1107 {
1108   change_annotation_level ();
1109 }
1110
1111 /* Called by do_setshow_command.  */
1112 /* ARGSUSED */
1113 void
1114 set_async_prompt (char *args, int from_tty, struct cmd_list_element *c)
1115 {
1116   PROMPT (0) = savestring (new_async_prompt, strlen (new_async_prompt));
1117 }
1118
1119 /* Set things up for readline to be invoked via the alternate
1120    interface, i.e. via a callback function (rl_callback_read_char),
1121    and hook up instream to the event loop. */
1122 void
1123 _initialize_event_loop (void)
1124 {
1125   if (event_loop_p)
1126     {
1127       /* If the input stream is connected to a terminal, turn on
1128          editing.  */
1129       if (ISATTY (instream))
1130         {
1131           /* Tell gdb that we will be using the readline library. This
1132              could be overwritten by a command in .gdbinit like 'set
1133              editing on' or 'off'. */
1134           async_command_editing_p = 1;
1135           
1136           /* When a character is detected on instream by select or
1137              poll, readline will be invoked via this callback
1138              function. */
1139           call_readline = rl_callback_read_char_wrapper;
1140         }
1141       else
1142         {
1143           async_command_editing_p = 0;
1144           call_readline = gdb_readline2;
1145         }
1146
1147       /* When readline has read an end-of-line character, it passes
1148          the complete line to gdb for processing. command_line_handler
1149          is the function that does this. */
1150       input_handler = command_line_handler;
1151
1152       /* Tell readline to use the same input stream that gdb uses. */
1153       rl_instream = instream;
1154
1155       /* Get a file descriptor for the input stream, so that we can
1156          register it with the event loop. */
1157       input_fd = fileno (instream);
1158
1159       /* Tell gdb to use the cli_command_loop as the main loop. */
1160       command_loop_hook = cli_command_loop;
1161
1162       /* Now we need to create the event sources for the input file
1163          descriptor. */
1164       /* At this point in time, this is the only event source that we
1165          register with the even loop. Another source is going to be
1166          the target program (inferior), but that must be registered
1167          only when it actually exists (I.e. after we say 'run' or
1168          after we connect to a remote target. */
1169       add_file_handler (input_fd, stdin_event_handler, 0);
1170     }
1171 }