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