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