]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/gdb/gdb/top.c
MFV: r366539
[FreeBSD/FreeBSD.git] / contrib / gdb / gdb / top.c
1 /* Top level stuff for GDB, the GNU debugger.
2
3    Copyright 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994,
4    1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
5    Free Software Foundation, Inc.
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 2 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, write to the Free Software
21    Foundation, Inc., 59 Temple Place - Suite 330,
22    Boston, MA 02111-1307, USA.  */
23
24 #include "defs.h"
25 #include "gdbcmd.h"
26 #include "call-cmds.h"
27 #include "cli/cli-cmds.h"
28 #include "cli/cli-script.h"
29 #include "cli/cli-setshow.h"
30 #include "cli/cli-decode.h"
31 #include "symtab.h"
32 #include "inferior.h"
33 #include <signal.h>
34 #include "target.h"
35 #include "breakpoint.h"
36 #include "gdbtypes.h"
37 #include "expression.h"
38 #include "value.h"
39 #include "language.h"
40 #include "terminal.h"           /* For job_control.  */
41 #include "annotate.h"
42 #include "completer.h"
43 #include "top.h"
44 #include "version.h"
45 #include "serial.h"
46 #include "doublest.h"
47 #include "gdb_assert.h"
48
49 /* readline include files */
50 #include "readline/readline.h"
51
52 /* readline defines this.  */
53 #undef savestring
54
55 #include <sys/types.h>
56
57 #include <setjmp.h>
58
59 #include "event-top.h"
60 #include "gdb_string.h"
61 #include "gdb_stat.h"
62 #include <ctype.h>
63 #include "ui-out.h"
64 #include "cli-out.h"
65
66 /* Default command line prompt.  This is overriden in some configs. */
67
68 #ifndef DEFAULT_PROMPT
69 #define DEFAULT_PROMPT  "(gdb) "
70 #endif
71
72 /* Initialization file name for gdb.  This is overridden in some configs.  */
73
74 #ifndef GDBINIT_FILENAME
75 #define GDBINIT_FILENAME        ".gdbinit"
76 #endif
77 char gdbinit[] = GDBINIT_FILENAME;
78
79 int inhibit_gdbinit = 0;
80
81 /* If nonzero, and GDB has been configured to be able to use windows,
82    attempt to open them upon startup.  */
83
84 int use_windows = 0;
85
86 extern char lang_frame_mismatch_warn[];         /* language.c */
87
88 /* Flag for whether we want all the "from_tty" gubbish printed.  */
89
90 int caution = 1;                /* Default is yes, sigh. */
91
92 /* stdio stream that command input is being read from.  Set to stdin normally.
93    Set by source_command to the file we are sourcing.  Set to NULL if we are
94    executing a user-defined command or interacting via a GUI.  */
95
96 FILE *instream;
97
98 /* Current working directory.  */
99
100 char *current_directory;
101
102 /* The directory name is actually stored here (usually).  */
103 char gdb_dirbuf[1024];
104
105 /* Function to call before reading a command, if nonzero.
106    The function receives two args: an input stream,
107    and a prompt string.  */
108
109 void (*window_hook) (FILE *, char *);
110
111 int epoch_interface;
112 int xgdb_verbose;
113
114 /* gdb prints this when reading a command interactively */
115 static char *gdb_prompt_string; /* the global prompt string */
116
117 /* Buffer used for reading command lines, and the size
118    allocated for it so far.  */
119
120 char *line;
121 int linesize = 100;
122
123 /* Nonzero if the current command is modified by "server ".  This
124    affects things like recording into the command history, commands
125    repeating on RETURN, etc.  This is so a user interface (emacs, GUI,
126    whatever) can issue its own commands and also send along commands
127    from the user, and have the user not notice that the user interface
128    is issuing commands too.  */
129 int server_command;
130
131 /* Baud rate specified for talking to serial target systems.  Default
132    is left as -1, so targets can choose their own defaults.  */
133 /* FIXME: This means that "show remotebaud" and gr_files_info can print -1
134    or (unsigned int)-1.  This is a Bad User Interface.  */
135
136 int baud_rate = -1;
137
138 /* Timeout limit for response from target. */
139
140 /* The default value has been changed many times over the years.  It 
141    was originally 5 seconds.  But that was thought to be a long time 
142    to sit and wait, so it was changed to 2 seconds.  That was thought
143    to be plenty unless the connection was going through some terminal 
144    server or multiplexer or other form of hairy serial connection.
145
146    In mid-1996, remote_timeout was moved from remote.c to top.c and 
147    it began being used in other remote-* targets.  It appears that the
148    default was changed to 20 seconds at that time, perhaps because the
149    Renesas E7000 ICE didn't always respond in a timely manner.
150
151    But if 5 seconds is a long time to sit and wait for retransmissions,
152    20 seconds is far worse.  This demonstrates the difficulty of using 
153    a single variable for all protocol timeouts.
154
155    As remote.c is used much more than remote-e7000.c, it was changed 
156    back to 2 seconds in 1999. */
157
158 int remote_timeout = 2;
159
160 /* Non-zero tells remote* modules to output debugging info.  */
161
162 int remote_debug = 0;
163
164 /* Non-zero means the target is running. Note: this is different from
165    saying that there is an active target and we are stopped at a
166    breakpoint, for instance. This is a real indicator whether the
167    target is off and running, which gdb is doing something else. */
168 int target_executing = 0;
169
170 /* Level of control structure.  */
171 static int control_level;
172
173 /* Sbrk location on entry to main.  Used for statistics only.  */
174 #ifdef HAVE_SBRK
175 char *lim_at_start;
176 #endif
177
178 /* Signal to catch ^Z typed while reading a command: SIGTSTP or SIGCONT.  */
179
180 #ifndef STOP_SIGNAL
181 #ifdef SIGTSTP
182 #define STOP_SIGNAL SIGTSTP
183 static void stop_sig (int);
184 #endif
185 #endif
186
187 /* Hooks for alternate command interfaces.  */
188
189 /* Called after most modules have been initialized, but before taking users
190    command file.
191
192    If the UI fails to initialize and it wants GDB to continue
193    using the default UI, then it should clear this hook before returning. */
194
195 void (*init_ui_hook) (char *argv0);
196
197 /* This hook is called from within gdb's many mini-event loops which could
198    steal control from a real user interface's event loop. It returns
199    non-zero if the user is requesting a detach, zero otherwise. */
200
201 int (*ui_loop_hook) (int);
202
203 /* Called instead of command_loop at top level.  Can be invoked via
204    throw_exception().  */
205
206 void (*command_loop_hook) (void);
207
208
209 /* Called from print_frame_info to list the line we stopped in.  */
210
211 void (*print_frame_info_listing_hook) (struct symtab * s, int line,
212                                        int stopline, int noerror);
213 /* Replaces most of query.  */
214
215 int (*query_hook) (const char *, va_list);
216
217 /* Replaces most of warning.  */
218
219 void (*warning_hook) (const char *, va_list);
220
221 /* These three functions support getting lines of text from the user.  They
222    are used in sequence.  First readline_begin_hook is called with a text
223    string that might be (for example) a message for the user to type in a
224    sequence of commands to be executed at a breakpoint.  If this function
225    calls back to a GUI, it might take this opportunity to pop up a text
226    interaction window with this message.  Next, readline_hook is called
227    with a prompt that is emitted prior to collecting the user input.
228    It can be called multiple times.  Finally, readline_end_hook is called
229    to notify the GUI that we are done with the interaction window and it
230    can close it. */
231
232 void (*readline_begin_hook) (char *, ...);
233 char *(*readline_hook) (char *);
234 void (*readline_end_hook) (void);
235
236 /* Called as appropriate to notify the interface of the specified breakpoint
237    conditions.  */
238
239 void (*create_breakpoint_hook) (struct breakpoint * bpt);
240 void (*delete_breakpoint_hook) (struct breakpoint * bpt);
241 void (*modify_breakpoint_hook) (struct breakpoint * bpt);
242
243 /* Called as appropriate to notify the interface that we have attached
244    to or detached from an already running process. */
245
246 void (*attach_hook) (void);
247 void (*detach_hook) (void);
248
249 /* Called during long calculations to allow GUI to repair window damage, and to
250    check for stop buttons, etc... */
251
252 void (*interactive_hook) (void);
253
254 /* Called when the registers have changed, as a hint to a GUI
255    to minimize window update. */
256
257 void (*registers_changed_hook) (void);
258
259 /* Tell the GUI someone changed the register REGNO. -1 means
260    that the caller does not know which register changed or
261    that several registers have changed (see value_assign). */
262 void (*register_changed_hook) (int regno);
263
264 /* Tell the GUI someone changed LEN bytes of memory at ADDR */
265 void (*memory_changed_hook) (CORE_ADDR addr, int len);
266
267 /* Called when going to wait for the target.  Usually allows the GUI to run
268    while waiting for target events.  */
269
270 ptid_t (*target_wait_hook) (ptid_t ptid,
271                             struct target_waitstatus * status);
272
273 /* Used by UI as a wrapper around command execution.  May do various things
274    like enabling/disabling buttons, etc...  */
275
276 void (*call_command_hook) (struct cmd_list_element * c, char *cmd,
277                            int from_tty);
278
279 /* Called after a `set' command has finished.  Is only run if the
280    `set' command succeeded.  */
281
282 void (*set_hook) (struct cmd_list_element * c);
283
284 /* Called when the current thread changes.  Argument is thread id.  */
285
286 void (*context_hook) (int id);
287
288 /* Takes control from error ().  Typically used to prevent longjmps out of the
289    middle of the GUI.  Usually used in conjunction with a catch routine.  */
290
291 NORETURN void (*error_hook) (void) ATTR_NORETURN;
292 \f
293
294 /* One should use catch_errors rather than manipulating these
295    directly.  */
296 #if defined(HAVE_SIGSETJMP)
297 #define SIGJMP_BUF              sigjmp_buf
298 #define SIGSETJMP(buf)          sigsetjmp((buf), 1)
299 #define SIGLONGJMP(buf,val)     siglongjmp((buf), (val))
300 #else
301 #define SIGJMP_BUF              jmp_buf
302 #define SIGSETJMP(buf)          setjmp(buf)
303 #define SIGLONGJMP(buf,val)     longjmp((buf), (val))
304 #endif
305
306 /* Where to go for throw_exception().  */
307 static SIGJMP_BUF *catch_return;
308
309 /* Return for reason REASON to the nearest containing catch_errors().  */
310
311 NORETURN void
312 throw_exception (enum return_reason reason)
313 {
314   quit_flag = 0;
315   immediate_quit = 0;
316
317   /* Perhaps it would be cleaner to do this via the cleanup chain (not sure
318      I can think of a reason why that is vital, though).  */
319   bpstat_clear_actions (stop_bpstat);   /* Clear queued breakpoint commands */
320
321   disable_current_display ();
322   do_cleanups (ALL_CLEANUPS);
323   if (event_loop_p && target_can_async_p () && !target_executing)
324     do_exec_cleanups (ALL_CLEANUPS);
325   if (event_loop_p && sync_execution)
326     do_exec_error_cleanups (ALL_CLEANUPS);
327
328   if (annotation_level > 1)
329     switch (reason)
330       {
331       case RETURN_QUIT:
332         annotate_quit ();
333         break;
334       case RETURN_ERROR:
335         annotate_error ();
336         break;
337       }
338
339   /* Jump to the containing catch_errors() call, communicating REASON
340      to that call via setjmp's return value.  Note that REASON can't
341      be zero, by definition in defs.h. */
342
343   (NORETURN void) SIGLONGJMP (*catch_return, (int) reason);
344 }
345
346 /* Call FUNC() with args FUNC_UIOUT and FUNC_ARGS, catching any
347    errors.  Set FUNC_CAUGHT to an ``enum return_reason'' if the
348    function is aborted (using throw_exception() or zero if the
349    function returns normally.  Set FUNC_VAL to the value returned by
350    the function or 0 if the function was aborted.
351
352    Must not be called with immediate_quit in effect (bad things might
353    happen, say we got a signal in the middle of a memcpy to quit_return).
354    This is an OK restriction; with very few exceptions immediate_quit can
355    be replaced by judicious use of QUIT.
356
357    MASK specifies what to catch; it is normally set to
358    RETURN_MASK_ALL, if for no other reason than that the code which
359    calls catch_errors might not be set up to deal with a quit which
360    isn't caught.  But if the code can deal with it, it generally
361    should be RETURN_MASK_ERROR, unless for some reason it is more
362    useful to abort only the portion of the operation inside the
363    catch_errors.  Note that quit should return to the command line
364    fairly quickly, even if some further processing is being done.  */
365
366 /* MAYBE: cagney/1999-11-05: catch_errors() in conjunction with
367    error() et.al. could maintain a set of flags that indicate the the
368    current state of each of the longjmp buffers.  This would give the
369    longjmp code the chance to detect a longjmp botch (before it gets
370    to longjmperror()).  Prior to 1999-11-05 this wasn't possible as
371    code also randomly used a SET_TOP_LEVEL macro that directly
372    initialize the longjmp buffers. */
373
374 /* MAYBE: cagney/1999-11-05: Should the catch_errors and cleanups code
375    be consolidated into a single file instead of being distributed
376    between utils.c and top.c? */
377
378 static void
379 catcher (catch_exceptions_ftype *func,
380          struct ui_out *func_uiout,
381          void *func_args,
382          int *func_val,
383          enum return_reason *func_caught,
384          char *errstring,
385          char **gdberrmsg,
386          return_mask mask)
387 {
388   SIGJMP_BUF *saved_catch;
389   SIGJMP_BUF catch;
390   struct cleanup *saved_cleanup_chain;
391   char *saved_error_pre_print;
392   char *saved_quit_pre_print;
393   struct ui_out *saved_uiout;
394
395   /* Return value from SIGSETJMP(): enum return_reason if error or
396      quit caught, 0 otherwise. */
397   int caught;
398
399   /* Return value from FUNC(): Hopefully non-zero. Explicitly set to
400      zero if an error quit was caught.  */
401   int val;
402
403   /* Override error/quit messages during FUNC. */
404
405   saved_error_pre_print = error_pre_print;
406   saved_quit_pre_print = quit_pre_print;
407
408   if (mask & RETURN_MASK_ERROR)
409     error_pre_print = errstring;
410   if (mask & RETURN_MASK_QUIT)
411     quit_pre_print = errstring;
412
413   /* Override the global ``struct ui_out'' builder.  */
414
415   saved_uiout = uiout;
416   uiout = func_uiout;
417
418   /* Prevent error/quit during FUNC from calling cleanups established
419      prior to here. */
420
421   saved_cleanup_chain = save_cleanups ();
422
423   /* Call FUNC, catching error/quit events. */
424
425   saved_catch = catch_return;
426   catch_return = &catch;
427   caught = SIGSETJMP (catch);
428   if (!caught)
429     val = (*func) (func_uiout, func_args);
430   else
431     {
432       val = 0;
433       /* If caller wants a copy of the low-level error message, make one.  
434          This is used in the case of a silent error whereby the caller
435          may optionally want to issue the message.  */
436       if (gdberrmsg)
437         *gdberrmsg = error_last_message ();
438     }
439   catch_return = saved_catch;
440
441   /* FIXME: cagney/1999-11-05: A correct FUNC implementation will
442      clean things up (restoring the cleanup chain) to the state they
443      were just prior to the call.  Unfortunately, many FUNC's are not
444      that well behaved.  This could be fixed by adding either a
445      do_cleanups call (to cover the problem) or an assertion check to
446      detect bad FUNCs code. */
447
448   /* Restore the cleanup chain, the error/quit messages, and the uiout
449      builder, to their original states. */
450
451   restore_cleanups (saved_cleanup_chain);
452
453   uiout = saved_uiout;
454
455   if (mask & RETURN_MASK_QUIT)
456     quit_pre_print = saved_quit_pre_print;
457   if (mask & RETURN_MASK_ERROR)
458     error_pre_print = saved_error_pre_print;
459
460   /* Return normally if no error/quit event occurred or this catcher
461      can handle this exception.  The caller analyses the func return
462      values.  */
463
464   if (!caught || (mask & RETURN_MASK (caught)))
465     {
466       *func_val = val;
467       *func_caught = caught;
468       return;
469     }
470
471   /* The caller didn't request that the event be caught, relay the
472      event to the next containing catch_errors(). */
473
474   throw_exception (caught);
475 }
476
477 int
478 catch_exceptions (struct ui_out *uiout,
479                   catch_exceptions_ftype *func,
480                   void *func_args,
481                   char *errstring,
482                   return_mask mask)
483 {
484   int val;
485   enum return_reason caught;
486   catcher (func, uiout, func_args, &val, &caught, errstring, NULL, mask);
487   gdb_assert (val >= 0);
488   gdb_assert (caught <= 0);
489   if (caught < 0)
490     return caught;
491   return val;
492 }
493
494 int
495 catch_exceptions_with_msg (struct ui_out *uiout,
496                            catch_exceptions_ftype *func,
497                            void *func_args,
498                            char *errstring,
499                            char **gdberrmsg,
500                            return_mask mask)
501 {
502   int val;
503   enum return_reason caught;
504   catcher (func, uiout, func_args, &val, &caught, errstring, gdberrmsg, mask);
505   gdb_assert (val >= 0);
506   gdb_assert (caught <= 0);
507   if (caught < 0)
508     return caught;
509   return val;
510 }
511
512 struct catch_errors_args
513 {
514   catch_errors_ftype *func;
515   void *func_args;
516 };
517
518 static int
519 do_catch_errors (struct ui_out *uiout, void *data)
520 {
521   struct catch_errors_args *args = data;
522   return args->func (args->func_args);
523 }
524
525 int
526 catch_errors (catch_errors_ftype *func, void *func_args, char *errstring,
527               return_mask mask)
528 {
529   int val;
530   enum return_reason caught;
531   struct catch_errors_args args;
532   args.func = func;
533   args.func_args = func_args;
534   catcher (do_catch_errors, uiout, &args, &val, &caught, errstring, 
535            NULL, mask);
536   if (caught != 0)
537     return 0;
538   return val;
539 }
540
541 struct captured_command_args
542   {
543     catch_command_errors_ftype *command;
544     char *arg;
545     int from_tty;
546   };
547
548 static int
549 do_captured_command (void *data)
550 {
551   struct captured_command_args *context = data;
552   context->command (context->arg, context->from_tty);
553   /* FIXME: cagney/1999-11-07: Technically this do_cleanups() call
554      isn't needed.  Instead an assertion check could be made that
555      simply confirmed that the called function correctly cleaned up
556      after itself.  Unfortunately, old code (prior to 1999-11-04) in
557      main.c was calling SET_TOP_LEVEL(), calling the command function,
558      and then *always* calling do_cleanups().  For the moment we
559      remain ``bug compatible'' with that old code..  */
560   do_cleanups (ALL_CLEANUPS);
561   return 1;
562 }
563
564 int
565 catch_command_errors (catch_command_errors_ftype * command,
566                       char *arg, int from_tty, return_mask mask)
567 {
568   struct captured_command_args args;
569   args.command = command;
570   args.arg = arg;
571   args.from_tty = from_tty;
572   return catch_errors (do_captured_command, &args, "", mask);
573 }
574
575
576 /* Handler for SIGHUP.  */
577
578 #ifdef SIGHUP
579 /* Just a little helper function for disconnect().  */
580
581 /* NOTE 1999-04-29: This function will be static again, once we modify
582    gdb to use the event loop as the default command loop and we merge
583    event-top.c into this file, top.c */
584 /* static */ int
585 quit_cover (void *s)
586 {
587   caution = 0;                  /* Throw caution to the wind -- we're exiting.
588                                    This prevents asking the user dumb questions.  */
589   quit_command ((char *) 0, 0);
590   return 0;
591 }
592
593 static void
594 disconnect (int signo)
595 {
596   catch_errors (quit_cover, NULL,
597               "Could not kill the program being debugged", RETURN_MASK_ALL);
598   signal (SIGHUP, SIG_DFL);
599   kill (getpid (), SIGHUP);
600 }
601 #endif /* defined SIGHUP */
602 \f
603 /* Line number we are currently in in a file which is being sourced.  */
604 /* NOTE 1999-04-29: This variable will be static again, once we modify
605    gdb to use the event loop as the default command loop and we merge
606    event-top.c into this file, top.c */
607 /* static */ int source_line_number;
608
609 /* Name of the file we are sourcing.  */
610 /* NOTE 1999-04-29: This variable will be static again, once we modify
611    gdb to use the event loop as the default command loop and we merge
612    event-top.c into this file, top.c */
613 /* static */ char *source_file_name;
614
615 /* Buffer containing the error_pre_print used by the source stuff.
616    Malloc'd.  */
617 /* NOTE 1999-04-29: This variable will be static again, once we modify
618    gdb to use the event loop as the default command loop and we merge
619    event-top.c into this file, top.c */
620 /* static */ char *source_error;
621 static int source_error_allocated;
622
623 /* Something to glom on to the start of error_pre_print if source_file_name
624    is set.  */
625 /* NOTE 1999-04-29: This variable will be static again, once we modify
626    gdb to use the event loop as the default command loop and we merge
627    event-top.c into this file, top.c */
628 /* static */ char *source_pre_error;
629
630 /* Clean up on error during a "source" command (or execution of a
631    user-defined command).  */
632
633 void
634 do_restore_instream_cleanup (void *stream)
635 {
636   /* Restore the previous input stream.  */
637   instream = stream;
638 }
639
640 /* Read commands from STREAM.  */
641 void
642 read_command_file (FILE *stream)
643 {
644   struct cleanup *cleanups;
645
646   cleanups = make_cleanup (do_restore_instream_cleanup, instream);
647   instream = stream;
648   command_loop ();
649   do_cleanups (cleanups);
650 }
651 \f
652 void (*pre_init_ui_hook) (void);
653
654 #ifdef __MSDOS__
655 void
656 do_chdir_cleanup (void *old_dir)
657 {
658   chdir (old_dir);
659   xfree (old_dir);
660 }
661 #endif
662
663 /* Execute the line P as a command.
664    Pass FROM_TTY as second argument to the defining function.  */
665
666 void
667 execute_command (char *p, int from_tty)
668 {
669   struct cmd_list_element *c;
670   enum language flang;
671   static int warned = 0;
672   char *line;
673   
674   free_all_values ();
675
676   /* Force cleanup of any alloca areas if using C alloca instead of
677      a builtin alloca.  */
678   alloca (0);
679
680   /* This can happen when command_line_input hits end of file.  */
681   if (p == NULL)
682     return;
683
684   serial_log_command (p);
685
686   while (*p == ' ' || *p == '\t')
687     p++;
688   if (*p)
689     {
690       char *arg;
691       line = p;
692
693       c = lookup_cmd (&p, cmdlist, "", 0, 1);
694
695       /* If the target is running, we allow only a limited set of
696          commands. */
697       if (event_loop_p && target_can_async_p () && target_executing)
698         if (strcmp (c->name, "help") != 0
699             && strcmp (c->name, "pwd") != 0
700             && strcmp (c->name, "show") != 0
701             && strcmp (c->name, "stop") != 0)
702           error ("Cannot execute this command while the target is running.");
703
704       /* Pass null arg rather than an empty one.  */
705       arg = *p ? p : 0;
706
707       /* FIXME: cagney/2002-02-02: The c->type test is pretty dodgy
708          while the is_complete_command(cfunc) test is just plain
709          bogus.  They should both be replaced by a test of the form
710          c->strip_trailing_white_space_p.  */
711       /* NOTE: cagney/2002-02-02: The function.cfunc in the below
712          can't be replaced with func.  This is because it is the
713          cfunc, and not the func, that has the value that the
714          is_complete_command hack is testing for.  */
715       /* Clear off trailing whitespace, except for set and complete
716          command.  */
717       if (arg
718           && c->type != set_cmd
719           && !is_complete_command (c))
720         {
721           p = arg + strlen (arg) - 1;
722           while (p >= arg && (*p == ' ' || *p == '\t'))
723             p--;
724           *(p + 1) = '\0';
725         }
726
727       /* If this command has been pre-hooked, run the hook first. */
728       execute_cmd_pre_hook (c);
729
730       if (c->flags & DEPRECATED_WARN_USER)
731         deprecated_cmd_warning (&line);
732
733       if (c->class == class_user)
734         execute_user_command (c, arg);
735       else if (c->type == set_cmd || c->type == show_cmd)
736         do_setshow_command (arg, from_tty & caution, c);
737       else if (!cmd_func_p (c))
738         error ("That is not a command, just a help topic.");
739       else if (call_command_hook)
740         call_command_hook (c, arg, from_tty & caution);
741       else
742         cmd_func (c, arg, from_tty & caution);
743        
744       /* If this command has been post-hooked, run the hook last. */
745       execute_cmd_post_hook (c);
746
747     }
748
749   /* Tell the user if the language has changed (except first time).  */
750   if (current_language != expected_language)
751     {
752       if (language_mode == language_mode_auto)
753         {
754           language_info (1);    /* Print what changed.  */
755         }
756       warned = 0;
757     }
758
759   /* Warn the user if the working language does not match the
760      language of the current frame.  Only warn the user if we are
761      actually running the program, i.e. there is a stack. */
762   /* FIXME:  This should be cacheing the frame and only running when
763      the frame changes.  */
764
765   if (target_has_stack)
766     {
767       flang = get_frame_language ();
768       if (!warned
769           && flang != language_unknown
770           && flang != current_language->la_language)
771         {
772           printf_filtered ("%s\n", lang_frame_mismatch_warn);
773           warned = 1;
774         }
775     }
776 }
777
778 /* Read commands from `instream' and execute them
779    until end of file or error reading instream.  */
780
781 void
782 command_loop (void)
783 {
784   struct cleanup *old_chain;
785   char *command;
786   int stdin_is_tty = ISATTY (stdin);
787   long time_at_cmd_start;
788 #ifdef HAVE_SBRK
789   long space_at_cmd_start = 0;
790 #endif
791   extern int display_time;
792   extern int display_space;
793
794   while (instream && !feof (instream))
795     {
796       if (window_hook && instream == stdin)
797         (*window_hook) (instream, get_prompt ());
798
799       quit_flag = 0;
800       if (instream == stdin && stdin_is_tty)
801         reinitialize_more_filter ();
802       old_chain = make_cleanup (null_cleanup, 0);
803
804       /* Get a command-line. This calls the readline package. */
805       command = command_line_input (instream == stdin ?
806                                     get_prompt () : (char *) NULL,
807                                     instream == stdin, "prompt");
808       if (command == 0)
809         return;
810
811       time_at_cmd_start = get_run_time ();
812
813       if (display_space)
814         {
815 #ifdef HAVE_SBRK
816           char *lim = (char *) sbrk (0);
817           space_at_cmd_start = lim - lim_at_start;
818 #endif
819         }
820
821       execute_command (command, instream == stdin);
822       /* Do any commands attached to breakpoint we stopped at.  */
823       bpstat_do_actions (&stop_bpstat);
824       do_cleanups (old_chain);
825
826       if (display_time)
827         {
828           long cmd_time = get_run_time () - time_at_cmd_start;
829
830           printf_unfiltered ("Command execution time: %ld.%06ld\n",
831                              cmd_time / 1000000, cmd_time % 1000000);
832         }
833
834       if (display_space)
835         {
836 #ifdef HAVE_SBRK
837           char *lim = (char *) sbrk (0);
838           long space_now = lim - lim_at_start;
839           long space_diff = space_now - space_at_cmd_start;
840
841           printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
842                              space_now,
843                              (space_diff >= 0 ? '+' : '-'),
844                              space_diff);
845 #endif
846         }
847     }
848 }
849
850 /* Read commands from `instream' and execute them until end of file or
851    error reading instream. This command loop doesnt care about any
852    such things as displaying time and space usage. If the user asks
853    for those, they won't work. */
854 void
855 simplified_command_loop (char *(*read_input_func) (char *),
856                          void (*execute_command_func) (char *, int))
857 {
858   struct cleanup *old_chain;
859   char *command;
860   int stdin_is_tty = ISATTY (stdin);
861
862   while (instream && !feof (instream))
863     {
864       quit_flag = 0;
865       if (instream == stdin && stdin_is_tty)
866         reinitialize_more_filter ();
867       old_chain = make_cleanup (null_cleanup, 0);
868
869       /* Get a command-line. */
870       command = (*read_input_func) (instream == stdin ?
871                                     get_prompt () : (char *) NULL);
872
873       if (command == 0)
874         return;
875
876       (*execute_command_func) (command, instream == stdin);
877
878       /* Do any commands attached to breakpoint we stopped at.  */
879       bpstat_do_actions (&stop_bpstat);
880
881       do_cleanups (old_chain);
882     }
883 }
884 \f
885 /* Commands call this if they do not want to be repeated by null lines.  */
886
887 void
888 dont_repeat (void)
889 {
890   if (server_command)
891     return;
892
893   /* If we aren't reading from standard input, we are saving the last
894      thing read from stdin in line and don't want to delete it.  Null lines
895      won't repeat here in any case.  */
896   if (instream == stdin)
897     *line = 0;
898 }
899 \f
900 /* Read a line from the stream "instream" without command line editing.
901
902    It prints PROMPT_ARG once at the start.
903    Action is compatible with "readline", e.g. space for the result is
904    malloc'd and should be freed by the caller.
905
906    A NULL return means end of file.  */
907 char *
908 gdb_readline (char *prompt_arg)
909 {
910   int c;
911   char *result;
912   int input_index = 0;
913   int result_size = 80;
914
915   if (prompt_arg)
916     {
917       /* Don't use a _filtered function here.  It causes the assumed
918          character position to be off, since the newline we read from
919          the user is not accounted for.  */
920       fputs_unfiltered (prompt_arg, gdb_stdout);
921       gdb_flush (gdb_stdout);
922     }
923
924   result = (char *) xmalloc (result_size);
925
926   while (1)
927     {
928       /* Read from stdin if we are executing a user defined command.
929          This is the right thing for prompt_for_continue, at least.  */
930       c = fgetc (instream ? instream : stdin);
931
932       if (c == EOF)
933         {
934           if (input_index > 0)
935             /* The last line does not end with a newline.  Return it, and
936                if we are called again fgetc will still return EOF and
937                we'll return NULL then.  */
938             break;
939           xfree (result);
940           return NULL;
941         }
942
943       if (c == '\n')
944 #ifndef CRLF_SOURCE_FILES
945         break;
946 #else
947         {
948           if (input_index > 0 && result[input_index - 1] == '\r')
949             input_index--;
950           break;
951         }
952 #endif
953
954       result[input_index++] = c;
955       while (input_index >= result_size)
956         {
957           result_size *= 2;
958           result = (char *) xrealloc (result, result_size);
959         }
960     }
961
962   result[input_index++] = '\0';
963   return result;
964 }
965
966 /* Variables which control command line editing and history
967    substitution.  These variables are given default values at the end
968    of this file.  */
969 static int command_editing_p;
970 /* NOTE 1999-04-29: This variable will be static again, once we modify
971    gdb to use the event loop as the default command loop and we merge
972    event-top.c into this file, top.c */
973 /* static */ int history_expansion_p;
974 static int write_history_p;
975 static int history_size;
976 static char *history_filename;
977
978 /* This is like readline(), but it has some gdb-specific behavior.
979    gdb can use readline in both the synchronous and async modes during
980    a single gdb invocation.  At the ordinary top-level prompt we might
981    be using the async readline.  That means we can't use
982    rl_pre_input_hook, since it doesn't work properly in async mode.
983    However, for a secondary prompt (" >", such as occurs during a
984    `define'), gdb just calls readline() directly, running it in
985    synchronous mode.  So for operate-and-get-next to work in this
986    situation, we have to switch the hooks around.  That is what
987    gdb_readline_wrapper is for.  */
988 char *
989 gdb_readline_wrapper (char *prompt)
990 {
991   /* Set the hook that works in this case.  */
992   if (event_loop_p && after_char_processing_hook)
993     {
994       rl_pre_input_hook = (Function *) after_char_processing_hook;
995       after_char_processing_hook = NULL;
996     }
997
998   return readline (prompt);
999 }
1000
1001 \f
1002 #ifdef STOP_SIGNAL
1003 static void
1004 stop_sig (int signo)
1005 {
1006 #if STOP_SIGNAL == SIGTSTP
1007   signal (SIGTSTP, SIG_DFL);
1008 #if HAVE_SIGPROCMASK
1009   {
1010     sigset_t zero;
1011
1012     sigemptyset (&zero);
1013     sigprocmask (SIG_SETMASK, &zero, 0);
1014   }
1015 #elif HAVE_SIGSETMASK
1016   sigsetmask (0);
1017 #endif
1018   kill (getpid (), SIGTSTP);
1019   signal (SIGTSTP, stop_sig);
1020 #else
1021   signal (STOP_SIGNAL, stop_sig);
1022 #endif
1023   printf_unfiltered ("%s", get_prompt ());
1024   gdb_flush (gdb_stdout);
1025
1026   /* Forget about any previous command -- null line now will do nothing.  */
1027   dont_repeat ();
1028 }
1029 #endif /* STOP_SIGNAL */
1030
1031 /* Initialize signal handlers. */
1032 static void
1033 float_handler (int signo)
1034 {
1035   /* This message is based on ANSI C, section 4.7.  Note that integer
1036      divide by zero causes this, so "float" is a misnomer.  */
1037   signal (SIGFPE, float_handler);
1038   error ("Erroneous arithmetic operation.");
1039 }
1040
1041 static void
1042 do_nothing (int signo)
1043 {
1044   /* Under System V the default disposition of a signal is reinstated after
1045      the signal is caught and delivered to an application process.  On such
1046      systems one must restore the replacement signal handler if one wishes
1047      to continue handling the signal in one's program.  On BSD systems this
1048      is not needed but it is harmless, and it simplifies the code to just do
1049      it unconditionally. */
1050   signal (signo, do_nothing);
1051 }
1052
1053 static void
1054 init_signals (void)
1055 {
1056   signal (SIGINT, request_quit);
1057
1058   /* If SIGTRAP was set to SIG_IGN, then the SIG_IGN will get passed
1059      to the inferior and breakpoints will be ignored.  */
1060 #ifdef SIGTRAP
1061   signal (SIGTRAP, SIG_DFL);
1062 #endif
1063
1064   /* If we initialize SIGQUIT to SIG_IGN, then the SIG_IGN will get
1065      passed to the inferior, which we don't want.  It would be
1066      possible to do a "signal (SIGQUIT, SIG_DFL)" after we fork, but
1067      on BSD4.3 systems using vfork, that can affect the
1068      GDB process as well as the inferior (the signal handling tables
1069      might be in memory, shared between the two).  Since we establish
1070      a handler for SIGQUIT, when we call exec it will set the signal
1071      to SIG_DFL for us.  */
1072   signal (SIGQUIT, do_nothing);
1073 #ifdef SIGHUP
1074   if (signal (SIGHUP, do_nothing) != SIG_IGN)
1075     signal (SIGHUP, disconnect);
1076 #endif
1077   signal (SIGFPE, float_handler);
1078
1079 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1080   signal (SIGWINCH, SIGWINCH_HANDLER);
1081 #endif
1082 }
1083 \f
1084 /* The current saved history number from operate-and-get-next.
1085    This is -1 if not valid.  */
1086 static int operate_saved_history = -1;
1087
1088 /* This is put on the appropriate hook and helps operate-and-get-next
1089    do its work.  */
1090 static void
1091 gdb_rl_operate_and_get_next_completion (void)
1092 {
1093   int delta = where_history () - operate_saved_history;
1094   /* The `key' argument to rl_get_previous_history is ignored.  */
1095   rl_get_previous_history (delta, 0);
1096   operate_saved_history = -1;
1097
1098   /* readline doesn't automatically update the display for us.  */
1099   rl_redisplay ();
1100
1101   after_char_processing_hook = NULL;
1102   rl_pre_input_hook = NULL;
1103 }
1104
1105 /* This is a gdb-local readline command handler.  It accepts the
1106    current command line (like RET does) and, if this command was taken
1107    from the history, arranges for the next command in the history to
1108    appear on the command line when the prompt returns.
1109    We ignore the arguments.  */
1110 static int
1111 gdb_rl_operate_and_get_next (int count, int key)
1112 {
1113   int where;
1114
1115   if (event_loop_p)
1116     {
1117       /* Use the async hook.  */
1118       after_char_processing_hook = gdb_rl_operate_and_get_next_completion;
1119     }
1120   else
1121     {
1122       /* This hook only works correctly when we are using the
1123          synchronous readline.  */
1124       rl_pre_input_hook = (Function *) gdb_rl_operate_and_get_next_completion;
1125     }
1126
1127   /* Find the current line, and find the next line to use.  */
1128   where = where_history();
1129
1130   /* FIXME: kettenis/20020817: max_input_history is renamed into
1131      history_max_entries in readline-4.2.  When we do a new readline
1132      import, we should probably change it here too, even though
1133      readline maintains backwards compatibility for now by still
1134      defining max_input_history.  */
1135   if ((history_is_stifled () && (history_length >= max_input_history)) ||
1136       (where >= history_length - 1))
1137     operate_saved_history = where;
1138   else
1139     operate_saved_history = where + 1;
1140
1141   return rl_newline (1, key);
1142 }
1143 \f
1144 /* Read one line from the command input stream `instream'
1145    into the local static buffer `linebuffer' (whose current length
1146    is `linelength').
1147    The buffer is made bigger as necessary.
1148    Returns the address of the start of the line.
1149
1150    NULL is returned for end of file.
1151
1152    *If* the instream == stdin & stdin is a terminal, the line read
1153    is copied into the file line saver (global var char *line,
1154    length linesize) so that it can be duplicated.
1155
1156    This routine either uses fancy command line editing or
1157    simple input as the user has requested.  */
1158
1159 char *
1160 command_line_input (char *prompt_arg, int repeat, char *annotation_suffix)
1161 {
1162   static char *linebuffer = 0;
1163   static unsigned linelength = 0;
1164   char *p;
1165   char *p1;
1166   char *rl;
1167   char *local_prompt = prompt_arg;
1168   char *nline;
1169   char got_eof = 0;
1170
1171   /* The annotation suffix must be non-NULL.  */
1172   if (annotation_suffix == NULL)
1173     annotation_suffix = "";
1174
1175   if (annotation_level > 1 && instream == stdin)
1176     {
1177       local_prompt = alloca ((prompt_arg == NULL ? 0 : strlen (prompt_arg))
1178                              + strlen (annotation_suffix) + 40);
1179       if (prompt_arg == NULL)
1180         local_prompt[0] = '\0';
1181       else
1182         strcpy (local_prompt, prompt_arg);
1183       strcat (local_prompt, "\n\032\032");
1184       strcat (local_prompt, annotation_suffix);
1185       strcat (local_prompt, "\n");
1186     }
1187
1188   if (linebuffer == 0)
1189     {
1190       linelength = 80;
1191       linebuffer = (char *) xmalloc (linelength);
1192     }
1193
1194   p = linebuffer;
1195
1196   /* Control-C quits instantly if typed while in this loop
1197      since it should not wait until the user types a newline.  */
1198   immediate_quit++;
1199 #ifdef STOP_SIGNAL
1200   if (job_control)
1201     {
1202       if (event_loop_p)
1203         signal (STOP_SIGNAL, handle_stop_sig);
1204       else
1205         signal (STOP_SIGNAL, stop_sig);
1206     }
1207 #endif
1208
1209   while (1)
1210     {
1211       /* Make sure that all output has been output.  Some machines may let
1212          you get away with leaving out some of the gdb_flush, but not all.  */
1213       wrap_here ("");
1214       gdb_flush (gdb_stdout);
1215       gdb_flush (gdb_stderr);
1216
1217       if (source_file_name != NULL)
1218         {
1219           ++source_line_number;
1220           sprintf (source_error,
1221                    "%s%s:%d: Error in sourced command file:\n",
1222                    source_pre_error,
1223                    source_file_name,
1224                    source_line_number);
1225           error_pre_print = source_error;
1226         }
1227
1228       if (annotation_level > 1 && instream == stdin)
1229         {
1230           puts_unfiltered ("\n\032\032pre-");
1231           puts_unfiltered (annotation_suffix);
1232           puts_unfiltered ("\n");
1233         }
1234
1235       /* Don't use fancy stuff if not talking to stdin.  */
1236       if (readline_hook && instream == NULL)
1237         {
1238           rl = (*readline_hook) (local_prompt);
1239         }
1240       else if (command_editing_p && instream == stdin && ISATTY (instream))
1241         {
1242           rl = gdb_readline_wrapper (local_prompt);
1243         }
1244       else
1245         {
1246           rl = gdb_readline (local_prompt);
1247         }
1248
1249       if (annotation_level > 1 && instream == stdin)
1250         {
1251           puts_unfiltered ("\n\032\032post-");
1252           puts_unfiltered (annotation_suffix);
1253           puts_unfiltered ("\n");
1254         }
1255
1256       if (!rl || rl == (char *) EOF)
1257         {
1258           got_eof = 1;
1259           break;
1260         }
1261       if (strlen (rl) + 1 + (p - linebuffer) > linelength)
1262         {
1263           linelength = strlen (rl) + 1 + (p - linebuffer);
1264           nline = (char *) xrealloc (linebuffer, linelength);
1265           p += nline - linebuffer;
1266           linebuffer = nline;
1267         }
1268       p1 = rl;
1269       /* Copy line.  Don't copy null at end.  (Leaves line alone
1270          if this was just a newline)  */
1271       while (*p1)
1272         *p++ = *p1++;
1273
1274       xfree (rl);               /* Allocated in readline.  */
1275
1276       if (p == linebuffer || *(p - 1) != '\\')
1277         break;
1278
1279       p--;                      /* Put on top of '\'.  */
1280       local_prompt = (char *) 0;
1281     }
1282
1283 #ifdef STOP_SIGNAL
1284   if (job_control)
1285     signal (STOP_SIGNAL, SIG_DFL);
1286 #endif
1287   immediate_quit--;
1288
1289   if (got_eof)
1290     return NULL;
1291
1292 #define SERVER_COMMAND_LENGTH 7
1293   server_command =
1294     (p - linebuffer > SERVER_COMMAND_LENGTH)
1295     && strncmp (linebuffer, "server ", SERVER_COMMAND_LENGTH) == 0;
1296   if (server_command)
1297     {
1298       /* Note that we don't set `line'.  Between this and the check in
1299          dont_repeat, this insures that repeating will still do the
1300          right thing.  */
1301       *p = '\0';
1302       return linebuffer + SERVER_COMMAND_LENGTH;
1303     }
1304
1305   /* Do history expansion if that is wished.  */
1306   if (history_expansion_p && instream == stdin
1307       && ISATTY (instream))
1308     {
1309       char *history_value;
1310       int expanded;
1311
1312       *p = '\0';                /* Insert null now.  */
1313       expanded = history_expand (linebuffer, &history_value);
1314       if (expanded)
1315         {
1316           /* Print the changes.  */
1317           printf_unfiltered ("%s\n", history_value);
1318
1319           /* If there was an error, call this function again.  */
1320           if (expanded < 0)
1321             {
1322               xfree (history_value);
1323               return command_line_input (prompt_arg, repeat, annotation_suffix);
1324             }
1325           if (strlen (history_value) > linelength)
1326             {
1327               linelength = strlen (history_value) + 1;
1328               linebuffer = (char *) xrealloc (linebuffer, linelength);
1329             }
1330           strcpy (linebuffer, history_value);
1331           p = linebuffer + strlen (linebuffer);
1332           xfree (history_value);
1333         }
1334     }
1335
1336   /* If we just got an empty line, and that is supposed
1337      to repeat the previous command, return the value in the
1338      global buffer.  */
1339   if (repeat && p == linebuffer)
1340     return line;
1341   for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
1342   if (repeat && !*p1)
1343     return line;
1344
1345   *p = 0;
1346
1347   /* Add line to history if appropriate.  */
1348   if (instream == stdin
1349       && ISATTY (stdin) && *linebuffer)
1350     add_history (linebuffer);
1351
1352   /* Note: lines consisting solely of comments are added to the command
1353      history.  This is useful when you type a command, and then
1354      realize you don't want to execute it quite yet.  You can comment
1355      out the command and then later fetch it from the value history
1356      and remove the '#'.  The kill ring is probably better, but some
1357      people are in the habit of commenting things out.  */
1358   if (*p1 == '#')
1359     *p1 = '\0';                 /* Found a comment. */
1360
1361   /* Save into global buffer if appropriate.  */
1362   if (repeat)
1363     {
1364       if (linelength > linesize)
1365         {
1366           line = xrealloc (line, linelength);
1367           linesize = linelength;
1368         }
1369       strcpy (line, linebuffer);
1370       return line;
1371     }
1372
1373   return linebuffer;
1374 }
1375 \f
1376 /* Print the GDB banner. */
1377 void
1378 print_gdb_version (struct ui_file *stream)
1379 {
1380   /* From GNU coding standards, first line is meant to be easy for a
1381      program to parse, and is just canonical program name and version
1382      number, which starts after last space. */
1383
1384   fprintf_filtered (stream, "GNU gdb %s\n", version);
1385
1386   /* Second line is a copyright notice. */
1387
1388   fprintf_filtered (stream, "Copyright 2004 Free Software Foundation, Inc.\n");
1389
1390   /* Following the copyright is a brief statement that the program is
1391      free software, that users are free to copy and change it on
1392      certain conditions, that it is covered by the GNU GPL, and that
1393      there is no warranty. */
1394
1395   fprintf_filtered (stream, "\
1396 GDB is free software, covered by the GNU General Public License, and you are\n\
1397 welcome to change it and/or distribute copies of it under certain conditions.\n\
1398 Type \"show copying\" to see the conditions.\n\
1399 There is absolutely no warranty for GDB.  Type \"show warranty\" for details.\n");
1400
1401   /* After the required info we print the configuration information. */
1402
1403   fprintf_filtered (stream, "This GDB was configured as \"");
1404   if (strcmp (host_name, target_name) != 0)
1405     {
1406       fprintf_filtered (stream, "--host=%s --target=%s", host_name, target_name);
1407     }
1408   else
1409     {
1410       fprintf_filtered (stream, "%s", host_name);
1411     }
1412   fprintf_filtered (stream, "\".");
1413 }
1414 \f
1415 /* get_prompt: access method for the GDB prompt string.  */
1416
1417 char *
1418 get_prompt (void)
1419 {
1420   if (event_loop_p)
1421     return PROMPT (0);
1422   else
1423     return gdb_prompt_string;
1424 }
1425
1426 void
1427 set_prompt (char *s)
1428 {
1429 /* ??rehrauer: I don't know why this fails, since it looks as though
1430    assignments to prompt are wrapped in calls to savestring...
1431    if (prompt != NULL)
1432    xfree (prompt);
1433  */
1434   if (event_loop_p)
1435     PROMPT (0) = savestring (s, strlen (s));
1436   else
1437     gdb_prompt_string = savestring (s, strlen (s));
1438 }
1439 \f
1440
1441 /* If necessary, make the user confirm that we should quit.  Return
1442    non-zero if we should quit, zero if we shouldn't.  */
1443
1444 int
1445 quit_confirm (void)
1446 {
1447   if (! ptid_equal (inferior_ptid, null_ptid) && target_has_execution)
1448     {
1449       char *s;
1450
1451       /* This is something of a hack.  But there's no reliable way to
1452          see if a GUI is running.  The `use_windows' variable doesn't
1453          cut it.  */
1454       if (init_ui_hook)
1455         s = "A debugging session is active.\nDo you still want to close the debugger?";
1456       else if (attach_flag)
1457         s = "The program is running.  Quit anyway (and detach it)? ";
1458       else
1459         s = "The program is running.  Exit anyway? ";
1460
1461       if (!query ("%s", s))
1462         return 0;
1463     }
1464
1465   return 1;
1466 }
1467
1468 /* Helper routine for quit_force that requires error handling.  */
1469
1470 struct qt_args
1471 {
1472   char *args;
1473   int from_tty;
1474 };
1475
1476 static int
1477 quit_target (void *arg)
1478 {
1479   struct qt_args *qt = (struct qt_args *)arg;
1480
1481   if (! ptid_equal (inferior_ptid, null_ptid) && target_has_execution)
1482     {
1483       if (attach_flag)
1484         target_detach (qt->args, qt->from_tty);
1485       else
1486         target_kill ();
1487     }
1488
1489   /* UDI wants this, to kill the TIP.  */
1490   target_close (&current_target, 1);
1491
1492   /* Save the history information if it is appropriate to do so.  */
1493   if (write_history_p && history_filename)
1494     write_history (history_filename);
1495
1496   do_final_cleanups (ALL_CLEANUPS);     /* Do any final cleanups before exiting */
1497
1498   return 0;
1499 }
1500
1501 /* Quit without asking for confirmation.  */
1502
1503 void
1504 quit_force (char *args, int from_tty)
1505 {
1506   int exit_code = 0;
1507   struct qt_args qt;
1508
1509   /* An optional expression may be used to cause gdb to terminate with the 
1510      value of that expression. */
1511   if (args)
1512     {
1513       struct value *val = parse_and_eval (args);
1514
1515       exit_code = (int) value_as_long (val);
1516     }
1517
1518   qt.args = args;
1519   qt.from_tty = from_tty;
1520
1521   /* We want to handle any quit errors and exit regardless.  */
1522   catch_errors (quit_target, &qt,
1523                 "Quitting: ", RETURN_MASK_ALL);
1524
1525   exit (exit_code);
1526 }
1527
1528 /* Returns whether GDB is running on a terminal and whether the user
1529    desires that questions be asked of them on that terminal.  */
1530
1531 int
1532 input_from_terminal_p (void)
1533 {
1534   return gdb_has_a_terminal () && (instream == stdin) & caution;
1535 }
1536 \f
1537 static void
1538 dont_repeat_command (char *ignored, int from_tty)
1539 {
1540   *line = 0;                    /* Can't call dont_repeat here because we're not
1541                                    necessarily reading from stdin.  */
1542 }
1543 \f
1544 /* Functions to manipulate command line editing control variables.  */
1545
1546 /* Number of commands to print in each call to show_commands.  */
1547 #define Hist_print 10
1548 void
1549 show_commands (char *args, int from_tty)
1550 {
1551   /* Index for history commands.  Relative to history_base.  */
1552   int offset;
1553
1554   /* Number of the history entry which we are planning to display next.
1555      Relative to history_base.  */
1556   static int num = 0;
1557
1558   /* The first command in the history which doesn't exist (i.e. one more
1559      than the number of the last command).  Relative to history_base.  */
1560   int hist_len;
1561
1562   /* Print out some of the commands from the command history.  */
1563   /* First determine the length of the history list.  */
1564   hist_len = history_size;
1565   for (offset = 0; offset < history_size; offset++)
1566     {
1567       if (!history_get (history_base + offset))
1568         {
1569           hist_len = offset;
1570           break;
1571         }
1572     }
1573
1574   if (args)
1575     {
1576       if (args[0] == '+' && args[1] == '\0')
1577         /* "info editing +" should print from the stored position.  */
1578         ;
1579       else
1580         /* "info editing <exp>" should print around command number <exp>.  */
1581         num = (parse_and_eval_long (args) - history_base) - Hist_print / 2;
1582     }
1583   /* "show commands" means print the last Hist_print commands.  */
1584   else
1585     {
1586       num = hist_len - Hist_print;
1587     }
1588
1589   if (num < 0)
1590     num = 0;
1591
1592   /* If there are at least Hist_print commands, we want to display the last
1593      Hist_print rather than, say, the last 6.  */
1594   if (hist_len - num < Hist_print)
1595     {
1596       num = hist_len - Hist_print;
1597       if (num < 0)
1598         num = 0;
1599     }
1600
1601   for (offset = num; offset < num + Hist_print && offset < hist_len; offset++)
1602     {
1603       printf_filtered ("%5d  %s\n", history_base + offset,
1604                        (history_get (history_base + offset))->line);
1605     }
1606
1607   /* The next command we want to display is the next one that we haven't
1608      displayed yet.  */
1609   num += Hist_print;
1610
1611   /* If the user repeats this command with return, it should do what
1612      "show commands +" does.  This is unnecessary if arg is null,
1613      because "show commands +" is not useful after "show commands".  */
1614   if (from_tty && args)
1615     {
1616       args[0] = '+';
1617       args[1] = '\0';
1618     }
1619 }
1620
1621 /* Called by do_setshow_command.  */
1622 static void
1623 set_history_size_command (char *args, int from_tty, struct cmd_list_element *c)
1624 {
1625   if (history_size == INT_MAX)
1626     unstifle_history ();
1627   else if (history_size >= 0)
1628     stifle_history (history_size);
1629   else
1630     {
1631       history_size = INT_MAX;
1632       error ("History size must be non-negative");
1633     }
1634 }
1635
1636 void
1637 set_history (char *args, int from_tty)
1638 {
1639   printf_unfiltered ("\"set history\" must be followed by the name of a history subcommand.\n");
1640   help_list (sethistlist, "set history ", -1, gdb_stdout);
1641 }
1642
1643 void
1644 show_history (char *args, int from_tty)
1645 {
1646   cmd_show_list (showhistlist, from_tty, "");
1647 }
1648
1649 int info_verbose = 0;           /* Default verbose msgs off */
1650
1651 /* Called by do_setshow_command.  An elaborate joke.  */
1652 void
1653 set_verbose (char *args, int from_tty, struct cmd_list_element *c)
1654 {
1655   char *cmdname = "verbose";
1656   struct cmd_list_element *showcmd;
1657
1658   showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, 1);
1659
1660   if (info_verbose)
1661     {
1662       c->doc = "Set verbose printing of informational messages.";
1663       showcmd->doc = "Show verbose printing of informational messages.";
1664     }
1665   else
1666     {
1667       c->doc = "Set verbosity.";
1668       showcmd->doc = "Show verbosity.";
1669     }
1670 }
1671
1672 /* Init the history buffer.  Note that we are called after the init file(s)
1673  * have been read so that the user can change the history file via his
1674  * .gdbinit file (for instance).  The GDBHISTFILE environment variable
1675  * overrides all of this.
1676  */
1677
1678 void
1679 init_history (void)
1680 {
1681   char *tmpenv;
1682
1683   tmpenv = getenv ("HISTSIZE");
1684   if (tmpenv)
1685     history_size = atoi (tmpenv);
1686   else if (!history_size)
1687     history_size = 256;
1688
1689   stifle_history (history_size);
1690
1691   tmpenv = getenv ("GDBHISTFILE");
1692   if (tmpenv)
1693     history_filename = savestring (tmpenv, strlen (tmpenv));
1694   else if (!history_filename)
1695     {
1696       /* We include the current directory so that if the user changes
1697          directories the file written will be the same as the one
1698          that was read.  */
1699 #ifdef __MSDOS__
1700       /* No leading dots in file names are allowed on MSDOS.  */
1701       history_filename = concat (current_directory, "/_gdb_history", NULL);
1702 #else
1703       history_filename = concat (current_directory, "/.gdb_history", NULL);
1704 #endif
1705     }
1706   read_history (history_filename);
1707 }
1708
1709 static void
1710 init_main (void)
1711 {
1712   struct cmd_list_element *c;
1713
1714   /* If we are running the asynchronous version,
1715      we initialize the prompts differently. */
1716   if (!event_loop_p)
1717     {
1718       gdb_prompt_string = savestring (DEFAULT_PROMPT, strlen (DEFAULT_PROMPT));
1719     }
1720   else
1721     {
1722       /* initialize the prompt stack to a simple "(gdb) " prompt or to
1723          whatever the DEFAULT_PROMPT is. */
1724       the_prompts.top = 0;
1725       PREFIX (0) = "";
1726       PROMPT (0) = savestring (DEFAULT_PROMPT, strlen (DEFAULT_PROMPT));
1727       SUFFIX (0) = "";
1728       /* Set things up for annotation_level > 1, if the user ever decides
1729          to use it. */
1730       async_annotation_suffix = "prompt";
1731       /* Set the variable associated with the setshow prompt command. */
1732       new_async_prompt = savestring (PROMPT (0), strlen (PROMPT (0)));
1733
1734       /* If gdb was started with --annotate=2, this is equivalent to
1735          the user entering the command 'set annotate 2' at the gdb
1736          prompt, so we need to do extra processing. */
1737       if (annotation_level > 1)
1738         set_async_annotation_level (NULL, 0, NULL);
1739     }
1740
1741   /* Set the important stuff up for command editing.  */
1742   command_editing_p = 1;
1743   history_expansion_p = 0;
1744   write_history_p = 0;
1745
1746   /* Setup important stuff for command line editing.  */
1747   rl_completion_entry_function = readline_line_completion_function;
1748   rl_completer_word_break_characters = default_word_break_characters ();
1749   rl_completer_quote_characters = get_gdb_completer_quote_characters ();
1750   rl_readline_name = "gdb";
1751   rl_terminal_name = getenv ("TERM");
1752
1753   /* The name for this defun comes from Bash, where it originated.
1754      15 is Control-o, the same binding this function has in Bash.  */
1755   rl_add_defun ("operate-and-get-next", gdb_rl_operate_and_get_next, 15);
1756
1757   /* The set prompt command is different depending whether or not the
1758      async version is run. NOTE: this difference is going to
1759      disappear as we make the event loop be the default engine of
1760      gdb. */
1761   if (!event_loop_p)
1762     {
1763       add_show_from_set
1764         (add_set_cmd ("prompt", class_support, var_string,
1765                       (char *) &gdb_prompt_string, "Set gdb's prompt",
1766                       &setlist),
1767          &showlist);
1768     }
1769   else
1770     {
1771       c = add_set_cmd ("prompt", class_support, var_string,
1772                        (char *) &new_async_prompt, "Set gdb's prompt",
1773                        &setlist);
1774       add_show_from_set (c, &showlist);
1775       set_cmd_sfunc (c, set_async_prompt);
1776     }
1777
1778   add_com ("dont-repeat", class_support, dont_repeat_command, "Don't repeat this command.\n\
1779 Primarily used inside of user-defined commands that should not be repeated when\n\
1780 hitting return.");
1781
1782   /* The set editing command is different depending whether or not the
1783      async version is run. NOTE: this difference is going to disappear
1784      as we make the event loop be the default engine of gdb. */
1785   if (!event_loop_p)
1786     {
1787       add_show_from_set
1788         (add_set_cmd ("editing", class_support, var_boolean, (char *) &command_editing_p,
1789                       "Set editing of command lines as they are typed.\n\
1790 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
1791 Without an argument, command line editing is enabled.  To edit, use\n\
1792 EMACS-like or VI-like commands like control-P or ESC.", &setlist),
1793          &showlist);
1794     }
1795   else
1796     {
1797       c = add_set_cmd ("editing", class_support, var_boolean, (char *) &async_command_editing_p,
1798                        "Set editing of command lines as they are typed.\n\
1799 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
1800 Without an argument, command line editing is enabled.  To edit, use\n\
1801 EMACS-like or VI-like commands like control-P or ESC.", &setlist);
1802
1803       add_show_from_set (c, &showlist);
1804       set_cmd_sfunc (c, set_async_editing_command);
1805     }
1806
1807   add_show_from_set
1808     (add_set_cmd ("save", no_class, var_boolean, (char *) &write_history_p,
1809                   "Set saving of the history record on exit.\n\
1810 Use \"on\" to enable the saving, and \"off\" to disable it.\n\
1811 Without an argument, saving is enabled.", &sethistlist),
1812      &showhistlist);
1813
1814   c = add_set_cmd ("size", no_class, var_integer, (char *) &history_size,
1815                    "Set the size of the command history,\n\
1816 ie. the number of previous commands to keep a record of.", &sethistlist);
1817   add_show_from_set (c, &showhistlist);
1818   set_cmd_sfunc (c, set_history_size_command);
1819
1820   c = add_set_cmd ("filename", no_class, var_filename,
1821                    (char *) &history_filename,
1822                    "Set the filename in which to record the command history\n\
1823 (the list of previous commands of which a record is kept).", &sethistlist);
1824   set_cmd_completer (c, filename_completer);
1825   add_show_from_set (c, &showhistlist);
1826
1827   add_show_from_set
1828     (add_set_cmd ("confirm", class_support, var_boolean,
1829                   (char *) &caution,
1830                   "Set whether to confirm potentially dangerous operations.",
1831                   &setlist),
1832      &showlist);
1833
1834   /* The set annotate command is different depending whether or not
1835      the async version is run. NOTE: this difference is going to
1836      disappear as we make the event loop be the default engine of
1837      gdb. */
1838   if (!event_loop_p)
1839     {
1840       c = add_set_cmd ("annotate", class_obscure, var_zinteger,
1841                        (char *) &annotation_level, "Set annotation_level.\n\
1842 0 == normal;     1 == fullname (for use when running under emacs)\n\
1843 2 == output annotated suitably for use by programs that control GDB.",
1844                        &setlist);
1845       c = add_show_from_set (c, &showlist);
1846     }
1847   else
1848     {
1849       c = add_set_cmd ("annotate", class_obscure, var_zinteger,
1850                        (char *) &annotation_level, "Set annotation_level.\n\
1851 0 == normal;     1 == fullname (for use when running under emacs)\n\
1852 2 == output annotated suitably for use by programs that control GDB.",
1853                        &setlist);
1854       add_show_from_set (c, &showlist);
1855       set_cmd_sfunc (c, set_async_annotation_level);
1856     }
1857   if (event_loop_p)
1858     {
1859       add_show_from_set
1860         (add_set_cmd ("exec-done-display", class_support, var_boolean, (char *) &exec_done_display_p,
1861                       "Set notification of completion for asynchronous execution commands.\n\
1862 Use \"on\" to enable the notification, and \"off\" to disable it.", &setlist),
1863          &showlist);
1864     }
1865 }
1866
1867 void
1868 gdb_init (char *argv0)
1869 {
1870   if (pre_init_ui_hook)
1871     pre_init_ui_hook ();
1872
1873   /* Run the init function of each source file */
1874
1875   getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
1876   current_directory = gdb_dirbuf;
1877
1878 #ifdef __MSDOS__
1879   /* Make sure we return to the original directory upon exit, come
1880      what may, since the OS doesn't do that for us.  */
1881   make_final_cleanup (do_chdir_cleanup, xstrdup (current_directory));
1882 #endif
1883
1884   init_cmd_lists ();            /* This needs to be done first */
1885   initialize_targets ();        /* Setup target_terminal macros for utils.c */
1886   initialize_utils ();          /* Make errors and warnings possible */
1887   initialize_all_files ();
1888   initialize_current_architecture ();
1889   init_cli_cmds();
1890   init_main ();                 /* But that omits this file!  Do it now */
1891
1892   /* The signal handling mechanism is different depending whether or
1893      not the async version is run. NOTE: in the future we plan to make
1894      the event loop be the default engine of gdb, and this difference
1895      will disappear. */
1896   if (event_loop_p)
1897     async_init_signals ();
1898   else
1899     init_signals ();
1900
1901   /* We need a default language for parsing expressions, so simple things like
1902      "set width 0" won't fail if no language is explicitly set in a config file
1903      or implicitly set by reading an executable during startup. */
1904   set_language (language_c);
1905   expected_language = current_language;         /* don't warn about the change.  */
1906
1907   /* Allow another UI to initialize. If the UI fails to initialize, and
1908      it wants GDB to revert to the CLI, it should clear init_ui_hook. */
1909   if (init_ui_hook)
1910     init_ui_hook (argv0);
1911 }