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