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