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