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