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