gdb/top.c - gdb

Global variables defined

Data types defined

Functions defined

Macros 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 "gdbcmd.h"
  16. #include "cli/cli-cmds.h"
  17. #include "cli/cli-script.h"
  18. #include "cli/cli-setshow.h"
  19. #include "cli/cli-decode.h"
  20. #include "symtab.h"
  21. #include "inferior.h"
  22. #include "infrun.h"
  23. #include <signal.h>
  24. #include "target.h"
  25. #include "target-dcache.h"
  26. #include "breakpoint.h"
  27. #include "gdbtypes.h"
  28. #include "expression.h"
  29. #include "value.h"
  30. #include "language.h"
  31. #include "terminal.h"                /* For job_control.  */
  32. #include "annotate.h"
  33. #include "completer.h"
  34. #include "top.h"
  35. #include "version.h"
  36. #include "serial.h"
  37. #include "doublest.h"
  38. #include "main.h"
  39. #include "event-loop.h"
  40. #include "gdbthread.h"
  41. #include "extension.h"
  42. #include "interps.h"
  43. #include "observer.h"
  44. #include "maint.h"
  45. #include "filenames.h"

  46. /* readline include files.  */
  47. #include "readline/readline.h"
  48. #include "readline/history.h"

  49. /* readline defines this.  */
  50. #undef savestring

  51. #include <sys/types.h>

  52. #include "event-top.h"
  53. #include <sys/stat.h>
  54. #include <ctype.h>
  55. #include "ui-out.h"
  56. #include "cli-out.h"
  57. #include "tracepoint.h"
  58. #include "inf-loop.h"

  59. extern void initialize_all_files (void);

  60. #define PROMPT(X) the_prompts.prompt_stack[the_prompts.top + X].prompt
  61. #define PREFIX(X) the_prompts.prompt_stack[the_prompts.top + X].prefix
  62. #define SUFFIX(X) the_prompts.prompt_stack[the_prompts.top + X].suffix

  63. /* Default command line prompt.  This is overriden in some configs.  */

  64. #ifndef DEFAULT_PROMPT
  65. #define DEFAULT_PROMPT        "(gdb) "
  66. #endif

  67. /* Initialization file name for gdb.  This is host-dependent.  */

  68. const char gdbinit[] = GDBINIT;

  69. int inhibit_gdbinit = 0;

  70. extern char lang_frame_mismatch_warn[];                /* language.c */

  71. /* Flag for whether we want to confirm potentially dangerous
  72.    operations.  Default is yes.  */

  73. int confirm = 1;

  74. static void
  75. show_confirm (struct ui_file *file, int from_tty,
  76.               struct cmd_list_element *c, const char *value)
  77. {
  78.   fprintf_filtered (file, _("Whether to confirm potentially "
  79.                             "dangerous operations is %s.\n"),
  80.                     value);
  81. }

  82. /* stdio stream that command input is being read from.  Set to stdin
  83.    normally.  Set by source_command to the file we are sourcing.  Set
  84.    to NULL if we are executing a user-defined command or interacting
  85.    via a GUI.  */

  86. FILE *instream;

  87. /* Flag to indicate whether a user defined command is currently running.  */

  88. int in_user_command;

  89. /* Current working directory.  */

  90. char *current_directory;

  91. /* The directory name is actually stored here (usually).  */
  92. char gdb_dirbuf[1024];

  93. /* Function to call before reading a command, if nonzero.
  94.    The function receives two args: an input stream,
  95.    and a prompt string.  */

  96. void (*window_hook) (FILE *, char *);

  97. /* Buffer used for reading command lines, and the size
  98.    allocated for it so far.  */

  99. char *saved_command_line;
  100. int saved_command_line_size = 100;

  101. /* Nonzero if the current command is modified by "server ".  This
  102.    affects things like recording into the command history, commands
  103.    repeating on RETURN, etc.  This is so a user interface (emacs, GUI,
  104.    whatever) can issue its own commands and also send along commands
  105.    from the user, and have the user not notice that the user interface
  106.    is issuing commands too.  */
  107. int server_command;

  108. /* Timeout limit for response from target.  */

  109. /* The default value has been changed many times over the years.  It
  110.    was originally 5 seconds.  But that was thought to be a long time
  111.    to sit and wait, so it was changed to 2 seconds.  That was thought
  112.    to be plenty unless the connection was going through some terminal
  113.    server or multiplexer or other form of hairy serial connection.

  114.    In mid-1996, remote_timeout was moved from remote.c to top.c and
  115.    it began being used in other remote-* targets.  It appears that the
  116.    default was changed to 20 seconds at that time, perhaps because the
  117.    Renesas E7000 ICE didn't always respond in a timely manner.

  118.    But if 5 seconds is a long time to sit and wait for retransmissions,
  119.    20 seconds is far worse.  This demonstrates the difficulty of using
  120.    a single variable for all protocol timeouts.

  121.    As remote.c is used much more than remote-e7000.c, it was changed
  122.    back to 2 seconds in 1999.  */

  123. int remote_timeout = 2;

  124. /* Non-zero tells remote* modules to output debugging info.  */

  125. int remote_debug = 0;

  126. /* Sbrk location on entry to main.  Used for statistics only.  */
  127. #ifdef HAVE_SBRK
  128. char *lim_at_start;
  129. #endif

  130. /* Hooks for alternate command interfaces.  */

  131. /* Called after most modules have been initialized, but before taking
  132.    users command file.

  133.    If the UI fails to initialize and it wants GDB to continue using
  134.    the default UI, then it should clear this hook before returning.  */

  135. void (*deprecated_init_ui_hook) (char *argv0);

  136. /* This hook is called from within gdb's many mini-event loops which
  137.    could steal control from a real user interface's event loop.  It
  138.    returns non-zero if the user is requesting a detach, zero
  139.    otherwise.  */

  140. int (*deprecated_ui_loop_hook) (int);


  141. /* Called from print_frame_info to list the line we stopped in.  */

  142. void (*deprecated_print_frame_info_listing_hook) (struct symtab * s,
  143.                                                   int line,
  144.                                                   int stopline,
  145.                                                   int noerror);
  146. /* Replaces most of query.  */

  147. int (*deprecated_query_hook) (const char *, va_list);

  148. /* Replaces most of warning.  */

  149. void (*deprecated_warning_hook) (const char *, va_list);

  150. /* These three functions support getting lines of text from the user.
  151.    They are used in sequence.  First deprecated_readline_begin_hook is
  152.    called with a text string that might be (for example) a message for
  153.    the user to type in a sequence of commands to be executed at a
  154.    breakpoint.  If this function calls back to a GUI, it might take
  155.    this opportunity to pop up a text interaction window with this
  156.    message.  Next, deprecated_readline_hook is called with a prompt
  157.    that is emitted prior to collecting the user input.  It can be
  158.    called multiple times.  Finally, deprecated_readline_end_hook is
  159.    called to notify the GUI that we are done with the interaction
  160.    window and it can close it.  */

  161. void (*deprecated_readline_begin_hook) (char *, ...);
  162. char *(*deprecated_readline_hook) (const char *);
  163. void (*deprecated_readline_end_hook) (void);

  164. /* Called as appropriate to notify the interface that we have attached
  165.    to or detached from an already running process.  */

  166. void (*deprecated_attach_hook) (void);
  167. void (*deprecated_detach_hook) (void);

  168. /* Called during long calculations to allow GUI to repair window
  169.    damage, and to check for stop buttons, etc...  */

  170. void (*deprecated_interactive_hook) (void);

  171. /* Tell the GUI someone changed the register REGNO.  -1 means
  172.    that the caller does not know which register changed or
  173.    that several registers have changed (see value_assign).  */
  174. void (*deprecated_register_changed_hook) (int regno);

  175. /* Called when going to wait for the target.  Usually allows the GUI
  176.    to run while waiting for target events.  */

  177. ptid_t (*deprecated_target_wait_hook) (ptid_t ptid,
  178.                                        struct target_waitstatus *status,
  179.                                        int options);

  180. /* Used by UI as a wrapper around command execution.  May do various
  181.    things like enabling/disabling buttons, etc...  */

  182. void (*deprecated_call_command_hook) (struct cmd_list_element * c,
  183.                                       char *cmd, int from_tty);

  184. /* Called when the current thread changes.  Argument is thread id.  */

  185. void (*deprecated_context_hook) (int id);

  186. /* Handler for SIGHUP.  */

  187. #ifdef SIGHUP
  188. /* NOTE 1999-04-29: This function will be static again, once we modify
  189.    gdb to use the event loop as the default command loop and we merge
  190.    event-top.c into this file, top.c.  */
  191. /* static */ void
  192. quit_cover (void)
  193. {
  194.   /* Stop asking user for confirmation --- we're exiting.  This
  195.      prevents asking the user dumb questions.  */
  196.   confirm = 0;
  197.   quit_command ((char *) 0, 0);
  198. }
  199. #endif /* defined SIGHUP */

  200. /* Line number we are currently in, in a file which is being sourced.  */
  201. /* NOTE 1999-04-29: This variable will be static again, once we modify
  202.    gdb to use the event loop as the default command loop and we merge
  203.    event-top.c into this file, top.c.  */
  204. /* static */ int source_line_number;

  205. /* Name of the file we are sourcing.  */
  206. /* NOTE 1999-04-29: This variable will be static again, once we modify
  207.    gdb to use the event loop as the default command loop and we merge
  208.    event-top.c into this file, top.c.  */
  209. /* static */ const char *source_file_name;

  210. /* Clean up on error during a "source" command (or execution of a
  211.    user-defined command).  */

  212. void
  213. do_restore_instream_cleanup (void *stream)
  214. {
  215.   /* Restore the previous input stream.  */
  216.   instream = stream;
  217. }

  218. /* Read commands from STREAM.  */
  219. void
  220. read_command_file (FILE *stream)
  221. {
  222.   struct cleanup *cleanups;

  223.   cleanups = make_cleanup (do_restore_instream_cleanup, instream);
  224.   instream = stream;
  225.   command_loop ();
  226.   do_cleanups (cleanups);
  227. }

  228. void (*pre_init_ui_hook) (void);

  229. #ifdef __MSDOS__
  230. static void
  231. do_chdir_cleanup (void *old_dir)
  232. {
  233.   chdir (old_dir);
  234.   xfree (old_dir);
  235. }
  236. #endif

  237. struct cleanup *
  238. prepare_execute_command (void)
  239. {
  240.   struct value *mark;
  241.   struct cleanup *cleanup;

  242.   mark = value_mark ();
  243.   cleanup = make_cleanup_value_free_to_mark (mark);

  244.   /* With multiple threads running while the one we're examining is
  245.      stopped, the dcache can get stale without us being able to detect
  246.      it.  For the duration of the command, though, use the dcache to
  247.      help things like backtrace.  */
  248.   if (non_stop)
  249.     target_dcache_invalidate ();

  250.   return cleanup;
  251. }

  252. /* Tell the user if the language has changed (except first time) after
  253.    executing a command.  */

  254. void
  255. check_frame_language_change (void)
  256. {
  257.   static int warned = 0;

  258.   /* First make sure that a new frame has been selected, in case the
  259.      command or the hooks changed the program state.  */
  260.   deprecated_safe_get_selected_frame ();
  261.   if (current_language != expected_language)
  262.     {
  263.       if (language_mode == language_mode_auto && info_verbose)
  264.         {
  265.           language_info (1);        /* Print what changed.  */
  266.         }
  267.       warned = 0;
  268.     }

  269.   /* Warn the user if the working language does not match the language
  270.      of the current frame.  Only warn the user if we are actually
  271.      running the program, i.e. there is a stack.  */
  272.   /* FIXME: This should be cacheing the frame and only running when
  273.      the frame changes.  */

  274.   if (has_stack_frames ())
  275.     {
  276.       enum language flang;

  277.       flang = get_frame_language ();
  278.       if (!warned
  279.           && flang != language_unknown
  280.           && flang != current_language->la_language)
  281.         {
  282.           printf_filtered ("%s\n", lang_frame_mismatch_warn);
  283.           warned = 1;
  284.         }
  285.     }
  286. }

  287. /* See top.h.  */

  288. void
  289. maybe_wait_sync_command_done (int was_sync)
  290. {
  291.   /* If the interpreter is in sync mode (we're running a user
  292.      command's list, running command hooks or similars), and we
  293.      just ran a synchronous command that started the target, wait
  294.      for that command to end.  */
  295.   if (!interpreter_async && !was_sync && sync_execution)
  296.     {
  297.       while (gdb_do_one_event () >= 0)
  298.         if (!sync_execution)
  299.           break;
  300.     }
  301. }

  302. /* Execute the line P as a command, in the current user context.
  303.    Pass FROM_TTY as second argument to the defining function.  */

  304. void
  305. execute_command (char *p, int from_tty)
  306. {
  307.   struct cleanup *cleanup_if_error, *cleanup;
  308.   struct cmd_list_element *c;
  309.   char *line;

  310.   cleanup_if_error = make_bpstat_clear_actions_cleanup ();
  311.   cleanup = prepare_execute_command ();

  312.   /* Force cleanup of any alloca areas if using C alloca instead of
  313.      a builtin alloca.  */
  314.   alloca (0);

  315.   /* This can happen when command_line_input hits end of file.  */
  316.   if (p == NULL)
  317.     {
  318.       do_cleanups (cleanup);
  319.       discard_cleanups (cleanup_if_error);
  320.       return;
  321.     }

  322.   target_log_command (p);

  323.   while (*p == ' ' || *p == '\t')
  324.     p++;
  325.   if (*p)
  326.     {
  327.       const char *cmd = p;
  328.       char *arg;
  329.       int was_sync = sync_execution;

  330.       line = p;

  331.       /* If trace-commands is set then this will print this command.  */
  332.       print_command_trace (p);

  333.       c = lookup_cmd (&cmd, cmdlist, "", 0, 1);
  334.       p = (char *) cmd;

  335.       /* Pass null arg rather than an empty one.  */
  336.       arg = *p ? p : 0;

  337.       /* FIXME: cagney/2002-02-02: The c->type test is pretty dodgy
  338.          while the is_complete_command(cfunc) test is just plain
  339.          bogus.  They should both be replaced by a test of the form
  340.          c->strip_trailing_white_space_p.  */
  341.       /* NOTE: cagney/2002-02-02: The function.cfunc in the below
  342.          can't be replaced with func.  This is because it is the
  343.          cfunc, and not the func, that has the value that the
  344.          is_complete_command hack is testing for.  */
  345.       /* Clear off trailing whitespace, except for set and complete
  346.          command.  */
  347.       if (arg
  348.           && c->type != set_cmd
  349.           && !is_complete_command (c))
  350.         {
  351.           p = arg + strlen (arg) - 1;
  352.           while (p >= arg && (*p == ' ' || *p == '\t'))
  353.             p--;
  354.           *(p + 1) = '\0';
  355.         }

  356.       /* If this command has been pre-hooked, run the hook first.  */
  357.       execute_cmd_pre_hook (c);

  358.       if (c->deprecated_warn_user)
  359.         deprecated_cmd_warning (line);

  360.       /* c->user_commands would be NULL in the case of a python command.  */
  361.       if (c->class == class_user && c->user_commands)
  362.         execute_user_command (c, arg);
  363.       else if (c->type == set_cmd)
  364.         do_set_command (arg, from_tty, c);
  365.       else if (c->type == show_cmd)
  366.         do_show_command (arg, from_tty, c);
  367.       else if (!cmd_func_p (c))
  368.         error (_("That is not a command, just a help topic."));
  369.       else if (deprecated_call_command_hook)
  370.         deprecated_call_command_hook (c, arg, from_tty);
  371.       else
  372.         cmd_func (c, arg, from_tty);

  373.       maybe_wait_sync_command_done (was_sync);

  374.       /* If this command has been post-hooked, run the hook last.  */
  375.       execute_cmd_post_hook (c);

  376.     }

  377.   check_frame_language_change ();

  378.   do_cleanups (cleanup);
  379.   discard_cleanups (cleanup_if_error);
  380. }

  381. /* Run execute_command for P and FROM_TTY.  Capture its output into the
  382.    returned string, do not display it to the screen.  BATCH_FLAG will be
  383.    temporarily set to true.  */

  384. char *
  385. execute_command_to_string (char *p, int from_tty)
  386. {
  387.   struct ui_file *str_file;
  388.   struct cleanup *cleanup;
  389.   char *retval;

  390.   /* GDB_STDOUT should be better already restored during these
  391.      restoration callbacks.  */
  392.   cleanup = set_batch_flag_and_make_cleanup_restore_page_info ();

  393.   make_cleanup_restore_integer (&interpreter_async);
  394.   interpreter_async = 0;

  395.   str_file = mem_fileopen ();

  396.   make_cleanup_ui_file_delete (str_file);
  397.   make_cleanup_restore_ui_file (&gdb_stdout);
  398.   make_cleanup_restore_ui_file (&gdb_stderr);
  399.   make_cleanup_restore_ui_file (&gdb_stdlog);
  400.   make_cleanup_restore_ui_file (&gdb_stdtarg);
  401.   make_cleanup_restore_ui_file (&gdb_stdtargerr);

  402.   if (ui_out_redirect (current_uiout, str_file) < 0)
  403.     warning (_("Current output protocol does not support redirection"));
  404.   else
  405.     make_cleanup_ui_out_redirect_pop (current_uiout);

  406.   gdb_stdout = str_file;
  407.   gdb_stderr = str_file;
  408.   gdb_stdlog = str_file;
  409.   gdb_stdtarg = str_file;
  410.   gdb_stdtargerr = str_file;

  411.   execute_command (p, from_tty);

  412.   retval = ui_file_xstrdup (str_file, NULL);

  413.   do_cleanups (cleanup);

  414.   return retval;
  415. }

  416. /* Read commands from `instream' and execute them
  417.    until end of file or error reading instream.  */

  418. void
  419. command_loop (void)
  420. {
  421.   struct cleanup *old_chain;
  422.   char *command;
  423.   int stdin_is_tty = ISATTY (stdin);

  424.   while (instream && !feof (instream))
  425.     {
  426.       if (window_hook && instream == stdin)
  427.         (*window_hook) (instream, get_prompt ());

  428.       clear_quit_flag ();
  429.       if (instream == stdin && stdin_is_tty)
  430.         reinitialize_more_filter ();
  431.       old_chain = make_cleanup (null_cleanup, 0);

  432.       /* Get a command-line.  This calls the readline package.  */
  433.       command = command_line_input (instream == stdin ?
  434.                                     get_prompt () : (char *) NULL,
  435.                                     instream == stdin, "prompt");
  436.       if (command == 0)
  437.         {
  438.           do_cleanups (old_chain);
  439.           return;
  440.         }

  441.       make_command_stats_cleanup (1);

  442.       /* Do not execute commented lines.  */
  443.       if (command[0] != '#')
  444.         {
  445.           execute_command (command, instream == stdin);

  446.           /* Do any commands attached to breakpoint we are stopped at.  */
  447.           bpstat_do_actions ();
  448.         }
  449.       do_cleanups (old_chain);
  450.     }
  451. }

  452. /* When nonzero, cause dont_repeat to do nothing.  This should only be
  453.    set via prevent_dont_repeat.  */

  454. static int suppress_dont_repeat = 0;

  455. /* Commands call this if they do not want to be repeated by null lines.  */

  456. void
  457. dont_repeat (void)
  458. {
  459.   if (suppress_dont_repeat || server_command)
  460.     return;

  461.   /* If we aren't reading from standard input, we are saving the last
  462.      thing read from stdin in line and don't want to delete it.  Null
  463.      lines won't repeat here in any case.  */
  464.   if (instream == stdin)
  465.     *saved_command_line = 0;
  466. }

  467. /* Prevent dont_repeat from working, and return a cleanup that
  468.    restores the previous state.  */

  469. struct cleanup *
  470. prevent_dont_repeat (void)
  471. {
  472.   struct cleanup *result = make_cleanup_restore_integer (&suppress_dont_repeat);

  473.   suppress_dont_repeat = 1;
  474.   return result;
  475. }


  476. /* Read a line from the stream "instream" without command line editing.

  477.    It prints PROMPT_ARG once at the start.
  478.    Action is compatible with "readline", e.g. space for the result is
  479.    malloc'd and should be freed by the caller.

  480.    A NULL return means end of file.  */
  481. char *
  482. gdb_readline (const char *prompt_arg)
  483. {
  484.   int c;
  485.   char *result;
  486.   int input_index = 0;
  487.   int result_size = 80;

  488.   if (prompt_arg)
  489.     {
  490.       /* Don't use a _filtered function here.  It causes the assumed
  491.          character position to be off, since the newline we read from
  492.          the user is not accounted for.  */
  493.       fputs_unfiltered (prompt_arg, gdb_stdout);
  494.       gdb_flush (gdb_stdout);
  495.     }

  496.   result = (char *) xmalloc (result_size);

  497.   while (1)
  498.     {
  499.       /* Read from stdin if we are executing a user defined command.
  500.          This is the right thing for prompt_for_continue, at least.  */
  501.       c = fgetc (instream ? instream : stdin);

  502.       if (c == EOF)
  503.         {
  504.           if (input_index > 0)
  505.             /* The last line does not end with a newline.  Return it, and
  506.                if we are called again fgetc will still return EOF and
  507.                we'll return NULL then.  */
  508.             break;
  509.           xfree (result);
  510.           return NULL;
  511.         }

  512.       if (c == '\n')
  513.         {
  514.           if (input_index > 0 && result[input_index - 1] == '\r')
  515.             input_index--;
  516.           break;
  517.         }

  518.       result[input_index++] = c;
  519.       while (input_index >= result_size)
  520.         {
  521.           result_size *= 2;
  522.           result = (char *) xrealloc (result, result_size);
  523.         }
  524.     }

  525.   result[input_index++] = '\0';
  526.   return result;
  527. }

  528. /* Variables which control command line editing and history
  529.    substitution.  These variables are given default values at the end
  530.    of this file.  */
  531. static int command_editing_p;

  532. /* NOTE 1999-04-29: This variable will be static again, once we modify
  533.    gdb to use the event loop as the default command loop and we merge
  534.    event-top.c into this file, top.c.  */

  535. /* static */ int history_expansion_p;

  536. static int write_history_p;
  537. static void
  538. show_write_history_p (struct ui_file *file, int from_tty,
  539.                       struct cmd_list_element *c, const char *value)
  540. {
  541.   fprintf_filtered (file, _("Saving of the history record on exit is %s.\n"),
  542.                     value);
  543. }

  544. /* The variable associated with the "set/show history size"
  545.    command.  */
  546. static unsigned int history_size_setshow_var;

  547. static void
  548. show_history_size (struct ui_file *file, int from_tty,
  549.                    struct cmd_list_element *c, const char *value)
  550. {
  551.   fprintf_filtered (file, _("The size of the command history is %s.\n"),
  552.                     value);
  553. }

  554. static char *history_filename;
  555. static void
  556. show_history_filename (struct ui_file *file, int from_tty,
  557.                        struct cmd_list_element *c, const char *value)
  558. {
  559.   fprintf_filtered (file, _("The filename in which to record "
  560.                             "the command history is \"%s\".\n"),
  561.                     value);
  562. }

  563. /* This is like readline(), but it has some gdb-specific behavior.
  564.    gdb may want readline in both the synchronous and async modes during
  565.    a single gdb invocation.  At the ordinary top-level prompt we might
  566.    be using the async readline.  That means we can't use
  567.    rl_pre_input_hook, since it doesn't work properly in async mode.
  568.    However, for a secondary prompt (" >", such as occurs during a
  569.    `define'), gdb wants a synchronous response.

  570.    We used to call readline() directly, running it in synchronous
  571.    mode.  But mixing modes this way is not supported, and as of
  572.    readline 5.x it no longer works; the arrow keys come unbound during
  573.    the synchronous call.  So we make a nested call into the event
  574.    loop.  That's what gdb_readline_wrapper is for.  */

  575. /* A flag set as soon as gdb_readline_wrapper_line is called; we can't
  576.    rely on gdb_readline_wrapper_result, which might still be NULL if
  577.    the user types Control-D for EOF.  */
  578. static int gdb_readline_wrapper_done;

  579. /* The result of the current call to gdb_readline_wrapper, once a newline
  580.    is seen.  */
  581. static char *gdb_readline_wrapper_result;

  582. /* Any intercepted hook.  Operate-and-get-next sets this, expecting it
  583.    to be called after the newline is processed (which will redisplay
  584.    the prompt).  But in gdb_readline_wrapper we will not get a new
  585.    prompt until the next call, or until we return to the event loop.
  586.    So we disable this hook around the newline and restore it before we
  587.    return.  */
  588. static void (*saved_after_char_processing_hook) (void);

  589. /* This function is called when readline has seen a complete line of
  590.    text.  */

  591. static void
  592. gdb_readline_wrapper_line (char *line)
  593. {
  594.   gdb_assert (!gdb_readline_wrapper_done);
  595.   gdb_readline_wrapper_result = line;
  596.   gdb_readline_wrapper_done = 1;

  597.   /* Prevent operate-and-get-next from acting too early.  */
  598.   saved_after_char_processing_hook = after_char_processing_hook;
  599.   after_char_processing_hook = NULL;

  600.   /* Prevent parts of the prompt from being redisplayed if annotations
  601.      are enabled, and readline's state getting out of sync.  We'll
  602.      reinstall the callback handler, which puts the terminal in raw
  603.      mode (or in readline lingo, in prepped state), when we're next
  604.      ready to process user input, either in display_gdb_prompt, or if
  605.      we're handling an asynchronous target event and running in the
  606.      background, just before returning to the event loop to process
  607.      further input (or more target events).  */
  608.   if (async_command_editing_p)
  609.     gdb_rl_callback_handler_remove ();
  610. }

  611. struct gdb_readline_wrapper_cleanup
  612.   {
  613.     void (*handler_orig) (char *);
  614.     int already_prompted_orig;

  615.     /* Whether the target was async.  */
  616.     int target_is_async_orig;
  617.   };

  618. static void
  619. gdb_readline_wrapper_cleanup (void *arg)
  620. {
  621.   struct gdb_readline_wrapper_cleanup *cleanup = arg;

  622.   rl_already_prompted = cleanup->already_prompted_orig;

  623.   gdb_assert (input_handler == gdb_readline_wrapper_line);
  624.   input_handler = cleanup->handler_orig;

  625.   /* Don't restore our input handler in readline yet.  That would make
  626.      readline prep the terminal (putting it in raw mode), while the
  627.      line we just read may trigger execution of a command that expects
  628.      the terminal in the default cooked/canonical mode, such as e.g.,
  629.      running Python's interactive online help utility.  See
  630.      gdb_readline_wrapper_line for when we'll reinstall it.  */

  631.   gdb_readline_wrapper_result = NULL;
  632.   gdb_readline_wrapper_done = 0;

  633.   after_char_processing_hook = saved_after_char_processing_hook;
  634.   saved_after_char_processing_hook = NULL;

  635.   if (cleanup->target_is_async_orig)
  636.     target_async (inferior_event_handler, 0);

  637.   xfree (cleanup);
  638. }

  639. char *
  640. gdb_readline_wrapper (const char *prompt)
  641. {
  642.   struct cleanup *back_to;
  643.   struct gdb_readline_wrapper_cleanup *cleanup;
  644.   char *retval;

  645.   cleanup = xmalloc (sizeof (*cleanup));
  646.   cleanup->handler_orig = input_handler;
  647.   input_handler = gdb_readline_wrapper_line;

  648.   cleanup->already_prompted_orig = rl_already_prompted;

  649.   cleanup->target_is_async_orig = target_is_async_p ();

  650.   back_to = make_cleanup (gdb_readline_wrapper_cleanup, cleanup);

  651.   if (cleanup->target_is_async_orig)
  652.     target_async (NULL, NULL);

  653.   /* Display our prompt and prevent double prompt display.  */
  654.   display_gdb_prompt (prompt);
  655.   rl_already_prompted = 1;

  656.   if (after_char_processing_hook)
  657.     (*after_char_processing_hook) ();
  658.   gdb_assert (after_char_processing_hook == NULL);

  659.   while (gdb_do_one_event () >= 0)
  660.     if (gdb_readline_wrapper_done)
  661.       break;

  662.   retval = gdb_readline_wrapper_result;
  663.   do_cleanups (back_to);
  664.   return retval;
  665. }


  666. /* The current saved history number from operate-and-get-next.
  667.    This is -1 if not valid.  */
  668. static int operate_saved_history = -1;

  669. /* This is put on the appropriate hook and helps operate-and-get-next
  670.    do its work.  */
  671. static void
  672. gdb_rl_operate_and_get_next_completion (void)
  673. {
  674.   int delta = where_history () - operate_saved_history;

  675.   /* The `key' argument to rl_get_previous_history is ignored.  */
  676.   rl_get_previous_history (delta, 0);
  677.   operate_saved_history = -1;

  678.   /* readline doesn't automatically update the display for us.  */
  679.   rl_redisplay ();

  680.   after_char_processing_hook = NULL;
  681.   rl_pre_input_hook = NULL;
  682. }

  683. /* This is a gdb-local readline command handler.  It accepts the
  684.    current command line (like RET does) and, if this command was taken
  685.    from the history, arranges for the next command in the history to
  686.    appear on the command line when the prompt returns.
  687.    We ignore the arguments.  */
  688. static int
  689. gdb_rl_operate_and_get_next (int count, int key)
  690. {
  691.   int where;

  692.   /* Use the async hook.  */
  693.   after_char_processing_hook = gdb_rl_operate_and_get_next_completion;

  694.   /* Find the current line, and find the next line to use.  */
  695.   where = where_history();

  696.   if ((history_is_stifled () && (history_length >= history_max_entries))
  697.       || (where >= history_length - 1))
  698.     operate_saved_history = where;
  699.   else
  700.     operate_saved_history = where + 1;

  701.   return rl_newline (1, key);
  702. }

  703. /* Read one line from the command input stream `instream'
  704.    into the local static buffer `linebuffer' (whose current length
  705.    is `linelength').
  706.    The buffer is made bigger as necessary.
  707.    Returns the address of the start of the line.

  708.    NULL is returned for end of file.

  709.    *If* the instream == stdin & stdin is a terminal, the line read
  710.    is copied into the file line saver (global var char *line,
  711.    length linesize) so that it can be duplicated.

  712.    This routine either uses fancy command line editing or
  713.    simple input as the user has requested.  */

  714. char *
  715. command_line_input (const char *prompt_arg, int repeat, char *annotation_suffix)
  716. {
  717.   static char *linebuffer = 0;
  718.   static unsigned linelength = 0;
  719.   const char *prompt = prompt_arg;
  720.   char *p;
  721.   char *p1;
  722.   char *rl;
  723.   char *nline;
  724.   char got_eof = 0;

  725.   /* The annotation suffix must be non-NULL.  */
  726.   if (annotation_suffix == NULL)
  727.     annotation_suffix = "";

  728.   if (annotation_level > 1 && instream == stdin)
  729.     {
  730.       char *local_prompt;

  731.       local_prompt = alloca ((prompt == NULL ? 0 : strlen (prompt))
  732.                              + strlen (annotation_suffix) + 40);
  733.       if (prompt == NULL)
  734.         local_prompt[0] = '\0';
  735.       else
  736.         strcpy (local_prompt, prompt);
  737.       strcat (local_prompt, "\n\032\032");
  738.       strcat (local_prompt, annotation_suffix);
  739.       strcat (local_prompt, "\n");

  740.       prompt = local_prompt;
  741.     }

  742.   if (linebuffer == 0)
  743.     {
  744.       linelength = 80;
  745.       linebuffer = (char *) xmalloc (linelength);
  746.     }

  747.   p = linebuffer;

  748.   /* Control-C quits instantly if typed while in this loop
  749.      since it should not wait until the user types a newline.  */
  750.   immediate_quit++;
  751.   QUIT;
  752. #ifdef STOP_SIGNAL
  753.   if (job_control)
  754.     signal (STOP_SIGNAL, handle_stop_sig);
  755. #endif

  756.   while (1)
  757.     {
  758.       /* Make sure that all output has been output.  Some machines may
  759.          let you get away with leaving out some of the gdb_flush, but
  760.          not all.  */
  761.       wrap_here ("");
  762.       gdb_flush (gdb_stdout);
  763.       gdb_flush (gdb_stderr);

  764.       if (source_file_name != NULL)
  765.         ++source_line_number;

  766.       if (annotation_level > 1 && instream == stdin)
  767.         {
  768.           puts_unfiltered ("\n\032\032pre-");
  769.           puts_unfiltered (annotation_suffix);
  770.           puts_unfiltered ("\n");
  771.         }

  772.       /* Don't use fancy stuff if not talking to stdin.  */
  773.       if (deprecated_readline_hook && input_from_terminal_p ())
  774.         {
  775.           rl = (*deprecated_readline_hook) (prompt);
  776.         }
  777.       else if (command_editing_p && input_from_terminal_p ())
  778.         {
  779.           rl = gdb_readline_wrapper (prompt);
  780.         }
  781.       else
  782.         {
  783.           rl = gdb_readline (prompt);
  784.         }

  785.       if (annotation_level > 1 && instream == stdin)
  786.         {
  787.           puts_unfiltered ("\n\032\032post-");
  788.           puts_unfiltered (annotation_suffix);
  789.           puts_unfiltered ("\n");
  790.         }

  791.       if (!rl || rl == (char *) EOF)
  792.         {
  793.           got_eof = 1;
  794.           break;
  795.         }
  796.       if (strlen (rl) + 1 + (p - linebuffer) > linelength)
  797.         {
  798.           linelength = strlen (rl) + 1 + (p - linebuffer);
  799.           nline = (char *) xrealloc (linebuffer, linelength);
  800.           p += nline - linebuffer;
  801.           linebuffer = nline;
  802.         }
  803.       p1 = rl;
  804.       /* Copy line.  Don't copy null at end.  (Leaves line alone
  805.          if this was just a newline).  */
  806.       while (*p1)
  807.         *p++ = *p1++;

  808.       xfree (rl);                /* Allocated in readline.  */

  809.       if (p == linebuffer || *(p - 1) != '\\')
  810.         break;

  811.       p--;                        /* Put on top of '\'.  */
  812.       prompt = NULL;
  813.     }

  814. #ifdef STOP_SIGNAL
  815.   if (job_control)
  816.     signal (STOP_SIGNAL, SIG_DFL);
  817. #endif
  818.   immediate_quit--;

  819.   if (got_eof)
  820.     return NULL;

  821. #define SERVER_COMMAND_LENGTH 7
  822.   server_command =
  823.     (p - linebuffer > SERVER_COMMAND_LENGTH)
  824.     && strncmp (linebuffer, "server ", SERVER_COMMAND_LENGTH) == 0;
  825.   if (server_command)
  826.     {
  827.       /* Note that we don't set `line'.  Between this and the check in
  828.          dont_repeat, this insures that repeating will still do the
  829.          right thing.  */
  830.       *p = '\0';
  831.       return linebuffer + SERVER_COMMAND_LENGTH;
  832.     }

  833.   /* Do history expansion if that is wished.  */
  834.   if (history_expansion_p && instream == stdin
  835.       && ISATTY (instream))
  836.     {
  837.       char *history_value;
  838.       int expanded;

  839.       *p = '\0';                /* Insert null now.  */
  840.       expanded = history_expand (linebuffer, &history_value);
  841.       if (expanded)
  842.         {
  843.           /* Print the changes.  */
  844.           printf_unfiltered ("%s\n", history_value);

  845.           /* If there was an error, call this function again.  */
  846.           if (expanded < 0)
  847.             {
  848.               xfree (history_value);
  849.               return command_line_input (prompt, repeat,
  850.                                          annotation_suffix);
  851.             }
  852.           if (strlen (history_value) > linelength)
  853.             {
  854.               linelength = strlen (history_value) + 1;
  855.               linebuffer = (char *) xrealloc (linebuffer, linelength);
  856.             }
  857.           strcpy (linebuffer, history_value);
  858.           p = linebuffer + strlen (linebuffer);
  859.         }
  860.       xfree (history_value);
  861.     }

  862.   /* If we just got an empty line, and that is supposed to repeat the
  863.      previous command, return the value in the global buffer.  */
  864.   if (repeat && p == linebuffer)
  865.     return saved_command_line;
  866.   for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
  867.   if (repeat && !*p1)
  868.     return saved_command_line;

  869.   *p = 0;

  870.   /* Add line to history if appropriate.  */
  871.   if (*linebuffer && input_from_terminal_p ())
  872.     add_history (linebuffer);

  873.   /* Save into global buffer if appropriate.  */
  874.   if (repeat)
  875.     {
  876.       if (linelength > saved_command_line_size)
  877.         {
  878.           saved_command_line = xrealloc (saved_command_line, linelength);
  879.           saved_command_line_size = linelength;
  880.         }
  881.       strcpy (saved_command_line, linebuffer);
  882.       return saved_command_line;
  883.     }

  884.   return linebuffer;
  885. }

  886. /* Print the GDB banner.  */
  887. void
  888. print_gdb_version (struct ui_file *stream)
  889. {
  890.   /* From GNU coding standards, first line is meant to be easy for a
  891.      program to parse, and is just canonical program name and version
  892.      number, which starts after last space.  */

  893.   fprintf_filtered (stream, "GNU gdb %s%s\n", PKGVERSION, version);

  894.   /* Second line is a copyright notice.  */

  895.   fprintf_filtered (stream,
  896.                     "Copyright (C) 2015 Free Software Foundation, Inc.\n");

  897.   /* Following the copyright is a brief statement that the program is
  898.      free software, that users are free to copy and change it on
  899.      certain conditions, that it is covered by the GNU GPL, and that
  900.      there is no warranty.  */

  901.   fprintf_filtered (stream, "\
  902. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\
  903. \nThis is free software: you are free to change and redistribute it.\n\
  904. There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\n\
  905. and \"show warranty\" for details.\n");

  906.   /* After the required info we print the configuration information.  */

  907.   fprintf_filtered (stream, "This GDB was configured as \"");
  908.   if (strcmp (host_name, target_name) != 0)
  909.     {
  910.       fprintf_filtered (stream, "--host=%s --target=%s",
  911.                         host_name, target_name);
  912.     }
  913.   else
  914.     {
  915.       fprintf_filtered (stream, "%s", host_name);
  916.     }
  917.   fprintf_filtered (stream, "\".\n\
  918. Type \"show configuration\" for configuration details.");

  919.   if (REPORT_BUGS_TO[0])
  920.     {
  921.       fprintf_filtered (stream,
  922.                         _("\nFor bug reporting instructions, please see:\n"));
  923.       fprintf_filtered (stream, "%s.\n", REPORT_BUGS_TO);
  924.     }
  925.   fprintf_filtered (stream,
  926.                     _("Find the GDB manual and other documentation \
  927. resources online at:\n<http://www.gnu.org/software/gdb/documentation/>.\n"));
  928.   fprintf_filtered (stream, _("For help, type \"help\".\n"));
  929.   fprintf_filtered (stream, _("Type \"apropos word\" to search for \
  930. commands related to \"word\"."));
  931. }

  932. /* Print the details of GDB build-time configuration.  */
  933. void
  934. print_gdb_configuration (struct ui_file *stream)
  935. {
  936.   fprintf_filtered (stream, _("\
  937. This GDB was configured as follows:\n\
  938.    configure --host=%s --target=%s\n\
  939. "), host_name, target_name);
  940.   fprintf_filtered (stream, _("\
  941.              --with-auto-load-dir=%s\n\
  942.              --with-auto-load-safe-path=%s\n\
  943. "), AUTO_LOAD_DIR, AUTO_LOAD_SAFE_PATH);
  944. #if HAVE_LIBEXPAT
  945.   fprintf_filtered (stream, _("\
  946.              --with-expat\n\
  947. "));
  948. #else
  949.   fprintf_filtered (stream, _("\
  950.              --without-expat\n\
  951. "));
  952. #endif
  953.   if (GDB_DATADIR[0])
  954.     fprintf_filtered (stream, _("\
  955.              --with-gdb-datadir=%s%s\n\
  956. "), GDB_DATADIR, GDB_DATADIR_RELOCATABLE ? " (relocatable)" : "");
  957. #ifdef ICONV_BIN
  958.   fprintf_filtered (stream, _("\
  959.              --with-iconv-bin=%s%s\n\
  960. "), ICONV_BIN, ICONV_BIN_RELOCATABLE ? " (relocatable)" : "");
  961. #endif
  962.   if (JIT_READER_DIR[0])
  963.     fprintf_filtered (stream, _("\
  964.              --with-jit-reader-dir=%s%s\n\
  965. "), JIT_READER_DIR, JIT_READER_DIR_RELOCATABLE ? " (relocatable)" : "");
  966. #if HAVE_LIBUNWIND_IA64_H
  967.   fprintf_filtered (stream, _("\
  968.              --with-libunwind-ia64\n\
  969. "));
  970. #else
  971.   fprintf_filtered (stream, _("\
  972.              --without-libunwind-ia64\n\
  973. "));
  974. #endif
  975. #if HAVE_LIBLZMA
  976.   fprintf_filtered (stream, _("\
  977.              --with-lzma\n\
  978. "));
  979. #else
  980.   fprintf_filtered (stream, _("\
  981.              --without-lzma\n\
  982. "));
  983. #endif
  984. #ifdef WITH_PYTHON_PATH
  985.   fprintf_filtered (stream, _("\
  986.              --with-python=%s%s\n\
  987. "), WITH_PYTHON_PATH, PYTHON_PATH_RELOCATABLE ? " (relocatable)" : "");
  988. #endif
  989. #if HAVE_GUILE
  990.   fprintf_filtered (stream, _("\
  991.              --with-guile\n\
  992. "));
  993. #else
  994.   fprintf_filtered (stream, _("\
  995.              --without-guile\n\
  996. "));
  997. #endif
  998. #ifdef RELOC_SRCDIR
  999.   fprintf_filtered (stream, _("\
  1000.              --with-relocated-sources=%s\n\
  1001. "), RELOC_SRCDIR);
  1002. #endif
  1003.   if (DEBUGDIR[0])
  1004.     fprintf_filtered (stream, _("\
  1005.              --with-separate-debug-dir=%s%s\n\
  1006. "), DEBUGDIR, DEBUGDIR_RELOCATABLE ? " (relocatable)" : "");
  1007.   if (TARGET_SYSTEM_ROOT[0])
  1008.     fprintf_filtered (stream, _("\
  1009.              --with-sysroot=%s%s\n\
  1010. "), TARGET_SYSTEM_ROOT, TARGET_SYSTEM_ROOT_RELOCATABLE ? " (relocatable)" : "");
  1011.   if (SYSTEM_GDBINIT[0])
  1012.     fprintf_filtered (stream, _("\
  1013.              --with-system-gdbinit=%s%s\n\
  1014. "), SYSTEM_GDBINIT, SYSTEM_GDBINIT_RELOCATABLE ? " (relocatable)" : "");
  1015. #if HAVE_ZLIB_H
  1016.   fprintf_filtered (stream, _("\
  1017.              --with-zlib\n\
  1018. "));
  1019. #else
  1020.   fprintf_filtered (stream, _("\
  1021.              --without-zlib\n\
  1022. "));
  1023. #endif
  1024. #if HAVE_LIBBABELTRACE
  1025.     fprintf_filtered (stream, _("\
  1026.              --with-babeltrace\n\
  1027. "));
  1028. #else
  1029.     fprintf_filtered (stream, _("\
  1030.              --without-babeltrace\n\
  1031. "));
  1032. #endif
  1033.     /* We assume "relocatable" will be printed at least once, thus we always
  1034.        print this text.  It's a reasonably safe assumption for now.  */
  1035.     fprintf_filtered (stream, _("\n\
  1036. (\"Relocatable\" means the directory can be moved with the GDB installation\n\
  1037. tree, and GDB will still find it.)\n\
  1038. "));
  1039. }


  1040. /* The current top level prompt, settable with "set prompt", and/or
  1041.    with the python `gdb.prompt_hook' hook.  */
  1042. static char *top_prompt;

  1043. /* Access method for the GDB prompt string.  */

  1044. char *
  1045. get_prompt (void)
  1046. {
  1047.   return top_prompt;
  1048. }

  1049. /* Set method for the GDB prompt string.  */

  1050. void
  1051. set_prompt (const char *s)
  1052. {
  1053.   char *p = xstrdup (s);

  1054.   xfree (top_prompt);
  1055.   top_prompt = p;
  1056. }


  1057. struct qt_args
  1058. {
  1059.   char *args;
  1060.   int from_tty;
  1061. };

  1062. /* Callback for iterate_over_inferiors.  Kills or detaches the given
  1063.    inferior, depending on how we originally gained control of it.  */

  1064. static int
  1065. kill_or_detach (struct inferior *inf, void *args)
  1066. {
  1067.   struct qt_args *qt = args;
  1068.   struct thread_info *thread;

  1069.   if (inf->pid == 0)
  1070.     return 0;

  1071.   thread = any_thread_of_process (inf->pid);
  1072.   if (thread != NULL)
  1073.     {
  1074.       switch_to_thread (thread->ptid);

  1075.       /* Leave core files alone.  */
  1076.       if (target_has_execution)
  1077.         {
  1078.           if (inf->attach_flag)
  1079.             target_detach (qt->args, qt->from_tty);
  1080.           else
  1081.             target_kill ();
  1082.         }
  1083.     }

  1084.   return 0;
  1085. }

  1086. /* Callback for iterate_over_inferiors.  Prints info about what GDB
  1087.    will do to each inferior on a "quit".  ARG points to a struct
  1088.    ui_out where output is to be collected.  */

  1089. static int
  1090. print_inferior_quit_action (struct inferior *inf, void *arg)
  1091. {
  1092.   struct ui_file *stb = arg;

  1093.   if (inf->pid == 0)
  1094.     return 0;

  1095.   if (inf->attach_flag)
  1096.     fprintf_filtered (stb,
  1097.                       _("\tInferior %d [%s] will be detached.\n"), inf->num,
  1098.                       target_pid_to_str (pid_to_ptid (inf->pid)));
  1099.   else
  1100.     fprintf_filtered (stb,
  1101.                       _("\tInferior %d [%s] will be killed.\n"), inf->num,
  1102.                       target_pid_to_str (pid_to_ptid (inf->pid)));

  1103.   return 0;
  1104. }

  1105. /* If necessary, make the user confirm that we should quit.  Return
  1106.    non-zero if we should quit, zero if we shouldn't.  */

  1107. int
  1108. quit_confirm (void)
  1109. {
  1110.   struct ui_file *stb;
  1111.   struct cleanup *old_chain;
  1112.   char *str;
  1113.   int qr;

  1114.   /* Don't even ask if we're only debugging a core file inferior.  */
  1115.   if (!have_live_inferiors ())
  1116.     return 1;

  1117.   /* Build the query string as a single string.  */
  1118.   stb = mem_fileopen ();
  1119.   old_chain = make_cleanup_ui_file_delete (stb);

  1120.   fprintf_filtered (stb, _("A debugging session is active.\n\n"));
  1121.   iterate_over_inferiors (print_inferior_quit_action, stb);
  1122.   fprintf_filtered (stb, _("\nQuit anyway? "));

  1123.   str = ui_file_xstrdup (stb, NULL);
  1124.   make_cleanup (xfree, str);

  1125.   qr = query ("%s", str);
  1126.   do_cleanups (old_chain);
  1127.   return qr;
  1128. }

  1129. /* Quit without asking for confirmation.  */

  1130. void
  1131. quit_force (char *args, int from_tty)
  1132. {
  1133.   int exit_code = 0;
  1134.   struct qt_args qt;
  1135.   volatile struct gdb_exception ex;

  1136.   /* An optional expression may be used to cause gdb to terminate with the
  1137.      value of that expression.  */
  1138.   if (args)
  1139.     {
  1140.       struct value *val = parse_and_eval (args);

  1141.       exit_code = (int) value_as_long (val);
  1142.     }
  1143.   else if (return_child_result)
  1144.     exit_code = return_child_result_value;

  1145.   qt.args = args;
  1146.   qt.from_tty = from_tty;

  1147.   /* Wrappers to make the code below a bit more readable.  */
  1148. #define DO_TRY \
  1149.   TRY_CATCH (ex, RETURN_MASK_ALL)

  1150. #define DO_PRINT_EX \
  1151.   if (ex.reason < 0) \
  1152.     exception_print (gdb_stderr, ex)

  1153.   /* We want to handle any quit errors and exit regardless.  */

  1154.   /* Get out of tfind mode, and kill or detach all inferiors.  */
  1155.   DO_TRY
  1156.     {
  1157.       disconnect_tracing ();
  1158.       iterate_over_inferiors (kill_or_detach, &qt);
  1159.     }
  1160.   DO_PRINT_EX;

  1161.   /* Give all pushed targets a chance to do minimal cleanup, and pop
  1162.      them all out.  */
  1163.   DO_TRY
  1164.     {
  1165.       pop_all_targets ();
  1166.     }
  1167.   DO_PRINT_EX;

  1168.   /* Save the history information if it is appropriate to do so.  */
  1169.   DO_TRY
  1170.     {
  1171.       if (write_history_p && history_filename
  1172.           && input_from_terminal_p ())
  1173.         write_history (history_filename);
  1174.     }
  1175.   DO_PRINT_EX;

  1176.   /* Do any final cleanups before exiting.  */
  1177.   DO_TRY
  1178.     {
  1179.       do_final_cleanups (all_cleanups ());
  1180.     }
  1181.   DO_PRINT_EX;

  1182.   exit (exit_code);
  1183. }

  1184. /* Returns whether GDB is running on a terminal and input is
  1185.    currently coming from that terminal.  */

  1186. int
  1187. input_from_terminal_p (void)
  1188. {
  1189.   if (batch_flag)
  1190.     return 0;

  1191.   if (gdb_has_a_terminal () && instream == stdin)
  1192.     return 1;

  1193.   /* If INSTREAM is unset, and we are not in a user command, we
  1194.      must be in Insight.  That's like having a terminal, for our
  1195.      purposes.  */
  1196.   if (instream == NULL && !in_user_command)
  1197.     return 1;

  1198.   return 0;
  1199. }

  1200. static void
  1201. dont_repeat_command (char *ignored, int from_tty)
  1202. {
  1203.   /* Can't call dont_repeat here because we're not necessarily reading
  1204.      from stdin.  */
  1205.   *saved_command_line = 0;
  1206. }

  1207. /* Functions to manipulate command line editing control variables.  */

  1208. /* Number of commands to print in each call to show_commands.  */
  1209. #define Hist_print 10
  1210. void
  1211. show_commands (char *args, int from_tty)
  1212. {
  1213.   /* Index for history commands.  Relative to history_base.  */
  1214.   int offset;

  1215.   /* Number of the history entry which we are planning to display next.
  1216.      Relative to history_base.  */
  1217.   static int num = 0;

  1218.   /* Print out some of the commands from the command history.  */

  1219.   if (args)
  1220.     {
  1221.       if (args[0] == '+' && args[1] == '\0')
  1222.         /* "info editing +" should print from the stored position.  */
  1223.         ;
  1224.       else
  1225.         /* "info editing <exp>" should print around command number <exp>.  */
  1226.         num = (parse_and_eval_long (args) - history_base) - Hist_print / 2;
  1227.     }
  1228.   /* "show commands" means print the last Hist_print commands.  */
  1229.   else
  1230.     {
  1231.       num = history_length - Hist_print;
  1232.     }

  1233.   if (num < 0)
  1234.     num = 0;

  1235.   /* If there are at least Hist_print commands, we want to display the last
  1236.      Hist_print rather than, say, the last 6.  */
  1237.   if (history_length - num < Hist_print)
  1238.     {
  1239.       num = history_length - Hist_print;
  1240.       if (num < 0)
  1241.         num = 0;
  1242.     }

  1243.   for (offset = num;
  1244.        offset < num + Hist_print && offset < history_length;
  1245.        offset++)
  1246.     {
  1247.       printf_filtered ("%5d  %s\n", history_base + offset,
  1248.                        (history_get (history_base + offset))->line);
  1249.     }

  1250.   /* The next command we want to display is the next one that we haven't
  1251.      displayed yet.  */
  1252.   num += Hist_print;

  1253.   /* If the user repeats this command with return, it should do what
  1254.      "show commands +" does.  This is unnecessary if arg is null,
  1255.      because "show commands +" is not useful after "show commands".  */
  1256.   if (from_tty && args)
  1257.     {
  1258.       args[0] = '+';
  1259.       args[1] = '\0';
  1260.     }
  1261. }

  1262. /* Called by do_setshow_command.  */
  1263. static void
  1264. set_history_size_command (char *args, int from_tty, struct cmd_list_element *c)
  1265. {
  1266.   /* Readline's history interface works with 'int', so it can only
  1267.      handle history sizes up to INT_MAX.  The command itself is
  1268.      uinteger, so UINT_MAX means "unlimited", but we only get that if
  1269.      the user does "set history size 0" -- "set history size <UINT_MAX>"
  1270.      throws out-of-range.  */
  1271.   if (history_size_setshow_var > INT_MAX
  1272.       && history_size_setshow_var != UINT_MAX)
  1273.     {
  1274.       unsigned int new_value = history_size_setshow_var;

  1275.       /* Restore previous value before throwing.  */
  1276.       if (history_is_stifled ())
  1277.         history_size_setshow_var = history_max_entries;
  1278.       else
  1279.         history_size_setshow_var = UINT_MAX;

  1280.       error (_("integer %u out of range"), new_value);
  1281.     }

  1282.   /* Commit the new value to readline's history.  */
  1283.   if (history_size_setshow_var == UINT_MAX)
  1284.     unstifle_history ();
  1285.   else
  1286.     stifle_history (history_size_setshow_var);
  1287. }

  1288. void
  1289. set_history (char *args, int from_tty)
  1290. {
  1291.   printf_unfiltered (_("\"set history\" must be followed "
  1292.                        "by the name of a history subcommand.\n"));
  1293.   help_list (sethistlist, "set history ", all_commands, gdb_stdout);
  1294. }

  1295. void
  1296. show_history (char *args, int from_tty)
  1297. {
  1298.   cmd_show_list (showhistlist, from_tty, "");
  1299. }

  1300. int info_verbose = 0;                /* Default verbose msgs off.  */

  1301. /* Called by do_setshow_command.  An elaborate joke.  */
  1302. void
  1303. set_verbose (char *args, int from_tty, struct cmd_list_element *c)
  1304. {
  1305.   const char *cmdname = "verbose";
  1306.   struct cmd_list_element *showcmd;

  1307.   showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, 1);
  1308.   gdb_assert (showcmd != NULL && showcmd != CMD_LIST_AMBIGUOUS);

  1309.   if (info_verbose)
  1310.     {
  1311.       c->doc = "Set verbose printing of informational messages.";
  1312.       showcmd->doc = "Show verbose printing of informational messages.";
  1313.     }
  1314.   else
  1315.     {
  1316.       c->doc = "Set verbosity.";
  1317.       showcmd->doc = "Show verbosity.";
  1318.     }
  1319. }

  1320. /* Init the history buffer.  Note that we are called after the init file(s)
  1321.    have been read so that the user can change the history file via his
  1322.    .gdbinit file (for instance).  The GDBHISTFILE environment variable
  1323.    overrides all of this.  */

  1324. void
  1325. init_history (void)
  1326. {
  1327.   char *tmpenv;

  1328.   tmpenv = getenv ("HISTSIZE");
  1329.   if (tmpenv)
  1330.     {
  1331.       int var;

  1332.       var = atoi (tmpenv);
  1333.       if (var < 0)
  1334.         {
  1335.           /* Prefer ending up with no history rather than overflowing
  1336.              readline's history interface, which uses signed 'int'
  1337.              everywhere.  */
  1338.           var = 0;
  1339.         }

  1340.       history_size_setshow_var = var;
  1341.     }
  1342.   /* If the init file hasn't set a size yet, pick the default.  */
  1343.   else if (history_size_setshow_var == 0)
  1344.     history_size_setshow_var = 256;

  1345.   /* Note that unlike "set history size 0", "HISTSIZE=0" really sets
  1346.      the history size to 0...  */
  1347.   stifle_history (history_size_setshow_var);

  1348.   tmpenv = getenv ("GDBHISTFILE");
  1349.   if (tmpenv)
  1350.     history_filename = xstrdup (tmpenv);
  1351.   else if (!history_filename)
  1352.     {
  1353.       /* We include the current directory so that if the user changes
  1354.          directories the file written will be the same as the one
  1355.          that was read.  */
  1356. #ifdef __MSDOS__
  1357.       /* No leading dots in file names are allowed on MSDOS.  */
  1358.       history_filename = concat (current_directory, "/_gdb_history",
  1359.                                  (char *)NULL);
  1360. #else
  1361.       history_filename = concat (current_directory, "/.gdb_history",
  1362.                                  (char *)NULL);
  1363. #endif
  1364.     }
  1365.   read_history (history_filename);
  1366. }

  1367. static void
  1368. show_prompt (struct ui_file *file, int from_tty,
  1369.              struct cmd_list_element *c, const char *value)
  1370. {
  1371.   fprintf_filtered (file, _("Gdb's prompt is \"%s\".\n"), value);
  1372. }

  1373. static void
  1374. show_async_command_editing_p (struct ui_file *file, int from_tty,
  1375.                               struct cmd_list_element *c, const char *value)
  1376. {
  1377.   fprintf_filtered (file, _("Editing of command lines as "
  1378.                             "they are typed is %s.\n"),
  1379.                     value);
  1380. }

  1381. static void
  1382. show_annotation_level (struct ui_file *file, int from_tty,
  1383.                        struct cmd_list_element *c, const char *value)
  1384. {
  1385.   fprintf_filtered (file, _("Annotation_level is %s.\n"), value);
  1386. }

  1387. static void
  1388. show_exec_done_display_p (struct ui_file *file, int from_tty,
  1389.                           struct cmd_list_element *c, const char *value)
  1390. {
  1391.   fprintf_filtered (file, _("Notification of completion for "
  1392.                             "asynchronous execution commands is %s.\n"),
  1393.                     value);
  1394. }

  1395. /* New values of the "data-directory" parameter are staged here.  */
  1396. static char *staged_gdb_datadir;

  1397. /* "set" command for the gdb_datadir configuration variable.  */

  1398. static void
  1399. set_gdb_datadir (char *args, int from_tty, struct cmd_list_element *c)
  1400. {
  1401.   set_gdb_data_directory (staged_gdb_datadir);
  1402.   observer_notify_gdb_datadir_changed ();
  1403. }

  1404. /* "show" command for the gdb_datadir configuration variable.  */

  1405. static void
  1406. show_gdb_datadir (struct ui_file *file, int from_tty,
  1407.                   struct cmd_list_element *c, const char *value)
  1408. {
  1409.   fprintf_filtered (file, _("GDB's data directory is \"%s\".\n"),
  1410.                     gdb_datadir);
  1411. }

  1412. static void
  1413. set_history_filename (char *args, int from_tty, struct cmd_list_element *c)
  1414. {
  1415.   /* We include the current directory so that if the user changes
  1416.      directories the file written will be the same as the one
  1417.      that was read.  */
  1418.   if (!IS_ABSOLUTE_PATH (history_filename))
  1419.     history_filename = reconcat (history_filename, current_directory, "/",
  1420.                                  history_filename, (char *) NULL);
  1421. }

  1422. static void
  1423. init_main (void)
  1424. {
  1425.   /* Initialize the prompt to a simple "(gdb) " prompt or to whatever
  1426.      the DEFAULT_PROMPT is.  */
  1427.   set_prompt (DEFAULT_PROMPT);

  1428.   /* Set things up for annotation_level > 1, if the user ever decides
  1429.      to use it.  */
  1430.   async_annotation_suffix = "prompt";

  1431.   /* Set the important stuff up for command editing.  */
  1432.   command_editing_p = 1;
  1433.   history_expansion_p = 0;
  1434.   write_history_p = 0;

  1435.   /* Setup important stuff for command line editing.  */
  1436.   rl_completion_word_break_hook = gdb_completion_word_break_characters;
  1437.   rl_completion_entry_function = readline_line_completion_function;
  1438.   rl_completer_word_break_characters = default_word_break_characters ();
  1439.   rl_completer_quote_characters = get_gdb_completer_quote_characters ();
  1440.   rl_readline_name = "gdb";
  1441.   rl_terminal_name = getenv ("TERM");

  1442.   /* The name for this defun comes from Bash, where it originated.
  1443.      15 is Control-o, the same binding this function has in Bash.  */
  1444.   rl_add_defun ("operate-and-get-next", gdb_rl_operate_and_get_next, 15);

  1445.   add_setshow_string_cmd ("prompt", class_support,
  1446.                           &top_prompt,
  1447.                           _("Set gdb's prompt"),
  1448.                           _("Show gdb's prompt"),
  1449.                           NULL, NULL,
  1450.                           show_prompt,
  1451.                           &setlist, &showlist);

  1452.   add_com ("dont-repeat", class_support, dont_repeat_command, _("\
  1453. Don't repeat this command.\nPrimarily \
  1454. used inside of user-defined commands that should not be repeated when\n\
  1455. hitting return."));

  1456.   add_setshow_boolean_cmd ("editing", class_support,
  1457.                            &async_command_editing_p, _("\
  1458. Set editing of command lines as they are typed."), _("\
  1459. Show editing of command lines as they are typed."), _("\
  1460. Use \"on\" to enable the editing, and \"off\" to disable it.\n\
  1461. Without an argument, command line editing is enabled.  To edit, use\n\
  1462. EMACS-like or VI-like commands like control-P or ESC."),
  1463.                            set_async_editing_command,
  1464.                            show_async_command_editing_p,
  1465.                            &setlist, &showlist);

  1466.   add_setshow_boolean_cmd ("save", no_class, &write_history_p, _("\
  1467. Set saving of the history record on exit."), _("\
  1468. Show saving of the history record on exit."), _("\
  1469. Use \"on\" to enable the saving, and \"off\" to disable it.\n\
  1470. Without an argument, saving is enabled."),
  1471.                            NULL,
  1472.                            show_write_history_p,
  1473.                            &sethistlist, &showhistlist);

  1474.   add_setshow_uinteger_cmd ("size", no_class, &history_size_setshow_var, _("\
  1475. Set the size of the command history,"), _("\
  1476. Show the size of the command history,"), _("\
  1477. ie. the number of previous commands to keep a record of.\n\
  1478. If set to \"unlimited\", the number of commands kept in the history\n\
  1479. list is unlimited.  This defaults to the value of the environment\n\
  1480. variable \"HISTSIZE\", or to 256 if this variable is not set."),
  1481.                             set_history_size_command,
  1482.                             show_history_size,
  1483.                             &sethistlist, &showhistlist);

  1484.   add_setshow_filename_cmd ("filename", no_class, &history_filename, _("\
  1485. Set the filename in which to record the command history"), _("\
  1486. Show the filename in which to record the command history"), _("\
  1487. (the list of previous commands of which a record is kept)."),
  1488.                             set_history_filename,
  1489.                             show_history_filename,
  1490.                             &sethistlist, &showhistlist);

  1491.   add_setshow_boolean_cmd ("confirm", class_support, &confirm, _("\
  1492. Set whether to confirm potentially dangerous operations."), _("\
  1493. Show whether to confirm potentially dangerous operations."), NULL,
  1494.                            NULL,
  1495.                            show_confirm,
  1496.                            &setlist, &showlist);

  1497.   add_setshow_zinteger_cmd ("annotate", class_obscure, &annotation_level, _("\
  1498. Set annotation_level."), _("\
  1499. Show annotation_level."), _("\
  1500. 0 == normal;     1 == fullname (for use when running under emacs)\n\
  1501. 2 == output annotated suitably for use by programs that control GDB."),
  1502.                             NULL,
  1503.                             show_annotation_level,
  1504.                             &setlist, &showlist);

  1505.   add_setshow_boolean_cmd ("exec-done-display", class_support,
  1506.                            &exec_done_display_p, _("\
  1507. Set notification of completion for asynchronous execution commands."), _("\
  1508. Show notification of completion for asynchronous execution commands."), _("\
  1509. Use \"on\" to enable the notification, and \"off\" to disable it."),
  1510.                            NULL,
  1511.                            show_exec_done_display_p,
  1512.                            &setlist, &showlist);

  1513.   add_setshow_filename_cmd ("data-directory", class_maintenance,
  1514.                            &staged_gdb_datadir, _("Set GDB's data directory."),
  1515.                            _("Show GDB's data directory."),
  1516.                            _("\
  1517. When set, GDB uses the specified path to search for data files."),
  1518.                            set_gdb_datadir, show_gdb_datadir,
  1519.                            &setlist,
  1520.                            &showlist);
  1521. }

  1522. void
  1523. gdb_init (char *argv0)
  1524. {
  1525.   if (pre_init_ui_hook)
  1526.     pre_init_ui_hook ();

  1527.   /* Run the init function of each source file.  */

  1528. #ifdef __MSDOS__
  1529.   /* Make sure we return to the original directory upon exit, come
  1530.      what may, since the OS doesn't do that for us.  */
  1531.   make_final_cleanup (do_chdir_cleanup, xstrdup (current_directory));
  1532. #endif

  1533.   init_cmd_lists ();            /* This needs to be done first.  */
  1534.   initialize_targets ();    /* Setup target_terminal macros for utils.c.  */
  1535.   initialize_utils ();            /* Make errors and warnings possible.  */

  1536.   /* Here is where we call all the _initialize_foo routines.  */
  1537.   initialize_all_files ();

  1538.   /* This creates the current_program_space.  Do this after all the
  1539.      _initialize_foo routines have had a chance to install their
  1540.      per-sspace data keys.  Also do this before
  1541.      initialize_current_architecture is called, because it accesses
  1542.      exec_bfd of the current program space.  */
  1543.   initialize_progspace ();
  1544.   initialize_inferiors ();
  1545.   initialize_current_architecture ();
  1546.   init_cli_cmds();
  1547.   initialize_event_loop ();
  1548.   init_main ();                        /* But that omits this file!  Do it now.  */

  1549.   initialize_stdin_serial ();

  1550.   /* Take a snapshot of our tty state before readline/ncurses have had a chance
  1551.      to alter it.  */
  1552.   set_initial_gdb_ttystate ();

  1553.   async_init_signals ();

  1554.   /* We need a default language for parsing expressions, so simple
  1555.      things like "set width 0" won't fail if no language is explicitly
  1556.      set in a config file or implicitly set by reading an executable
  1557.      during startup.  */
  1558.   set_language (language_c);
  1559.   expected_language = current_language;        /* Don't warn about the change.  */

  1560.   /* Allow another UI to initialize.  If the UI fails to initialize,
  1561.      and it wants GDB to revert to the CLI, it should clear
  1562.      deprecated_init_ui_hook.  */
  1563.   if (deprecated_init_ui_hook)
  1564.     deprecated_init_ui_hook (argv0);

  1565.   /* Python initialization, for example, can require various commands to be
  1566.      installed.  For example "info pretty-printer" needs the "info"
  1567.      prefix to be installed.  Keep things simple and just do final
  1568.      script initialization here.  */
  1569.   finish_ext_lang_initialization ();
  1570. }