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