gdb/main.c - gdb

Global variables defined

Data types defined

Functions defined

Source code

  1. /* Top level stuff for GDB, the GNU debugger.

  2.    Copyright (C) 1986-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "top.h"
  16. #include "target.h"
  17. #include "inferior.h"
  18. #include "symfile.h"
  19. #include "gdbcore.h"
  20. #include "getopt.h"

  21. #include <sys/types.h>
  22. #include <sys/stat.h>
  23. #include <ctype.h>
  24. #include "event-loop.h"
  25. #include "ui-out.h"

  26. #include "interps.h"
  27. #include "main.h"
  28. #include "source.h"
  29. #include "cli/cli-cmds.h"
  30. #include "objfiles.h"
  31. #include "auto-load.h"
  32. #include "maint.h"

  33. #include "filenames.h"
  34. #include "filestuff.h"
  35. #include <signal.h>
  36. #include "event-top.h"
  37. #include "infrun.h"

  38. /* The selected interpreter.  This will be used as a set command
  39.    variable, so it should always be malloc'ed - since
  40.    do_setshow_command will free it.  */
  41. char *interpreter_p;

  42. /* Whether xdb commands will be handled.  */
  43. int xdb_commands = 0;

  44. /* Whether dbx commands will be handled.  */
  45. int dbx_commands = 0;

  46. /* System root path, used to find libraries etc.  */
  47. char *gdb_sysroot = 0;

  48. /* GDB datadir, used to store data files.  */
  49. char *gdb_datadir = 0;

  50. /* Non-zero if GDB_DATADIR was provided on the command line.
  51.    This doesn't track whether data-directory is set later from the
  52.    command line, but we don't reread system.gdbinit when that happens.  */
  53. static int gdb_datadir_provided = 0;

  54. /* If gdb was configured with --with-python=/path,
  55.    the possibly relocated path to python's lib directory.  */
  56. char *python_libdir = 0;

  57. struct ui_file *gdb_stdout;
  58. struct ui_file *gdb_stderr;
  59. struct ui_file *gdb_stdlog;
  60. struct ui_file *gdb_stdin;
  61. /* Target IO streams.  */
  62. struct ui_file *gdb_stdtargin;
  63. struct ui_file *gdb_stdtarg;
  64. struct ui_file *gdb_stdtargerr;

  65. /* True if --batch or --batch-silent was seen.  */
  66. int batch_flag = 0;

  67. /* Support for the --batch-silent option.  */
  68. int batch_silent = 0;

  69. /* Support for --return-child-result option.
  70.    Set the default to -1 to return error in the case
  71.    that the program does not run or does not complete.  */
  72. int return_child_result = 0;
  73. int return_child_result_value = -1;


  74. /* GDB as it has been invoked from the command line (i.e. argv[0]).  */
  75. static char *gdb_program_name;

  76. /* Return read only pointer to GDB_PROGRAM_NAME.  */
  77. const char *
  78. get_gdb_program_name (void)
  79. {
  80.   return gdb_program_name;
  81. }

  82. static void print_gdb_help (struct ui_file *);

  83. /* Set the data-directory parameter to NEW_DATADIR.
  84.    If NEW_DATADIR is not a directory then a warning is printed.
  85.    We don't signal an error for backward compatibility.  */

  86. void
  87. set_gdb_data_directory (const char *new_datadir)
  88. {
  89.   struct stat st;

  90.   if (stat (new_datadir, &st) < 0)
  91.     {
  92.       int save_errno = errno;

  93.       fprintf_unfiltered (gdb_stderr, "Warning: ");
  94.       print_sys_errmsg (new_datadir, save_errno);
  95.     }
  96.   else if (!S_ISDIR (st.st_mode))
  97.     warning (_("%s is not a directory."), new_datadir);

  98.   xfree (gdb_datadir);
  99.   gdb_datadir = gdb_realpath (new_datadir);

  100.   /* gdb_realpath won't return an absolute path if the path doesn't exist,
  101.      but we still want to record an absolute path here.  If the user entered
  102.      "../foo" and "../foo" doesn't exist then we'll record $(pwd)/../foo which
  103.      isn't canonical, but that's ok.  */
  104.   if (!IS_ABSOLUTE_PATH (gdb_datadir))
  105.     {
  106.       char *abs_datadir = gdb_abspath (gdb_datadir);

  107.       xfree (gdb_datadir);
  108.       gdb_datadir = abs_datadir;
  109.     }
  110. }

  111. /* Relocate a file or directory.  PROGNAME is the name by which gdb
  112.    was invoked (i.e., argv[0]).  INITIAL is the default value for the
  113.    file or directory.  FLAG is true if the value is relocatable, false
  114.    otherwise.  Returns a newly allocated string; this may return NULL
  115.    under the same conditions as make_relative_prefix.  */

  116. static char *
  117. relocate_path (const char *progname, const char *initial, int flag)
  118. {
  119.   if (flag)
  120.     return make_relative_prefix (progname, BINDIR, initial);
  121.   return xstrdup (initial);
  122. }

  123. /* Like relocate_path, but specifically checks for a directory.
  124.    INITIAL is relocated according to the rules of relocate_path.  If
  125.    the result is a directory, it is used; otherwise, INITIAL is used.
  126.    The chosen directory is then canonicalized using lrealpath.  This
  127.    function always returns a newly-allocated string.  */

  128. char *
  129. relocate_gdb_directory (const char *initial, int flag)
  130. {
  131.   char *dir;

  132.   dir = relocate_path (gdb_program_name, initial, flag);
  133.   if (dir)
  134.     {
  135.       struct stat s;

  136.       if (*dir == '\0' || stat (dir, &s) != 0 || !S_ISDIR (s.st_mode))
  137.         {
  138.           xfree (dir);
  139.           dir = NULL;
  140.         }
  141.     }
  142.   if (!dir)
  143.     dir = xstrdup (initial);

  144.   /* Canonicalize the directory.  */
  145.   if (*dir)
  146.     {
  147.       char *canon_sysroot = lrealpath (dir);

  148.       if (canon_sysroot)
  149.         {
  150.           xfree (dir);
  151.           dir = canon_sysroot;
  152.         }
  153.     }

  154.   return dir;
  155. }

  156. /* Compute the locations of init files that GDB should source and
  157.    return them in SYSTEM_GDBINIT, HOME_GDBINIT, LOCAL_GDBINIT.  If
  158.    there is no system gdbinit (resp. home gdbinit and local gdbinit)
  159.    to be loaded, then SYSTEM_GDBINIT (resp. HOME_GDBINIT and
  160.    LOCAL_GDBINIT) is set to NULL.  */
  161. static void
  162. get_init_files (const char **system_gdbinit,
  163.                 const char **home_gdbinit,
  164.                 const char **local_gdbinit)
  165. {
  166.   static const char *sysgdbinit = NULL;
  167.   static char *homeinit = NULL;
  168.   static const char *localinit = NULL;
  169.   static int initialized = 0;

  170.   if (!initialized)
  171.     {
  172.       struct stat homebuf, cwdbuf, s;
  173.       char *homedir;

  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.           /* If SYSTEM_GDBINIT lives in data-directory, and data-directory
  180.              has been provided, search for SYSTEM_GDBINIT there.  */
  181.           if (gdb_datadir_provided
  182.               && datadir_len < sys_gdbinit_len
  183.               && filename_ncmp (SYSTEM_GDBINIT, GDB_DATADIR, datadir_len) == 0
  184.               && IS_DIR_SEPARATOR (SYSTEM_GDBINIT[datadir_len]))
  185.             {
  186.               /* Append the part of SYSTEM_GDBINIT that follows GDB_DATADIR
  187.                  to gdb_datadir.  */
  188.               char *tmp_sys_gdbinit = xstrdup (SYSTEM_GDBINIT + datadir_len);
  189.               char *p;

  190.               for (p = tmp_sys_gdbinit; IS_DIR_SEPARATOR (*p); ++p)
  191.                 continue;
  192.               relocated_sysgdbinit = concat (gdb_datadir, SLASH_STRING, p,
  193.                                              NULL);
  194.               xfree (tmp_sys_gdbinit);
  195.             }
  196.           else
  197.             {
  198.               relocated_sysgdbinit = relocate_path (gdb_program_name,
  199.                                                     SYSTEM_GDBINIT,
  200.                                                     SYSTEM_GDBINIT_RELOCATABLE);
  201.             }
  202.           if (relocated_sysgdbinit && stat (relocated_sysgdbinit, &s) == 0)
  203.             sysgdbinit = relocated_sysgdbinit;
  204.           else
  205.             xfree (relocated_sysgdbinit);
  206.         }

  207.       homedir = getenv ("HOME");

  208.       /* If the .gdbinit file in the current directory is the same as
  209.          the $HOME/.gdbinit file, it should not be sourced.  homebuf
  210.          and cwdbuf are used in that purpose.  Make sure that the stats
  211.          are zero in case one of them fails (this guarantees that they
  212.          won't match if either exists).  */

  213.       memset (&homebuf, 0, sizeof (struct stat));
  214.       memset (&cwdbuf, 0, sizeof (struct stat));

  215.       if (homedir)
  216.         {
  217.           homeinit = xstrprintf ("%s/%s", homedir, gdbinit);
  218.           if (stat (homeinit, &homebuf) != 0)
  219.             {
  220.               xfree (homeinit);
  221.               homeinit = NULL;
  222.             }
  223.         }

  224.       if (stat (gdbinit, &cwdbuf) == 0)
  225.         {
  226.           if (!homeinit
  227.               || memcmp ((char *) &homebuf, (char *) &cwdbuf,
  228.                          sizeof (struct stat)))
  229.             localinit = gdbinit;
  230.         }

  231.       initialized = 1;
  232.     }

  233.   *system_gdbinit = sysgdbinit;
  234.   *home_gdbinit = homeinit;
  235.   *local_gdbinit = localinit;
  236. }

  237. /* Try to set up an alternate signal stack for SIGSEGV handlers.
  238.    This allows us to handle SIGSEGV signals generated when the
  239.    normal process stack is exhausted.  If this stack is not set
  240.    up (sigaltstack is unavailable or fails) and a SIGSEGV is
  241.    generated when the normal stack is exhausted then the program
  242.    will behave as though no SIGSEGV handler was installed.  */

  243. static void
  244. setup_alternate_signal_stack (void)
  245. {
  246. #ifdef HAVE_SIGALTSTACK
  247.   stack_t ss;

  248.   ss.ss_sp = xmalloc (SIGSTKSZ);
  249.   ss.ss_size = SIGSTKSZ;
  250.   ss.ss_flags = 0;

  251.   sigaltstack(&ss, NULL);
  252. #endif
  253. }

  254. /* Call command_loop.  If it happens to return, pass that through as a
  255.    non-zero return status.  */

  256. static int
  257. captured_command_loop (void *data)
  258. {
  259.   /* Top-level execution commands can be run in the background from
  260.      here on.  */
  261.   interpreter_async = 1;

  262.   current_interp_command_loop ();
  263.   /* FIXME: cagney/1999-11-05: A correct command_loop() implementaton
  264.      would clean things up (restoring the cleanup chain) to the state
  265.      they were just prior to the call.  Technically, this means that
  266.      the do_cleanups() below is redundant.  Unfortunately, many FUNCs
  267.      are not that well behaved.  do_cleanups should either be replaced
  268.      with a do_cleanups call (to cover the problem) or an assertion
  269.      check to detect bad FUNCs code.  */
  270.   do_cleanups (all_cleanups ());
  271.   /* If the command_loop returned, normally (rather than threw an
  272.      error) we try to quit.  If the quit is aborted, catch_errors()
  273.      which called this catch the signal and restart the command
  274.      loop.  */
  275.   quit_command (NULL, instream == stdin);
  276.   return 1;
  277. }

  278. /* Handle command errors thrown from within
  279.    catch_command_errors/catch_command_errors_const.  */

  280. static int
  281. handle_command_errors (volatile struct gdb_exception e)
  282. {
  283.   if (e.reason < 0)
  284.     {
  285.       exception_print (gdb_stderr, e);

  286.       /* If any exception escaped to here, we better enable stdin.
  287.          Otherwise, any command that calls async_disable_stdin, and
  288.          then throws, will leave stdin inoperable.  */
  289.       async_enable_stdin ();
  290.       return 0;
  291.     }
  292.   return 1;
  293. }

  294. /* Type of the command callback passed to catch_command_errors.  */

  295. typedef void (catch_command_errors_ftype) (char *, int);

  296. /* Wrap calls to commands run before the event loop is started.  */

  297. static int
  298. catch_command_errors (catch_command_errors_ftype *command,
  299.                       char *arg, int from_tty, return_mask mask)
  300. {
  301.   volatile struct gdb_exception e;

  302.   TRY_CATCH (e, mask)
  303.     {
  304.       int was_sync = sync_execution;

  305.       command (arg, from_tty);

  306.       maybe_wait_sync_command_done (was_sync);
  307.     }
  308.   return handle_command_errors (e);
  309. }

  310. /* Type of the command callback passed to catch_command_errors_const.  */

  311. typedef void (catch_command_errors_const_ftype) (const char *, int);

  312. /* Like catch_command_errors, but works with const command and args.  */

  313. static int
  314. catch_command_errors_const (catch_command_errors_const_ftype *command,
  315.                             const char *arg, int from_tty, return_mask mask)
  316. {
  317.   volatile struct gdb_exception e;

  318.   TRY_CATCH (e, mask)
  319.     {
  320.       int was_sync = sync_execution;

  321.       command (arg, from_tty);

  322.       maybe_wait_sync_command_done (was_sync);
  323.     }
  324.   return handle_command_errors (e);
  325. }

  326. /* Arguments of --command option and its counterpart.  */
  327. typedef struct cmdarg {
  328.   /* Type of this option.  */
  329.   enum {
  330.     /* Option type -x.  */
  331.     CMDARG_FILE,

  332.     /* Option type -ex.  */
  333.     CMDARG_COMMAND,

  334.     /* Option type -ix.  */
  335.     CMDARG_INIT_FILE,

  336.     /* Option type -iex.  */
  337.     CMDARG_INIT_COMMAND
  338.   } type;

  339.   /* Value of this option - filename or the GDB command itself.  String memory
  340.      is not owned by this structure despite it is 'const'.  */
  341.   char *string;
  342. } cmdarg_s;

  343. /* Define type VEC (cmdarg_s).  */
  344. DEF_VEC_O (cmdarg_s);

  345. static int
  346. captured_main (void *data)
  347. {
  348.   struct captured_main_args *context = data;
  349.   int argc = context->argc;
  350.   char **argv = context->argv;
  351.   static int quiet = 0;
  352.   static int set_args = 0;
  353.   static int inhibit_home_gdbinit = 0;

  354.   /* Pointers to various arguments from command line.  */
  355.   char *symarg = NULL;
  356.   char *execarg = NULL;
  357.   char *pidarg = NULL;
  358.   char *corearg = NULL;
  359.   char *pid_or_core_arg = NULL;
  360.   char *cdarg = NULL;
  361.   char *ttyarg = NULL;

  362.   /* These are static so that we can take their address in an
  363.      initializer.  */
  364.   static int print_help;
  365.   static int print_version;
  366.   static int print_configuration;

  367.   /* Pointers to all arguments of --command option.  */
  368.   VEC (cmdarg_s) *cmdarg_vec = NULL;
  369.   struct cmdarg *cmdarg_p;

  370.   /* Indices of all arguments of --directory option.  */
  371.   char **dirarg;
  372.   /* Allocated size.  */
  373.   int dirsize;
  374.   /* Number of elements used.  */
  375.   int ndir;

  376.   /* gdb init files.  */
  377.   const char *system_gdbinit;
  378.   const char *home_gdbinit;
  379.   const char *local_gdbinit;

  380.   int i;
  381.   int save_auto_load;
  382.   struct objfile *objfile;

  383.   struct cleanup *pre_stat_chain;

  384. #ifdef HAVE_SBRK
  385.   /* Set this before calling make_command_stats_cleanup.  */
  386.   lim_at_start = (char *) sbrk (0);
  387. #endif

  388.   pre_stat_chain = make_command_stats_cleanup (0);

  389. #if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
  390.   setlocale (LC_MESSAGES, "");
  391. #endif
  392. #if defined (HAVE_SETLOCALE)
  393.   setlocale (LC_CTYPE, "");
  394. #endif
  395.   bindtextdomain (PACKAGE, LOCALEDIR);
  396.   textdomain (PACKAGE);

  397.   bfd_init ();
  398.   notice_open_fds ();

  399.   make_cleanup (VEC_cleanup (cmdarg_s), &cmdarg_vec);
  400.   dirsize = 1;
  401.   dirarg = (char **) xmalloc (dirsize * sizeof (*dirarg));
  402.   ndir = 0;

  403.   clear_quit_flag ();
  404.   saved_command_line = (char *) xmalloc (saved_command_line_size);
  405.   saved_command_line[0] = '\0';
  406.   instream = stdin;

  407. #ifdef __MINGW32__
  408.   /* Ensure stderr is unbuffered.  A Cygwin pty or pipe is implemented
  409.      as a Windows pipe, and Windows buffers on pipes.  */
  410.   setvbuf (stderr, NULL, _IONBF, BUFSIZ);
  411. #endif

  412.   gdb_stdout = stdio_fileopen (stdout);
  413.   gdb_stderr = stderr_fileopen ();

  414.   gdb_stdlog = gdb_stderr;        /* for moment */
  415.   gdb_stdtarg = gdb_stderr;        /* for moment */
  416.   gdb_stdin = stdio_fileopen (stdin);
  417.   gdb_stdtargerr = gdb_stderr;        /* for moment */
  418.   gdb_stdtargin = gdb_stdin;        /* for moment */

  419. #ifdef __MINGW32__
  420.   /* On Windows, argv[0] is not necessarily set to absolute form when
  421.      GDB is found along PATH, without which relocation doesn't work.  */
  422.   gdb_program_name = windows_get_absolute_argv0 (argv[0]);
  423. #else
  424.   gdb_program_name = xstrdup (argv[0]);
  425. #endif

  426.   /* Prefix warning messages with the command name.  */
  427.   warning_pre_print = xstrprintf ("%s: warning: ", gdb_program_name);

  428.   if (! getcwd (gdb_dirbuf, sizeof (gdb_dirbuf)))
  429.     perror_warning_with_name (_("error finding working directory"));

  430.   current_directory = gdb_dirbuf;

  431.   /* Set the sysroot path.  */
  432.   gdb_sysroot = relocate_gdb_directory (TARGET_SYSTEM_ROOT,
  433.                                         TARGET_SYSTEM_ROOT_RELOCATABLE);

  434.   debug_file_directory = relocate_gdb_directory (DEBUGDIR,
  435.                                                  DEBUGDIR_RELOCATABLE);

  436.   gdb_datadir = relocate_gdb_directory (GDB_DATADIR,
  437.                                         GDB_DATADIR_RELOCATABLE);

  438. #ifdef WITH_PYTHON_PATH
  439.   {
  440.     /* For later use in helping Python find itself.  */
  441.     char *tmp = concat (WITH_PYTHON_PATH, SLASH_STRING, "lib", NULL);

  442.     python_libdir = relocate_gdb_directory (tmp, PYTHON_PATH_RELOCATABLE);
  443.     xfree (tmp);
  444.   }
  445. #endif

  446. #ifdef RELOC_SRCDIR
  447.   add_substitute_path_rule (RELOC_SRCDIR,
  448.                             make_relative_prefix (gdb_program_name, BINDIR,
  449.                                                   RELOC_SRCDIR));
  450. #endif

  451.   /* There will always be an interpreter.  Either the one passed into
  452.      this captured main, or one specified by the user at start up, or
  453.      the console.  Initialize the interpreter to the one requested by
  454.      the application.  */
  455.   interpreter_p = xstrdup (context->interpreter_p);

  456.   /* Parse arguments and options.  */
  457.   {
  458.     int c;
  459.     /* When var field is 0, use flag field to record the equivalent
  460.        short option (or arbitrary numbers starting at 10 for those
  461.        with no equivalent).  */
  462.     enum {
  463.       OPT_SE = 10,
  464.       OPT_CD,
  465.       OPT_ANNOTATE,
  466.       OPT_STATISTICS,
  467.       OPT_TUI,
  468.       OPT_NOWINDOWS,
  469.       OPT_WINDOWS,
  470.       OPT_IX,
  471.       OPT_IEX
  472.     };
  473.     static struct option long_options[] =
  474.     {
  475.       {"tui", no_argument, 0, OPT_TUI},
  476.       {"xdb", no_argument, &xdb_commands, 1},
  477.       {"dbx", no_argument, &dbx_commands, 1},
  478.       {"readnow", no_argument, &readnow_symbol_files, 1},
  479.       {"r", no_argument, &readnow_symbol_files, 1},
  480.       {"quiet", no_argument, &quiet, 1},
  481.       {"q", no_argument, &quiet, 1},
  482.       {"silent", no_argument, &quiet, 1},
  483.       {"nh", no_argument, &inhibit_home_gdbinit, 1},
  484.       {"nx", no_argument, &inhibit_gdbinit, 1},
  485.       {"n", no_argument, &inhibit_gdbinit, 1},
  486.       {"batch-silent", no_argument, 0, 'B'},
  487.       {"batch", no_argument, &batch_flag, 1},

  488.     /* This is a synonym for "--annotate=1".  --annotate is now
  489.        preferred, but keep this here for a long time because people
  490.        will be running emacses which use --fullname.  */
  491.       {"fullname", no_argument, 0, 'f'},
  492.       {"f", no_argument, 0, 'f'},

  493.       {"annotate", required_argument, 0, OPT_ANNOTATE},
  494.       {"help", no_argument, &print_help, 1},
  495.       {"se", required_argument, 0, OPT_SE},
  496.       {"symbols", required_argument, 0, 's'},
  497.       {"s", required_argument, 0, 's'},
  498.       {"exec", required_argument, 0, 'e'},
  499.       {"e", required_argument, 0, 'e'},
  500.       {"core", required_argument, 0, 'c'},
  501.       {"c", required_argument, 0, 'c'},
  502.       {"pid", required_argument, 0, 'p'},
  503.       {"p", required_argument, 0, 'p'},
  504.       {"command", required_argument, 0, 'x'},
  505.       {"eval-command", required_argument, 0, 'X'},
  506.       {"version", no_argument, &print_version, 1},
  507.       {"configuration", no_argument, &print_configuration, 1},
  508.       {"x", required_argument, 0, 'x'},
  509.       {"ex", required_argument, 0, 'X'},
  510.       {"init-command", required_argument, 0, OPT_IX},
  511.       {"init-eval-command", required_argument, 0, OPT_IEX},
  512.       {"ix", required_argument, 0, OPT_IX},
  513.       {"iex", required_argument, 0, OPT_IEX},
  514. #ifdef GDBTK
  515.       {"tclcommand", required_argument, 0, 'z'},
  516.       {"enable-external-editor", no_argument, 0, 'y'},
  517.       {"editor-command", required_argument, 0, 'w'},
  518. #endif
  519.       {"ui", required_argument, 0, 'i'},
  520.       {"interpreter", required_argument, 0, 'i'},
  521.       {"i", required_argument, 0, 'i'},
  522.       {"directory", required_argument, 0, 'd'},
  523.       {"d", required_argument, 0, 'd'},
  524.       {"data-directory", required_argument, 0, 'D'},
  525.       {"D", required_argument, 0, 'D'},
  526.       {"cd", required_argument, 0, OPT_CD},
  527.       {"tty", required_argument, 0, 't'},
  528.       {"baud", required_argument, 0, 'b'},
  529.       {"b", required_argument, 0, 'b'},
  530.       {"nw", no_argument, NULL, OPT_NOWINDOWS},
  531.       {"nowindows", no_argument, NULL, OPT_NOWINDOWS},
  532.       {"w", no_argument, NULL, OPT_WINDOWS},
  533.       {"windows", no_argument, NULL, OPT_WINDOWS},
  534.       {"statistics", no_argument, 0, OPT_STATISTICS},
  535.       {"write", no_argument, &write_files, 1},
  536.       {"args", no_argument, &set_args, 1},
  537.       {"l", required_argument, 0, 'l'},
  538.       {"return-child-result", no_argument, &return_child_result, 1},
  539.       {0, no_argument, 0, 0}
  540.     };

  541.     while (1)
  542.       {
  543.         int option_index;

  544.         c = getopt_long_only (argc, argv, "",
  545.                               long_options, &option_index);
  546.         if (c == EOF || set_args)
  547.           break;

  548.         /* Long option that takes an argument.  */
  549.         if (c == 0 && long_options[option_index].flag == 0)
  550.           c = long_options[option_index].val;

  551.         switch (c)
  552.           {
  553.           case 0:
  554.             /* Long option that just sets a flag.  */
  555.             break;
  556.           case OPT_SE:
  557.             symarg = optarg;
  558.             execarg = optarg;
  559.             break;
  560.           case OPT_CD:
  561.             cdarg = optarg;
  562.             break;
  563.           case OPT_ANNOTATE:
  564.             /* FIXME: what if the syntax is wrong (e.g. not digits)?  */
  565.             annotation_level = atoi (optarg);
  566.             break;
  567.           case OPT_STATISTICS:
  568.             /* Enable the display of both time and space usage.  */
  569.             set_per_command_time (1);
  570.             set_per_command_space (1);
  571.             break;
  572.           case OPT_TUI:
  573.             /* --tui is equivalent to -i=tui.  */
  574. #ifdef TUI
  575.             xfree (interpreter_p);
  576.             interpreter_p = xstrdup (INTERP_TUI);
  577. #else
  578.             error (_("%s: TUI mode is not supported"), gdb_program_name);
  579. #endif
  580.             break;
  581.           case OPT_WINDOWS:
  582.             /* FIXME: cagney/2003-03-01: Not sure if this option is
  583.                actually useful, and if it is, what it should do.  */
  584. #ifdef GDBTK
  585.             /* --windows is equivalent to -i=insight.  */
  586.             xfree (interpreter_p);
  587.             interpreter_p = xstrdup (INTERP_INSIGHT);
  588. #endif
  589.             break;
  590.           case OPT_NOWINDOWS:
  591.             /* -nw is equivalent to -i=console.  */
  592.             xfree (interpreter_p);
  593.             interpreter_p = xstrdup (INTERP_CONSOLE);
  594.             break;
  595.           case 'f':
  596.             annotation_level = 1;
  597.             break;
  598.           case 's':
  599.             symarg = optarg;
  600.             break;
  601.           case 'e':
  602.             execarg = optarg;
  603.             break;
  604.           case 'c':
  605.             corearg = optarg;
  606.             break;
  607.           case 'p':
  608.             pidarg = optarg;
  609.             break;
  610.           case 'x':
  611.             {
  612.               struct cmdarg cmdarg = { CMDARG_FILE, optarg };

  613.               VEC_safe_push (cmdarg_s, cmdarg_vec, &cmdarg);
  614.             }
  615.             break;
  616.           case 'X':
  617.             {
  618.               struct cmdarg cmdarg = { CMDARG_COMMAND, optarg };

  619.               VEC_safe_push (cmdarg_s, cmdarg_vec, &cmdarg);
  620.             }
  621.             break;
  622.           case OPT_IX:
  623.             {
  624.               struct cmdarg cmdarg = { CMDARG_INIT_FILE, optarg };

  625.               VEC_safe_push (cmdarg_s, cmdarg_vec, &cmdarg);
  626.             }
  627.             break;
  628.           case OPT_IEX:
  629.             {
  630.               struct cmdarg cmdarg = { CMDARG_INIT_COMMAND, optarg };

  631.               VEC_safe_push (cmdarg_s, cmdarg_vec, &cmdarg);
  632.             }
  633.             break;
  634.           case 'B':
  635.             batch_flag = batch_silent = 1;
  636.             gdb_stdout = ui_file_new();
  637.             break;
  638.           case 'D':
  639.             if (optarg[0] == '\0')
  640.               error (_("%s: empty path for `--data-directory'"),
  641.                      gdb_program_name);
  642.             set_gdb_data_directory (optarg);
  643.             gdb_datadir_provided = 1;
  644.             break;
  645. #ifdef GDBTK
  646.           case 'z':
  647.             {
  648.               extern int gdbtk_test (char *);

  649.               if (!gdbtk_test (optarg))
  650.                 error (_("%s: unable to load tclcommand file \"%s\""),
  651.                        gdb_program_name, optarg);
  652.               break;
  653.             }
  654.           case 'y':
  655.             /* Backwards compatibility only.  */
  656.             break;
  657.           case 'w':
  658.             {
  659.               /* Set the external editor commands when gdb is farming out files
  660.                  to be edited by another program.  */
  661.               extern char *external_editor_command;

  662.               external_editor_command = xstrdup (optarg);
  663.               break;
  664.             }
  665. #endif /* GDBTK */
  666.           case 'i':
  667.             xfree (interpreter_p);
  668.             interpreter_p = xstrdup (optarg);
  669.             break;
  670.           case 'd':
  671.             dirarg[ndir++] = optarg;
  672.             if (ndir >= dirsize)
  673.               {
  674.                 dirsize *= 2;
  675.                 dirarg = (char **) xrealloc ((char *) dirarg,
  676.                                              dirsize * sizeof (*dirarg));
  677.               }
  678.             break;
  679.           case 't':
  680.             ttyarg = optarg;
  681.             break;
  682.           case 'q':
  683.             quiet = 1;
  684.             break;
  685.           case 'b':
  686.             {
  687.               int i;
  688.               char *p;

  689.               i = strtol (optarg, &p, 0);
  690.               if (i == 0 && p == optarg)
  691.                 warning (_("could not set baud rate to `%s'."),
  692.                          optarg);
  693.               else
  694.                 baud_rate = i;
  695.             }
  696.             break;
  697.           case 'l':
  698.             {
  699.               int i;
  700.               char *p;

  701.               i = strtol (optarg, &p, 0);
  702.               if (i == 0 && p == optarg)
  703.                 warning (_("could not set timeout limit to `%s'."),
  704.                          optarg);
  705.               else
  706.                 remote_timeout = i;
  707.             }
  708.             break;

  709.           case '?':
  710.             error (_("Use `%s --help' for a complete list of options."),
  711.                    gdb_program_name);
  712.           }
  713.       }

  714.     if (batch_flag)
  715.       quiet = 1;
  716.   }

  717.   /* Try to set up an alternate signal stack for SIGSEGV handlers.  */
  718.   setup_alternate_signal_stack ();

  719.   /* Initialize all files.  Give the interpreter a chance to take
  720.      control of the console via the deprecated_init_ui_hook ().  */
  721.   gdb_init (gdb_program_name);

  722.   /* Now that gdb_init has created the initial inferior, we're in
  723.      position to set args for that inferior.  */
  724.   if (set_args)
  725.     {
  726.       /* The remaining options are the command-line options for the
  727.          inferior.  The first one is the sym/exec file, and the rest
  728.          are arguments.  */
  729.       if (optind >= argc)
  730.         error (_("%s: `--args' specified but no program specified"),
  731.                gdb_program_name);

  732.       symarg = argv[optind];
  733.       execarg = argv[optind];
  734.       ++optind;
  735.       set_inferior_args_vector (argc - optind, &argv[optind]);
  736.     }
  737.   else
  738.     {
  739.       /* OK, that's all the options.  */

  740.       /* The first argument, if specified, is the name of the
  741.          executable.  */
  742.       if (optind < argc)
  743.         {
  744.           symarg = argv[optind];
  745.           execarg = argv[optind];
  746.           optind++;
  747.         }

  748.       /* If the user hasn't already specified a PID or the name of a
  749.          core file, then a second optional argument is allowed.  If
  750.          present, this argument should be interpreted as either a
  751.          PID or a core file, whichever works.  */
  752.       if (pidarg == NULL && corearg == NULL && optind < argc)
  753.         {
  754.           pid_or_core_arg = argv[optind];
  755.           optind++;
  756.         }

  757.       /* Any argument left on the command line is unexpected and
  758.          will be ignored.  Inform the user.  */
  759.       if (optind < argc)
  760.         fprintf_unfiltered (gdb_stderr,
  761.                             _("Excess command line "
  762.                               "arguments ignored. (%s%s)\n"),
  763.                             argv[optind],
  764.                             (optind == argc - 1) ? "" : " ...");
  765.     }

  766.   /* Lookup gdbinit files.  Note that the gdbinit file name may be
  767.      overriden during file initialization, so get_init_files should be
  768.      called after gdb_init.  */
  769.   get_init_files (&system_gdbinit, &home_gdbinit, &local_gdbinit);

  770.   /* Do these (and anything which might call wrap_here or *_filtered)
  771.      after initialize_all_files() but before the interpreter has been
  772.      installed.  Otherwize the help/version messages will be eaten by
  773.      the interpreter's output handler.  */

  774.   if (print_version)
  775.     {
  776.       print_gdb_version (gdb_stdout);
  777.       wrap_here ("");
  778.       printf_filtered ("\n");
  779.       exit (0);
  780.     }

  781.   if (print_help)
  782.     {
  783.       print_gdb_help (gdb_stdout);
  784.       fputs_unfiltered ("\n", gdb_stdout);
  785.       exit (0);
  786.     }

  787.   if (print_configuration)
  788.     {
  789.       print_gdb_configuration (gdb_stdout);
  790.       wrap_here ("");
  791.       printf_filtered ("\n");
  792.       exit (0);
  793.     }

  794.   /* FIXME: cagney/2003-02-03: The big hack (part 1 of 2) that lets
  795.      GDB retain the old MI1 interpreter startup behavior.  Output the
  796.      copyright message before the interpreter is installed.  That way
  797.      it isn't encapsulated in MI output.  */
  798.   if (!quiet && strcmp (interpreter_p, INTERP_MI1) == 0)
  799.     {
  800.       /* Print all the junk at the top, with trailing "..." if we are
  801.          about to read a symbol file (possibly slowly).  */
  802.       print_gdb_version (gdb_stdout);
  803.       if (symarg)
  804.         printf_filtered ("..");
  805.       wrap_here ("");
  806.       printf_filtered ("\n");
  807.       gdb_flush (gdb_stdout);        /* Force to screen during slow
  808.                                    operations.  */
  809.     }

  810.   /* Install the default UI.  All the interpreters should have had a
  811.      look at things by now.  Initialize the default interpreter.  */

  812.   {
  813.     /* Find it.  */
  814.     struct interp *interp = interp_lookup (interpreter_p);

  815.     if (interp == NULL)
  816.       error (_("Interpreter `%s' unrecognized"), interpreter_p);
  817.     /* Install it.  */
  818.     if (!interp_set (interp, 1))
  819.       error (_("Interpreter `%s' failed to initialize."), interpreter_p);
  820.   }

  821.   /* FIXME: cagney/2003-02-03: The big hack (part 2 of 2) that lets
  822.      GDB retain the old MI1 interpreter startup behavior.  Output the
  823.      copyright message after the interpreter is installed when it is
  824.      any sane interpreter.  */
  825.   if (!quiet && !current_interp_named_p (INTERP_MI1))
  826.     {
  827.       /* Print all the junk at the top, with trailing "..." if we are
  828.          about to read a symbol file (possibly slowly).  */
  829.       print_gdb_version (gdb_stdout);
  830.       if (symarg)
  831.         printf_filtered ("..");
  832.       wrap_here ("");
  833.       printf_filtered ("\n");
  834.       gdb_flush (gdb_stdout);        /* Force to screen during slow
  835.                                    operations.  */
  836.     }

  837.   /* Set off error and warning messages with a blank line.  */
  838.   xfree (warning_pre_print);
  839.   warning_pre_print = _("\nwarning: ");

  840.   /* Read and execute the system-wide gdbinit file, if it exists.
  841.      This is done *before* all the command line arguments are
  842.      processed; it sets global parameters, which are independent of
  843.      what file you are debugging or what directory you are in.  */
  844.   if (system_gdbinit && !inhibit_gdbinit)
  845.     catch_command_errors_const (source_script, system_gdbinit,
  846.                                 0, RETURN_MASK_ALL);

  847.   /* Read and execute $HOME/.gdbinit file, if it exists.  This is done
  848.      *before* all the command line arguments are processed; it sets
  849.      global parameters, which are independent of what file you are
  850.      debugging or what directory you are in.  */

  851.   if (home_gdbinit && !inhibit_gdbinit && !inhibit_home_gdbinit)
  852.     catch_command_errors_const (source_script,
  853.                                 home_gdbinit, 0, RETURN_MASK_ALL);

  854.   /* Process '-ix' and '-iex' options early.  */
  855.   for (i = 0; VEC_iterate (cmdarg_s, cmdarg_vec, i, cmdarg_p); i++)
  856.     switch (cmdarg_p->type)
  857.     {
  858.       case CMDARG_INIT_FILE:
  859.         catch_command_errors_const (source_script, cmdarg_p->string,
  860.                                     !batch_flag, RETURN_MASK_ALL);
  861.         break;
  862.       case CMDARG_INIT_COMMAND:
  863.         catch_command_errors (execute_command, cmdarg_p->string,
  864.                               !batch_flag, RETURN_MASK_ALL);
  865.         break;
  866.     }

  867.   /* Now perform all the actions indicated by the arguments.  */
  868.   if (cdarg != NULL)
  869.     {
  870.       catch_command_errors (cd_command, cdarg, 0, RETURN_MASK_ALL);
  871.     }

  872.   for (i = 0; i < ndir; i++)
  873.     catch_command_errors (directory_switch, dirarg[i], 0, RETURN_MASK_ALL);
  874.   xfree (dirarg);

  875.   /* Skip auto-loading section-specified scripts until we've sourced
  876.      local_gdbinit (which is often used to augment the source search
  877.      path).  */
  878.   save_auto_load = global_auto_load;
  879.   global_auto_load = 0;

  880.   if (execarg != NULL
  881.       && symarg != NULL
  882.       && strcmp (execarg, symarg) == 0)
  883.     {
  884.       /* The exec file and the symbol-file are the same.  If we can't
  885.          open it, better only print one error message.
  886.          catch_command_errors returns non-zero on success!  */
  887.       if (catch_command_errors_const (exec_file_attach, execarg,
  888.                                       !batch_flag, RETURN_MASK_ALL))
  889.         catch_command_errors_const (symbol_file_add_main, symarg,
  890.                                     !batch_flag, RETURN_MASK_ALL);
  891.     }
  892.   else
  893.     {
  894.       if (execarg != NULL)
  895.         catch_command_errors_const (exec_file_attach, execarg,
  896.                                     !batch_flag, RETURN_MASK_ALL);
  897.       if (symarg != NULL)
  898.         catch_command_errors_const (symbol_file_add_main, symarg,
  899.                                     !batch_flag, RETURN_MASK_ALL);
  900.     }

  901.   if (corearg && pidarg)
  902.     error (_("Can't attach to process and specify "
  903.              "a core file at the same time."));

  904.   if (corearg != NULL)
  905.     catch_command_errors (core_file_command, corearg,
  906.                           !batch_flag, RETURN_MASK_ALL);
  907.   else if (pidarg != NULL)
  908.     catch_command_errors (attach_command, pidarg,
  909.                           !batch_flag, RETURN_MASK_ALL);
  910.   else if (pid_or_core_arg)
  911.     {
  912.       /* The user specified 'gdb program pid' or gdb program core'.
  913.          If pid_or_core_arg's first character is a digit, try attach
  914.          first and then corefile.  Otherwise try just corefile.  */

  915.       if (isdigit (pid_or_core_arg[0]))
  916.         {
  917.           if (catch_command_errors (attach_command, pid_or_core_arg,
  918.                                     !batch_flag, RETURN_MASK_ALL) == 0)
  919.             catch_command_errors (core_file_command, pid_or_core_arg,
  920.                                   !batch_flag, RETURN_MASK_ALL);
  921.         }
  922.       else /* Can't be a pid, better be a corefile.  */
  923.         catch_command_errors (core_file_command, pid_or_core_arg,
  924.                               !batch_flag, RETURN_MASK_ALL);
  925.     }

  926.   if (ttyarg != NULL)
  927.     set_inferior_io_terminal (ttyarg);

  928.   /* Error messages should no longer be distinguished with extra output.  */
  929.   warning_pre_print = _("warning: ");

  930.   /* Read the .gdbinit file in the current directory, *if* it isn't
  931.      the same as the $HOME/.gdbinit file (it should exist, also).  */
  932.   if (local_gdbinit)
  933.     {
  934.       auto_load_local_gdbinit_pathname = gdb_realpath (local_gdbinit);

  935.       if (!inhibit_gdbinit && auto_load_local_gdbinit
  936.           && file_is_auto_load_safe (local_gdbinit,
  937.                                      _("auto-load: Loading .gdbinit "
  938.                                        "file \"%s\".\n"),
  939.                                      local_gdbinit))
  940.         {
  941.           auto_load_local_gdbinit_loaded = 1;

  942.           catch_command_errors_const (source_script, local_gdbinit, 0,
  943.                                       RETURN_MASK_ALL);
  944.         }
  945.     }

  946.   /* Now that all .gdbinit's have been read and all -d options have been
  947.      processed, we can read any scripts mentioned in SYMARG.
  948.      We wait until now because it is common to add to the source search
  949.      path in local_gdbinit.  */
  950.   global_auto_load = save_auto_load;
  951.   ALL_OBJFILES (objfile)
  952.     load_auto_scripts_for_objfile (objfile);

  953.   /* Process '-x' and '-ex' options.  */
  954.   for (i = 0; VEC_iterate (cmdarg_s, cmdarg_vec, i, cmdarg_p); i++)
  955.     switch (cmdarg_p->type)
  956.     {
  957.       case CMDARG_FILE:
  958.         catch_command_errors_const (source_script, cmdarg_p->string,
  959.                                     !batch_flag, RETURN_MASK_ALL);
  960.         break;
  961.       case CMDARG_COMMAND:
  962.         catch_command_errors (execute_command, cmdarg_p->string,
  963.                               !batch_flag, RETURN_MASK_ALL);
  964.         break;
  965.     }

  966.   /* Read in the old history after all the command files have been
  967.      read.  */
  968.   init_history ();

  969.   if (batch_flag)
  970.     {
  971.       /* We have hit the end of the batch file.  */
  972.       quit_force (NULL, 0);
  973.     }

  974.   /* Show time and/or space usage.  */
  975.   do_cleanups (pre_stat_chain);

  976.   /* NOTE: cagney/1999-11-07: There is probably no reason for not
  977.      moving this loop and the code found in captured_command_loop()
  978.      into the command_loop() proper.  The main thing holding back that
  979.      change - SET_TOP_LEVEL() - has been eliminated.  */
  980.   while (1)
  981.     {
  982.       catch_errors (captured_command_loop, 0, "", RETURN_MASK_ALL);
  983.     }
  984.   /* No exit -- exit is through quit_command.  */
  985. }

  986. int
  987. gdb_main (struct captured_main_args *args)
  988. {
  989.   catch_errors (captured_main, args, "", RETURN_MASK_ALL);
  990.   /* The only way to end up here is by an error (normal exit is
  991.      handled by quit_force()), hence always return an error status.  */
  992.   return 1;
  993. }


  994. /* Don't use *_filtered for printing help.  We don't want to prompt
  995.    for continue no matter how small the screen or how much we're going
  996.    to print.  */

  997. static void
  998. print_gdb_help (struct ui_file *stream)
  999. {
  1000.   const char *system_gdbinit;
  1001.   const char *home_gdbinit;
  1002.   const char *local_gdbinit;

  1003.   get_init_files (&system_gdbinit, &home_gdbinit, &local_gdbinit);

  1004.   /* Note: The options in the list below are only approximately sorted
  1005.      in the alphabetical order, so as to group closely related options
  1006.      together.  */
  1007.   fputs_unfiltered (_("\
  1008. This is the GNU debugger.  Usage:\n\n\
  1009.     gdb [options] [executable-file [core-file or process-id]]\n\
  1010.     gdb [options] --args executable-file [inferior-arguments ...]\n\n\
  1011. "), stream);
  1012.   fputs_unfiltered (_("\
  1013. Selection of debuggee and its files:\n\n\
  1014.   --args             Arguments after executable-file are passed to inferior\n\
  1015.   --core=COREFILE    Analyze the core dump COREFILE.\n\
  1016.   --exec=EXECFILE    Use EXECFILE as the executable.\n\
  1017.   --pid=PID          Attach to running process PID.\n\
  1018.   --directory=DIR    Search for source files in DIR.\n\
  1019.   --se=FILE          Use FILE as symbol file and executable file.\n\
  1020.   --symbols=SYMFILE  Read symbols from SYMFILE.\n\
  1021.   --readnow          Fully read symbol files on first access.\n\
  1022.   --write            Set writing into executable and core files.\n\n\
  1023. "), stream);
  1024.   fputs_unfiltered (_("\
  1025. Initial commands and command files:\n\n\
  1026.   --command=FILE, -x Execute GDB commands from FILE.\n\
  1027.   --init-command=FILE, -ix\n\
  1028.                      Like -x but execute commands before loading inferior.\n\
  1029.   --eval-command=COMMAND, -ex\n\
  1030.                      Execute a single GDB command.\n\
  1031.                      May be used multiple times and in conjunction\n\
  1032.                      with --command.\n\
  1033.   --init-eval-command=COMMAND, -iex\n\
  1034.                      Like -ex but before loading inferior.\n\
  1035.   --nh               Do not read ~/.gdbinit.\n\
  1036.   --nx               Do not read any .gdbinit files in any directory.\n\n\
  1037. "), stream);
  1038.   fputs_unfiltered (_("\
  1039. Output and user interface control:\n\n\
  1040.   --fullname         Output information used by emacs-GDB interface.\n\
  1041.   --interpreter=INTERP\n\
  1042.                      Select a specific interpreter / user interface\n\
  1043.   --tty=TTY          Use TTY for input/output by the program being debugged.\n\
  1044.   -w                 Use the GUI interface.\n\
  1045.   --nw               Do not use the GUI interface.\n\
  1046. "), stream);
  1047. #if defined(TUI)
  1048.   fputs_unfiltered (_("\
  1049.   --tui              Use a terminal user interface.\n\
  1050. "), stream);
  1051. #endif
  1052.   fputs_unfiltered (_("\
  1053.   --dbx              DBX compatibility mode.\n\
  1054.   --xdb              XDB compatibility mode.\n\
  1055.   -q, --quiet, --silent\n\
  1056.                      Do not print version number on startup.\n\n\
  1057. "), stream);
  1058.   fputs_unfiltered (_("\
  1059. Operating modes:\n\n\
  1060.   --batch            Exit after processing options.\n\
  1061.   --batch-silent     Like --batch, but suppress all gdb stdout output.\n\
  1062.   --return-child-result\n\
  1063.                      GDB exit code will be the child's exit code.\n\
  1064.   --configuration    Print details about GDB configuration and then exit.\n\
  1065.   --help             Print this message and then exit.\n\
  1066.   --version          Print version information and then exit.\n\n\
  1067. Remote debugging options:\n\n\
  1068.   -b BAUDRATE        Set serial port baud rate used for remote debugging.\n\
  1069.   -l TIMEOUT         Set timeout in seconds for remote debugging.\n\n\
  1070. Other options:\n\n\
  1071.   --cd=DIR           Change current directory to DIR.\n\
  1072.   --data-directory=DIR, -D\n\
  1073.                      Set GDB's data-directory to DIR.\n\
  1074. "), stream);
  1075.   fputs_unfiltered (_("\n\
  1076. At startup, GDB reads the following init files and executes their commands:\n\
  1077. "), stream);
  1078.   if (system_gdbinit)
  1079.     fprintf_unfiltered (stream, _("\
  1080.    * system-wide init file: %s\n\
  1081. "), system_gdbinit);
  1082.   if (home_gdbinit)
  1083.     fprintf_unfiltered (stream, _("\
  1084.    * user-specific init file: %s\n\
  1085. "), home_gdbinit);
  1086.   if (local_gdbinit)
  1087.     fprintf_unfiltered (stream, _("\
  1088.    * local init file (see also 'set auto-load local-gdbinit'): ./%s\n\
  1089. "), local_gdbinit);
  1090.   fputs_unfiltered (_("\n\
  1091. For more information, type \"help\" from within GDB, or consult the\n\
  1092. GDB manual (available as on-line info or a printed manual).\n\
  1093. "), stream);
  1094.   if (REPORT_BUGS_TO[0] && stream == gdb_stdout)
  1095.     fprintf_unfiltered (stream, _("\
  1096. Report bugs to \"%s\".\n\
  1097. "), REPORT_BUGS_TO);
  1098. }