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