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