Make sure terminal settings are restored before exiting
[external/binutils.git] / gdb / top.c
1 /* Top level stuff for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2015 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "gdbcmd.h"
22 #include "cli/cli-cmds.h"
23 #include "cli/cli-script.h"
24 #include "cli/cli-setshow.h"
25 #include "cli/cli-decode.h"
26 #include "symtab.h"
27 #include "inferior.h"
28 #include "infrun.h"
29 #include <signal.h>
30 #include "target.h"
31 #include "target-dcache.h"
32 #include "breakpoint.h"
33 #include "gdbtypes.h"
34 #include "expression.h"
35 #include "value.h"
36 #include "language.h"
37 #include "terminal.h"           /* For job_control.  */
38 #include "annotate.h"
39 #include "completer.h"
40 #include "top.h"
41 #include "version.h"
42 #include "serial.h"
43 #include "doublest.h"
44 #include "main.h"
45 #include "event-loop.h"
46 #include "gdbthread.h"
47 #include "extension.h"
48 #include "interps.h"
49 #include "observer.h"
50 #include "maint.h"
51 #include "filenames.h"
52
53 /* readline include files.  */
54 #include "readline/readline.h"
55 #include "readline/history.h"
56
57 /* readline defines this.  */
58 #undef savestring
59
60 #include <sys/types.h>
61
62 #include "event-top.h"
63 #include <sys/stat.h>
64 #include <ctype.h>
65 #include "ui-out.h"
66 #include "cli-out.h"
67 #include "tracepoint.h"
68 #include "inf-loop.h"
69
70 #if defined(TUI)
71 # include "tui/tui.h"
72 #endif
73
74 extern void initialize_all_files (void);
75
76 #define PROMPT(X) the_prompts.prompt_stack[the_prompts.top + X].prompt
77 #define PREFIX(X) the_prompts.prompt_stack[the_prompts.top + X].prefix
78 #define SUFFIX(X) the_prompts.prompt_stack[the_prompts.top + X].suffix
79
80 /* Default command line prompt.  This is overriden in some configs.  */
81
82 #ifndef DEFAULT_PROMPT
83 #define DEFAULT_PROMPT  "(gdb) "
84 #endif
85
86 /* Initialization file name for gdb.  This is host-dependent.  */
87
88 const char gdbinit[] = GDBINIT;
89
90 int inhibit_gdbinit = 0;
91
92 extern char lang_frame_mismatch_warn[];         /* language.c */
93
94 /* Flag for whether we want to confirm potentially dangerous
95    operations.  Default is yes.  */
96
97 int confirm = 1;
98
99 static void
100 show_confirm (struct ui_file *file, int from_tty,
101               struct cmd_list_element *c, const char *value)
102 {
103   fprintf_filtered (file, _("Whether to confirm potentially "
104                             "dangerous operations is %s.\n"),
105                     value);
106 }
107
108 /* stdio stream that command input is being read from.  Set to stdin
109    normally.  Set by source_command to the file we are sourcing.  Set
110    to NULL if we are executing a user-defined command or interacting
111    via a GUI.  */
112
113 FILE *instream;
114
115 /* Flag to indicate whether a user defined command is currently running.  */
116
117 int in_user_command;
118
119 /* Current working directory.  */
120
121 char *current_directory;
122
123 /* The directory name is actually stored here (usually).  */
124 char gdb_dirbuf[1024];
125
126 /* Function to call before reading a command, if nonzero.
127    The function receives two args: an input stream,
128    and a prompt string.  */
129
130 void (*window_hook) (FILE *, char *);
131
132 /* Buffer used for reading command lines, and the size
133    allocated for it so far.  */
134
135 char *saved_command_line;
136 int saved_command_line_size = 100;
137
138 /* Nonzero if the current command is modified by "server ".  This
139    affects things like recording into the command history, commands
140    repeating on RETURN, etc.  This is so a user interface (emacs, GUI,
141    whatever) can issue its own commands and also send along commands
142    from the user, and have the user not notice that the user interface
143    is issuing commands too.  */
144 int server_command;
145
146 /* Timeout limit for response from target.  */
147
148 /* The default value has been changed many times over the years.  It 
149    was originally 5 seconds.  But that was thought to be a long time 
150    to sit and wait, so it was changed to 2 seconds.  That was thought
151    to be plenty unless the connection was going through some terminal 
152    server or multiplexer or other form of hairy serial connection.
153
154    In mid-1996, remote_timeout was moved from remote.c to top.c and 
155    it began being used in other remote-* targets.  It appears that the
156    default was changed to 20 seconds at that time, perhaps because the
157    Renesas E7000 ICE didn't always respond in a timely manner.
158
159    But if 5 seconds is a long time to sit and wait for retransmissions,
160    20 seconds is far worse.  This demonstrates the difficulty of using 
161    a single variable for all protocol timeouts.
162
163    As remote.c is used much more than remote-e7000.c, it was changed 
164    back to 2 seconds in 1999.  */
165
166 int remote_timeout = 2;
167
168 /* Non-zero tells remote* modules to output debugging info.  */
169
170 int remote_debug = 0;
171
172 /* Sbrk location on entry to main.  Used for statistics only.  */
173 #ifdef HAVE_SBRK
174 char *lim_at_start;
175 #endif
176
177 /* Hooks for alternate command interfaces.  */
178
179 /* This hook is called from within gdb's many mini-event loops which
180    could steal control from a real user interface's event loop.  It
181    returns non-zero if the user is requesting a detach, zero
182    otherwise.  */
183
184 int (*deprecated_ui_loop_hook) (int);
185
186
187 /* Called from print_frame_info to list the line we stopped in.  */
188
189 void (*deprecated_print_frame_info_listing_hook) (struct symtab * s, 
190                                                   int line,
191                                                   int stopline, 
192                                                   int noerror);
193 /* Replaces most of query.  */
194
195 int (*deprecated_query_hook) (const char *, va_list);
196
197 /* Replaces most of warning.  */
198
199 void (*deprecated_warning_hook) (const char *, va_list);
200
201 /* These three functions support getting lines of text from the user.
202    They are used in sequence.  First deprecated_readline_begin_hook is
203    called with a text string that might be (for example) a message for
204    the user to type in a sequence of commands to be executed at a
205    breakpoint.  If this function calls back to a GUI, it might take
206    this opportunity to pop up a text interaction window with this
207    message.  Next, deprecated_readline_hook is called with a prompt
208    that is emitted prior to collecting the user input.  It can be
209    called multiple times.  Finally, deprecated_readline_end_hook is
210    called to notify the GUI that we are done with the interaction
211    window and it can close it.  */
212
213 void (*deprecated_readline_begin_hook) (char *, ...);
214 char *(*deprecated_readline_hook) (const char *);
215 void (*deprecated_readline_end_hook) (void);
216
217 /* Called as appropriate to notify the interface that we have attached
218    to or detached from an already running process.  */
219
220 void (*deprecated_attach_hook) (void);
221 void (*deprecated_detach_hook) (void);
222
223 /* Called during long calculations to allow GUI to repair window
224    damage, and to check for stop buttons, etc...  */
225
226 void (*deprecated_interactive_hook) (void);
227
228 /* Called when going to wait for the target.  Usually allows the GUI
229    to run while waiting for target events.  */
230
231 ptid_t (*deprecated_target_wait_hook) (ptid_t ptid,
232                                        struct target_waitstatus *status,
233                                        int options);
234
235 /* Used by UI as a wrapper around command execution.  May do various
236    things like enabling/disabling buttons, etc...  */
237
238 void (*deprecated_call_command_hook) (struct cmd_list_element * c, 
239                                       char *cmd, int from_tty);
240
241 /* Called when the current thread changes.  Argument is thread id.  */
242
243 void (*deprecated_context_hook) (int id);
244
245 /* Handler for SIGHUP.  */
246
247 #ifdef SIGHUP
248 /* NOTE 1999-04-29: This function will be static again, once we modify
249    gdb to use the event loop as the default command loop and we merge
250    event-top.c into this file, top.c.  */
251 /* static */ void
252 quit_cover (void)
253 {
254   /* Stop asking user for confirmation --- we're exiting.  This
255      prevents asking the user dumb questions.  */
256   confirm = 0;
257   quit_command ((char *) 0, 0);
258 }
259 #endif /* defined SIGHUP */
260 \f
261 /* Line number we are currently in, in a file which is being sourced.  */
262 /* NOTE 1999-04-29: This variable will be static again, once we modify
263    gdb to use the event loop as the default command loop and we merge
264    event-top.c into this file, top.c.  */
265 /* static */ int source_line_number;
266
267 /* Name of the file we are sourcing.  */
268 /* NOTE 1999-04-29: This variable will be static again, once we modify
269    gdb to use the event loop as the default command loop and we merge
270    event-top.c into this file, top.c.  */
271 /* static */ const char *source_file_name;
272
273 /* Clean up on error during a "source" command (or execution of a
274    user-defined command).  */
275
276 void
277 do_restore_instream_cleanup (void *stream)
278 {
279   /* Restore the previous input stream.  */
280   instream = stream;
281 }
282
283 /* Read commands from STREAM.  */
284 void
285 read_command_file (FILE *stream)
286 {
287   struct cleanup *cleanups;
288
289   cleanups = make_cleanup (do_restore_instream_cleanup, instream);
290   instream = stream;
291   command_loop ();
292   do_cleanups (cleanups);
293 }
294 \f
295 void (*pre_init_ui_hook) (void);
296
297 #ifdef __MSDOS__
298 static void
299 do_chdir_cleanup (void *old_dir)
300 {
301   chdir (old_dir);
302   xfree (old_dir);
303 }
304 #endif
305
306 struct cleanup *
307 prepare_execute_command (void)
308 {
309   struct value *mark;
310   struct cleanup *cleanup;
311
312   mark = value_mark ();
313   cleanup = make_cleanup_value_free_to_mark (mark);
314
315   /* With multiple threads running while the one we're examining is
316      stopped, the dcache can get stale without us being able to detect
317      it.  For the duration of the command, though, use the dcache to
318      help things like backtrace.  */
319   if (non_stop)
320     target_dcache_invalidate ();
321
322   return cleanup;
323 }
324
325 /* Tell the user if the language has changed (except first time) after
326    executing a command.  */
327
328 void
329 check_frame_language_change (void)
330 {
331   static int warned = 0;
332
333   /* First make sure that a new frame has been selected, in case the
334      command or the hooks changed the program state.  */
335   deprecated_safe_get_selected_frame ();
336   if (current_language != expected_language)
337     {
338       if (language_mode == language_mode_auto && info_verbose)
339         {
340           language_info (1);    /* Print what changed.  */
341         }
342       warned = 0;
343     }
344
345   /* Warn the user if the working language does not match the language
346      of the current frame.  Only warn the user if we are actually
347      running the program, i.e. there is a stack.  */
348   /* FIXME: This should be cacheing the frame and only running when
349      the frame changes.  */
350
351   if (has_stack_frames ())
352     {
353       enum language flang;
354
355       flang = get_frame_language ();
356       if (!warned
357           && flang != language_unknown
358           && flang != current_language->la_language)
359         {
360           printf_filtered ("%s\n", lang_frame_mismatch_warn);
361           warned = 1;
362         }
363     }
364 }
365
366 /* See top.h.  */
367
368 void
369 maybe_wait_sync_command_done (int was_sync)
370 {
371   /* If the interpreter is in sync mode (we're running a user
372      command's list, running command hooks or similars), and we
373      just ran a synchronous command that started the target, wait
374      for that command to end.  */
375   if (!interpreter_async && !was_sync && sync_execution)
376     {
377       while (gdb_do_one_event () >= 0)
378         if (!sync_execution)
379           break;
380     }
381 }
382
383 /* Execute the line P as a command, in the current user context.
384    Pass FROM_TTY as second argument to the defining function.  */
385
386 void
387 execute_command (char *p, int from_tty)
388 {
389   struct cleanup *cleanup_if_error, *cleanup;
390   struct cmd_list_element *c;
391   char *line;
392
393   cleanup_if_error = make_bpstat_clear_actions_cleanup ();
394   cleanup = prepare_execute_command ();
395
396   /* Force cleanup of any alloca areas if using C alloca instead of
397      a builtin alloca.  */
398   alloca (0);
399
400   /* This can happen when command_line_input hits end of file.  */
401   if (p == NULL)
402     {
403       do_cleanups (cleanup);
404       discard_cleanups (cleanup_if_error);
405       return;
406     }
407
408   target_log_command (p);
409
410   while (*p == ' ' || *p == '\t')
411     p++;
412   if (*p)
413     {
414       const char *cmd = p;
415       char *arg;
416       int was_sync = sync_execution;
417
418       line = p;
419
420       /* If trace-commands is set then this will print this command.  */
421       print_command_trace (p);
422
423       c = lookup_cmd (&cmd, cmdlist, "", 0, 1);
424       p = (char *) cmd;
425
426       /* Pass null arg rather than an empty one.  */
427       arg = *p ? p : 0;
428
429       /* FIXME: cagney/2002-02-02: The c->type test is pretty dodgy
430          while the is_complete_command(cfunc) test is just plain
431          bogus.  They should both be replaced by a test of the form
432          c->strip_trailing_white_space_p.  */
433       /* NOTE: cagney/2002-02-02: The function.cfunc in the below
434          can't be replaced with func.  This is because it is the
435          cfunc, and not the func, that has the value that the
436          is_complete_command hack is testing for.  */
437       /* Clear off trailing whitespace, except for set and complete
438          command.  */
439       if (arg
440           && c->type != set_cmd
441           && !is_complete_command (c))
442         {
443           p = arg + strlen (arg) - 1;
444           while (p >= arg && (*p == ' ' || *p == '\t'))
445             p--;
446           *(p + 1) = '\0';
447         }
448
449       /* If this command has been pre-hooked, run the hook first.  */
450       execute_cmd_pre_hook (c);
451
452       if (c->deprecated_warn_user)
453         deprecated_cmd_warning (line);
454
455       /* c->user_commands would be NULL in the case of a python command.  */
456       if (c->theclass == class_user && c->user_commands)
457         execute_user_command (c, arg);
458       else if (c->type == set_cmd)
459         do_set_command (arg, from_tty, c);
460       else if (c->type == show_cmd)
461         do_show_command (arg, from_tty, c);
462       else if (!cmd_func_p (c))
463         error (_("That is not a command, just a help topic."));
464       else if (deprecated_call_command_hook)
465         deprecated_call_command_hook (c, arg, from_tty);
466       else
467         cmd_func (c, arg, from_tty);
468
469       maybe_wait_sync_command_done (was_sync);
470
471       /* If this command has been post-hooked, run the hook last.  */
472       execute_cmd_post_hook (c);
473
474     }
475
476   check_frame_language_change ();
477
478   do_cleanups (cleanup);
479   discard_cleanups (cleanup_if_error);
480 }
481
482 /* Run execute_command for P and FROM_TTY.  Capture its output into the
483    returned string, do not display it to the screen.  BATCH_FLAG will be
484    temporarily set to true.  */
485
486 char *
487 execute_command_to_string (char *p, int from_tty)
488 {
489   struct ui_file *str_file;
490   struct cleanup *cleanup;
491   char *retval;
492
493   /* GDB_STDOUT should be better already restored during these
494      restoration callbacks.  */
495   cleanup = set_batch_flag_and_make_cleanup_restore_page_info ();
496
497   make_cleanup_restore_integer (&interpreter_async);
498   interpreter_async = 0;
499
500   str_file = mem_fileopen ();
501
502   make_cleanup_ui_file_delete (str_file);
503   make_cleanup_restore_ui_file (&gdb_stdout);
504   make_cleanup_restore_ui_file (&gdb_stderr);
505   make_cleanup_restore_ui_file (&gdb_stdlog);
506   make_cleanup_restore_ui_file (&gdb_stdtarg);
507   make_cleanup_restore_ui_file (&gdb_stdtargerr);
508
509   if (ui_out_redirect (current_uiout, str_file) < 0)
510     warning (_("Current output protocol does not support redirection"));
511   else
512     make_cleanup_ui_out_redirect_pop (current_uiout);
513
514   gdb_stdout = str_file;
515   gdb_stderr = str_file;
516   gdb_stdlog = str_file;
517   gdb_stdtarg = str_file;
518   gdb_stdtargerr = str_file;
519
520   execute_command (p, from_tty);
521
522   retval = ui_file_xstrdup (str_file, NULL);
523
524   do_cleanups (cleanup);
525
526   return retval;
527 }
528
529 /* Read commands from `instream' and execute them
530    until end of file or error reading instream.  */
531
532 void
533 command_loop (void)
534 {
535   struct cleanup *old_chain;
536   char *command;
537   int stdin_is_tty = ISATTY (stdin);
538
539   while (instream && !feof (instream))
540     {
541       if (window_hook && instream == stdin)
542         (*window_hook) (instream, get_prompt ());
543
544       clear_quit_flag ();
545       if (instream == stdin && stdin_is_tty)
546         reinitialize_more_filter ();
547       old_chain = make_cleanup (null_cleanup, 0);
548
549       /* Get a command-line.  This calls the readline package.  */
550       command = command_line_input (instream == stdin ?
551                                     get_prompt () : (char *) NULL,
552                                     instream == stdin, "prompt");
553       if (command == 0)
554         {
555           do_cleanups (old_chain);
556           return;
557         }
558
559       make_command_stats_cleanup (1);
560
561       /* Do not execute commented lines.  */
562       if (command[0] != '#')
563         {
564           execute_command (command, instream == stdin);
565
566           /* Do any commands attached to breakpoint we are stopped at.  */
567           bpstat_do_actions ();
568         }
569       do_cleanups (old_chain);
570     }
571 }
572 \f
573 /* When nonzero, cause dont_repeat to do nothing.  This should only be
574    set via prevent_dont_repeat.  */
575
576 static int suppress_dont_repeat = 0;
577
578 /* Commands call this if they do not want to be repeated by null lines.  */
579
580 void
581 dont_repeat (void)
582 {
583   if (suppress_dont_repeat || server_command)
584     return;
585
586   /* If we aren't reading from standard input, we are saving the last
587      thing read from stdin in line and don't want to delete it.  Null
588      lines won't repeat here in any case.  */
589   if (instream == stdin)
590     *saved_command_line = 0;
591 }
592
593 /* Prevent dont_repeat from working, and return a cleanup that
594    restores the previous state.  */
595
596 struct cleanup *
597 prevent_dont_repeat (void)
598 {
599   struct cleanup *result = make_cleanup_restore_integer (&suppress_dont_repeat);
600
601   suppress_dont_repeat = 1;
602   return result;
603 }
604
605 \f
606 /* Read a line from the stream "instream" without command line editing.
607
608    It prints PROMPT_ARG once at the start.
609    Action is compatible with "readline", e.g. space for the result is
610    malloc'd and should be freed by the caller.
611
612    A NULL return means end of file.  */
613 char *
614 gdb_readline (const char *prompt_arg)
615 {
616   int c;
617   char *result;
618   int input_index = 0;
619   int result_size = 80;
620
621   if (prompt_arg)
622     {
623       /* Don't use a _filtered function here.  It causes the assumed
624          character position to be off, since the newline we read from
625          the user is not accounted for.  */
626       fputs_unfiltered (prompt_arg, gdb_stdout);
627       gdb_flush (gdb_stdout);
628     }
629
630   result = (char *) xmalloc (result_size);
631
632   while (1)
633     {
634       /* Read from stdin if we are executing a user defined command.
635          This is the right thing for prompt_for_continue, at least.  */
636       c = fgetc (instream ? instream : stdin);
637
638       if (c == EOF)
639         {
640           if (input_index > 0)
641             /* The last line does not end with a newline.  Return it, and
642                if we are called again fgetc will still return EOF and
643                we'll return NULL then.  */
644             break;
645           xfree (result);
646           return NULL;
647         }
648
649       if (c == '\n')
650         {
651           if (input_index > 0 && result[input_index - 1] == '\r')
652             input_index--;
653           break;
654         }
655
656       result[input_index++] = c;
657       while (input_index >= result_size)
658         {
659           result_size *= 2;
660           result = (char *) xrealloc (result, result_size);
661         }
662     }
663
664   result[input_index++] = '\0';
665   return result;
666 }
667
668 /* Variables which control command line editing and history
669    substitution.  These variables are given default values at the end
670    of this file.  */
671 static int command_editing_p;
672
673 /* NOTE 1999-04-29: This variable will be static again, once we modify
674    gdb to use the event loop as the default command loop and we merge
675    event-top.c into this file, top.c.  */
676
677 /* static */ int history_expansion_p;
678
679 static int write_history_p;
680 static void
681 show_write_history_p (struct ui_file *file, int from_tty,
682                       struct cmd_list_element *c, const char *value)
683 {
684   fprintf_filtered (file, _("Saving of the history record on exit is %s.\n"),
685                     value);
686 }
687
688 /* The variable associated with the "set/show history size"
689    command.  The value -1 means unlimited, and -2 means undefined.  */
690 static int history_size_setshow_var = -2;
691
692 static void
693 show_history_size (struct ui_file *file, int from_tty,
694                    struct cmd_list_element *c, const char *value)
695 {
696   fprintf_filtered (file, _("The size of the command history is %s.\n"),
697                     value);
698 }
699
700 /* Variable associated with the "history remove-duplicates" option.
701    The value -1 means unlimited.  */
702 static int history_remove_duplicates = 0;
703
704 static void
705 show_history_remove_duplicates (struct ui_file *file, int from_tty,
706                                 struct cmd_list_element *c, const char *value)
707 {
708   fprintf_filtered (file,
709                     _("The number of history entries to look back at for "
710                       "duplicates is %s.\n"),
711                     value);
712 }
713
714 static char *history_filename;
715 static void
716 show_history_filename (struct ui_file *file, int from_tty,
717                        struct cmd_list_element *c, const char *value)
718 {
719   fprintf_filtered (file, _("The filename in which to record "
720                             "the command history is \"%s\".\n"),
721                     value);
722 }
723
724 /* This is like readline(), but it has some gdb-specific behavior.
725    gdb may want readline in both the synchronous and async modes during
726    a single gdb invocation.  At the ordinary top-level prompt we might
727    be using the async readline.  That means we can't use
728    rl_pre_input_hook, since it doesn't work properly in async mode.
729    However, for a secondary prompt (" >", such as occurs during a
730    `define'), gdb wants a synchronous response.
731
732    We used to call readline() directly, running it in synchronous
733    mode.  But mixing modes this way is not supported, and as of
734    readline 5.x it no longer works; the arrow keys come unbound during
735    the synchronous call.  So we make a nested call into the event
736    loop.  That's what gdb_readline_wrapper is for.  */
737
738 /* A flag set as soon as gdb_readline_wrapper_line is called; we can't
739    rely on gdb_readline_wrapper_result, which might still be NULL if
740    the user types Control-D for EOF.  */
741 static int gdb_readline_wrapper_done;
742
743 /* The result of the current call to gdb_readline_wrapper, once a newline
744    is seen.  */
745 static char *gdb_readline_wrapper_result;
746
747 /* Any intercepted hook.  Operate-and-get-next sets this, expecting it
748    to be called after the newline is processed (which will redisplay
749    the prompt).  But in gdb_readline_wrapper we will not get a new
750    prompt until the next call, or until we return to the event loop.
751    So we disable this hook around the newline and restore it before we
752    return.  */
753 static void (*saved_after_char_processing_hook) (void);
754
755 /* This function is called when readline has seen a complete line of
756    text.  */
757
758 static void
759 gdb_readline_wrapper_line (char *line)
760 {
761   gdb_assert (!gdb_readline_wrapper_done);
762   gdb_readline_wrapper_result = line;
763   gdb_readline_wrapper_done = 1;
764
765   /* Prevent operate-and-get-next from acting too early.  */
766   saved_after_char_processing_hook = after_char_processing_hook;
767   after_char_processing_hook = NULL;
768
769   /* Prevent parts of the prompt from being redisplayed if annotations
770      are enabled, and readline's state getting out of sync.  We'll
771      reinstall the callback handler, which puts the terminal in raw
772      mode (or in readline lingo, in prepped state), when we're next
773      ready to process user input, either in display_gdb_prompt, or if
774      we're handling an asynchronous target event and running in the
775      background, just before returning to the event loop to process
776      further input (or more target events).  */
777   if (async_command_editing_p)
778     gdb_rl_callback_handler_remove ();
779 }
780
781 struct gdb_readline_wrapper_cleanup
782   {
783     void (*handler_orig) (char *);
784     int already_prompted_orig;
785
786     /* Whether the target was async.  */
787     int target_is_async_orig;
788   };
789
790 static void
791 gdb_readline_wrapper_cleanup (void *arg)
792 {
793   struct gdb_readline_wrapper_cleanup *cleanup = arg;
794
795   rl_already_prompted = cleanup->already_prompted_orig;
796
797   gdb_assert (input_handler == gdb_readline_wrapper_line);
798   input_handler = cleanup->handler_orig;
799
800   /* Don't restore our input handler in readline yet.  That would make
801      readline prep the terminal (putting it in raw mode), while the
802      line we just read may trigger execution of a command that expects
803      the terminal in the default cooked/canonical mode, such as e.g.,
804      running Python's interactive online help utility.  See
805      gdb_readline_wrapper_line for when we'll reinstall it.  */
806
807   gdb_readline_wrapper_result = NULL;
808   gdb_readline_wrapper_done = 0;
809
810   after_char_processing_hook = saved_after_char_processing_hook;
811   saved_after_char_processing_hook = NULL;
812
813   if (cleanup->target_is_async_orig)
814     target_async (1);
815
816   xfree (cleanup);
817 }
818
819 char *
820 gdb_readline_wrapper (const char *prompt)
821 {
822   struct cleanup *back_to;
823   struct gdb_readline_wrapper_cleanup *cleanup;
824   char *retval;
825
826   cleanup = xmalloc (sizeof (*cleanup));
827   cleanup->handler_orig = input_handler;
828   input_handler = gdb_readline_wrapper_line;
829
830   cleanup->already_prompted_orig = rl_already_prompted;
831
832   cleanup->target_is_async_orig = target_is_async_p ();
833
834   back_to = make_cleanup (gdb_readline_wrapper_cleanup, cleanup);
835
836   if (cleanup->target_is_async_orig)
837     target_async (0);
838
839   /* Display our prompt and prevent double prompt display.  */
840   display_gdb_prompt (prompt);
841   rl_already_prompted = 1;
842
843   if (after_char_processing_hook)
844     (*after_char_processing_hook) ();
845   gdb_assert (after_char_processing_hook == NULL);
846
847   while (gdb_do_one_event () >= 0)
848     if (gdb_readline_wrapper_done)
849       break;
850
851   retval = gdb_readline_wrapper_result;
852   do_cleanups (back_to);
853   return retval;
854 }
855
856 \f
857 /* The current saved history number from operate-and-get-next.
858    This is -1 if not valid.  */
859 static int operate_saved_history = -1;
860
861 /* This is put on the appropriate hook and helps operate-and-get-next
862    do its work.  */
863 static void
864 gdb_rl_operate_and_get_next_completion (void)
865 {
866   int delta = where_history () - operate_saved_history;
867
868   /* The `key' argument to rl_get_previous_history is ignored.  */
869   rl_get_previous_history (delta, 0);
870   operate_saved_history = -1;
871
872   /* readline doesn't automatically update the display for us.  */
873   rl_redisplay ();
874
875   after_char_processing_hook = NULL;
876   rl_pre_input_hook = NULL;
877 }
878
879 /* This is a gdb-local readline command handler.  It accepts the
880    current command line (like RET does) and, if this command was taken
881    from the history, arranges for the next command in the history to
882    appear on the command line when the prompt returns.
883    We ignore the arguments.  */
884 static int
885 gdb_rl_operate_and_get_next (int count, int key)
886 {
887   int where;
888
889   /* Use the async hook.  */
890   after_char_processing_hook = gdb_rl_operate_and_get_next_completion;
891
892   /* Find the current line, and find the next line to use.  */
893   where = where_history();
894
895   if ((history_is_stifled () && (history_length >= history_max_entries))
896       || (where >= history_length - 1))
897     operate_saved_history = where;
898   else
899     operate_saved_history = where + 1;
900
901   return rl_newline (1, key);
902 }
903
904 /* Number of user commands executed during this session.  */
905
906 static int command_count = 0;
907
908 /* Add the user command COMMAND to the input history list.  */
909
910 void
911 gdb_add_history (const char *command)
912 {
913   command_count++;
914
915   if (history_remove_duplicates != 0)
916     {
917       int lookbehind;
918       int lookbehind_threshold;
919
920       /* The lookbehind threshold for finding a duplicate history entry is
921          bounded by command_count because we can't meaningfully delete
922          history entries that are already stored in the history file since
923          the history file is appended to.  */
924       if (history_remove_duplicates == -1
925           || history_remove_duplicates > command_count)
926         lookbehind_threshold = command_count;
927       else
928         lookbehind_threshold = history_remove_duplicates;
929
930       using_history ();
931       for (lookbehind = 0; lookbehind < lookbehind_threshold; lookbehind++)
932         {
933           HIST_ENTRY *temp = previous_history ();
934
935           if (temp == NULL)
936             break;
937
938           if (strcmp (temp->line, command) == 0)
939             {
940               HIST_ENTRY *prev = remove_history (where_history ());
941               command_count--;
942               free_history_entry (prev);
943               break;
944             }
945         }
946       using_history ();
947     }
948
949   add_history (command);
950 }
951
952 /* Safely append new history entries to the history file in a corruption-free
953    way using an intermediate local history file.  */
954
955 static void
956 gdb_safe_append_history (void)
957 {
958   int ret, saved_errno;
959   char *local_history_filename;
960   struct cleanup *old_chain;
961
962   local_history_filename
963     = xstrprintf ("%s-gdb%d~", history_filename, getpid ());
964   old_chain = make_cleanup (xfree, local_history_filename);
965
966   ret = rename (history_filename, local_history_filename);
967   saved_errno = errno;
968   if (ret < 0 && saved_errno != ENOENT)
969     {
970       warning (_("Could not rename %s to %s: %s"),
971                history_filename, local_history_filename,
972                safe_strerror (saved_errno));
973     }
974   else
975     {
976       if (ret < 0)
977         {
978           /* If the rename failed with ENOENT then either the global history
979              file never existed in the first place or another GDB process is
980              currently appending to it (and has thus temporarily renamed it).
981              Since we can't distinguish between these two cases, we have to
982              conservatively assume the first case and therefore must write out
983              (not append) our known history to our local history file and try
984              to move it back anyway.  Otherwise a global history file would
985              never get created!  */
986            gdb_assert (saved_errno == ENOENT);
987            write_history (local_history_filename);
988         }
989       else
990         {
991           append_history (command_count, local_history_filename);
992           if (history_is_stifled ())
993             history_truncate_file (local_history_filename, history_max_entries);
994         }
995
996       ret = rename (local_history_filename, history_filename);
997       saved_errno = errno;
998       if (ret < 0 && saved_errno != EEXIST)
999         warning (_("Could not rename %s to %s: %s"),
1000                  local_history_filename, history_filename,
1001                  safe_strerror (saved_errno));
1002     }
1003
1004   do_cleanups (old_chain);
1005 }
1006
1007 /* Read one line from the command input stream `instream'
1008    into the local static buffer `linebuffer' (whose current length
1009    is `linelength').
1010    The buffer is made bigger as necessary.
1011    Returns the address of the start of the line.
1012
1013    NULL is returned for end of file.
1014
1015    *If* the instream == stdin & stdin is a terminal, the line read
1016    is copied into the file line saver (global var char *line,
1017    length linesize) so that it can be duplicated.
1018
1019    This routine either uses fancy command line editing or
1020    simple input as the user has requested.  */
1021
1022 char *
1023 command_line_input (const char *prompt_arg, int repeat, char *annotation_suffix)
1024 {
1025   static char *linebuffer = 0;
1026   static unsigned linelength = 0;
1027   const char *prompt = prompt_arg;
1028   char *p;
1029   char *p1;
1030   char *rl;
1031   char *nline;
1032   char got_eof = 0;
1033
1034   /* The annotation suffix must be non-NULL.  */
1035   if (annotation_suffix == NULL)
1036     annotation_suffix = "";
1037
1038   if (annotation_level > 1 && instream == stdin)
1039     {
1040       char *local_prompt;
1041
1042       local_prompt = alloca ((prompt == NULL ? 0 : strlen (prompt))
1043                              + strlen (annotation_suffix) + 40);
1044       if (prompt == NULL)
1045         local_prompt[0] = '\0';
1046       else
1047         strcpy (local_prompt, prompt);
1048       strcat (local_prompt, "\n\032\032");
1049       strcat (local_prompt, annotation_suffix);
1050       strcat (local_prompt, "\n");
1051
1052       prompt = local_prompt;
1053     }
1054
1055   if (linebuffer == 0)
1056     {
1057       linelength = 80;
1058       linebuffer = (char *) xmalloc (linelength);
1059     }
1060
1061   p = linebuffer;
1062
1063   /* Control-C quits instantly if typed while in this loop
1064      since it should not wait until the user types a newline.  */
1065   immediate_quit++;
1066   QUIT;
1067 #ifdef STOP_SIGNAL
1068   if (job_control)
1069     signal (STOP_SIGNAL, handle_stop_sig);
1070 #endif
1071
1072   while (1)
1073     {
1074       /* Make sure that all output has been output.  Some machines may
1075          let you get away with leaving out some of the gdb_flush, but
1076          not all.  */
1077       wrap_here ("");
1078       gdb_flush (gdb_stdout);
1079       gdb_flush (gdb_stderr);
1080
1081       if (source_file_name != NULL)
1082         ++source_line_number;
1083
1084       if (annotation_level > 1 && instream == stdin)
1085         {
1086           puts_unfiltered ("\n\032\032pre-");
1087           puts_unfiltered (annotation_suffix);
1088           puts_unfiltered ("\n");
1089         }
1090
1091       /* Don't use fancy stuff if not talking to stdin.  */
1092       if (deprecated_readline_hook && input_from_terminal_p ())
1093         {
1094           rl = (*deprecated_readline_hook) (prompt);
1095         }
1096       else if (command_editing_p && input_from_terminal_p ())
1097         {
1098           rl = gdb_readline_wrapper (prompt);
1099         }
1100       else
1101         {
1102           rl = gdb_readline (prompt);
1103         }
1104
1105       if (annotation_level > 1 && instream == stdin)
1106         {
1107           puts_unfiltered ("\n\032\032post-");
1108           puts_unfiltered (annotation_suffix);
1109           puts_unfiltered ("\n");
1110         }
1111
1112       if (!rl || rl == (char *) EOF)
1113         {
1114           got_eof = 1;
1115           break;
1116         }
1117       if (strlen (rl) + 1 + (p - linebuffer) > linelength)
1118         {
1119           linelength = strlen (rl) + 1 + (p - linebuffer);
1120           nline = (char *) xrealloc (linebuffer, linelength);
1121           p += nline - linebuffer;
1122           linebuffer = nline;
1123         }
1124       p1 = rl;
1125       /* Copy line.  Don't copy null at end.  (Leaves line alone
1126          if this was just a newline).  */
1127       while (*p1)
1128         *p++ = *p1++;
1129
1130       xfree (rl);               /* Allocated in readline.  */
1131
1132       if (p == linebuffer || *(p - 1) != '\\')
1133         break;
1134
1135       p--;                      /* Put on top of '\'.  */
1136       prompt = NULL;
1137     }
1138
1139 #ifdef STOP_SIGNAL
1140   if (job_control)
1141     signal (STOP_SIGNAL, SIG_DFL);
1142 #endif
1143   immediate_quit--;
1144
1145   if (got_eof)
1146     return NULL;
1147
1148 #define SERVER_COMMAND_LENGTH 7
1149   server_command =
1150     (p - linebuffer > SERVER_COMMAND_LENGTH)
1151     && strncmp (linebuffer, "server ", SERVER_COMMAND_LENGTH) == 0;
1152   if (server_command)
1153     {
1154       /* Note that we don't set `line'.  Between this and the check in
1155          dont_repeat, this insures that repeating will still do the
1156          right thing.  */
1157       *p = '\0';
1158       return linebuffer + SERVER_COMMAND_LENGTH;
1159     }
1160
1161   /* Do history expansion if that is wished.  */
1162   if (history_expansion_p && instream == stdin
1163       && ISATTY (instream))
1164     {
1165       char *history_value;
1166       int expanded;
1167
1168       *p = '\0';                /* Insert null now.  */
1169       expanded = history_expand (linebuffer, &history_value);
1170       if (expanded)
1171         {
1172           /* Print the changes.  */
1173           printf_unfiltered ("%s\n", history_value);
1174
1175           /* If there was an error, call this function again.  */
1176           if (expanded < 0)
1177             {
1178               xfree (history_value);
1179               return command_line_input (prompt, repeat,
1180                                          annotation_suffix);
1181             }
1182           if (strlen (history_value) > linelength)
1183             {
1184               linelength = strlen (history_value) + 1;
1185               linebuffer = (char *) xrealloc (linebuffer, linelength);
1186             }
1187           strcpy (linebuffer, history_value);
1188           p = linebuffer + strlen (linebuffer);
1189         }
1190       xfree (history_value);
1191     }
1192
1193   /* If we just got an empty line, and that is supposed to repeat the
1194      previous command, return the value in the global buffer.  */
1195   if (repeat && p == linebuffer)
1196     return saved_command_line;
1197   for (p1 = linebuffer; *p1 == ' ' || *p1 == '\t'; p1++);
1198   if (repeat && !*p1)
1199     return saved_command_line;
1200
1201   *p = 0;
1202
1203   /* Add line to history if appropriate.  */
1204   if (*linebuffer && input_from_terminal_p ())
1205     gdb_add_history (linebuffer);
1206
1207   /* Save into global buffer if appropriate.  */
1208   if (repeat)
1209     {
1210       if (linelength > saved_command_line_size)
1211         {
1212           saved_command_line = xrealloc (saved_command_line, linelength);
1213           saved_command_line_size = linelength;
1214         }
1215       strcpy (saved_command_line, linebuffer);
1216       return saved_command_line;
1217     }
1218
1219   return linebuffer;
1220 }
1221 \f
1222 /* Print the GDB banner.  */
1223 void
1224 print_gdb_version (struct ui_file *stream)
1225 {
1226   /* From GNU coding standards, first line is meant to be easy for a
1227      program to parse, and is just canonical program name and version
1228      number, which starts after last space.  */
1229
1230   fprintf_filtered (stream, "GNU gdb %s%s\n", PKGVERSION, version);
1231
1232   /* Second line is a copyright notice.  */
1233
1234   fprintf_filtered (stream,
1235                     "Copyright (C) 2015 Free Software Foundation, Inc.\n");
1236
1237   /* Following the copyright is a brief statement that the program is
1238      free software, that users are free to copy and change it on
1239      certain conditions, that it is covered by the GNU GPL, and that
1240      there is no warranty.  */
1241
1242   fprintf_filtered (stream, "\
1243 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\
1244 \nThis is free software: you are free to change and redistribute it.\n\
1245 There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\n\
1246 and \"show warranty\" for details.\n");
1247
1248   /* After the required info we print the configuration information.  */
1249
1250   fprintf_filtered (stream, "This GDB was configured as \"");
1251   if (strcmp (host_name, target_name) != 0)
1252     {
1253       fprintf_filtered (stream, "--host=%s --target=%s",
1254                         host_name, target_name);
1255     }
1256   else
1257     {
1258       fprintf_filtered (stream, "%s", host_name);
1259     }
1260   fprintf_filtered (stream, "\".\n\
1261 Type \"show configuration\" for configuration details.");
1262
1263   if (REPORT_BUGS_TO[0])
1264     {
1265       fprintf_filtered (stream,
1266                         _("\nFor bug reporting instructions, please see:\n"));
1267       fprintf_filtered (stream, "%s.\n", REPORT_BUGS_TO);
1268     }
1269   fprintf_filtered (stream,
1270                     _("Find the GDB manual and other documentation \
1271 resources online at:\n<http://www.gnu.org/software/gdb/documentation/>.\n"));
1272   fprintf_filtered (stream, _("For help, type \"help\".\n"));
1273   fprintf_filtered (stream, _("Type \"apropos word\" to search for \
1274 commands related to \"word\"."));
1275 }
1276
1277 /* Print the details of GDB build-time configuration.  */
1278 void
1279 print_gdb_configuration (struct ui_file *stream)
1280 {
1281   fprintf_filtered (stream, _("\
1282 This GDB was configured as follows:\n\
1283    configure --host=%s --target=%s\n\
1284 "), host_name, target_name);
1285   fprintf_filtered (stream, _("\
1286              --with-auto-load-dir=%s\n\
1287              --with-auto-load-safe-path=%s\n\
1288 "), AUTO_LOAD_DIR, AUTO_LOAD_SAFE_PATH);
1289 #if HAVE_LIBEXPAT
1290   fprintf_filtered (stream, _("\
1291              --with-expat\n\
1292 "));
1293 #else
1294   fprintf_filtered (stream, _("\
1295              --without-expat\n\
1296 "));
1297 #endif
1298   if (GDB_DATADIR[0])
1299     fprintf_filtered (stream, _("\
1300              --with-gdb-datadir=%s%s\n\
1301 "), GDB_DATADIR, GDB_DATADIR_RELOCATABLE ? " (relocatable)" : "");
1302 #ifdef ICONV_BIN
1303   fprintf_filtered (stream, _("\
1304              --with-iconv-bin=%s%s\n\
1305 "), ICONV_BIN, ICONV_BIN_RELOCATABLE ? " (relocatable)" : "");
1306 #endif
1307   if (JIT_READER_DIR[0])
1308     fprintf_filtered (stream, _("\
1309              --with-jit-reader-dir=%s%s\n\
1310 "), JIT_READER_DIR, JIT_READER_DIR_RELOCATABLE ? " (relocatable)" : "");
1311 #if HAVE_LIBUNWIND_IA64_H
1312   fprintf_filtered (stream, _("\
1313              --with-libunwind-ia64\n\
1314 "));
1315 #else
1316   fprintf_filtered (stream, _("\
1317              --without-libunwind-ia64\n\
1318 "));
1319 #endif
1320 #if HAVE_LIBLZMA
1321   fprintf_filtered (stream, _("\
1322              --with-lzma\n\
1323 "));
1324 #else
1325   fprintf_filtered (stream, _("\
1326              --without-lzma\n\
1327 "));
1328 #endif
1329 #ifdef WITH_PYTHON_PATH
1330   fprintf_filtered (stream, _("\
1331              --with-python=%s%s\n\
1332 "), WITH_PYTHON_PATH, PYTHON_PATH_RELOCATABLE ? " (relocatable)" : "");
1333 #endif
1334 #if HAVE_GUILE
1335   fprintf_filtered (stream, _("\
1336              --with-guile\n\
1337 "));
1338 #else
1339   fprintf_filtered (stream, _("\
1340              --without-guile\n\
1341 "));
1342 #endif
1343 #ifdef RELOC_SRCDIR
1344   fprintf_filtered (stream, _("\
1345              --with-relocated-sources=%s\n\
1346 "), RELOC_SRCDIR);
1347 #endif
1348   if (DEBUGDIR[0])
1349     fprintf_filtered (stream, _("\
1350              --with-separate-debug-dir=%s%s\n\
1351 "), DEBUGDIR, DEBUGDIR_RELOCATABLE ? " (relocatable)" : "");
1352   if (TARGET_SYSTEM_ROOT[0])
1353     fprintf_filtered (stream, _("\
1354              --with-sysroot=%s%s\n\
1355 "), TARGET_SYSTEM_ROOT, TARGET_SYSTEM_ROOT_RELOCATABLE ? " (relocatable)" : "");
1356   if (SYSTEM_GDBINIT[0])
1357     fprintf_filtered (stream, _("\
1358              --with-system-gdbinit=%s%s\n\
1359 "), SYSTEM_GDBINIT, SYSTEM_GDBINIT_RELOCATABLE ? " (relocatable)" : "");
1360 #if HAVE_LIBBABELTRACE
1361     fprintf_filtered (stream, _("\
1362              --with-babeltrace\n\
1363 "));
1364 #else
1365     fprintf_filtered (stream, _("\
1366              --without-babeltrace\n\
1367 "));
1368 #endif
1369     /* We assume "relocatable" will be printed at least once, thus we always
1370        print this text.  It's a reasonably safe assumption for now.  */
1371     fprintf_filtered (stream, _("\n\
1372 (\"Relocatable\" means the directory can be moved with the GDB installation\n\
1373 tree, and GDB will still find it.)\n\
1374 "));
1375 }
1376 \f
1377
1378 /* The current top level prompt, settable with "set prompt", and/or
1379    with the python `gdb.prompt_hook' hook.  */
1380 static char *top_prompt;
1381
1382 /* Access method for the GDB prompt string.  */
1383
1384 char *
1385 get_prompt (void)
1386 {
1387   return top_prompt;
1388 }
1389
1390 /* Set method for the GDB prompt string.  */
1391
1392 void
1393 set_prompt (const char *s)
1394 {
1395   char *p = xstrdup (s);
1396
1397   xfree (top_prompt);
1398   top_prompt = p;
1399 }
1400 \f
1401
1402 struct qt_args
1403 {
1404   char *args;
1405   int from_tty;
1406 };
1407
1408 /* Callback for iterate_over_inferiors.  Kills or detaches the given
1409    inferior, depending on how we originally gained control of it.  */
1410
1411 static int
1412 kill_or_detach (struct inferior *inf, void *args)
1413 {
1414   struct qt_args *qt = args;
1415   struct thread_info *thread;
1416
1417   if (inf->pid == 0)
1418     return 0;
1419
1420   thread = any_thread_of_process (inf->pid);
1421   if (thread != NULL)
1422     {
1423       switch_to_thread (thread->ptid);
1424
1425       /* Leave core files alone.  */
1426       if (target_has_execution)
1427         {
1428           if (inf->attach_flag)
1429             target_detach (qt->args, qt->from_tty);
1430           else
1431             target_kill ();
1432         }
1433     }
1434
1435   return 0;
1436 }
1437
1438 /* Callback for iterate_over_inferiors.  Prints info about what GDB
1439    will do to each inferior on a "quit".  ARG points to a struct
1440    ui_out where output is to be collected.  */
1441
1442 static int
1443 print_inferior_quit_action (struct inferior *inf, void *arg)
1444 {
1445   struct ui_file *stb = arg;
1446
1447   if (inf->pid == 0)
1448     return 0;
1449
1450   if (inf->attach_flag)
1451     fprintf_filtered (stb,
1452                       _("\tInferior %d [%s] will be detached.\n"), inf->num,
1453                       target_pid_to_str (pid_to_ptid (inf->pid)));
1454   else
1455     fprintf_filtered (stb,
1456                       _("\tInferior %d [%s] will be killed.\n"), inf->num,
1457                       target_pid_to_str (pid_to_ptid (inf->pid)));
1458
1459   return 0;
1460 }
1461
1462 /* If necessary, make the user confirm that we should quit.  Return
1463    non-zero if we should quit, zero if we shouldn't.  */
1464
1465 int
1466 quit_confirm (void)
1467 {
1468   struct ui_file *stb;
1469   struct cleanup *old_chain;
1470   char *str;
1471   int qr;
1472
1473   /* Don't even ask if we're only debugging a core file inferior.  */
1474   if (!have_live_inferiors ())
1475     return 1;
1476
1477   /* Build the query string as a single string.  */
1478   stb = mem_fileopen ();
1479   old_chain = make_cleanup_ui_file_delete (stb);
1480
1481   fprintf_filtered (stb, _("A debugging session is active.\n\n"));
1482   iterate_over_inferiors (print_inferior_quit_action, stb);
1483   fprintf_filtered (stb, _("\nQuit anyway? "));
1484
1485   str = ui_file_xstrdup (stb, NULL);
1486   make_cleanup (xfree, str);
1487
1488   qr = query ("%s", str);
1489   do_cleanups (old_chain);
1490   return qr;
1491 }
1492
1493 /* Prepare to exit GDB cleanly by undoing any changes made to the
1494    terminal so that we leave the terminal in the state we acquired it.  */
1495
1496 static void
1497 undo_terminal_modifications_before_exit (void)
1498 {
1499   target_terminal_ours ();
1500 #if defined(TUI)
1501   tui_disable ();
1502 #endif
1503   if (async_command_editing_p)
1504     gdb_disable_readline ();
1505 }
1506
1507
1508 /* Quit without asking for confirmation.  */
1509
1510 void
1511 quit_force (char *args, int from_tty)
1512 {
1513   int exit_code = 0;
1514   struct qt_args qt;
1515
1516   undo_terminal_modifications_before_exit ();
1517
1518   /* An optional expression may be used to cause gdb to terminate with the 
1519      value of that expression.  */
1520   if (args)
1521     {
1522       struct value *val = parse_and_eval (args);
1523
1524       exit_code = (int) value_as_long (val);
1525     }
1526   else if (return_child_result)
1527     exit_code = return_child_result_value;
1528
1529   qt.args = args;
1530   qt.from_tty = from_tty;
1531
1532   /* We want to handle any quit errors and exit regardless.  */
1533
1534   /* Get out of tfind mode, and kill or detach all inferiors.  */
1535   TRY
1536     {
1537       disconnect_tracing ();
1538       iterate_over_inferiors (kill_or_detach, &qt);
1539     }
1540   CATCH (ex, RETURN_MASK_ALL)
1541     {
1542       exception_print (gdb_stderr, ex);
1543     }
1544   END_CATCH
1545
1546   /* Give all pushed targets a chance to do minimal cleanup, and pop
1547      them all out.  */
1548   TRY
1549     {
1550       pop_all_targets ();
1551     }
1552   CATCH (ex, RETURN_MASK_ALL)
1553     {
1554       exception_print (gdb_stderr, ex);
1555     }
1556   END_CATCH
1557
1558   /* Save the history information if it is appropriate to do so.  */
1559   TRY
1560     {
1561       if (write_history_p && history_filename
1562           && input_from_terminal_p ())
1563         gdb_safe_append_history ();
1564     }
1565   CATCH (ex, RETURN_MASK_ALL)
1566     {
1567       exception_print (gdb_stderr, ex);
1568     }
1569   END_CATCH
1570
1571   /* Do any final cleanups before exiting.  */
1572   TRY
1573     {
1574       do_final_cleanups (all_cleanups ());
1575     }
1576   CATCH (ex, RETURN_MASK_ALL)
1577     {
1578       exception_print (gdb_stderr, ex);
1579     }
1580   END_CATCH
1581
1582   exit (exit_code);
1583 }
1584
1585 /* Returns whether GDB is running on a terminal and input is
1586    currently coming from that terminal.  */
1587
1588 int
1589 input_from_terminal_p (void)
1590 {
1591   if (batch_flag)
1592     return 0;
1593
1594   if (gdb_has_a_terminal () && instream == stdin)
1595     return 1;
1596
1597   /* If INSTREAM is unset, and we are not in a user command, we
1598      must be in Insight.  That's like having a terminal, for our
1599      purposes.  */
1600   if (instream == NULL && !in_user_command)
1601     return 1;
1602
1603   return 0;
1604 }
1605 \f
1606 static void
1607 dont_repeat_command (char *ignored, int from_tty)
1608 {
1609   /* Can't call dont_repeat here because we're not necessarily reading
1610      from stdin.  */
1611   *saved_command_line = 0;
1612 }
1613 \f
1614 /* Functions to manipulate command line editing control variables.  */
1615
1616 /* Number of commands to print in each call to show_commands.  */
1617 #define Hist_print 10
1618 void
1619 show_commands (char *args, int from_tty)
1620 {
1621   /* Index for history commands.  Relative to history_base.  */
1622   int offset;
1623
1624   /* Number of the history entry which we are planning to display next.
1625      Relative to history_base.  */
1626   static int num = 0;
1627
1628   /* Print out some of the commands from the command history.  */
1629
1630   if (args)
1631     {
1632       if (args[0] == '+' && args[1] == '\0')
1633         /* "info editing +" should print from the stored position.  */
1634         ;
1635       else
1636         /* "info editing <exp>" should print around command number <exp>.  */
1637         num = (parse_and_eval_long (args) - history_base) - Hist_print / 2;
1638     }
1639   /* "show commands" means print the last Hist_print commands.  */
1640   else
1641     {
1642       num = history_length - Hist_print;
1643     }
1644
1645   if (num < 0)
1646     num = 0;
1647
1648   /* If there are at least Hist_print commands, we want to display the last
1649      Hist_print rather than, say, the last 6.  */
1650   if (history_length - num < Hist_print)
1651     {
1652       num = history_length - Hist_print;
1653       if (num < 0)
1654         num = 0;
1655     }
1656
1657   for (offset = num;
1658        offset < num + Hist_print && offset < history_length;
1659        offset++)
1660     {
1661       printf_filtered ("%5d  %s\n", history_base + offset,
1662                        (history_get (history_base + offset))->line);
1663     }
1664
1665   /* The next command we want to display is the next one that we haven't
1666      displayed yet.  */
1667   num += Hist_print;
1668
1669   /* If the user repeats this command with return, it should do what
1670      "show commands +" does.  This is unnecessary if arg is null,
1671      because "show commands +" is not useful after "show commands".  */
1672   if (from_tty && args)
1673     {
1674       args[0] = '+';
1675       args[1] = '\0';
1676     }
1677 }
1678
1679 /* Update the size of our command history file to HISTORY_SIZE.
1680
1681    A HISTORY_SIZE of -1 stands for unlimited.  */
1682
1683 static void
1684 set_readline_history_size (int history_size)
1685 {
1686   gdb_assert (history_size >= -1);
1687
1688   if (history_size == -1)
1689     unstifle_history ();
1690   else
1691     stifle_history (history_size);
1692 }
1693
1694 /* Called by do_setshow_command.  */
1695 static void
1696 set_history_size_command (char *args, int from_tty, struct cmd_list_element *c)
1697 {
1698   set_readline_history_size (history_size_setshow_var);
1699 }
1700
1701 void
1702 set_history (char *args, int from_tty)
1703 {
1704   printf_unfiltered (_("\"set history\" must be followed "
1705                        "by the name of a history subcommand.\n"));
1706   help_list (sethistlist, "set history ", all_commands, gdb_stdout);
1707 }
1708
1709 void
1710 show_history (char *args, int from_tty)
1711 {
1712   cmd_show_list (showhistlist, from_tty, "");
1713 }
1714
1715 int info_verbose = 0;           /* Default verbose msgs off.  */
1716
1717 /* Called by do_setshow_command.  An elaborate joke.  */
1718 void
1719 set_verbose (char *args, int from_tty, struct cmd_list_element *c)
1720 {
1721   const char *cmdname = "verbose";
1722   struct cmd_list_element *showcmd;
1723
1724   showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, 1);
1725   gdb_assert (showcmd != NULL && showcmd != CMD_LIST_AMBIGUOUS);
1726
1727   if (info_verbose)
1728     {
1729       c->doc = "Set verbose printing of informational messages.";
1730       showcmd->doc = "Show verbose printing of informational messages.";
1731     }
1732   else
1733     {
1734       c->doc = "Set verbosity.";
1735       showcmd->doc = "Show verbosity.";
1736     }
1737 }
1738
1739 /* Init the history buffer.  Note that we are called after the init file(s)
1740    have been read so that the user can change the history file via his
1741    .gdbinit file (for instance).  The GDBHISTFILE environment variable
1742    overrides all of this.  */
1743
1744 void
1745 init_history (void)
1746 {
1747   char *tmpenv;
1748
1749   tmpenv = getenv ("GDBHISTSIZE");
1750   if (tmpenv)
1751     {
1752       long var;
1753       int saved_errno;
1754       char *endptr;
1755
1756       tmpenv = skip_spaces (tmpenv);
1757       errno = 0;
1758       var = strtol (tmpenv, &endptr, 10);
1759       saved_errno = errno;
1760       endptr = skip_spaces (endptr);
1761
1762       /* If GDBHISTSIZE is non-numeric then ignore it.  If GDBHISTSIZE is the
1763          empty string, a negative number or a huge positive number (larger than
1764          INT_MAX) then set the history size to unlimited.  Otherwise set our
1765          history size to the number we have read.  This behavior is consistent
1766          with how bash handles HISTSIZE.  */
1767       if (*endptr != '\0')
1768         ;
1769       else if (*tmpenv == '\0'
1770                || var < 0
1771                || var > INT_MAX
1772                /* On targets where INT_MAX == LONG_MAX, we have to look at
1773                   errno after calling strtol to distinguish between a value that
1774                   is exactly INT_MAX and an overflowing value that was clamped
1775                   to INT_MAX.  */
1776                || (var == INT_MAX && saved_errno == ERANGE))
1777         history_size_setshow_var = -1;
1778       else
1779         history_size_setshow_var = var;
1780     }
1781
1782   /* If neither the init file nor GDBHISTSIZE has set a size yet, pick the
1783      default.  */
1784   if (history_size_setshow_var == -2)
1785     history_size_setshow_var = 256;
1786
1787   set_readline_history_size (history_size_setshow_var);
1788
1789   tmpenv = getenv ("GDBHISTFILE");
1790   if (tmpenv)
1791     history_filename = xstrdup (tmpenv);
1792   else if (!history_filename)
1793     {
1794       /* We include the current directory so that if the user changes
1795          directories the file written will be the same as the one
1796          that was read.  */
1797 #ifdef __MSDOS__
1798       /* No leading dots in file names are allowed on MSDOS.  */
1799       history_filename = concat (current_directory, "/_gdb_history",
1800                                  (char *)NULL);
1801 #else
1802       history_filename = concat (current_directory, "/.gdb_history",
1803                                  (char *)NULL);
1804 #endif
1805     }
1806   read_history (history_filename);
1807 }
1808
1809 static void
1810 show_prompt (struct ui_file *file, int from_tty,
1811              struct cmd_list_element *c, const char *value)
1812 {
1813   fprintf_filtered (file, _("Gdb's prompt is \"%s\".\n"), value);
1814 }
1815
1816 static void
1817 show_async_command_editing_p (struct ui_file *file, int from_tty,
1818                               struct cmd_list_element *c, const char *value)
1819 {
1820   fprintf_filtered (file, _("Editing of command lines as "
1821                             "they are typed is %s.\n"),
1822                     value);
1823 }
1824
1825 static void
1826 show_annotation_level (struct ui_file *file, int from_tty,
1827                        struct cmd_list_element *c, const char *value)
1828 {
1829   fprintf_filtered (file, _("Annotation_level is %s.\n"), value);
1830 }
1831
1832 static void
1833 show_exec_done_display_p (struct ui_file *file, int from_tty,
1834                           struct cmd_list_element *c, const char *value)
1835 {
1836   fprintf_filtered (file, _("Notification of completion for "
1837                             "asynchronous execution commands is %s.\n"),
1838                     value);
1839 }
1840
1841 /* New values of the "data-directory" parameter are staged here.  */
1842 static char *staged_gdb_datadir;
1843
1844 /* "set" command for the gdb_datadir configuration variable.  */
1845
1846 static void
1847 set_gdb_datadir (char *args, int from_tty, struct cmd_list_element *c)
1848 {
1849   set_gdb_data_directory (staged_gdb_datadir);
1850   observer_notify_gdb_datadir_changed ();
1851 }
1852
1853 /* "show" command for the gdb_datadir configuration variable.  */
1854
1855 static void
1856 show_gdb_datadir (struct ui_file *file, int from_tty,
1857                   struct cmd_list_element *c, const char *value)
1858 {
1859   fprintf_filtered (file, _("GDB's data directory is \"%s\".\n"),
1860                     gdb_datadir);
1861 }
1862
1863 static void
1864 set_history_filename (char *args, int from_tty, struct cmd_list_element *c)
1865 {
1866   /* We include the current directory so that if the user changes
1867      directories the file written will be the same as the one
1868      that was read.  */
1869   if (!IS_ABSOLUTE_PATH (history_filename))
1870     history_filename = reconcat (history_filename, current_directory, "/", 
1871                                  history_filename, (char *) NULL);
1872 }
1873
1874 static void
1875 init_main (void)
1876 {
1877   /* Initialize the prompt to a simple "(gdb) " prompt or to whatever
1878      the DEFAULT_PROMPT is.  */
1879   set_prompt (DEFAULT_PROMPT);
1880
1881   /* Set things up for annotation_level > 1, if the user ever decides
1882      to use it.  */
1883   async_annotation_suffix = "prompt";
1884
1885   /* Set the important stuff up for command editing.  */
1886   command_editing_p = 1;
1887   history_expansion_p = 0;
1888   write_history_p = 0;
1889
1890   /* Setup important stuff for command line editing.  */
1891   rl_completion_word_break_hook = gdb_completion_word_break_characters;
1892   rl_completion_entry_function = readline_line_completion_function;
1893   rl_completer_word_break_characters = default_word_break_characters ();
1894   rl_completer_quote_characters = get_gdb_completer_quote_characters ();
1895   rl_completion_display_matches_hook = cli_display_match_list;
1896   rl_readline_name = "gdb";
1897   rl_terminal_name = getenv ("TERM");
1898
1899   /* The name for this defun comes from Bash, where it originated.
1900      15 is Control-o, the same binding this function has in Bash.  */
1901   rl_add_defun ("operate-and-get-next", gdb_rl_operate_and_get_next, 15);
1902
1903   add_setshow_string_cmd ("prompt", class_support,
1904                           &top_prompt,
1905                           _("Set gdb's prompt"),
1906                           _("Show gdb's prompt"),
1907                           NULL, NULL,
1908                           show_prompt,
1909                           &setlist, &showlist);
1910
1911   add_com ("dont-repeat", class_support, dont_repeat_command, _("\
1912 Don't repeat this command.\nPrimarily \
1913 used inside of user-defined commands that should not be repeated when\n\
1914 hitting return."));
1915
1916   add_setshow_boolean_cmd ("editing", class_support,
1917                            &async_command_editing_p, _("\
1918 Set editing of command lines as they are typed."), _("\
1919 Show editing of command lines as they are typed."), _("\
1920 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
1921 Without an argument, command line editing is enabled.  To edit, use\n\
1922 EMACS-like or VI-like commands like control-P or ESC."),
1923                            set_async_editing_command,
1924                            show_async_command_editing_p,
1925                            &setlist, &showlist);
1926
1927   add_setshow_boolean_cmd ("save", no_class, &write_history_p, _("\
1928 Set saving of the history record on exit."), _("\
1929 Show saving of the history record on exit."), _("\
1930 Use \"on\" to enable the saving, and \"off\" to disable it.\n\
1931 Without an argument, saving is enabled."),
1932                            NULL,
1933                            show_write_history_p,
1934                            &sethistlist, &showhistlist);
1935
1936   add_setshow_zuinteger_unlimited_cmd ("size", no_class,
1937                                        &history_size_setshow_var, _("\
1938 Set the size of the command history,"), _("\
1939 Show the size of the command history,"), _("\
1940 ie. the number of previous commands to keep a record of.\n\
1941 If set to \"unlimited\", the number of commands kept in the history\n\
1942 list is unlimited.  This defaults to the value of the environment\n\
1943 variable \"GDBHISTSIZE\", or to 256 if this variable is not set."),
1944                             set_history_size_command,
1945                             show_history_size,
1946                             &sethistlist, &showhistlist);
1947
1948   add_setshow_zuinteger_unlimited_cmd ("remove-duplicates", no_class,
1949                                        &history_remove_duplicates, _("\
1950 Set how far back in history to look for and remove duplicate entries."), _("\
1951 Show how far back in history to look for and remove duplicate entries."), _("\
1952 If set to a nonzero value N, GDB will look back at the last N history entries\n\
1953 and remove the first history entry that is a duplicate of the most recent\n\
1954 entry, each time a new history entry is added.\n\
1955 If set to \"unlimited\", this lookbehind is unbounded.\n\
1956 Only history entries added during this session are considered for removal.\n\
1957 If set to 0, removal of duplicate history entries is disabled.\n\
1958 By default this option is set to 0."),
1959                            NULL,
1960                            show_history_remove_duplicates,
1961                            &sethistlist, &showhistlist);
1962
1963   add_setshow_filename_cmd ("filename", no_class, &history_filename, _("\
1964 Set the filename in which to record the command history"), _("\
1965 Show the filename in which to record the command history"), _("\
1966 (the list of previous commands of which a record is kept)."),
1967                             set_history_filename,
1968                             show_history_filename,
1969                             &sethistlist, &showhistlist);
1970
1971   add_setshow_boolean_cmd ("confirm", class_support, &confirm, _("\
1972 Set whether to confirm potentially dangerous operations."), _("\
1973 Show whether to confirm potentially dangerous operations."), NULL,
1974                            NULL,
1975                            show_confirm,
1976                            &setlist, &showlist);
1977
1978   add_setshow_zinteger_cmd ("annotate", class_obscure, &annotation_level, _("\
1979 Set annotation_level."), _("\
1980 Show annotation_level."), _("\
1981 0 == normal;     1 == fullname (for use when running under emacs)\n\
1982 2 == output annotated suitably for use by programs that control GDB."),
1983                             NULL,
1984                             show_annotation_level,
1985                             &setlist, &showlist);
1986
1987   add_setshow_boolean_cmd ("exec-done-display", class_support,
1988                            &exec_done_display_p, _("\
1989 Set notification of completion for asynchronous execution commands."), _("\
1990 Show notification of completion for asynchronous execution commands."), _("\
1991 Use \"on\" to enable the notification, and \"off\" to disable it."),
1992                            NULL,
1993                            show_exec_done_display_p,
1994                            &setlist, &showlist);
1995
1996   add_setshow_filename_cmd ("data-directory", class_maintenance,
1997                            &staged_gdb_datadir, _("Set GDB's data directory."),
1998                            _("Show GDB's data directory."),
1999                            _("\
2000 When set, GDB uses the specified path to search for data files."),
2001                            set_gdb_datadir, show_gdb_datadir,
2002                            &setlist,
2003                            &showlist);
2004 }
2005
2006 void
2007 gdb_init (char *argv0)
2008 {
2009   if (pre_init_ui_hook)
2010     pre_init_ui_hook ();
2011
2012   /* Run the init function of each source file.  */
2013
2014 #ifdef __MSDOS__
2015   /* Make sure we return to the original directory upon exit, come
2016      what may, since the OS doesn't do that for us.  */
2017   make_final_cleanup (do_chdir_cleanup, xstrdup (current_directory));
2018 #endif
2019
2020   init_cmd_lists ();        /* This needs to be done first.  */
2021   initialize_targets ();    /* Setup target_terminal macros for utils.c.  */
2022   initialize_utils ();      /* Make errors and warnings possible.  */
2023
2024   init_page_info ();
2025
2026   /* Here is where we call all the _initialize_foo routines.  */
2027   initialize_all_files ();
2028
2029   /* This creates the current_program_space.  Do this after all the
2030      _initialize_foo routines have had a chance to install their
2031      per-sspace data keys.  Also do this before
2032      initialize_current_architecture is called, because it accesses
2033      exec_bfd of the current program space.  */
2034   initialize_progspace ();
2035   initialize_inferiors ();
2036   initialize_current_architecture ();
2037   init_cli_cmds();
2038   init_main ();                 /* But that omits this file!  Do it now.  */
2039
2040   initialize_stdin_serial ();
2041
2042   /* Take a snapshot of our tty state before readline/ncurses have had a chance
2043      to alter it.  */
2044   set_initial_gdb_ttystate ();
2045
2046   async_init_signals ();
2047
2048   /* We need a default language for parsing expressions, so simple
2049      things like "set width 0" won't fail if no language is explicitly
2050      set in a config file or implicitly set by reading an executable
2051      during startup.  */
2052   set_language (language_c);
2053   expected_language = current_language; /* Don't warn about the change.  */
2054
2055   /* Python initialization, for example, can require various commands to be
2056      installed.  For example "info pretty-printer" needs the "info"
2057      prefix to be installed.  Keep things simple and just do final
2058      script initialization here.  */
2059   finish_ext_lang_initialization ();
2060 }