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