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