import gdb-1999-06-14 snapshot
[external/binutils.git] / gdb / top.c
1 /* Top level stuff for GDB, the GNU debugger.
2    Copyright 1986, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 1998
3    Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, 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 "event-loop.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 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49
50 #include "gdb_string.h"
51 #include "gdb_stat.h"
52 #include <ctype.h>
53
54 /* Prototypes for local functions */
55
56 static void dont_repeat_command PARAMS ((char *, int));
57
58 static void source_cleanup_lines PARAMS ((PTR));
59
60 static void user_defined_command PARAMS ((char *, int));
61
62 static void init_signals PARAMS ((void));
63
64 #ifdef STOP_SIGNAL
65 static void stop_sig PARAMS ((int));
66 #endif
67
68 static char * line_completion_function PARAMS ((char *, int, char *, int));
69
70 static char * readline_line_completion_function PARAMS ((char *, int));
71
72 /* NOTE 1999-04-29: this function will be static again, after we make the
73    event loop be the default command loop for gdb, and we merge
74    event-top.c into this file, top.c */
75 /* static */ void command_loop_marker PARAMS ((int));
76
77 static void while_command PARAMS ((char *, int));
78
79 static void if_command PARAMS ((char *, int));
80
81 static struct command_line *
82 build_command_line PARAMS ((enum command_control_type, char *));
83
84 static struct command_line *
85 get_command_line PARAMS ((enum command_control_type, char *));
86
87 static void realloc_body_list PARAMS ((struct command_line *, int));
88
89 static enum misc_command_type read_next_line PARAMS ((struct command_line **));
90
91 static enum command_control_type
92 recurse_read_control_structure PARAMS ((struct command_line *));
93
94 static struct cleanup * setup_user_args PARAMS ((char *));
95
96 static char * locate_arg PARAMS ((char *));
97
98 static char * insert_args PARAMS ((char *));
99
100 static void arg_cleanup PARAMS ((void));
101
102 static void init_main PARAMS ((void));
103
104 static void init_cmd_lists PARAMS ((void));
105
106 static void float_handler PARAMS ((int));
107
108 static void init_signals PARAMS ((void));
109
110 static void set_verbose PARAMS ((char *, int, struct cmd_list_element *));
111
112 static void show_history PARAMS ((char *, int));
113
114 static void set_history PARAMS ((char *, int));
115
116 static void set_history_size_command PARAMS ((char *, int,
117                                               struct cmd_list_element *));
118
119 static void show_commands PARAMS ((char *, int));
120
121 static void echo_command PARAMS ((char *, int));
122
123 static void pwd_command PARAMS ((char *, int));
124
125 static void show_version PARAMS ((char *, int));
126
127 static void document_command PARAMS ((char *, int));
128
129 static void define_command PARAMS ((char *, int));
130
131 static void validate_comname PARAMS ((char *));
132
133 static void help_command PARAMS ((char *, int));
134
135 static void show_command PARAMS ((char *, int));
136
137 static void info_command PARAMS ((char *, int));
138
139 static void complete_command PARAMS ((char *, int));
140
141 static void do_nothing PARAMS ((int));
142
143 #ifdef SIGHUP
144 /* NOTE 1999-04-29: This function will be static again, once we modify
145    gdb to use the event loop as the default command loop and we merge
146    event-top.c into this file, top.c */
147 /* static */ int quit_cover PARAMS ((PTR));
148
149 static void disconnect PARAMS ((int));
150 #endif
151
152 static void source_cleanup PARAMS ((FILE *));
153
154 /* If this definition isn't overridden by the header files, assume
155    that isatty and fileno exist on this system.  */
156 #ifndef ISATTY
157 #define ISATTY(FP)      (isatty (fileno (FP)))
158 #endif
159
160 /* Initialization file name for gdb.  This is overridden in some configs.  */
161
162 #ifndef GDBINIT_FILENAME
163 #define GDBINIT_FILENAME        ".gdbinit"
164 #endif
165 char gdbinit[] = GDBINIT_FILENAME;
166
167 int inhibit_gdbinit = 0;
168
169 /* If nonzero, and GDB has been configured to be able to use windows,
170    attempt to open them upon startup.  */
171
172 int use_windows = 1;
173
174 /* Version number of GDB, as a string.  */
175
176 extern char *version;
177
178 /* Canonical host name as a string. */
179
180 extern char *host_name;
181
182 /* Canonical target name as a string. */
183
184 extern char *target_name;
185
186 extern char lang_frame_mismatch_warn[];         /* language.c */
187
188 /* Flag for whether we want all the "from_tty" gubbish printed.  */
189
190 int caution = 1;                        /* Default is yes, sigh. */
191
192 /* Define all cmd_list_elements.  */
193
194 /* Chain containing all defined commands.  */
195
196 struct cmd_list_element *cmdlist;
197
198 /* Chain containing all defined info subcommands.  */
199
200 struct cmd_list_element *infolist;
201
202 /* Chain containing all defined enable subcommands. */
203
204 struct cmd_list_element *enablelist;
205
206 /* Chain containing all defined disable subcommands. */
207
208 struct cmd_list_element *disablelist;
209
210 /* Chain containing all defined toggle subcommands. */
211
212 struct cmd_list_element *togglelist;
213
214 /* Chain containing all defined stop subcommands. */
215
216 struct cmd_list_element *stoplist;
217
218 /* Chain containing all defined delete subcommands. */
219
220 struct cmd_list_element *deletelist;
221
222 /* Chain containing all defined "enable breakpoint" subcommands. */
223
224 struct cmd_list_element *enablebreaklist;
225
226 /* Chain containing all defined set subcommands */
227
228 struct cmd_list_element *setlist;
229
230 /* Chain containing all defined unset subcommands */
231
232 struct cmd_list_element *unsetlist;
233
234 /* Chain containing all defined show subcommands.  */
235
236 struct cmd_list_element *showlist;
237
238 /* Chain containing all defined \"set history\".  */
239
240 struct cmd_list_element *sethistlist;
241
242 /* Chain containing all defined \"show history\".  */
243
244 struct cmd_list_element *showhistlist;
245
246 /* Chain containing all defined \"unset history\".  */
247
248 struct cmd_list_element *unsethistlist;
249
250 /* Chain containing all defined maintenance subcommands. */
251
252 struct cmd_list_element *maintenancelist;
253
254 /* Chain containing all defined "maintenance info" subcommands. */
255
256 struct cmd_list_element *maintenanceinfolist;
257
258 /* Chain containing all defined "maintenance print" subcommands. */
259
260 struct cmd_list_element *maintenanceprintlist;
261
262 struct cmd_list_element *setprintlist;
263
264 struct cmd_list_element *showprintlist;
265
266 struct cmd_list_element *setchecklist;
267
268 struct cmd_list_element *showchecklist;
269
270 /* stdio stream that command input is being read from.  Set to stdin normally.
271    Set by source_command to the file we are sourcing.  Set to NULL if we are
272    executing a user-defined command or interacting via a GUI.  */
273
274 FILE *instream;
275
276 /* Current working directory.  */
277
278 char *current_directory;
279
280 /* The directory name is actually stored here (usually).  */
281 char gdb_dirbuf[1024];
282
283 /* Function to call before reading a command, if nonzero.
284    The function receives two args: an input stream,
285    and a prompt string.  */
286
287 void (*window_hook) PARAMS ((FILE *, char *));
288
289 int epoch_interface;
290 int xgdb_verbose;
291
292 /* gdb prints this when reading a command interactively */
293 static char *gdb_prompt_string;         /* the global prompt string */
294 extern char *get_prompt PARAMS((void)); /* access function for prompt string */
295
296 /* Buffer used for reading command lines, and the size
297    allocated for it so far.  */
298
299 char *line;
300 int linesize = 100;
301
302 /* Nonzero if the current command is modified by "server ".  This
303    affects things like recording into the command history, comamnds
304    repeating on RETURN, etc.  This is so a user interface (emacs, GUI,
305    whatever) can issue its own commands and also send along commands
306    from the user, and have the user not notice that the user interface
307    is issuing commands too.  */
308 int server_command;
309
310 /* Baud rate specified for talking to serial target systems.  Default
311    is left as -1, so targets can choose their own defaults.  */
312 /* FIXME: This means that "show remotebaud" and gr_files_info can print -1
313    or (unsigned int)-1.  This is a Bad User Interface.  */
314
315 int baud_rate = -1;
316
317 /* Timeout limit for response from target. */
318
319 int remote_timeout = 20;        /* Set default to 20 */
320
321 /* Non-zero tells remote* modules to output debugging info.  */
322
323 int remote_debug = 0;
324
325 /* Level of control structure.  */
326 static int control_level;
327
328 /* Structure for arguments to user defined functions.  */
329 #define MAXUSERARGS 10
330 struct user_args
331 {
332   struct user_args *next;
333   struct
334     {
335       char *arg;
336       int len;
337     } a[MAXUSERARGS];
338   int count;
339 } *user_args;
340
341 /* Signal to catch ^Z typed while reading a command: SIGTSTP or SIGCONT.  */
342
343 #ifndef STOP_SIGNAL
344 #ifdef SIGTSTP
345 #define STOP_SIGNAL SIGTSTP
346 static void stop_sig PARAMS ((int));
347 #endif
348 #endif
349
350 /* Some System V have job control but not sigsetmask(). */
351 #if !defined (HAVE_SIGSETMASK)
352 #if !defined (USG)
353 #define HAVE_SIGSETMASK 1
354 #else
355 #define HAVE_SIGSETMASK 0
356 #endif
357 #endif
358
359 #if 0 == (HAVE_SIGSETMASK)
360 #define sigsetmask(n)
361 #endif
362
363 /* Hooks for alternate command interfaces.  */
364
365 /* Called after most modules have been initialized, but before taking users
366    command file.  */
367
368 void (*init_ui_hook) PARAMS ((char *argv0));
369
370 /* This hook is called from within gdb's many mini-event loops which could
371    steal control from a real user interface's event loop. It returns
372    non-zero if the user is requesting a detach, zero otherwise. */
373
374 int (*ui_loop_hook) PARAMS ((int));
375
376 /* Called instead of command_loop at top level.  Can be invoked via
377    return_to_top_level.  */
378
379 void (*command_loop_hook) PARAMS ((void));
380
381
382 /* Called instead of fputs for all output.  */
383
384 void (*fputs_unfiltered_hook) PARAMS ((const char *linebuffer, GDB_FILE *stream));
385
386 /* Called when the target says something to the host, which may
387    want to appear in a different window. */
388
389 void (*target_output_hook) PARAMS ((char *));
390
391 /* Called from print_frame_info to list the line we stopped in.  */
392
393 void (*print_frame_info_listing_hook) PARAMS ((struct symtab *s, int line,
394                                                int stopline, int noerror));
395 /* Replaces most of query.  */
396
397 int (*query_hook) PARAMS ((const char *, va_list));
398
399 /* Replaces most of warning.  */
400
401 void (*warning_hook) PARAMS ((const char *, va_list));
402
403 /* Called from gdb_flush to flush output.  */
404
405 void (*flush_hook) PARAMS ((GDB_FILE *stream));
406
407 /* These three functions support getting lines of text from the user.  They
408    are used in sequence.  First readline_begin_hook is called with a text
409    string that might be (for example) a message for the user to type in a
410    sequence of commands to be executed at a breakpoint.  If this function
411    calls back to a GUI, it might take this opportunity to pop up a text
412    interaction window with this message.  Next, readline_hook is called
413    with a prompt that is emitted prior to collecting the user input.
414    It can be called multiple times.  Finally, readline_end_hook is called
415    to notify the GUI that we are done with the interaction window and it
416    can close it. */
417
418 void (*readline_begin_hook) PARAMS ((char *, ...));
419 char * (*readline_hook) PARAMS ((char *));
420 void (*readline_end_hook) PARAMS ((void));
421
422 /* Called as appropriate to notify the interface of the specified breakpoint
423    conditions.  */
424
425 void (*create_breakpoint_hook) PARAMS ((struct breakpoint *bpt));
426 void (*delete_breakpoint_hook) PARAMS ((struct breakpoint *bpt));
427 void (*modify_breakpoint_hook) PARAMS ((struct breakpoint *bpt));
428
429 /* Called during long calculations to allow GUI to repair window damage, and to
430    check for stop buttons, etc... */
431
432 void (*interactive_hook) PARAMS ((void));
433
434 /* Called when the registers have changed, as a hint to a GUI
435    to minimize window update. */
436
437 void (*registers_changed_hook) PARAMS ((void));
438
439 /* Tell the GUI someone changed the register REGNO. -1 means
440    that the caller does not know which register changed or
441    that several registers have changed (see value_assign).*/
442 void (*register_changed_hook) PARAMS ((int regno));
443
444 /* Tell the GUI someone changed LEN bytes of memory at ADDR */
445 void (*memory_changed_hook) PARAMS ((CORE_ADDR addr, int len));
446
447 /* Called when going to wait for the target.  Usually allows the GUI to run
448    while waiting for target events.  */
449
450 int (*target_wait_hook) PARAMS ((int pid, struct target_waitstatus *status));
451
452 /* Used by UI as a wrapper around command execution.  May do various things
453    like enabling/disabling buttons, etc...  */
454
455 void (*call_command_hook) PARAMS ((struct cmd_list_element *c, char *cmd,
456                                    int from_tty));
457
458 /* Called when the current thread changes.  Argument is thread id.  */
459
460 void (*context_hook) PARAMS ((int id));
461
462 /* Takes control from error ().  Typically used to prevent longjmps out of the
463    middle of the GUI.  Usually used in conjunction with a catch routine.  */
464
465 NORETURN void (*error_hook) PARAMS ((void)) ATTR_NORETURN;
466
467 \f
468 /* Where to go for return_to_top_level (RETURN_ERROR).  */
469 SIGJMP_BUF error_return;
470 /* Where to go for return_to_top_level (RETURN_QUIT).  */
471 SIGJMP_BUF quit_return;
472
473 /* Return for reason REASON.  This generally gets back to the command
474    loop, but can be caught via catch_errors.  */
475
476 NORETURN void
477 return_to_top_level (reason)
478      enum return_reason reason;
479 {
480   quit_flag = 0;
481   immediate_quit = 0;
482
483   /* Perhaps it would be cleaner to do this via the cleanup chain (not sure
484      I can think of a reason why that is vital, though).  */
485   bpstat_clear_actions(stop_bpstat);    /* Clear queued breakpoint commands */
486
487   disable_current_display ();
488   do_cleanups (ALL_CLEANUPS);
489
490   if (annotation_level > 1)
491     switch (reason)
492       {
493       case RETURN_QUIT:
494         annotate_quit ();
495         break;
496       case RETURN_ERROR:
497         annotate_error ();
498         break;
499       }
500
501   (NORETURN void) SIGLONGJMP
502     (reason == RETURN_ERROR ? error_return : quit_return, 1);
503 }
504
505 /* Call FUNC with arg ARGS, catching any errors.  If there is no
506    error, return the value returned by FUNC.  If there is an error,
507    print ERRSTRING, print the specific error message, then return
508    zero.
509
510    Must not be called with immediate_quit in effect (bad things might
511    happen, say we got a signal in the middle of a memcpy to quit_return).
512    This is an OK restriction; with very few exceptions immediate_quit can
513    be replaced by judicious use of QUIT.
514
515    MASK specifies what to catch; it is normally set to
516    RETURN_MASK_ALL, if for no other reason than that the code which
517    calls catch_errors might not be set up to deal with a quit which
518    isn't caught.  But if the code can deal with it, it generally
519    should be RETURN_MASK_ERROR, unless for some reason it is more
520    useful to abort only the portion of the operation inside the
521    catch_errors.  Note that quit should return to the command line
522    fairly quickly, even if some further processing is being done.  */
523
524 int
525 catch_errors (func, args, errstring, mask)
526      catch_errors_ftype *func;
527      PTR args;
528      char *errstring;
529      return_mask mask;
530 {
531   SIGJMP_BUF saved_error;
532   SIGJMP_BUF saved_quit;
533   SIGJMP_BUF tmp_jmp;
534   int val;
535   struct cleanup *saved_cleanup_chain;
536   char *saved_error_pre_print;
537   char *saved_quit_pre_print;
538
539   saved_cleanup_chain = save_cleanups ();
540   saved_error_pre_print = error_pre_print;
541   saved_quit_pre_print = quit_pre_print;
542
543   if (mask & RETURN_MASK_ERROR)
544     {
545       memcpy ((char *)saved_error, (char *)error_return, sizeof (SIGJMP_BUF));
546       error_pre_print = errstring;
547     }
548   if (mask & RETURN_MASK_QUIT)
549     {
550       memcpy (saved_quit, quit_return, sizeof (SIGJMP_BUF));
551       quit_pre_print = errstring;
552     }
553
554   if (SIGSETJMP (tmp_jmp) == 0)
555     {
556       if (mask & RETURN_MASK_ERROR)
557         memcpy (error_return, tmp_jmp, sizeof (SIGJMP_BUF));
558       if (mask & RETURN_MASK_QUIT)
559         memcpy (quit_return, tmp_jmp, sizeof (SIGJMP_BUF));
560       val = (*func) (args);
561     }
562   else
563     val = 0;
564
565   restore_cleanups (saved_cleanup_chain);
566
567   if (mask & RETURN_MASK_ERROR)
568     {
569       memcpy (error_return, saved_error, sizeof (SIGJMP_BUF));
570       error_pre_print = saved_error_pre_print;
571     }
572   if (mask & RETURN_MASK_QUIT)
573     {
574       memcpy (quit_return, saved_quit, sizeof (SIGJMP_BUF));
575       quit_pre_print = saved_quit_pre_print;
576     }
577   return val;
578 }
579
580 /* Handler for SIGHUP.  */
581
582 #ifdef SIGHUP
583 static void
584 disconnect (signo)
585 int signo;
586 {
587   catch_errors (quit_cover, NULL,
588                 "Could not kill the program being debugged", RETURN_MASK_ALL);
589   signal (SIGHUP, SIG_DFL);
590   kill (getpid (), SIGHUP);
591 }
592
593 /* Just a little helper function for disconnect().  */
594
595 /* NOTE 1999-04-29: This function will be static again, once we modify
596    gdb to use the event loop as the default command loop and we merge
597    event-top.c into this file, top.c */
598 /* static */ int
599 quit_cover (s)
600      PTR s;
601 {
602   caution = 0;          /* Throw caution to the wind -- we're exiting.
603                            This prevents asking the user dumb questions.  */
604   quit_command((char *)0, 0);
605   return 0;
606 }
607 #endif /* defined SIGHUP */
608 \f
609 /* Line number we are currently in in a file which is being sourced.  */
610 /* NOTE 1999-04-29: This variable will be static again, once we modify
611    gdb to use the event loop as the default command loop and we merge
612    event-top.c into this file, top.c */
613 /* static */ int source_line_number;
614
615 /* Name of the file we are sourcing.  */
616 /* NOTE 1999-04-29: This variable will be static again, once we modify
617    gdb to use the event loop as the default command loop and we merge
618    event-top.c into this file, top.c */
619 /* static */ char *source_file_name;
620
621 /* Buffer containing the error_pre_print used by the source stuff.
622    Malloc'd.  */
623 /* NOTE 1999-04-29: This variable will be static again, once we modify
624    gdb to use the event loop as the default command loop and we merge
625    event-top.c into this file, top.c */
626 /* static */ char *source_error;
627 static int source_error_allocated;
628
629 /* Something to glom on to the start of error_pre_print if source_file_name
630    is set.  */
631 /* NOTE 1999-04-29: This variable will be static again, once we modify
632    gdb to use the event loop as the default command loop and we merge
633    event-top.c into this file, top.c */
634 /* static */ char *source_pre_error;
635
636 /* Clean up on error during a "source" command (or execution of a
637    user-defined command).  */
638
639 static void
640 source_cleanup (stream)
641      FILE *stream;
642 {
643   /* Restore the previous input stream.  */
644   instream = stream;
645 }
646
647 /* Read commands from STREAM.  */
648 void
649 read_command_file (stream)
650      FILE *stream;
651 {
652   struct cleanup *cleanups;
653
654   cleanups = make_cleanup ((make_cleanup_func) source_cleanup, instream);
655   instream = stream;
656   command_loop (); 
657   do_cleanups (cleanups);
658 }
659 \f
660 extern void init_proc PARAMS ((void));
661
662 void (*pre_init_ui_hook) PARAMS ((void));
663
664 void
665 gdb_init (argv0)
666      char *argv0;
667 {
668   if (pre_init_ui_hook)
669     pre_init_ui_hook ();
670
671   /* Run the init function of each source file */
672
673   getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
674   current_directory = gdb_dirbuf;
675
676   init_cmd_lists ();    /* This needs to be done first */
677   initialize_targets (); /* Setup target_terminal macros for utils.c */
678   initialize_utils ();  /* Make errors and warnings possible */
679   initialize_all_files ();
680   init_main ();         /* But that omits this file!  Do it now */
681
682   /* The signal handling mechanism is different depending whether or
683      not the async version is run. NOTE: in the future we plan to make
684      the event loop be the default engine of gdb, and this difference
685      will disappear. */
686   if (async_p)
687     async_init_signals ();
688   else
689     init_signals (); 
690
691   /* We need a default language for parsing expressions, so simple things like
692      "set width 0" won't fail if no language is explicitly set in a config file
693      or implicitly set by reading an executable during startup. */
694   set_language (language_c);
695   expected_language = current_language; /* don't warn about the change.  */
696
697   /* All the interpreters should have had a look at things by now.
698      Initialize the selected interpreter. */
699   if (init_ui_hook)
700     init_ui_hook (argv0);
701 }
702
703 /* Allocate, initialize a new command line structure for one of the
704    control commands (if/while).  */
705
706 static struct command_line *
707 build_command_line (type, args)
708      enum command_control_type type;
709      char *args;
710 {
711   struct command_line *cmd;
712
713   if (args == NULL)
714     error ("if/while commands require arguments.\n");
715
716   cmd = (struct command_line *)xmalloc (sizeof (struct command_line));
717   cmd->next = NULL;
718   cmd->control_type = type;
719
720   cmd->body_count = 1;
721   cmd->body_list
722     = (struct command_line **)xmalloc (sizeof (struct command_line *)
723                                        * cmd->body_count);
724   memset (cmd->body_list, 0, sizeof (struct command_line *) * cmd->body_count);
725   cmd->line = savestring (args, strlen (args));
726   return cmd;
727 }
728
729 /* Build and return a new command structure for the control commands
730    such as "if" and "while".  */
731
732 static struct command_line *
733 get_command_line (type, arg)
734      enum command_control_type type;
735      char *arg;
736 {
737   struct command_line *cmd;
738   struct cleanup *old_chain = NULL;
739
740   /* Allocate and build a new command line structure.  */
741   cmd = build_command_line (type, arg);
742
743   old_chain = make_cleanup ((make_cleanup_func) free_command_lines, &cmd);
744
745   /* Read in the body of this command.  */
746   if (recurse_read_control_structure (cmd) == invalid_control)
747     {
748       warning ("error reading in control structure\n");
749       do_cleanups (old_chain);
750       return NULL;
751     }
752
753   discard_cleanups (old_chain);
754   return cmd;
755 }
756
757 /* Recursively print a command (including full control structures).  */
758 void
759 print_command_line (cmd, depth, stream)
760      struct command_line *cmd;
761      unsigned int depth;
762      GDB_FILE *stream;
763 {
764   unsigned int i;
765
766   if (depth)
767     {
768       for (i = 0; i < depth; i++)
769         fputs_filtered ("  ", stream);
770     }
771
772   /* A simple command, print it and return.  */
773   if (cmd->control_type == simple_control)
774     {
775       fputs_filtered (cmd->line, stream);
776       fputs_filtered ("\n", stream);
777       return;
778     }
779
780   /* loop_continue to jump to the start of a while loop, print it
781      and return. */
782   if (cmd->control_type == continue_control)
783     {
784       fputs_filtered ("loop_continue\n", stream);
785       return;
786     }
787
788   /* loop_break to break out of a while loop, print it and return.  */
789   if (cmd->control_type == break_control)
790     {
791       fputs_filtered ("loop_break\n", stream);
792       return;
793     }
794
795   /* A while command.  Recursively print its subcommands before returning.  */
796   if (cmd->control_type == while_control)
797     {
798       struct command_line *list;
799       fputs_filtered ("while ", stream);
800       fputs_filtered (cmd->line, stream);
801       fputs_filtered ("\n", stream);
802       list = *cmd->body_list;
803       while (list)
804         {
805           print_command_line (list, depth + 1, stream);
806           list = list->next;
807         }
808     }
809
810   /* An if command.  Recursively print both arms before returning.  */
811   if (cmd->control_type == if_control)
812     {
813       fputs_filtered ("if ", stream);
814       fputs_filtered (cmd->line, stream);
815       fputs_filtered ("\n", stream);
816       /* The true arm. */
817       print_command_line (cmd->body_list[0], depth + 1, stream);
818
819       /* Show the false arm if it exists.  */
820       if (cmd->body_count == 2)
821           {
822             if (depth)
823               {
824                 for (i = 0; i < depth; i++)
825                   fputs_filtered ("  ", stream);
826               }
827             fputs_filtered ("else\n", stream);
828             print_command_line (cmd->body_list[1], depth + 1, stream);
829           }
830       if (depth)
831         {
832           for (i = 0; i < depth; i++)
833             fputs_filtered ("  ", stream);
834         }
835       fputs_filtered ("end\n", stream);
836     }
837 }
838
839 /* Execute the command in CMD.  */
840
841 enum command_control_type
842 execute_control_command (cmd)
843      struct command_line *cmd;
844 {
845   struct expression *expr;
846   struct command_line *current;
847   struct cleanup *old_chain = 0;
848   value_ptr val;
849   value_ptr val_mark;
850   int loop;
851   enum command_control_type ret;
852   char *new_line;
853
854   switch (cmd->control_type)
855     {
856     case simple_control:
857       /* A simple command, execute it and return.  */
858       new_line = insert_args (cmd->line);
859       if (!new_line)
860         return invalid_control;
861       old_chain = make_cleanup ((make_cleanup_func) free_current_contents, 
862                                 &new_line);
863       execute_command (new_line, 0);
864       ret = cmd->control_type;
865       break;
866
867     case continue_control:
868     case break_control:
869       /* Return for "continue", and "break" so we can either
870          continue the loop at the top, or break out.  */
871       ret = cmd->control_type;
872       break;
873
874     case while_control:
875       {
876         /* Parse the loop control expression for the while statement.  */
877         new_line = insert_args (cmd->line);
878         if (!new_line)
879           return invalid_control;
880         old_chain = make_cleanup ((make_cleanup_func) free_current_contents, 
881                                   &new_line);
882         expr = parse_expression (new_line);
883         make_cleanup ((make_cleanup_func) free_current_contents, &expr);
884         
885         ret = simple_control;
886         loop = 1;
887
888         /* Keep iterating so long as the expression is true.  */
889         while (loop == 1)
890           {
891             int cond_result;
892
893             QUIT;
894
895             /* Evaluate the expression.  */
896             val_mark = value_mark ();
897             val = evaluate_expression (expr);
898             cond_result = value_true (val);
899             value_free_to_mark (val_mark);
900
901             /* If the value is false, then break out of the loop.  */
902             if (!cond_result)
903               break;
904
905             /* Execute the body of the while statement.  */
906             current = *cmd->body_list;
907             while (current)
908               {
909                 ret = execute_control_command (current);
910
911                 /* If we got an error, or a "break" command, then stop
912                    looping.  */
913                 if (ret == invalid_control || ret == break_control)
914                   {
915                     loop = 0;
916                     break;
917                   }
918
919                 /* If we got a "continue" command, then restart the loop
920                    at this point.  */
921                 if (ret == continue_control)
922                   break;
923                 
924                 /* Get the next statement.  */
925                 current = current->next; 
926               }
927           }
928
929         /* Reset RET so that we don't recurse the break all the way down.  */
930         if (ret == break_control)
931           ret = simple_control;
932
933         break;
934       }
935
936     case if_control:
937       {
938         new_line = insert_args (cmd->line);
939         if (!new_line)
940           return invalid_control;
941         old_chain = make_cleanup ((make_cleanup_func) free_current_contents, 
942                                   &new_line);
943         /* Parse the conditional for the if statement.  */
944         expr = parse_expression (new_line);
945         make_cleanup ((make_cleanup_func) free_current_contents, &expr);
946
947         current = NULL;
948         ret = simple_control;
949
950         /* Evaluate the conditional.  */
951         val_mark = value_mark ();
952         val = evaluate_expression (expr);
953
954         /* Choose which arm to take commands from based on the value of the
955            conditional expression.  */
956         if (value_true (val))
957           current = *cmd->body_list;
958         else if (cmd->body_count == 2)
959           current = *(cmd->body_list + 1);
960         value_free_to_mark (val_mark);
961
962         /* Execute commands in the given arm.  */
963         while (current)
964           {
965             ret = execute_control_command (current);
966
967             /* If we got an error, get out.  */
968             if (ret != simple_control)
969               break;
970
971             /* Get the next statement in the body.  */
972             current = current->next;
973           }
974
975         break;
976       }
977
978     default:
979       warning ("Invalid control type in command structure.");
980       return invalid_control;
981     }
982
983   if (old_chain)
984     do_cleanups (old_chain);
985
986   return ret;
987 }
988
989 /* "while" command support.  Executes a body of statements while the
990    loop condition is nonzero.  */
991
992 static void
993 while_command (arg, from_tty)
994      char *arg;
995      int from_tty;
996 {
997   struct command_line *command = NULL;
998
999   control_level = 1;
1000   command = get_command_line (while_control, arg);
1001
1002   if (command == NULL)
1003     return;
1004
1005   execute_control_command (command);
1006   free_command_lines (&command);
1007 }
1008
1009 /* "if" command support.  Execute either the true or false arm depending
1010    on the value of the if conditional.  */
1011
1012 static void
1013 if_command (arg, from_tty)
1014      char *arg;
1015      int from_tty;
1016 {
1017   struct command_line *command = NULL;
1018
1019   control_level = 1;
1020   command = get_command_line (if_control, arg);
1021
1022   if (command == NULL)
1023     return;
1024
1025   execute_control_command (command);
1026   free_command_lines (&command);
1027 }
1028
1029 /* Cleanup */
1030 static void
1031 arg_cleanup ()
1032 {
1033   struct user_args *oargs = user_args;
1034   if (!user_args)
1035     fatal ("Internal error, arg_cleanup called with no user args.\n");
1036
1037   user_args = user_args->next;
1038   free (oargs);
1039 }
1040
1041 /* Bind the incomming arguments for a user defined command to
1042    $arg0, $arg1 ... $argMAXUSERARGS.  */
1043
1044 static struct cleanup *
1045 setup_user_args (p)
1046      char *p;
1047 {
1048   struct user_args *args;
1049   struct cleanup *old_chain;
1050   unsigned int arg_count = 0;
1051
1052   args = (struct user_args *)xmalloc (sizeof (struct user_args));
1053   memset (args, 0, sizeof (struct user_args));
1054
1055   args->next = user_args;
1056   user_args = args;
1057
1058   old_chain = make_cleanup ((make_cleanup_func) arg_cleanup, 0);
1059
1060   if (p == NULL)
1061     return old_chain;
1062
1063   while (*p)
1064     {
1065       char *start_arg;
1066       int squote = 0;
1067       int dquote = 0;
1068       int bsquote = 0;
1069
1070       if (arg_count >= MAXUSERARGS)
1071         {
1072           error ("user defined function may only have %d arguments.\n",
1073                  MAXUSERARGS);
1074           return old_chain;
1075         }
1076
1077       /* Strip whitespace.  */
1078       while (*p == ' ' || *p == '\t')
1079         p++;
1080
1081       /* P now points to an argument.  */
1082       start_arg = p;
1083       user_args->a[arg_count].arg = p;
1084
1085       /* Get to the end of this argument.  */
1086       while (*p)
1087         {
1088           if (((*p == ' ' || *p == '\t')) && !squote && !dquote && !bsquote)
1089             break;
1090           else
1091             {
1092               if (bsquote)
1093                 bsquote = 0;
1094               else if (*p == '\\')
1095                 bsquote = 1;
1096               else if (squote)
1097                 {
1098                   if (*p == '\'')
1099                     squote = 0;
1100                 }
1101               else if (dquote)
1102                 {
1103                   if (*p == '"')
1104                     dquote = 0;
1105                 }
1106               else
1107                 {
1108                   if (*p == '\'')
1109                     squote = 1;
1110                   else if (*p == '"')
1111                     dquote = 1;
1112                 }
1113               p++;
1114             }
1115         }
1116
1117       user_args->a[arg_count].len = p - start_arg;
1118       arg_count++;
1119       user_args->count++;
1120     }
1121   return old_chain;
1122 }
1123
1124 /* Given character string P, return a point to the first argument ($arg),
1125    or NULL if P contains no arguments.  */
1126
1127 static char *
1128 locate_arg (p)
1129      char *p;
1130 {
1131   while ((p = strchr (p, '$')))
1132     {
1133       if (strncmp (p, "$arg", 4) == 0 && isdigit (p[4]))
1134         return p;
1135       p++;
1136     }
1137   return NULL;
1138 }
1139
1140 /* Insert the user defined arguments stored in user_arg into the $arg
1141    arguments found in line, with the updated copy being placed into nline.  */
1142
1143 static char *
1144 insert_args (line)
1145      char *line;
1146 {
1147   char *p, *save_line, *new_line;
1148   unsigned len, i;
1149
1150   /* First we need to know how much memory to allocate for the new line.  */
1151   save_line = line;
1152   len = 0;
1153   while ((p = locate_arg (line)))
1154     {
1155       len += p - line;
1156       i = p[4] - '0';
1157       
1158       if (i >= user_args->count)
1159         {
1160           error ("Missing argument %d in user function.\n", i);
1161           return NULL;
1162         }
1163       len += user_args->a[i].len;
1164       line = p + 5;
1165     }
1166
1167   /* Don't forget the tail.  */
1168   len += strlen (line);
1169
1170   /* Allocate space for the new line and fill it in.  */
1171   new_line = (char *)xmalloc (len + 1);
1172   if (new_line == NULL)
1173     return NULL;
1174
1175   /* Restore pointer to beginning of old line.  */
1176   line = save_line;
1177
1178   /* Save pointer to beginning of new line.  */
1179   save_line = new_line;
1180
1181   while ((p = locate_arg (line)))
1182     {
1183       int i, len;
1184
1185       memcpy (new_line, line, p - line);
1186       new_line += p - line;
1187       i = p[4] - '0';
1188
1189       len = user_args->a[i].len;
1190       if (len)
1191         {
1192           memcpy (new_line, user_args->a[i].arg, len);
1193           new_line += len;
1194         }
1195       line = p + 5;
1196     }
1197   /* Don't forget the tail.  */
1198   strcpy (new_line, line);
1199
1200   /* Return a pointer to the beginning of the new line.  */
1201   return save_line;
1202 }
1203
1204 void
1205 execute_user_command (c, args)
1206      struct cmd_list_element *c;
1207      char *args;
1208 {
1209   register struct command_line *cmdlines;
1210   struct cleanup *old_chain;
1211   enum command_control_type ret;
1212
1213   old_chain = setup_user_args (args);
1214
1215   cmdlines = c->user_commands;
1216   if (cmdlines == 0)
1217     /* Null command */
1218     return;
1219
1220   /* Set the instream to 0, indicating execution of a
1221      user-defined function.  */
1222   old_chain = make_cleanup ((make_cleanup_func) source_cleanup, instream);
1223   instream = (FILE *) 0;
1224   while (cmdlines)
1225     {
1226       ret = execute_control_command (cmdlines);
1227       if (ret != simple_control && ret != break_control)
1228         {
1229           warning ("Error in control structure.\n");
1230           break;
1231         }
1232       cmdlines = cmdlines->next;
1233     }
1234   do_cleanups (old_chain);
1235 }
1236
1237 /* Execute the line P as a command.
1238    Pass FROM_TTY as second argument to the defining function.  */
1239
1240 void
1241 execute_command (p, from_tty)
1242      char *p;
1243      int from_tty;
1244 {
1245   register struct cmd_list_element *c;
1246   register enum language flang;
1247   static int warned = 0;
1248   /* FIXME: These should really be in an appropriate header file */
1249   extern void serial_log_command PARAMS ((const char *));
1250
1251   free_all_values ();
1252
1253   /* Force cleanup of any alloca areas if using C alloca instead of
1254      a builtin alloca.  */
1255   alloca (0);
1256
1257   /* This can happen when command_line_input hits end of file.  */
1258   if (p == NULL)
1259       return;
1260
1261   serial_log_command (p);
1262
1263   while (*p == ' ' || *p == '\t') p++;
1264   if (*p)
1265     {
1266       char *arg;
1267
1268       c = lookup_cmd (&p, cmdlist, "", 0, 1);
1269       /* Pass null arg rather than an empty one.  */
1270       arg = *p ? p : 0;
1271
1272       /* Clear off trailing whitespace, except for set and complete command.  */
1273       if (arg && c->type != set_cmd && c->function.cfunc != complete_command)
1274         {
1275           p = arg + strlen (arg) - 1;
1276           while (p >= arg && (*p == ' ' || *p == '\t'))
1277             p--;
1278           *(p + 1) = '\0';
1279         }
1280
1281       /* If this command has been hooked, run the hook first. */
1282       if (c->hook)
1283         execute_user_command (c->hook, (char *)0);
1284
1285       if (c->class == class_user)
1286         execute_user_command (c, arg);
1287       else if (c->type == set_cmd || c->type == show_cmd)
1288         do_setshow_command (arg, from_tty & caution, c);
1289       else if (c->function.cfunc == NO_FUNCTION)
1290         error ("That is not a command, just a help topic.");
1291       else if (call_command_hook)
1292         call_command_hook (c, arg, from_tty & caution);
1293       else
1294         (*c->function.cfunc) (arg, from_tty & caution);
1295    }
1296
1297   /* Tell the user if the language has changed (except first time).  */
1298   if (current_language != expected_language)
1299   {
1300     if (language_mode == language_mode_auto) {
1301       language_info (1);        /* Print what changed.  */
1302     }
1303     warned = 0;
1304   }
1305
1306   /* Warn the user if the working language does not match the
1307      language of the current frame.  Only warn the user if we are
1308      actually running the program, i.e. there is a stack. */
1309   /* FIXME:  This should be cacheing the frame and only running when
1310      the frame changes.  */
1311
1312   if (target_has_stack)
1313     {
1314       flang = get_frame_language ();
1315       if (!warned
1316           && flang != language_unknown
1317           && flang != current_language->la_language)
1318         {
1319           printf_filtered ("%s\n", lang_frame_mismatch_warn);
1320           warned = 1;
1321         }
1322     }
1323 }
1324
1325 /* ARGSUSED */
1326 /* NOTE 1999-04-29: This function will be static again, once we modify
1327    gdb to use the event loop as the default command loop and we merge
1328    event-top.c into this file, top.c */
1329 /* static */ void
1330 command_loop_marker (foo)
1331      int foo;
1332 {
1333 }
1334
1335 /* Read commands from `instream' and execute them
1336    until end of file or error reading instream.  */
1337
1338 void
1339 command_loop ()
1340 {
1341   struct cleanup *old_chain;
1342   char *command;
1343   int stdin_is_tty = ISATTY (stdin);
1344   long time_at_cmd_start;
1345 #ifdef HAVE_SBRK
1346   long space_at_cmd_start = 0;
1347 #endif
1348   extern int display_time;
1349   extern int display_space;
1350
1351   while (instream && !feof (instream))
1352     {
1353 #if defined(TUI)
1354       extern int insert_mode;
1355 #endif
1356       if (window_hook && instream == stdin)
1357         (*window_hook) (instream, get_prompt ());
1358
1359       quit_flag = 0;
1360       if (instream == stdin && stdin_is_tty)
1361         reinitialize_more_filter ();
1362       old_chain = make_cleanup ((make_cleanup_func) command_loop_marker, 0);
1363
1364 #if defined(TUI)
1365       /* A bit of paranoia: I want to make sure the "insert_mode" global
1366        * is clear except when it is being used for command-line editing
1367        * (see tuiIO.c, utils.c); otherwise normal output will
1368        * get messed up in the TUI. So clear it before/after
1369        * the command-line-input call. - RT
1370        */
1371       insert_mode = 0;
1372 #endif
1373       /* Get a command-line. This calls the readline package. */
1374       command = command_line_input (instream == stdin ? 
1375                                     get_prompt () : (char *) NULL,
1376                                     instream == stdin, "prompt");
1377 #if defined(TUI)
1378       insert_mode = 0;
1379 #endif
1380       if (command == 0)
1381         return;
1382
1383       time_at_cmd_start = get_run_time ();
1384
1385       if (display_space)
1386         {
1387 #ifdef HAVE_SBRK
1388           extern char **environ;
1389           char *lim = (char *) sbrk (0);
1390
1391           space_at_cmd_start = (long) (lim - (char *) &environ);
1392 #endif
1393         }
1394
1395       execute_command (command, instream == stdin);
1396       /* Do any commands attached to breakpoint we stopped at.  */
1397       bpstat_do_actions (&stop_bpstat);
1398       do_cleanups (old_chain);
1399
1400       if (display_time)
1401         {
1402           long cmd_time = get_run_time () - time_at_cmd_start;
1403
1404           printf_unfiltered ("Command execution time: %ld.%06ld\n",
1405                              cmd_time / 1000000, cmd_time % 1000000);
1406         }
1407
1408       if (display_space)
1409         {
1410 #ifdef HAVE_SBRK
1411           extern char **environ;
1412           char *lim = (char *) sbrk (0);
1413           long space_now = lim - (char *) &environ;
1414           long space_diff = space_now - space_at_cmd_start;
1415
1416           printf_unfiltered ("Space used: %ld (%c%ld for this command)\n",
1417                              space_now,
1418                              (space_diff >= 0 ? '+' : '-'),
1419                              space_diff);
1420 #endif
1421         }
1422     }
1423 }
1424