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