xref: /netbsd-src/external/gpl3/gdb/dist/gdb/main.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /* Top level stuff for GDB, the GNU debugger.
2 
3    Copyright (C) 1986-2019 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 #include "getopt.h"
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <ctype.h>
31 #include "event-loop.h"
32 #include "ui-out.h"
33 
34 #include "interps.h"
35 #include "main.h"
36 #include "source.h"
37 #include "cli/cli-cmds.h"
38 #include "objfiles.h"
39 #include "auto-load.h"
40 #include "maint.h"
41 
42 #include "filenames.h"
43 #include "common/filestuff.h"
44 #include <signal.h>
45 #include "event-top.h"
46 #include "infrun.h"
47 #include "common/signals-state-save-restore.h"
48 #include <vector>
49 #include "common/pathstuff.h"
50 #include "cli/cli-style.h"
51 
52 /* The selected interpreter.  This will be used as a set command
53    variable, so it should always be malloc'ed - since
54    do_setshow_command will free it.  */
55 char *interpreter_p;
56 
57 /* Whether dbx commands will be handled.  */
58 int dbx_commands = 0;
59 
60 /* System root path, used to find libraries etc.  */
61 char *gdb_sysroot = 0;
62 
63 /* GDB datadir, used to store data files.  */
64 char *gdb_datadir = 0;
65 
66 /* Non-zero if GDB_DATADIR was provided on the command line.
67    This doesn't track whether data-directory is set later from the
68    command line, but we don't reread system.gdbinit when that happens.  */
69 static int gdb_datadir_provided = 0;
70 
71 /* If gdb was configured with --with-python=/path,
72    the possibly relocated path to python's lib directory.  */
73 char *python_libdir = 0;
74 
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 
93 /* GDB as it has been invoked from the command line (i.e. argv[0]).  */
94 static char *gdb_program_name;
95 
96 /* Return read only pointer to GDB_PROGRAM_NAME.  */
97 const char *
98 get_gdb_program_name (void)
99 {
100   return gdb_program_name;
101 }
102 
103 static void print_gdb_help (struct ui_file *);
104 
105 /* Set the data-directory parameter to NEW_DATADIR.
106    If NEW_DATADIR is not a directory then a warning is printed.
107    We don't signal an error for backward compatibility.  */
108 
109 void
110 set_gdb_data_directory (const char *new_datadir)
111 {
112   struct stat st;
113 
114   if (stat (new_datadir, &st) < 0)
115     {
116       int save_errno = errno;
117 
118       fprintf_unfiltered (gdb_stderr, "Warning: ");
119       print_sys_errmsg (new_datadir, save_errno);
120     }
121   else if (!S_ISDIR (st.st_mode))
122     warning (_("%s is not a directory."), new_datadir);
123 
124   xfree (gdb_datadir);
125   gdb_datadir = gdb_realpath (new_datadir).release ();
126 
127   /* gdb_realpath won't return an absolute path if the path doesn't exist,
128      but we still want to record an absolute path here.  If the user entered
129      "../foo" and "../foo" doesn't exist then we'll record $(pwd)/../foo which
130      isn't canonical, but that's ok.  */
131   if (!IS_ABSOLUTE_PATH (gdb_datadir))
132     {
133       gdb::unique_xmalloc_ptr<char> abs_datadir = gdb_abspath (gdb_datadir);
134 
135       xfree (gdb_datadir);
136       gdb_datadir = abs_datadir.release ();
137     }
138 }
139 
140 /* Relocate a file or directory.  PROGNAME is the name by which gdb
141    was invoked (i.e., argv[0]).  INITIAL is the default value for the
142    file or directory.  FLAG is true if the value is relocatable, false
143    otherwise.  Returns a newly allocated string; this may return NULL
144    under the same conditions as make_relative_prefix.  */
145 
146 static char *
147 relocate_path (const char *progname, const char *initial, int flag)
148 {
149   if (flag)
150     return make_relative_prefix (progname, BINDIR, initial);
151   return xstrdup (initial);
152 }
153 
154 /* Like relocate_path, but specifically checks for a directory.
155    INITIAL is relocated according to the rules of relocate_path.  If
156    the result is a directory, it is used; otherwise, INITIAL is used.
157    The chosen directory is then canonicalized using lrealpath.  This
158    function always returns a newly-allocated string.  */
159 
160 char *
161 relocate_gdb_directory (const char *initial, int flag)
162 {
163   char *dir;
164 
165   dir = relocate_path (gdb_program_name, initial, flag);
166   if (dir)
167     {
168       struct stat s;
169 
170       if (*dir == '\0' || stat (dir, &s) != 0 || !S_ISDIR (s.st_mode))
171 	{
172 	  xfree (dir);
173 	  dir = NULL;
174 	}
175     }
176   if (!dir)
177     dir = xstrdup (initial);
178 
179   /* Canonicalize the directory.  */
180   if (*dir)
181     {
182       char *canon_sysroot = lrealpath (dir);
183 
184       if (canon_sysroot)
185 	{
186 	  xfree (dir);
187 	  dir = canon_sysroot;
188 	}
189     }
190 
191   return dir;
192 }
193 
194 /* Compute the locations of init files that GDB should source and
195    return them in SYSTEM_GDBINIT, HOME_GDBINIT, LOCAL_GDBINIT.  If
196    there is no system gdbinit (resp. home gdbinit and local gdbinit)
197    to be loaded, then SYSTEM_GDBINIT (resp. HOME_GDBINIT and
198    LOCAL_GDBINIT) is set to NULL.  */
199 static void
200 get_init_files (const char **system_gdbinit,
201 		const char **home_gdbinit,
202 		const char **local_gdbinit)
203 {
204   static const char *sysgdbinit = NULL;
205   static char *homeinit = NULL;
206   static const char *localinit = NULL;
207   static int initialized = 0;
208 
209   if (!initialized)
210     {
211       struct stat homebuf, cwdbuf, s;
212       const char *homedir;
213 
214       if (SYSTEM_GDBINIT[0])
215 	{
216 	  int datadir_len = strlen (GDB_DATADIR);
217 	  int sys_gdbinit_len = strlen (SYSTEM_GDBINIT);
218 	  char *relocated_sysgdbinit;
219 
220 	  /* If SYSTEM_GDBINIT lives in data-directory, and data-directory
221 	     has been provided, search for SYSTEM_GDBINIT there.  */
222 	  if (gdb_datadir_provided
223 	      && datadir_len < sys_gdbinit_len
224 	      && filename_ncmp (SYSTEM_GDBINIT, GDB_DATADIR, datadir_len) == 0
225 	      && IS_DIR_SEPARATOR (SYSTEM_GDBINIT[datadir_len]))
226 	    {
227 	      /* Append the part of SYSTEM_GDBINIT that follows GDB_DATADIR
228 		 to gdb_datadir.  */
229 	      char *tmp_sys_gdbinit = xstrdup (&SYSTEM_GDBINIT[datadir_len]);
230 	      char *p;
231 
232 	      for (p = tmp_sys_gdbinit; IS_DIR_SEPARATOR (*p); ++p)
233 		continue;
234 	      relocated_sysgdbinit = concat (gdb_datadir, SLASH_STRING, p,
235 					     (char *) NULL);
236 	      xfree (tmp_sys_gdbinit);
237 	    }
238 	  else
239 	    {
240 	      relocated_sysgdbinit = relocate_path (gdb_program_name,
241 						    SYSTEM_GDBINIT,
242 						    SYSTEM_GDBINIT_RELOCATABLE);
243 	    }
244 	  if (relocated_sysgdbinit && stat (relocated_sysgdbinit, &s) == 0)
245 	    sysgdbinit = relocated_sysgdbinit;
246 	  else
247 	    xfree (relocated_sysgdbinit);
248 	}
249 
250       homedir = getenv ("HOME");
251 
252       /* If the .gdbinit file in the current directory is the same as
253 	 the $HOME/.gdbinit file, it should not be sourced.  homebuf
254 	 and cwdbuf are used in that purpose.  Make sure that the stats
255 	 are zero in case one of them fails (this guarantees that they
256 	 won't match if either exists).  */
257 
258       memset (&homebuf, 0, sizeof (struct stat));
259       memset (&cwdbuf, 0, sizeof (struct stat));
260 
261       if (homedir)
262 	{
263 	  homeinit = xstrprintf ("%s/%s", homedir, gdbinit);
264 	  if (stat (homeinit, &homebuf) != 0)
265 	    {
266 	      xfree (homeinit);
267 	      homeinit = NULL;
268 	    }
269 	}
270 
271       if (stat (gdbinit, &cwdbuf) == 0)
272 	{
273 	  if (!homeinit
274 	      || memcmp ((char *) &homebuf, (char *) &cwdbuf,
275 			 sizeof (struct stat)))
276 	    localinit = gdbinit;
277 	}
278 
279       initialized = 1;
280     }
281 
282   *system_gdbinit = sysgdbinit;
283   *home_gdbinit = homeinit;
284   *local_gdbinit = localinit;
285 }
286 
287 /* Try to set up an alternate signal stack for SIGSEGV handlers.
288    This allows us to handle SIGSEGV signals generated when the
289    normal process stack is exhausted.  If this stack is not set
290    up (sigaltstack is unavailable or fails) and a SIGSEGV is
291    generated when the normal stack is exhausted then the program
292    will behave as though no SIGSEGV handler was installed.  */
293 
294 static void
295 setup_alternate_signal_stack (void)
296 {
297 #ifdef HAVE_SIGALTSTACK
298   stack_t ss;
299 
300   /* FreeBSD versions older than 11.0 use char * for ss_sp instead of
301      void *.  This cast works with both types.  */
302   ss.ss_sp = (char *) xmalloc (SIGSTKSZ);
303   ss.ss_size = SIGSTKSZ;
304   ss.ss_flags = 0;
305 
306   sigaltstack(&ss, NULL);
307 #endif
308 }
309 
310 /* Call command_loop.  */
311 
312 /* Prevent inlining this function for the benefit of GDB's selftests
313    in the testsuite.  Those tests want to run GDB under GDB and stop
314    here.  */
315 static void captured_command_loop () __attribute__((noinline));
316 
317 static void
318 captured_command_loop ()
319 {
320   struct ui *ui = current_ui;
321 
322   /* Top-level execution commands can be run in the background from
323      here on.  */
324   current_ui->async = 1;
325 
326   /* Give the interpreter a chance to print a prompt, if necessary  */
327   if (ui->prompt_state != PROMPT_BLOCKED)
328     interp_pre_command_loop (top_level_interpreter ());
329 
330   /* Now it's time to start the event loop.  */
331   start_event_loop ();
332 
333   /* FIXME: cagney/1999-11-05: A correct command_loop() implementaton
334      would clean things up (restoring the cleanup chain) to the state
335      they were just prior to the call.  Technically, this means that
336      the do_cleanups() below is redundant.  Unfortunately, many FUNCs
337      are not that well behaved.  do_cleanups should either be replaced
338      with a do_cleanups call (to cover the problem) or an assertion
339      check to detect bad FUNCs code.  */
340   do_cleanups (all_cleanups ());
341   /* If the command_loop returned, normally (rather than threw an
342      error) we try to quit.  If the quit is aborted, our caller
343      catches the signal and restarts the command loop.  */
344   quit_command (NULL, ui->instream == ui->stdin_stream);
345 }
346 
347 /* Handle command errors thrown from within catch_command_errors.  */
348 
349 static int
350 handle_command_errors (struct gdb_exception e)
351 {
352   if (e.reason < 0)
353     {
354       exception_print (gdb_stderr, e);
355 
356       /* If any exception escaped to here, we better enable stdin.
357 	 Otherwise, any command that calls async_disable_stdin, and
358 	 then throws, will leave stdin inoperable.  */
359       async_enable_stdin ();
360       return 0;
361     }
362   return 1;
363 }
364 
365 /* Type of the command callback passed to the const
366    catch_command_errors.  */
367 
368 typedef void (catch_command_errors_const_ftype) (const char *, int);
369 
370 /* Wrap calls to commands run before the event loop is started.  */
371 
372 static int
373 catch_command_errors (catch_command_errors_const_ftype command,
374 		      const char *arg, int from_tty)
375 {
376   TRY
377     {
378       int was_sync = current_ui->prompt_state == PROMPT_BLOCKED;
379 
380       command (arg, from_tty);
381 
382       maybe_wait_sync_command_done (was_sync);
383     }
384   CATCH (e, RETURN_MASK_ALL)
385     {
386       return handle_command_errors (e);
387     }
388   END_CATCH
389 
390   return 1;
391 }
392 
393 /* Adapter for symbol_file_add_main that translates 'from_tty' to a
394    symfile_add_flags.  */
395 
396 static void
397 symbol_file_add_main_adapter (const char *arg, int from_tty)
398 {
399   symfile_add_flags add_flags = 0;
400 
401   if (from_tty)
402     add_flags |= SYMFILE_VERBOSE;
403 
404   symbol_file_add_main (arg, add_flags);
405 }
406 
407 /* Perform validation of the '--readnow' and '--readnever' flags.  */
408 
409 static void
410 validate_readnow_readnever ()
411 {
412   if (readnever_symbol_files && readnow_symbol_files)
413     {
414       error (_("%s: '--readnow' and '--readnever' cannot be "
415 	       "specified simultaneously"),
416 	     gdb_program_name);
417     }
418 }
419 
420 /* Type of this option.  */
421 enum cmdarg_kind
422 {
423   /* Option type -x.  */
424   CMDARG_FILE,
425 
426   /* Option type -ex.  */
427   CMDARG_COMMAND,
428 
429   /* Option type -ix.  */
430   CMDARG_INIT_FILE,
431 
432   /* Option type -iex.  */
433   CMDARG_INIT_COMMAND
434 };
435 
436 /* Arguments of --command option and its counterpart.  */
437 struct cmdarg
438 {
439   cmdarg (cmdarg_kind type_, char *string_)
440     : type (type_), string (string_)
441   {}
442 
443   /* Type of this option.  */
444   enum cmdarg_kind type;
445 
446   /* Value of this option - filename or the GDB command itself.  String memory
447      is not owned by this structure despite it is 'const'.  */
448   char *string;
449 };
450 
451 static void
452 captured_main_1 (struct captured_main_args *context)
453 {
454   int argc = context->argc;
455   char **argv = context->argv;
456 
457   static int quiet = 0;
458   static int set_args = 0;
459   static int inhibit_home_gdbinit = 0;
460 
461   /* Pointers to various arguments from command line.  */
462   char *symarg = NULL;
463   char *execarg = NULL;
464   char *pidarg = NULL;
465   char *corearg = NULL;
466   char *pid_or_core_arg = NULL;
467   char *cdarg = NULL;
468   char *ttyarg = NULL;
469 
470   /* These are static so that we can take their address in an
471      initializer.  */
472   static int print_help;
473   static int print_version;
474   static int print_configuration;
475 
476   /* Pointers to all arguments of --command option.  */
477   std::vector<struct cmdarg> cmdarg_vec;
478 
479   /* All arguments of --directory option.  */
480   std::vector<char *> dirarg;
481 
482   /* gdb init files.  */
483   const char *system_gdbinit;
484   const char *home_gdbinit;
485   const char *local_gdbinit;
486 
487   int i;
488   int save_auto_load;
489   int ret = 1;
490 
491 #ifdef HAVE_USEFUL_SBRK
492   /* Set this before constructing scoped_command_stats.  */
493   lim_at_start = (char *) sbrk (0);
494 #endif
495 
496   scoped_command_stats stat_reporter (false);
497 
498 #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
499   setlocale (LC_MESSAGES, "");
500 #endif
501 #if defined (HAVE_SETLOCALE)
502   setlocale (LC_CTYPE, "");
503 #endif
504 #ifdef ENABLE_NLS
505   bindtextdomain (PACKAGE, LOCALEDIR);
506   textdomain (PACKAGE);
507 #endif
508 
509   notice_open_fds ();
510 
511   saved_command_line = (char *) xstrdup ("");
512 
513 #ifdef __MINGW32__
514   /* Ensure stderr is unbuffered.  A Cygwin pty or pipe is implemented
515      as a Windows pipe, and Windows buffers on pipes.  */
516   setvbuf (stderr, NULL, _IONBF, BUFSIZ);
517 #endif
518 
519   /* Note: `error' cannot be called before this point, because the
520      caller will crash when trying to print the exception.  */
521   main_ui = new ui (stdin, stdout, stderr);
522   current_ui = main_ui;
523 
524   gdb_stdtargerr = gdb_stderr;	/* for moment */
525   gdb_stdtargin = gdb_stdin;	/* for moment */
526 
527   if (bfd_init () != BFD_INIT_MAGIC)
528     error (_("fatal error: libbfd ABI mismatch"));
529 
530 #ifdef __MINGW32__
531   /* On Windows, argv[0] is not necessarily set to absolute form when
532      GDB is found along PATH, without which relocation doesn't work.  */
533   gdb_program_name = windows_get_absolute_argv0 (argv[0]);
534 #else
535   gdb_program_name = xstrdup (argv[0]);
536 #endif
537 
538   /* Prefix warning messages with the command name.  */
539   gdb::unique_xmalloc_ptr<char> tmp_warn_preprint
540     (xstrprintf ("%s: warning: ", gdb_program_name));
541   warning_pre_print = tmp_warn_preprint.get ();
542 
543   current_directory = getcwd (NULL, 0);
544   if (current_directory == NULL)
545     perror_warning_with_name (_("error finding working directory"));
546 
547   /* Set the sysroot path.  */
548   gdb_sysroot = relocate_gdb_directory (TARGET_SYSTEM_ROOT,
549 					TARGET_SYSTEM_ROOT_RELOCATABLE);
550 
551   if (gdb_sysroot == NULL || *gdb_sysroot == '\0')
552     {
553       xfree (gdb_sysroot);
554       gdb_sysroot = xstrdup (TARGET_SYSROOT_PREFIX);
555     }
556 
557   debug_file_directory = relocate_gdb_directory (DEBUGDIR,
558 						 DEBUGDIR_RELOCATABLE);
559 
560   gdb_datadir = relocate_gdb_directory (GDB_DATADIR,
561 					GDB_DATADIR_RELOCATABLE);
562 
563 #ifdef WITH_PYTHON_PATH
564   {
565     /* For later use in helping Python find itself.  */
566     char *tmp = concat (WITH_PYTHON_PATH, SLASH_STRING, "lib", (char *) NULL);
567 
568     python_libdir = relocate_gdb_directory (tmp, PYTHON_PATH_RELOCATABLE);
569     xfree (tmp);
570   }
571 #endif
572 
573 #ifdef RELOC_SRCDIR
574   add_substitute_path_rule (RELOC_SRCDIR,
575 			    make_relative_prefix (gdb_program_name, BINDIR,
576 						  RELOC_SRCDIR));
577 #endif
578 
579   /* There will always be an interpreter.  Either the one passed into
580      this captured main, or one specified by the user at start up, or
581      the console.  Initialize the interpreter to the one requested by
582      the application.  */
583   interpreter_p = xstrdup (context->interpreter_p);
584 
585   /* Parse arguments and options.  */
586   {
587     int c;
588     /* When var field is 0, use flag field to record the equivalent
589        short option (or arbitrary numbers starting at 10 for those
590        with no equivalent).  */
591     enum {
592       OPT_SE = 10,
593       OPT_CD,
594       OPT_ANNOTATE,
595       OPT_STATISTICS,
596       OPT_TUI,
597       OPT_NOWINDOWS,
598       OPT_WINDOWS,
599       OPT_IX,
600       OPT_IEX,
601       OPT_READNOW,
602       OPT_READNEVER
603     };
604     static struct option long_options[] =
605     {
606       {"tui", no_argument, 0, OPT_TUI},
607       {"dbx", no_argument, &dbx_commands, 1},
608       {"readnow", no_argument, NULL, OPT_READNOW},
609       {"readnever", no_argument, NULL, OPT_READNEVER},
610       {"r", no_argument, NULL, OPT_READNOW},
611       {"quiet", no_argument, &quiet, 1},
612       {"q", no_argument, &quiet, 1},
613       {"silent", no_argument, &quiet, 1},
614       {"nh", no_argument, &inhibit_home_gdbinit, 1},
615       {"nx", no_argument, &inhibit_gdbinit, 1},
616       {"n", no_argument, &inhibit_gdbinit, 1},
617       {"batch-silent", no_argument, 0, 'B'},
618       {"batch", no_argument, &batch_flag, 1},
619 
620     /* This is a synonym for "--annotate=1".  --annotate is now
621        preferred, but keep this here for a long time because people
622        will be running emacses which use --fullname.  */
623       {"fullname", no_argument, 0, 'f'},
624       {"f", no_argument, 0, 'f'},
625 
626       {"annotate", required_argument, 0, OPT_ANNOTATE},
627       {"help", no_argument, &print_help, 1},
628       {"se", required_argument, 0, OPT_SE},
629       {"symbols", required_argument, 0, 's'},
630       {"s", required_argument, 0, 's'},
631       {"exec", required_argument, 0, 'e'},
632       {"e", required_argument, 0, 'e'},
633       {"core", required_argument, 0, 'c'},
634       {"c", required_argument, 0, 'c'},
635       {"pid", required_argument, 0, 'p'},
636       {"p", required_argument, 0, 'p'},
637       {"command", required_argument, 0, 'x'},
638       {"eval-command", required_argument, 0, 'X'},
639       {"version", no_argument, &print_version, 1},
640       {"configuration", no_argument, &print_configuration, 1},
641       {"x", required_argument, 0, 'x'},
642       {"ex", required_argument, 0, 'X'},
643       {"init-command", required_argument, 0, OPT_IX},
644       {"init-eval-command", required_argument, 0, OPT_IEX},
645       {"ix", required_argument, 0, OPT_IX},
646       {"iex", required_argument, 0, OPT_IEX},
647 #ifdef GDBTK
648       {"tclcommand", required_argument, 0, 'z'},
649       {"enable-external-editor", no_argument, 0, 'y'},
650       {"editor-command", required_argument, 0, 'w'},
651 #endif
652       {"ui", required_argument, 0, 'i'},
653       {"interpreter", required_argument, 0, 'i'},
654       {"i", required_argument, 0, 'i'},
655       {"directory", required_argument, 0, 'd'},
656       {"d", required_argument, 0, 'd'},
657       {"data-directory", required_argument, 0, 'D'},
658       {"D", required_argument, 0, 'D'},
659       {"cd", required_argument, 0, OPT_CD},
660       {"tty", required_argument, 0, 't'},
661       {"baud", required_argument, 0, 'b'},
662       {"b", required_argument, 0, 'b'},
663       {"nw", no_argument, NULL, OPT_NOWINDOWS},
664       {"nowindows", no_argument, NULL, OPT_NOWINDOWS},
665       {"w", no_argument, NULL, OPT_WINDOWS},
666       {"windows", no_argument, NULL, OPT_WINDOWS},
667       {"statistics", no_argument, 0, OPT_STATISTICS},
668       {"write", no_argument, &write_files, 1},
669       {"args", no_argument, &set_args, 1},
670       {"l", required_argument, 0, 'l'},
671       {"return-child-result", no_argument, &return_child_result, 1},
672       {0, no_argument, 0, 0}
673     };
674 
675     while (1)
676       {
677 	int option_index;
678 
679 	c = getopt_long_only (argc, argv, "",
680 			      long_options, &option_index);
681 	if (c == EOF || set_args)
682 	  break;
683 
684 	/* Long option that takes an argument.  */
685 	if (c == 0 && long_options[option_index].flag == 0)
686 	  c = long_options[option_index].val;
687 
688 	switch (c)
689 	  {
690 	  case 0:
691 	    /* Long option that just sets a flag.  */
692 	    break;
693 	  case OPT_SE:
694 	    symarg = optarg;
695 	    execarg = optarg;
696 	    break;
697 	  case OPT_CD:
698 	    cdarg = optarg;
699 	    break;
700 	  case OPT_ANNOTATE:
701 	    /* FIXME: what if the syntax is wrong (e.g. not digits)?  */
702 	    annotation_level = atoi (optarg);
703 	    break;
704 	  case OPT_STATISTICS:
705 	    /* Enable the display of both time and space usage.  */
706 	    set_per_command_time (1);
707 	    set_per_command_space (1);
708 	    break;
709 	  case OPT_TUI:
710 	    /* --tui is equivalent to -i=tui.  */
711 #ifdef TUI
712 	    xfree (interpreter_p);
713 	    interpreter_p = xstrdup (INTERP_TUI);
714 #else
715 	    error (_("%s: TUI mode is not supported"), gdb_program_name);
716 #endif
717 	    break;
718 	  case OPT_WINDOWS:
719 	    /* FIXME: cagney/2003-03-01: Not sure if this option is
720                actually useful, and if it is, what it should do.  */
721 #ifdef GDBTK
722 	    /* --windows is equivalent to -i=insight.  */
723 	    xfree (interpreter_p);
724 	    interpreter_p = xstrdup (INTERP_INSIGHT);
725 #endif
726 	    break;
727 	  case OPT_NOWINDOWS:
728 	    /* -nw is equivalent to -i=console.  */
729 	    xfree (interpreter_p);
730 	    interpreter_p = xstrdup (INTERP_CONSOLE);
731 	    break;
732 	  case 'f':
733 	    annotation_level = 1;
734 	    break;
735 	  case 's':
736 	    symarg = optarg;
737 	    break;
738 	  case 'e':
739 	    execarg = optarg;
740 	    break;
741 	  case 'c':
742 	    corearg = optarg;
743 	    break;
744 	  case 'p':
745 	    pidarg = optarg;
746 	    break;
747 	  case 'x':
748 	    cmdarg_vec.emplace_back (CMDARG_FILE, optarg);
749 	    break;
750 	  case 'X':
751 	    cmdarg_vec.emplace_back (CMDARG_COMMAND, optarg);
752 	    break;
753 	  case OPT_IX:
754 	    cmdarg_vec.emplace_back (CMDARG_INIT_FILE, optarg);
755 	    break;
756 	  case OPT_IEX:
757 	    cmdarg_vec.emplace_back (CMDARG_INIT_COMMAND, optarg);
758 	    break;
759 	  case 'B':
760 	    batch_flag = batch_silent = 1;
761 	    gdb_stdout = new null_file ();
762 	    break;
763 	  case 'D':
764 	    if (optarg[0] == '\0')
765 	      error (_("%s: empty path for `--data-directory'"),
766 		     gdb_program_name);
767 	    set_gdb_data_directory (optarg);
768 	    gdb_datadir_provided = 1;
769 	    break;
770 #ifdef GDBTK
771 	  case 'z':
772 	    {
773 	      extern int gdbtk_test (char *);
774 
775 	      if (!gdbtk_test (optarg))
776 		error (_("%s: unable to load tclcommand file \"%s\""),
777 		       gdb_program_name, optarg);
778 	      break;
779 	    }
780 	  case 'y':
781 	    /* Backwards compatibility only.  */
782 	    break;
783 	  case 'w':
784 	    {
785 	      /* Set the external editor commands when gdb is farming out files
786 		 to be edited by another program.  */
787 	      extern char *external_editor_command;
788 
789 	      external_editor_command = xstrdup (optarg);
790 	      break;
791 	    }
792 #endif /* GDBTK */
793 	  case 'i':
794 	    xfree (interpreter_p);
795 	    interpreter_p = xstrdup (optarg);
796 	    break;
797 	  case 'd':
798 	    dirarg.push_back (optarg);
799 	    break;
800 	  case 't':
801 	    ttyarg = optarg;
802 	    break;
803 	  case 'q':
804 	    quiet = 1;
805 	    break;
806 	  case 'b':
807 	    {
808 	      int rate;
809 	      char *p;
810 
811 	      rate = strtol (optarg, &p, 0);
812 	      if (rate == 0 && p == optarg)
813 		warning (_("could not set baud rate to `%s'."),
814 			 optarg);
815 	      else
816 		baud_rate = rate;
817 	    }
818             break;
819 	  case 'l':
820 	    {
821 	      int timeout;
822 	      char *p;
823 
824 	      timeout = strtol (optarg, &p, 0);
825 	      if (timeout == 0 && p == optarg)
826 		warning (_("could not set timeout limit to `%s'."),
827 			 optarg);
828 	      else
829 		remote_timeout = timeout;
830 	    }
831 	    break;
832 
833 	  case OPT_READNOW:
834 	    {
835 	      readnow_symbol_files = 1;
836 	      validate_readnow_readnever ();
837 	    }
838 	    break;
839 
840 	  case OPT_READNEVER:
841 	    {
842 	      readnever_symbol_files = 1;
843 	      validate_readnow_readnever ();
844 	    }
845 	    break;
846 
847 	  case '?':
848 	    error (_("Use `%s --help' for a complete list of options."),
849 		   gdb_program_name);
850 	  }
851       }
852 
853     if (batch_flag)
854       {
855 	quiet = 1;
856 
857 	/* Disable all output styling when running in batch mode.  */
858 	cli_styling = 0;
859       }
860   }
861 
862   save_original_signals_state (quiet);
863 
864   /* Try to set up an alternate signal stack for SIGSEGV handlers.  */
865   setup_alternate_signal_stack ();
866 
867   /* Initialize all files.  */
868   gdb_init (gdb_program_name);
869 
870   /* Now that gdb_init has created the initial inferior, we're in
871      position to set args for that inferior.  */
872   if (set_args)
873     {
874       /* The remaining options are the command-line options for the
875 	 inferior.  The first one is the sym/exec file, and the rest
876 	 are arguments.  */
877       if (optind >= argc)
878 	error (_("%s: `--args' specified but no program specified"),
879 	       gdb_program_name);
880 
881       symarg = argv[optind];
882       execarg = argv[optind];
883       ++optind;
884       set_inferior_args_vector (argc - optind, &argv[optind]);
885     }
886   else
887     {
888       /* OK, that's all the options.  */
889 
890       /* The first argument, if specified, is the name of the
891 	 executable.  */
892       if (optind < argc)
893 	{
894 	  symarg = argv[optind];
895 	  execarg = argv[optind];
896 	  optind++;
897 	}
898 
899       /* If the user hasn't already specified a PID or the name of a
900 	 core file, then a second optional argument is allowed.  If
901 	 present, this argument should be interpreted as either a
902 	 PID or a core file, whichever works.  */
903       if (pidarg == NULL && corearg == NULL && optind < argc)
904 	{
905 	  pid_or_core_arg = argv[optind];
906 	  optind++;
907 	}
908 
909       /* Any argument left on the command line is unexpected and
910 	 will be ignored.  Inform the user.  */
911       if (optind < argc)
912 	fprintf_unfiltered (gdb_stderr,
913 			    _("Excess command line "
914 			      "arguments ignored. (%s%s)\n"),
915 			    argv[optind],
916 			    (optind == argc - 1) ? "" : " ...");
917     }
918 
919   /* Lookup gdbinit files.  Note that the gdbinit file name may be
920      overriden during file initialization, so get_init_files should be
921      called after gdb_init.  */
922   get_init_files (&system_gdbinit, &home_gdbinit, &local_gdbinit);
923 
924   /* Do these (and anything which might call wrap_here or *_filtered)
925      after initialize_all_files() but before the interpreter has been
926      installed.  Otherwize the help/version messages will be eaten by
927      the interpreter's output handler.  */
928 
929   if (print_version)
930     {
931       print_gdb_version (gdb_stdout, false);
932       wrap_here ("");
933       printf_filtered ("\n");
934       exit (0);
935     }
936 
937   if (print_help)
938     {
939       print_gdb_help (gdb_stdout);
940       fputs_unfiltered ("\n", gdb_stdout);
941       exit (0);
942     }
943 
944   if (print_configuration)
945     {
946       print_gdb_configuration (gdb_stdout);
947       wrap_here ("");
948       printf_filtered ("\n");
949       exit (0);
950     }
951 
952   /* FIXME: cagney/2003-02-03: The big hack (part 1 of 2) that lets
953      GDB retain the old MI1 interpreter startup behavior.  Output the
954      copyright message before the interpreter is installed.  That way
955      it isn't encapsulated in MI output.  */
956   if (!quiet && strcmp (interpreter_p, INTERP_MI1) == 0)
957     {
958       /* Print all the junk at the top, with trailing "..." if we are
959          about to read a symbol file (possibly slowly).  */
960       print_gdb_version (gdb_stdout, true);
961       if (symarg)
962 	printf_filtered ("..");
963       wrap_here ("");
964       printf_filtered ("\n");
965       gdb_flush (gdb_stdout);	/* Force to screen during slow
966 				   operations.  */
967     }
968 
969   /* Install the default UI.  All the interpreters should have had a
970      look at things by now.  Initialize the default interpreter.  */
971   set_top_level_interpreter (interpreter_p);
972 
973   /* FIXME: cagney/2003-02-03: The big hack (part 2 of 2) that lets
974      GDB retain the old MI1 interpreter startup behavior.  Output the
975      copyright message after the interpreter is installed when it is
976      any sane interpreter.  */
977   if (!quiet && !current_interp_named_p (INTERP_MI1))
978     {
979       /* Print all the junk at the top, with trailing "..." if we are
980          about to read a symbol file (possibly slowly).  */
981       print_gdb_version (gdb_stdout, true);
982       if (symarg)
983 	printf_filtered ("..");
984       wrap_here ("");
985       printf_filtered ("\n");
986       gdb_flush (gdb_stdout);	/* Force to screen during slow
987 				   operations.  */
988     }
989 
990   /* Set off error and warning messages with a blank line.  */
991   tmp_warn_preprint.reset ();
992   warning_pre_print = _("\nwarning: ");
993 
994   /* Read and execute the system-wide gdbinit file, if it exists.
995      This is done *before* all the command line arguments are
996      processed; it sets global parameters, which are independent of
997      what file you are debugging or what directory you are in.  */
998   if (system_gdbinit && !inhibit_gdbinit)
999     ret = catch_command_errors (source_script, system_gdbinit, 0);
1000 
1001   /* Read and execute $HOME/.gdbinit file, if it exists.  This is done
1002      *before* all the command line arguments are processed; it sets
1003      global parameters, which are independent of what file you are
1004      debugging or what directory you are in.  */
1005 
1006   if (home_gdbinit && !inhibit_gdbinit && !inhibit_home_gdbinit)
1007     ret = catch_command_errors (source_script, home_gdbinit, 0);
1008 
1009   /* Process '-ix' and '-iex' options early.  */
1010   for (i = 0; i < cmdarg_vec.size (); i++)
1011     {
1012       const struct cmdarg &cmdarg_p = cmdarg_vec[i];
1013 
1014       switch (cmdarg_p.type)
1015 	{
1016 	case CMDARG_INIT_FILE:
1017 	  ret = catch_command_errors (source_script, cmdarg_p.string,
1018 				      !batch_flag);
1019 	  break;
1020 	case CMDARG_INIT_COMMAND:
1021 	  ret = catch_command_errors (execute_command, cmdarg_p.string,
1022 				      !batch_flag);
1023 	  break;
1024 	}
1025     }
1026 
1027   /* Now perform all the actions indicated by the arguments.  */
1028   if (cdarg != NULL)
1029     {
1030       ret = catch_command_errors (cd_command, cdarg, 0);
1031     }
1032 
1033   for (i = 0; i < dirarg.size (); i++)
1034     ret = catch_command_errors (directory_switch, dirarg[i], 0);
1035 
1036   /* Skip auto-loading section-specified scripts until we've sourced
1037      local_gdbinit (which is often used to augment the source search
1038      path).  */
1039   save_auto_load = global_auto_load;
1040   global_auto_load = 0;
1041 
1042   if (execarg != NULL
1043       && symarg != NULL
1044       && strcmp (execarg, symarg) == 0)
1045     {
1046       /* The exec file and the symbol-file are the same.  If we can't
1047          open it, better only print one error message.
1048          catch_command_errors returns non-zero on success!  */
1049       ret = catch_command_errors (exec_file_attach, execarg,
1050 				  !batch_flag);
1051       if (ret != 0)
1052 	ret = catch_command_errors (symbol_file_add_main_adapter,
1053 				    symarg, !batch_flag);
1054     }
1055   else
1056     {
1057       if (execarg != NULL)
1058 	ret = catch_command_errors (exec_file_attach, execarg,
1059 				    !batch_flag);
1060       if (symarg != NULL)
1061 	ret = catch_command_errors (symbol_file_add_main_adapter,
1062 				    symarg, !batch_flag);
1063     }
1064 
1065   if (corearg && pidarg)
1066     error (_("Can't attach to process and specify "
1067 	     "a core file at the same time."));
1068 
1069   if (corearg != NULL)
1070     {
1071       ret = catch_command_errors (core_file_command, corearg,
1072 				  !batch_flag);
1073     }
1074   else if (pidarg != NULL)
1075     {
1076       ret = catch_command_errors (attach_command, pidarg, !batch_flag);
1077     }
1078   else if (pid_or_core_arg)
1079     {
1080       /* The user specified 'gdb program pid' or gdb program core'.
1081 	 If pid_or_core_arg's first character is a digit, try attach
1082 	 first and then corefile.  Otherwise try just corefile.  */
1083 
1084       if (isdigit (pid_or_core_arg[0]))
1085 	{
1086 	  ret = catch_command_errors (attach_command, pid_or_core_arg,
1087 				      !batch_flag);
1088 	  if (ret == 0)
1089 	    ret = catch_command_errors (core_file_command,
1090 					pid_or_core_arg,
1091 					!batch_flag);
1092 	}
1093       else
1094 	{
1095 	  /* Can't be a pid, better be a corefile.  */
1096 	  ret = catch_command_errors (core_file_command,
1097 				      pid_or_core_arg,
1098 				      !batch_flag);
1099 	}
1100     }
1101 
1102   if (ttyarg != NULL)
1103     set_inferior_io_terminal (ttyarg);
1104 
1105   /* Error messages should no longer be distinguished with extra output.  */
1106   warning_pre_print = _("warning: ");
1107 
1108   /* Read the .gdbinit file in the current directory, *if* it isn't
1109      the same as the $HOME/.gdbinit file (it should exist, also).  */
1110   if (local_gdbinit)
1111     {
1112       auto_load_local_gdbinit_pathname
1113 	= gdb_realpath (local_gdbinit).release ();
1114 
1115       if (!inhibit_gdbinit && auto_load_local_gdbinit
1116 	  && file_is_auto_load_safe (local_gdbinit,
1117 				     _("auto-load: Loading .gdbinit "
1118 				       "file \"%s\".\n"),
1119 				     local_gdbinit))
1120 	{
1121 	  auto_load_local_gdbinit_loaded = 1;
1122 
1123 	  ret = catch_command_errors (source_script, local_gdbinit, 0);
1124 	}
1125     }
1126 
1127   /* Now that all .gdbinit's have been read and all -d options have been
1128      processed, we can read any scripts mentioned in SYMARG.
1129      We wait until now because it is common to add to the source search
1130      path in local_gdbinit.  */
1131   global_auto_load = save_auto_load;
1132   for (objfile *objfile : current_program_space->objfiles ())
1133     load_auto_scripts_for_objfile (objfile);
1134 
1135   /* Process '-x' and '-ex' options.  */
1136   for (i = 0; i < cmdarg_vec.size (); i++)
1137     {
1138       const struct cmdarg &cmdarg_p = cmdarg_vec[i];
1139 
1140       switch (cmdarg_p.type)
1141 	{
1142 	case CMDARG_FILE:
1143 	  ret = catch_command_errors (source_script, cmdarg_p.string,
1144 				      !batch_flag);
1145 	  break;
1146 	case CMDARG_COMMAND:
1147 	  ret = catch_command_errors (execute_command, cmdarg_p.string,
1148 				      !batch_flag);
1149 	  break;
1150 	}
1151     }
1152 
1153   /* Read in the old history after all the command files have been
1154      read.  */
1155   init_history ();
1156 
1157   if (batch_flag)
1158     {
1159       int error_status = EXIT_FAILURE;
1160       int *exit_arg = ret == 0 ? &error_status : NULL;
1161 
1162       /* We have hit the end of the batch file.  */
1163       quit_force (exit_arg, 0);
1164     }
1165 }
1166 
1167 static void
1168 captured_main (void *data)
1169 {
1170   struct captured_main_args *context = (struct captured_main_args *) data;
1171 
1172   captured_main_1 (context);
1173 
1174   /* NOTE: cagney/1999-11-07: There is probably no reason for not
1175      moving this loop and the code found in captured_command_loop()
1176      into the command_loop() proper.  The main thing holding back that
1177      change - SET_TOP_LEVEL() - has been eliminated.  */
1178   while (1)
1179     {
1180       TRY
1181 	{
1182 	  captured_command_loop ();
1183 	}
1184       CATCH (ex, RETURN_MASK_ALL)
1185 	{
1186 	  exception_print (gdb_stderr, ex);
1187 	}
1188       END_CATCH
1189     }
1190   /* No exit -- exit is through quit_command.  */
1191 }
1192 
1193 int
1194 gdb_main (struct captured_main_args *args)
1195 {
1196   TRY
1197     {
1198       captured_main (args);
1199     }
1200   CATCH (ex, RETURN_MASK_ALL)
1201     {
1202       exception_print (gdb_stderr, ex);
1203     }
1204   END_CATCH
1205 
1206   /* The only way to end up here is by an error (normal exit is
1207      handled by quit_force()), hence always return an error status.  */
1208   return 1;
1209 }
1210 
1211 
1212 /* Don't use *_filtered for printing help.  We don't want to prompt
1213    for continue no matter how small the screen or how much we're going
1214    to print.  */
1215 
1216 static void
1217 print_gdb_help (struct ui_file *stream)
1218 {
1219   const char *system_gdbinit;
1220   const char *home_gdbinit;
1221   const char *local_gdbinit;
1222 
1223   get_init_files (&system_gdbinit, &home_gdbinit, &local_gdbinit);
1224 
1225   /* Note: The options in the list below are only approximately sorted
1226      in the alphabetical order, so as to group closely related options
1227      together.  */
1228   fputs_unfiltered (_("\
1229 This is the GNU debugger.  Usage:\n\n\
1230     gdb [options] [executable-file [core-file or process-id]]\n\
1231     gdb [options] --args executable-file [inferior-arguments ...]\n\n\
1232 "), stream);
1233   fputs_unfiltered (_("\
1234 Selection of debuggee and its files:\n\n\
1235   --args             Arguments after executable-file are passed to inferior\n\
1236   --core=COREFILE    Analyze the core dump COREFILE.\n\
1237   --exec=EXECFILE    Use EXECFILE as the executable.\n\
1238   --pid=PID          Attach to running process PID.\n\
1239   --directory=DIR    Search for source files in DIR.\n\
1240   --se=FILE          Use FILE as symbol file and executable file.\n\
1241   --symbols=SYMFILE  Read symbols from SYMFILE.\n\
1242   --readnow          Fully read symbol files on first access.\n\
1243   --readnever        Do not read symbol files.\n\
1244   --write            Set writing into executable and core files.\n\n\
1245 "), stream);
1246   fputs_unfiltered (_("\
1247 Initial commands and command files:\n\n\
1248   --command=FILE, -x Execute GDB commands from FILE.\n\
1249   --init-command=FILE, -ix\n\
1250                      Like -x but execute commands before loading inferior.\n\
1251   --eval-command=COMMAND, -ex\n\
1252                      Execute a single GDB command.\n\
1253                      May be used multiple times and in conjunction\n\
1254                      with --command.\n\
1255   --init-eval-command=COMMAND, -iex\n\
1256                      Like -ex but before loading inferior.\n\
1257   --nh               Do not read ~/.gdbinit.\n\
1258   --nx               Do not read any .gdbinit files in any directory.\n\n\
1259 "), stream);
1260   fputs_unfiltered (_("\
1261 Output and user interface control:\n\n\
1262   --fullname         Output information used by emacs-GDB interface.\n\
1263   --interpreter=INTERP\n\
1264                      Select a specific interpreter / user interface\n\
1265   --tty=TTY          Use TTY for input/output by the program being debugged.\n\
1266   -w                 Use the GUI interface.\n\
1267   --nw               Do not use the GUI interface.\n\
1268 "), stream);
1269 #if defined(TUI)
1270   fputs_unfiltered (_("\
1271   --tui              Use a terminal user interface.\n\
1272 "), stream);
1273 #endif
1274   fputs_unfiltered (_("\
1275   --dbx              DBX compatibility mode.\n\
1276   -q, --quiet, --silent\n\
1277                      Do not print version number on startup.\n\n\
1278 "), stream);
1279   fputs_unfiltered (_("\
1280 Operating modes:\n\n\
1281   --batch            Exit after processing options.\n\
1282   --batch-silent     Like --batch, but suppress all gdb stdout output.\n\
1283   --return-child-result\n\
1284                      GDB exit code will be the child's exit code.\n\
1285   --configuration    Print details about GDB configuration and then exit.\n\
1286   --help             Print this message and then exit.\n\
1287   --version          Print version information and then exit.\n\n\
1288 Remote debugging options:\n\n\
1289   -b BAUDRATE        Set serial port baud rate used for remote debugging.\n\
1290   -l TIMEOUT         Set timeout in seconds for remote debugging.\n\n\
1291 Other options:\n\n\
1292   --cd=DIR           Change current directory to DIR.\n\
1293   --data-directory=DIR, -D\n\
1294                      Set GDB's data-directory to DIR.\n\
1295 "), stream);
1296   fputs_unfiltered (_("\n\
1297 At startup, GDB reads the following init files and executes their commands:\n\
1298 "), stream);
1299   if (system_gdbinit)
1300     fprintf_unfiltered (stream, _("\
1301    * system-wide init file: %s\n\
1302 "), system_gdbinit);
1303   if (home_gdbinit)
1304     fprintf_unfiltered (stream, _("\
1305    * user-specific init file: %s\n\
1306 "), home_gdbinit);
1307   if (local_gdbinit)
1308     fprintf_unfiltered (stream, _("\
1309    * local init file (see also 'set auto-load local-gdbinit'): ./%s\n\
1310 "), local_gdbinit);
1311   fputs_unfiltered (_("\n\
1312 For more information, type \"help\" from within GDB, or consult the\n\
1313 GDB manual (available as on-line info or a printed manual).\n\
1314 "), stream);
1315   if (REPORT_BUGS_TO[0] && stream == gdb_stdout)
1316     fprintf_unfiltered (stream, _("\
1317 Report bugs to \"%s\".\n\
1318 "), REPORT_BUGS_TO);
1319 }
1320