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