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