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