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