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