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