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