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