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