xref: /dragonfly/contrib/gdb-7/gdb/main.c (revision 89a89091)
1 /* Top level stuff for GDB, the GNU debugger.
2 
3    Copyright (C) 1986-2005, 2007-2012 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "defs.h"
21 #include "top.h"
22 #include "target.h"
23 #include "inferior.h"
24 #include "symfile.h"
25 #include "gdbcore.h"
26 
27 #include "exceptions.h"
28 #include "getopt.h"
29 
30 #include <sys/types.h>
31 #include "gdb_stat.h"
32 #include <ctype.h>
33 
34 #include "gdb_string.h"
35 #include "event-loop.h"
36 #include "ui-out.h"
37 
38 #include "interps.h"
39 #include "main.h"
40 #include "source.h"
41 #include "cli/cli-cmds.h"
42 #include "python/python.h"
43 #include "objfiles.h"
44 
45 /* The selected interpreter.  This will be used as a set command
46    variable, so it should always be malloc'ed - since
47    do_setshow_command will free it.  */
48 char *interpreter_p;
49 
50 /* Whether xdb commands will be handled.  */
51 int xdb_commands = 0;
52 
53 /* Whether dbx commands will be handled.  */
54 int dbx_commands = 0;
55 
56 /* System root path, used to find libraries etc.  */
57 char *gdb_sysroot = 0;
58 
59 /* GDB datadir, used to store data files.  */
60 char *gdb_datadir = 0;
61 
62 /* If gdb was configured with --with-python=/path,
63    the possibly relocated path to python's lib directory.  */
64 char *python_libdir = 0;
65 
66 struct ui_file *gdb_stdout;
67 struct ui_file *gdb_stderr;
68 struct ui_file *gdb_stdlog;
69 struct ui_file *gdb_stdin;
70 /* Target IO streams.  */
71 struct ui_file *gdb_stdtargin;
72 struct ui_file *gdb_stdtarg;
73 struct ui_file *gdb_stdtargerr;
74 
75 /* True if --batch or --batch-silent was seen.  */
76 int batch_flag = 0;
77 
78 /* Support for the --batch-silent option.  */
79 int batch_silent = 0;
80 
81 /* Support for --return-child-result option.
82    Set the default to -1 to return error in the case
83    that the program does not run or does not complete.  */
84 int return_child_result = 0;
85 int return_child_result_value = -1;
86 
87 /* Whether to enable writing into executable and core files.  */
88 extern int write_files;
89 
90 /* GDB as it has been invoked from the command line (i.e. argv[0]).  */
91 static char *gdb_program_name;
92 
93 /* DragonFly kgdb support */
94 int kernel_debugger;
95 
96 static void print_gdb_help (struct ui_file *);
97 
98 /* These two are used to set the external editor commands when gdb is
99    farming out files to be edited by another program.  */
100 
101 extern char *external_editor_command;
102 
103 /* Relocate a file or directory.  PROGNAME is the name by which gdb
104    was invoked (i.e., argv[0]).  INITIAL is the default value for the
105    file or directory.  FLAG is true if the value is relocatable, false
106    otherwise.  Returns a newly allocated string; this may return NULL
107    under the same conditions as make_relative_prefix.  */
108 
109 static char *
110 relocate_path (const char *progname, const char *initial, int flag)
111 {
112   if (flag)
113     return make_relative_prefix (progname, BINDIR, initial);
114   return xstrdup (initial);
115 }
116 
117 /* Like relocate_path, but specifically checks for a directory.
118    INITIAL is relocated according to the rules of relocate_path.  If
119    the result is a directory, it is used; otherwise, INITIAL is used.
120    The chosen directory is then canonicalized using lrealpath.  This
121    function always returns a newly-allocated string.  */
122 
123 char *
124 relocate_gdb_directory (const char *initial, int flag)
125 {
126   char *dir;
127 
128   dir = relocate_path (gdb_program_name, initial, flag);
129   if (dir)
130     {
131       struct stat s;
132 
133       if (stat (dir, &s) != 0 || !S_ISDIR (s.st_mode))
134 	{
135 	  xfree (dir);
136 	  dir = NULL;
137 	}
138     }
139   if (!dir)
140     dir = xstrdup (initial);
141 
142   /* Canonicalize the directory.  */
143   if (*dir)
144     {
145       char *canon_sysroot = lrealpath (dir);
146 
147       if (canon_sysroot)
148 	{
149 	  xfree (dir);
150 	  dir = canon_sysroot;
151 	}
152     }
153 
154   return dir;
155 }
156 
157 /* Compute the locations of init files that GDB should source and
158    return them in SYSTEM_GDBINIT, HOME_GDBINIT, LOCAL_GDBINIT.  If
159    there is no system gdbinit (resp. home gdbinit and local gdbinit)
160    to be loaded, then SYSTEM_GDBINIT (resp. HOME_GDBINIT and
161    LOCAL_GDBINIT) is set to NULL.  */
162 static void
163 get_init_files (char **system_gdbinit,
164 		char **home_gdbinit,
165 		char **local_gdbinit)
166 {
167   static char *sysgdbinit = NULL;
168   static char *homeinit = NULL;
169   static char *localinit = NULL;
170   static int initialized = 0;
171 
172   if (!initialized)
173     {
174       struct stat homebuf, cwdbuf, s;
175       char *homedir, *relocated_sysgdbinit;
176 
177       if (SYSTEM_GDBINIT[0])
178 	{
179 	  relocated_sysgdbinit = relocate_path (gdb_program_name,
180 						SYSTEM_GDBINIT,
181 						SYSTEM_GDBINIT_RELOCATABLE);
182 	  if (relocated_sysgdbinit && stat (relocated_sysgdbinit, &s) == 0)
183 	    sysgdbinit = relocated_sysgdbinit;
184 	  else
185 	    xfree (relocated_sysgdbinit);
186 	}
187 
188       homedir = getenv ("HOME");
189 
190       /* If the .gdbinit file in the current directory is the same as
191 	 the $HOME/.gdbinit file, it should not be sourced.  homebuf
192 	 and cwdbuf are used in that purpose.  Make sure that the stats
193 	 are zero in case one of them fails (this guarantees that they
194 	 won't match if either exists).  */
195 
196       memset (&homebuf, 0, sizeof (struct stat));
197       memset (&cwdbuf, 0, sizeof (struct stat));
198 
199       if (homedir)
200 	{
201 	  homeinit = xstrprintf ("%s/%s", homedir, gdbinit);
202 	  if (stat (homeinit, &homebuf) != 0)
203 	    {
204 	      xfree (homeinit);
205 	      homeinit = NULL;
206 	    }
207 	}
208 
209       if (stat (gdbinit, &cwdbuf) == 0)
210 	{
211 	  if (!homeinit
212 	      || memcmp ((char *) &homebuf, (char *) &cwdbuf,
213 			 sizeof (struct stat)))
214 	    localinit = gdbinit;
215 	}
216 
217       initialized = 1;
218     }
219 
220   *system_gdbinit = sysgdbinit;
221   *home_gdbinit = homeinit;
222   *local_gdbinit = localinit;
223 }
224 
225 /* Call command_loop.  If it happens to return, pass that through as a
226    non-zero return status.  */
227 
228 static int
229 captured_command_loop (void *data)
230 {
231   /* Top-level execution commands can be run on the background from
232      here on.  */
233   interpreter_async = 1;
234 
235   current_interp_command_loop ();
236   /* FIXME: cagney/1999-11-05: A correct command_loop() implementaton
237      would clean things up (restoring the cleanup chain) to the state
238      they were just prior to the call.  Technically, this means that
239      the do_cleanups() below is redundant.  Unfortunately, many FUNCs
240      are not that well behaved.  do_cleanups should either be replaced
241      with a do_cleanups call (to cover the problem) or an assertion
242      check to detect bad FUNCs code.  */
243   do_cleanups (ALL_CLEANUPS);
244   /* If the command_loop returned, normally (rather than threw an
245      error) we try to quit.  If the quit is aborted, catch_errors()
246      which called this catch the signal and restart the command
247      loop.  */
248   quit_command (NULL, instream == stdin);
249   return 1;
250 }
251 
252 static int
253 captured_main (void *data)
254 {
255   struct captured_main_args *context = data;
256   int argc = context->argc;
257   char **argv = context->argv;
258   static int quiet = 0;
259   static int set_args = 0;
260 
261   /* Pointers to various arguments from command line.  */
262   char *symarg = NULL;
263   char *execarg = NULL;
264   char *pidarg = NULL;
265   char *corearg = NULL;
266   char *pid_or_core_arg = NULL;
267   char *cdarg = NULL;
268   char *ttyarg = NULL;
269 
270   /* These are static so that we can take their address in an
271      initializer.  */
272   static int print_help;
273   static int print_version;
274 
275   /* Pointers to all arguments of --command option.  */
276   struct cmdarg {
277     enum {
278       CMDARG_FILE,
279       CMDARG_COMMAND
280     } type;
281     char *string;
282   } *cmdarg;
283   /* Allocated size of cmdarg.  */
284   int cmdsize;
285   /* Number of elements of cmdarg used.  */
286   int ncmd;
287 
288   /* Indices of all arguments of --directory option.  */
289   char **dirarg;
290   /* Allocated size.  */
291   int dirsize;
292   /* Number of elements used.  */
293   int ndir;
294 
295   /* gdb init files.  */
296   char *system_gdbinit;
297   char *home_gdbinit;
298   char *local_gdbinit;
299 
300   int i;
301   int save_auto_load;
302   struct objfile *objfile;
303 
304   struct cleanup *pre_stat_chain;
305 
306 #ifdef HAVE_SBRK
307   /* Set this before calling make_command_stats_cleanup.  */
308   lim_at_start = (char *) sbrk (0);
309 #endif
310 
311   pre_stat_chain = make_command_stats_cleanup (0);
312 
313 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
314   setlocale (LC_MESSAGES, "");
315 #endif
316 #if defined (HAVE_SETLOCALE)
317   setlocale (LC_CTYPE, "");
318 #endif
319   bindtextdomain (PACKAGE, LOCALEDIR);
320   textdomain (PACKAGE);
321 
322   cmdsize = 1;
323   cmdarg = (struct cmdarg *) xmalloc (cmdsize * sizeof (*cmdarg));
324   ncmd = 0;
325   dirsize = 1;
326   dirarg = (char **) xmalloc (dirsize * sizeof (*dirarg));
327   ndir = 0;
328 
329   quit_flag = 0;
330   saved_command_line = (char *) xmalloc (saved_command_line_size);
331   saved_command_line[0] = '\0';
332   instream = stdin;
333 
334   gdb_stdout = stdio_fileopen (stdout);
335   gdb_stderr = stdio_fileopen (stderr);
336   gdb_stdlog = gdb_stderr;	/* for moment */
337   gdb_stdtarg = gdb_stderr;	/* for moment */
338   gdb_stdin = stdio_fileopen (stdin);
339   gdb_stdtargerr = gdb_stderr;	/* for moment */
340   gdb_stdtargin = gdb_stdin;	/* for moment */
341 
342   gdb_program_name = xstrdup (argv[0]);
343 
344   if (! getcwd (gdb_dirbuf, sizeof (gdb_dirbuf)))
345     /* Don't use *_filtered or warning() (which relies on
346        current_target) until after initialize_all_files().  */
347     fprintf_unfiltered (gdb_stderr,
348 			_("%s: warning: error finding "
349 			  "working directory: %s\n"),
350                         argv[0], safe_strerror (errno));
351 
352   current_directory = gdb_dirbuf;
353 
354   /* Set the sysroot path.  */
355   gdb_sysroot = relocate_gdb_directory (TARGET_SYSTEM_ROOT,
356 					TARGET_SYSTEM_ROOT_RELOCATABLE);
357 
358   debug_file_directory = relocate_gdb_directory (DEBUGDIR,
359 						 DEBUGDIR_RELOCATABLE);
360 
361   gdb_datadir = relocate_gdb_directory (GDB_DATADIR,
362 					GDB_DATADIR_RELOCATABLE);
363 
364 #ifdef WITH_PYTHON_PATH
365   {
366     /* For later use in helping Python find itself.  */
367     char *tmp = concat (WITH_PYTHON_PATH, SLASH_STRING, "lib", NULL);
368 
369     python_libdir = relocate_gdb_directory (tmp, PYTHON_PATH_RELOCATABLE);
370     xfree (tmp);
371   }
372 #endif
373 
374 #ifdef RELOC_SRCDIR
375   add_substitute_path_rule (RELOC_SRCDIR,
376 			    make_relative_prefix (argv[0], BINDIR,
377 						  RELOC_SRCDIR));
378 #endif
379 
380   /* There will always be an interpreter.  Either the one passed into
381      this captured main, or one specified by the user at start up, or
382      the console.  Initialize the interpreter to the one requested by
383      the application.  */
384   interpreter_p = xstrdup (context->interpreter_p);
385 
386   /* Parse arguments and options.  */
387   {
388     int c;
389     /* When var field is 0, use flag field to record the equivalent
390        short option (or arbitrary numbers starting at 10 for those
391        with no equivalent).  */
392     enum {
393       OPT_SE = 10,
394       OPT_CD,
395       OPT_ANNOTATE,
396       OPT_STATISTICS,
397       OPT_TUI,
398       OPT_KGDB,
399       OPT_NOWINDOWS,
400       OPT_WINDOWS
401     };
402     static struct option long_options[] =
403     {
404       {"tui", no_argument, 0, OPT_TUI},
405       {"xdb", no_argument, &xdb_commands, 1},
406       {"dbx", no_argument, &dbx_commands, 1},
407       {"readnow", no_argument, &readnow_symbol_files, 1},
408       {"r", no_argument, &readnow_symbol_files, 1},
409       {"quiet", no_argument, &quiet, 1},
410       {"q", no_argument, &quiet, 1},
411       {"silent", no_argument, &quiet, 1},
412       {"nx", no_argument, &inhibit_gdbinit, 1},
413       {"n", no_argument, &inhibit_gdbinit, 1},
414       {"batch-silent", no_argument, 0, 'B'},
415       {"batch", no_argument, &batch_flag, 1},
416       {"epoch", no_argument, &epoch_interface, 1},
417 
418     /* This is a synonym for "--annotate=1".  --annotate is now
419        preferred, but keep this here for a long time because people
420        will be running emacses which use --fullname.  */
421       {"fullname", no_argument, 0, 'f'},
422       {"f", no_argument, 0, 'f'},
423 
424       {"kernel", no_argument, 0, OPT_KGDB},
425       {"annotate", required_argument, 0, OPT_ANNOTATE},
426       {"help", no_argument, &print_help, 1},
427       {"se", required_argument, 0, OPT_SE},
428       {"symbols", required_argument, 0, 's'},
429       {"s", required_argument, 0, 's'},
430       {"exec", required_argument, 0, 'e'},
431       {"e", required_argument, 0, 'e'},
432       {"core", required_argument, 0, 'c'},
433       {"c", required_argument, 0, 'c'},
434       {"pid", required_argument, 0, 'p'},
435       {"p", required_argument, 0, 'p'},
436       {"command", required_argument, 0, 'x'},
437       {"eval-command", required_argument, 0, 'X'},
438       {"version", no_argument, &print_version, 1},
439       {"x", required_argument, 0, 'x'},
440       {"ex", required_argument, 0, 'X'},
441 #ifdef GDBTK
442       {"tclcommand", required_argument, 0, 'z'},
443       {"enable-external-editor", no_argument, 0, 'y'},
444       {"editor-command", required_argument, 0, 'w'},
445 #endif
446       {"ui", required_argument, 0, 'i'},
447       {"interpreter", required_argument, 0, 'i'},
448       {"i", required_argument, 0, 'i'},
449       {"directory", required_argument, 0, 'd'},
450       {"d", required_argument, 0, 'd'},
451       {"data-directory", required_argument, 0, 'D'},
452       {"cd", required_argument, 0, OPT_CD},
453       {"tty", required_argument, 0, 't'},
454       {"baud", required_argument, 0, 'b'},
455       {"b", required_argument, 0, 'b'},
456       {"nw", no_argument, NULL, OPT_NOWINDOWS},
457       {"nowindows", no_argument, NULL, OPT_NOWINDOWS},
458       {"w", no_argument, NULL, OPT_WINDOWS},
459       {"windows", no_argument, NULL, OPT_WINDOWS},
460       {"statistics", no_argument, 0, OPT_STATISTICS},
461       {"write", no_argument, &write_files, 1},
462       {"args", no_argument, &set_args, 1},
463       {"l", required_argument, 0, 'l'},
464       {"return-child-result", no_argument, &return_child_result, 1},
465       {0, no_argument, 0, 0}
466     };
467 
468     while (1)
469       {
470 	int option_index;
471 
472 	c = getopt_long_only (argc, argv, "",
473 			      long_options, &option_index);
474 	if (c == EOF || set_args)
475 	  break;
476 
477 	/* Long option that takes an argument.  */
478 	if (c == 0 && long_options[option_index].flag == 0)
479 	  c = long_options[option_index].val;
480 
481 	switch (c)
482 	  {
483 	  case 0:
484 	    /* Long option that just sets a flag.  */
485 	    break;
486 	  case OPT_SE:
487 	    symarg = optarg;
488 	    execarg = optarg;
489 	    break;
490 	  case OPT_CD:
491 	    cdarg = optarg;
492 	    break;
493 	  case OPT_ANNOTATE:
494 	    /* FIXME: what if the syntax is wrong (e.g. not digits)?  */
495 	    annotation_level = atoi (optarg);
496 	    break;
497 	  case OPT_STATISTICS:
498 	    /* Enable the display of both time and space usage.  */
499 	    set_display_time (1);
500 	    set_display_space (1);
501 	    break;
502 	  case OPT_TUI:
503 	    /* --tui is equivalent to -i=tui.  */
504 #ifdef TUI
505 	    xfree (interpreter_p);
506 	    interpreter_p = xstrdup (INTERP_TUI);
507 #else
508 	    fprintf_unfiltered (gdb_stderr,
509 				_("%s: TUI mode is not supported\n"),
510 				argv[0]);
511 	    exit (1);
512 #endif
513 	    break;
514 	  case OPT_KGDB:
515 	    kernel_debugger = 1;
516 	    break;
517 	  case OPT_WINDOWS:
518 	    /* FIXME: cagney/2003-03-01: Not sure if this option is
519                actually useful, and if it is, what it should do.  */
520 #ifdef GDBTK
521 	    /* --windows is equivalent to -i=insight.  */
522 	    xfree (interpreter_p);
523 	    interpreter_p = xstrdup (INTERP_INSIGHT);
524 #endif
525 	    use_windows = 1;
526 	    break;
527 	  case OPT_NOWINDOWS:
528 	    /* -nw is equivalent to -i=console.  */
529 	    xfree (interpreter_p);
530 	    interpreter_p = xstrdup (INTERP_CONSOLE);
531 	    use_windows = 0;
532 	    break;
533 	  case 'f':
534 	    annotation_level = 1;
535 	    /* We have probably been invoked from emacs.  Disable
536 	       window interface.  */
537 	    use_windows = 0;
538 	    break;
539 	  case 's':
540 	    symarg = optarg;
541 	    break;
542 	  case 'e':
543 	    execarg = optarg;
544 	    break;
545 	  case 'c':
546 	    corearg = optarg;
547 	    break;
548 	  case 'p':
549 	    pidarg = optarg;
550 	    break;
551 	  case 'x':
552 	    cmdarg[ncmd].type = CMDARG_FILE;
553 	    cmdarg[ncmd++].string = optarg;
554 	    if (ncmd >= cmdsize)
555 	      {
556 		cmdsize *= 2;
557 		cmdarg = xrealloc ((char *) cmdarg,
558 				   cmdsize * sizeof (*cmdarg));
559 	      }
560 	    break;
561 	  case 'X':
562 	    cmdarg[ncmd].type = CMDARG_COMMAND;
563 	    cmdarg[ncmd++].string = optarg;
564 	    if (ncmd >= cmdsize)
565 	      {
566 		cmdsize *= 2;
567 		cmdarg = xrealloc ((char *) cmdarg,
568 				   cmdsize * sizeof (*cmdarg));
569 	      }
570 	    break;
571 	  case 'B':
572 	    batch_flag = batch_silent = 1;
573 	    gdb_stdout = ui_file_new();
574 	    break;
575 	  case 'D':
576 	    xfree (gdb_datadir);
577 	    gdb_datadir = xstrdup (optarg);
578 	    break;
579 #ifdef GDBTK
580 	  case 'z':
581 	    {
582 	      extern int gdbtk_test (char *);
583 
584 	      if (!gdbtk_test (optarg))
585 		{
586 		  fprintf_unfiltered (gdb_stderr,
587 				      _("%s: unable to load "
588 					"tclcommand file \"%s\""),
589 				      argv[0], optarg);
590 		  exit (1);
591 		}
592 	      break;
593 	    }
594 	  case 'y':
595 	    /* Backwards compatibility only.  */
596 	    break;
597 	  case 'w':
598 	    {
599 	      external_editor_command = xstrdup (optarg);
600 	      break;
601 	    }
602 #endif /* GDBTK */
603 	  case 'i':
604 	    xfree (interpreter_p);
605 	    interpreter_p = xstrdup (optarg);
606 	    break;
607 	  case 'd':
608 	    dirarg[ndir++] = optarg;
609 	    if (ndir >= dirsize)
610 	      {
611 		dirsize *= 2;
612 		dirarg = (char **) xrealloc ((char *) dirarg,
613 					     dirsize * sizeof (*dirarg));
614 	      }
615 	    break;
616 	  case 't':
617 	    ttyarg = optarg;
618 	    break;
619 	  case 'q':
620 	    quiet = 1;
621 	    break;
622 	  case 'b':
623 	    {
624 	      int i;
625 	      char *p;
626 
627 	      i = strtol (optarg, &p, 0);
628 	      if (i == 0 && p == optarg)
629 
630 		/* Don't use *_filtered or warning() (which relies on
631 		   current_target) until after initialize_all_files().  */
632 
633 		fprintf_unfiltered
634 		  (gdb_stderr,
635 		   _("warning: could not set baud rate to `%s'.\n"), optarg);
636 	      else
637 		baud_rate = i;
638 	    }
639             break;
640 	  case 'l':
641 	    {
642 	      int i;
643 	      char *p;
644 
645 	      i = strtol (optarg, &p, 0);
646 	      if (i == 0 && p == optarg)
647 
648 		/* Don't use *_filtered or warning() (which relies on
649 		   current_target) until after initialize_all_files().  */
650 
651 		fprintf_unfiltered (gdb_stderr,
652 				    _("warning: could not set "
653 				      "timeout limit to `%s'.\n"), optarg);
654 	      else
655 		remote_timeout = i;
656 	    }
657 	    break;
658 
659 	  case '?':
660 	    fprintf_unfiltered (gdb_stderr,
661 				_("Use `%s --help' for a "
662 				  "complete list of options.\n"),
663 				argv[0]);
664 	    exit (1);
665 	  }
666       }
667 
668     /* If --help or --version, disable window interface.  */
669     if (print_help || print_version)
670       {
671 	use_windows = 0;
672       }
673 
674     if (batch_flag)
675       quiet = 1;
676   }
677 
678   /* Initialize all files.  Give the interpreter a chance to take
679      control of the console via the deprecated_init_ui_hook ().  */
680   gdb_init (argv[0]);
681 
682   /* Now that gdb_init has created the initial inferior, we're in
683      position to set args for that inferior.  */
684   if (set_args)
685     {
686       /* The remaining options are the command-line options for the
687 	 inferior.  The first one is the sym/exec file, and the rest
688 	 are arguments.  */
689       if (optind >= argc)
690 	{
691 	  fprintf_unfiltered (gdb_stderr,
692 			      _("%s: `--args' specified but "
693 				"no program specified\n"),
694 			      argv[0]);
695 	  exit (1);
696 	}
697       symarg = argv[optind];
698       execarg = argv[optind];
699       ++optind;
700       set_inferior_args_vector (argc - optind, &argv[optind]);
701     }
702   else
703     {
704       /* OK, that's all the options.  */
705 
706       /* The first argument, if specified, is the name of the
707 	 executable.  */
708       if (optind < argc)
709 	{
710 	  symarg = argv[optind];
711 	  execarg = argv[optind];
712 	  optind++;
713 	}
714 
715       /* If the user hasn't already specified a PID or the name of a
716 	 core file, then a second optional argument is allowed.  If
717 	 present, this argument should be interpreted as either a
718 	 PID or a core file, whichever works.  */
719       if (pidarg == NULL && corearg == NULL && optind < argc)
720 	{
721 	  pid_or_core_arg = argv[optind];
722 	  optind++;
723 	}
724 
725       /* Any argument left on the command line is unexpected and
726 	 will be ignored.  Inform the user.  */
727       if (optind < argc)
728 	fprintf_unfiltered (gdb_stderr,
729 			    _("Excess command line "
730 			      "arguments ignored. (%s%s)\n"),
731 			    argv[optind],
732 			    (optind == argc - 1) ? "" : " ...");
733     }
734 
735   /* Lookup gdbinit files.  Note that the gdbinit file name may be
736      overriden during file initialization, so get_init_files should be
737      called after gdb_init.  */
738   get_init_files (&system_gdbinit, &home_gdbinit, &local_gdbinit);
739 
740   /* Do these (and anything which might call wrap_here or *_filtered)
741      after initialize_all_files() but before the interpreter has been
742      installed.  Otherwize the help/version messages will be eaten by
743      the interpreter's output handler.  */
744 
745   if (print_version)
746     {
747       print_gdb_version (gdb_stdout);
748       wrap_here ("");
749       printf_filtered ("\n");
750       exit (0);
751     }
752 
753   if (print_help)
754     {
755       print_gdb_help (gdb_stdout);
756       fputs_unfiltered ("\n", gdb_stdout);
757       exit (0);
758     }
759 
760   /* FIXME: cagney/2003-02-03: The big hack (part 1 of 2) that lets
761      GDB retain the old MI1 interpreter startup behavior.  Output the
762      copyright message before the interpreter is installed.  That way
763      it isn't encapsulated in MI output.  */
764   if (!quiet && strcmp (interpreter_p, INTERP_MI1) == 0)
765     {
766       /* Print all the junk at the top, with trailing "..." if we are
767          about to read a symbol file (possibly slowly).  */
768       print_gdb_version (gdb_stdout);
769       if (symarg)
770 	printf_filtered ("..");
771       wrap_here ("");
772       printf_filtered ("\n");
773       gdb_flush (gdb_stdout);	/* Force to screen during slow
774 				   operations.  */
775     }
776 
777   /* Install the default UI.  All the interpreters should have had a
778      look at things by now.  Initialize the default interpreter.  */
779 
780   {
781     /* Find it.  */
782     struct interp *interp = interp_lookup (interpreter_p);
783 
784     if (interp == NULL)
785       error (_("Interpreter `%s' unrecognized"), interpreter_p);
786     /* Install it.  */
787     if (!interp_set (interp, 1))
788       {
789         fprintf_unfiltered (gdb_stderr,
790 			    "Interpreter `%s' failed to initialize.\n",
791                             interpreter_p);
792         exit (1);
793       }
794   }
795 
796   /* FIXME: cagney/2003-02-03: The big hack (part 2 of 2) that lets
797      GDB retain the old MI1 interpreter startup behavior.  Output the
798      copyright message after the interpreter is installed when it is
799      any sane interpreter.  */
800   if (!quiet && !current_interp_named_p (INTERP_MI1))
801     {
802       /* Print all the junk at the top, with trailing "..." if we are
803          about to read a symbol file (possibly slowly).  */
804       print_gdb_version (gdb_stdout);
805       if (symarg)
806 	printf_filtered ("..");
807       wrap_here ("");
808       printf_filtered ("\n");
809       gdb_flush (gdb_stdout);	/* Force to screen during slow
810 				   operations.  */
811     }
812 
813   /* Set off error and warning messages with a blank line.  */
814   error_pre_print = "\n";
815   quit_pre_print = error_pre_print;
816   warning_pre_print = _("\nwarning: ");
817 
818   /* Read and execute the system-wide gdbinit file, if it exists.
819      This is done *before* all the command line arguments are
820      processed; it sets global parameters, which are independent of
821      what file you are debugging or what directory you are in.  */
822   if (system_gdbinit && !inhibit_gdbinit)
823     catch_command_errors (source_script, system_gdbinit, 0, RETURN_MASK_ALL);
824 
825   /* Read and execute $HOME/.gdbinit file, if it exists.  This is done
826      *before* all the command line arguments are processed; it sets
827      global parameters, which are independent of what file you are
828      debugging or what directory you are in.  */
829 
830   if (home_gdbinit && !inhibit_gdbinit)
831     catch_command_errors (source_script, home_gdbinit, 0, RETURN_MASK_ALL);
832 
833   /* Now perform all the actions indicated by the arguments.  */
834   if (cdarg != NULL)
835     {
836       catch_command_errors (cd_command, cdarg, 0, RETURN_MASK_ALL);
837     }
838 
839   for (i = 0; i < ndir; i++)
840     catch_command_errors (directory_switch, dirarg[i], 0, RETURN_MASK_ALL);
841   xfree (dirarg);
842 
843   /* Skip auto-loading section-specified scripts until we've sourced
844      local_gdbinit (which is often used to augment the source search
845      path).  */
846   save_auto_load = gdbpy_global_auto_load;
847   gdbpy_global_auto_load = 0;
848 
849   if (execarg != NULL
850       && symarg != NULL
851       && strcmp (execarg, symarg) == 0)
852     {
853       /* The exec file and the symbol-file are the same.  If we can't
854          open it, better only print one error message.
855          catch_command_errors returns non-zero on success!  */
856       if (catch_command_errors (exec_file_attach, execarg,
857 				!batch_flag, RETURN_MASK_ALL))
858 	catch_command_errors (symbol_file_add_main, symarg,
859 			      !batch_flag, RETURN_MASK_ALL);
860     }
861   else
862     {
863       if (execarg != NULL)
864 	catch_command_errors (exec_file_attach, execarg,
865 			      !batch_flag, RETURN_MASK_ALL);
866       if (symarg != NULL)
867 	catch_command_errors (symbol_file_add_main, symarg,
868 			      !batch_flag, RETURN_MASK_ALL);
869     }
870 
871   if (corearg && pidarg)
872     error (_("Can't attach to process and specify "
873 	     "a core file at the same time."));
874 
875   if (corearg != NULL)
876     catch_command_errors (core_file_command, corearg,
877 			  !batch_flag, RETURN_MASK_ALL);
878   else if (pidarg != NULL)
879     catch_command_errors (attach_command, pidarg,
880 			  !batch_flag, RETURN_MASK_ALL);
881   else if (pid_or_core_arg)
882     {
883       /* The user specified 'gdb program pid' or gdb program core'.
884 	 If pid_or_core_arg's first character is a digit, try attach
885 	 first and then corefile.  Otherwise try just corefile.  */
886 
887       if (isdigit (pid_or_core_arg[0]))
888 	{
889 	  if (catch_command_errors (attach_command, pid_or_core_arg,
890 				    !batch_flag, RETURN_MASK_ALL) == 0)
891 	    catch_command_errors (core_file_command, pid_or_core_arg,
892 				  !batch_flag, RETURN_MASK_ALL);
893 	}
894       else /* Can't be a pid, better be a corefile.  */
895 	catch_command_errors (core_file_command, pid_or_core_arg,
896 			      !batch_flag, RETURN_MASK_ALL);
897     }
898 
899   if (ttyarg != NULL)
900     set_inferior_io_terminal (ttyarg);
901 
902   /* Error messages should no longer be distinguished with extra output.  */
903   error_pre_print = NULL;
904   quit_pre_print = NULL;
905   warning_pre_print = _("warning: ");
906 
907   /* Read the .gdbinit file in the current directory, *if* it isn't
908      the same as the $HOME/.gdbinit file (it should exist, also).  */
909   if (local_gdbinit && !inhibit_gdbinit)
910     catch_command_errors (source_script, local_gdbinit, 0, RETURN_MASK_ALL);
911 
912   /* Now that all .gdbinit's have been read and all -d options have been
913      processed, we can read any scripts mentioned in SYMARG.
914      We wait until now because it is common to add to the source search
915      path in local_gdbinit.  */
916   gdbpy_global_auto_load = save_auto_load;
917   ALL_OBJFILES (objfile)
918     load_auto_scripts_for_objfile (objfile);
919 
920   for (i = 0; i < ncmd; i++)
921     {
922       if (cmdarg[i].type == CMDARG_FILE)
923         catch_command_errors (source_script, cmdarg[i].string,
924 			      !batch_flag, RETURN_MASK_ALL);
925       else  /* cmdarg[i].type == CMDARG_COMMAND */
926         catch_command_errors (execute_command, cmdarg[i].string,
927 			      !batch_flag, RETURN_MASK_ALL);
928     }
929   xfree (cmdarg);
930 
931   /* Read in the old history after all the command files have been
932      read.  */
933   init_history ();
934 
935   if (batch_flag)
936     {
937       /* We have hit the end of the batch file.  */
938       quit_force (NULL, 0);
939     }
940 
941   /* Show time and/or space usage.  */
942   do_cleanups (pre_stat_chain);
943 
944   /* NOTE: cagney/1999-11-07: There is probably no reason for not
945      moving this loop and the code found in captured_command_loop()
946      into the command_loop() proper.  The main thing holding back that
947      change - SET_TOP_LEVEL() - has been eliminated.  */
948   while (1)
949     {
950       catch_errors (captured_command_loop, 0, "", RETURN_MASK_ALL);
951     }
952   /* No exit -- exit is through quit_command.  */
953 }
954 
955 int
956 gdb_main (struct captured_main_args *args)
957 {
958   kernel_debugger = 0;
959   use_windows = args->use_windows;
960   catch_errors (captured_main, args, "", RETURN_MASK_ALL);
961   /* The only way to end up here is by an error (normal exit is
962      handled by quit_force()), hence always return an error status.  */
963   return 1;
964 }
965 
966 
967 /* Don't use *_filtered for printing help.  We don't want to prompt
968    for continue no matter how small the screen or how much we're going
969    to print.  */
970 
971 static void
972 print_gdb_help (struct ui_file *stream)
973 {
974   char *system_gdbinit;
975   char *home_gdbinit;
976   char *local_gdbinit;
977 
978   get_init_files (&system_gdbinit, &home_gdbinit, &local_gdbinit);
979 
980   fputs_unfiltered (_("\
981 This is the GNU debugger.  Usage:\n\n\
982     gdb [options] [executable-file [core-file or process-id]]\n\
983     gdb [options] --args executable-file [inferior-arguments ...]\n\n\
984 Options:\n\n\
985 "), stream);
986   fputs_unfiltered (_("\
987   --args             Arguments after executable-file are passed to inferior\n\
988 "), stream);
989   fputs_unfiltered (_("\
990   -b BAUDRATE        Set serial port baud rate used for remote debugging.\n\
991   --batch            Exit after processing options.\n\
992   --batch-silent     As for --batch, but suppress all gdb stdout output.\n\
993   --return-child-result\n\
994                      GDB exit code will be the child's exit code.\n\
995   --cd=DIR           Change current directory to DIR.\n\
996   --command=FILE, -x Execute GDB commands from FILE.\n\
997   --eval-command=COMMAND, -ex\n\
998                      Execute a single GDB command.\n\
999                      May be used multiple times and in conjunction\n\
1000                      with --command.\n\
1001   --core=COREFILE    Analyze the core dump COREFILE.\n\
1002   --pid=PID          Attach to running process PID.\n\
1003 "), stream);
1004   fputs_unfiltered (_("\
1005   --dbx              DBX compatibility mode.\n\
1006   --directory=DIR    Search for source files in DIR.\n\
1007   --epoch            Output information used by epoch emacs-GDB interface.\n\
1008   --exec=EXECFILE    Use EXECFILE as the executable.\n\
1009   --fullname         Output information used by emacs-GDB interface.\n\
1010   --help             Print this message.\n\
1011 "), stream);
1012   fputs_unfiltered (_("\
1013   --interpreter=INTERP\n\
1014                      Select a specific interpreter / user interface\n\
1015 "), stream);
1016   fputs_unfiltered (_("\
1017   -l TIMEOUT         Set timeout in seconds for remote debugging.\n\
1018   --nw		     Do not use a window interface.\n\
1019   --nx               Do not read "), stream);
1020   fputs_unfiltered (gdbinit, stream);
1021   fputs_unfiltered (_(" file.\n\
1022   --quiet            Do not print version number on startup.\n\
1023   --readnow          Fully read symbol files on first access.\n\
1024 "), stream);
1025   fputs_unfiltered (_("\
1026   --se=FILE          Use FILE as symbol file and executable file.\n\
1027   --symbols=SYMFILE  Read symbols from SYMFILE.\n\
1028   --tty=TTY          Use TTY for input/output by the program being debugged.\n\
1029 "), stream);
1030 #if defined(TUI)
1031   fputs_unfiltered (_("\
1032   --tui              Use a terminal user interface.\n\
1033 "), stream);
1034 #endif
1035   fputs_unfiltered (_("\
1036   --version          Print version information and then exit.\n\
1037   -w                 Use a window interface.\n\
1038   --write            Set writing into executable and core files.\n\
1039   --xdb              XDB compatibility mode.\n\
1040 "), stream);
1041   fputs_unfiltered (_("\n\
1042 At startup, GDB reads the following init files and executes their commands:\n\
1043 "), stream);
1044   if (system_gdbinit)
1045     fprintf_unfiltered (stream, _("\
1046    * system-wide init file: %s\n\
1047 "), system_gdbinit);
1048   if (home_gdbinit)
1049     fprintf_unfiltered (stream, _("\
1050    * user-specific init file: %s\n\
1051 "), home_gdbinit);
1052   if (local_gdbinit)
1053     fprintf_unfiltered (stream, _("\
1054    * local init file: ./%s\n\
1055 "), local_gdbinit);
1056   fputs_unfiltered (_("\n\
1057 For more information, type \"help\" from within GDB, or consult the\n\
1058 GDB manual (available as on-line info or a printed manual).\n\
1059 "), stream);
1060   if (REPORT_BUGS_TO[0] && stream == gdb_stdout)
1061     fprintf_unfiltered (stream, _("\
1062 Report bugs to \"%s\".\n\
1063 "), REPORT_BUGS_TO);
1064 }
1065