import gdb-2000-02-02 snapshot
[platform/upstream/binutils.git] / gdb / top.c
1 /* Top level stuff for GDB, the GNU debugger.
2    Copyright 1986-2000 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include "gdbcmd.h"
23 #include "call-cmds.h"
24 #include "symtab.h"
25 #include "inferior.h"
26 #include "signals.h"
27 #include "target.h"
28 #include "breakpoint.h"
29 #include "gdbtypes.h"
30 #include "expression.h"
31 #include "value.h"
32 #include "language.h"
33 #include "terminal.h"           /* For job_control.  */
34 #include "annotate.h"
35 #include "top.h"
36 #include "version.h"
37
38 /* readline include files */
39 #include <readline/readline.h>
40 #include <readline/history.h>
41
42 /* readline defines this.  */
43 #undef savestring
44
45 #include <sys/types.h>
46
47 #include <setjmp.h>
48
49 #include "event-top.h"
50 #include "gdb_string.h"
51 #include "gdb_stat.h"
52 #include <ctype.h>
53 #ifdef UI_OUT
54 #include "ui-out.h"
55 #include "cli-out.h"
56 #endif
57
58 /* Prototypes for local functions */
59
60 static void dont_repeat_command PARAMS ((char *, int));
61
62 static void source_cleanup_lines PARAMS ((PTR));
63
64 static void user_defined_command PARAMS ((char *, int));
65
66 static void init_signals PARAMS ((void));
67
68 #ifdef STOP_SIGNAL
69 static void stop_sig PARAMS ((int));
70 #endif
71
72 static char *line_completion_function PARAMS ((char *, int, char *, int));
73
74 static char *readline_line_completion_function PARAMS ((char *, int));
75
76 /* NOTE 1999-04-29: this function will be static again, after we make the
77    event loop be the default command loop for gdb, and we merge
78    event-top.c into this file, top.c */
79 /* static */ void command_loop_marker PARAMS ((int));
80
81 static void while_command PARAMS ((char *, int));
82
83 static void if_command PARAMS ((char *, int));
84
85 static struct command_line *
86   build_command_line PARAMS ((enum command_control_type, char *));
87
88 static struct command_line *
89   get_command_line PARAMS ((enum command_control_type, char *));
90
91 static void realloc_body_list PARAMS ((struct command_line *, int));
92
93 static enum misc_command_type read_next_line PARAMS ((struct command_line **));
94
95 static enum command_control_type
96 recurse_read_control_structure PARAMS ((struct command_line *));
97
98 static struct cleanup *setup_user_args PARAMS ((char *));
99
100 static char *locate_arg PARAMS ((char *));
101
102 static char *insert_args PARAMS ((char *));
103
104 static void arg_cleanup PARAMS ((void));
105
106 static void init_main PARAMS ((void));
107
108 static void init_cmd_lists PARAMS ((void));
109
110 static void float_handler PARAMS ((int));
111
112 static void init_signals PARAMS ((void));
113
114 static void set_verbose PARAMS ((char *, int, struct cmd_list_element *));
115
116 static void show_history PARAMS ((char *, int));
117
118 static void set_history PARAMS ((char *, int));
119
120 static void set_history_size_command PARAMS ((char *, int,
121                                               struct cmd_list_element *));
122
123 static void show_commands PARAMS ((char *, int));
124
125 static void echo_command PARAMS ((char *, int));
126
127 static void pwd_command PARAMS ((char *, int));
128
129 static void show_version PARAMS ((char *, int));
130
131 static void document_command PARAMS ((char *, int));
132
133 static void define_command PARAMS ((char *, int));
134
135 static void validate_comname PARAMS ((char *));
136
137 static void help_command PARAMS ((char *, int));
138
139 static void show_command PARAMS ((char *, int));
140
141 static void info_command PARAMS ((char *, int));
142
143 static void complete_command PARAMS ((char *, int));
144
145 static void do_nothing PARAMS ((int));
146
147 #ifdef SIGHUP
148 /* NOTE 1999-04-29: This function will be static again, once we modify
149    gdb to use the event loop as the default command loop and we merge
150    event-top.c into this file, top.c */
151 /* static */ int quit_cover PARAMS ((PTR));
152
153 static void disconnect PARAMS ((int));
154 #endif
155
156 static void source_cleanup PARAMS ((FILE *));
157
158 /* Default command line prompt.  This is overriden in some configs. */
159
160 #ifndef DEFAULT_PROMPT
161 #define DEFAULT_PROMPT  "(gdb) "
162 #endif
163
164 /* Initialization file name for gdb.  This is overridden in some configs.  */
165
166 #ifndef GDBINIT_FILENAME
167 #define GDBINIT_FILENAME        ".gdbinit"
168 #endif
169 char gdbinit[] = GDBINIT_FILENAME;
170
171 int inhibit_gdbinit = 0;
172
173 /* If nonzero, and GDB has been configured to be able to use windows,
174    attempt to open them upon startup.  */
175
176 int use_windows = 1;
177
178 extern char lang_frame_mismatch_warn[];         /* language.c */
179
180 /* Flag for whether we want all the "from_tty" gubbish printed.  */
181
182 int caution = 1;                /* Default is yes, sigh. */
183
184 /* Define all cmd_list_elements.  */
185
186 /* Chain containing all defined commands.  */
187
188 struct cmd_list_element *cmdlist;
189
190 /* Chain containing all defined info subcommands.  */
191
192 struct cmd_list_element *infolist;
193
194 /* Chain containing all defined enable subcommands. */
195
196 struct cmd_list_element *enablelist;
197
198 /* Chain containing all defined disable subcommands. */
199
200 struct cmd_list_element *disablelist;
201
202 /* Chain containing all defined toggle subcommands. */
203
204 struct cmd_list_element *togglelist;
205
206 /* Chain containing all defined stop subcommands. */
207
208 struct cmd_list_element *stoplist;
209
210 /* Chain containing all defined delete subcommands. */
211
212 struct cmd_list_element *deletelist;
213
214 /* Chain containing all defined "enable breakpoint" subcommands. */
215
216 struct cmd_list_element *enablebreaklist;
217
218 /* Chain containing all defined set subcommands */
219
220 struct cmd_list_element *setlist;
221
222 /* Chain containing all defined unset subcommands */
223
224 struct cmd_list_element *unsetlist;
225
226 /* Chain containing all defined show subcommands.  */
227
228 struct cmd_list_element *showlist;
229
230 /* Chain containing all defined \"set history\".  */
231
232 struct cmd_list_element *sethistlist;
233
234 /* Chain containing all defined \"show history\".  */
235
236 struct cmd_list_element *showhistlist;
237
238 /* Chain containing all defined \"unset history\".  */
239
240 struct cmd_list_element *unsethistlist;
241
242 /* Chain containing all defined maintenance subcommands. */
243
244 struct cmd_list_element *maintenancelist;
245
246 /* Chain containing all defined "maintenance info" subcommands. */
247
248 struct cmd_list_element *maintenanceinfolist;
249
250 /* Chain containing all defined "maintenance print" subcommands. */
251
252 struct cmd_list_element *maintenanceprintlist;
253
254 struct cmd_list_element *setprintlist;
255
256 struct cmd_list_element *showprintlist;
257
258 struct cmd_list_element *setchecklist;
259
260 struct cmd_list_element *showchecklist;
261
262 /* stdio stream that command input is being read from.  Set to stdin normally.
263    Set by source_command to the file we are sourcing.  Set to NULL if we are
264    executing a user-defined command or interacting via a GUI.  */
265
266 FILE *instream;
267
268 /* Current working directory.  */
269
270 char *current_directory;
271
272 /* The directory name is actually stored here (usually).  */
273 char gdb_dirbuf[1024];
274
275 /* Function to call before reading a command, if nonzero.
276    The function receives two args: an input stream,
277    and a prompt string.  */
278
279 void (*window_hook) PARAMS ((FILE *, char *));
280
281 int epoch_interface;
282 int xgdb_verbose;
283
284 /* gdb prints this when reading a command interactively */
285 static char *gdb_prompt_string; /* the global prompt string */
286 extern char *get_prompt PARAMS ((void));        /* access function for prompt string */
287
288 /* Buffer used for reading command lines, and the size
289    allocated for it so far.  */
290
291 char *line;
292 int linesize = 100;
293
294 /* Nonzero if the current command is modified by "server ".  This
295    affects things like recording into the command history, commands
296    repeating on RETURN, etc.  This is so a user interface (emacs, GUI,
297    whatever) can issue its own commands and also send along commands
298    from the user, and have the user not notice that the user interface
299    is issuing commands too.  */
300 int server_command;
301
302 /* Baud rate specified for talking to serial target systems.  Default
303    is left as -1, so targets can choose their own defaults.  */
304 /* FIXME: This means that "show remotebaud" and gr_files_info can print -1
305    or (unsigned int)-1.  This is a Bad User Interface.  */
306
307 int baud_rate = -1;
308
309 /* Timeout limit for response from target. */
310
311 int remote_timeout = 20;        /* Set default to 20 */
312
313 /* Non-zero tells remote* modules to output debugging info.  */
314
315 int remote_debug = 0;
316
317 /* Non-zero means the target is running. Note: this is different from
318    saying that there is an active target and we are stopped at a
319    breakpoint, for instance. This is a real indicator whether the
320    target is off and running, which gdb is doing something else. */
321 int target_executing = 0;
322
323 /* Level of control structure.  */
324 static int control_level;
325
326 /* Structure for arguments to user defined functions.  */
327 #define MAXUSERARGS 10
328 struct user_args
329   {
330     struct user_args *next;
331     struct
332       {
333         char *arg;
334         int len;
335       }
336     a[MAXUSERARGS];
337     int count;
338   }
339  *user_args;
340
341 /* Signal to catch ^Z typed while reading a command: SIGTSTP or SIGCONT.  */
342
343 #ifndef STOP_SIGNAL
344 #ifdef SIGTSTP
345 #define STOP_SIGNAL SIGTSTP
346 static void stop_sig PARAMS ((int));
347 #endif
348 #endif
349
350 /* Some System V have job control but not sigsetmask(). */
351 #if !defined (HAVE_SIGSETMASK)
352 #if !defined (USG)
353 #define HAVE_SIGSETMASK 1
354 #else
355 #define HAVE_SIGSETMASK 0
356 #endif
357 #endif
358
359 #if 0 == (HAVE_SIGSETMASK)
360 #define sigsetmask(n)
361 #endif
362
363 /* Hooks for alternate command interfaces.  */
364
365 /* Called after most modules have been initialized, but before taking users
366    command file.  */
367
368 void (*init_ui_hook) PARAMS ((char *argv0));
369
370 /* This hook is called from within gdb's many mini-event loops which could
371    steal control from a real user interface's event loop. It returns
372    non-zero if the user is requesting a detach, zero otherwise. */
373
374 int (*ui_loop_hook) PARAMS ((int));
375
376 /* Called instead of command_loop at top level.  Can be invoked via
377    return_to_top_level.  */
378
379 void (*command_loop_hook) PARAMS ((void));
380
381
382 /* Called from print_frame_info to list the line we stopped in.  */
383
384 void (*print_frame_info_listing_hook) PARAMS ((struct symtab * s, int line,
385                                                int stopline, int noerror));
386 /* Replaces most of query.  */
387
388 int (*query_hook) PARAMS ((const char *, va_list));
389
390 /* Replaces most of warning.  */
391
392 void (*warning_hook) PARAMS ((const char *, va_list));
393
394 /* These three functions support getting lines of text from the user.  They
395    are used in sequence.  First readline_begin_hook is called with a text
396    string that might be (for example) a message for the user to type in a
397    sequence of commands to be executed at a breakpoint.  If this function
398    calls back to a GUI, it might take this opportunity to pop up a text
399    interaction window with this message.  Next, readline_hook is called
400    with a prompt that is emitted prior to collecting the user input.
401    It can be called multiple times.  Finally, readline_end_hook is called
402    to notify the GUI that we are done with the interaction window and it
403    can close it. */
404
405 void (*readline_begin_hook) PARAMS ((char *,...));
406 char *(*readline_hook) PARAMS ((char *));
407 void (*readline_end_hook) PARAMS ((void));
408
409 /* Called as appropriate to notify the interface of the specified breakpoint
410    conditions.  */
411
412 void (*create_breakpoint_hook) PARAMS ((struct breakpoint * bpt));
413 void (*delete_breakpoint_hook) PARAMS ((struct breakpoint * bpt));
414 void (*modify_breakpoint_hook) PARAMS ((struct breakpoint * bpt));
415
416 /* Called as appropriate to notify the interface that we have attached
417    to or detached from an already running process. */
418
419 void (*attach_hook) PARAMS ((void));
420 void (*detach_hook) PARAMS ((void));
421
422 /* Called during long calculations to allow GUI to repair window damage, and to
423    check for stop buttons, etc... */
424
425 void (*interactive_hook) PARAMS ((void));
426
427 /* Called when the registers have changed, as a hint to a GUI
428    to minimize window update. */
429
430 void (*registers_changed_hook) PARAMS ((void));
431
432 /* Tell the GUI someone changed the register REGNO. -1 means
433    that the caller does not know which register changed or
434    that several registers have changed (see value_assign). */
435 void (*register_changed_hook) PARAMS ((int regno));
436
437 /* Tell the GUI someone changed LEN bytes of memory at ADDR */
438 void (*memory_changed_hook) PARAMS ((CORE_ADDR addr, int len));
439
440 /* Called when going to wait for the target.  Usually allows the GUI to run
441    while waiting for target events.  */
442
443 int (*target_wait_hook) PARAMS ((int pid, struct target_waitstatus * status));
444
445 /* Used by UI as a wrapper around command execution.  May do various things
446    like enabling/disabling buttons, etc...  */
447
448 void (*call_command_hook) PARAMS ((struct cmd_list_element * c, char *cmd,
449                                    int from_tty));
450
451 /* Called after a `set' command has finished.  Is only run if the
452    `set' command succeeded.  */
453
454 void (*set_hook) PARAMS ((struct cmd_list_element *c));
455
456 /* Called when the current thread changes.  Argument is thread id.  */
457
458 void (*context_hook) PARAMS ((int id));
459
460 /* Takes control from error ().  Typically used to prevent longjmps out of the
461    middle of the GUI.  Usually used in conjunction with a catch routine.  */
462
463 NORETURN void (*error_hook)
464 PARAMS ((void)) ATTR_NORETURN;
465 \f
466
467 /* Generally one should use catch_errors rather than manipulating these
468    directly.  The exception is main().  */
469 #if defined(HAVE_SIGSETJMP)
470 #define SIGJMP_BUF              sigjmp_buf
471 #define SIGSETJMP(buf)          sigsetjmp(buf, 1)
472 #define SIGLONGJMP(buf,val)     siglongjmp(buf,val)
473 #else
474 #define SIGJMP_BUF              jmp_buf
475 #define SIGSETJMP(buf)          setjmp(buf)
476 #define SIGLONGJMP(buf,val)     longjmp(buf,val)
477 #endif
478
479 /* Where to go for return_to_top_level (RETURN_ERROR).  */
480 static SIGJMP_BUF error_return;
481 /* Where to go for return_to_top_level (RETURN_QUIT).  */
482 static SIGJMP_BUF quit_return;
483
484 /* Return for reason REASON.  This generally gets back to the command
485    loop, but can be caught via catch_errors.  */
486
487 NORETURN void
488 return_to_top_level (reason)
489      enum return_reason reason;
490 {
491   quit_flag = 0;
492   immediate_quit = 0;
493
494   /* Perhaps it would be cleaner to do this via the cleanup chain (not sure
495      I can think of a reason why that is vital, though).  */
496   bpstat_clear_actions (stop_bpstat);   /* Clear queued breakpoint commands */
497
498   disable_current_display ();
499   do_cleanups (ALL_CLEANUPS);
500   if (event_loop_p && target_can_async_p () && !target_executing)
501     do_exec_cleanups (ALL_CLEANUPS);
502   if (event_loop_p && sync_execution)
503     do_exec_error_cleanups (ALL_CLEANUPS);
504
505   if (annotation_level > 1)
506     switch (reason)
507       {
508       case RETURN_QUIT:
509         annotate_quit ();
510         break;
511       case RETURN_ERROR:
512         annotate_error ();
513         break;
514       }
515
516   (NORETURN void) SIGLONGJMP
517     (reason == RETURN_ERROR ? error_return : quit_return, 1);
518 }
519
520 /* Call FUNC with arg ARGS, catching any errors.  If there is no
521    error, return the value returned by FUNC.  If there is an error,
522    print ERRSTRING, print the specific error message, then return
523    zero.
524
525    Must not be called with immediate_quit in effect (bad things might
526    happen, say we got a signal in the middle of a memcpy to quit_return).
527    This is an OK restriction; with very few exceptions immediate_quit can
528    be replaced by judicious use of QUIT.
529
530    MASK specifies what to catch; it is normally set to
531    RETURN_MASK_ALL, if for no other reason than that the code which
532    calls catch_errors might not be set up to deal with a quit which
533    isn't caught.  But if the code can deal with it, it generally
534    should be RETURN_MASK_ERROR, unless for some reason it is more
535    useful to abort only the portion of the operation inside the
536    catch_errors.  Note that quit should return to the command line
537    fairly quickly, even if some further processing is being done.  */
538
539 /* MAYBE: cagney/1999-11-05: catch_errors() in conjunction with
540    error() et.al. could maintain a set of flags that indicate the the
541    current state of each of the longjmp buffers.  This would give the
542    longjmp code the chance to detect a longjmp botch (before it gets
543    to longjmperror()).  Prior to 1999-11-05 this wasn't possible as
544    code also randomly used a SET_TOP_LEVEL macro that directly
545    initialize the longjmp buffers. */
546
547 /* MAYBE: cagney/1999-11-05: Since the SET_TOP_LEVEL macro has been
548    eliminated it is now possible to use the stack to directly store
549    each longjmp buffer.  The global code would just need to update a
550    pointer (onto the stack - ulgh!?) indicating the current longjmp
551    buffers. It would certainly improve the performance of the longjmp
552    code since the memcpy's would be eliminated. */
553
554 /* MAYBE: cagney/1999-11-05: Should the catch_erros and cleanups code
555    be consolidated into a single file instead of being distributed
556    between utils.c and top.c? */
557
558 int
559 catch_errors (func, args, errstring, mask)
560      catch_errors_ftype *func;
561      PTR args;
562      char *errstring;
563      return_mask mask;
564 {
565   SIGJMP_BUF saved_error;
566   SIGJMP_BUF saved_quit;
567   SIGJMP_BUF tmp_jmp;
568   int val;
569   struct cleanup *saved_cleanup_chain;
570   char *saved_error_pre_print;
571   char *saved_quit_pre_print;
572
573   saved_cleanup_chain = save_cleanups ();
574   saved_error_pre_print = error_pre_print;
575   saved_quit_pre_print = quit_pre_print;
576
577   if (mask & RETURN_MASK_ERROR)
578     {
579       memcpy ((char *) saved_error, (char *) error_return, sizeof (SIGJMP_BUF));
580       error_pre_print = errstring;
581     }
582   if (mask & RETURN_MASK_QUIT)
583     {
584       memcpy (saved_quit, quit_return, sizeof (SIGJMP_BUF));
585       quit_pre_print = errstring;
586     }
587
588   if (SIGSETJMP (tmp_jmp) == 0)
589     {
590       if (mask & RETURN_MASK_ERROR)
591         memcpy (error_return, tmp_jmp, sizeof (SIGJMP_BUF));
592       if (mask & RETURN_MASK_QUIT)
593         memcpy (quit_return, tmp_jmp, sizeof (SIGJMP_BUF));
594       val = (*func) (args);
595       /* FIXME: cagney/1999-11-05: A correct FUNC implementaton will
596          clean things up (restoring the cleanup chain) to the state
597          they were just prior to the call.  Technically, this means
598          that the below restore_cleanups call is redundant.
599          Unfortunatly, many FUNC's are not that well behaved.
600          restore_cleanups should either be replaced with a do_cleanups
601          call (to cover the problem) or an assertion check to detect
602          bad FUNCs code. */
603     }
604   else
605     val = 0;
606
607   restore_cleanups (saved_cleanup_chain);
608
609   if (mask & RETURN_MASK_ERROR)
610     {
611       memcpy (error_return, saved_error, sizeof (SIGJMP_BUF));
612       error_pre_print = saved_error_pre_print;
613     }
614   if (mask & RETURN_MASK_QUIT)
615     {
616       memcpy (quit_return, saved_quit, sizeof (SIGJMP_BUF));
617       quit_pre_print = saved_quit_pre_print;
618     }
619   return val;
620 }
621
622 struct captured_command_args
623   {
624     catch_command_errors_ftype *command;
625     char *arg;
626     int from_tty;
627   };
628
629 static int
630 do_captured_command (void *data)
631 {
632   struct captured_command_args *context = data;
633   context->command (context->arg, context->from_tty);
634   /* FIXME: cagney/1999-11-07: Technically this do_cleanups() call
635      isn't needed.  Instead an assertion check could be made that
636      simply confirmed that the called function correctly cleaned up
637      after its self.  Unfortunatly, old code (prior to 1999-11-04) in
638      main.c was calling SET_TOP_LEVEL(), calling the command function,
639      and then *always* calling do_cleanups().  For the moment we
640      remain ``bug compatible'' with that old code..  */
641   do_cleanups (ALL_CLEANUPS);
642   return 1;
643 }
644
645 int
646 catch_command_errors (catch_command_errors_ftype *command,
647                       char *arg, int from_tty, return_mask mask)
648 {
649   struct captured_command_args args;
650   args.command = command;
651   args.arg = arg;
652   args.from_tty = from_tty;
653   return catch_errors (do_captured_command, &args, "", mask);
654 }
655
656
657 /* Handler for SIGHUP.  */
658
659 #ifdef SIGHUP
660 static void
661 disconnect (signo)
662      int signo;
663 {
664   catch_errors (quit_cover, NULL,
665               "Could not kill the program being debugged", RETURN_MASK_ALL);
666   signal (SIGHUP, SIG_DFL);
667   kill (getpid (), SIGHUP);
668 }
669
670 /* Just a little helper function for disconnect().  */
671
672 /* NOTE 1999-04-29: This function will be static again, once we modify
673    gdb to use the event loop as the default command loop and we merge
674    event-top.c into this file, top.c */
675 /* static */ int
676 quit_cover (s)
677      PTR s;
678 {
679   caution = 0;                  /* Throw caution to the wind -- we're exiting.
680                                    This prevents asking the user dumb questions.  */
681   quit_command ((char *) 0, 0);
682   return 0;
683 }
684 #endif /* defined SIGHUP */
685 \f
686 /* Line number we are currently in in a file which is being sourced.  */
687 /* NOTE 1999-04-29: This variable will be static again, once we modify
688    gdb to use the event loop as the default command loop and we merge
689    event-top.c into this file, top.c */
690 /* static */ int source_line_number;
691
692 /* Name of the file we are sourcing.  */
693 /* NOTE 1999-04-29: This variable will be static again, once we modify
694    gdb to use the event loop as the default command loop and we merge
695    event-top.c into this file, top.c */
696 /* static */ char *source_file_name;
697
698 /* Buffer containing the error_pre_print used by the source stuff.
699    Malloc'd.  */
700 /* NOTE 1999-04-29: This variable will be static again, once we modify
701    gdb to use the event loop as the default command loop and we merge
702    event-top.c into this file, top.c */
703 /* static */ char *source_error;
704 static int source_error_allocated;
705
706 /* Something to glom on to the start of error_pre_print if source_file_name
707    is set.  */
708 /* NOTE 1999-04-29: This variable will be static again, once we modify
709    gdb to use the event loop as the default command loop and we merge
710    event-top.c into this file, top.c */
711 /* static */ char *source_pre_error;
712
713 /* Clean up on error during a "source" command (or execution of a
714    user-defined command).  */
715
716 static void
717 source_cleanup (stream)
718      FILE *stream;
719 {
720   /* Restore the previous input stream.  */
721   instream = stream;
722 }
723
724 /* Read commands from STREAM.  */
725 void
726 read_command_file (stream)
727      FILE *stream;
728 {
729   struct cleanup *cleanups;
730
731   cleanups = make_cleanup ((make_cleanup_func) source_cleanup, instream);
732   instream = stream;
733   command_loop ();
734   do_cleanups (cleanups);
735 }
736 \f
737 extern void init_proc PARAMS ((void));
738
739 void (*pre_init_ui_hook) PARAMS ((void));
740
741 void
742 gdb_init (argv0)
743      char *argv0;
744 {
745   if (pre_init_ui_hook)
746     pre_init_ui_hook ();
747
748   /* Run the init function of each source file */
749
750   getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
751   current_directory = gdb_dirbuf;
752
753 #ifdef __MSDOS__
754   /* Make sure we return to the original directory upon exit, come
755      what may, since the OS doesn't do that for us.  */
756   make_final_cleanup ((make_cleanup_func) chdir, strsave (current_directory));
757 #endif
758
759   init_cmd_lists ();            /* This needs to be done first */
760   initialize_targets ();        /* Setup target_terminal macros for utils.c */
761   initialize_utils ();          /* Make errors and warnings possible */
762   initialize_all_files ();
763   initialize_current_architecture ();
764   init_main ();                 /* But that omits this file!  Do it now */
765
766   /* The signal handling mechanism is different depending whether or
767      not the async version is run. NOTE: in the future we plan to make
768      the event loop be the default engine of gdb, and this difference
769      will disappear. */
770   if (event_loop_p)
771     async_init_signals ();
772   else
773     init_signals ();
774
775   /* We need a default language for parsing expressions, so simple things like
776      "set width 0" won't fail if no language is explicitly set in a config file
777      or implicitly set by reading an executable during startup. */
778   set_language (language_c);
779   expected_language = current_language;         /* don't warn about the change.  */
780
781 #ifdef UI_OUT
782   /* Install the default UI */
783   uiout = cli_out_new (gdb_stdout);
784 #endif
785
786   if (init_ui_hook)
787     init_ui_hook (argv0);
788 }
789
790 /* Allocate, initialize a new command line structure for one of the
791    control commands (if/while).  */
792
793 static struct command_line *
794 build_command_line (type, args)
795      enum command_control_type type;
796      char *args;
797 {
798   struct command_line *cmd;
799
800   if (args == NULL)
801     error ("if/while commands require arguments.\n");
802
803   cmd = (struct command_line *) xmalloc (sizeof (struct command_line));
804   cmd->next = NULL;
805   cmd->control_type = type;
806
807   cmd->body_count = 1;
808   cmd->body_list
809     = (struct command_line **) xmalloc (sizeof (struct command_line *)
810                                         * cmd->body_count);
811   memset (cmd->body_list, 0, sizeof (struct command_line *) * cmd->body_count);
812   cmd->line = savestring (args, strlen (args));
813   return cmd;
814 }
815
816 /* Build and return a new command structure for the control commands
817    such as "if" and "while".  */
818
819 static struct command_line *
820 get_command_line (type, arg)
821      enum command_control_type type;
822      char *arg;
823 {
824   struct command_line *cmd;
825   struct cleanup *old_chain = NULL;
826
827   /* Allocate and build a new command line structure.  */
828   cmd = build_command_line (type, arg);
829
830   old_chain = make_cleanup ((make_cleanup_func) free_command_lines, &cmd);
831
832   /* Read in the body of this command.  */
833   if (recurse_read_control_structure (cmd) == invalid_control)
834     {
835       warning ("error reading in control structure\n");
836       do_cleanups (old_chain);
837       return NULL;
838     }
839
840   discard_cleanups (old_chain);
841   return cmd;
842 }
843
844 /* Recursively print a command (including full control structures).  */
845 #ifdef UI_OUT
846 void
847 print_command_lines (uiout, cmd, depth)
848      struct ui_out *uiout;
849      struct command_line *cmd;
850      unsigned int depth;
851 {
852   struct command_line *list;
853
854   list = cmd;
855   while (list)
856     {
857
858       if (depth)
859         ui_out_spaces (uiout, 2 * depth);
860
861       /* A simple command, print it and continue.  */
862       if (list->control_type == simple_control)
863         {
864           ui_out_field_string (uiout, NULL, list->line);
865           ui_out_text (uiout, "\n");
866           list = list->next;
867           continue;
868         }
869
870       /* loop_continue to jump to the start of a while loop, print it
871          and continue. */
872       if (list->control_type == continue_control)
873         {
874           ui_out_field_string (uiout, NULL, "loop_continue");
875           ui_out_text (uiout, "\n");
876           list = list->next;
877           continue;
878         }
879
880       /* loop_break to break out of a while loop, print it and continue.  */
881       if (list->control_type == break_control)
882         {
883           ui_out_field_string (uiout, NULL, "loop_break");
884           ui_out_text (uiout, "\n");
885           list = list->next;
886           continue;
887         }
888
889       /* A while command.  Recursively print its subcommands and continue.  */
890       if (list->control_type == while_control)
891         {
892           ui_out_text (uiout, "while ");
893           ui_out_field_fmt (uiout, NULL, "while %s", list->line);
894           ui_out_text (uiout, "\n");
895           print_command_lines (uiout, *list->body_list, depth + 1);
896           ui_out_field_string (uiout, NULL, "end");
897           if (depth)
898             ui_out_spaces (uiout, 2 * depth);
899           ui_out_text (uiout, "end\n");
900           list = list->next;
901           continue;
902         }
903
904       /* An if command.  Recursively print both arms before continueing.  */
905       if (list->control_type == if_control)
906         {
907           ui_out_text (uiout, "if ");
908           ui_out_field_fmt (uiout, NULL, "if %s", list->line);
909           ui_out_text (uiout, "\n");
910           /* The true arm. */
911           print_command_lines (uiout, list->body_list[0], depth + 1);
912
913           /* Show the false arm if it exists.  */
914           if (list->body_count == 2)
915             {
916               if (depth)
917                 ui_out_spaces (uiout, 2 * depth);
918               ui_out_field_string (uiout, NULL, "else");
919               ui_out_text (uiout, "else\n");
920               print_command_lines (uiout, list->body_list[1], depth + 1);
921             }
922
923           ui_out_field_string (uiout, NULL, "end");
924           if (depth)
925             ui_out_spaces (uiout, 2 * depth);
926           ui_out_text (uiout, "end\n");
927           list = list->next;
928           continue;
929         }
930
931       /* ignore illegal command type and try next */
932       list = list->next;
933     }                           /* while (list) */
934 }
935 #else
936 void
937 print_command_line (cmd, depth, stream)
938      struct command_line *cmd;
939      unsigned int depth;
940      struct ui_file *stream;
941 {
942   unsigned int i;
943
944   if (depth)
945     {
946       for (i = 0; i < depth; i++)
947         fputs_filtered ("  ", stream);
948     }
949
950   /* A simple command, print it and return.  */
951   if (cmd->control_type == simple_control)
952     {
953       fputs_filtered (cmd->line, stream);
954       fputs_filtered ("\n", stream);
955       return;
956     }
957
958   /* loop_continue to jump to the start of a while loop, print it
959      and return. */
960   if (cmd->control_type == continue_control)
961     {
962       fputs_filtered ("loop_continue\n", stream);
963       return;
964     }
965
966   /* loop_break to break out of a while loop, print it and return.  */
967   if (cmd->control_type == break_control)
968     {
969       fputs_filtered ("loop_break\n", stream);
970       return;
971     }
972
973   /* A while command.  Recursively print its subcommands before returning.  */
974   if (cmd->control_type == while_control)
975     {
976       struct command_line *list;
977       fputs_filtered ("while ", stream);
978       fputs_filtered (cmd->line, stream);
979       fputs_filtered ("\n", stream);
980       list = *cmd->body_list;
981       while (list)
982         {
983           print_command_line (list, depth + 1, stream);
984           list = list->next;
985         }
986     }
987
988   /* An if command.  Recursively print both arms before returning.  */
989   if (cmd->control_type == if_control)
990     {
991       fputs_filtered ("if ", stream);
992       fputs_filtered (cmd->line, stream);
993       fputs_filtered ("\n", stream);
994       /* The true arm. */
995       print_command_line (cmd->body_list[0], depth + 1, stream);
996
997       /* Show the false arm if it exists.  */
998       if (cmd->body_count == 2)
999         {
1000           if (depth)
1001             {
1002               for (i = 0; i < depth; i++)
1003                 fputs_filtered ("  ", stream);
1004             }
1005           fputs_filtered ("else\n", stream);
1006           print_command_line (cmd->body_list[1], depth + 1, stream);
1007         }
1008       if (depth)
1009         {
1010           for (i = 0; i < depth; i++)
1011             fputs_filtered ("  ", stream);
1012         }
1013       fputs_filtered ("end\n", stream);
1014     }
1015 }
1016 #endif
1017
1018 /* Execute the command in CMD.  */
1019
1020 enum command_control_type
1021 execute_control_command (cmd)
1022      struct command_line *cmd;
1023 {
1024   struct expression *expr;
1025   struct command_line *current;
1026   struct cleanup *old_chain = 0;
1027   value_ptr val;
1028   value_ptr val_mark;
1029   int loop;
1030   enum command_control_type ret;
1031   char *new_line;
1032
1033   switch (cmd->control_type)
1034     {
1035     case simple_control:
1036       /* A simple command, execute it and return.  */
1037       new_line = insert_args (cmd->line);
1038       if (!new_line)
1039         return invalid_control;
1040       old_chain = make_cleanup ((make_cleanup_func) free_current_contents,
1041                                 &new_line);
1042       execute_command (new_line, 0);
1043       ret = cmd->control_type;
1044       break;
1045
1046     case continue_control:
1047     case break_control:
1048       /* Return for "continue", and "break" so we can either
1049          continue the loop at the top, or break out.  */
1050       ret = cmd->control_type;
1051       break;
1052
1053     case while_control:
1054       {
1055         /* Parse the loop control expression for the while statement.  */
1056         new_line = insert_args (cmd->line);
1057         if (!new_line)
1058           return invalid_control;
1059         old_chain = make_cleanup ((make_cleanup_func) free_current_contents,
1060                                   &new_line);
1061         expr = parse_expression (new_line);
1062         make_cleanup ((make_cleanup_func) free_current_contents, &expr);
1063
1064         ret = simple_control;
1065         loop = 1;
1066
1067         /* Keep iterating so long as the expression is true.  */
1068         while (loop == 1)
1069           {
1070             int cond_result;
1071
1072             QUIT;
1073
1074             /* Evaluate the expression.  */
1075             val_mark = value_mark ();
1076             val = evaluate_expression (expr);
1077             cond_result = value_true (val);
1078             value_free_to_mark (val_mark);
1079
1080             /* If the value is false, then break out of the loop.  */
1081             if (!cond_result)
1082               break;
1083
1084             /* Execute the body of the while statement.  */
1085             current = *cmd->body_list;
1086             while (current)
1087               {
1088                 ret = execute_control_command (current);
1089
1090                 /* If we got an error, or a "break" command, then stop
1091                    looping.  */
1092                 if (ret == invalid_control || ret == break_control)
1093                   {
1094                     loop = 0;
1095                     break;
1096                   }
1097
1098                 /* If we got a "continue" command, then restart the loop
1099                    at this point.  */
1100                 if (ret == continue_control)
1101                   break;
1102
1103                 /* Get the next statement.  */
1104                 current = current->next;
1105               }
1106           }
1107
1108         /* Reset RET so that we don't recurse the break all the way down.  */
1109         if (ret == break_control)
1110           ret = simple_control;
1111
1112         break;
1113       }
1114
1115     case if_control:
1116       {
1117         new_line = insert_args (cmd->line);
1118         if (!new_line)
1119           return invalid_control;
1120         old_chain = make_cleanup ((make_cleanup_func) free_current_contents,
1121                                   &new_line);
1122         /* Parse the conditional for the if statement.  */
1123         expr = parse_expression (new_line);
1124         make_cleanup ((make_cleanup_func) free_current_contents, &expr);
1125
1126         current = NULL;
1127         ret = simple_control;
1128
1129         /* Evaluate the conditional.  */
1130         val_mark = value_mark ();
1131         val = evaluate_expression (expr);
1132
1133         /* Choose which arm to take commands from based on the value of the
1134            conditional expression.  */
1135         if (value_true (val))
1136           current = *cmd->body_list;
1137         else if (cmd->body_count == 2)
1138           current = *(cmd->body_list + 1);
1139         value_free_to_mark (val_mark);
1140
1141         /* Execute commands in the given arm.  */
1142         while (current)
1143           {
1144             ret = execute_control_command (current);
1145
1146             /* If we got an error, get out.  */
1147             if (ret != simple_control)
1148               break;
1149
1150             /* Get the next statement in the body.  */
1151             current = current->next;
1152           }
1153
1154         break;
1155       }
1156
1157     default:
1158       warning ("Invalid control type in command structure.");
1159       return invalid_control;
1160     }
1161
1162   if (old_chain)
1163     do_cleanups (old_chain);
1164
1165   return ret;
1166 }
1167
1168 /* "while" command support.  Executes a body of statements while the
1169    loop condition is nonzero.  */
1170
1171 static void
1172 while_command (arg, from_tty)
1173      char *arg;
1174      int from_tty;
1175 {
1176   struct command_line *command = NULL;
1177
1178   control_level = 1;
1179   command = get_command_line (while_control, arg);
1180
1181   if (command == NULL)
1182     return;
1183
1184   execute_control_command (command);
1185   free_command_lines (&command);
1186 }
1187
1188 /* "if" command support.  Execute either the true or false arm depending
1189    on the value of the if conditional.  */
1190
1191 static void
1192 if_command (arg, from_tty)
1193      char *arg;
1194      int from_tty;
1195 {
1196   struct command_line *command = NULL;
1197
1198   control_level = 1;
1199   command = get_command_line (if_control, arg);
1200
1201   if (command == NULL)
1202     return;
1203
1204   execute_control_command (command);
1205   free_command_lines (&command);
1206 }
1207
1208 /* Cleanup */
1209 static void
1210 arg_cleanup ()
1211 {
1212   struct user_args *oargs = user_args;
1213   if (!user_args)
1214     internal_error ("Internal error, arg_cleanup called with no user args.\n");
1215
1216   user_args = user_args->next;
1217   free (oargs);
1218 }
1219
1220 /* Bind the incomming arguments for a user defined command to
1221    $arg0, $arg1 ... $argMAXUSERARGS.  */
1222
1223 static struct cleanup *
1224 setup_user_args (p)
1225      char *p;
1226 {
1227   struct user_args *args;
1228   struct cleanup *old_chain;
1229   unsigned int arg_count = 0;
1230
1231   args = (struct user_args *) xmalloc (sizeof (struct user_args));
1232   memset (args, 0, sizeof (struct user_args));
1233
1234   args->next = user_args;
1235   user_args = args;
1236
1237   old_chain = make_cleanup ((make_cleanup_func) arg_cleanup, 0);
1238
1239   if (p == NULL)
1240     return old_chain;
1241
1242   while (*p)
1243     {
1244       char *start_arg;
1245       int squote = 0;
1246       int dquote = 0;
1247       int bsquote = 0;
1248
1249       if (arg_count >= MAXUSERARGS)
1250         {
1251           error ("user defined function may only have %d arguments.\n",
1252                  MAXUSERARGS);
1253           return old_chain;
1254         }
1255
1256       /* Strip whitespace.  */
1257       while (*p == ' ' || *p == '\t')
1258         p++;
1259
1260       /* P now points to an argument.  */
1261       start_arg = p;
1262       user_args->a[arg_count].arg = p;
1263
1264       /* Get to the end of this argument.  */
1265       while (*p)
1266         {
1267           if (((*p == ' ' || *p == '\t')) && !squote && !dquote && !bsquote)
1268             break;
1269           else
1270             {
1271               if (bsquote)
1272                 bsquote = 0;
1273               else if (*p == '\\')
1274                 bsquote = 1;
1275               else if (squote)
1276                 {
1277                   if (*p == '\'')
1278                     squote = 0;
1279                 }
1280               else if (dquote)
1281                 {
1282                   if (*p == '"')
1283                     dquote = 0;
1284                 }
1285               else
1286                 {
1287                   if (*p == '\'')
1288                     squote = 1;
1289                   else if (*p == '"')
1290                     dquote = 1;
1291                 }
1292               p++;
1293             }
1294         }
1295
1296       user_args->a[arg_count].len = p - start_arg;
1297       arg_count++;
1298       user_args->count++;
1299     }
1300   return old_chain;
1301 }
1302
1303 /* Given character string P, return a point to the first argument ($arg),
1304    or NULL if P contains no arguments.  */
1305
1306 static char *
1307 locate_arg (p)
1308      char *p;
1309 {
1310   while ((p = strchr (p, '$')))
1311     {
1312       if (strncmp (p, "$arg", 4) == 0 && isdigit (p[4]))
1313         return p;
1314       p++;
1315     }
1316   return NULL;
1317 }
1318
1319 /* Insert the user defined arguments stored in user_arg into the $arg
1320    arguments found in line, with the updated copy being placed into nline.  */
1321
1322 static char *
1323 insert_args (line)
1324      char *line;
1325 {
1326   char *p, *save_line, *new_line;
1327   unsigned len, i;
1328
1329   /* First we need to know how much memory to allocate for the new line.  */
1330   save_line = line;
1331   len = 0;
1332   while ((p = locate_arg (line)))
1333     {
1334       len += p - line;
1335       i = p[4] - '0';
1336
1337       if (i >= user_args->count)
1338         {
1339           error ("Missing argument %d in user function.\n", i);
1340           return NULL;
1341         }
1342       len += user_args->a[i].len;
1343       line = p + 5;
1344     }
1345
1346   /* Don't forget the tail.  */
1347   len += strlen (line);
1348
1349   /* Allocate space for the new line and fill it in.  */
1350   new_line = (char *) xmalloc (len + 1);
1351   if (new_line == NULL)
1352     return NULL;
1353
1354   /* Restore pointer to beginning of old line.  */
1355   line = save_line;
1356
1357   /* Save pointer to beginning of new line.  */
1358   save_line = new_line;
1359
1360   while ((p = locate_arg (line)))
1361     {
1362       int i, len;
1363
1364       memcpy (new_line, line, p - line);
1365       new_line += p - line;
1366       i = p[4] - '0';
1367
1368       len = user_args->a[i].len;
1369       if (len)
1370         {
1371           memcpy (new_line, user_args->a[i].arg, len);
1372           new_line += len;
1373         }
1374       line = p + 5;
1375     }
1376   /* Don't forget the tail.  */
1377   strcpy (new_line, line);
1378
1379   /* Return a pointer to the beginning of the new line.  */
1380   return save_line;
1381 }
1382
1383 void
1384 execute_user_command (c, args)
1385      struct cmd_list_element *c;
1386      char *args;
1387 {
1388   register struct command_line *cmdlines;
1389   struct cleanup *old_chain;
1390   enum command_control_type ret;
1391
1392   old_chain = setup_user_args (args);
1393
1394   cmdlines = c->user_commands;
1395   if (cmdlines == 0)
1396     /* Null command */
1397     return;
1398
1399   /* Set the instream to 0, indicating execution of a
1400      user-defined function.  */
1401   old_chain = make_cleanup ((make_cleanup_func) source_cleanup, instream);
1402   instream = (FILE *) 0;
1403   while (cmdlines)
1404     {
1405       ret = execute_control_command (cmdlines);
1406       if (ret != simple_control && ret != break_control)
1407         {
1408           warning ("Error in control structure.\n");
1409           break;
1410         }
1411       cmdlines = cmdlines->next;
1412     }
1413   do_cleanups (old_chain);
1414 }
1415
1416 /* Execute the line P as a command.
1417    Pass FROM_TTY as second argument to the defining function.  */
1418
1419 void
1420 execute_command (p, from_tty)
1421      char *p;
1422      int from_tty;
1423 {
1424   register struct cmd_list_element *c;
1425   register enum language flang;
1426   static int warned = 0;
1427   /* FIXME: These should really be in an appropriate header file */
1428   extern void serial_log_command PARAMS ((const char *));
1429
1430   free_all_values ();
1431
1432   /* Force cleanup of any alloca areas if using C alloca instead of
1433      a builtin alloca.  */
1434   alloca (0);
1435
1436   /* This can happen when command_line_input hits end of file.  */
1437   if (p == NULL)
1438     return;
1439
1440   serial_log_command (p);
1441
1442   while (*p == ' ' || *p == '\t')
1443     p++;
1444   if (*p)
1445     {
1446       char *arg;
1447
1448       c = lookup_cmd (&p, cmdlist, "", 0, 1);
1449
1450       /* If the target is running, we allow only a limited set of
1451          commands. */
1452       if (event_loop_p && target_can_async_p () && target_executing)
1453         if (!strcmp (c->name, "help")
1454             && !strcmp (c->name, "pwd")
1455             && !strcmp (c->name, "show")
1456             && !strcmp (c->name, "stop"))
1457           error ("Cannot execute this command while the target is running.");
1458
1459       /* Pass null arg rather than an empty one.  */
1460       arg = *p ? p : 0;
1461
1462       /* Clear off trailing whitespace, except for set and complete command.  */
1463       if (arg && c->type != set_cmd && c->function.cfunc != complete_command)
1464         {
1465           p = arg + strlen (arg) - 1;
1466           while (p >= arg && (*p == ' ' || *p == '\t'))
1467             p--;
1468           *(p + 1) = '\0';
1469         }
1470
1471       /* If this command has been hooked, run the hook first. */
1472       if (c->hook)
1473         execute_user_command (c->hook, (char *) 0);
1474
1475       if (c->class == class_user)
1476         execute_user_command (c, arg);
1477       else if (c->type == set_cmd || c->type == show_cmd)
1478         do_setshow_command (arg, from_tty & caution, c);
1479       else if (c->function.cfunc == NO_FUNCTION)
1480         error ("That is not a command, just a help topic.");
1481       else if (call_command_hook)
1482         call_command_hook (c, arg, from_tty & caution);
1483       else
1484         (*c->function.cfunc) (arg, from_tty & caution);
1485     }
1486
1487   /* Tell the user if the language has changed (except first time).  */
1488   if (current_language != expected_language)
1489     {
1490       if (language_mode == language_mode_auto)
1491         {
1492           language_info (1);    /* Print what changed.  */
1493         }
1494       warned = 0;
1495     }
1496
1497   /* Warn the user if the working language does not match the
1498      language of the current frame.  Only warn the user if we are
1499      actually running the program, i.e. there is a stack. */
1500   /* FIXME:  This should be cacheing the frame and only running when
1501      the frame changes.  */
1502
1503   if (target_has_stack)
1504     {
1505       flang = get_frame_language ();
1506       if (!warned
1507           && flang != language_unknown
1508           && flang != current_language->la_language)
1509         {
1510           printf_filtered ("%s\n", lang_frame_mismatch_warn);
1511           warned = 1;
1512         }
1513     }
1514 }
1515
1516 /* ARGSUSED */
1517 /* NOTE 1999-04-29: This function will be static again, once we modify
1518    gdb to use the event loop as the default command loop and we merge
1519    event-top.c into this file, top.c */
1520 /* static */ void
1521 command_loop_marker (foo)
1522      int foo;
1523 {
1524 }
1525
1526 /* Read commands from `instream' and execute them
1527    until end of file or error reading instream.  */
1528
1529 void
1530 command_loop ()
1531 {
1532   struct cleanup *old_chain;
1533   char *command;
1534   int stdin_is_tty = ISATTY (stdin);
1535   long time_at_cmd_start;
1536 #ifdef HAVE_SBRK
1537   long space_at_cmd_start = 0;
1538 #endif
1539   extern int display_time;
1540   extern int display_space;
1541
1542   while (instream && !feof (instream))
1543     {
1544 #if defined(TUI)
1545       extern int insert_mode;
1546 #endif
1547       if (window_hook && instream == stdin)
1548         (*window_hook) (instream, get_prompt ());
1549
1550       quit_flag = 0;
1551       if (instream == stdin && stdin_is_tty)
1552         reinitialize_more_filter ();
1553       old_chain = make_cleanup ((make_cleanup_func) command_loop_marker, 0);
1554
1555 #if defined(TUI)
1556       /* A bit of paranoia: I want to make sure the "insert_mode" global
1557        * is clear except when it is being used for command-line editing
1558        * (see tuiIO.c, utils.c); otherwise normal output will
1559        * get messed up in the TUI. So clear it before/after
1560        * the command-line-input call. - RT
1561        */
1562       insert_mode = 0;
1563 #endif
1564       /* Get a command-line. This calls the readline package. */
1565       command = command_line_input (instream == stdin ?
1566                                     get_prompt () : (char *) NULL,
1567                                     instream == stdin, "prompt");
1568 #if defined(TUI)
1569       insert_mode = 0;
1570 #endif
1571       if (command == 0)
1572         return;
1573
1574       time_at_cmd_start = get_run_time ();
1575
1576       if (display_space)
1577         {
1578 #ifdef HAVE_SBRK
1579           extern char **environ;
1580           char *lim = (char *) sbrk (0);
1581
1582           space_at_cmd_start = (long) (lim - (char *) &environ);
1583 #endif
1584         }
1585
1586       execute_command (command, instream == stdin);
1587       /* Do any commands attached to breakpoint we stopped at.  */
1588       bpstat_do_actions (&stop_bpstat);
1589       do_cleanups (old_chain);
1590
1591       if (display_time)
1592         {
1593           long cmd_time = get_run_time () - time_at_cmd_start;
1594
1595           printf_unfiltered ("Command execution time: %ld.%06ld\n",
1596                              cmd_time / 1000000, cmd_time % 1000000);
1597         }
1598
1599       if (display_space)
1600         {
1601 #ifdef HAVE_SBRK
1602           extern char **environ;
1603           char *lim = (char *) sbrk (0);
1604           long space_now = lim - (char *) &environ;
1605           long space_diff = space_now - space_at_cmd_start;
1606
1607           printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
1608                              space_now,
1609                              (space_diff >= 0 ? '+' : '-'),
1610                              space_diff);
1611 #endif
1612         }
1613     }
1614 }
1615
1616 /* Read commands from `instream' and execute them until end of file or
1617    error reading instream. This command loop doesnt care about any
1618    such things as displaying time and space usage. If the user asks
1619    for those, they won't work. */
1620 void
1621 simplified_command_loop (read_input_func, execute_command_func)
1622      char *(*read_input_func) (char *);
1623      void (*execute_command_func) (char *, int);
1624 {
1625   struct cleanup *old_chain;
1626   char *command;
1627   int stdin_is_tty = ISATTY (stdin);
1628
1629   while (instream && !feof (instream))
1630     {
1631       quit_flag = 0;
1632       if (instream == stdin && stdin_is_tty)
1633         reinitialize_more_filter ();
1634       old_chain = make_cleanup ((make_cleanup_func) command_loop_marker, 0);
1635
1636       /* Get a command-line. */
1637       command = (*read_input_func) (instream == stdin ?
1638                                     get_prompt () : (char *) NULL);
1639
1640       if (command == 0)
1641         return;
1642
1643       (*execute_command_func) (command, instream == stdin);
1644
1645       /* Do any commands attached to breakpoint we stopped at.  */
1646       bpstat_do_actions (&stop_bpstat);
1647
1648       do_cleanups (old_chain);
1649     }
1650 }
1651 \f
1652 /* Commands call this if they do not want to be repeated by null lines.  */
1653
1654 void
1655 dont_repeat ()
1656 {
1657   if (server_command)
1658     return;
1659
1660   /* If we aren't reading from standard input, we are saving the last
1661      thing read from stdin in line and don't want to delete it.  Null lines
1662      won't repeat here in any case.  */
1663   if (instream == stdin)
1664     *line = 0;
1665 }
1666 \f
1667 /* Read a line from the stream "instream" without command line editing.
1668
1669    It prints PROMPT_ARG once at the start.
1670    Action is compatible with "readline", e.g. space for the result is
1671    malloc'd and should be freed by the caller.
1672
1673    A NULL return means end of file.  */
1674 char *
1675 gdb_readline (prompt_arg)
1676      char *prompt_arg;
1677 {
1678   int c;
1679   char *result;
1680   int input_index = 0;
1681   int result_size = 80;
1682
1683   if (prompt_arg)
1684     {
1685       /* Don't use a _filtered function here.  It causes the assumed
1686          character position to be off, since the newline we read from
1687          the user is not accounted for.  */
1688       fputs_unfiltered (prompt_arg, gdb_stdout);
1689 #ifdef MPW
1690       /* Move to a new line so the entered line doesn't have a prompt
1691          on the front of it. */
1692       fputs_unfiltered ("\n", gdb_stdout);
1693 #endif /* MPW */
1694       gdb_flush (gdb_stdout);
1695     }
1696
1697   result = (char *) xmalloc (result_size);
1698
1699   while (1)
1700     {
1701       /* Read from stdin if we are executing a user defined command.
1702          This is the right thing for prompt_for_continue, at least.  */
1703       c = fgetc (instream ? instream : stdin);
1704
1705       if (c == EOF)
1706         {
1707           if (input_index > 0)
1708             /* The last line does not end with a newline.  Return it, and
1709                if we are called again fgetc will still return EOF and
1710                we'll return NULL then.  */
1711             break;
1712           free (result);
1713           return NULL;
1714         }
1715
1716       if (c == '\n')
1717 #ifndef CRLF_SOURCE_FILES
1718         break;
1719 #else
1720         {
1721           if (input_index > 0 && result[input_index - 1] == '\r')
1722             input_index--;
1723           break;
1724         }
1725 #endif
1726
1727       result[input_index++] = c;
1728       while (input_index >= result_size)
1729         {
1730           result_size *= 2;
1731           result = (char *) xrealloc (result, result_size);
1732         }
1733     }
1734
1735   result[input_index++] = '\0';
1736   return result;
1737 }
1738
1739 /* Variables which control command line editing and history
1740    substitution.  These variables are given default values at the end
1741    of this file.  */
1742 static int command_editing_p;
1743 /* NOTE 1999-04-29: This variable will be static again, once we modify
1744    gdb to use the event loop as the default command loop and we merge
1745    event-top.c into this file, top.c */
1746 /* static */ int history_expansion_p;
1747 static int write_history_p;
1748 static int history_size;
1749 static char *history_filename;
1750
1751 /* readline uses the word breaks for two things:
1752    (1) In figuring out where to point the TEXT parameter to the
1753    rl_completion_entry_function.  Since we don't use TEXT for much,
1754    it doesn't matter a lot what the word breaks are for this purpose, but
1755    it does affect how much stuff M-? lists.
1756    (2) If one of the matches contains a word break character, readline
1757    will quote it.  That's why we switch between
1758    gdb_completer_word_break_characters and
1759    gdb_completer_command_word_break_characters.  I'm not sure when
1760    we need this behavior (perhaps for funky characters in C++ symbols?).  */
1761
1762 /* Variables which are necessary for fancy command line editing.  */
1763 char *gdb_completer_word_break_characters =
1764 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,-";
1765
1766 /* When completing on command names, we remove '-' from the list of
1767    word break characters, since we use it in command names.  If the
1768    readline library sees one in any of the current completion strings,
1769    it thinks that the string needs to be quoted and automatically supplies
1770    a leading quote. */
1771 char *gdb_completer_command_word_break_characters =
1772 " \t\n!@#$%^&*()+=|~`}{[]\"';:?/>.<,";
1773
1774 /* Characters that can be used to quote completion strings.  Note that we
1775    can't include '"' because the gdb C parser treats such quoted sequences
1776    as strings. */
1777 char *gdb_completer_quote_characters =
1778 "'";
1779
1780 /* Functions that are used as part of the fancy command line editing.  */
1781
1782 /* This can be used for functions which don't want to complete on symbols
1783    but don't want to complete on anything else either.  */
1784 /* ARGSUSED */
1785 char **
1786 noop_completer (text, prefix)
1787      char *text;
1788      char *prefix;
1789 {
1790   return NULL;
1791 }
1792
1793 /* Complete on filenames.  */
1794 char **
1795 filename_completer (text, word)
1796      char *text;
1797      char *word;
1798 {
1799   /* From readline.  */
1800   extern char *filename_completion_function PARAMS ((char *, int));
1801   int subsequent_name;
1802   char **return_val;
1803   int return_val_used;
1804   int return_val_alloced;
1805
1806   return_val_used = 0;
1807   /* Small for testing.  */
1808   return_val_alloced = 1;
1809   return_val = (char **) xmalloc (return_val_alloced * sizeof (char *));
1810
1811   subsequent_name = 0;
1812   while (1)
1813     {
1814       char *p;
1815       p = filename_completion_function (text, subsequent_name);
1816       if (return_val_used >= return_val_alloced)
1817         {
1818           return_val_alloced *= 2;
1819           return_val =
1820             (char **) xrealloc (return_val,
1821                                 return_val_alloced * sizeof (char *));
1822         }
1823       if (p == NULL)
1824         {
1825           return_val[return_val_used++] = p;
1826           break;
1827         }
1828       /* Like emacs, don't complete on old versions.  Especially useful
1829          in the "source" command.  */
1830       if (p[strlen (p) - 1] == '~')
1831         continue;
1832
1833       {
1834         char *q;
1835         if (word == text)
1836           /* Return exactly p.  */
1837           return_val[return_val_used++] = p;
1838         else if (word > text)
1839           {
1840             /* Return some portion of p.  */
1841             q = xmalloc (strlen (p) + 5);
1842             strcpy (q, p + (word - text));
1843             return_val[return_val_used++] = q;
1844             free (p);
1845           }
1846         else
1847           {
1848             /* Return some of TEXT plus p.  */
1849             q = xmalloc (strlen (p) + (text - word) + 5);
1850             strncpy (q, word, text - word);
1851             q[text - word] = '\0';
1852             strcat (q, p);
1853             return_val[return_val_used++] = q;
1854             free (p);
1855           }
1856       }
1857       subsequent_name = 1;
1858     }
1859 #if 0
1860   /* There is no way to do this just long enough to affect quote inserting
1861      without also affecting the next completion.  This should be fixed in
1862      readline.  FIXME.  */
1863   /* Insure that readline does the right thing
1864      with respect to inserting quotes.  */
1865   rl_completer_word_break_characters = "";
1866 #endif
1867   return return_val;
1868 }
1869
1870 /* Here are some useful test cases for completion.  FIXME: These should
1871    be put in the test suite.  They should be tested with both M-? and TAB.
1872
1873    "show output-" "radix"
1874    "show output" "-radix"
1875    "p" ambiguous (commands starting with p--path, print, printf, etc.)
1876    "p "  ambiguous (all symbols)
1877    "info t foo" no completions
1878    "info t " no completions
1879    "info t" ambiguous ("info target", "info terminal", etc.)
1880    "info ajksdlfk" no completions
1881    "info ajksdlfk " no completions
1882    "info" " "
1883    "info " ambiguous (all info commands)
1884    "p \"a" no completions (string constant)
1885    "p 'a" ambiguous (all symbols starting with a)
1886    "p b-a" ambiguous (all symbols starting with a)
1887    "p b-" ambiguous (all symbols)
1888    "file Make" "file" (word break hard to screw up here)
1889    "file ../gdb.stabs/we" "ird" (needs to not break word at slash)
1890  */
1891
1892 /* Generate completions one by one for the completer.  Each time we are
1893    called return another potential completion to the caller.
1894    line_completion just completes on commands or passes the buck to the
1895    command's completer function, the stuff specific to symbol completion
1896    is in make_symbol_completion_list.
1897
1898    TEXT is the caller's idea of the "word" we are looking at.
1899
1900    MATCHES is the number of matches that have currently been collected from
1901    calling this completion function.  When zero, then we need to initialize,
1902    otherwise the initialization has already taken place and we can just
1903    return the next potential completion string.
1904
1905    LINE_BUFFER is available to be looked at; it contains the entire text
1906    of the line.  POINT is the offset in that line of the cursor.  You
1907    should pretend that the line ends at POINT.
1908
1909    Returns NULL if there are no more completions, else a pointer to a string
1910    which is a possible completion, it is the caller's responsibility to
1911    free the string.  */
1912
1913 static char *
1914 line_completion_function (text, matches, line_buffer, point)
1915      char *text;
1916      int matches;
1917      char *line_buffer;
1918      int point;
1919 {
1920   static char **list = (char **) NULL;  /* Cache of completions */
1921   static int index;             /* Next cached completion */
1922   char *output = NULL;
1923   char *tmp_command, *p;
1924   /* Pointer within tmp_command which corresponds to text.  */
1925   char *word;
1926   struct cmd_list_element *c, *result_list;
1927
1928   if (matches == 0)
1929     {
1930       /* The caller is beginning to accumulate a new set of completions, so
1931          we need to find all of them now, and cache them for returning one at
1932          a time on future calls. */
1933
1934       if (list)
1935         {
1936           /* Free the storage used by LIST, but not by the strings inside.
1937              This is because rl_complete_internal () frees the strings. */
1938           free ((PTR) list);
1939         }
1940       list = 0;
1941       index = 0;
1942
1943       /* Choose the default set of word break characters to break completions.
1944          If we later find out that we are doing completions on command strings
1945          (as opposed to strings supplied by the individual command completer
1946          functions, which can be any string) then we will switch to the
1947          special word break set for command strings, which leaves out the
1948          '-' character used in some commands.  */
1949
1950       rl_completer_word_break_characters =
1951         gdb_completer_word_break_characters;
1952
1953       /* Decide whether to complete on a list of gdb commands or on symbols. */
1954       tmp_command = (char *) alloca (point + 1);
1955       p = tmp_command;
1956
1957       strncpy (tmp_command, line_buffer, point);
1958       tmp_command[point] = '\0';
1959       /* Since text always contains some number of characters leading up
1960          to point, we can find the equivalent position in tmp_command
1961          by subtracting that many characters from the end of tmp_command.  */
1962       word = tmp_command + point - strlen (text);
1963
1964       if (point == 0)
1965         {
1966           /* An empty line we want to consider ambiguous; that is, it
1967              could be any command.  */
1968           c = (struct cmd_list_element *) -1;
1969           result_list = 0;
1970         }
1971       else
1972         {
1973           c = lookup_cmd_1 (&p, cmdlist, &result_list, 1);
1974         }
1975
1976       /* Move p up to the next interesting thing.  */
1977       while (*p == ' ' || *p == '\t')
1978         {
1979           p++;
1980         }
1981
1982       if (!c)
1983         {
1984           /* It is an unrecognized command.  So there are no
1985              possible completions.  */
1986           list = NULL;
1987         }
1988       else if (c == (struct cmd_list_element *) -1)
1989         {
1990           char *q;
1991
1992           /* lookup_cmd_1 advances p up to the first ambiguous thing, but
1993              doesn't advance over that thing itself.  Do so now.  */
1994           q = p;
1995           while (*q && (isalnum (*q) || *q == '-' || *q == '_'))
1996             ++q;
1997           if (q != tmp_command + point)
1998             {
1999               /* There is something beyond the ambiguous
2000                  command, so there are no possible completions.  For
2001                  example, "info t " or "info t foo" does not complete
2002                  to anything, because "info t" can be "info target" or
2003                  "info terminal".  */
2004               list = NULL;
2005             }
2006           else
2007             {
2008               /* We're trying to complete on the command which was ambiguous.
2009                  This we can deal with.  */
2010               if (result_list)
2011                 {
2012                   list = complete_on_cmdlist (*result_list->prefixlist, p,
2013                                               word);
2014                 }
2015               else
2016                 {
2017                   list = complete_on_cmdlist (cmdlist, p, word);
2018                 }
2019               /* Insure that readline does the right thing with respect to
2020                  inserting quotes.  */
2021               rl_completer_word_break_characters =
2022                 gdb_completer_command_word_break_characters;
2023             }
2024         }
2025       else
2026         {
2027           /* We've recognized a full command.  */
2028
2029           if (p == tmp_command + point)
2030             {
2031               /* There is no non-whitespace in the line beyond the command.  */
2032
2033               if (p[-1] == ' ' || p[-1] == '\t')
2034                 {
2035                   /* The command is followed by whitespace; we need to complete
2036                      on whatever comes after command.  */
2037                   if (c->prefixlist)
2038                     {
2039                       /* It is a prefix command; what comes after it is
2040                          a subcommand (e.g. "info ").  */
2041                       list = complete_on_cmdlist (*c->prefixlist, p, word);
2042
2043                       /* Insure that readline does the right thing
2044                          with respect to inserting quotes.  */
2045                       rl_completer_word_break_characters =
2046                         gdb_completer_command_word_break_characters;
2047                     }
2048                   else if (c->enums)
2049                     {
2050                       list = complete_on_enum (c->enums, p, word);
2051                       rl_completer_word_break_characters =
2052                         gdb_completer_command_word_break_characters;
2053                     }
2054                   else
2055                     {
2056                       /* It is a normal command; what comes after it is
2057                          completed by the command's completer function.  */
2058                       list = (*c->completer) (p, word);
2059                     }
2060                 }
2061               else
2062                 {
2063                   /* The command is not followed by whitespace; we need to
2064                      complete on the command itself.  e.g. "p" which is a
2065                      command itself but also can complete to "print", "ptype"
2066                      etc.  */
2067                   char *q;
2068
2069                   /* Find the command we are completing on.  */
2070                   q = p;
2071                   while (q > tmp_command)
2072                     {
2073                       if (isalnum (q[-1]) || q[-1] == '-' || q[-1] == '_')
2074                         --q;
2075                       else
2076                         break;
2077                     }
2078
2079                   list = complete_on_cmdlist (result_list, q, word);
2080
2081                   /* Insure that readline does the right thing
2082                      with respect to inserting quotes.  */
2083                   rl_completer_word_break_characters =
2084                     gdb_completer_command_word_break_characters;
2085                 }
2086             }
2087           else
2088             {
2089               /* There is non-whitespace beyond the command.  */
2090
2091               if (c->prefixlist && !c->allow_unknown)
2092                 {
2093                   /* It is an unrecognized subcommand of a prefix command,
2094                      e.g. "info adsfkdj".  */
2095                   list = NULL;
2096                 }
2097               else if (c->enums)
2098                 {
2099                   list = complete_on_enum (c->enums, p, word);
2100                 }
2101               else
2102                 {
2103                   /* It is a normal command.  */
2104                   list = (*c->completer) (p, word);
2105                 }
2106             }
2107         }
2108     }
2109
2110   /* If we found a list of potential completions during initialization then
2111      dole them out one at a time.  The vector of completions is NULL
2112      terminated, so after returning the last one, return NULL (and continue
2113      to do so) each time we are called after that, until a new list is
2114      available. */
2115
2116   if (list)
2117     {
2118       output = list[index];
2119       if (output)
2120         {
2121           index++;
2122         }
2123     }
2124
2125 #if 0
2126   /* Can't do this because readline hasn't yet checked the word breaks
2127      for figuring out whether to insert a quote.  */
2128   if (output == NULL)
2129     /* Make sure the word break characters are set back to normal for the
2130        next time that readline tries to complete something.  */
2131     rl_completer_word_break_characters =
2132       gdb_completer_word_break_characters;
2133 #endif
2134
2135   return (output);
2136 }
2137
2138 /* Line completion interface function for readline.  */
2139
2140 static char *
2141 readline_line_completion_function (text, matches)
2142      char *text;
2143      int matches;
2144 {
2145   return line_completion_function (text, matches, rl_line_buffer, rl_point);
2146 }
2147
2148 /* Skip over a possibly quoted word (as defined by the quote characters
2149    and word break characters the completer uses).  Returns pointer to the
2150    location after the "word". */
2151
2152 char *
2153 skip_quoted (str)
2154      char *str;
2155 {
2156   char quote_char = '\0';
2157   char *scan;
2158
2159   for (scan = str; *scan != '\0'; scan++)
2160     {
2161       if (quote_char != '\0')
2162         {
2163           /* Ignore everything until the matching close quote char */
2164           if (*scan == quote_char)
2165             {
2166               /* Found matching close quote. */
2167               scan++;
2168               break;
2169             }
2170         }
2171       else if (strchr (gdb_completer_quote_characters, *scan))
2172         {
2173           /* Found start of a quoted string. */
2174           quote_char = *scan;
2175         }
2176       else if (strchr (gdb_completer_word_break_characters, *scan))
2177         {
2178           break;
2179         }
2180     }
2181   return (scan);
2182 }
2183 \f
2184
2185 #ifdef STOP_SIGNAL
2186 static void
2187 stop_sig (signo)
2188      int signo;
2189 {
2190 #if STOP_SIGNAL == SIGTSTP
2191   signal (SIGTSTP, SIG_DFL);
2192   sigsetmask (0);
2193   kill (getpid (), SIGTSTP);
2194   signal (SIGTSTP, stop_sig);
2195 #else
2196   signal (STOP_SIGNAL, stop_sig);
2197 #endif
2198   printf_unfiltered ("%s", get_prompt ());
2199   gdb_flush (gdb_stdout);
2200
2201   /* Forget about any previous command -- null line now will do nothing.  */
2202   dont_repeat ();
2203 }
2204 #endif /* STOP_SIGNAL */
2205
2206 /* Initialize signal handlers. */
2207 static void
2208 do_nothing (signo)
2209      int signo;
2210 {
2211   /* Under System V the default disposition of a signal is reinstated after
2212      the signal is caught and delivered to an application process.  On such
2213      systems one must restore the replacement signal handler if one wishes
2214      to continue handling the signal in one's program.  On BSD systems this
2215      is not needed but it is harmless, and it simplifies the code to just do
2216      it unconditionally. */
2217   signal (signo, do_nothing);
2218 }
2219
2220 static void
2221 init_signals ()
2222 {
2223   signal (SIGINT, request_quit);
2224
2225   /* If SIGTRAP was set to SIG_IGN, then the SIG_IGN will get passed
2226      to the inferior and breakpoints will be ignored.  */
2227 #ifdef SIGTRAP
2228   signal (SIGTRAP, SIG_DFL);
2229 #endif
2230
2231   /* If we initialize SIGQUIT to SIG_IGN, then the SIG_IGN will get
2232      passed to the inferior, which we don't want.  It would be
2233      possible to do a "signal (SIGQUIT, SIG_DFL)" after we fork, but
2234      on BSD4.3 systems using vfork, that can affect the
2235      GDB process as well as the inferior (the signal handling tables
2236      might be in memory, shared between the two).  Since we establish
2237      a handler for SIGQUIT, when we call exec it will set the signal
2238      to SIG_DFL for us.  */
2239   signal (SIGQUIT, do_nothing);
2240 #ifdef SIGHUP
2241   if (signal (SIGHUP, do_nothing) != SIG_IGN)
2242     signal (SIGHUP, disconnect);
2243 #endif
2244   signal (SIGFPE, float_handler);
2245
2246 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
2247   signal (SIGWINCH, SIGWINCH_HANDLER);
2248 #endif
2249 }
2250 \f
2251 /* Read one line from the command input stream `instream'
2252    into the local static buffer `linebuffer' (whose current length
2253    is `linelength').
2254    The buffer is made bigger as necessary.
2255    Returns the address of the start of the line.
2256
2257    NULL is returned for end of file.
2258
2259    *If* the instream == stdin & stdin is a terminal, the line read
2260    is copied into the file line saver (global var char *line,
2261    length linesize) so that it can be duplicated.
2262
2263    This routine either uses fancy command line editing or
2264    simple input as the user has requested.  */
2265
2266 char *
2267 command_line_input (prompt_arg, repeat, annotation_suffix)
2268      char *prompt_arg;
2269      int repeat;
2270      char *annotation_suffix;
2271 {
2272   static char *linebuffer = 0;
2273   static unsigned linelength = 0;
2274   register char *p;
2275   char *p1;
2276   char *rl;
2277   char *local_prompt = prompt_arg;
2278   char *nline;
2279   char got_eof = 0;
2280
2281   /* The annotation suffix must be non-NULL.  */
2282   if (annotation_suffix == NULL)
2283     annotation_suffix = "";
2284
2285   if (annotation_level > 1 && instream == stdin)
2286     {
2287       local_prompt = alloca ((prompt_arg == NULL ? 0 : strlen (prompt_arg))
2288                              + strlen (annotation_suffix) + 40);
2289       if (prompt_arg == NULL)
2290         local_prompt[0] = '\0';
2291       else
2292         strcpy (local_prompt, prompt_arg);
2293       strcat (local_prompt, "\n\032\032");
2294       strcat (local_prompt, annotation_suffix);
2295       strcat (local_prompt, "\n");
2296     }
2297
2298   if (linebuffer == 0)
2299     {
2300       linelength = 80;
2301       linebuffer = (char *) xmalloc (linelength);
2302     }
2303
2304   p = linebuffer;
2305
2306   /* Control-C quits instantly if typed while in this loop
2307      since it should not wait until the user types a newline.  */
2308   immediate_quit++;
2309 #ifdef STOP_SIGNAL
2310   if (job_control)
2311     {
2312       if (event_loop_p)
2313         signal (STOP_SIGNAL, handle_stop_sig);
2314       else
2315         signal (STOP_SIGNAL, stop_sig);
2316     }
2317 #endif
2318
2319   while (1)
2320     {
2321       /* Make sure that all output has been output.  Some machines may let
2322          you get away with leaving out some of the gdb_flush, but not all.  */
2323       wrap_here ("");
2324       gdb_flush (gdb_stdout);
2325       gdb_flush (gdb_stderr);
2326
2327       if (source_file_name != NULL)
2328         {
2329           ++source_line_number;
2330           sprintf (source_error,
2331                    "%s%s:%d: Error in sourced command file:\n",
2332                    source_pre_error,
2333                    source_file_name,
2334                    source_line_number);
2335           error_pre_print = source_error;
2336         }
2337
2338       if (annotation_level > 1 && instream == stdin)
2339         {
2340           printf_unfiltered ("\n\032\032pre-");
2341           printf_unfiltered (annotation_suffix);
2342           printf_unfiltered ("\n");
2343         }
2344
2345       /* Don't use fancy stuff if not talking to stdin.  */
2346       if (readline_hook && instream == NULL)
2347         {
2348           rl = (*readline_hook) (local_prompt);
2349         }
2350       else if (command_editing_p && instream == stdin && ISATTY (instream))
2351         {
2352           rl = readline (local_prompt);
2353         }
2354       else
2355         {
2356           rl = gdb_readline (local_prompt);
2357         }
2358
2359       if (annotation_level > 1 && instream == stdin)
2360         {
2361           printf_unfiltered ("\n\032\032post-");
2362           printf_unfiltered (annotation_suffix);
2363           printf_unfiltered ("\n");
2364         }
2365
2366       if (!rl || rl == (char *) EOF)
2367         {
2368           got_eof = 1;
2369           break;
2370         }
2371       if (strlen (rl) + 1 + (p - linebuffer) > linelength)
2372         {
2373           linelength = strlen (rl) + 1 + (p - linebuffer);
2374           nline = (char *) xrealloc (linebuffer, linelength);
2375           p += nline - linebuffer;
2376           linebuffer = nline;
2377         }
2378       p1 = rl;
2379       /* Copy line.  Don't copy null at end.  (Leaves line alone
2380          if this was just a newline)  */
2381       while (*p1)
2382         *p++ = *p1++;
2383
2384       free (rl);                /* Allocated in readline.  */
2385
2386       if (p == linebuffer || *(p - 1) != '\\')
2387         break;
2388
2389       p--;                      /* Put on top of '\'.  */
2390       local_prompt = (char *) 0;
2391     }
2392
2393 #ifdef STOP_SIGNAL
2394   if (job_control)
2395     signal (STOP_SIGNAL, SIG_DFL);
2396 #endif
2397   immediate_quit--;
2398
2399   if (got_eof)
2400     return NULL;
2401
2402 #define SERVER_COMMAND_LENGTH 7
2403   server_command =
2404     (p - linebuffer > SERVER_COMMAND_LENGTH)
2405     && STREQN (linebuffer, "server ", SERVER_COMMAND_LENGTH);
2406   if (server_command)
2407     {
2408       /* Note that we don't set `line'.  Between this and the check in
2409          dont_repeat, this insures that repeating will still do the
2410          right thing.  */
2411       *p = '\0';
2412       return linebuffer + SERVER_COMMAND_LENGTH;
2413     }
2414
2415   /* Do history expansion if that is wished.  */
2416   if (history_expansion_p && instream == stdin
2417       && ISATTY (instream))
2418     {
2419       char *history_value;
2420       int expanded;
2421
2422       *p = '\0';                /* Insert null now.  */
2423       expanded = history_expand (linebuffer, &history_value);
2424       if (expanded)
2425         {
2426           /* Print the changes.  */
2427           printf_unfiltered ("%s\n", history_value);
2428
2429           /* If there was an error, call this function again.  */
2430           if (expanded < 0)
2431             {
2432               free (history_value);
2433               return command_line_input (prompt_arg, repeat, annotation_suffix);
2434             }
2435           if (strlen (history_value) > linelength)
2436             {
2437               linelength = strlen (history_value) + 1;
2438               linebuffer = (char *) xrealloc (linebuffer, linelength);
2439             }
2440           strcpy (linebuffer, history_value);
2441           p = linebuffer + strlen (linebuffer);
2442           free (history_value);
2443         }
2444     }
2445
2446   /* If we just got an empty line, and that is supposed
2447      to repeat the previous command, return the value in the
2448      global buffer.  */
2449   if (repeat && p == linebuffer)
2450     return line;
2451   for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
2452   if (repeat && !*p1)
2453     return line;
2454
2455   *p = 0;
2456
2457   /* Add line to history if appropriate.  */
2458   if (instream == stdin
2459       && ISATTY (stdin) && *linebuffer)
2460     add_history (linebuffer);
2461
2462   /* Note: lines consisting solely of comments are added to the command
2463      history.  This is useful when you type a command, and then
2464      realize you don't want to execute it quite yet.  You can comment
2465      out the command and then later fetch it from the value history
2466      and remove the '#'.  The kill ring is probably better, but some
2467      people are in the habit of commenting things out.  */
2468   if (*p1 == '#')
2469     *p1 = '\0';                 /* Found a comment. */
2470
2471   /* Save into global buffer if appropriate.  */
2472   if (repeat)
2473     {
2474       if (linelength > linesize)
2475         {
2476           line = xrealloc (line, linelength);
2477           linesize = linelength;
2478         }
2479       strcpy (line, linebuffer);
2480       return line;
2481     }
2482
2483   return linebuffer;
2484 }
2485 \f
2486
2487 /* Expand the body_list of COMMAND so that it can hold NEW_LENGTH
2488    code bodies.  This is typically used when we encounter an "else"
2489    clause for an "if" command.  */
2490
2491 static void
2492 realloc_body_list (command, new_length)
2493      struct command_line *command;
2494      int new_length;
2495 {
2496   int n;
2497   struct command_line **body_list;
2498
2499   n = command->body_count;
2500
2501   /* Nothing to do?  */
2502   if (new_length <= n)
2503     return;
2504
2505   body_list = (struct command_line **)
2506     xmalloc (sizeof (struct command_line *) * new_length);
2507
2508   memcpy (body_list, command->body_list, sizeof (struct command_line *) * n);
2509
2510   free (command->body_list);
2511   command->body_list = body_list;
2512   command->body_count = new_length;
2513 }
2514
2515 /* Read one line from the input stream.  If the command is an "else" or
2516    "end", return such an indication to the caller.  */
2517
2518 static enum misc_command_type
2519 read_next_line (command)
2520      struct command_line **command;
2521 {
2522   char *p, *p1, *prompt_ptr, control_prompt[256];
2523   int i = 0;
2524
2525   if (control_level >= 254)
2526     error ("Control nesting too deep!\n");
2527
2528   /* Set a prompt based on the nesting of the control commands.  */
2529   if (instream == stdin || (instream == 0 && readline_hook != NULL))
2530     {
2531       for (i = 0; i < control_level; i++)
2532         control_prompt[i] = ' ';
2533       control_prompt[i] = '>';
2534       control_prompt[i + 1] = '\0';
2535       prompt_ptr = (char *) &control_prompt[0];
2536     }
2537   else
2538     prompt_ptr = NULL;
2539
2540   p = command_line_input (prompt_ptr, instream == stdin, "commands");
2541
2542   /* Not sure what to do here.  */
2543   if (p == NULL)
2544     return end_command;
2545
2546   /* Strip leading and trailing whitespace.  */
2547   while (*p == ' ' || *p == '\t')
2548     p++;
2549
2550   p1 = p + strlen (p);
2551   while (p1 != p && (p1[-1] == ' ' || p1[-1] == '\t'))
2552     p1--;
2553
2554   /* Blanks and comments don't really do anything, but we need to
2555      distinguish them from else, end and other commands which can be
2556      executed.  */
2557   if (p1 == p || p[0] == '#')
2558     return nop_command;
2559
2560   /* Is this the end of a simple, while, or if control structure?  */
2561   if (p1 - p == 3 && !strncmp (p, "end", 3))
2562     return end_command;
2563
2564   /* Is the else clause of an if control structure?  */
2565   if (p1 - p == 4 && !strncmp (p, "else", 4))
2566     return else_command;
2567
2568   /* Check for while, if, break, continue, etc and build a new command
2569      line structure for them.  */
2570   if (p1 - p > 5 && !strncmp (p, "while", 5))
2571     *command = build_command_line (while_control, p + 6);
2572   else if (p1 - p > 2 && !strncmp (p, "if", 2))
2573     *command = build_command_line (if_control, p + 3);
2574   else if (p1 - p == 10 && !strncmp (p, "loop_break", 10))
2575     {
2576       *command = (struct command_line *)
2577         xmalloc (sizeof (struct command_line));
2578       (*command)->next = NULL;
2579       (*command)->line = NULL;
2580       (*command)->control_type = break_control;
2581       (*command)->body_count = 0;
2582       (*command)->body_list = NULL;
2583     }
2584   else if (p1 - p == 13 && !strncmp (p, "loop_continue", 13))
2585     {
2586       *command = (struct command_line *)
2587         xmalloc (sizeof (struct command_line));
2588       (*command)->next = NULL;
2589       (*command)->line = NULL;
2590       (*command)->control_type = continue_control;
2591       (*command)->body_count = 0;
2592       (*command)->body_list = NULL;
2593     }
2594   else
2595     {
2596       /* A normal command.  */
2597       *command = (struct command_line *)
2598         xmalloc (sizeof (struct command_line));
2599       (*command)->next = NULL;
2600       (*command)->line = savestring (p, p1 - p);
2601       (*command)->control_type = simple_control;
2602       (*command)->body_count = 0;
2603       (*command)->body_list = NULL;
2604     }
2605
2606   /* Nothing special.  */
2607   return ok_command;
2608 }
2609
2610 /* Recursively read in the control structures and create a command_line 
2611    structure from them.
2612
2613    The parent_control parameter is the control structure in which the
2614    following commands are nested.  */
2615
2616 static enum command_control_type
2617 recurse_read_control_structure (current_cmd)
2618      struct command_line *current_cmd;
2619 {
2620   int current_body, i;
2621   enum misc_command_type val;
2622   enum command_control_type ret;
2623   struct command_line **body_ptr, *child_tail, *next;
2624
2625   child_tail = NULL;
2626   current_body = 1;
2627
2628   /* Sanity checks.  */
2629   if (current_cmd->control_type == simple_control)
2630     {
2631       error ("Recursed on a simple control type\n");
2632       return invalid_control;
2633     }
2634
2635   if (current_body > current_cmd->body_count)
2636     {
2637       error ("Allocated body is smaller than this command type needs\n");
2638       return invalid_control;
2639     }
2640
2641   /* Read lines from the input stream and build control structures.  */
2642   while (1)
2643     {
2644       dont_repeat ();
2645
2646       next = NULL;
2647       val = read_next_line (&next);
2648
2649       /* Just skip blanks and comments.  */
2650       if (val == nop_command)
2651         continue;
2652
2653       if (val == end_command)
2654         {
2655           if (current_cmd->control_type == while_control
2656               || current_cmd->control_type == if_control)
2657             {
2658               /* Success reading an entire control structure.  */
2659               ret = simple_control;
2660               break;
2661             }
2662           else
2663             {
2664               ret = invalid_control;
2665               break;
2666             }
2667         }
2668
2669       /* Not the end of a control structure.  */
2670       if (val == else_command)
2671         {
2672           if (current_cmd->control_type == if_control
2673               && current_body == 1)
2674             {
2675               realloc_body_list (current_cmd, 2);
2676               current_body = 2;
2677               child_tail = NULL;
2678               continue;
2679             }
2680           else
2681             {
2682               ret = invalid_control;
2683               break;
2684             }
2685         }
2686
2687       if (child_tail)
2688         {
2689           child_tail->next = next;
2690         }
2691       else
2692         {
2693           body_ptr = current_cmd->body_list;
2694           for (i = 1; i < current_body; i++)
2695             body_ptr++;
2696
2697           *body_ptr = next;
2698
2699         }
2700
2701       child_tail = next;
2702
2703       /* If the latest line is another control structure, then recurse
2704          on it.  */
2705       if (next->control_type == while_control
2706           || next->control_type == if_control)
2707         {
2708           control_level++;
2709           ret = recurse_read_control_structure (next);
2710           control_level--;
2711
2712           if (ret != simple_control)
2713             break;
2714         }
2715     }
2716
2717   dont_repeat ();
2718
2719   return ret;
2720 }
2721
2722 /* Read lines from the input stream and accumulate them in a chain of
2723    struct command_line's, which is then returned.  For input from a
2724    terminal, the special command "end" is used to mark the end of the
2725    input, and is not included in the returned chain of commands. */
2726
2727 #define END_MESSAGE "End with a line saying just \"end\"."
2728
2729 struct command_line *
2730 read_command_lines (prompt_arg, from_tty)
2731      char *prompt_arg;
2732      int from_tty;
2733 {
2734   struct command_line *head, *tail, *next;
2735   struct cleanup *old_chain;
2736   enum command_control_type ret;
2737   enum misc_command_type val;
2738
2739   control_level = 0;
2740   if (readline_begin_hook)
2741     {
2742       /* Note - intentional to merge messages with no newline */
2743       (*readline_begin_hook) ("%s  %s\n", prompt_arg, END_MESSAGE);
2744     }
2745   else if (from_tty && input_from_terminal_p ())
2746     {
2747       printf_unfiltered ("%s\n%s\n", prompt_arg, END_MESSAGE);
2748       gdb_flush (gdb_stdout);
2749     }
2750
2751   head = tail = NULL;
2752   old_chain = NULL;
2753
2754   while (1)
2755     {
2756       val = read_next_line (&next);
2757
2758       /* Ignore blank lines or comments.  */
2759       if (val == nop_command)
2760         continue;
2761
2762       if (val == end_command)
2763         {
2764           ret = simple_control;
2765           break;
2766         }
2767
2768       if (val != ok_command)
2769         {
2770           ret = invalid_control;
2771           break;
2772         }
2773
2774       if (next->control_type == while_control
2775           || next->control_type == if_control)
2776         {
2777           control_level++;
2778           ret = recurse_read_control_structure (next);
2779           control_level--;
2780
2781           if (ret == invalid_control)
2782             break;
2783         }
2784
2785       if (tail)
2786         {
2787           tail->next = next;
2788         }
2789       else
2790         {
2791           head = next;
2792           old_chain = make_cleanup ((make_cleanup_func) free_command_lines,
2793                                     &head);
2794         }
2795       tail = next;
2796     }
2797
2798   dont_repeat ();
2799
2800   if (head)
2801     {
2802       if (ret != invalid_control)
2803         {
2804           discard_cleanups (old_chain);
2805         }
2806       else
2807         do_cleanups (old_chain);
2808     }
2809
2810   if (readline_end_hook)
2811     {
2812       (*readline_end_hook) ();
2813     }
2814   return (head);
2815 }
2816
2817 /* Free a chain of struct command_line's.  */
2818
2819 void
2820 free_command_lines (lptr)
2821      struct command_line **lptr;
2822 {
2823   register struct command_line *l = *lptr;
2824   register struct command_line *next;
2825   struct command_line **blist;
2826   int i;
2827
2828   while (l)
2829     {
2830       if (l->body_count > 0)
2831         {
2832           blist = l->body_list;
2833           for (i = 0; i < l->body_count; i++, blist++)
2834             free_command_lines (blist);
2835         }
2836       next = l->next;
2837       free (l->line);
2838       free ((PTR) l);
2839       l = next;
2840     }
2841 }
2842 \f
2843 /* Add an element to the list of info subcommands.  */
2844
2845 void
2846 add_info (name, fun, doc)
2847      char *name;
2848      void (*fun) PARAMS ((char *, int));
2849      char *doc;
2850 {
2851   add_cmd (name, no_class, fun, doc, &infolist);
2852 }
2853
2854 /* Add an alias to the list of info subcommands.  */
2855
2856 void
2857 add_info_alias (name, oldname, abbrev_flag)
2858      char *name;
2859      char *oldname;
2860      int abbrev_flag;
2861 {
2862   add_alias_cmd (name, oldname, 0, abbrev_flag, &infolist);
2863 }
2864
2865 /* The "info" command is defined as a prefix, with allow_unknown = 0.
2866    Therefore, its own definition is called only for "info" with no args.  */
2867
2868 /* ARGSUSED */
2869 static void
2870 info_command (arg, from_tty)
2871      char *arg;
2872      int from_tty;
2873 {
2874   printf_unfiltered ("\"info\" must be followed by the name of an info command.\n");
2875   help_list (infolist, "info ", -1, gdb_stdout);
2876 }
2877
2878 /* The "complete" command is used by Emacs to implement completion.  */
2879
2880 /* ARGSUSED */
2881 static void
2882 complete_command (arg, from_tty)
2883      char *arg;
2884      int from_tty;
2885 {
2886   int i;
2887   int argpoint;
2888   char *completion;
2889
2890   dont_repeat ();
2891
2892   if (arg == NULL)
2893     arg = "";
2894   argpoint = strlen (arg);
2895
2896   for (completion = line_completion_function (arg, i = 0, arg, argpoint);
2897        completion;
2898        completion = line_completion_function (arg, ++i, arg, argpoint))
2899     {
2900       printf_unfiltered ("%s\n", completion);
2901       free (completion);
2902     }
2903 }
2904
2905 /* The "show" command with no arguments shows all the settings.  */
2906
2907 /* ARGSUSED */
2908 static void
2909 show_command (arg, from_tty)
2910      char *arg;
2911      int from_tty;
2912 {
2913   cmd_show_list (showlist, from_tty, "");
2914 }
2915 \f
2916 /* Add an element to the list of commands.  */
2917
2918 void
2919 add_com (name, class, fun, doc)
2920      char *name;
2921      enum command_class class;
2922      void (*fun) PARAMS ((char *, int));
2923      char *doc;
2924 {
2925   add_cmd (name, class, fun, doc, &cmdlist);
2926 }
2927
2928 /* Add an alias or abbreviation command to the list of commands.  */
2929
2930 void
2931 add_com_alias (name, oldname, class, abbrev_flag)
2932      char *name;
2933      char *oldname;
2934      enum command_class class;
2935      int abbrev_flag;
2936 {
2937   add_alias_cmd (name, oldname, class, abbrev_flag, &cmdlist);
2938 }
2939
2940 void
2941 error_no_arg (why)
2942      char *why;
2943 {
2944   error ("Argument required (%s).", why);
2945 }
2946
2947 /* ARGSUSED */
2948 static void
2949 help_command (command, from_tty)
2950      char *command;
2951      int from_tty;              /* Ignored */
2952 {
2953   help_cmd (command, gdb_stdout);
2954 }
2955 \f
2956 static void
2957 validate_comname (comname)
2958      char *comname;
2959 {
2960   register char *p;
2961
2962   if (comname == 0)
2963     error_no_arg ("name of command to define");
2964
2965   p = comname;
2966   while (*p)
2967     {
2968       if (!isalnum (*p) && *p != '-' && *p != '_')
2969         error ("Junk in argument list: \"%s\"", p);
2970       p++;
2971     }
2972 }
2973
2974 /* This is just a placeholder in the command data structures.  */
2975 static void
2976 user_defined_command (ignore, from_tty)
2977      char *ignore;
2978      int from_tty;
2979 {
2980 }
2981
2982 static void
2983 define_command (comname, from_tty)
2984      char *comname;
2985      int from_tty;
2986 {
2987   register struct command_line *cmds;
2988   register struct cmd_list_element *c, *newc, *hookc = 0;
2989   char *tem = comname;
2990   char tmpbuf[128];
2991 #define HOOK_STRING     "hook-"
2992 #define HOOK_LEN 5
2993
2994   validate_comname (comname);
2995
2996   /* Look it up, and verify that we got an exact match.  */
2997   c = lookup_cmd (&tem, cmdlist, "", -1, 1);
2998   if (c && !STREQ (comname, c->name))
2999     c = 0;
3000
3001   if (c)
3002     {
3003       if (c->class == class_user || c->class == class_alias)
3004         tem = "Redefine command \"%s\"? ";
3005       else
3006         tem = "Really redefine built-in command \"%s\"? ";
3007       if (!query (tem, c->name))
3008         error ("Command \"%s\" not redefined.", c->name);
3009     }
3010
3011   /* If this new command is a hook, then mark the command which it
3012      is hooking.  Note that we allow hooking `help' commands, so that
3013      we can hook the `stop' pseudo-command.  */
3014
3015   if (!strncmp (comname, HOOK_STRING, HOOK_LEN))
3016     {
3017       /* Look up cmd it hooks, and verify that we got an exact match.  */
3018       tem = comname + HOOK_LEN;
3019       hookc = lookup_cmd (&tem, cmdlist, "", -1, 0);
3020       if (hookc && !STREQ (comname + HOOK_LEN, hookc->name))
3021         hookc = 0;
3022       if (!hookc)
3023         {
3024           warning ("Your new `%s' command does not hook any existing command.",
3025                    comname);
3026           if (!query ("Proceed? "))
3027             error ("Not confirmed.");
3028         }
3029     }
3030
3031   comname = savestring (comname, strlen (comname));
3032
3033   /* If the rest of the commands will be case insensitive, this one
3034      should behave in the same manner. */
3035   for (tem = comname; *tem; tem++)
3036     if (isupper (*tem))
3037       *tem = tolower (*tem);
3038
3039   sprintf (tmpbuf, "Type commands for definition of \"%s\".", comname);
3040   cmds = read_command_lines (tmpbuf, from_tty);
3041
3042   if (c && c->class == class_user)
3043     free_command_lines (&c->user_commands);
3044
3045   newc = add_cmd (comname, class_user, user_defined_command,
3046                   (c && c->class == class_user)
3047                   ? c->doc : savestring ("User-defined.", 13), &cmdlist);
3048   newc->user_commands = cmds;
3049
3050   /* If this new command is a hook, then mark both commands as being
3051      tied.  */
3052   if (hookc)
3053     {
3054       hookc->hook = newc;       /* Target gets hooked.  */
3055       newc->hookee = hookc;     /* We are marked as hooking target cmd.  */
3056     }
3057 }
3058
3059 static void
3060 document_command (comname, from_tty)
3061      char *comname;
3062      int from_tty;
3063 {
3064   struct command_line *doclines;
3065   register struct cmd_list_element *c;
3066   char *tem = comname;
3067   char tmpbuf[128];
3068
3069   validate_comname (comname);
3070
3071   c = lookup_cmd (&tem, cmdlist, "", 0, 1);
3072
3073   if (c->class != class_user)
3074     error ("Command \"%s\" is built-in.", comname);
3075
3076   sprintf (tmpbuf, "Type documentation for \"%s\".", comname);
3077   doclines = read_command_lines (tmpbuf, from_tty);
3078
3079   if (c->doc)
3080     free (c->doc);
3081
3082   {
3083     register struct command_line *cl1;
3084     register int len = 0;
3085
3086     for (cl1 = doclines; cl1; cl1 = cl1->next)
3087       len += strlen (cl1->line) + 1;
3088
3089     c->doc = (char *) xmalloc (len + 1);
3090     *c->doc = 0;
3091
3092     for (cl1 = doclines; cl1; cl1 = cl1->next)
3093       {
3094         strcat (c->doc, cl1->line);
3095         if (cl1->next)
3096           strcat (c->doc, "\n");
3097       }
3098   }
3099
3100   free_command_lines (&doclines);
3101 }
3102 \f
3103 /* Print the GDB banner. */
3104 void
3105 print_gdb_version (stream)
3106      struct ui_file *stream;
3107 {
3108   /* From GNU coding standards, first line is meant to be easy for a
3109      program to parse, and is just canonical program name and version
3110      number, which starts after last space. */
3111
3112 #ifdef UI_OUT
3113   /* Print it console style until a format is defined */
3114   fprintf_filtered (stream, "GNU gdb %s (UI_OUT)\n", version);
3115 #else
3116   fprintf_filtered (stream, "GNU gdb %s\n", version);
3117 #endif
3118
3119   /* Second line is a copyright notice. */
3120
3121   fprintf_filtered (stream, "Copyright 1998 Free Software Foundation, Inc.\n");
3122
3123   /* Following the copyright is a brief statement that the program is
3124      free software, that users are free to copy and change it on
3125      certain conditions, that it is covered by the GNU GPL, and that
3126      there is no warranty. */
3127
3128   fprintf_filtered (stream, "\
3129 GDB is free software, covered by the GNU General Public License, and you are\n\
3130 welcome to change it and/or distribute copies of it under certain conditions.\n\
3131 Type \"show copying\" to see the conditions.\n\
3132 There is absolutely no warranty for GDB.  Type \"show warranty\" for details.\n");
3133
3134   /* After the required info we print the configuration information. */
3135
3136   fprintf_filtered (stream, "This GDB was configured as \"");
3137   if (!STREQ (host_name, target_name))
3138     {
3139       fprintf_filtered (stream, "--host=%s --target=%s", host_name, target_name);
3140     }
3141   else
3142     {
3143       fprintf_filtered (stream, "%s", host_name);
3144     }
3145   fprintf_filtered (stream, "\".");
3146 }
3147
3148 /* ARGSUSED */
3149 static void
3150 show_version (args, from_tty)
3151      char *args;
3152      int from_tty;
3153 {
3154   immediate_quit++;
3155   print_gdb_version (gdb_stdout);
3156   printf_filtered ("\n");
3157   immediate_quit--;
3158 }
3159 \f
3160 /* get_prompt: access method for the GDB prompt string.  */
3161
3162 #define MAX_PROMPT_SIZE 256
3163
3164 /*
3165  * int get_prompt_1 (char * buf);
3166  *
3167  * Work-horse for get_prompt (called via catch_errors).
3168  * Argument is buffer to hold the formatted prompt.
3169  *
3170  * Returns: 1 for success (use formatted prompt)
3171  *          0 for failure (use gdb_prompt_string).
3172  */
3173
3174 static int gdb_prompt_escape;
3175
3176 static int
3177 get_prompt_1 (formatted_prompt)
3178      char *formatted_prompt;
3179 {
3180   char *local_prompt;
3181
3182   if (event_loop_p)
3183     local_prompt = PROMPT (0);
3184   else
3185     local_prompt = gdb_prompt_string;
3186
3187
3188   if (gdb_prompt_escape == 0)
3189     {
3190       return 0;                 /* do no formatting */
3191     }
3192   else
3193     /* formatted prompt */
3194     {
3195       char fmt[40], *promptp, *outp, *tmp;
3196       value_ptr arg_val;
3197       DOUBLEST doubleval;
3198       LONGEST longval;
3199       CORE_ADDR addrval;
3200
3201       int i, len;
3202       struct type *arg_type, *elt_type;
3203
3204       promptp = local_prompt;
3205       outp = formatted_prompt;
3206
3207       while (*promptp != '\0')
3208         {
3209           int available = MAX_PROMPT_SIZE - (outp - formatted_prompt) - 1;
3210
3211           if (*promptp != gdb_prompt_escape)
3212             {
3213               if (available >= 1)       /* overflow protect */
3214                 *outp++ = *promptp++;
3215             }
3216           else
3217             {
3218               /* GDB prompt string contains escape char.  Parse for arg.
3219                  Two consecutive escape chars followed by arg followed by
3220                  a comma means to insert the arg using a default format.
3221                  Otherwise a printf format string may be included between
3222                  the two escape chars.  eg:
3223                  %%foo, insert foo using default format
3224                  %2.2f%foo,     insert foo using "%2.2f" format
3225                  A mismatch between the format string and the data type
3226                  of "foo" is an error (which we don't know how to protect
3227                  against).  */
3228
3229               fmt[0] = '\0';    /* assume null format string */
3230               if (promptp[1] == gdb_prompt_escape)      /* double esc char */
3231                 {
3232                   promptp += 2; /* skip past two escape chars. */
3233                 }
3234               else
3235                 {
3236                   /* extract format string from between two esc chars */
3237                   i = 0;
3238                   do
3239                     {
3240                       fmt[i++] = *promptp++;    /* copy format string */
3241                     }
3242                   while (i < sizeof (fmt) - 1 &&
3243                          *promptp != gdb_prompt_escape &&
3244                          *promptp != '\0');
3245
3246                   if (*promptp != gdb_prompt_escape)
3247                     error ("Syntax error at prompt position %d",
3248                            promptp - local_prompt);
3249                   else
3250                     {
3251                       promptp++;        /* skip second escape char */
3252                       fmt[i++] = '\0';  /* terminate the format string */
3253                     }
3254                 }
3255
3256               arg_val = parse_to_comma_and_eval (&promptp);
3257               if (*promptp == ',')
3258                 promptp++;      /* skip past the comma */
3259               arg_type = check_typedef (VALUE_TYPE (arg_val));
3260               switch (TYPE_CODE (arg_type))
3261                 {
3262                 case TYPE_CODE_ARRAY:
3263                   elt_type = check_typedef (TYPE_TARGET_TYPE (arg_type));
3264                   if (TYPE_LENGTH (arg_type) > 0 &&
3265                       TYPE_LENGTH (elt_type) == 1 &&
3266                       TYPE_CODE (elt_type) == TYPE_CODE_INT)
3267                     {
3268                       int len = TYPE_LENGTH (arg_type);
3269
3270                       if (VALUE_LAZY (arg_val))
3271                         value_fetch_lazy (arg_val);
3272                       tmp = VALUE_CONTENTS (arg_val);
3273
3274                       if (len > available)
3275                         len = available;        /* overflow protect */
3276
3277                       /* FIXME: how to protect GDB from crashing
3278                          from bad user-supplied format string? */
3279                       if (fmt[0] != 0)
3280                         sprintf (outp, fmt, tmp);
3281                       else
3282                         strncpy (outp, tmp, len);
3283                       outp[len] = '\0';
3284                     }
3285                   break;
3286                 case TYPE_CODE_PTR:
3287                   elt_type = check_typedef (TYPE_TARGET_TYPE (arg_type));
3288                   addrval = value_as_pointer (arg_val);
3289
3290                   if (TYPE_LENGTH (elt_type) == 1 &&
3291                       TYPE_CODE (elt_type) == TYPE_CODE_INT &&
3292                       addrval != 0)
3293                     {
3294                       /* display it as a string */
3295                       char *default_fmt = "%s";
3296                       char *tmp;
3297                       int err = 0;
3298
3299                       /* Limiting the number of bytes that the following call
3300                          will read protects us from sprintf overflow later. */
3301                       i = target_read_string (addrval,  /* src */
3302                                               &tmp,     /* dest */
3303                                               available,        /* len */
3304                                               &err);
3305                       if (err)  /* read failed */
3306                         error ("%s on target_read", safe_strerror (err));
3307
3308                       tmp[i] = '\0';    /* force-terminate string */
3309                       /* FIXME: how to protect GDB from crashing
3310                          from bad user-supplied format string? */
3311                       sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
3312                                tmp);
3313                       free (tmp);
3314                     }
3315                   else
3316                     {
3317                       /* display it as a pointer */
3318                       char *default_fmt = "0x%x";
3319
3320                       /* FIXME: how to protect GDB from crashing
3321                          from bad user-supplied format string? */
3322                       if (available >= 16 /*? */ )      /* overflow protect */
3323                         sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
3324                                  (long) addrval);
3325                     }
3326                   break;
3327                 case TYPE_CODE_FLT:
3328                   {
3329                     char *default_fmt = "%g";
3330
3331                     doubleval = value_as_double (arg_val);
3332                     /* FIXME: how to protect GDB from crashing
3333                        from bad user-supplied format string? */
3334                     if (available >= 16 /*? */ )        /* overflow protect */
3335                       sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
3336                                (double) doubleval);
3337                     break;
3338                   }
3339                 case TYPE_CODE_INT:
3340                   {
3341                     char *default_fmt = "%d";
3342
3343                     longval = value_as_long (arg_val);
3344                     /* FIXME: how to protect GDB from crashing
3345                        from bad user-supplied format string? */
3346                     if (available >= 16 /*? */ )        /* overflow protect */
3347                       sprintf (outp, fmt[0] == 0 ? default_fmt : fmt,
3348                                (long) longval);
3349                     break;
3350                   }
3351                 case TYPE_CODE_BOOL:
3352                   {
3353                     /* no default format for bool */
3354                     longval = value_as_long (arg_val);
3355                     if (available >= 8 /*? */ )         /* overflow protect */
3356                       {
3357                         if (longval)
3358                           strcpy (outp, "<true>");
3359                         else
3360                           strcpy (outp, "<false>");
3361                       }
3362                     break;
3363                   }
3364                 case TYPE_CODE_ENUM:
3365                   {
3366                     /* no default format for enum */
3367                     longval = value_as_long (arg_val);
3368                     len = TYPE_NFIELDS (arg_type);
3369                     /* find enum name if possible */
3370                     for (i = 0; i < len; i++)
3371                       if (TYPE_FIELD_BITPOS (arg_type, i) == longval)
3372                         break;  /* match -- end loop */
3373
3374                     if (i < len)        /* enum name found */
3375                       {
3376                         char *name = TYPE_FIELD_NAME (arg_type, i);
3377
3378                         strncpy (outp, name, available);
3379                         /* in casel available < strlen (name), */
3380                         outp[available] = '\0';
3381                       }
3382                     else
3383                       {
3384                         if (available >= 16 /*? */ )    /* overflow protect */
3385                           sprintf (outp, "%ld", (long) longval);
3386                       }
3387                     break;
3388                   }
3389                 case TYPE_CODE_VOID:
3390                   *outp = '\0';
3391                   break;        /* void type -- no output */
3392                 default:
3393                   error ("bad data type at prompt position %d",
3394                          promptp - local_prompt);
3395                   break;
3396                 }
3397               outp += strlen (outp);
3398             }
3399         }
3400       *outp++ = '\0';           /* terminate prompt string */
3401       return 1;
3402     }
3403 }
3404
3405 char *
3406 get_prompt ()
3407 {
3408   static char buf[MAX_PROMPT_SIZE];
3409
3410   if (catch_errors (get_prompt_1, buf, "bad formatted prompt: ",
3411                     RETURN_MASK_ALL))
3412     {
3413       return &buf[0];           /* successful formatted prompt */
3414     }
3415   else
3416     {
3417       /* Prompt could not be formatted.  */
3418       if (event_loop_p)
3419         return PROMPT (0);
3420       else
3421         return gdb_prompt_string;
3422     }
3423 }
3424
3425 void
3426 set_prompt (s)
3427      char *s;
3428 {
3429 /* ??rehrauer: I don't know why this fails, since it looks as though
3430    assignments to prompt are wrapped in calls to savestring...
3431    if (prompt != NULL)
3432    free (prompt);
3433  */
3434   if (event_loop_p)
3435     PROMPT (0) = savestring (s, strlen (s));
3436   else
3437     gdb_prompt_string = savestring (s, strlen (s));
3438 }
3439 \f
3440
3441 /* If necessary, make the user confirm that we should quit.  Return
3442    non-zero if we should quit, zero if we shouldn't.  */
3443
3444 int
3445 quit_confirm ()
3446 {
3447   if (inferior_pid != 0 && target_has_execution)
3448     {
3449       char *s;
3450
3451       /* This is something of a hack.  But there's no reliable way to
3452          see if a GUI is running.  The `use_windows' variable doesn't
3453          cut it.  */
3454       if (init_ui_hook)
3455         s = "A debugging session is active.\nDo you still want to close the debugger?";
3456       else if (attach_flag)
3457         s = "The program is running.  Quit anyway (and detach it)? ";
3458       else
3459         s = "The program is running.  Exit anyway? ";
3460
3461       if (!query (s))
3462         return 0;
3463     }
3464
3465   return 1;
3466 }
3467
3468 /* Quit without asking for confirmation.  */
3469
3470 void
3471 quit_force (args, from_tty)
3472      char *args;
3473      int from_tty;
3474 {
3475   int exit_code = 0;
3476
3477   /* An optional expression may be used to cause gdb to terminate with the 
3478      value of that expression. */
3479   if (args)
3480     {
3481       value_ptr val = parse_and_eval (args);
3482
3483       exit_code = (int) value_as_long (val);
3484     }
3485
3486   if (inferior_pid != 0 && target_has_execution)
3487     {
3488       if (attach_flag)
3489         target_detach (args, from_tty);
3490       else
3491         target_kill ();
3492     }
3493
3494   /* UDI wants this, to kill the TIP.  */
3495   target_close (1);
3496
3497   /* Save the history information if it is appropriate to do so.  */
3498   if (write_history_p && history_filename)
3499     write_history (history_filename);
3500
3501   do_final_cleanups (ALL_CLEANUPS);     /* Do any final cleanups before exiting */
3502
3503 #if defined(TUI)
3504   /* tuiDo((TuiOpaqueFuncPtr)tuiCleanUp); */
3505   /* The above does not need to be inside a tuiDo(), since
3506    * it is not manipulating the curses screen, but rather,
3507    * it is tearing it down.
3508    */
3509   if (tui_version)
3510     tuiCleanUp ();
3511 #endif
3512
3513   exit (exit_code);
3514 }
3515
3516 /* Handle the quit command.  */
3517
3518 void
3519 quit_command (args, from_tty)
3520      char *args;
3521      int from_tty;
3522 {
3523   if (!quit_confirm ())
3524     error ("Not confirmed.");
3525   quit_force (args, from_tty);
3526 }
3527
3528 /* Returns whether GDB is running on a terminal and whether the user
3529    desires that questions be asked of them on that terminal.  */
3530
3531 int
3532 input_from_terminal_p ()
3533 {
3534   return gdb_has_a_terminal () && (instream == stdin) & caution;
3535 }
3536 \f
3537 /* ARGSUSED */
3538 static void
3539 pwd_command (args, from_tty)
3540      char *args;
3541      int from_tty;
3542 {
3543   if (args)
3544     error ("The \"pwd\" command does not take an argument: %s", args);
3545   getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
3546
3547   if (!STREQ (gdb_dirbuf, current_directory))
3548     printf_unfiltered ("Working directory %s\n (canonically %s).\n",
3549                        current_directory, gdb_dirbuf);
3550   else
3551     printf_unfiltered ("Working directory %s.\n", current_directory);
3552 }
3553
3554 void
3555 cd_command (dir, from_tty)
3556      char *dir;
3557      int from_tty;
3558 {
3559   int len;
3560   /* Found something other than leading repetitions of "/..".  */
3561   int found_real_path;
3562   char *p;
3563
3564   /* If the new directory is absolute, repeat is a no-op; if relative,
3565      repeat might be useful but is more likely to be a mistake.  */
3566   dont_repeat ();
3567
3568   if (dir == 0)
3569     error_no_arg ("new working directory");
3570
3571   dir = tilde_expand (dir);
3572   make_cleanup (free, dir);
3573
3574   if (chdir (dir) < 0)
3575     perror_with_name (dir);
3576
3577 #if defined(_WIN32) || defined(__MSDOS__)
3578   /* There's too much mess with DOSish names like "d:", "d:.",
3579      "d:./foo" etc.  Instead of having lots of special #ifdef'ed code,
3580      simply get the canonicalized name of the current directory.  */
3581   dir = getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
3582 #endif
3583
3584   len = strlen (dir);
3585   if (SLASH_P (dir[len-1]))
3586     {
3587       /* Remove the trailing slash unless this is a root directory
3588          (including a drive letter on non-Unix systems).  */
3589       if (!(len == 1) /* "/" */
3590 #if defined(_WIN32) || defined(__MSDOS__)
3591           && !(!SLASH_P (*dir) && ROOTED_P (dir) && len <= 3) /* "d:/" */
3592 #endif
3593           )
3594         len--;
3595     }
3596
3597   dir = savestring (dir, len);
3598   if (ROOTED_P (dir))
3599     current_directory = dir;
3600   else
3601     {
3602       if (SLASH_P (current_directory[strlen (current_directory) - 1]))
3603         current_directory = concat (current_directory, dir, NULL);
3604       else
3605         current_directory = concat (current_directory, SLASH_STRING, dir, NULL);
3606       free (dir);
3607     }
3608
3609   /* Now simplify any occurrences of `.' and `..' in the pathname.  */
3610
3611   found_real_path = 0;
3612   for (p = current_directory; *p;)
3613     {
3614       if (SLASH_P (p[0]) && p[1] == '.' && (p[2] == 0 || SLASH_P (p[2])))
3615         strcpy (p, p + 2);
3616       else if (SLASH_P (p[0]) && p[1] == '.' && p[2] == '.'
3617                && (p[3] == 0 || SLASH_P (p[3])))
3618         {
3619           if (found_real_path)
3620             {
3621               /* Search backwards for the directory just before the "/.."
3622                  and obliterate it and the "/..".  */
3623               char *q = p;
3624               while (q != current_directory && !SLASH_P (q[-1]))
3625                 --q;
3626
3627               if (q == current_directory)
3628                 /* current_directory is
3629                    a relative pathname ("can't happen"--leave it alone).  */
3630                 ++p;
3631               else
3632                 {
3633                   strcpy (q - 1, p + 3);
3634                   p = q - 1;
3635                 }
3636             }
3637           else
3638             /* We are dealing with leading repetitions of "/..", for example
3639                "/../..", which is the Mach super-root.  */
3640             p += 3;
3641         }
3642       else
3643         {
3644           found_real_path = 1;
3645           ++p;
3646         }
3647     }
3648
3649   forget_cached_source_info ();
3650
3651   if (from_tty)
3652     pwd_command ((char *) 0, 1);
3653 }
3654 \f
3655 struct source_cleanup_lines_args
3656 {
3657   int old_line;
3658   char *old_file;
3659   char *old_pre_error;
3660   char *old_error_pre_print;
3661 };
3662
3663 static void
3664 source_cleanup_lines (args)
3665      PTR args;
3666 {
3667   struct source_cleanup_lines_args *p =
3668   (struct source_cleanup_lines_args *) args;
3669   source_line_number = p->old_line;
3670   source_file_name = p->old_file;
3671   source_pre_error = p->old_pre_error;
3672   error_pre_print = p->old_error_pre_print;
3673 }
3674
3675 /* ARGSUSED */
3676 void
3677 source_command (args, from_tty)
3678      char *args;
3679      int from_tty;
3680 {
3681   FILE *stream;
3682   struct cleanup *old_cleanups;
3683   char *file = args;
3684   struct source_cleanup_lines_args old_lines;
3685   int needed_length;
3686
3687   if (file == NULL)
3688     {
3689       error ("source command requires pathname of file to source.");
3690     }
3691
3692   file = tilde_expand (file);
3693   old_cleanups = make_cleanup (free, file);
3694
3695   stream = fopen (file, FOPEN_RT);
3696   if (!stream)
3697     {
3698       if (from_tty)
3699         perror_with_name (file);
3700       else
3701         return;
3702     }
3703
3704   make_cleanup ((make_cleanup_func) fclose, stream);
3705
3706   old_lines.old_line = source_line_number;
3707   old_lines.old_file = source_file_name;
3708   old_lines.old_pre_error = source_pre_error;
3709   old_lines.old_error_pre_print = error_pre_print;
3710   make_cleanup (source_cleanup_lines, &old_lines);
3711   source_line_number = 0;
3712   source_file_name = file;
3713   source_pre_error = error_pre_print == NULL ? "" : error_pre_print;
3714   source_pre_error = savestring (source_pre_error, strlen (source_pre_error));
3715   make_cleanup (free, source_pre_error);
3716   /* This will get set every time we read a line.  So it won't stay "" for
3717      long.  */
3718   error_pre_print = "";
3719
3720   needed_length = strlen (source_file_name) + strlen (source_pre_error) + 80;
3721   if (source_error_allocated < needed_length)
3722     {
3723       source_error_allocated *= 2;
3724       if (source_error_allocated < needed_length)
3725         source_error_allocated = needed_length;
3726       if (source_error == NULL)
3727         source_error = xmalloc (source_error_allocated);
3728       else
3729         source_error = xrealloc (source_error, source_error_allocated);
3730     }
3731
3732   read_command_file (stream);
3733
3734   do_cleanups (old_cleanups);
3735 }
3736
3737 /* ARGSUSED */
3738 static void
3739 echo_command (text, from_tty)
3740      char *text;
3741      int from_tty;
3742 {
3743   char *p = text;
3744   register int c;
3745
3746   if (text)
3747     while ((c = *p++) != '\0')
3748       {
3749         if (c == '\\')
3750           {
3751             /* \ at end of argument is used after spaces
3752                so they won't be lost.  */
3753             if (*p == 0)
3754               return;
3755
3756             c = parse_escape (&p);
3757             if (c >= 0)
3758               printf_filtered ("%c", c);
3759           }
3760         else
3761           printf_filtered ("%c", c);
3762       }
3763
3764   /* Force this output to appear now.  */
3765   wrap_here ("");
3766   gdb_flush (gdb_stdout);
3767 }
3768
3769 /* ARGSUSED */
3770 static void
3771 dont_repeat_command (ignored, from_tty)
3772      char *ignored;
3773      int from_tty;
3774 {
3775   *line = 0;                    /* Can't call dont_repeat here because we're not
3776                                    necessarily reading from stdin.  */
3777 }
3778 \f
3779 /* Functions to manipulate command line editing control variables.  */
3780
3781 /* Number of commands to print in each call to show_commands.  */
3782 #define Hist_print 10
3783 static void
3784 show_commands (args, from_tty)
3785      char *args;
3786      int from_tty;
3787 {
3788   /* Index for history commands.  Relative to history_base.  */
3789   int offset;
3790
3791   /* Number of the history entry which we are planning to display next.
3792      Relative to history_base.  */
3793   static int num = 0;
3794
3795   /* The first command in the history which doesn't exist (i.e. one more
3796      than the number of the last command).  Relative to history_base.  */
3797   int hist_len;
3798
3799   extern HIST_ENTRY *history_get PARAMS ((int));
3800
3801   /* Print out some of the commands from the command history.  */
3802   /* First determine the length of the history list.  */
3803   hist_len = history_size;
3804   for (offset = 0; offset < history_size; offset++)
3805     {
3806       if (!history_get (history_base + offset))
3807         {
3808           hist_len = offset;
3809           break;
3810         }
3811     }
3812
3813   if (args)
3814     {
3815       if (args[0] == '+' && args[1] == '\0')
3816         /* "info editing +" should print from the stored position.  */
3817         ;
3818       else
3819         /* "info editing <exp>" should print around command number <exp>.  */
3820         num = (parse_and_eval_address (args) - history_base) - Hist_print / 2;
3821     }
3822   /* "show commands" means print the last Hist_print commands.  */
3823   else
3824     {
3825       num = hist_len - Hist_print;
3826     }
3827
3828   if (num < 0)
3829     num = 0;
3830
3831   /* If there are at least Hist_print commands, we want to display the last
3832      Hist_print rather than, say, the last 6.  */
3833   if (hist_len - num < Hist_print)
3834     {
3835       num = hist_len - Hist_print;
3836       if (num < 0)
3837         num = 0;
3838     }
3839
3840   for (offset = num; offset < num + Hist_print && offset < hist_len; offset++)
3841     {
3842       printf_filtered ("%5d  %s\n", history_base + offset,
3843                        (history_get (history_base + offset))->line);
3844     }
3845
3846   /* The next command we want to display is the next one that we haven't
3847      displayed yet.  */
3848   num += Hist_print;
3849
3850   /* If the user repeats this command with return, it should do what
3851      "show commands +" does.  This is unnecessary if arg is null,
3852      because "show commands +" is not useful after "show commands".  */
3853   if (from_tty && args)
3854     {
3855       args[0] = '+';
3856       args[1] = '\0';
3857     }
3858 }
3859
3860 /* Called by do_setshow_command.  */
3861 /* ARGSUSED */
3862 static void
3863 set_history_size_command (args, from_tty, c)
3864      char *args;
3865      int from_tty;
3866      struct cmd_list_element *c;
3867 {
3868   if (history_size == INT_MAX)
3869     unstifle_history ();
3870   else if (history_size >= 0)
3871     stifle_history (history_size);
3872   else
3873     {
3874       history_size = INT_MAX;
3875       error ("History size must be non-negative");
3876     }
3877 }
3878
3879 /* ARGSUSED */
3880 static void
3881 set_history (args, from_tty)
3882      char *args;
3883      int from_tty;
3884 {
3885   printf_unfiltered ("\"set history\" must be followed by the name of a history subcommand.\n");
3886   help_list (sethistlist, "set history ", -1, gdb_stdout);
3887 }
3888
3889 /* ARGSUSED */
3890 static void
3891 show_history (args, from_tty)
3892      char *args;
3893      int from_tty;
3894 {
3895   cmd_show_list (showhistlist, from_tty, "");
3896 }
3897
3898 int info_verbose = 0;           /* Default verbose msgs off */
3899
3900 /* Called by do_setshow_command.  An elaborate joke.  */
3901 /* ARGSUSED */
3902 static void
3903 set_verbose (args, from_tty, c)
3904      char *args;
3905      int from_tty;
3906      struct cmd_list_element *c;
3907 {
3908   char *cmdname = "verbose";
3909   struct cmd_list_element *showcmd;
3910
3911   showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, 1);
3912
3913   if (info_verbose)
3914     {
3915       c->doc = "Set verbose printing of informational messages.";
3916       showcmd->doc = "Show verbose printing of informational messages.";
3917     }
3918   else
3919     {
3920       c->doc = "Set verbosity.";
3921       showcmd->doc = "Show verbosity.";
3922     }
3923 }
3924
3925 static void
3926 float_handler (signo)
3927      int signo;
3928 {
3929   /* This message is based on ANSI C, section 4.7.  Note that integer
3930      divide by zero causes this, so "float" is a misnomer.  */
3931   signal (SIGFPE, float_handler);
3932   error ("Erroneous arithmetic operation.");
3933 }
3934 \f
3935
3936 static void
3937 init_cmd_lists ()
3938 {
3939   cmdlist = NULL;
3940   infolist = NULL;
3941   enablelist = NULL;
3942   disablelist = NULL;
3943   togglelist = NULL;
3944   stoplist = NULL;
3945   deletelist = NULL;
3946   enablebreaklist = NULL;
3947   setlist = NULL;
3948   unsetlist = NULL;
3949   showlist = NULL;
3950   sethistlist = NULL;
3951   showhistlist = NULL;
3952   unsethistlist = NULL;
3953   maintenancelist = NULL;
3954   maintenanceinfolist = NULL;
3955   maintenanceprintlist = NULL;
3956   setprintlist = NULL;
3957   showprintlist = NULL;
3958   setchecklist = NULL;
3959   showchecklist = NULL;
3960 }
3961
3962 /* Init the history buffer.  Note that we are called after the init file(s)
3963  * have been read so that the user can change the history file via his
3964  * .gdbinit file (for instance).  The GDBHISTFILE environment variable
3965  * overrides all of this.
3966  */
3967
3968 void
3969 init_history ()
3970 {
3971   char *tmpenv;
3972
3973   tmpenv = getenv ("HISTSIZE");
3974   if (tmpenv)
3975     history_size = atoi (tmpenv);
3976   else if (!history_size)
3977     history_size = 256;
3978
3979   stifle_history (history_size);
3980
3981   tmpenv = getenv ("GDBHISTFILE");
3982   if (tmpenv)
3983     history_filename = savestring (tmpenv, strlen (tmpenv));
3984   else if (!history_filename)
3985     {
3986       /* We include the current directory so that if the user changes
3987          directories the file written will be the same as the one
3988          that was read.  */
3989 #ifdef __MSDOS__
3990     /* No leading dots in file names are allowed on MSDOS.  */
3991     history_filename = concat (current_directory, "/_gdb_history", NULL);
3992 #else
3993       history_filename = concat (current_directory, "/.gdb_history", NULL);
3994 #endif
3995     }
3996   read_history (history_filename);
3997 }
3998
3999 static void
4000 init_main ()
4001 {
4002   struct cmd_list_element *c;
4003
4004   /* If we are running the asynchronous version,
4005      we initialize the prompts differently. */
4006   if (!event_loop_p)
4007     {
4008       gdb_prompt_string = savestring (DEFAULT_PROMPT, strlen (DEFAULT_PROMPT));
4009     }
4010   else
4011     {
4012       /* initialize the prompt stack to a simple "(gdb) " prompt or to
4013          whatever the DEFAULT_PROMPT is. */
4014       the_prompts.top = 0;
4015       PREFIX (0) = "";
4016       PROMPT (0) = savestring (DEFAULT_PROMPT, strlen (DEFAULT_PROMPT));
4017       SUFFIX (0) = "";
4018       /* Set things up for annotation_level > 1, if the user ever decides
4019          to use it. */
4020       async_annotation_suffix = "prompt";
4021       /* Set the variable associated with the setshow prompt command. */
4022       new_async_prompt = savestring (PROMPT (0), strlen (PROMPT (0)));
4023     }
4024   gdb_prompt_escape = 0;        /* default to none.  */
4025
4026   /* Set the important stuff up for command editing.  */
4027   command_editing_p = 1;
4028   history_expansion_p = 0;
4029   write_history_p = 0;
4030
4031   /* Setup important stuff for command line editing.  */
4032   rl_completion_entry_function = (int (*)()) readline_line_completion_function;
4033   rl_completer_word_break_characters = gdb_completer_word_break_characters;
4034   rl_completer_quote_characters = gdb_completer_quote_characters;
4035   rl_readline_name = "gdb";
4036
4037   /* Define the classes of commands.
4038      They will appear in the help list in the reverse of this order.  */
4039
4040   add_cmd ("internals", class_maintenance, NO_FUNCTION,
4041            "Maintenance commands.\n\
4042 Some gdb commands are provided just for use by gdb maintainers.\n\
4043 These commands are subject to frequent change, and may not be as\n\
4044 well documented as user commands.",
4045            &cmdlist);
4046   add_cmd ("obscure", class_obscure, NO_FUNCTION, "Obscure features.", &cmdlist);
4047   add_cmd ("aliases", class_alias, NO_FUNCTION, "Aliases of other commands.", &cmdlist);
4048   add_cmd ("user-defined", class_user, NO_FUNCTION, "User-defined commands.\n\
4049 The commands in this class are those defined by the user.\n\
4050 Use the \"define\" command to define a command.", &cmdlist);
4051   add_cmd ("support", class_support, NO_FUNCTION, "Support facilities.", &cmdlist);
4052   if (!dbx_commands)
4053     add_cmd ("status", class_info, NO_FUNCTION, "Status inquiries.", &cmdlist);
4054   add_cmd ("files", class_files, NO_FUNCTION, "Specifying and examining files.", &cmdlist);
4055   add_cmd ("breakpoints", class_breakpoint, NO_FUNCTION, "Making program stop at certain points.", &cmdlist);
4056   add_cmd ("data", class_vars, NO_FUNCTION, "Examining data.", &cmdlist);
4057   add_cmd ("stack", class_stack, NO_FUNCTION, "Examining the stack.\n\
4058 The stack is made up of stack frames.  Gdb assigns numbers to stack frames\n\
4059 counting from zero for the innermost (currently executing) frame.\n\n\
4060 At any time gdb identifies one frame as the \"selected\" frame.\n\
4061 Variable lookups are done with respect to the selected frame.\n\
4062 When the program being debugged stops, gdb selects the innermost frame.\n\
4063 The commands below can be used to select other frames by number or address.",
4064            &cmdlist);
4065   add_cmd ("running", class_run, NO_FUNCTION, "Running the program.", &cmdlist);
4066
4067   add_com ("pwd", class_files, pwd_command,
4068         "Print working directory.  This is used for your program as well.");
4069   c = add_cmd ("cd", class_files, cd_command,
4070                "Set working directory to DIR for debugger and program being debugged.\n\
4071 The change does not take effect for the program being debugged\n\
4072 until the next time it is started.", &cmdlist);
4073   c->completer = filename_completer;
4074
4075   /* The set prompt command is different depending whether or not the
4076      async version is run. NOTE: this difference is going to
4077      disappear as we make the event loop be the default engine of
4078      gdb. */
4079   if (!event_loop_p)
4080     {
4081       add_show_from_set
4082         (add_set_cmd ("prompt", class_support, var_string,
4083                       (char *) &gdb_prompt_string, "Set gdb's prompt",
4084                       &setlist),
4085          &showlist);
4086     }
4087   else
4088     {
4089       c = add_set_cmd ("prompt", class_support, var_string,
4090                        (char *) &new_async_prompt, "Set gdb's prompt",
4091                        &setlist);
4092       add_show_from_set (c, &showlist);
4093       c->function.sfunc = set_async_prompt;
4094     }
4095
4096   add_show_from_set
4097     (add_set_cmd ("prompt-escape-char", class_support, var_zinteger,
4098                   (char *) &gdb_prompt_escape,
4099                   "Set escape character for formatting of gdb's prompt",
4100                   &setlist),
4101      &showlist);
4102
4103   add_com ("echo", class_support, echo_command,
4104            "Print a constant string.  Give string as argument.\n\
4105 C escape sequences may be used in the argument.\n\
4106 No newline is added at the end of the argument;\n\
4107 use \"\\n\" if you want a newline to be printed.\n\
4108 Since leading and trailing whitespace are ignored in command arguments,\n\
4109 if you want to print some you must use \"\\\" before leading whitespace\n\
4110 to be printed or after trailing whitespace.");
4111   add_com ("document", class_support, document_command,
4112            "Document a user-defined command.\n\
4113 Give command name as argument.  Give documentation on following lines.\n\
4114 End with a line of just \"end\".");
4115   add_com ("define", class_support, define_command,
4116            "Define a new command name.  Command name is argument.\n\
4117 Definition appears on following lines, one command per line.\n\
4118 End with a line of just \"end\".\n\
4119 Use the \"document\" command to give documentation for the new command.\n\
4120 Commands defined in this way may have up to ten arguments.");
4121
4122 #ifdef __STDC__
4123   c = add_cmd ("source", class_support, source_command,
4124                "Read commands from a file named FILE.\n\
4125 Note that the file \"" GDBINIT_FILENAME "\" is read automatically in this way\n\
4126 when gdb is started.", &cmdlist);
4127 #else
4128   /* Punt file name, we can't help it easily.  */
4129   c = add_cmd ("source", class_support, source_command,
4130                "Read commands from a file named FILE.\n\
4131 Note that the file \".gdbinit\" is read automatically in this way\n\
4132 when gdb is started.", &cmdlist);
4133 #endif
4134   c->completer = filename_completer;
4135
4136   add_com ("quit", class_support, quit_command, "Exit gdb.");
4137   add_com ("help", class_support, help_command, "Print list of commands.");
4138   add_com_alias ("q", "quit", class_support, 1);
4139   add_com_alias ("h", "help", class_support, 1);
4140
4141   add_com ("dont-repeat", class_support, dont_repeat_command, "Don't repeat this command.\n\
4142 Primarily used inside of user-defined commands that should not be repeated when\n\
4143 hitting return.");
4144
4145   c = add_set_cmd ("verbose", class_support, var_boolean, (char *) &info_verbose,
4146                    "Set ",
4147                    &setlist),
4148     add_show_from_set (c, &showlist);
4149   c->function.sfunc = set_verbose;
4150   set_verbose (NULL, 0, c);
4151
4152   /* The set editing command is different depending whether or not the
4153      async version is run. NOTE: this difference is going to disappear
4154      as we make the event loop be the default engine of gdb. */
4155   if (!event_loop_p)
4156     {
4157       add_show_from_set
4158         (add_set_cmd ("editing", class_support, var_boolean, (char *) &command_editing_p,
4159                       "Set editing of command lines as they are typed.\n\
4160 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
4161 Without an argument, command line editing is enabled.  To edit, use\n\
4162 EMACS-like or VI-like commands like control-P or ESC.", &setlist),
4163          &showlist);
4164     }
4165   else
4166     {
4167       c = add_set_cmd ("editing", class_support, var_boolean, (char *) &async_command_editing_p,
4168                        "Set editing of command lines as they are typed.\n\
4169 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
4170 Without an argument, command line editing is enabled.  To edit, use\n\
4171 EMACS-like or VI-like commands like control-P or ESC.", &setlist);
4172
4173       add_show_from_set (c, &showlist);
4174       c->function.sfunc = set_async_editing_command;
4175     }
4176
4177   add_prefix_cmd ("history", class_support, set_history,
4178                   "Generic command for setting command history parameters.",
4179                   &sethistlist, "set history ", 0, &setlist);
4180   add_prefix_cmd ("history", class_support, show_history,
4181                   "Generic command for showing command history parameters.",
4182                   &showhistlist, "show history ", 0, &showlist);
4183
4184   add_show_from_set
4185     (add_set_cmd ("expansion", no_class, var_boolean, (char *) &history_expansion_p,
4186                   "Set history expansion on command input.\n\
4187 Without an argument, history expansion is enabled.", &sethistlist),
4188      &showhistlist);
4189
4190   add_show_from_set
4191     (add_set_cmd ("save", no_class, var_boolean, (char *) &write_history_p,
4192                   "Set saving of the history record on exit.\n\
4193 Use \"on\" to enable the saving, and \"off\" to disable it.\n\
4194 Without an argument, saving is enabled.", &sethistlist),
4195      &showhistlist);
4196
4197   c = add_set_cmd ("size", no_class, var_integer, (char *) &history_size,
4198                    "Set the size of the command history, \n\
4199 ie. the number of previous commands to keep a record of.", &sethistlist);
4200   add_show_from_set (c, &showhistlist);
4201   c->function.sfunc = set_history_size_command;
4202
4203   add_show_from_set
4204     (add_set_cmd ("filename", no_class, var_filename, (char *) &history_filename,
4205                   "Set the filename in which to record the command history\n\
4206  (the list of previous commands of which a record is kept).", &sethistlist),
4207      &showhistlist);
4208
4209   add_show_from_set
4210     (add_set_cmd ("confirm", class_support, var_boolean,
4211                   (char *) &caution,
4212                   "Set whether to confirm potentially dangerous operations.",
4213                   &setlist),
4214      &showlist);
4215
4216   add_prefix_cmd ("info", class_info, info_command,
4217      "Generic command for showing things about the program being debugged.",
4218                   &infolist, "info ", 0, &cmdlist);
4219   add_com_alias ("i", "info", class_info, 1);
4220
4221   add_com ("complete", class_obscure, complete_command,
4222            "List the completions for the rest of the line as a command.");
4223
4224   add_prefix_cmd ("show", class_info, show_command,
4225                   "Generic command for showing things about the debugger.",
4226                   &showlist, "show ", 0, &cmdlist);
4227   /* Another way to get at the same thing.  */
4228   add_info ("set", show_command, "Show all GDB settings.");
4229
4230   add_cmd ("commands", no_class, show_commands,
4231            "Show the history of commands you typed.\n\
4232 You can supply a command number to start with, or a `+' to start after\n\
4233 the previous command number shown.",
4234            &showlist);
4235
4236   add_cmd ("version", no_class, show_version,
4237            "Show what version of GDB this is.", &showlist);
4238
4239   add_com ("while", class_support, while_command,
4240            "Execute nested commands WHILE the conditional expression is non zero.\n\
4241 The conditional expression must follow the word `while' and must in turn be\n\
4242 followed by a new line.  The nested commands must be entered one per line,\n\
4243 and should be terminated by the word `end'.");
4244
4245   add_com ("if", class_support, if_command,
4246            "Execute nested commands once IF the conditional expression is non zero.\n\
4247 The conditional expression must follow the word `if' and must in turn be\n\
4248 followed by a new line.  The nested commands must be entered one per line,\n\
4249 and should be terminated by the word 'else' or `end'.  If an else clause\n\
4250 is used, the same rules apply to its nested commands as to the first ones.");
4251
4252   /* If target is open when baud changes, it doesn't take effect until the
4253      next open (I think, not sure).  */
4254   add_show_from_set (add_set_cmd ("remotebaud", no_class,
4255                                   var_zinteger, (char *) &baud_rate,
4256                                   "Set baud rate for remote serial I/O.\n\
4257 This value is used to set the speed of the serial port when debugging\n\
4258 using remote targets.", &setlist),
4259                      &showlist);
4260
4261   add_show_from_set (
4262   add_set_cmd ("remotedebug", no_class, var_zinteger, (char *) &remote_debug,
4263                "Set debugging of remote protocol.\n\
4264 When enabled, each packet sent or received with the remote target\n\
4265 is displayed.", &setlist),
4266                       &showlist);
4267
4268   add_show_from_set (
4269                       add_set_cmd ("remotetimeout", no_class, var_integer, (char *) &remote_timeout,
4270                                    "Set timeout limit to wait for target to respond.\n\
4271 This value is used to set the time limit for gdb to wait for a response\n\
4272 from the target.", &setlist),
4273                       &showlist);
4274
4275   /* The set annotate command is different depending whether or not
4276      the async version is run. NOTE: this difference is going to
4277      disappear as we make the event loop be the default engine of
4278      gdb. */
4279   if (!event_loop_p)
4280     {
4281       c = add_set_cmd ("annotate", class_obscure, var_zinteger,
4282                        (char *) &annotation_level, "Set annotation_level.\n\
4283 0 == normal;     1 == fullname (for use when running under emacs)\n\
4284 2 == output annotated suitably for use by programs that control GDB.",
4285                        &setlist);
4286       c = add_show_from_set (c, &showlist);
4287     }
4288   else
4289     {
4290       c = add_set_cmd ("annotate", class_obscure, var_zinteger,
4291                        (char *) &annotation_level, "Set annotation_level.\n\
4292 0 == normal;     1 == fullname (for use when running under emacs)\n\
4293 2 == output annotated suitably for use by programs that control GDB.",
4294                        &setlist);
4295       add_show_from_set (c, &showlist);
4296       c->function.sfunc = set_async_annotation_level;
4297     }
4298   if (event_loop_p)
4299     {
4300       add_show_from_set
4301         (add_set_cmd ("exec-done-display", class_support, var_boolean, (char *) &exec_done_display_p,
4302                       "Set notification of completion for asynchronous execution commands.\n\
4303 Use \"on\" to enable the notification, and \"off\" to disable it.", &setlist),
4304          &showlist);
4305     }
4306 }