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