GDB (API)
/home/stan/gdb/src/gdb/top.c
Go to the documentation of this file.
00001 /* Top level stuff for GDB, the GNU debugger.
00002 
00003    Copyright (C) 1986-2013 Free Software Foundation, Inc.
00004 
00005    This file is part of GDB.
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; either version 3 of the License, or
00010    (at your option) any later version.
00011 
00012    This program is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015    GNU General Public License for more details.
00016 
00017    You should have received a copy of the GNU General Public License
00018    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00019 
00020 #include "defs.h"
00021 #include "gdbcmd.h"
00022 #include "cli/cli-cmds.h"
00023 #include "cli/cli-script.h"
00024 #include "cli/cli-setshow.h"
00025 #include "cli/cli-decode.h"
00026 #include "symtab.h"
00027 #include "inferior.h"
00028 #include "exceptions.h"
00029 #include <signal.h>
00030 #include "target.h"
00031 #include "breakpoint.h"
00032 #include "gdbtypes.h"
00033 #include "expression.h"
00034 #include "value.h"
00035 #include "language.h"
00036 #include "terminal.h"           /* For job_control.  */
00037 #include "annotate.h"
00038 #include "completer.h"
00039 #include "top.h"
00040 #include "version.h"
00041 #include "serial.h"
00042 #include "doublest.h"
00043 #include "gdb_assert.h"
00044 #include "main.h"
00045 #include "event-loop.h"
00046 #include "gdbthread.h"
00047 #include "python/python.h"
00048 #include "interps.h"
00049 #include "observer.h"
00050 #include "maint.h"
00051 #include "filenames.h"
00052 
00053 /* readline include files.  */
00054 #include "readline/readline.h"
00055 #include "readline/history.h"
00056 
00057 /* readline defines this.  */
00058 #undef savestring
00059 
00060 #include <sys/types.h>
00061 
00062 #include "event-top.h"
00063 #include "gdb_string.h"
00064 #include "gdb_stat.h"
00065 #include <ctype.h>
00066 #include "ui-out.h"
00067 #include "cli-out.h"
00068 #include "tracepoint.h"
00069 
00070 extern void initialize_all_files (void);
00071 
00072 #define PROMPT(X) the_prompts.prompt_stack[the_prompts.top + X].prompt
00073 #define PREFIX(X) the_prompts.prompt_stack[the_prompts.top + X].prefix
00074 #define SUFFIX(X) the_prompts.prompt_stack[the_prompts.top + X].suffix
00075 
00076 /* Default command line prompt.  This is overriden in some configs.  */
00077 
00078 #ifndef DEFAULT_PROMPT
00079 #define DEFAULT_PROMPT  "(gdb) "
00080 #endif
00081 
00082 /* Initialization file name for gdb.  This is host-dependent.  */
00083 
00084 const char gdbinit[] = GDBINIT;
00085 
00086 int inhibit_gdbinit = 0;
00087 
00088 /* If nonzero, and GDB has been configured to be able to use windows,
00089    attempt to open them upon startup.  */
00090 
00091 int use_windows = 0;
00092 
00093 extern char lang_frame_mismatch_warn[];         /* language.c */
00094 
00095 /* Flag for whether we want to confirm potentially dangerous
00096    operations.  Default is yes.  */
00097 
00098 int confirm = 1;
00099 
00100 static void
00101 show_confirm (struct ui_file *file, int from_tty,
00102               struct cmd_list_element *c, const char *value)
00103 {
00104   fprintf_filtered (file, _("Whether to confirm potentially "
00105                             "dangerous operations is %s.\n"),
00106                     value);
00107 }
00108 
00109 /* stdio stream that command input is being read from.  Set to stdin
00110    normally.  Set by source_command to the file we are sourcing.  Set
00111    to NULL if we are executing a user-defined command or interacting
00112    via a GUI.  */
00113 
00114 FILE *instream;
00115 
00116 /* Flag to indicate whether a user defined command is currently running.  */
00117 
00118 int in_user_command;
00119 
00120 /* Current working directory.  */
00121 
00122 char *current_directory;
00123 
00124 /* The directory name is actually stored here (usually).  */
00125 char gdb_dirbuf[1024];
00126 
00127 /* Function to call before reading a command, if nonzero.
00128    The function receives two args: an input stream,
00129    and a prompt string.  */
00130 
00131 void (*window_hook) (FILE *, char *);
00132 
00133 /* Buffer used for reading command lines, and the size
00134    allocated for it so far.  */
00135 
00136 char *saved_command_line;
00137 int saved_command_line_size = 100;
00138 
00139 /* Nonzero if the current command is modified by "server ".  This
00140    affects things like recording into the command history, commands
00141    repeating on RETURN, etc.  This is so a user interface (emacs, GUI,
00142    whatever) can issue its own commands and also send along commands
00143    from the user, and have the user not notice that the user interface
00144    is issuing commands too.  */
00145 int server_command;
00146 
00147 /* Timeout limit for response from target.  */
00148 
00149 /* The default value has been changed many times over the years.  It 
00150    was originally 5 seconds.  But that was thought to be a long time 
00151    to sit and wait, so it was changed to 2 seconds.  That was thought
00152    to be plenty unless the connection was going through some terminal 
00153    server or multiplexer or other form of hairy serial connection.
00154 
00155    In mid-1996, remote_timeout was moved from remote.c to top.c and 
00156    it began being used in other remote-* targets.  It appears that the
00157    default was changed to 20 seconds at that time, perhaps because the
00158    Renesas E7000 ICE didn't always respond in a timely manner.
00159 
00160    But if 5 seconds is a long time to sit and wait for retransmissions,
00161    20 seconds is far worse.  This demonstrates the difficulty of using 
00162    a single variable for all protocol timeouts.
00163 
00164    As remote.c is used much more than remote-e7000.c, it was changed 
00165    back to 2 seconds in 1999.  */
00166 
00167 int remote_timeout = 2;
00168 
00169 /* Non-zero tells remote* modules to output debugging info.  */
00170 
00171 int remote_debug = 0;
00172 
00173 /* Sbrk location on entry to main.  Used for statistics only.  */
00174 #ifdef HAVE_SBRK
00175 char *lim_at_start;
00176 #endif
00177 
00178 /* Hooks for alternate command interfaces.  */
00179 
00180 /* Called after most modules have been initialized, but before taking
00181    users command file.
00182 
00183    If the UI fails to initialize and it wants GDB to continue using
00184    the default UI, then it should clear this hook before returning.  */
00185 
00186 void (*deprecated_init_ui_hook) (char *argv0);
00187 
00188 /* This hook is called from within gdb's many mini-event loops which
00189    could steal control from a real user interface's event loop.  It
00190    returns non-zero if the user is requesting a detach, zero
00191    otherwise.  */
00192 
00193 int (*deprecated_ui_loop_hook) (int);
00194 
00195 
00196 /* Called from print_frame_info to list the line we stopped in.  */
00197 
00198 void (*deprecated_print_frame_info_listing_hook) (struct symtab * s, 
00199                                                   int line,
00200                                                   int stopline, 
00201                                                   int noerror);
00202 /* Replaces most of query.  */
00203 
00204 int (*deprecated_query_hook) (const char *, va_list);
00205 
00206 /* Replaces most of warning.  */
00207 
00208 void (*deprecated_warning_hook) (const char *, va_list);
00209 
00210 /* These three functions support getting lines of text from the user.
00211    They are used in sequence.  First deprecated_readline_begin_hook is
00212    called with a text string that might be (for example) a message for
00213    the user to type in a sequence of commands to be executed at a
00214    breakpoint.  If this function calls back to a GUI, it might take
00215    this opportunity to pop up a text interaction window with this
00216    message.  Next, deprecated_readline_hook is called with a prompt
00217    that is emitted prior to collecting the user input.  It can be
00218    called multiple times.  Finally, deprecated_readline_end_hook is
00219    called to notify the GUI that we are done with the interaction
00220    window and it can close it.  */
00221 
00222 void (*deprecated_readline_begin_hook) (char *, ...);
00223 char *(*deprecated_readline_hook) (char *);
00224 void (*deprecated_readline_end_hook) (void);
00225 
00226 /* Called as appropriate to notify the interface that we have attached
00227    to or detached from an already running process.  */
00228 
00229 void (*deprecated_attach_hook) (void);
00230 void (*deprecated_detach_hook) (void);
00231 
00232 /* Called during long calculations to allow GUI to repair window
00233    damage, and to check for stop buttons, etc...  */
00234 
00235 void (*deprecated_interactive_hook) (void);
00236 
00237 /* Tell the GUI someone changed the register REGNO.  -1 means
00238    that the caller does not know which register changed or
00239    that several registers have changed (see value_assign).  */
00240 void (*deprecated_register_changed_hook) (int regno);
00241 
00242 /* Called when going to wait for the target.  Usually allows the GUI
00243    to run while waiting for target events.  */
00244 
00245 ptid_t (*deprecated_target_wait_hook) (ptid_t ptid,
00246                                        struct target_waitstatus *status,
00247                                        int options);
00248 
00249 /* Used by UI as a wrapper around command execution.  May do various
00250    things like enabling/disabling buttons, etc...  */
00251 
00252 void (*deprecated_call_command_hook) (struct cmd_list_element * c, 
00253                                       char *cmd, int from_tty);
00254 
00255 /* Called after a `set' command has finished.  Is only run if the
00256    `set' command succeeded.  */
00257 
00258 void (*deprecated_set_hook) (struct cmd_list_element * c);
00259 
00260 /* Called when the current thread changes.  Argument is thread id.  */
00261 
00262 void (*deprecated_context_hook) (int id);
00263 
00264 /* Handler for SIGHUP.  */
00265 
00266 #ifdef SIGHUP
00267 /* NOTE 1999-04-29: This function will be static again, once we modify
00268    gdb to use the event loop as the default command loop and we merge
00269    event-top.c into this file, top.c.  */
00270 /* static */ void
00271 quit_cover (void)
00272 {
00273   /* Stop asking user for confirmation --- we're exiting.  This
00274      prevents asking the user dumb questions.  */
00275   confirm = 0;
00276   quit_command ((char *) 0, 0);
00277 }
00278 #endif /* defined SIGHUP */
00279 
00280 /* Line number we are currently in, in a file which is being sourced.  */
00281 /* NOTE 1999-04-29: This variable will be static again, once we modify
00282    gdb to use the event loop as the default command loop and we merge
00283    event-top.c into this file, top.c.  */
00284 /* static */ int source_line_number;
00285 
00286 /* Name of the file we are sourcing.  */
00287 /* NOTE 1999-04-29: This variable will be static again, once we modify
00288    gdb to use the event loop as the default command loop and we merge
00289    event-top.c into this file, top.c.  */
00290 /* static */ const char *source_file_name;
00291 
00292 /* Clean up on error during a "source" command (or execution of a
00293    user-defined command).  */
00294 
00295 void
00296 do_restore_instream_cleanup (void *stream)
00297 {
00298   /* Restore the previous input stream.  */
00299   instream = stream;
00300 }
00301 
00302 /* Read commands from STREAM.  */
00303 void
00304 read_command_file (FILE *stream)
00305 {
00306   struct cleanup *cleanups;
00307 
00308   cleanups = make_cleanup (do_restore_instream_cleanup, instream);
00309   instream = stream;
00310   command_loop ();
00311   do_cleanups (cleanups);
00312 }
00313 
00314 void (*pre_init_ui_hook) (void);
00315 
00316 #ifdef __MSDOS__
00317 static void
00318 do_chdir_cleanup (void *old_dir)
00319 {
00320   chdir (old_dir);
00321   xfree (old_dir);
00322 }
00323 #endif
00324 
00325 struct cleanup *
00326 prepare_execute_command (void)
00327 {
00328   struct value *mark;
00329   struct cleanup *cleanup;
00330 
00331   mark = value_mark ();
00332   cleanup = make_cleanup_value_free_to_mark (mark);
00333 
00334   /* With multiple threads running while the one we're examining is
00335      stopped, the dcache can get stale without us being able to detect
00336      it.  For the duration of the command, though, use the dcache to
00337      help things like backtrace.  */
00338   if (non_stop)
00339     target_dcache_invalidate ();
00340 
00341   return cleanup;
00342 }
00343 
00344 /* Tell the user if the language has changed (except first time) after
00345    executing a command.  */
00346 
00347 void
00348 check_frame_language_change (void)
00349 {
00350   static int warned = 0;
00351 
00352   /* First make sure that a new frame has been selected, in case the
00353      command or the hooks changed the program state.  */
00354   deprecated_safe_get_selected_frame ();
00355   if (current_language != expected_language)
00356     {
00357       if (language_mode == language_mode_auto && info_verbose)
00358         {
00359           language_info (1);    /* Print what changed.  */
00360         }
00361       warned = 0;
00362     }
00363 
00364   /* Warn the user if the working language does not match the language
00365      of the current frame.  Only warn the user if we are actually
00366      running the program, i.e. there is a stack.  */
00367   /* FIXME: This should be cacheing the frame and only running when
00368      the frame changes.  */
00369 
00370   if (has_stack_frames ())
00371     {
00372       enum language flang;
00373 
00374       flang = get_frame_language ();
00375       if (!warned
00376           && flang != language_unknown
00377           && flang != current_language->la_language)
00378         {
00379           printf_filtered ("%s\n", lang_frame_mismatch_warn);
00380           warned = 1;
00381         }
00382     }
00383 }
00384 
00385 /* Execute the line P as a command, in the current user context.
00386    Pass FROM_TTY as second argument to the defining function.  */
00387 
00388 void
00389 execute_command (char *p, int from_tty)
00390 {
00391   struct cleanup *cleanup_if_error, *cleanup;
00392   struct cmd_list_element *c;
00393   char *line;
00394 
00395   cleanup_if_error = make_bpstat_clear_actions_cleanup ();
00396   cleanup = prepare_execute_command ();
00397 
00398   /* Force cleanup of any alloca areas if using C alloca instead of
00399      a builtin alloca.  */
00400   alloca (0);
00401 
00402   /* This can happen when command_line_input hits end of file.  */
00403   if (p == NULL)
00404     {
00405       do_cleanups (cleanup);
00406       discard_cleanups (cleanup_if_error);
00407       return;
00408     }
00409 
00410   target_log_command (p);
00411 
00412   while (*p == ' ' || *p == '\t')
00413     p++;
00414   if (*p)
00415     {
00416       const char *cmd = p;
00417       char *arg;
00418       line = p;
00419 
00420       /* If trace-commands is set then this will print this command.  */
00421       print_command_trace (p);
00422 
00423       c = lookup_cmd (&cmd, cmdlist, "", 0, 1);
00424       p = (char *) cmd;
00425 
00426       /* Pass null arg rather than an empty one.  */
00427       arg = *p ? p : 0;
00428 
00429       /* FIXME: cagney/2002-02-02: The c->type test is pretty dodgy
00430          while the is_complete_command(cfunc) test is just plain
00431          bogus.  They should both be replaced by a test of the form
00432          c->strip_trailing_white_space_p.  */
00433       /* NOTE: cagney/2002-02-02: The function.cfunc in the below
00434          can't be replaced with func.  This is because it is the
00435          cfunc, and not the func, that has the value that the
00436          is_complete_command hack is testing for.  */
00437       /* Clear off trailing whitespace, except for set and complete
00438          command.  */
00439       if (arg
00440           && c->type != set_cmd
00441           && !is_complete_command (c))
00442         {
00443           p = arg + strlen (arg) - 1;
00444           while (p >= arg && (*p == ' ' || *p == '\t'))
00445             p--;
00446           *(p + 1) = '\0';
00447         }
00448 
00449       /* If this command has been pre-hooked, run the hook first.  */
00450       execute_cmd_pre_hook (c);
00451 
00452       if (c->flags & DEPRECATED_WARN_USER)
00453         deprecated_cmd_warning (line);
00454 
00455       /* c->user_commands would be NULL in the case of a python command.  */
00456       if (c->class == class_user && c->user_commands)
00457         execute_user_command (c, arg);
00458       else if (c->type == set_cmd)
00459         do_set_command (arg, from_tty, c);
00460       else if (c->type == show_cmd)
00461         do_show_command (arg, from_tty, c);
00462       else if (!cmd_func_p (c))
00463         error (_("That is not a command, just a help topic."));
00464       else if (deprecated_call_command_hook)
00465         deprecated_call_command_hook (c, arg, from_tty);
00466       else
00467         cmd_func (c, arg, from_tty);
00468 
00469       /* If the interpreter is in sync mode (we're running a user
00470          command's list, running command hooks or similars), and we
00471          just ran a synchronous command that started the target, wait
00472          for that command to end.  */
00473       if (!interpreter_async && sync_execution)
00474         {
00475           while (gdb_do_one_event () >= 0)
00476             if (!sync_execution)
00477               break;
00478         }
00479 
00480       /* If this command has been post-hooked, run the hook last.  */
00481       execute_cmd_post_hook (c);
00482 
00483     }
00484 
00485   check_frame_language_change ();
00486 
00487   do_cleanups (cleanup);
00488   discard_cleanups (cleanup_if_error);
00489 }
00490 
00491 /* Run execute_command for P and FROM_TTY.  Capture its output into the
00492    returned string, do not display it to the screen.  BATCH_FLAG will be
00493    temporarily set to true.  */
00494 
00495 char *
00496 execute_command_to_string (char *p, int from_tty)
00497 {
00498   struct ui_file *str_file;
00499   struct cleanup *cleanup;
00500   char *retval;
00501 
00502   /* GDB_STDOUT should be better already restored during these
00503      restoration callbacks.  */
00504   cleanup = set_batch_flag_and_make_cleanup_restore_page_info ();
00505 
00506   make_cleanup_restore_integer (&interpreter_async);
00507   interpreter_async = 0;
00508 
00509   str_file = mem_fileopen ();
00510 
00511   make_cleanup_ui_file_delete (str_file);
00512   make_cleanup_restore_ui_file (&gdb_stdout);
00513   make_cleanup_restore_ui_file (&gdb_stderr);
00514   make_cleanup_restore_ui_file (&gdb_stdlog);
00515   make_cleanup_restore_ui_file (&gdb_stdtarg);
00516   make_cleanup_restore_ui_file (&gdb_stdtargerr);
00517 
00518   if (ui_out_redirect (current_uiout, str_file) < 0)
00519     warning (_("Current output protocol does not support redirection"));
00520   else
00521     make_cleanup_ui_out_redirect_pop (current_uiout);
00522 
00523   gdb_stdout = str_file;
00524   gdb_stderr = str_file;
00525   gdb_stdlog = str_file;
00526   gdb_stdtarg = str_file;
00527   gdb_stdtargerr = str_file;
00528 
00529   execute_command (p, from_tty);
00530 
00531   retval = ui_file_xstrdup (str_file, NULL);
00532 
00533   do_cleanups (cleanup);
00534 
00535   return retval;
00536 }
00537 
00538 /* Read commands from `instream' and execute them
00539    until end of file or error reading instream.  */
00540 
00541 void
00542 command_loop (void)
00543 {
00544   struct cleanup *old_chain;
00545   char *command;
00546   int stdin_is_tty = ISATTY (stdin);
00547 
00548   while (instream && !feof (instream))
00549     {
00550       if (window_hook && instream == stdin)
00551         (*window_hook) (instream, get_prompt ());
00552 
00553       clear_quit_flag ();
00554       if (instream == stdin && stdin_is_tty)
00555         reinitialize_more_filter ();
00556       old_chain = make_cleanup (null_cleanup, 0);
00557 
00558       /* Get a command-line.  This calls the readline package.  */
00559       command = command_line_input (instream == stdin ?
00560                                     get_prompt () : (char *) NULL,
00561                                     instream == stdin, "prompt");
00562       if (command == 0)
00563         {
00564           do_cleanups (old_chain);
00565           return;
00566         }
00567 
00568       make_command_stats_cleanup (1);
00569 
00570       execute_command (command, instream == stdin);
00571 
00572       /* Do any commands attached to breakpoint we are stopped at.  */
00573       bpstat_do_actions ();
00574 
00575       do_cleanups (old_chain);
00576     }
00577 }
00578 
00579 /* When nonzero, cause dont_repeat to do nothing.  This should only be
00580    set via prevent_dont_repeat.  */
00581 
00582 static int suppress_dont_repeat = 0;
00583 
00584 /* Commands call this if they do not want to be repeated by null lines.  */
00585 
00586 void
00587 dont_repeat (void)
00588 {
00589   if (suppress_dont_repeat || server_command)
00590     return;
00591 
00592   /* If we aren't reading from standard input, we are saving the last
00593      thing read from stdin in line and don't want to delete it.  Null
00594      lines won't repeat here in any case.  */
00595   if (instream == stdin)
00596     *saved_command_line = 0;
00597 }
00598 
00599 /* Prevent dont_repeat from working, and return a cleanup that
00600    restores the previous state.  */
00601 
00602 struct cleanup *
00603 prevent_dont_repeat (void)
00604 {
00605   struct cleanup *result = make_cleanup_restore_integer (&suppress_dont_repeat);
00606 
00607   suppress_dont_repeat = 1;
00608   return result;
00609 }
00610 
00611 
00612 /* Read a line from the stream "instream" without command line editing.
00613 
00614    It prints PROMPT_ARG once at the start.
00615    Action is compatible with "readline", e.g. space for the result is
00616    malloc'd and should be freed by the caller.
00617 
00618    A NULL return means end of file.  */
00619 char *
00620 gdb_readline (char *prompt_arg)
00621 {
00622   int c;
00623   char *result;
00624   int input_index = 0;
00625   int result_size = 80;
00626 
00627   if (prompt_arg)
00628     {
00629       /* Don't use a _filtered function here.  It causes the assumed
00630          character position to be off, since the newline we read from
00631          the user is not accounted for.  */
00632       fputs_unfiltered (prompt_arg, gdb_stdout);
00633       gdb_flush (gdb_stdout);
00634     }
00635 
00636   result = (char *) xmalloc (result_size);
00637 
00638   while (1)
00639     {
00640       /* Read from stdin if we are executing a user defined command.
00641          This is the right thing for prompt_for_continue, at least.  */
00642       c = fgetc (instream ? instream : stdin);
00643 
00644       if (c == EOF)
00645         {
00646           if (input_index > 0)
00647             /* The last line does not end with a newline.  Return it, and
00648                if we are called again fgetc will still return EOF and
00649                we'll return NULL then.  */
00650             break;
00651           xfree (result);
00652           return NULL;
00653         }
00654 
00655       if (c == '\n')
00656         {
00657           if (input_index > 0 && result[input_index - 1] == '\r')
00658             input_index--;
00659           break;
00660         }
00661 
00662       result[input_index++] = c;
00663       while (input_index >= result_size)
00664         {
00665           result_size *= 2;
00666           result = (char *) xrealloc (result, result_size);
00667         }
00668     }
00669 
00670   result[input_index++] = '\0';
00671   return result;
00672 }
00673 
00674 /* Variables which control command line editing and history
00675    substitution.  These variables are given default values at the end
00676    of this file.  */
00677 static int command_editing_p;
00678 
00679 /* NOTE 1999-04-29: This variable will be static again, once we modify
00680    gdb to use the event loop as the default command loop and we merge
00681    event-top.c into this file, top.c.  */
00682 
00683 /* static */ int history_expansion_p;
00684 
00685 static int write_history_p;
00686 static void
00687 show_write_history_p (struct ui_file *file, int from_tty,
00688                       struct cmd_list_element *c, const char *value)
00689 {
00690   fprintf_filtered (file, _("Saving of the history record on exit is %s.\n"),
00691                     value);
00692 }
00693 
00694 /* The variable associated with the "set/show history size"
00695    command.  */
00696 static unsigned int history_size_setshow_var;
00697 
00698 static void
00699 show_history_size (struct ui_file *file, int from_tty,
00700                    struct cmd_list_element *c, const char *value)
00701 {
00702   fprintf_filtered (file, _("The size of the command history is %s.\n"),
00703                     value);
00704 }
00705 
00706 static char *history_filename;
00707 static void
00708 show_history_filename (struct ui_file *file, int from_tty,
00709                        struct cmd_list_element *c, const char *value)
00710 {
00711   fprintf_filtered (file, _("The filename in which to record "
00712                             "the command history is \"%s\".\n"),
00713                     value);
00714 }
00715 
00716 /* This is like readline(), but it has some gdb-specific behavior.
00717    gdb may want readline in both the synchronous and async modes during
00718    a single gdb invocation.  At the ordinary top-level prompt we might
00719    be using the async readline.  That means we can't use
00720    rl_pre_input_hook, since it doesn't work properly in async mode.
00721    However, for a secondary prompt (" >", such as occurs during a
00722    `define'), gdb wants a synchronous response.
00723 
00724    We used to call readline() directly, running it in synchronous
00725    mode.  But mixing modes this way is not supported, and as of
00726    readline 5.x it no longer works; the arrow keys come unbound during
00727    the synchronous call.  So we make a nested call into the event
00728    loop.  That's what gdb_readline_wrapper is for.  */
00729 
00730 /* A flag set as soon as gdb_readline_wrapper_line is called; we can't
00731    rely on gdb_readline_wrapper_result, which might still be NULL if
00732    the user types Control-D for EOF.  */
00733 static int gdb_readline_wrapper_done;
00734 
00735 /* The result of the current call to gdb_readline_wrapper, once a newline
00736    is seen.  */
00737 static char *gdb_readline_wrapper_result;
00738 
00739 /* Any intercepted hook.  Operate-and-get-next sets this, expecting it
00740    to be called after the newline is processed (which will redisplay
00741    the prompt).  But in gdb_readline_wrapper we will not get a new
00742    prompt until the next call, or until we return to the event loop.
00743    So we disable this hook around the newline and restore it before we
00744    return.  */
00745 static void (*saved_after_char_processing_hook) (void);
00746 
00747 /* This function is called when readline has seen a complete line of
00748    text.  */
00749 
00750 static void
00751 gdb_readline_wrapper_line (char *line)
00752 {
00753   gdb_assert (!gdb_readline_wrapper_done);
00754   gdb_readline_wrapper_result = line;
00755   gdb_readline_wrapper_done = 1;
00756 
00757   /* Prevent operate-and-get-next from acting too early.  */
00758   saved_after_char_processing_hook = after_char_processing_hook;
00759   after_char_processing_hook = NULL;
00760 
00761   /* Prevent parts of the prompt from being redisplayed if annotations
00762      are enabled, and readline's state getting out of sync.  */
00763   if (async_command_editing_p)
00764     rl_callback_handler_remove ();
00765 }
00766 
00767 struct gdb_readline_wrapper_cleanup
00768   {
00769     void (*handler_orig) (char *);
00770     int already_prompted_orig;
00771   };
00772 
00773 static void
00774 gdb_readline_wrapper_cleanup (void *arg)
00775 {
00776   struct gdb_readline_wrapper_cleanup *cleanup = arg;
00777 
00778   rl_already_prompted = cleanup->already_prompted_orig;
00779 
00780   gdb_assert (input_handler == gdb_readline_wrapper_line);
00781   input_handler = cleanup->handler_orig;
00782   gdb_readline_wrapper_result = NULL;
00783   gdb_readline_wrapper_done = 0;
00784 
00785   after_char_processing_hook = saved_after_char_processing_hook;
00786   saved_after_char_processing_hook = NULL;
00787 
00788   xfree (cleanup);
00789 }
00790 
00791 char *
00792 gdb_readline_wrapper (char *prompt)
00793 {
00794   struct cleanup *back_to;
00795   struct gdb_readline_wrapper_cleanup *cleanup;
00796   char *retval;
00797 
00798   cleanup = xmalloc (sizeof (*cleanup));
00799   cleanup->handler_orig = input_handler;
00800   input_handler = gdb_readline_wrapper_line;
00801 
00802   cleanup->already_prompted_orig = rl_already_prompted;
00803 
00804   back_to = make_cleanup (gdb_readline_wrapper_cleanup, cleanup);
00805 
00806   /* Display our prompt and prevent double prompt display.  */
00807   display_gdb_prompt (prompt);
00808   rl_already_prompted = 1;
00809 
00810   if (after_char_processing_hook)
00811     (*after_char_processing_hook) ();
00812   gdb_assert (after_char_processing_hook == NULL);
00813 
00814   while (gdb_do_one_event () >= 0)
00815     if (gdb_readline_wrapper_done)
00816       break;
00817 
00818   retval = gdb_readline_wrapper_result;
00819   do_cleanups (back_to);
00820   return retval;
00821 }
00822 
00823 
00824 /* The current saved history number from operate-and-get-next.
00825    This is -1 if not valid.  */
00826 static int operate_saved_history = -1;
00827 
00828 /* This is put on the appropriate hook and helps operate-and-get-next
00829    do its work.  */
00830 static void
00831 gdb_rl_operate_and_get_next_completion (void)
00832 {
00833   int delta = where_history () - operate_saved_history;
00834 
00835   /* The `key' argument to rl_get_previous_history is ignored.  */
00836   rl_get_previous_history (delta, 0);
00837   operate_saved_history = -1;
00838 
00839   /* readline doesn't automatically update the display for us.  */
00840   rl_redisplay ();
00841 
00842   after_char_processing_hook = NULL;
00843   rl_pre_input_hook = NULL;
00844 }
00845 
00846 /* This is a gdb-local readline command handler.  It accepts the
00847    current command line (like RET does) and, if this command was taken
00848    from the history, arranges for the next command in the history to
00849    appear on the command line when the prompt returns.
00850    We ignore the arguments.  */
00851 static int
00852 gdb_rl_operate_and_get_next (int count, int key)
00853 {
00854   int where;
00855 
00856   /* Use the async hook.  */
00857   after_char_processing_hook = gdb_rl_operate_and_get_next_completion;
00858 
00859   /* Find the current line, and find the next line to use.  */
00860   where = where_history();
00861 
00862   if ((history_is_stifled () && (history_length >= history_max_entries))
00863       || (where >= history_length - 1))
00864     operate_saved_history = where;
00865   else
00866     operate_saved_history = where + 1;
00867 
00868   return rl_newline (1, key);
00869 }
00870 
00871 /* Read one line from the command input stream `instream'
00872    into the local static buffer `linebuffer' (whose current length
00873    is `linelength').
00874    The buffer is made bigger as necessary.
00875    Returns the address of the start of the line.
00876 
00877    NULL is returned for end of file.
00878 
00879    *If* the instream == stdin & stdin is a terminal, the line read
00880    is copied into the file line saver (global var char *line,
00881    length linesize) so that it can be duplicated.
00882 
00883    This routine either uses fancy command line editing or
00884    simple input as the user has requested.  */
00885 
00886 char *
00887 command_line_input (char *prompt_arg, int repeat, char *annotation_suffix)
00888 {
00889   static char *linebuffer = 0;
00890   static unsigned linelength = 0;
00891   char *p;
00892   char *p1;
00893   char *rl;
00894   char *local_prompt = prompt_arg;
00895   char *nline;
00896   char got_eof = 0;
00897 
00898   /* The annotation suffix must be non-NULL.  */
00899   if (annotation_suffix == NULL)
00900     annotation_suffix = "";
00901 
00902   if (annotation_level > 1 && instream == stdin)
00903     {
00904       local_prompt = alloca ((prompt_arg == NULL ? 0 : strlen (prompt_arg))
00905                              + strlen (annotation_suffix) + 40);
00906       if (prompt_arg == NULL)
00907         local_prompt[0] = '\0';
00908       else
00909         strcpy (local_prompt, prompt_arg);
00910       strcat (local_prompt, "\n\032\032");
00911       strcat (local_prompt, annotation_suffix);
00912       strcat (local_prompt, "\n");
00913     }
00914 
00915   if (linebuffer == 0)
00916     {
00917       linelength = 80;
00918       linebuffer = (char *) xmalloc (linelength);
00919     }
00920 
00921   p = linebuffer;
00922 
00923   /* Control-C quits instantly if typed while in this loop
00924      since it should not wait until the user types a newline.  */
00925   immediate_quit++;
00926   QUIT;
00927 #ifdef STOP_SIGNAL
00928   if (job_control)
00929     signal (STOP_SIGNAL, handle_stop_sig);
00930 #endif
00931 
00932   while (1)
00933     {
00934       /* Make sure that all output has been output.  Some machines may
00935          let you get away with leaving out some of the gdb_flush, but
00936          not all.  */
00937       wrap_here ("");
00938       gdb_flush (gdb_stdout);
00939       gdb_flush (gdb_stderr);
00940 
00941       if (source_file_name != NULL)
00942         ++source_line_number;
00943 
00944       if (annotation_level > 1 && instream == stdin)
00945         {
00946           puts_unfiltered ("\n\032\032pre-");
00947           puts_unfiltered (annotation_suffix);
00948           puts_unfiltered ("\n");
00949         }
00950 
00951       /* Don't use fancy stuff if not talking to stdin.  */
00952       if (deprecated_readline_hook && input_from_terminal_p ())
00953         {
00954           rl = (*deprecated_readline_hook) (local_prompt);
00955         }
00956       else if (command_editing_p && input_from_terminal_p ())
00957         {
00958           rl = gdb_readline_wrapper (local_prompt);
00959         }
00960       else
00961         {
00962           rl = gdb_readline (local_prompt);
00963         }
00964 
00965       if (annotation_level > 1 && instream == stdin)
00966         {
00967           puts_unfiltered ("\n\032\032post-");
00968           puts_unfiltered (annotation_suffix);
00969           puts_unfiltered ("\n");
00970         }
00971 
00972       if (!rl || rl == (char *) EOF)
00973         {
00974           got_eof = 1;
00975           break;
00976         }
00977       if (strlen (rl) + 1 + (p - linebuffer) > linelength)
00978         {
00979           linelength = strlen (rl) + 1 + (p - linebuffer);
00980           nline = (char *) xrealloc (linebuffer, linelength);
00981           p += nline - linebuffer;
00982           linebuffer = nline;
00983         }
00984       p1 = rl;
00985       /* Copy line.  Don't copy null at end.  (Leaves line alone
00986          if this was just a newline).  */
00987       while (*p1)
00988         *p++ = *p1++;
00989 
00990       xfree (rl);               /* Allocated in readline.  */
00991 
00992       if (p == linebuffer || *(p - 1) != '\\')
00993         break;
00994 
00995       p--;                      /* Put on top of '\'.  */
00996       local_prompt = (char *) 0;
00997     }
00998 
00999 #ifdef STOP_SIGNAL
01000   if (job_control)
01001     signal (STOP_SIGNAL, SIG_DFL);
01002 #endif
01003   immediate_quit--;
01004 
01005   if (got_eof)
01006     return NULL;
01007 
01008 #define SERVER_COMMAND_LENGTH 7
01009   server_command =
01010     (p - linebuffer > SERVER_COMMAND_LENGTH)
01011     && strncmp (linebuffer, "server ", SERVER_COMMAND_LENGTH) == 0;
01012   if (server_command)
01013     {
01014       /* Note that we don't set `line'.  Between this and the check in
01015          dont_repeat, this insures that repeating will still do the
01016          right thing.  */
01017       *p = '\0';
01018       return linebuffer + SERVER_COMMAND_LENGTH;
01019     }
01020 
01021   /* Do history expansion if that is wished.  */
01022   if (history_expansion_p && instream == stdin
01023       && ISATTY (instream))
01024     {
01025       char *history_value;
01026       int expanded;
01027 
01028       *p = '\0';                /* Insert null now.  */
01029       expanded = history_expand (linebuffer, &history_value);
01030       if (expanded)
01031         {
01032           /* Print the changes.  */
01033           printf_unfiltered ("%s\n", history_value);
01034 
01035           /* If there was an error, call this function again.  */
01036           if (expanded < 0)
01037             {
01038               xfree (history_value);
01039               return command_line_input (prompt_arg, repeat,
01040                                          annotation_suffix);
01041             }
01042           if (strlen (history_value) > linelength)
01043             {
01044               linelength = strlen (history_value) + 1;
01045               linebuffer = (char *) xrealloc (linebuffer, linelength);
01046             }
01047           strcpy (linebuffer, history_value);
01048           p = linebuffer + strlen (linebuffer);
01049         }
01050       xfree (history_value);
01051     }
01052 
01053   /* If we just got an empty line, and that is supposed to repeat the
01054      previous command, return the value in the global buffer.  */
01055   if (repeat && p == linebuffer)
01056     return saved_command_line;
01057   for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
01058   if (repeat && !*p1)
01059     return saved_command_line;
01060 
01061   *p = 0;
01062 
01063   /* Add line to history if appropriate.  */
01064   if (instream == stdin
01065       && ISATTY (stdin) && *linebuffer)
01066     add_history (linebuffer);
01067 
01068   /* Note: lines consisting solely of comments are added to the command
01069      history.  This is useful when you type a command, and then
01070      realize you don't want to execute it quite yet.  You can comment
01071      out the command and then later fetch it from the value history
01072      and remove the '#'.  The kill ring is probably better, but some
01073      people are in the habit of commenting things out.  */
01074   if (*p1 == '#')
01075     *p1 = '\0';                 /* Found a comment.  */
01076 
01077   /* Save into global buffer if appropriate.  */
01078   if (repeat)
01079     {
01080       if (linelength > saved_command_line_size)
01081         {
01082           saved_command_line = xrealloc (saved_command_line, linelength);
01083           saved_command_line_size = linelength;
01084         }
01085       strcpy (saved_command_line, linebuffer);
01086       return saved_command_line;
01087     }
01088 
01089   return linebuffer;
01090 }
01091 
01092 /* Print the GDB banner.  */
01093 void
01094 print_gdb_version (struct ui_file *stream)
01095 {
01096   /* From GNU coding standards, first line is meant to be easy for a
01097      program to parse, and is just canonical program name and version
01098      number, which starts after last space.  */
01099 
01100   fprintf_filtered (stream, "GNU gdb %s%s\n", PKGVERSION, version);
01101 
01102   /* Second line is a copyright notice.  */
01103 
01104   fprintf_filtered (stream,
01105                     "Copyright (C) 2013 Free Software Foundation, Inc.\n");
01106 
01107   /* Following the copyright is a brief statement that the program is
01108      free software, that users are free to copy and change it on
01109      certain conditions, that it is covered by the GNU GPL, and that
01110      there is no warranty.  */
01111 
01112   fprintf_filtered (stream, "\
01113 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\
01114 \nThis is free software: you are free to change and redistribute it.\n\
01115 There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\n\
01116 and \"show warranty\" for details.\n");
01117 
01118   /* After the required info we print the configuration information.  */
01119 
01120   fprintf_filtered (stream, "This GDB was configured as \"");
01121   if (strcmp (host_name, target_name) != 0)
01122     {
01123       fprintf_filtered (stream, "--host=%s --target=%s",
01124                         host_name, target_name);
01125     }
01126   else
01127     {
01128       fprintf_filtered (stream, "%s", host_name);
01129     }
01130   fprintf_filtered (stream, "\".\n\
01131 Type \"show configuration\" for configuration details.");
01132 
01133   if (REPORT_BUGS_TO[0])
01134     {
01135       fprintf_filtered (stream,
01136                         _("\nFor bug reporting instructions, please see:\n"));
01137       fprintf_filtered (stream, "%s.\n", REPORT_BUGS_TO);
01138     }
01139   fprintf_filtered (stream,
01140                     _("Find the GDB manual and other documentation \
01141 resources online at:\n<http://www.gnu.org/software/gdb/documentation/>.\n"));
01142   fprintf_filtered (stream, _("For help, type \"help\".\n"));
01143   fprintf_filtered (stream, _("Type \"apropos word\" to search for \
01144 commands related to \"word\"."));
01145 }
01146 
01147 /* Print the details of GDB build-time configuration.  */
01148 void
01149 print_gdb_configuration (struct ui_file *stream)
01150 {
01151   fprintf_filtered (stream, _("\
01152 This GDB was configured as follows:\n\
01153    configure --host=%s --target=%s\n\
01154 "), host_name, target_name);
01155   fprintf_filtered (stream, _("\
01156              --with-auto-load-dir=%s\n\
01157              --with-auto-load-safe-path=%s\n\
01158 "), AUTO_LOAD_DIR, AUTO_LOAD_SAFE_PATH);
01159 #if HAVE_LIBEXPAT
01160   fprintf_filtered (stream, _("\
01161              --with-expat\n\
01162 "));
01163 #else
01164   fprintf_filtered (stream, _("\
01165              --without-expat\n\
01166 "));
01167 #endif
01168   if (GDB_DATADIR[0])
01169     fprintf_filtered (stream, _("\
01170              --with-gdb-datadir=%s%s\n\
01171 "), GDB_DATADIR, GDB_DATADIR_RELOCATABLE ? " (relocatable)" : "");
01172 #ifdef ICONV_BIN
01173   fprintf_filtered (stream, _("\
01174              --with-iconv-bin=%s%s\n\
01175 "), ICONV_BIN, ICONV_BIN_RELOCATABLE ? " (relocatable)" : "");
01176 #endif
01177   if (JIT_READER_DIR[0])
01178     fprintf_filtered (stream, _("\
01179              --with-jit-reader-dir=%s%s\n\
01180 "), JIT_READER_DIR, JIT_READER_DIR_RELOCATABLE ? " (relocatable)" : "");
01181 #if HAVE_LIBUNWIND_IA64_H
01182   fprintf_filtered (stream, _("\
01183              --with-libunwind-ia64\n\
01184 "));
01185 #else
01186   fprintf_filtered (stream, _("\
01187              --without-libunwind-ia64\n\
01188 "));
01189 #endif
01190 #if HAVE_LIBLZMA
01191   fprintf_filtered (stream, _("\
01192              --with-lzma\n\
01193 "));
01194 #else
01195   fprintf_filtered (stream, _("\
01196              --without-lzma\n\
01197 "));
01198 #endif
01199 #ifdef WITH_PYTHON_PATH
01200   fprintf_filtered (stream, _("\
01201              --with-python=%s%s\n\
01202 "), WITH_PYTHON_PATH, PYTHON_PATH_RELOCATABLE ? " (relocatable)" : "");
01203 #endif
01204 #ifdef RELOC_SRCDIR
01205   fprintf_filtered (stream, _("\
01206              --with-relocated-sources=%s\n\
01207 "), RELOC_SRCDIR);
01208 #endif
01209   if (DEBUGDIR[0])
01210     fprintf_filtered (stream, _("\
01211              --with-separate-debug-dir=%s%s\n\
01212 "), DEBUGDIR, DEBUGDIR_RELOCATABLE ? " (relocatable)" : "");
01213   if (TARGET_SYSTEM_ROOT[0])
01214     fprintf_filtered (stream, _("\
01215              --with-sysroot=%s%s\n\
01216 "), TARGET_SYSTEM_ROOT, TARGET_SYSTEM_ROOT_RELOCATABLE ? " (relocatable)" : "");
01217   if (SYSTEM_GDBINIT[0])
01218     fprintf_filtered (stream, _("\
01219              --with-system-gdbinit=%s%s\n\
01220 "), SYSTEM_GDBINIT, SYSTEM_GDBINIT_RELOCATABLE ? " (relocatable)" : "");
01221 #if HAVE_ZLIB_H
01222   fprintf_filtered (stream, _("\
01223              --with-zlib\n\
01224 "));
01225 #else
01226   fprintf_filtered (stream, _("\
01227              --without-zlib\n\
01228 "));
01229 #endif
01230 #if HAVE_LIBBABELTRACE
01231     fprintf_filtered (stream, _("\
01232              --with-babeltrace\n\
01233 "));
01234 #else
01235     fprintf_filtered (stream, _("\
01236              --without-babeltrace\n\
01237 "));
01238 #endif
01239     /* We assume "relocatable" will be printed at least once, thus we always
01240        print this text.  It's a reasonably safe assumption for now.  */
01241     fprintf_filtered (stream, _("\n\
01242 (\"Relocatable\" means the directory can be moved with the GDB installation\n\
01243 tree, and GDB will still find it.)\n\
01244 "));
01245 }
01246 
01247 
01248 /* The current top level prompt, settable with "set prompt", and/or
01249    with the python `gdb.prompt_hook' hook.  */
01250 static char *top_prompt;
01251 
01252 /* Access method for the GDB prompt string.  */
01253 
01254 char *
01255 get_prompt (void)
01256 {
01257   return top_prompt;
01258 }
01259 
01260 /* Set method for the GDB prompt string.  */
01261 
01262 void
01263 set_prompt (const char *s)
01264 {
01265   char *p = xstrdup (s);
01266 
01267   xfree (top_prompt);
01268   top_prompt = p;
01269 }
01270 
01271 
01272 struct qt_args
01273 {
01274   char *args;
01275   int from_tty;
01276 };
01277 
01278 /* Callback for iterate_over_inferiors.  Kills or detaches the given
01279    inferior, depending on how we originally gained control of it.  */
01280 
01281 static int
01282 kill_or_detach (struct inferior *inf, void *args)
01283 {
01284   struct qt_args *qt = args;
01285   struct thread_info *thread;
01286 
01287   if (inf->pid == 0)
01288     return 0;
01289 
01290   thread = any_thread_of_process (inf->pid);
01291   if (thread != NULL)
01292     {
01293       switch_to_thread (thread->ptid);
01294 
01295       /* Leave core files alone.  */
01296       if (target_has_execution)
01297         {
01298           if (inf->attach_flag)
01299             target_detach (qt->args, qt->from_tty);
01300           else
01301             target_kill ();
01302         }
01303     }
01304 
01305   return 0;
01306 }
01307 
01308 /* Callback for iterate_over_inferiors.  Prints info about what GDB
01309    will do to each inferior on a "quit".  ARG points to a struct
01310    ui_out where output is to be collected.  */
01311 
01312 static int
01313 print_inferior_quit_action (struct inferior *inf, void *arg)
01314 {
01315   struct ui_file *stb = arg;
01316 
01317   if (inf->pid == 0)
01318     return 0;
01319 
01320   if (inf->attach_flag)
01321     fprintf_filtered (stb,
01322                       _("\tInferior %d [%s] will be detached.\n"), inf->num,
01323                       target_pid_to_str (pid_to_ptid (inf->pid)));
01324   else
01325     fprintf_filtered (stb,
01326                       _("\tInferior %d [%s] will be killed.\n"), inf->num,
01327                       target_pid_to_str (pid_to_ptid (inf->pid)));
01328 
01329   return 0;
01330 }
01331 
01332 /* If necessary, make the user confirm that we should quit.  Return
01333    non-zero if we should quit, zero if we shouldn't.  */
01334 
01335 int
01336 quit_confirm (void)
01337 {
01338   struct ui_file *stb;
01339   struct cleanup *old_chain;
01340   char *str;
01341   int qr;
01342 
01343   /* Don't even ask if we're only debugging a core file inferior.  */
01344   if (!have_live_inferiors ())
01345     return 1;
01346 
01347   /* Build the query string as a single string.  */
01348   stb = mem_fileopen ();
01349   old_chain = make_cleanup_ui_file_delete (stb);
01350 
01351   fprintf_filtered (stb, _("A debugging session is active.\n\n"));
01352   iterate_over_inferiors (print_inferior_quit_action, stb);
01353   fprintf_filtered (stb, _("\nQuit anyway? "));
01354 
01355   str = ui_file_xstrdup (stb, NULL);
01356   make_cleanup (xfree, str);
01357 
01358   qr = query ("%s", str);
01359   do_cleanups (old_chain);
01360   return qr;
01361 }
01362 
01363 /* Quit without asking for confirmation.  */
01364 
01365 void
01366 quit_force (char *args, int from_tty)
01367 {
01368   int exit_code = 0;
01369   struct qt_args qt;
01370   volatile struct gdb_exception ex;
01371 
01372   /* An optional expression may be used to cause gdb to terminate with the 
01373      value of that expression.  */
01374   if (args)
01375     {
01376       struct value *val = parse_and_eval (args);
01377 
01378       exit_code = (int) value_as_long (val);
01379     }
01380   else if (return_child_result)
01381     exit_code = return_child_result_value;
01382 
01383   qt.args = args;
01384   qt.from_tty = from_tty;
01385 
01386   /* Wrappers to make the code below a bit more readable.  */
01387 #define DO_TRY \
01388   TRY_CATCH (ex, RETURN_MASK_ALL)
01389 
01390 #define DO_PRINT_EX \
01391   if (ex.reason < 0) \
01392     exception_print (gdb_stderr, ex)
01393 
01394   /* We want to handle any quit errors and exit regardless.  */
01395 
01396   /* Get out of tfind mode, and kill or detach all inferiors.  */
01397   DO_TRY
01398     {
01399       disconnect_tracing ();
01400       iterate_over_inferiors (kill_or_detach, &qt);
01401     }
01402   DO_PRINT_EX;
01403 
01404   /* Give all pushed targets a chance to do minimal cleanup, and pop
01405      them all out.  */
01406   DO_TRY
01407     {
01408       pop_all_targets ();
01409     }
01410   DO_PRINT_EX;
01411 
01412   /* Save the history information if it is appropriate to do so.  */
01413   DO_TRY
01414     {
01415       if (write_history_p && history_filename
01416           && input_from_terminal_p ())
01417         write_history (history_filename);
01418     }
01419   DO_PRINT_EX;
01420 
01421   /* Do any final cleanups before exiting.  */
01422   DO_TRY
01423     {
01424       do_final_cleanups (all_cleanups ());
01425     }
01426   DO_PRINT_EX;
01427 
01428   exit (exit_code);
01429 }
01430 
01431 /* Returns whether GDB is running on a terminal and input is
01432    currently coming from that terminal.  */
01433 
01434 int
01435 input_from_terminal_p (void)
01436 {
01437   if (batch_flag)
01438     return 0;
01439 
01440   if (gdb_has_a_terminal () && instream == stdin)
01441     return 1;
01442 
01443   /* If INSTREAM is unset, and we are not in a user command, we
01444      must be in Insight.  That's like having a terminal, for our
01445      purposes.  */
01446   if (instream == NULL && !in_user_command)
01447     return 1;
01448 
01449   return 0;
01450 }
01451 
01452 static void
01453 dont_repeat_command (char *ignored, int from_tty)
01454 {
01455   /* Can't call dont_repeat here because we're not necessarily reading
01456      from stdin.  */
01457   *saved_command_line = 0;
01458 }
01459 
01460 /* Functions to manipulate command line editing control variables.  */
01461 
01462 /* Number of commands to print in each call to show_commands.  */
01463 #define Hist_print 10
01464 void
01465 show_commands (char *args, int from_tty)
01466 {
01467   /* Index for history commands.  Relative to history_base.  */
01468   int offset;
01469 
01470   /* Number of the history entry which we are planning to display next.
01471      Relative to history_base.  */
01472   static int num = 0;
01473 
01474   /* Print out some of the commands from the command history.  */
01475 
01476   if (args)
01477     {
01478       if (args[0] == '+' && args[1] == '\0')
01479         /* "info editing +" should print from the stored position.  */
01480         ;
01481       else
01482         /* "info editing <exp>" should print around command number <exp>.  */
01483         num = (parse_and_eval_long (args) - history_base) - Hist_print / 2;
01484     }
01485   /* "show commands" means print the last Hist_print commands.  */
01486   else
01487     {
01488       num = history_length - Hist_print;
01489     }
01490 
01491   if (num < 0)
01492     num = 0;
01493 
01494   /* If there are at least Hist_print commands, we want to display the last
01495      Hist_print rather than, say, the last 6.  */
01496   if (history_length - num < Hist_print)
01497     {
01498       num = history_length - Hist_print;
01499       if (num < 0)
01500         num = 0;
01501     }
01502 
01503   for (offset = num;
01504        offset < num + Hist_print && offset < history_length;
01505        offset++)
01506     {
01507       printf_filtered ("%5d  %s\n", history_base + offset,
01508                        (history_get (history_base + offset))->line);
01509     }
01510 
01511   /* The next command we want to display is the next one that we haven't
01512      displayed yet.  */
01513   num += Hist_print;
01514 
01515   /* If the user repeats this command with return, it should do what
01516      "show commands +" does.  This is unnecessary if arg is null,
01517      because "show commands +" is not useful after "show commands".  */
01518   if (from_tty && args)
01519     {
01520       args[0] = '+';
01521       args[1] = '\0';
01522     }
01523 }
01524 
01525 /* Called by do_setshow_command.  */
01526 static void
01527 set_history_size_command (char *args, int from_tty, struct cmd_list_element *c)
01528 {
01529   /* Readline's history interface works with 'int', so it can only
01530      handle history sizes up to INT_MAX.  The command itself is
01531      uinteger, so UINT_MAX means "unlimited", but we only get that if
01532      the user does "set history size 0" -- "set history size <UINT_MAX>"
01533      throws out-of-range.  */
01534   if (history_size_setshow_var > INT_MAX
01535       && history_size_setshow_var != UINT_MAX)
01536     {
01537       unsigned int new_value = history_size_setshow_var;
01538 
01539       /* Restore previous value before throwing.  */
01540       if (history_is_stifled ())
01541         history_size_setshow_var = history_max_entries;
01542       else
01543         history_size_setshow_var = UINT_MAX;
01544 
01545       error (_("integer %u out of range"), new_value);
01546     }
01547 
01548   /* Commit the new value to readline's history.  */
01549   if (history_size_setshow_var == UINT_MAX)
01550     unstifle_history ();
01551   else
01552     stifle_history (history_size_setshow_var);
01553 }
01554 
01555 void
01556 set_history (char *args, int from_tty)
01557 {
01558   printf_unfiltered (_("\"set history\" must be followed "
01559                        "by the name of a history subcommand.\n"));
01560   help_list (sethistlist, "set history ", -1, gdb_stdout);
01561 }
01562 
01563 void
01564 show_history (char *args, int from_tty)
01565 {
01566   cmd_show_list (showhistlist, from_tty, "");
01567 }
01568 
01569 int info_verbose = 0;           /* Default verbose msgs off.  */
01570 
01571 /* Called by do_setshow_command.  An elaborate joke.  */
01572 void
01573 set_verbose (char *args, int from_tty, struct cmd_list_element *c)
01574 {
01575   const char *cmdname = "verbose";
01576   struct cmd_list_element *showcmd;
01577 
01578   showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, 1);
01579   gdb_assert (showcmd != NULL && showcmd != CMD_LIST_AMBIGUOUS);
01580 
01581   if (info_verbose)
01582     {
01583       c->doc = "Set verbose printing of informational messages.";
01584       showcmd->doc = "Show verbose printing of informational messages.";
01585     }
01586   else
01587     {
01588       c->doc = "Set verbosity.";
01589       showcmd->doc = "Show verbosity.";
01590     }
01591 }
01592 
01593 /* Init the history buffer.  Note that we are called after the init file(s)
01594    have been read so that the user can change the history file via his
01595    .gdbinit file (for instance).  The GDBHISTFILE environment variable
01596    overrides all of this.  */
01597 
01598 void
01599 init_history (void)
01600 {
01601   char *tmpenv;
01602 
01603   tmpenv = getenv ("HISTSIZE");
01604   if (tmpenv)
01605     {
01606       int var;
01607 
01608       var = atoi (tmpenv);
01609       if (var < 0)
01610         {
01611           /* Prefer ending up with no history rather than overflowing
01612              readline's history interface, which uses signed 'int'
01613              everywhere.  */
01614           var = 0;
01615         }
01616 
01617       history_size_setshow_var = var;
01618     }
01619   /* If the init file hasn't set a size yet, pick the default.  */
01620   else if (history_size_setshow_var == 0)
01621     history_size_setshow_var = 256;
01622 
01623   /* Note that unlike "set history size 0", "HISTSIZE=0" really sets
01624      the history size to 0...  */
01625   stifle_history (history_size_setshow_var);
01626 
01627   tmpenv = getenv ("GDBHISTFILE");
01628   if (tmpenv)
01629     history_filename = xstrdup (tmpenv);
01630   else if (!history_filename)
01631     {
01632       /* We include the current directory so that if the user changes
01633          directories the file written will be the same as the one
01634          that was read.  */
01635 #ifdef __MSDOS__
01636       /* No leading dots in file names are allowed on MSDOS.  */
01637       history_filename = concat (current_directory, "/_gdb_history",
01638                                  (char *)NULL);
01639 #else
01640       history_filename = concat (current_directory, "/.gdb_history",
01641                                  (char *)NULL);
01642 #endif
01643     }
01644   read_history (history_filename);
01645 }
01646 
01647 static void
01648 show_prompt (struct ui_file *file, int from_tty,
01649              struct cmd_list_element *c, const char *value)
01650 {
01651   fprintf_filtered (file, _("Gdb's prompt is \"%s\".\n"), value);
01652 }
01653 
01654 static void
01655 show_async_command_editing_p (struct ui_file *file, int from_tty,
01656                               struct cmd_list_element *c, const char *value)
01657 {
01658   fprintf_filtered (file, _("Editing of command lines as "
01659                             "they are typed is %s.\n"),
01660                     value);
01661 }
01662 
01663 static void
01664 show_annotation_level (struct ui_file *file, int from_tty,
01665                        struct cmd_list_element *c, const char *value)
01666 {
01667   fprintf_filtered (file, _("Annotation_level is %s.\n"), value);
01668 }
01669 
01670 static void
01671 show_exec_done_display_p (struct ui_file *file, int from_tty,
01672                           struct cmd_list_element *c, const char *value)
01673 {
01674   fprintf_filtered (file, _("Notification of completion for "
01675                             "asynchronous execution commands is %s.\n"),
01676                     value);
01677 }
01678 
01679 /* "set" command for the gdb_datadir configuration variable.  */
01680 
01681 static void
01682 set_gdb_datadir (char *args, int from_tty, struct cmd_list_element *c)
01683 {
01684   observer_notify_gdb_datadir_changed ();
01685 }
01686 
01687 static void
01688 set_history_filename (char *args, int from_tty, struct cmd_list_element *c)
01689 {
01690   /* We include the current directory so that if the user changes
01691      directories the file written will be the same as the one
01692      that was read.  */
01693   if (!IS_ABSOLUTE_PATH (history_filename))
01694     history_filename = reconcat (history_filename, current_directory, "/", 
01695                                  history_filename, (char *) NULL);
01696 }
01697 
01698 static void
01699 init_main (void)
01700 {
01701   /* Initialize the prompt to a simple "(gdb) " prompt or to whatever
01702      the DEFAULT_PROMPT is.  */
01703   set_prompt (DEFAULT_PROMPT);
01704 
01705   /* Set things up for annotation_level > 1, if the user ever decides
01706      to use it.  */
01707   async_annotation_suffix = "prompt";
01708 
01709   /* Set the important stuff up for command editing.  */
01710   command_editing_p = 1;
01711   history_expansion_p = 0;
01712   write_history_p = 0;
01713 
01714   /* Setup important stuff for command line editing.  */
01715   rl_completion_word_break_hook = gdb_completion_word_break_characters;
01716   rl_completion_entry_function = readline_line_completion_function;
01717   rl_completer_word_break_characters = default_word_break_characters ();
01718   rl_completer_quote_characters = get_gdb_completer_quote_characters ();
01719   rl_readline_name = "gdb";
01720   rl_terminal_name = getenv ("TERM");
01721 
01722   /* The name for this defun comes from Bash, where it originated.
01723      15 is Control-o, the same binding this function has in Bash.  */
01724   rl_add_defun ("operate-and-get-next", gdb_rl_operate_and_get_next, 15);
01725 
01726   add_setshow_string_cmd ("prompt", class_support,
01727                           &top_prompt,
01728                           _("Set gdb's prompt"),
01729                           _("Show gdb's prompt"),
01730                           NULL, NULL,
01731                           show_prompt,
01732                           &setlist, &showlist);
01733 
01734   add_com ("dont-repeat", class_support, dont_repeat_command, _("\
01735 Don't repeat this command.\nPrimarily \
01736 used inside of user-defined commands that should not be repeated when\n\
01737 hitting return."));
01738 
01739   add_setshow_boolean_cmd ("editing", class_support,
01740                            &async_command_editing_p, _("\
01741 Set editing of command lines as they are typed."), _("\
01742 Show editing of command lines as they are typed."), _("\
01743 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
01744 Without an argument, command line editing is enabled.  To edit, use\n\
01745 EMACS-like or VI-like commands like control-P or ESC."),
01746                            set_async_editing_command,
01747                            show_async_command_editing_p,
01748                            &setlist, &showlist);
01749 
01750   add_setshow_boolean_cmd ("save", no_class, &write_history_p, _("\
01751 Set saving of the history record on exit."), _("\
01752 Show saving of the history record on exit."), _("\
01753 Use \"on\" to enable the saving, and \"off\" to disable it.\n\
01754 Without an argument, saving is enabled."),
01755                            NULL,
01756                            show_write_history_p,
01757                            &sethistlist, &showhistlist);
01758 
01759   add_setshow_uinteger_cmd ("size", no_class, &history_size_setshow_var, _("\
01760 Set the size of the command history,"), _("\
01761 Show the size of the command history,"), _("\
01762 ie. the number of previous commands to keep a record of.\n\
01763 If set to \"unlimited\", the number of commands kept in the history\n\
01764 list is unlimited.  This defaults to the value of the environment\n\
01765 variable \"HISTSIZE\", or to 256 if this variable is not set."),
01766                             set_history_size_command,
01767                             show_history_size,
01768                             &sethistlist, &showhistlist);
01769 
01770   add_setshow_filename_cmd ("filename", no_class, &history_filename, _("\
01771 Set the filename in which to record the command history"), _("\
01772 Show the filename in which to record the command history"), _("\
01773 (the list of previous commands of which a record is kept)."),
01774                             set_history_filename,
01775                             show_history_filename,
01776                             &sethistlist, &showhistlist);
01777 
01778   add_setshow_boolean_cmd ("confirm", class_support, &confirm, _("\
01779 Set whether to confirm potentially dangerous operations."), _("\
01780 Show whether to confirm potentially dangerous operations."), NULL,
01781                            NULL,
01782                            show_confirm,
01783                            &setlist, &showlist);
01784 
01785   add_setshow_zinteger_cmd ("annotate", class_obscure, &annotation_level, _("\
01786 Set annotation_level."), _("\
01787 Show annotation_level."), _("\
01788 0 == normal;     1 == fullname (for use when running under emacs)\n\
01789 2 == output annotated suitably for use by programs that control GDB."),
01790                             NULL,
01791                             show_annotation_level,
01792                             &setlist, &showlist);
01793 
01794   add_setshow_boolean_cmd ("exec-done-display", class_support,
01795                            &exec_done_display_p, _("\
01796 Set notification of completion for asynchronous execution commands."), _("\
01797 Show notification of completion for asynchronous execution commands."), _("\
01798 Use \"on\" to enable the notification, and \"off\" to disable it."),
01799                            NULL,
01800                            show_exec_done_display_p,
01801                            &setlist, &showlist);
01802 
01803   add_setshow_filename_cmd ("data-directory", class_maintenance,
01804                            &gdb_datadir, _("Set GDB's data directory."),
01805                            _("Show GDB's data directory."),
01806                            _("\
01807 When set, GDB uses the specified path to search for data files."),
01808                            set_gdb_datadir, NULL,
01809                            &setlist,
01810                            &showlist);
01811 }
01812 
01813 void
01814 gdb_init (char *argv0)
01815 {
01816   if (pre_init_ui_hook)
01817     pre_init_ui_hook ();
01818 
01819   /* Run the init function of each source file.  */
01820 
01821 #ifdef __MSDOS__
01822   /* Make sure we return to the original directory upon exit, come
01823      what may, since the OS doesn't do that for us.  */
01824   make_final_cleanup (do_chdir_cleanup, xstrdup (current_directory));
01825 #endif
01826 
01827   init_cmd_lists ();        /* This needs to be done first.  */
01828   initialize_targets ();    /* Setup target_terminal macros for utils.c.  */
01829   initialize_utils ();      /* Make errors and warnings possible.  */
01830 
01831   /* Here is where we call all the _initialize_foo routines.  */
01832   initialize_all_files ();
01833 
01834   /* This creates the current_program_space.  Do this after all the
01835      _initialize_foo routines have had a chance to install their
01836      per-sspace data keys.  Also do this before
01837      initialize_current_architecture is called, because it accesses
01838      exec_bfd of the current program space.  */
01839   initialize_progspace ();
01840   initialize_inferiors ();
01841   initialize_current_architecture ();
01842   init_cli_cmds();
01843   initialize_event_loop ();
01844   init_main ();                 /* But that omits this file!  Do it now.  */
01845 
01846   initialize_stdin_serial ();
01847 
01848   async_init_signals ();
01849 
01850   /* We need a default language for parsing expressions, so simple
01851      things like "set width 0" won't fail if no language is explicitly
01852      set in a config file or implicitly set by reading an executable
01853      during startup.  */
01854   set_language (language_c);
01855   expected_language = current_language; /* Don't warn about the change.  */
01856 
01857   /* Allow another UI to initialize.  If the UI fails to initialize,
01858      and it wants GDB to revert to the CLI, it should clear
01859      deprecated_init_ui_hook.  */
01860   if (deprecated_init_ui_hook)
01861     deprecated_init_ui_hook (argv0);
01862 
01863 #ifdef HAVE_PYTHON
01864   /* Python initialization can require various commands to be
01865      installed.  For example "info pretty-printer" needs the "info"
01866      prefix to be installed.  Keep things simple and just do final
01867      python initialization here.  */
01868   finish_python_initialization ();
01869 #endif
01870 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines