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