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