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