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