]> Git Repo - binutils.git/blob - gdb/main.c
*** empty log message ***
[binutils.git] / gdb / main.c
1 /* Top level for GDB, the GNU debugger.
2    Copyright (C) 1986, 1987, 1988, 1989, 1990 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 #include <stdio.h>
21 int fclose ();
22 #include "defs.h"
23 #include "gdbcmd.h"
24 #include "param.h"
25 #include "symtab.h"
26 #include "inferior.h"
27 #include "signals.h"
28 #include "target.h"
29 #include "breakpoint.h"
30 #include "language.h"
31
32 #include "getopt.h"
33
34 /* readline include files */
35 #include "readline.h"
36 #include "history.h"
37
38 /* readline defines this.  */
39 #undef savestring
40
41 #ifdef USG
42 #include <sys/types.h>
43 #include <unistd.h>
44 #endif
45
46 #include <string.h>
47 #include <sys/file.h>
48 #include <setjmp.h>
49 #include <sys/param.h>
50 #include <sys/stat.h>
51 #include <ctype.h>
52
53 #ifdef SET_STACK_LIMIT_HUGE
54 #include <sys/time.h>
55 #include <sys/resource.h>
56
57 int original_stack_limit;
58 #endif
59
60
61 /* If this definition isn't overridden by the header files, assume
62    that isatty and fileno exist on this system.  */
63 #ifndef ISATTY
64 #define ISATTY(FP)      (isatty (fileno (FP)))
65 #endif
66
67 /* Initialization file name for gdb.  This is overridden in some configs.  */
68
69 #ifndef GDBINIT_FILENAME
70 #define GDBINIT_FILENAME        ".gdbinit"
71 #endif
72 char gdbinit[] = GDBINIT_FILENAME;
73
74 #define ALL_CLEANUPS    ((struct cleanup *)0)
75
76 /* Version number of GDB, as a string.  */
77
78 extern char *version;
79
80 /* Message to be printed before the error message, when an error occurs.  */
81
82 extern char *error_pre_print;
83
84 extern char lang_frame_mismatch_warn[];         /* language.c */
85
86 /* Flag for whether we want all the "from_tty" gubbish printed.  */
87
88 int caution = 1;                        /* Default is yes, sigh. */
89
90 /*
91  * Define all cmd_list_element's
92  */
93
94 /* Chain containing all defined commands.  */
95
96 struct cmd_list_element *cmdlist;
97
98 /* Chain containing all defined info subcommands.  */
99
100 struct cmd_list_element *infolist;
101
102 /* Chain containing all defined enable subcommands. */
103
104 struct cmd_list_element *enablelist;
105
106 /* Chain containing all defined disable subcommands. */
107
108 struct cmd_list_element *disablelist;
109
110 /* Chain containing all defined delete subcommands. */
111
112 struct cmd_list_element *deletelist;
113
114 /* Chain containing all defined "enable breakpoint" subcommands. */
115
116 struct cmd_list_element *enablebreaklist;
117
118 /* Chain containing all defined set subcommands */
119
120 struct cmd_list_element *setlist;
121
122 /* Chain containing all defined show subcommands.  */
123 struct cmd_list_element *showlist;
124
125 /* Chain containing all defined \"set history\".  */
126
127 struct cmd_list_element *sethistlist;
128
129 /* Chain containing all defined \"show history\".  */
130 struct cmd_list_element *showhistlist;
131
132 /* Chain containing all defined \"unset history\".  */
133
134 struct cmd_list_element *unsethistlist;
135
136 /* stdio stream that command input is being read from.  */
137
138 FILE *instream;
139
140 /* Current working directory.  */
141
142 char *current_directory;
143
144 /* The directory name is actually stored here (usually).  */
145 static char dirbuf[MAXPATHLEN];
146
147 /* Function to call before reading a command, if nonzero.
148    The function receives two args: an input stream,
149    and a prompt string.  */
150
151 void (*window_hook) ();
152
153 extern int frame_file_full_name;
154 int epoch_interface;
155 int xgdb_verbose;
156
157 /* The external commands we call... */
158 extern void init_source_path ();
159 extern void directory_command ();
160 extern void exec_file_command ();
161 extern void symbol_file_command ();
162 extern void core_file_command ();
163 extern void tty_command ();
164
165 extern void help_list ();
166 extern void initialize_all_files ();
167 extern void init_malloc ();
168
169 /* Forward declarations for this file */
170 void free_command_lines ();
171 char *gdb_readline ();
172 char *command_line_input ();
173 static void initialize_main ();
174 static void initialize_cmd_lists ();
175 static void init_signals ();
176 static void quit_command ();
177 void command_loop ();
178 static void source_command ();
179 static void print_gdb_version ();
180 static void print_gnu_advertisement ();
181 static void float_handler ();
182 static void cd_command ();
183 static void read_command_file ();
184
185 char *getenv ();
186
187 /* gdb prints this when reading a command interactively */
188 static char *prompt;
189
190 /* Buffer used for reading command lines, and the size
191    allocated for it so far.  */
192
193 char *line;
194 int linesize = 100;
195
196 /* Baud rate specified for talking to serial target systems.  Default
197    is left as a zero pointer, so targets can choose their own defaults.  */
198
199 char *baud_rate;
200
201 /* Signal to catch ^Z typed while reading a command: SIGTSTP or SIGCONT.  */
202
203 #ifndef STOP_SIGNAL
204 #ifdef SIGTSTP
205 #define STOP_SIGNAL SIGTSTP
206 #endif
207 #endif
208
209 /* Some System V have job control but not sigsetmask(). */
210 #if !defined (HAVE_SIGSETMASK)
211 #define HAVE_SIGSETMASK !defined (USG)
212 #endif
213
214 #if !HAVE_SIGSETMASK
215 #define sigsetmask(n)
216 #endif
217 \f
218 /* This is how `error' returns to command level.  */
219
220 jmp_buf to_top_level;
221
222 void
223 return_to_top_level ()
224 {
225   quit_flag = 0;
226   immediate_quit = 0;
227   bpstat_clear_actions(stop_bpstat);    /* Clear queued breakpoint commands */
228   clear_momentary_breakpoints ();
229   disable_current_display ();
230   do_cleanups (ALL_CLEANUPS);
231   longjmp (to_top_level, 1);
232 }
233
234 /* Call FUNC with arg ARGS, catching any errors.
235    If there is no error, return the value returned by FUNC.
236    If there is an error, print ERRSTRING, print the specific error message,
237                          then return zero.  */
238
239 int
240 catch_errors (func, args, errstring)
241      int (*func) ();
242      char *args;
243      char *errstring;
244 {
245   jmp_buf saved;
246   int val;
247   struct cleanup *saved_cleanup_chain;
248   char *saved_error_pre_print;
249
250   saved_cleanup_chain = save_cleanups ();
251   saved_error_pre_print = error_pre_print;
252
253   bcopy (to_top_level, saved, sizeof (jmp_buf));
254   error_pre_print = errstring;
255
256   if (setjmp (to_top_level) == 0)
257     val = (*func) (args);
258   else
259     val = 0;
260
261   restore_cleanups (saved_cleanup_chain);
262
263   error_pre_print = saved_error_pre_print;
264   bcopy (saved, to_top_level, sizeof (jmp_buf));
265   return val;
266 }
267
268 /* Handler for SIGHUP.  */
269
270 static void
271 disconnect ()
272 {
273   kill_inferior_fast ();
274   signal (SIGHUP, SIG_DFL);
275   kill (getpid (), SIGHUP);
276 }
277 \f
278 /* Clean up on error during a "source" command (or execution of a
279    user-defined command).  */
280
281 static void
282 source_cleanup (stream)
283      FILE *stream;
284 {
285   /* Restore the previous input stream.  */
286   instream = stream;
287 }
288
289 /* Read commands from STREAM.  */
290 static void
291 read_command_file (stream)
292      FILE *stream;
293 {
294   struct cleanup *cleanups;
295
296   cleanups = make_cleanup (source_cleanup, instream);
297   instream = stream;
298   command_loop ();
299   do_cleanups (cleanups);
300 }
301 \f
302 int
303 main (argc, argv)
304      int argc;
305      char **argv;
306 {
307   int count;
308   static int inhibit_gdbinit = 0;
309   static int quiet = 0;
310   static int batch = 0;
311
312   /* Pointers to various arguments from command line.  */
313   char *symarg = NULL;
314   char *execarg = NULL;
315   char *corearg = NULL;
316   char *cdarg = NULL;
317   char *ttyarg = NULL;
318
319   /* Pointers to all arguments of +command option.  */
320   char **cmdarg;
321   /* Allocated size of cmdarg.  */
322   int cmdsize;
323   /* Number of elements of cmdarg used.  */
324   int ncmd;
325
326   /* Indices of all arguments of +directory option.  */
327   char **dirarg;
328   /* Allocated size.  */
329   int dirsize;
330   /* Number of elements used.  */
331   int ndir;
332   
333   register int i;
334
335   /* This needs to happen before the first use of malloc.  */
336   init_malloc ();
337
338 #if defined (ALIGN_STACK_ON_STARTUP)
339   i = (int) &count & 0x3;
340   if (i != 0)
341     alloca (4 - i);
342 #endif
343
344   /* If error() is called from initialization code, just exit */
345   if (setjmp (to_top_level)) {
346     exit(1);
347   }
348
349   cmdsize = 1;
350   cmdarg = (char **) xmalloc (cmdsize * sizeof (*cmdarg));
351   ncmd = 0;
352   dirsize = 1;
353   dirarg = (char **) xmalloc (dirsize * sizeof (*dirarg));
354   ndir = 0;
355
356   quit_flag = 0;
357   line = (char *) xmalloc (linesize);
358   line[0] = '\0';               /* Terminate saved (now empty) cmd line */
359   instream = stdin;
360
361   getwd (dirbuf);
362   current_directory = dirbuf;
363
364 #ifdef SET_STACK_LIMIT_HUGE
365   {
366     struct rlimit rlim;
367
368     /* Set the stack limit huge so that alloca (particularly stringtab
369      * in dbxread.c) does not fail. */
370     getrlimit (RLIMIT_STACK, &rlim);
371     original_stack_limit = rlim.rlim_cur;
372     rlim.rlim_cur = rlim.rlim_max;
373     setrlimit (RLIMIT_STACK, &rlim);
374   }
375 #endif /* SET_STACK_LIMIT_HUGE */
376
377   /* Parse arguments and options.  */
378   {
379     int c;
380     static int print_help;
381     /* When var field is 0, use flag field to record the equivalent
382        short option (or arbitrary numbers starting at 10 for those
383        with no equivalent).  */
384     static struct option long_options[] =
385       {
386         {"quiet", 0, &quiet, 1},
387         {"nx", 0, &inhibit_gdbinit, 1},
388         {"batch", 0, &batch, 1},
389         {"epoch", 0, &epoch_interface, 1},
390         {"fullname", 0, &frame_file_full_name, 1},
391         {"help", 0, &print_help, 1},
392         {"se", 1, 0, 10},
393         {"symbols", 1, 0, 's'},
394         {"s", 1, 0, 's'},
395         {"exec", 1, 0, 'e'},
396         {"core", 1, 0, 'c'},
397         {"c", 1, 0, 'c'},
398         {"command", 1, 0, 'x'},
399         {"x", 1, 0, 'x'},
400         {"directory", 1, 0, 'd'},
401         {"cd", 1, 0, 11},
402         {"tty", 1, 0, 't'},
403         {"b", 1, 0, 'b'},
404 /* Allow machine descriptions to add more options... */
405 #ifdef ADDITIONAL_OPTIONS
406         ADDITIONAL_OPTIONS
407 #endif
408         {0, 0, 0, 0},
409       };
410
411     while (1)
412       {
413         c = getopt_long_only (argc, argv, "",
414                               long_options, &option_index);
415         if (c == EOF)
416           break;
417
418         /* Long option that takes an argument.  */
419         if (c == 0 && long_options[option_index].flag == 0)
420           c = long_options[option_index].val;
421
422         switch (c)
423           {
424           case 0:
425             /* Long option that just sets a flag.  */
426             break;
427           case 10:
428             symarg = optarg;
429             execarg = optarg;
430             break;
431           case 11:
432             cdarg = optarg;
433             break;
434           case 's':
435             symarg = optarg;
436             break;
437           case 'e':
438             execarg = optarg;
439             break;
440           case 'c':
441             corearg = optarg;
442             break;
443           case 'x':
444             cmdarg[ncmd++] = optarg;
445             if (ncmd >= cmdsize)
446               {
447                 cmdsize *= 2;
448                 cmdarg = (char **) xrealloc ((char *)cmdarg,
449                                              cmdsize * sizeof (*cmdarg));
450               }
451             break;
452           case 'd':
453             dirarg[ndir++] = optarg;
454             if (ndir >= dirsize)
455               {
456                 dirsize *= 2;
457                 dirarg = (char **) xrealloc ((char *)dirarg,
458                                              dirsize * sizeof (*dirarg));
459               }
460             break;
461           case 't':
462             ttyarg = optarg;
463             break;
464           case 'q':
465             quiet = 1;
466             break;
467           case 'b':
468             baud_rate = optarg;
469             break;
470 #ifdef ADDITIONAL_OPTION_CASES
471           ADDITIONAL_OPTION_CASES
472 #endif
473           case '?':
474             fprintf (stderr,
475                      "Use `%s +help' for a complete list of options.\n",
476                      argv[0]);
477             exit (1);
478           }
479
480       }
481     if (print_help)
482       {
483         fputs ("\
484 This is GDB, the GNU debugger.  Use the command\n\
485     gdb [options] [executable [core-file]]\n\
486 to enter the debugger.\n\
487 \n\
488 Options available are:\n\
489   -help             Print this message.\n\
490   -quiet            Do not print version number on startup.\n\
491   -fullname         Output information used by emacs-GDB interface.\n\
492   -epoch            Output information used by epoch emacs-GDB interface.\n\
493   -batch            Exit after processing options.\n\
494   -nx               Do not read .gdbinit file.\n\
495   -tty=TTY          Use TTY for input/output by the program being debugged.\n\
496   -cd=DIR           Change current directory to DIR.\n\
497   -directory=DIR    Search for source files in DIR.\n\
498   -command=FILE     Execute GDB commands from FILE.\n\
499   -symbols=SYMFILE  Read symbols from SYMFILE.\n\
500   -exec=EXECFILE    Use EXECFILE as the executable.\n\
501   -se=FILE          Use FILE as symbol file and executable file.\n\
502   -core=COREFILE    Analyze the core dump COREFILE.\n\
503   -b BAUDRATE       Set serial port baud rate used for remote debugging\n\
504 ", stderr);
505 #ifdef ADDITIONAL_OPTION_HELP
506         fputs (ADDITIONAL_OPTION_HELP, stderr);
507 #endif
508         fputs ("\n\
509 For more information, type \"help\" from within GDB, or consult the\n\
510 GDB manual (available as on-line info or a printed manual).\n", stderr);
511         /* Exiting after printing this message seems like
512            the most useful thing to do.  */
513         exit (0);
514       }
515     
516     /* OK, that's all the options.  The other arguments are filenames.  */
517     count = 0;
518     for (; optind < argc; optind++)
519       switch (++count)
520         {
521         case 1:
522           symarg = argv[optind];
523           execarg = argv[optind];
524           break;
525         case 2:
526           corearg = argv[optind];
527           break;
528         case 3:
529           fprintf (stderr,
530                    "Excess command line arguments ignored. (%s%s)\n",
531                    argv[optind], (optind == argc - 1) ? "" : " ...");
532           break;
533         }
534     if (batch)
535       quiet = 1;
536   }
537
538   /* Run the init function of each source file */
539
540   initialize_cmd_lists ();      /* This needs to be done first */
541   initialize_all_files ();
542   initialize_main ();           /* But that omits this file!  Do it now */
543   init_signals ();
544
545   if (!quiet)
546     {
547       /* Print all the junk at the top, with trailing "..." if we are about
548          to read a symbol file (possibly slowly).  */
549       print_gnu_advertisement ();
550       print_gdb_version ();
551       if (symarg)
552         printf_filtered ("..");
553       wrap_here("");
554       fflush (stdout);          /* Force to screen during slow operations */
555     }
556
557   error_pre_print = "\n\n";
558
559   /* Now perform all the actions indicated by the arguments.  */
560   if (cdarg != NULL)
561     {
562       if (!setjmp (to_top_level))
563         {
564           cd_command (cdarg, 0);
565           init_source_path ();
566         }
567     }
568   do_cleanups (ALL_CLEANUPS);
569
570   for (i = 0; i < ndir; i++)
571     if (!setjmp (to_top_level))
572       directory_command (dirarg[i], 0);
573   free (dirarg);
574   do_cleanups (ALL_CLEANUPS);
575
576   if (execarg != NULL
577       && symarg != NULL
578       && strcmp (execarg, symarg) == 0)
579     {
580       /* The exec file and the symbol-file are the same.  If we can't open
581          it, better only print one error message.  */
582       if (!setjmp (to_top_level))
583         {
584           exec_file_command (execarg, !batch);
585           symbol_file_command (symarg, 0);
586         }
587     }
588   else
589     {
590       if (execarg != NULL)
591         if (!setjmp (to_top_level))
592           exec_file_command (execarg, !batch);
593       if (symarg != NULL)
594         if (!setjmp (to_top_level))
595           symbol_file_command (symarg, 0);
596     }
597   do_cleanups (ALL_CLEANUPS);
598
599   /* After the symbol file has been read, print a newline to get us
600      beyond the copyright line...  But errors should still set off
601      the error message with a (single) blank line.  */
602   printf_filtered ("\n");
603   error_pre_print = "\n";
604
605   if (corearg != NULL)
606     if (!setjmp (to_top_level))
607       core_file_command (corearg, !batch);
608     else if (isdigit (corearg[0]) && !setjmp (to_top_level))
609       attach_command (corearg, !batch);
610   do_cleanups (ALL_CLEANUPS);
611
612   if (ttyarg != NULL)
613     if (!setjmp (to_top_level))
614       tty_command (ttyarg, !batch);
615   do_cleanups (ALL_CLEANUPS);
616
617 #ifdef ADDITIONAL_OPTION_HANDLER
618   ADDITIONAL_OPTION_HANDLER;
619 #endif
620
621   /* Error messages should no longer be distinguished with extra output. */
622   error_pre_print = 0;
623
624   {
625     struct stat homebuf, cwdbuf;
626     char *homedir, *homeinit;
627
628     /* Read init file, if it exists in home directory  */
629     homedir = getenv ("HOME");
630     if (homedir)
631       {
632         homeinit = (char *) alloca (strlen (getenv ("HOME")) +
633                                     strlen (gdbinit) + 10);
634         strcpy (homeinit, getenv ("HOME"));
635         strcat (homeinit, "/");
636         strcat (homeinit, gdbinit);
637         if (!inhibit_gdbinit && access (homeinit, R_OK) == 0)
638           if (!setjmp (to_top_level))
639             source_command (homeinit, 0);
640         do_cleanups (ALL_CLEANUPS);
641
642         /* Do stats; no need to do them elsewhere since we'll only
643            need them if homedir is set.  Make sure that they are
644            zero in case one of them fails (this guarantees that they
645            won't match if either exists).  */
646         
647         bzero (&homebuf, sizeof (struct stat));
648         bzero (&cwdbuf, sizeof (struct stat));
649         
650         stat (homeinit, &homebuf);
651         stat (gdbinit, &cwdbuf); /* We'll only need this if
652                                          homedir was set.  */
653       }
654     
655     /* Read the input file in the current directory, *if* it isn't
656        the same file (it should exist, also).  */
657
658     if (!homedir
659         || bcmp ((char *) &homebuf,
660                  (char *) &cwdbuf,
661                  sizeof (struct stat)))
662       if (!inhibit_gdbinit && access (gdbinit, R_OK) == 0)
663         if (!setjmp (to_top_level))
664           source_command (gdbinit, 0);
665         do_cleanups (ALL_CLEANUPS);
666   }
667
668   for (i = 0; i < ncmd; i++)
669     if (!setjmp (to_top_level))
670       {
671         if (cmdarg[i][0] == '-' && cmdarg[i][1] == '\0')
672           read_command_file (stdin);
673         else
674           source_command (cmdarg[i], !batch);
675         do_cleanups (ALL_CLEANUPS);
676       }
677   free (cmdarg);
678
679   if (batch)
680     {
681       /* We have hit the end of the batch file.  */
682       exit (0);
683     }
684
685   /* Do any host- or target-specific hacks.  This is used for i960 targets
686      to force the user to set a nindy target and spec its parameters.  */
687
688 #ifdef BEFORE_MAIN_LOOP_HOOK
689   BEFORE_MAIN_LOOP_HOOK;
690 #endif
691
692   /* The command loop.  */
693
694   while (1)
695     {
696       if (!setjmp (to_top_level))
697         {
698           do_cleanups (ALL_CLEANUPS);           /* Do complete cleanup */
699           command_loop ();
700           quit_command ((char *)0, instream == stdin);
701         }
702     }
703   /* No exit -- exit is through quit_command.  */
704 }
705
706 /* Execute the line P as a command.
707    Pass FROM_TTY as second argument to the defining function.  */
708
709 void
710 execute_command (p, from_tty)
711      char *p;
712      int from_tty;
713 {
714   register struct cmd_list_element *c;
715   register struct command_line *cmdlines;
716   register enum language flang;
717   static enum language current = language_unknown;
718   static int warned = 0;
719
720   free_all_values ();
721
722   /* This can happen when command_line_input hits end of file.  */
723   if (p == NULL)
724       return;
725   
726   while (*p == ' ' || *p == '\t') p++;
727   if (*p)
728     {
729       char *arg;
730       
731       c = lookup_cmd (&p, cmdlist, "", 0, 1);
732       /* Pass null arg rather than an empty one.  */
733       arg = *p ? p : 0;
734       if (c->class == class_user)
735         {
736           struct cleanup *old_chain;
737           
738           if (*p)
739             error ("User-defined commands cannot take arguments.");
740           cmdlines = c->user_commands;
741           if (cmdlines == 0)
742             /* Null command */
743             return;
744
745           /* Set the instream to 0, indicating execution of a
746              user-defined function.  */
747           old_chain =  make_cleanup (source_cleanup, instream);
748           instream = (FILE *) 0;
749           while (cmdlines)
750             {
751               execute_command (cmdlines->line, 0);
752               cmdlines = cmdlines->next;
753             }
754           do_cleanups (old_chain);
755         }
756       else if (c->type == set_cmd || c->type == show_cmd)
757         do_setshow_command (arg, from_tty & caution, c);
758       else if (c->function == NO_FUNCTION)
759         error ("That is not a command, just a help topic.");
760       else
761         (*c->function) (arg, from_tty & caution);
762    }
763
764   /* Tell the user if the language has changed */
765   if (working_lang != current)
766   {
767     if (language_mode == language_mode_auto) {
768       if (current != language_unknown)
769         language_info ();
770     }
771     current = working_lang;
772     warned = 0;
773   }
774
775   /* Warn the user if the working language does not match the
776      language of the current frame.  Only warn the user if we are
777      actually running the program, i.e. there is a stack. */
778   if (target_has_stack)
779   {
780     flang = get_frame_language();
781     if(!warned && flang != language_unknown && flang != working_lang)
782     {
783       printf_filtered ("%s\n", lang_frame_mismatch_warn);
784       warned = 1;
785     }
786   }
787 }
788
789 /* ARGSUSED */
790 void
791 command_loop_marker (foo)
792      int foo;
793 {
794 }
795
796 /* Read commands from `instream' and execute them
797    until end of file or error reading instream.  */
798 void
799 command_loop ()
800 {
801   struct cleanup *old_chain;
802   char *command;
803   int stdin_is_tty = ISATTY (stdin);
804
805   while (!feof (instream))
806     {
807       if (window_hook && instream == stdin)
808         (*window_hook) (instream, prompt);
809
810       quit_flag = 0;
811       if (instream == stdin && stdin_is_tty)
812         reinitialize_more_filter ();
813       old_chain = make_cleanup (command_loop_marker, 0);
814       command = command_line_input (instream == stdin ? prompt : 0,
815                                       instream == stdin);
816       if (command == 0)
817         return;
818       execute_command (command, instream == stdin);
819       /* Do any commands attached to breakpoint we stopped at.  */
820       bpstat_do_actions (&stop_bpstat);
821       do_cleanups (old_chain);
822     }
823 }
824 \f
825 /* Commands call this if they do not want to be repeated by null lines.  */
826
827 void
828 dont_repeat ()
829 {
830   /* If we aren't reading from standard input, we are saving the last
831      thing read from stdin in line and don't want to delete it.  Null lines
832      won't repeat here in any case.  */
833   if (instream == stdin)
834     *line = 0;
835 }
836 \f
837 /* Read a line from the stream "instream" without command line editing.
838
839    It prints PRROMPT once at the start.
840    Action is compatible with "readline", e.g. space for the result is 
841    malloc'd and should be freed by the caller.
842
843    A NULL return means end of file.  */
844 char *
845 gdb_readline (prrompt)
846      char *prrompt;
847 {
848   int c;
849   char *result;
850   int input_index = 0;
851   int result_size = 80;
852
853   if (prrompt)
854     {
855       printf (prrompt);
856       fflush (stdout);
857     }
858   
859   result = (char *) xmalloc (result_size);
860
861   while (1)
862     {
863       /* Read from stdin if we are executing a user defined command.
864          This is the right thing for prompt_for_continue, at least.  */
865       c = fgetc (instream ? instream : stdin);
866
867       if (c == EOF)
868         {
869           free (result);
870           return NULL;
871         }
872
873       if (c == '\n')
874         break;
875
876       result[input_index++] = c;
877       while (input_index >= result_size)
878         {
879           result_size *= 2;
880           result = (char *) xrealloc (result, result_size);
881         }
882     }
883
884   result[input_index++] = '\0';
885   return result;
886 }
887
888 /* Declaration for fancy readline with command line editing.  */
889 char *readline ();
890
891 /* Variables which control command line editing and history
892    substitution.  These variables are given default values at the end
893    of this file.  */
894 static int command_editing_p;
895 static int history_expansion_p;
896 static int write_history_p;
897 static int history_size;
898 static char *history_filename;
899
900 /* Variables which are necessary for fancy command line editing.  */
901 char *gdb_completer_word_break_characters =
902   " \t\n!@#$%^&*()-+=|~`}{[]\"';:?/>.<,";
903
904 /* Functions that are used as part of the fancy command line editing.  */
905
906 /* This can be used for functions which don't want to complete on symbols
907    but don't want to complete on anything else either.  */
908 /* ARGSUSED */
909 char **
910 noop_completer (text)
911      char *text;
912 {
913   return NULL;
914 }
915
916 /* Generate symbol names one by one for the completer.  If STATE is
917    zero, then we need to initialize, otherwise the initialization has
918    already taken place.  TEXT is what we expect the symbol to start
919    with.  RL_LINE_BUFFER is available to be looked at; it contains the
920    entire text of the line.  RL_POINT is the offset in that line of
921    the cursor.  You should pretend that the line ends at RL_POINT.
922    The result is NULL if there are no more completions, else a char
923    string which is a possible completion.  */
924 char *
925 symbol_completion_function (text, state)
926      char *text;
927      int state;
928 {
929   static char **list = (char **)NULL;
930   static int index;
931   char *output;
932   extern char *rl_line_buffer;
933   extern int rl_point;
934   char *tmp_command, *p;
935   struct cmd_list_element *c, *result_list;
936
937   if (!state)
938     {
939       /* Free the storage used by LIST, but not by the strings inside.  This is
940          because rl_complete_internal () frees the strings. */
941       if (list)
942         free (list);
943       list = 0;
944       index = 0;
945
946       /* Decide whether to complete on a list of gdb commands or on
947          symbols.  */
948       tmp_command = (char *) alloca (rl_point + 1);
949       p = tmp_command;
950       
951       strncpy (tmp_command, rl_line_buffer, rl_point);
952       tmp_command[rl_point] = '\0';
953
954       if (rl_point == 0)
955         {
956           /* An empty line we want to consider ambiguous; that is,
957              it could be any command.  */
958           c = (struct cmd_list_element *) -1;
959           result_list = 0;
960         }
961       else
962         c = lookup_cmd_1 (&p, cmdlist, &result_list, 1);
963
964       /* Move p up to the next interesting thing.  */
965       while (*p == ' ' || *p == '\t')
966         p++;
967
968       if (!c)
969         /* He's typed something unrecognizable.  Sigh.  */
970         list = (char **) 0;
971       else if (c == (struct cmd_list_element *) -1)
972         {
973           /* If we didn't recognize everything up to the thing that
974              needs completing, and we don't know what command it is
975              yet, we are in trouble.  Part of the trouble might be
976              that the list of delimiters used by readline includes
977              '-', which we use in commands.  Check for this.  */
978           if (p + strlen(text) != tmp_command + rl_point) {
979             if (tmp_command[rl_point - strlen(text) - 1] == '-')
980               text = p;
981             else {
982               /* This really should not produce an error.  Better would
983                  be to pretend to hit RETURN here; this would produce a
984                  response like "Ambiguous command: foo, foobar, etc",
985                  and leave the line available for re-entry with ^P.  Instead,
986                  this error blows away the user's typed input without
987                  any way to get it back.  */
988               error ("  Unrecognized command.");
989             }
990           }
991           
992           /* He's typed something ambiguous.  This is easier.  */
993           if (result_list)
994             list = complete_on_cmdlist (*result_list->prefixlist, text);
995           else
996             list = complete_on_cmdlist (cmdlist, text);
997         }
998       else
999         {
1000           /* If we've gotten this far, gdb has recognized a full
1001              command.  There are several possibilities:
1002
1003              1) We need to complete on the command.
1004              2) We need to complete on the possibilities coming after
1005              the command.
1006              2) We need to complete the text of what comes after the
1007              command.   */
1008
1009           if (!*p && *text)
1010             /* Always (might be longer versions of thie command).  */
1011             list = complete_on_cmdlist (result_list, text);
1012           else if (!*p && !*text)
1013             {
1014               if (c->prefixlist)
1015                 list = complete_on_cmdlist (*c->prefixlist, "");
1016               else
1017                 list = (*c->completer) ("");
1018             }
1019           else
1020             {
1021               if (c->prefixlist && !c->allow_unknown)
1022                 {
1023 #if 0
1024                   /* Something like "info adsfkdj".  But error() is not
1025                      the proper response; just return no completions
1026                      instead.  */
1027                   *p = '\0';
1028                   error ("\"%s\" command requires a subcommand.",
1029                          tmp_command);
1030 #else
1031                   list = NULL;
1032 #endif
1033                 }
1034               else
1035                 list = (*c->completer) (text);
1036             }
1037         }
1038     }
1039
1040   /* If the debugged program wasn't compiled with symbols, or if we're
1041      clearly completing on a command and no command matches, return
1042      NULL.  */
1043   if (!list)
1044     return ((char *)NULL);
1045
1046   output = list[index];
1047   if (output)
1048     index++;
1049
1050   return (output);
1051 }
1052 \f
1053 #ifdef STOP_SIGNAL
1054 static void
1055 stop_sig ()
1056 {
1057 #if STOP_SIGNAL == SIGTSTP
1058   signal (SIGTSTP, SIG_DFL);
1059   sigsetmask (0);
1060   kill (getpid (), SIGTSTP);
1061   signal (SIGTSTP, stop_sig);
1062 #else
1063   signal (STOP_SIGNAL, stop_sig);
1064 #endif
1065   printf ("%s", prompt);
1066   fflush (stdout);
1067
1068   /* Forget about any previous command -- null line now will do nothing.  */
1069   dont_repeat ();
1070 }
1071 #endif /* STOP_SIGNAL */
1072
1073 /* Initialize signal handlers. */
1074 static void
1075 do_nothing ()
1076 {
1077 }
1078
1079 static void
1080 init_signals ()
1081 {
1082   extern void request_quit ();
1083
1084   signal (SIGINT, request_quit);
1085
1086   /* If we initialize SIGQUIT to SIG_IGN, then the SIG_IGN will get
1087      passed to the inferior, which we don't want.  It would be
1088      possible to do a "signal (SIGQUIT, SIG_DFL)" after we fork, but
1089      on BSD4.3 systems using vfork, that can affect the
1090      GDB process as well as the inferior (the signal handling tables
1091      might be in memory, shared between the two).  Since we establish
1092      a handler for SIGQUIT, when we call exec it will set the signal
1093      to SIG_DFL for us.  */
1094   signal (SIGQUIT, do_nothing);
1095   if (signal (SIGHUP, do_nothing) != SIG_IGN)
1096     signal (SIGHUP, disconnect);
1097   signal (SIGFPE, float_handler);
1098 }
1099 \f
1100 /* Read one line from the command input stream `instream'
1101    into the local static buffer `linebuffer' (whose current length
1102    is `linelength').
1103    The buffer is made bigger as necessary.
1104    Returns the address of the start of the line.
1105
1106    NULL is returned for end of file.
1107
1108    *If* the instream == stdin & stdin is a terminal, the line read
1109    is copied into the file line saver (global var char *line,
1110    length linesize) so that it can be duplicated.
1111
1112    This routine either uses fancy command line editing or
1113    simple input as the user has requested.  */
1114
1115 char *
1116 command_line_input (prrompt, repeat)
1117      char *prrompt;
1118      int repeat;
1119 {
1120   static char *linebuffer = 0;
1121   static int linelength = 0;
1122   register char *p;
1123   char *p1;
1124   char *rl;
1125   char *local_prompt = prrompt;
1126   register int c;
1127   char *nline;
1128   char got_eof = 0;
1129
1130   if (linebuffer == 0)
1131     {
1132       linelength = 80;
1133       linebuffer = (char *) xmalloc (linelength);
1134     }
1135
1136   p = linebuffer;
1137
1138   /* Control-C quits instantly if typed while in this loop
1139      since it should not wait until the user types a newline.  */
1140   immediate_quit++;
1141 #ifdef STOP_SIGNAL
1142   signal (STOP_SIGNAL, stop_sig);
1143 #endif
1144
1145   while (1)
1146     {
1147       /* Reports are that some Sys V's don't flush stdout/err on reads
1148          from stdin, when stdin/out are sockets rather than ttys.  So we
1149          have to do it ourselves, to make emacs-gdb and xxgdb work.
1150          On other machines, doing this once per input should be a cheap nop.  */
1151       fflush (stdout);
1152       fflush (stderr);
1153
1154       /* Don't use fancy stuff if not talking to stdin.  */
1155       if (command_editing_p && instream == stdin
1156           && ISATTY (instream))
1157         rl = readline (local_prompt);
1158       else
1159         rl = gdb_readline (local_prompt);
1160
1161       if (!rl || rl == (char *) EOF)
1162         {
1163           got_eof = 1;
1164           break;
1165         }
1166       if (strlen(rl) + 1 + (p - linebuffer) > linelength)
1167         {
1168           linelength = strlen(rl) + 1 + (p - linebuffer);
1169           nline = (char *) xrealloc (linebuffer, linelength);
1170           p += nline - linebuffer;
1171           linebuffer = nline;
1172         }
1173       p1 = rl;
1174       /* Copy line.  Don't copy null at end.  (Leaves line alone
1175          if this was just a newline)  */
1176       while (*p1)
1177         *p++ = *p1++;
1178
1179       free (rl);                        /* Allocated in readline.  */
1180
1181       if (p == linebuffer || *(p - 1) != '\\')
1182         break;
1183
1184       p--;                      /* Put on top of '\'.  */
1185       local_prompt = (char *) 0;
1186   }
1187
1188 #ifdef STOP_SIGNAL
1189   signal (SIGTSTP, SIG_DFL);
1190 #endif
1191   immediate_quit--;
1192
1193   if (got_eof)
1194     return NULL;
1195
1196   /* Do history expansion if that is wished.  */
1197   if (history_expansion_p && instream == stdin
1198       && ISATTY (instream))
1199     {
1200       char *history_value;
1201       int expanded;
1202
1203       *p = '\0';                /* Insert null now.  */
1204       expanded = history_expand (linebuffer, &history_value);
1205       if (expanded)
1206         {
1207           /* Print the changes.  */
1208           printf ("%s\n", history_value);
1209
1210           /* If there was an error, call this function again.  */
1211           if (expanded < 0)
1212             {
1213               free (history_value);
1214               return command_line_input (prrompt, repeat);
1215             }
1216           if (strlen (history_value) > linelength)
1217             {
1218               linelength = strlen (history_value) + 1;
1219               linebuffer = (char *) xrealloc (linebuffer, linelength);
1220             }
1221           strcpy (linebuffer, history_value);
1222           p = linebuffer + strlen(linebuffer);
1223           free (history_value);
1224         }
1225     }
1226
1227   /* If we just got an empty line, and that is supposed
1228      to repeat the previous command, return the value in the
1229      global buffer.  */
1230   if (repeat)
1231     {
1232       if (p == linebuffer)
1233         return line;
1234       p1 = linebuffer;
1235       while (*p1 == ' ' || *p1 == '\t')
1236         p1++;
1237       if (!*p1)
1238         return line;
1239     }
1240
1241   *p = 0;
1242
1243   /* Add line to history if appropriate.  */
1244   if (instream == stdin
1245       && ISATTY (stdin) && *linebuffer)
1246     add_history (linebuffer);
1247
1248   /* Note: lines consisting soley of comments are added to the command
1249      history.  This is useful when you type a command, and then
1250      realize you don't want to execute it quite yet.  You can comment
1251      out the command and then later fetch it from the value history
1252      and remove the '#'.  The kill ring is probably better, but some
1253      people are in the habit of commenting things out.  */
1254   p1 = linebuffer;
1255   while ((c = *p1++) != '\0')
1256     {
1257       if (c == '"')
1258         while ((c = *p1++) != '"')
1259           {
1260             /* Make sure an escaped '"' doesn't make us think the string
1261                is ended.  */
1262             if (c == '\\')
1263               parse_escape (&p1);
1264             if (c == '\0')
1265               break;
1266           }
1267       else if (c == '\'')
1268         while ((c = *p1++) != '\'')
1269           {
1270             /* Make sure an escaped '\'' doesn't make us think the string
1271                is ended.  */
1272             if (c == '\\')
1273               parse_escape (&p1);
1274             if (c == '\0')
1275               break;
1276           }
1277       else if (c == '#')
1278         {
1279           /* Found a comment.  */
1280           p1[-1] = '\0';
1281           break;
1282         }
1283     }
1284
1285   /* Save into global buffer if appropriate.  */
1286   if (repeat)
1287     {
1288       if (linelength > linesize)
1289         {
1290           line = xrealloc (line, linelength);
1291           linesize = linelength;
1292         }
1293       strcpy (line, linebuffer);
1294       return line;
1295     }
1296
1297   return linebuffer;
1298 }
1299 \f
1300 /* Read lines from the input stream
1301    and accumulate them in a chain of struct command_line's
1302    which is then returned.  */
1303
1304 struct command_line *
1305 read_command_lines ()
1306 {
1307   struct command_line *first = 0;
1308   register struct command_line *next, *tail = 0;
1309   register char *p, *p1;
1310   struct cleanup *old_chain = 0;
1311
1312   while (1)
1313     {
1314       dont_repeat ();
1315       p = command_line_input (0, instream == stdin);
1316       if (p == NULL)
1317         /* Treat end of file like "end".  */
1318         break;
1319       
1320       /* Remove leading and trailing blanks.  */
1321       while (*p == ' ' || *p == '\t') p++;
1322       p1 = p + strlen (p);
1323       while (p1 != p && (p1[-1] == ' ' || p1[-1] == '\t')) p1--;
1324
1325       /* Is this "end"?  */
1326       if (p1 - p == 3 && !strncmp (p, "end", 3))
1327         break;
1328
1329       /* No => add this line to the chain of command lines.  */
1330       next = (struct command_line *) xmalloc (sizeof (struct command_line));
1331       next->line = savestring (p, p1 - p);
1332       next->next = 0;
1333       if (tail)
1334         {
1335           tail->next = next;
1336         }
1337       else
1338         {
1339           /* We just read the first line.
1340              From now on, arrange to throw away the lines we have
1341              if we quit or get an error while inside this function.  */
1342           first = next;
1343           old_chain = make_cleanup (free_command_lines, &first);
1344         }
1345       tail = next;
1346     }
1347
1348   dont_repeat ();
1349
1350   /* Now we are about to return the chain to our caller,
1351      so freeing it becomes his responsibility.  */
1352   if (first)
1353     discard_cleanups (old_chain);
1354   return first;
1355 }
1356
1357 /* Free a chain of struct command_line's.  */
1358
1359 void
1360 free_command_lines (lptr)
1361       struct command_line **lptr;
1362 {
1363   register struct command_line *l = *lptr;
1364   register struct command_line *next;
1365
1366   while (l)
1367     {
1368       next = l->next;
1369       free (l->line);
1370       free (l);
1371       l = next;
1372     }
1373 }
1374 \f
1375 /* Add an element to the list of info subcommands.  */
1376
1377 void
1378 add_info (name, fun, doc)
1379      char *name;
1380      void (*fun) ();
1381      char *doc;
1382 {
1383   add_cmd (name, no_class, fun, doc, &infolist);
1384 }
1385
1386 /* Add an alias to the list of info subcommands.  */
1387
1388 void
1389 add_info_alias (name, oldname, abbrev_flag)
1390      char *name;
1391      char *oldname;
1392      int abbrev_flag;
1393 {
1394   add_alias_cmd (name, oldname, 0, abbrev_flag, &infolist);
1395 }
1396
1397 /* The "info" command is defined as a prefix, with allow_unknown = 0.
1398    Therefore, its own definition is called only for "info" with no args.  */
1399
1400 /* ARGSUSED */
1401 static void
1402 info_command (arg, from_tty)
1403      char *arg;
1404      int from_tty;
1405 {
1406   printf ("\"info\" must be followed by the name of an info command.\n");
1407   help_list (infolist, "info ", -1, stdout);
1408 }
1409
1410 /* The "show" command with no arguments shows all the settings.  */
1411
1412 /* ARGSUSED */
1413 static void
1414 show_command (arg, from_tty)
1415      char *arg;
1416      int from_tty;
1417 {
1418   cmd_show_list (showlist, from_tty, "");
1419 }
1420 \f
1421 /* Add an element to the list of commands.  */
1422
1423 void
1424 add_com (name, class, fun, doc)
1425      char *name;
1426      enum command_class class;
1427      void (*fun) ();
1428      char *doc;
1429 {
1430   add_cmd (name, class, fun, doc, &cmdlist);
1431 }
1432
1433 /* Add an alias or abbreviation command to the list of commands.  */
1434
1435 void
1436 add_com_alias (name, oldname, class, abbrev_flag)
1437      char *name;
1438      char *oldname;
1439      enum command_class class;
1440      int abbrev_flag;
1441 {
1442   add_alias_cmd (name, oldname, class, abbrev_flag, &cmdlist);
1443 }
1444
1445 void
1446 error_no_arg (why)
1447      char *why;
1448 {
1449   error ("Argument required (%s).", why);
1450 }
1451
1452 /* ARGSUSED */
1453 static void
1454 help_command (command, from_tty)
1455      char *command;
1456      int from_tty; /* Ignored */
1457 {
1458   help_cmd (command, stdout);
1459 }
1460 \f
1461 static void
1462 validate_comname (comname)
1463      char *comname;
1464 {
1465   register char *p;
1466
1467   if (comname == 0)
1468     error_no_arg ("name of command to define");
1469
1470   p = comname;
1471   while (*p)
1472     {
1473       if (!(*p >= 'A' && *p <= 'Z')
1474           && !(*p >= 'a' && *p <= 'z')
1475           && !(*p >= '0' && *p <= '9')
1476           && *p != '-')
1477         error ("Junk in argument list: \"%s\"", p);
1478       p++;
1479     }
1480 }
1481
1482 static void
1483 define_command (comname, from_tty)
1484      char *comname;
1485      int from_tty;
1486 {
1487   register struct command_line *cmds;
1488   register struct cmd_list_element *c, *newc;
1489   char *tem = comname;
1490   extern void not_just_help_class_command ();
1491
1492   validate_comname (comname);
1493
1494   c = lookup_cmd (&tem, cmdlist, "", -1, 1);
1495   if (c)
1496     {
1497       if (c->class == class_user || c->class == class_alias)
1498         tem = "Redefine command \"%s\"? ";
1499       else
1500         tem = "Really redefine built-in command \"%s\"? ";
1501       if (!query (tem, comname))
1502         error ("Command \"%s\" not redefined.", comname);
1503     }
1504
1505   if (from_tty)
1506     {
1507       printf ("Type commands for definition of \"%s\".\n\
1508 End with a line saying just \"end\".\n", comname);
1509       fflush (stdout);
1510     }
1511   comname = savestring (comname, strlen (comname));
1512
1513   cmds = read_command_lines ();
1514
1515   if (c && c->class == class_user)
1516     free_command_lines (&c->user_commands);
1517
1518   newc = add_cmd (comname, class_user, not_just_help_class_command,
1519            (c && c->class == class_user)
1520            ? c->doc : savestring ("User-defined.", 13), &cmdlist);
1521   newc->user_commands = cmds;
1522 }
1523
1524 static void
1525 document_command (comname, from_tty)
1526      char *comname;
1527      int from_tty;
1528 {
1529   struct command_line *doclines;
1530   register struct cmd_list_element *c;
1531   char *tem = comname;
1532
1533   validate_comname (comname);
1534
1535   c = lookup_cmd (&tem, cmdlist, "", 0, 1);
1536
1537   if (c->class != class_user)
1538     error ("Command \"%s\" is built-in.", comname);
1539
1540   if (from_tty)
1541     printf ("Type documentation for \"%s\".\n\
1542 End with a line saying just \"end\".\n", comname);
1543
1544   doclines = read_command_lines ();
1545
1546   if (c->doc) free (c->doc);
1547
1548   {
1549     register struct command_line *cl1;
1550     register int len = 0;
1551
1552     for (cl1 = doclines; cl1; cl1 = cl1->next)
1553       len += strlen (cl1->line) + 1;
1554
1555     c->doc = (char *) xmalloc (len + 1);
1556     *c->doc = 0;
1557
1558     for (cl1 = doclines; cl1; cl1 = cl1->next)
1559       {
1560         strcat (c->doc, cl1->line);
1561         if (cl1->next)
1562           strcat (c->doc, "\n");
1563       }
1564   }
1565
1566   free_command_lines (&doclines);
1567 }
1568 \f
1569 static void
1570 print_gnu_advertisement()
1571 {
1572     printf ("\
1573 GDB is free software and you are welcome to distribute copies of it\n\
1574  under certain conditions; type \"info copying\" to see the conditions.\n\
1575 There is absolutely no warranty for GDB; type \"info warranty\" for details.\n\
1576 ");
1577 }
1578
1579 static void
1580 print_gdb_version ()
1581 {
1582   printf_filtered ("\
1583 GDB %s, Copyright 1991 Free Software Foundation, Inc.",
1584           version);
1585 }
1586
1587 /* ARGSUSED */
1588 static void
1589 show_version (args, from_tty)
1590      char *args;
1591      int from_tty;
1592 {
1593   immediate_quit++;
1594   print_gnu_advertisement ();
1595   print_gdb_version ();
1596   printf_filtered ("\n");
1597   immediate_quit--;
1598 }
1599 \f
1600 /* xgdb calls this to reprint the usual GDB prompt.  */
1601
1602 void
1603 print_prompt ()
1604 {
1605   printf ("%s", prompt);
1606   fflush (stdout);
1607 }
1608 \f
1609 static void
1610 quit_command (args, from_tty)
1611      char *args;
1612      int from_tty;
1613 {
1614   if (inferior_pid != 0 && target_has_execution)
1615     {
1616       if (query ("The program is running.  Quit anyway? "))
1617         {
1618           target_kill (args, from_tty);
1619         }
1620       else
1621         error ("Not confirmed.");
1622     }
1623   /* Save the history information if it is appropriate to do so.  */
1624   if (write_history_p && history_filename)
1625     write_history (history_filename);
1626   exit (0);
1627 }
1628
1629 int
1630 input_from_terminal_p ()
1631 {
1632   return (instream == stdin) & caution;
1633 }
1634 \f
1635 /* ARGSUSED */
1636 static void
1637 pwd_command (args, from_tty)
1638      char *args;
1639      int from_tty;
1640 {
1641   if (args) error ("The \"pwd\" command does not take an argument: %s", args);
1642   getwd (dirbuf);
1643
1644   if (strcmp (dirbuf, current_directory))
1645     printf ("Working directory %s\n (canonically %s).\n",
1646             current_directory, dirbuf);
1647   else
1648     printf ("Working directory %s.\n", current_directory);
1649 }
1650
1651 static void
1652 cd_command (dir, from_tty)
1653      char *dir;
1654      int from_tty;
1655 {
1656   int len;
1657   int change;
1658
1659   /* If the new directory is absolute, repeat is a no-op; if relative,
1660      repeat might be useful but is more likely to be a mistake.  */
1661   dont_repeat ();
1662
1663   if (dir == 0)
1664     error_no_arg ("new working directory");
1665
1666   dir = tilde_expand (dir);
1667   make_cleanup (free, dir);
1668
1669   len = strlen (dir);
1670   dir = savestring (dir, len - (len > 1 && dir[len-1] == '/'));
1671   if (dir[0] == '/')
1672     current_directory = dir;
1673   else
1674     {
1675       current_directory = concat (current_directory, "/", dir);
1676       free (dir);
1677     }
1678
1679   /* Now simplify any occurrences of `.' and `..' in the pathname.  */
1680
1681   change = 1;
1682   while (change)
1683     {
1684       char *p;
1685       change = 0;
1686
1687       for (p = current_directory; *p;)
1688         {
1689           if (!strncmp (p, "/./", 2)
1690               && (p[2] == 0 || p[2] == '/'))
1691             strcpy (p, p + 2);
1692           else if (!strncmp (p, "/..", 3)
1693                    && (p[3] == 0 || p[3] == '/')
1694                    && p != current_directory)
1695             {
1696               char *q = p;
1697               while (q != current_directory && q[-1] != '/') q--;
1698               if (q != current_directory)
1699                 {
1700                   strcpy (q-1, p+3);
1701                   p = q-1;
1702                 }
1703             }
1704           else p++;
1705         }
1706     }
1707
1708   if (chdir (dir) < 0)
1709     perror_with_name (dir);
1710
1711   forget_cached_source_info ();
1712
1713   if (from_tty)
1714     pwd_command ((char *) 0, 1);
1715 }
1716 \f
1717 /* ARGSUSED */
1718 static void
1719 source_command (args, from_tty)
1720      char *args;
1721      int from_tty;
1722 {
1723   FILE *stream;
1724   struct cleanup *cleanups;
1725   char *file = args;
1726
1727   if (file == 0)
1728     /* Let source without arguments read .gdbinit.  */
1729     file = gdbinit;
1730
1731   file = tilde_expand (file);
1732   make_cleanup (free, file);
1733
1734   stream = fopen (file, "r");
1735   if (stream == 0)
1736     perror_with_name (file);
1737
1738   cleanups = make_cleanup (fclose, stream);
1739
1740   read_command_file (stream);
1741
1742   do_cleanups (cleanups);
1743 }
1744
1745 /* ARGSUSED */
1746 static void
1747 echo_command (text, from_tty)
1748      char *text;
1749      int from_tty;
1750 {
1751   char *p = text;
1752   register int c;
1753
1754   if (text)
1755     while (c = *p++)
1756       {
1757         if (c == '\\')
1758           {
1759             /* \ at end of argument is used after spaces
1760                so they won't be lost.  */
1761             if (*p == 0)
1762               return;
1763
1764             c = parse_escape (&p);
1765             if (c >= 0)
1766               fputc (c, stdout);
1767           }
1768         else
1769           fputc (c, stdout);
1770       }
1771   fflush (stdout);
1772 }
1773
1774 /* ARGSUSED */
1775 static void
1776 dump_me_command (args, from_tty)
1777      char *args;
1778      int from_tty;
1779 {
1780   if (query ("Should GDB dump core? "))
1781     {
1782       signal (SIGQUIT, SIG_DFL);
1783       kill (getpid (), SIGQUIT);
1784     }
1785 }
1786 \f
1787 /* Functions to manipulate command line editing control variables.  */
1788
1789 /* Number of commands to print in each call to show_commands.  */
1790 #define Hist_print 10
1791 static void
1792 show_commands (args, from_tty)
1793      char *args;
1794      int from_tty;
1795 {
1796   /* Index for history commands.  Relative to history_base.  */
1797   int offset;
1798
1799   /* Number of the history entry which we are planning to display next.
1800      Relative to history_base.  */
1801   static int num = 0;
1802
1803   /* The first command in the history which doesn't exist (i.e. one more
1804      than the number of the last command).  Relative to history_base.  */
1805   int hist_len;
1806
1807   struct _hist_entry *history_get();
1808   extern int history_base;
1809
1810 #if 0
1811   /* This is all reported by individual "show" commands.  */
1812   printf_filtered ("Interactive command editing is %s.\n",
1813           command_editing_p ? "on" : "off");
1814
1815   printf_filtered ("History expansion of command input is %s.\n",
1816           history_expansion_p ? "on" : "off");
1817   printf_filtered ("Writing of a history record upon exit is %s.\n",
1818           write_history_p ? "enabled" : "disabled");
1819   printf_filtered ("The size of the history list (number of stored commands) is %d.\n",
1820           history_size);
1821   printf_filtered ("The name of the history record is \"%s\".\n\n",
1822           history_filename ? history_filename : "");
1823 #endif /* 0 */
1824
1825   /* Print out some of the commands from the command history.  */
1826   /* First determine the length of the history list.  */
1827   hist_len = history_size;
1828   for (offset = 0; offset < history_size; offset++)
1829     {
1830       if (!history_get (history_base + offset))
1831         {
1832           hist_len = offset;
1833           break;
1834         }
1835     }
1836
1837   if (args)
1838     {
1839       if (args[0] == '+' && args[1] == '\0')
1840         /* "info editing +" should print from the stored position.  */
1841         ;
1842       else
1843         /* "info editing <exp>" should print around command number <exp>.  */
1844         num = (parse_and_eval_address (args) - history_base) - Hist_print / 2;
1845     }
1846   /* "info editing" means print the last Hist_print commands.  */
1847   else
1848     {
1849       num = hist_len - Hist_print;
1850     }
1851
1852   if (num < 0)
1853     num = 0;
1854
1855   /* If there are at least Hist_print commands, we want to display the last
1856      Hist_print rather than, say, the last 6.  */
1857   if (hist_len - num < Hist_print)
1858     {
1859       num = hist_len - Hist_print;
1860       if (num < 0)
1861         num = 0;
1862     }
1863
1864 #if 0
1865   /* No need for a header now that "info editing" only prints one thing.  */
1866   if (num == hist_len - Hist_print)
1867     printf_filtered ("The list of the last %d commands is:\n\n", Hist_print);
1868   else
1869     printf_filtered ("Some of the stored commands are:\n\n");
1870 #endif /* 0 */
1871
1872   for (offset = num; offset < num + Hist_print && offset < hist_len; offset++)
1873     {
1874       printf_filtered ("%5d  %s\n", history_base + offset,
1875               (history_get (history_base + offset))->line);
1876     }
1877
1878   /* The next command we want to display is the next one that we haven't
1879      displayed yet.  */
1880   num += Hist_print;
1881   
1882   /* If the user repeats this command with return, it should do what
1883      "info editing +" does.  This is unnecessary if arg is null,
1884      because "info editing +" is not useful after "info editing".  */
1885   if (from_tty && args)
1886     {
1887       args[0] = '+';
1888       args[1] = '\0';
1889     }
1890 }
1891
1892 /* Called by do_setshow_command.  */
1893 /* ARGSUSED */
1894 static void
1895 set_history_size_command (args, from_tty, c)
1896      char *args;
1897      int from_tty;
1898      struct cmd_list_element *c;
1899 {
1900   if (history_size == UINT_MAX)
1901     unstifle_history ();
1902   else
1903     stifle_history (history_size);
1904 }
1905
1906 /* ARGSUSED */
1907 static void
1908 set_history (args, from_tty)
1909      char *args;
1910      int from_tty;
1911 {
1912   printf ("\"set history\" must be followed by the name of a history subcommand.\n");
1913   help_list (sethistlist, "set history ", -1, stdout);
1914 }
1915
1916 /* ARGSUSED */
1917 static void
1918 show_history (args, from_tty)
1919      char *args;
1920      int from_tty;
1921 {
1922   cmd_show_list (showhistlist, from_tty, "");
1923 }
1924
1925 int info_verbose = 0;           /* Default verbose msgs off */
1926
1927 /* Called by do_setshow_command.  An elaborate joke.  */
1928 /* ARGSUSED */
1929 static void 
1930 set_verbose (args, from_tty, c)
1931      char *args;
1932      int from_tty;
1933      struct cmd_list_element *c;
1934 {
1935   char *cmdname = "verbose";
1936   struct cmd_list_element *showcmd;
1937   
1938   showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, 1);
1939
1940   if (info_verbose)
1941     {
1942       c->doc = "Set verbose printing of informational messages.";
1943       showcmd->doc = "Show verbose printing of informational messages.";
1944     }
1945   else
1946     {
1947       c->doc = "Set verbosity.";
1948       showcmd->doc = "Show verbosity.";
1949     }
1950 }
1951
1952 static void
1953 float_handler ()
1954 {
1955   /* This message is based on ANSI C, section 4.7.  Note that integer
1956      divide by zero causes this, so "float" is a misnomer.  */
1957   error ("Erroneous arithmetic operation.");
1958 }
1959
1960 /* Return whether we are running a batch file or from terminal.  */
1961 int
1962 batch_mode ()
1963 {
1964   return !(instream == stdin && ISATTY (stdin));
1965 }
1966
1967 \f
1968 static void
1969 initialize_cmd_lists ()
1970 {
1971   cmdlist = (struct cmd_list_element *) 0;
1972   infolist = (struct cmd_list_element *) 0;
1973   enablelist = (struct cmd_list_element *) 0;
1974   disablelist = (struct cmd_list_element *) 0;
1975   deletelist = (struct cmd_list_element *) 0;
1976   enablebreaklist = (struct cmd_list_element *) 0;
1977   setlist = (struct cmd_list_element *) 0;
1978   showlist = NULL;
1979   sethistlist = (struct cmd_list_element *) 0;
1980   showhistlist = NULL;
1981   unsethistlist = (struct cmd_list_element *) 0;
1982 }
1983
1984 static void
1985 initialize_main ()
1986 {
1987   struct cmd_list_element *c;
1988   
1989   char *tmpenv;
1990   
1991 #ifdef DEFAULT_PROMPT
1992   prompt = savestring (DEFAULT_PROMPT, strlen(DEFAULT_PROMPT));
1993 #else
1994   prompt = savestring ("(gdb) ", 6);
1995 #endif
1996
1997   /* Set the important stuff up for command editing.  */
1998   command_editing_p = 1;
1999   history_expansion_p = 0;
2000   write_history_p = 0;
2001   
2002   if (tmpenv = getenv ("HISTSIZE"))
2003     history_size = atoi (tmpenv);
2004   else
2005     history_size = 256;
2006
2007   stifle_history (history_size);
2008
2009   if (tmpenv = getenv ("GDBHISTFILE"))
2010     history_filename = savestring (tmpenv, strlen(tmpenv));
2011   else
2012     /* We include the current directory so that if the user changes
2013        directories the file written will be the same as the one
2014        that was read.  */
2015     history_filename = concat (current_directory, "/.gdb_history", "");
2016
2017   read_history (history_filename);
2018
2019   /* Setup important stuff for command line editing.  */
2020   rl_completion_entry_function = (int (*)()) symbol_completion_function;
2021   rl_completer_word_break_characters = gdb_completer_word_break_characters;
2022   rl_readline_name = "gdb";
2023
2024   /* Define the classes of commands.
2025      They will appear in the help list in the reverse of this order.  */
2026
2027   add_cmd ("obscure", class_obscure, NO_FUNCTION, "Obscure features.", &cmdlist);
2028   add_cmd ("aliases", class_alias, NO_FUNCTION, "Aliases of other commands.", &cmdlist);
2029   add_cmd ("user-defined", class_user, NO_FUNCTION, "User-defined commands.\n\
2030 The commands in this class are those defined by the user.\n\
2031 Use the \"define\" command to define a command.", &cmdlist);
2032   add_cmd ("support", class_support, NO_FUNCTION, "Support facilities.", &cmdlist);
2033   add_cmd ("status", class_info, NO_FUNCTION, "Status inquiries.", &cmdlist);
2034   add_cmd ("files", class_files, NO_FUNCTION, "Specifying and examining files.", &cmdlist);
2035   add_cmd ("breakpoints", class_breakpoint, NO_FUNCTION, "Making program stop at certain points.", &cmdlist);
2036   add_cmd ("data", class_vars, NO_FUNCTION, "Examining data.", &cmdlist);
2037   add_cmd ("stack", class_stack, NO_FUNCTION, "Examining the stack.\n\
2038 The stack is made up of stack frames.  Gdb assigns numbers to stack frames\n\
2039 counting from zero for the innermost (currently executing) frame.\n\n\
2040 At any time gdb identifies one frame as the \"selected\" frame.\n\
2041 Variable lookups are done with respect to the selected frame.\n\
2042 When the program being debugged stops, gdb selects the innermost frame.\n\
2043 The commands below can be used to select other frames by number or address.",
2044            &cmdlist);
2045   add_cmd ("running", class_run, NO_FUNCTION, "Running the program.", &cmdlist);
2046
2047   add_com ("pwd", class_files, pwd_command,
2048            "Print working directory.  This is used for your program as well.");
2049   add_com ("cd", class_files, cd_command,
2050            "Set working directory to DIR for debugger and program being debugged.\n\
2051 The change does not take effect for the program being debugged\n\
2052 until the next time it is started.");
2053
2054   add_show_from_set
2055     (add_set_cmd ("prompt", class_support, var_string, (char *)&prompt,
2056            "Set gdb's prompt",
2057            &setlist),
2058      &showlist);
2059   
2060   add_com ("echo", class_support, echo_command,
2061            "Print a constant string.  Give string as argument.\n\
2062 C escape sequences may be used in the argument.\n\
2063 No newline is added at the end of the argument;\n\
2064 use \"\\n\" if you want a newline to be printed.\n\
2065 Since leading and trailing whitespace are ignored in command arguments,\n\
2066 if you want to print some you must use \"\\\" before leading whitespace\n\
2067 to be printed or after trailing whitespace.");
2068   add_com ("document", class_support, document_command,
2069            "Document a user-defined command.\n\
2070 Give command name as argument.  Give documentation on following lines.\n\
2071 End with a line of just \"end\".");
2072   add_com ("define", class_support, define_command,
2073            "Define a new command name.  Command name is argument.\n\
2074 Definition appears on following lines, one command per line.\n\
2075 End with a line of just \"end\".\n\
2076 Use the \"document\" command to give documentation for the new command.\n\
2077 Commands defined in this way do not take arguments.");
2078
2079 #ifdef __STDC__
2080   add_com ("source", class_support, source_command,
2081            "Read commands from a file named FILE.\n\
2082 Note that the file \"" GDBINIT_FILENAME "\" is read automatically in this way\n\
2083 when gdb is started.");
2084 #else
2085   /* Punt file name, we can't help it easily.  */
2086   add_com ("source", class_support, source_command,
2087            "Read commands from a file named FILE.\n\
2088 Note that the file \".gdbinit\" is read automatically in this way\n\
2089 when gdb is started.");
2090 #endif
2091
2092   add_com ("quit", class_support, quit_command, "Exit gdb.");
2093   add_com ("help", class_support, help_command, "Print list of commands.");
2094   add_com_alias ("q", "quit", class_support, 1);
2095   add_com_alias ("h", "help", class_support, 1);
2096
2097
2098   c = add_set_cmd ("verbose", class_support, var_boolean, (char *)&info_verbose,
2099                    "Set ",
2100                    &setlist),
2101   add_show_from_set (c, &showlist);
2102   c->function = set_verbose;
2103   set_verbose (NULL, 0, c);
2104   
2105   add_com ("dump-me", class_obscure, dump_me_command,
2106            "Get fatal error; make debugger dump its core.");
2107
2108   add_show_from_set
2109     (add_set_cmd ("editing", class_support, var_boolean, (char *)&command_editing_p,
2110            "Set command line editing.\n\
2111 Use \"on\" to enable to enable the editing, and \"off\" to disable it.\n\
2112 Without an argument, command line editing is enabled.", &setlist),
2113      &showlist);
2114
2115   add_prefix_cmd ("history", class_support, set_history,
2116                   "Generic command for setting command history parameters.",
2117                   &sethistlist, "set history ", 0, &setlist);
2118   add_prefix_cmd ("history", class_support, show_history,
2119                   "Generic command for showing command history parameters.",
2120                   &showhistlist, "show history ", 0, &showlist);
2121
2122   add_show_from_set
2123     (add_set_cmd ("expansion", no_class, var_boolean, (char *)&history_expansion_p,
2124            "Set history expansion on command input.\n\
2125 Without an argument, history expansion is enabled.", &sethistlist),
2126      &showhistlist);
2127
2128   add_show_from_set
2129     (add_set_cmd ("save", no_class, var_boolean, (char *)&write_history_p,
2130            "Set saving of the history record on exit.\n\
2131 Use \"on\" to enable to enable the saving, and \"off\" to disable it.\n\
2132 Without an argument, saving is enabled.", &sethistlist),
2133      &showhistlist);
2134
2135   c = add_set_cmd ("size", no_class, var_uinteger, (char *)&history_size,
2136                    "Set the size of the command history, \n\
2137 ie. the number of previous commands to keep a record of.", &sethistlist);
2138   add_show_from_set (c, &showhistlist);
2139   c->function = set_history_size_command;
2140
2141   add_show_from_set
2142     (add_set_cmd ("filename", no_class, var_filename, (char *)&history_filename,
2143            "Set the filename in which to record the command history\n\
2144  (the list of previous commands of which a record is kept).", &sethistlist),
2145      &showhistlist);
2146
2147   add_show_from_set
2148     (add_set_cmd ("confirm", class_support, var_boolean,
2149                   (char *)&caution,
2150                   "Set whether to confirm potentially dangerous operations.",
2151                   &setlist),
2152      &showlist);
2153
2154   add_prefix_cmd ("info", class_info, info_command,
2155                   "Generic command for printing status.",
2156                   &infolist, "info ", 0, &cmdlist);
2157   add_com_alias ("i", "info", class_info, 1);
2158
2159   add_prefix_cmd ("show", class_info, show_command,
2160                   "Generic command for showing things set with \"set\".",
2161                   &showlist, "show ", 0, &cmdlist);
2162   /* Another way to get at the same thing.  */
2163   add_info ("set", show_command, "Show all GDB settings.");
2164
2165   add_cmd ("commands", no_class, show_commands, "Status of command editor.",
2166            &showlist);
2167
2168   add_cmd ("version", no_class, show_version,
2169            "Report what version of GDB this is.", &showlist);
2170 }
This page took 0.149655 seconds and 4 git commands to generate.