More updated translations
[binutils-gdb.git] / gdb / top.c
blob1b4740684d2ea6571c458cfa3e30dc84f31e3342
1 /* Top level stuff for GDB, the GNU debugger.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
20 #include "exceptions.h"
21 #include "cli/cli-cmds.h"
22 #include "cli/cli-script.h"
23 #include "cli/cli-setshow.h"
24 #include "cli/cli-decode.h"
25 #include "symtab.h"
26 #include "inferior.h"
27 #include "infrun.h"
28 #include <signal.h>
29 #include "target.h"
30 #include "target-dcache.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"
37 #include "gdbsupport/job-control.h"
38 #include "annotate.h"
39 #include "completer.h"
40 #include "top.h"
41 #include "ui.h"
42 #include "gdbsupport/version.h"
43 #include "serial.h"
44 #include "main.h"
45 #include "gdbsupport/event-loop.h"
46 #include "gdbthread.h"
47 #include "extension.h"
48 #include "interps.h"
49 #include "observable.h"
50 #include "maint.h"
51 #include "filenames.h"
52 #include "frame.h"
53 #include "gdbsupport/gdb_select.h"
54 #include "gdbsupport/scope-exit.h"
55 #include "gdbarch.h"
56 #include "gdbsupport/pathstuff.h"
57 #include "cli/cli-style.h"
58 #include "pager.h"
60 /* readline include files. */
61 #include "readline/readline.h"
62 #include "readline/history.h"
64 /* readline defines this. */
65 #undef savestring
67 #include <sys/types.h>
69 #include "event-top.h"
70 #include <sys/stat.h>
71 #include <ctype.h>
72 #include "ui-out.h"
73 #include "cli-out.h"
74 #include "tracepoint.h"
75 #include "inf-loop.h"
77 #if defined(TUI)
78 # include "tui/tui.h"
79 # include "tui/tui-io.h"
80 #endif
82 #ifndef O_NOCTTY
83 # define O_NOCTTY 0
84 #endif
86 extern void initialize_all_files (void);
88 /* Default command line prompt. This is overridden in some configs. */
90 #ifndef DEFAULT_PROMPT
91 #define DEFAULT_PROMPT "(gdb) "
92 #endif
94 struct ui_file **
95 current_ui_gdb_stdout_ptr ()
97 return &current_ui->m_gdb_stdout;
100 struct ui_file **
101 current_ui_gdb_stdin_ptr ()
103 return &current_ui->m_gdb_stdin;
106 struct ui_file **
107 current_ui_gdb_stderr_ptr ()
109 return &current_ui->m_gdb_stderr;
112 struct ui_file **
113 current_ui_gdb_stdlog_ptr ()
115 return &current_ui->m_gdb_stdlog;
118 struct ui_out **
119 current_ui_current_uiout_ptr ()
121 return &current_ui->m_current_uiout;
124 int inhibit_gdbinit = 0;
126 /* Flag for whether we want to confirm potentially dangerous
127 operations. Default is yes. */
129 bool confirm = true;
131 static void
132 show_confirm (struct ui_file *file, int from_tty,
133 struct cmd_list_element *c, const char *value)
135 gdb_printf (file, _("Whether to confirm potentially "
136 "dangerous operations is %s.\n"),
137 value);
140 /* The last command line executed on the console. Used for command
141 repetitions when the user enters an empty line. */
143 static char *saved_command_line;
145 /* If not NULL, the arguments that should be passed if
146 saved_command_line is repeated. */
148 static const char *repeat_arguments;
150 /* The previous last command line executed on the console. Used for command
151 repetitions when a command wants to relaunch the previously launched
152 command. We need this as when a command is running, saved_command_line
153 already contains the line of the currently executing command. */
155 static char *previous_saved_command_line;
157 /* If not NULL, the arguments that should be passed if the
158 previous_saved_command_line is repeated. */
160 static const char *previous_repeat_arguments;
162 /* Nonzero if the current command is modified by "server ". This
163 affects things like recording into the command history, commands
164 repeating on RETURN, etc. This is so a user interface (emacs, GUI,
165 whatever) can issue its own commands and also send along commands
166 from the user, and have the user not notice that the user interface
167 is issuing commands too. */
168 bool server_command;
170 /* Timeout limit for response from target. */
172 /* The default value has been changed many times over the years. It
173 was originally 5 seconds. But that was thought to be a long time
174 to sit and wait, so it was changed to 2 seconds. That was thought
175 to be plenty unless the connection was going through some terminal
176 server or multiplexer or other form of hairy serial connection.
178 In mid-1996, remote_timeout was moved from remote.c to top.c and
179 it began being used in other remote-* targets. It appears that the
180 default was changed to 20 seconds at that time, perhaps because the
181 Renesas E7000 ICE didn't always respond in a timely manner.
183 But if 5 seconds is a long time to sit and wait for retransmissions,
184 20 seconds is far worse. This demonstrates the difficulty of using
185 a single variable for all protocol timeouts.
187 As remote.c is used much more than remote-e7000.c, it was changed
188 back to 2 seconds in 1999. */
190 int remote_timeout = 2;
192 /* Sbrk location on entry to main. Used for statistics only. */
193 #ifdef HAVE_USEFUL_SBRK
194 char *lim_at_start;
195 #endif
197 /* Hooks for alternate command interfaces. */
199 /* This hook is called from within gdb's many mini-event loops which
200 could steal control from a real user interface's event loop. It
201 returns non-zero if the user is requesting a detach, zero
202 otherwise. */
204 int (*deprecated_ui_loop_hook) (int);
207 /* Called from print_frame_info to list the line we stopped in. */
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. */
215 int (*deprecated_query_hook) (const char *, va_list);
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. */
229 void (*deprecated_readline_begin_hook) (const char *, ...);
230 char *(*deprecated_readline_hook) (const char *);
231 void (*deprecated_readline_end_hook) (void);
233 /* Called as appropriate to notify the interface that we have attached
234 to or detached from an already running process. */
236 void (*deprecated_attach_hook) (void);
237 void (*deprecated_detach_hook) (void);
239 /* Used by UI as a wrapper around command execution. May do various
240 things like enabling/disabling buttons, etc... */
242 void (*deprecated_call_command_hook) (struct cmd_list_element * c,
243 const char *cmd, int from_tty);
245 /* Called when the current thread changes. Argument is thread id. */
247 void (*deprecated_context_hook) (int id);
249 /* See top.h. */
251 void
252 unbuffer_stream (FILE *stream)
254 /* Unbuffer the input stream so that in gdb_readline_no_editing_callback,
255 the calls to fgetc fetch only one char at the time from STREAM.
257 This is important because gdb_readline_no_editing_callback will read
258 from STREAM up to the first '\n' character, after this GDB returns to
259 the event loop and relies on a select on STREAM indicating that more
260 input is pending.
262 If STREAM is buffered then the fgetc calls may have moved all the
263 pending input from the kernel into a local buffer, after which the
264 select will not indicate that more input is pending, and input after
265 the first '\n' will not be processed immediately.
267 Please ensure that any changes in this area run the MI tests with the
268 FORCE_SEPARATE_MI_TTY=1 flag being passed. */
270 #ifdef __MINGW32__
271 /* With MS-Windows runtime, making stdin unbuffered when it's
272 connected to the terminal causes it to misbehave. */
273 if (!ISATTY (stream))
274 setbuf (stream, nullptr);
275 #else
276 /* On GNU/Linux the issues described above can impact GDB even when
277 dealing with input from a terminal. For now we unbuffer the input
278 stream for everyone except MS-Windows. */
279 setbuf (stream, nullptr);
280 #endif
283 /* Handler for SIGHUP. */
285 #ifdef SIGHUP
286 /* NOTE 1999-04-29: This function will be static again, once we modify
287 gdb to use the event loop as the default command loop and we merge
288 event-top.c into this file, top.c. */
289 /* static */ void
290 quit_cover (void)
292 /* Stop asking user for confirmation --- we're exiting. This
293 prevents asking the user dumb questions. */
294 confirm = 0;
295 quit_command ((char *) 0, 0);
297 #endif /* defined SIGHUP */
299 /* Line number we are currently in, in a file which is being sourced. */
300 /* NOTE 1999-04-29: This variable will be static again, once we modify
301 gdb to use the event loop as the default command loop and we merge
302 event-top.c into this file, top.c. */
303 /* static */ int source_line_number;
305 /* Name of the file we are sourcing. */
306 /* NOTE 1999-04-29: This variable will be static again, once we modify
307 gdb to use the event loop as the default command loop and we merge
308 event-top.c into this file, top.c. */
309 /* static */ std::string source_file_name;
311 /* Read commands from STREAM. */
312 void
313 read_command_file (FILE *stream)
315 struct ui *ui = current_ui;
317 unbuffer_stream (stream);
319 scoped_restore save_instream
320 = make_scoped_restore (&ui->instream, stream);
322 /* Read commands from `instream' and execute them until end of file
323 or error reading instream. */
325 while (ui->instream != NULL && !feof (ui->instream))
327 /* Get a command-line. This calls the readline package. */
328 std::string command_buffer;
329 const char *command
330 = command_line_input (command_buffer, nullptr, nullptr);
331 if (command == nullptr)
332 break;
333 command_handler (command);
337 #ifdef __MSDOS__
338 static void
339 do_chdir_cleanup (void *old_dir)
341 chdir ((const char *) old_dir);
342 xfree (old_dir);
344 #endif
346 scoped_value_mark
347 prepare_execute_command ()
349 /* With multiple threads running while the one we're examining is
350 stopped, the dcache can get stale without us being able to detect
351 it. For the duration of the command, though, use the dcache to
352 help things like backtrace. */
353 if (non_stop)
354 target_dcache_invalidate (current_program_space->aspace);
356 return scoped_value_mark ();
359 /* Tell the user if the language has changed (except first time) after
360 executing a command. */
362 void
363 check_frame_language_change (void)
365 static int warned = 0;
366 frame_info_ptr frame;
368 /* First make sure that a new frame has been selected, in case the
369 command or the hooks changed the program state. */
370 frame = deprecated_safe_get_selected_frame ();
371 if (current_language != expected_language)
373 if (language_mode == language_mode_auto && info_verbose)
375 /* Print what changed. */
376 language_info ();
378 warned = 0;
381 /* Warn the user if the working language does not match the language
382 of the current frame. Only warn the user if we are actually
383 running the program, i.e. there is a stack. */
384 /* FIXME: This should be cacheing the frame and only running when
385 the frame changes. */
387 if (warn_frame_lang_mismatch && has_stack_frames ())
389 enum language flang;
391 flang = get_frame_language (frame);
392 if (!warned
393 && flang != language_unknown
394 && flang != current_language->la_language)
396 gdb_printf ("%s\n", _(lang_frame_mismatch_warn));
397 warned = 1;
402 /* See top.h. */
404 void
405 wait_sync_command_done (void)
407 /* Processing events may change the current UI. */
408 scoped_restore save_ui = make_scoped_restore (&current_ui);
409 struct ui *ui = current_ui;
411 /* We're about to wait until the target stops after having resumed
412 it so must force-commit resumptions, in case we're being called
413 in some context where a scoped_disable_commit_resumed object is
414 active. I.e., this function is a commit-resumed sync/flush
415 point. */
416 scoped_enable_commit_resumed enable ("sync wait");
418 while (gdb_do_one_event () >= 0)
419 if (ui->prompt_state != PROMPT_BLOCKED)
420 break;
423 /* See top.h. */
425 void
426 maybe_wait_sync_command_done (int was_sync)
428 /* If the interpreter is in sync mode (we're running a user
429 command's list, running command hooks or similars), and we
430 just ran a synchronous command that started the target, wait
431 for that command to end. */
432 if (!current_ui->async
433 && !was_sync
434 && current_ui->prompt_state == PROMPT_BLOCKED)
435 wait_sync_command_done ();
438 /* See command.h. */
440 void
441 set_repeat_arguments (const char *args)
443 repeat_arguments = args;
446 /* Execute the line P as a command, in the current user context.
447 Pass FROM_TTY as second argument to the defining function. */
449 void
450 execute_command (const char *p, int from_tty)
452 struct cmd_list_element *c;
453 const char *line;
454 const char *cmd_start = p;
456 auto cleanup_if_error = make_scope_exit (bpstat_clear_actions);
457 scoped_value_mark cleanup = prepare_execute_command ();
459 /* This can happen when command_line_input hits end of file. */
460 if (p == NULL)
462 cleanup_if_error.release ();
463 return;
466 std::string cmd_copy = p;
468 target_log_command (p);
470 while (*p == ' ' || *p == '\t')
471 p++;
472 if (*p)
474 const char *cmd = p;
475 const char *arg;
476 std::string default_args;
477 std::string default_args_and_arg;
478 int was_sync = current_ui->prompt_state == PROMPT_BLOCKED;
480 line = p;
482 /* If trace-commands is set then this will print this command. */
483 print_command_trace ("%s", p);
485 c = lookup_cmd (&cmd, cmdlist, "", &default_args, 0, 1);
486 p = cmd;
488 scoped_restore save_repeat_args
489 = make_scoped_restore (&repeat_arguments, nullptr);
490 const char *args_pointer = p;
492 if (!default_args.empty ())
494 if (*p != '\0')
495 default_args_and_arg = default_args + ' ' + p;
496 else
497 default_args_and_arg = default_args;
498 arg = default_args_and_arg.c_str ();
500 else
502 /* Pass null arg rather than an empty one. */
503 arg = *p == '\0' ? nullptr : p;
506 /* FIXME: cagney/2002-02-02: The c->type test is pretty dodgy
507 while the is_complete_command(cfunc) test is just plain
508 bogus. They should both be replaced by a test of the form
509 c->strip_trailing_white_space_p. */
510 /* NOTE: cagney/2002-02-02: The function.cfunc in the below
511 can't be replaced with func. This is because it is the
512 cfunc, and not the func, that has the value that the
513 is_complete_command hack is testing for. */
514 /* Clear off trailing whitespace, except for set and complete
515 command. */
516 std::string without_whitespace;
517 if (arg
518 && c->type != set_cmd
519 && !is_complete_command (c))
521 const char *old_end = arg + strlen (arg) - 1;
522 p = old_end;
523 while (p >= arg && (*p == ' ' || *p == '\t'))
524 p--;
525 if (p != old_end)
527 without_whitespace = std::string (arg, p + 1);
528 arg = without_whitespace.c_str ();
532 /* If this command has been pre-hooked, run the hook first. */
533 execute_cmd_pre_hook (c);
535 if (c->deprecated_warn_user)
536 deprecated_cmd_warning (line, cmdlist);
538 /* c->user_commands would be NULL in the case of a python command. */
539 if (c->theclass == class_user && c->user_commands)
540 execute_user_command (c, arg);
541 else if (c->theclass == class_user
542 && c->is_prefix () && !c->allow_unknown)
543 /* If this is a user defined prefix that does not allow unknown
544 (in other words, C is a prefix command and not a command
545 that can be followed by its args), report the list of
546 subcommands. */
548 std::string prefixname = c->prefixname ();
549 std::string prefixname_no_space
550 = prefixname.substr (0, prefixname.length () - 1);
551 gdb_printf
552 ("\"%s\" must be followed by the name of a subcommand.\n",
553 prefixname_no_space.c_str ());
554 help_list (*c->subcommands, prefixname.c_str (), all_commands,
555 gdb_stdout);
557 else if (c->type == set_cmd)
558 do_set_command (arg, from_tty, c);
559 else if (c->type == show_cmd)
560 do_show_command (arg, from_tty, c);
561 else if (c->is_command_class_help ())
562 error (_("That is not a command, just a help topic."));
563 else if (deprecated_call_command_hook)
564 deprecated_call_command_hook (c, arg, from_tty);
565 else
566 cmd_func (c, arg, from_tty);
568 maybe_wait_sync_command_done (was_sync);
570 /* If this command has been post-hooked, run the hook last.
571 We need to lookup the command again since during its execution,
572 a command may redefine itself. In this case, C pointer
573 becomes invalid so we need to look it up again. */
574 const char *cmd2 = cmd_copy.c_str ();
575 c = lookup_cmd (&cmd2, cmdlist, "", nullptr, 1, 1);
576 if (c != nullptr)
577 execute_cmd_post_hook (c);
579 if (repeat_arguments != NULL && cmd_start == saved_command_line)
581 gdb_assert (strlen (args_pointer) >= strlen (repeat_arguments));
582 strcpy (saved_command_line + (args_pointer - cmd_start),
583 repeat_arguments);
587 /* Only perform the frame-language-change check if the command
588 we just finished executing did not resume the inferior's execution.
589 If it did resume the inferior, we will do that check after
590 the inferior stopped. */
591 if (has_stack_frames () && inferior_thread ()->state != THREAD_RUNNING)
592 check_frame_language_change ();
594 cleanup_if_error.release ();
597 /* Run FN. Send its output to FILE, do not display it to the screen.
598 The global BATCH_FLAG will be temporarily set to true. */
600 static void
601 execute_fn_to_ui_file (struct ui_file *file, std::function<void(void)> fn)
603 /* GDB_STDOUT should be better already restored during these
604 restoration callbacks. */
605 set_batch_flag_and_restore_page_info save_page_info;
607 scoped_restore save_async = make_scoped_restore (&current_ui->async, 0);
609 ui_out_redirect_pop redirect_popper (current_uiout, file);
611 scoped_restore save_stdout
612 = make_scoped_restore (&gdb_stdout, file);
613 scoped_restore save_stderr
614 = make_scoped_restore (&gdb_stderr, file);
615 scoped_restore save_stdlog
616 = make_scoped_restore (&gdb_stdlog, file);
617 scoped_restore save_stdtarg
618 = make_scoped_restore (&gdb_stdtarg, file);
620 fn ();
623 /* See top.h. */
625 void
626 execute_fn_to_string (std::string &res, std::function<void(void)> fn,
627 bool term_out)
629 string_file str_file (term_out);
631 SCOPE_EXIT { res = str_file.release (); };
633 execute_fn_to_ui_file (&str_file, fn);
636 /* See top.h. */
638 void
639 execute_command_to_ui_file (struct ui_file *file,
640 const char *p, int from_tty)
642 execute_fn_to_ui_file (file, [=]() { execute_command (p, from_tty); });
645 /* See top.h. */
647 void
648 execute_command_to_string (std::string &res, const char *p, int from_tty,
649 bool term_out)
651 execute_fn_to_string (res, [=]() { execute_command (p, from_tty); },
652 term_out);
655 /* See top.h. */
657 void
658 execute_command_to_string (const char *p, int from_tty,
659 bool term_out)
661 std::string dummy;
662 execute_fn_to_string (dummy, [=]() { execute_command (p, from_tty); },
663 term_out);
666 /* When nonzero, cause dont_repeat to do nothing. This should only be
667 set via prevent_dont_repeat. */
669 static int suppress_dont_repeat = 0;
671 /* See command.h */
673 void
674 dont_repeat (void)
676 struct ui *ui = current_ui;
678 if (suppress_dont_repeat || server_command)
679 return;
681 /* If we aren't reading from standard input, we are saving the last
682 thing read from stdin in line and don't want to delete it. Null
683 lines won't repeat here in any case. */
684 if (ui->instream == ui->stdin_stream)
686 *saved_command_line = 0;
687 repeat_arguments = NULL;
691 /* See command.h */
693 const char *
694 repeat_previous ()
696 /* Do not repeat this command, as this command is a repeating command. */
697 dont_repeat ();
699 /* We cannot free saved_command_line, as this line is being executed,
700 so swap it with previous_saved_command_line. */
701 std::swap (previous_saved_command_line, saved_command_line);
702 std::swap (previous_repeat_arguments, repeat_arguments);
704 const char *prev = skip_spaces (get_saved_command_line ());
705 if (*prev == '\0')
706 error (_("No previous command to relaunch"));
707 return prev;
710 /* See command.h. */
712 scoped_restore_tmpl<int>
713 prevent_dont_repeat (void)
715 return make_scoped_restore (&suppress_dont_repeat, 1);
718 /* See command.h. */
720 char *
721 get_saved_command_line ()
723 return saved_command_line;
726 /* See command.h. */
728 void
729 save_command_line (const char *cmd)
731 xfree (previous_saved_command_line);
732 previous_saved_command_line = saved_command_line;
733 previous_repeat_arguments = repeat_arguments;
734 saved_command_line = xstrdup (cmd);
735 repeat_arguments = NULL;
739 /* Read a line from the stream "instream" without command line editing.
741 It prints PROMPT once at the start.
742 Action is compatible with "readline", e.g. space for the result is
743 malloc'd and should be freed by the caller.
745 A NULL return means end of file. */
747 static gdb::unique_xmalloc_ptr<char>
748 gdb_readline_no_editing (const char *prompt)
750 std::string line_buffer;
751 struct ui *ui = current_ui;
752 /* Read from stdin if we are executing a user defined command. This
753 is the right thing for prompt_for_continue, at least. */
754 FILE *stream = ui->instream != NULL ? ui->instream : stdin;
755 int fd = fileno (stream);
757 if (prompt != NULL)
759 /* Don't use a _filtered function here. It causes the assumed
760 character position to be off, since the newline we read from
761 the user is not accounted for. */
762 printf_unfiltered ("%s", prompt);
763 gdb_flush (gdb_stdout);
766 while (1)
768 int c;
769 fd_set readfds;
771 QUIT;
773 /* Wait until at least one byte of data is available. Control-C
774 can interrupt interruptible_select, but not fgetc. */
775 FD_ZERO (&readfds);
776 FD_SET (fd, &readfds);
777 if (interruptible_select (fd + 1, &readfds, NULL, NULL, NULL) == -1)
779 if (errno == EINTR)
781 /* If this was ctrl-c, the QUIT above handles it. */
782 continue;
784 perror_with_name (("select"));
787 c = fgetc (stream);
789 if (c == EOF)
791 if (!line_buffer.empty ())
792 /* The last line does not end with a newline. Return it, and
793 if we are called again fgetc will still return EOF and
794 we'll return NULL then. */
795 break;
796 return NULL;
799 if (c == '\n')
801 if (!line_buffer.empty () && line_buffer.back () == '\r')
802 line_buffer.pop_back ();
803 break;
806 line_buffer += c;
809 return make_unique_xstrdup (line_buffer.c_str ());
812 /* Variables which control command line editing and history
813 substitution. These variables are given default values at the end
814 of this file. */
815 static bool command_editing_p;
817 /* NOTE 1999-04-29: This variable will be static again, once we modify
818 gdb to use the event loop as the default command loop and we merge
819 event-top.c into this file, top.c. */
821 /* static */ bool history_expansion_p;
823 /* Should we write out the command history on exit? In order to write out
824 the history both this flag must be true, and the history_filename
825 variable must be set to something sensible. */
826 static bool write_history_p;
828 /* The name of the file in which GDB history will be written. If this is
829 set to NULL, of the empty string then history will not be written. */
830 static std::string history_filename;
832 /* Implement 'show history save'. */
833 static void
834 show_write_history_p (struct ui_file *file, int from_tty,
835 struct cmd_list_element *c, const char *value)
837 if (!write_history_p || !history_filename.empty ())
838 gdb_printf (file, _("Saving of the history record on exit is %s.\n"),
839 value);
840 else
841 gdb_printf (file, _("Saving of the history is disabled due to "
842 "the value of 'history filename'.\n"));
845 /* The variable associated with the "set/show history size"
846 command. The value -1 means unlimited, and -2 means undefined. */
847 static int history_size_setshow_var = -2;
849 static void
850 show_history_size (struct ui_file *file, int from_tty,
851 struct cmd_list_element *c, const char *value)
853 gdb_printf (file, _("The size of the command history is %s.\n"),
854 value);
857 /* Variable associated with the "history remove-duplicates" option.
858 The value -1 means unlimited. */
859 static int history_remove_duplicates = 0;
861 static void
862 show_history_remove_duplicates (struct ui_file *file, int from_tty,
863 struct cmd_list_element *c, const char *value)
865 gdb_printf (file,
866 _("The number of history entries to look back at for "
867 "duplicates is %s.\n"),
868 value);
871 /* Implement 'show history filename'. */
872 static void
873 show_history_filename (struct ui_file *file, int from_tty,
874 struct cmd_list_element *c, const char *value)
876 if (!history_filename.empty ())
877 gdb_printf (file, _("The filename in which to record "
878 "the command history is \"%ps\".\n"),
879 styled_string (file_name_style.style (), value));
880 else
881 gdb_printf (file, _("There is no filename currently set for "
882 "recording the command history in.\n"));
885 /* This is like readline(), but it has some gdb-specific behavior.
886 gdb may want readline in both the synchronous and async modes during
887 a single gdb invocation. At the ordinary top-level prompt we might
888 be using the async readline. That means we can't use
889 rl_pre_input_hook, since it doesn't work properly in async mode.
890 However, for a secondary prompt (" >", such as occurs during a
891 `define'), gdb wants a synchronous response.
893 We used to call readline() directly, running it in synchronous
894 mode. But mixing modes this way is not supported, and as of
895 readline 5.x it no longer works; the arrow keys come unbound during
896 the synchronous call. So we make a nested call into the event
897 loop. That's what gdb_readline_wrapper is for. */
899 /* A flag set as soon as gdb_readline_wrapper_line is called; we can't
900 rely on gdb_readline_wrapper_result, which might still be NULL if
901 the user types Control-D for EOF. */
902 static int gdb_readline_wrapper_done;
904 /* The result of the current call to gdb_readline_wrapper, once a newline
905 is seen. */
906 static char *gdb_readline_wrapper_result;
908 /* Any intercepted hook. Operate-and-get-next sets this, expecting it
909 to be called after the newline is processed (which will redisplay
910 the prompt). But in gdb_readline_wrapper we will not get a new
911 prompt until the next call, or until we return to the event loop.
912 So we disable this hook around the newline and restore it before we
913 return. */
914 static void (*saved_after_char_processing_hook) (void);
917 /* See top.h. */
920 gdb_in_secondary_prompt_p (struct ui *ui)
922 return ui->secondary_prompt_depth > 0;
926 /* This function is called when readline has seen a complete line of
927 text. */
929 static void
930 gdb_readline_wrapper_line (gdb::unique_xmalloc_ptr<char> &&line)
932 gdb_assert (!gdb_readline_wrapper_done);
933 gdb_readline_wrapper_result = line.release ();
934 gdb_readline_wrapper_done = 1;
936 /* Prevent operate-and-get-next from acting too early. */
937 saved_after_char_processing_hook = after_char_processing_hook;
938 after_char_processing_hook = NULL;
940 #if defined(TUI)
941 if (tui_active)
942 tui_inject_newline_into_command_window ();
943 #endif
945 /* Prevent parts of the prompt from being redisplayed if annotations
946 are enabled, and readline's state getting out of sync. We'll
947 reinstall the callback handler, which puts the terminal in raw
948 mode (or in readline lingo, in prepped state), when we're next
949 ready to process user input, either in display_gdb_prompt, or if
950 we're handling an asynchronous target event and running in the
951 background, just before returning to the event loop to process
952 further input (or more target events). */
953 if (current_ui->command_editing)
954 gdb_rl_callback_handler_remove ();
957 class gdb_readline_wrapper_cleanup
959 public:
960 gdb_readline_wrapper_cleanup ()
961 : m_handler_orig (current_ui->input_handler),
962 m_already_prompted_orig (current_ui->command_editing
963 ? rl_already_prompted : 0),
964 m_target_is_async_orig (target_is_async_p ()),
965 m_save_ui (&current_ui)
967 current_ui->input_handler = gdb_readline_wrapper_line;
968 current_ui->secondary_prompt_depth++;
970 if (m_target_is_async_orig)
971 target_async (false);
974 ~gdb_readline_wrapper_cleanup ()
976 struct ui *ui = current_ui;
978 if (ui->command_editing)
979 rl_already_prompted = m_already_prompted_orig;
981 gdb_assert (ui->input_handler == gdb_readline_wrapper_line);
982 ui->input_handler = m_handler_orig;
984 /* Don't restore our input handler in readline yet. That would make
985 readline prep the terminal (putting it in raw mode), while the
986 line we just read may trigger execution of a command that expects
987 the terminal in the default cooked/canonical mode, such as e.g.,
988 running Python's interactive online help utility. See
989 gdb_readline_wrapper_line for when we'll reinstall it. */
991 gdb_readline_wrapper_result = NULL;
992 gdb_readline_wrapper_done = 0;
993 ui->secondary_prompt_depth--;
994 gdb_assert (ui->secondary_prompt_depth >= 0);
996 after_char_processing_hook = saved_after_char_processing_hook;
997 saved_after_char_processing_hook = NULL;
999 if (m_target_is_async_orig)
1000 target_async (true);
1003 DISABLE_COPY_AND_ASSIGN (gdb_readline_wrapper_cleanup);
1005 private:
1007 void (*m_handler_orig) (gdb::unique_xmalloc_ptr<char> &&);
1008 int m_already_prompted_orig;
1010 /* Whether the target was async. */
1011 int m_target_is_async_orig;
1013 /* Processing events may change the current UI. */
1014 scoped_restore_tmpl<struct ui *> m_save_ui;
1017 char *
1018 gdb_readline_wrapper (const char *prompt)
1020 struct ui *ui = current_ui;
1022 gdb_readline_wrapper_cleanup cleanup;
1024 /* Display our prompt and prevent double prompt display. Don't pass
1025 down a NULL prompt, since that has special meaning for
1026 display_gdb_prompt -- it indicates a request to print the primary
1027 prompt, while we want a secondary prompt here. */
1028 display_gdb_prompt (prompt != NULL ? prompt : "");
1029 if (ui->command_editing)
1030 rl_already_prompted = 1;
1032 if (after_char_processing_hook)
1033 (*after_char_processing_hook) ();
1034 gdb_assert (after_char_processing_hook == NULL);
1036 while (gdb_do_one_event () >= 0)
1037 if (gdb_readline_wrapper_done)
1038 break;
1040 return gdb_readline_wrapper_result;
1044 /* The current saved history number from operate-and-get-next.
1045 This is -1 if not valid. */
1046 static int operate_saved_history = -1;
1048 /* This is put on the appropriate hook and helps operate-and-get-next
1049 do its work. */
1050 static void
1051 gdb_rl_operate_and_get_next_completion (void)
1053 if (operate_saved_history != -1)
1055 int delta = where_history () - operate_saved_history;
1057 /* The `key' argument to rl_get_previous_history is ignored. */
1058 rl_get_previous_history (delta, 0);
1059 operate_saved_history = -1;
1062 /* readline doesn't automatically update the display for us. */
1063 rl_redisplay ();
1065 after_char_processing_hook = NULL;
1066 rl_pre_input_hook = NULL;
1069 /* This is a gdb-local readline command handler. It accepts the
1070 current command line (like RET does) and, if this command was taken
1071 from the history, arranges for the next command in the history to
1072 appear on the command line when the prompt returns.
1073 We ignore the arguments. */
1074 static int
1075 gdb_rl_operate_and_get_next (int count, int key)
1077 int where;
1079 /* Use the async hook. */
1080 after_char_processing_hook = gdb_rl_operate_and_get_next_completion;
1082 /* Find the current line, and find the next line to use. */
1083 where = where_history();
1085 if (history_is_stifled () && history_length >= history_max_entries)
1086 operate_saved_history = where;
1087 else if (where >= history_length - 1)
1088 operate_saved_history = -1;
1089 else
1090 operate_saved_history = where + 1;
1092 return rl_newline (1, key);
1095 /* Number of user commands executed during this session. */
1097 static int command_count = 0;
1099 /* Add the user command COMMAND to the input history list. */
1101 void
1102 gdb_add_history (const char *command)
1104 command_count++;
1106 if (history_remove_duplicates != 0)
1108 int lookbehind;
1109 int lookbehind_threshold;
1111 /* The lookbehind threshold for finding a duplicate history entry is
1112 bounded by command_count because we can't meaningfully delete
1113 history entries that are already stored in the history file since
1114 the history file is appended to. */
1115 if (history_remove_duplicates == -1
1116 || history_remove_duplicates > command_count)
1117 lookbehind_threshold = command_count;
1118 else
1119 lookbehind_threshold = history_remove_duplicates;
1121 using_history ();
1122 for (lookbehind = 0; lookbehind < lookbehind_threshold; lookbehind++)
1124 HIST_ENTRY *temp = previous_history ();
1126 if (temp == NULL)
1127 break;
1129 if (strcmp (temp->line, command) == 0)
1131 HIST_ENTRY *prev = remove_history (where_history ());
1132 command_count--;
1133 free_history_entry (prev);
1134 break;
1137 using_history ();
1140 add_history (command);
1143 /* Safely append new history entries to the history file in a corruption-free
1144 way using an intermediate local history file. */
1146 static void
1147 gdb_safe_append_history (void)
1149 int ret, saved_errno;
1151 std::string local_history_filename
1152 = string_printf ("%s-gdb%ld~", history_filename.c_str (), (long) getpid ());
1154 ret = rename (history_filename.c_str (), local_history_filename.c_str ());
1155 saved_errno = errno;
1156 if (ret < 0 && saved_errno != ENOENT)
1158 warning (_("Could not rename %ps to %ps: %s"),
1159 styled_string (file_name_style.style (),
1160 history_filename.c_str ()),
1161 styled_string (file_name_style.style (),
1162 local_history_filename.c_str ()),
1163 safe_strerror (saved_errno));
1165 else
1167 if (ret < 0)
1169 /* If the rename failed with ENOENT then either the global history
1170 file never existed in the first place or another GDB process is
1171 currently appending to it (and has thus temporarily renamed it).
1172 Since we can't distinguish between these two cases, we have to
1173 conservatively assume the first case and therefore must write out
1174 (not append) our known history to our local history file and try
1175 to move it back anyway. Otherwise a global history file would
1176 never get created! */
1177 gdb_assert (saved_errno == ENOENT);
1178 write_history (local_history_filename.c_str ());
1180 else
1182 append_history (command_count, local_history_filename.c_str ());
1183 if (history_is_stifled ())
1184 history_truncate_file (local_history_filename.c_str (),
1185 history_max_entries);
1188 ret = rename (local_history_filename.c_str (), history_filename.c_str ());
1189 saved_errno = errno;
1190 if (ret < 0 && saved_errno != EEXIST)
1191 warning (_("Could not rename %s to %s: %s"),
1192 local_history_filename.c_str (), history_filename.c_str (),
1193 safe_strerror (saved_errno));
1197 /* Read one line from the command input stream `instream'.
1199 CMD_LINE_BUFFER is a buffer that the function may use to store the result, if
1200 it needs to be dynamically-allocated. Otherwise, it is unused.string
1202 Return nullptr for end of file.
1204 This routine either uses fancy command line editing or simple input
1205 as the user has requested. */
1207 const char *
1208 command_line_input (std::string &cmd_line_buffer, const char *prompt_arg,
1209 const char *annotation_suffix)
1211 struct ui *ui = current_ui;
1212 const char *prompt = prompt_arg;
1213 const char *cmd;
1214 int from_tty = ui->instream == ui->stdin_stream;
1216 /* The annotation suffix must be non-NULL. */
1217 if (annotation_suffix == NULL)
1218 annotation_suffix = "";
1220 if (from_tty && annotation_level > 1)
1222 char *local_prompt;
1224 local_prompt
1225 = (char *) alloca ((prompt == NULL ? 0 : strlen (prompt))
1226 + strlen (annotation_suffix) + 40);
1227 if (prompt == NULL)
1228 local_prompt[0] = '\0';
1229 else
1230 strcpy (local_prompt, prompt);
1231 strcat (local_prompt, "\n\032\032");
1232 strcat (local_prompt, annotation_suffix);
1233 strcat (local_prompt, "\n");
1235 prompt = local_prompt;
1238 #ifdef SIGTSTP
1239 if (job_control)
1240 signal (SIGTSTP, handle_sigtstp);
1241 #endif
1243 while (1)
1245 gdb::unique_xmalloc_ptr<char> rl;
1247 /* Make sure that all output has been output. Some machines may
1248 let you get away with leaving out some of the gdb_flush, but
1249 not all. */
1250 gdb_flush (gdb_stdout);
1251 gdb_flush (gdb_stderr);
1253 if (!source_file_name.empty ())
1254 ++source_line_number;
1256 if (from_tty && annotation_level > 1)
1257 printf_unfiltered ("\n\032\032pre-%s\n", annotation_suffix);
1259 /* Don't use fancy stuff if not talking to stdin. */
1260 if (deprecated_readline_hook
1261 && from_tty
1262 && current_ui->input_interactive_p ())
1264 rl.reset ((*deprecated_readline_hook) (prompt));
1266 else if (command_editing_p
1267 && from_tty
1268 && current_ui->input_interactive_p ())
1270 rl.reset (gdb_readline_wrapper (prompt));
1272 else
1274 rl = gdb_readline_no_editing (prompt);
1277 cmd = handle_line_of_input (cmd_line_buffer, rl.get (),
1278 0, annotation_suffix);
1279 if (cmd == (char *) EOF)
1281 cmd = NULL;
1282 break;
1284 if (cmd != NULL)
1285 break;
1287 /* Got partial input. I.e., got a line that ends with a
1288 continuation character (backslash). Suppress printing the
1289 prompt again. */
1290 prompt = NULL;
1293 #ifdef SIGTSTP
1294 if (job_control)
1295 signal (SIGTSTP, SIG_DFL);
1296 #endif
1298 return cmd;
1301 /* See top.h. */
1302 void
1303 print_gdb_version (struct ui_file *stream, bool interactive)
1305 /* From GNU coding standards, first line is meant to be easy for a
1306 program to parse, and is just canonical program name and version
1307 number, which starts after last space. */
1309 std::string v_str = string_printf ("GNU gdb %s%s", PKGVERSION, version);
1310 gdb_printf (stream, "%ps\n",
1311 styled_string (version_style.style (), v_str.c_str ()));
1313 /* Second line is a copyright notice. */
1315 gdb_printf (stream,
1316 "Copyright (C) 2024 Free Software Foundation, Inc.\n");
1318 /* Following the copyright is a brief statement that the program is
1319 free software, that users are free to copy and change it on
1320 certain conditions, that it is covered by the GNU GPL, and that
1321 there is no warranty. */
1323 gdb_printf (stream, "\
1324 License GPLv3+: GNU GPL version 3 or later <%ps>\
1325 \nThis is free software: you are free to change and redistribute it.\n\
1326 There is NO WARRANTY, to the extent permitted by law.",
1327 styled_string (file_name_style.style (),
1328 "http://gnu.org/licenses/gpl.html"));
1330 if (!interactive)
1331 return;
1333 gdb_printf (stream, ("\nType \"%ps\" and \"%ps\" for details.\n"),
1334 styled_string (command_style.style (), "show copying"),
1335 styled_string (command_style.style (), "show warranty"));
1337 /* After the required info we print the configuration information. */
1339 gdb_printf (stream, "This GDB was configured as \"");
1340 if (strcmp (host_name, target_name) != 0)
1342 gdb_printf (stream, "--host=%s --target=%s",
1343 host_name, target_name);
1345 else
1347 gdb_printf (stream, "%s", host_name);
1349 gdb_printf (stream, "\".\n");
1351 gdb_printf (stream, _("Type \"%ps\" for configuration details.\n"),
1352 styled_string (command_style.style (), "show configuration"));
1354 if (REPORT_BUGS_TO[0])
1356 gdb_printf (stream,
1357 _("For bug reporting instructions, please see:\n"));
1358 gdb_printf (stream, "%ps.\n",
1359 styled_string (file_name_style.style (),
1360 REPORT_BUGS_TO));
1362 gdb_printf (stream,
1363 _("Find the GDB manual and other documentation \
1364 resources online at:\n <%ps>."),
1365 styled_string (file_name_style.style (),
1366 "http://www.gnu.org/software/gdb/documentation/"));
1367 gdb_printf (stream, "\n\n");
1368 gdb_printf (stream, _("For help, type \"%ps\".\n"),
1369 styled_string (command_style.style (), "help"));
1370 gdb_printf (stream,
1371 _("Type \"%ps\" to search for commands related to \"word\"."),
1372 styled_string (command_style.style (), "apropos word"));
1375 /* Print the details of GDB build-time configuration. */
1376 void
1377 print_gdb_configuration (struct ui_file *stream)
1379 gdb_printf (stream, _("\
1380 This GDB was configured as follows:\n\
1381 configure --host=%s --target=%s\n\
1382 "), host_name, target_name);
1384 #ifdef ENABLE_TARGETS
1385 gdb_printf (stream, _("\
1386 --enable-targets=%s\n"), ENABLE_TARGETS);
1387 #endif
1389 gdb_printf (stream, _("\
1390 --with-auto-load-dir=%s\n\
1391 --with-auto-load-safe-path=%s\n\
1392 "), AUTO_LOAD_DIR, AUTO_LOAD_SAFE_PATH);
1394 #if HAVE_LIBEXPAT
1395 gdb_printf (stream, _("\
1396 --with-expat\n\
1397 "));
1398 #else
1399 gdb_printf (stream, _("\
1400 --without-expat\n\
1401 "));
1402 #endif
1404 if (GDB_DATADIR[0])
1405 gdb_printf (stream, _("\
1406 --with-gdb-datadir=%s%s\n\
1407 "), GDB_DATADIR, GDB_DATADIR_RELOCATABLE ? " (relocatable)" : "");
1409 #ifdef ICONV_BIN
1410 gdb_printf (stream, _("\
1411 --with-iconv-bin=%s%s\n\
1412 "), ICONV_BIN, ICONV_BIN_RELOCATABLE ? " (relocatable)" : "");
1413 #endif
1415 if (JIT_READER_DIR[0])
1416 gdb_printf (stream, _("\
1417 --with-jit-reader-dir=%s%s\n\
1418 "), JIT_READER_DIR, JIT_READER_DIR_RELOCATABLE ? " (relocatable)" : "");
1420 #if HAVE_LIBUNWIND_IA64_H
1421 gdb_printf (stream, _("\
1422 --with-libunwind-ia64\n\
1423 "));
1424 #else
1425 gdb_printf (stream, _("\
1426 --without-libunwind-ia64\n\
1427 "));
1428 #endif
1430 #if HAVE_LIBLZMA
1431 gdb_printf (stream, _("\
1432 --with-lzma\n\
1433 "));
1434 #else
1435 gdb_printf (stream, _("\
1436 --without-lzma\n\
1437 "));
1438 #endif
1440 #if HAVE_LIBBABELTRACE
1441 gdb_printf (stream, _("\
1442 --with-babeltrace\n\
1443 "));
1444 #else
1445 gdb_printf (stream, _("\
1446 --without-babeltrace\n\
1447 "));
1448 #endif
1450 #if HAVE_LIBIPT
1451 gdb_printf (stream, _("\
1452 --with-intel-pt\n\
1453 "));
1454 #else
1455 gdb_printf (stream, _("\
1456 --without-intel-pt\n\
1457 "));
1458 #endif
1460 #if HAVE_LIBXXHASH
1461 gdb_printf (stream, _("\
1462 --with-xxhash\n\
1463 "));
1464 #else
1465 gdb_printf (stream, _("\
1466 --without-xxhash\n\
1467 "));
1468 #endif
1469 #ifdef WITH_PYTHON_PATH
1470 gdb_printf (stream, _("\
1471 --with-python=%s%s\n\
1472 "), WITH_PYTHON_PATH, PYTHON_PATH_RELOCATABLE ? " (relocatable)" : "");
1473 #else
1474 gdb_printf (stream, _("\
1475 --without-python\n\
1476 "));
1477 #endif
1478 #ifdef WITH_PYTHON_LIBDIR
1479 gdb_printf (stream, _("\
1480 --with-python-libdir=%s%s\n\
1481 "), WITH_PYTHON_LIBDIR, PYTHON_LIBDIR_RELOCATABLE ? " (relocatable)" : "");
1482 #else
1483 gdb_printf (stream, _("\
1484 --without-python-libdir\n\
1485 "));
1486 #endif
1488 #if HAVE_LIBDEBUGINFOD
1489 gdb_printf (stream, _("\
1490 --with-debuginfod\n\
1491 "));
1492 #else
1493 gdb_printf (stream, _("\
1494 --without-debuginfod\n\
1495 "));
1496 #endif
1498 #if HAVE_LIBCURSES
1499 gdb_printf (stream, _("\
1500 --with-curses\n\
1501 "));
1502 #else
1503 gdb_printf (stream, _("\
1504 --without-curses\n\
1505 "));
1506 #endif
1508 #if HAVE_GUILE
1509 gdb_printf (stream, _("\
1510 --with-guile\n\
1511 "));
1512 #else
1513 gdb_printf (stream, _("\
1514 --without-guile\n\
1515 "));
1516 #endif
1518 #if HAVE_AMD_DBGAPI
1519 gdb_printf (stream, _("\
1520 --with-amd-dbgapi\n\
1521 "));
1522 #else
1523 gdb_printf (stream, _("\
1524 --without-amd-dbgapi\n\
1525 "));
1526 #endif
1528 #if HAVE_SOURCE_HIGHLIGHT
1529 gdb_printf (stream, _("\
1530 --enable-source-highlight\n\
1531 "));
1532 #else
1533 gdb_printf (stream, _("\
1534 --disable-source-highlight\n\
1535 "));
1536 #endif
1538 #if CXX_STD_THREAD
1539 gdb_printf (stream, _("\
1540 --enable-threading\n\
1541 "));
1542 #else
1543 gdb_printf (stream, _("\
1544 --disable-threading\n\
1545 "));
1546 #endif
1548 #ifdef TUI
1549 gdb_printf (stream, _("\
1550 --enable-tui\n\
1551 "));
1552 #else
1553 gdb_printf (stream, _("\
1554 --disable-tui\n\
1555 "));
1556 #endif
1558 #ifdef HAVE_READLINE_READLINE_H
1559 gdb_printf (stream, _("\
1560 --with-system-readline\n\
1561 "));
1562 #else
1563 gdb_printf (stream, _("\
1564 --without-system-readline\n\
1565 "));
1566 #endif
1568 #ifdef RELOC_SRCDIR
1569 gdb_printf (stream, _("\
1570 --with-relocated-sources=%s\n\
1571 "), RELOC_SRCDIR);
1572 #endif
1574 if (DEBUGDIR[0])
1575 gdb_printf (stream, _("\
1576 --with-separate-debug-dir=%s%s\n\
1577 "), DEBUGDIR, DEBUGDIR_RELOCATABLE ? " (relocatable)" : "");
1579 #ifdef ADDITIONAL_DEBUG_DIRS
1580 gdb_printf (stream, _ ("\
1581 --with-additional-debug-dirs=%s\n\
1582 "), ADDITIONAL_DEBUG_DIRS);
1583 #endif
1585 if (TARGET_SYSTEM_ROOT[0])
1586 gdb_printf (stream, _("\
1587 --with-sysroot=%s%s\n\
1588 "), TARGET_SYSTEM_ROOT, TARGET_SYSTEM_ROOT_RELOCATABLE ? " (relocatable)" : "");
1590 if (SYSTEM_GDBINIT[0])
1591 gdb_printf (stream, _("\
1592 --with-system-gdbinit=%s%s\n\
1593 "), SYSTEM_GDBINIT, SYSTEM_GDBINIT_RELOCATABLE ? " (relocatable)" : "");
1595 if (SYSTEM_GDBINIT_DIR[0])
1596 gdb_printf (stream, _("\
1597 --with-system-gdbinit-dir=%s%s\n\
1598 "), SYSTEM_GDBINIT_DIR, SYSTEM_GDBINIT_DIR_RELOCATABLE ? " (relocatable)" : "");
1600 /* We assume "relocatable" will be printed at least once, thus we always
1601 print this text. It's a reasonably safe assumption for now. */
1602 gdb_printf (stream, _("\n\
1603 (\"Relocatable\" means the directory can be moved with the GDB installation\n\
1604 tree, and GDB will still find it.)\n\
1605 "));
1607 gdb_printf (stream, "\n");
1608 gdb_printf (stream, _("GNU Readline library version: %s\t%s\n"),
1609 rl_library_version,
1610 #ifdef HAVE_READLINE_READLINE_H
1611 "(system)"
1612 #else
1613 "(internal)"
1614 #endif
1619 /* The current top level prompt, settable with "set prompt", and/or
1620 with the python `gdb.prompt_hook' hook. */
1621 static std::string top_prompt;
1623 /* Access method for the GDB prompt string. */
1625 const std::string &
1626 get_prompt ()
1628 return top_prompt;
1631 /* Set method for the GDB prompt string. */
1633 void
1634 set_prompt (const char *s)
1636 top_prompt = s;
1640 /* Kills or detaches the given inferior, depending on how we originally
1641 gained control of it. */
1643 static void
1644 kill_or_detach (inferior *inf, int from_tty)
1646 if (inf->pid == 0)
1647 return;
1649 thread_info *thread = any_thread_of_inferior (inf);
1650 if (thread != NULL)
1652 switch_to_thread (thread);
1654 /* Leave core files alone. */
1655 if (target_has_execution ())
1657 if (inf->attach_flag)
1658 target_detach (inf, from_tty);
1659 else
1660 target_kill ();
1665 /* Prints info about what GDB will do to inferior INF on a "quit". OUT is
1666 where to collect the output. */
1668 static void
1669 print_inferior_quit_action (inferior *inf, ui_file *out)
1671 if (inf->pid == 0)
1672 return;
1674 if (inf->attach_flag)
1675 gdb_printf (out,
1676 _("\tInferior %d [%s] will be detached.\n"), inf->num,
1677 target_pid_to_str (ptid_t (inf->pid)).c_str ());
1678 else
1679 gdb_printf (out,
1680 _("\tInferior %d [%s] will be killed.\n"), inf->num,
1681 target_pid_to_str (ptid_t (inf->pid)).c_str ());
1684 /* If necessary, make the user confirm that we should quit. Return
1685 non-zero if we should quit, zero if we shouldn't. */
1688 quit_confirm (void)
1690 /* Don't even ask if we're only debugging a core file inferior. */
1691 if (!have_live_inferiors ())
1692 return 1;
1694 /* Build the query string as a single string. */
1695 string_file stb;
1697 stb.puts (_("A debugging session is active.\n\n"));
1699 for (inferior *inf : all_inferiors ())
1700 print_inferior_quit_action (inf, &stb);
1702 stb.puts (_("\nQuit anyway? "));
1704 return query ("%s", stb.c_str ());
1707 /* Prepare to exit GDB cleanly by undoing any changes made to the
1708 terminal so that we leave the terminal in the state we acquired it. */
1710 static void
1711 undo_terminal_modifications_before_exit (void)
1713 struct ui *saved_top_level = current_ui;
1715 target_terminal::ours ();
1717 current_ui = main_ui;
1719 #if defined(TUI)
1720 tui_disable ();
1721 #endif
1722 gdb_disable_readline ();
1724 current_ui = saved_top_level;
1728 /* Quit without asking for confirmation. */
1730 void
1731 quit_force (int *exit_arg, int from_tty)
1733 int exit_code = 0;
1735 /* Clear the quit flag and sync_quit_force_run so that a
1736 gdb_exception_forced_quit isn't inadvertently triggered by a QUIT
1737 check while running the various cleanup/exit code below. Note
1738 that the call to 'check_quit_flag' clears the quit flag as a side
1739 effect. */
1740 check_quit_flag ();
1741 sync_quit_force_run = false;
1743 /* An optional expression may be used to cause gdb to terminate with the
1744 value of that expression. */
1745 if (exit_arg)
1746 exit_code = *exit_arg;
1747 else if (return_child_result)
1748 exit_code = return_child_result_value;
1750 gdb::observers::gdb_exiting.notify (exit_code);
1752 undo_terminal_modifications_before_exit ();
1754 /* We want to handle any quit errors and exit regardless. */
1756 /* Get out of tfind mode, and kill or detach all inferiors. */
1759 disconnect_tracing ();
1760 for (inferior *inf : all_inferiors ())
1761 kill_or_detach (inf, from_tty);
1763 catch (const gdb_exception &ex)
1765 exception_print (gdb_stderr, ex);
1768 /* Give all pushed targets a chance to do minimal cleanup, and pop
1769 them all out. */
1770 for (inferior *inf : all_inferiors ())
1774 inf->pop_all_targets ();
1776 catch (const gdb_exception &ex)
1778 exception_print (gdb_stderr, ex);
1782 /* Save the history information if it is appropriate to do so. */
1785 if (write_history_p && !history_filename.empty ())
1787 int save = 0;
1789 /* History is currently shared between all UIs. If there's
1790 any UI with a terminal, save history. */
1791 for (ui *ui : all_uis ())
1793 if (ui->input_interactive_p ())
1795 save = 1;
1796 break;
1800 if (save)
1801 gdb_safe_append_history ();
1804 catch (const gdb_exception &ex)
1806 exception_print (gdb_stderr, ex);
1809 /* Do any final cleanups before exiting. */
1812 do_final_cleanups ();
1814 catch (const gdb_exception &ex)
1816 exception_print (gdb_stderr, ex);
1819 ext_lang_shutdown ();
1821 exit (exit_code);
1824 /* See top.h. */
1826 auto_boolean interactive_mode = AUTO_BOOLEAN_AUTO;
1828 /* Implement the "show interactive-mode" option. */
1830 static void
1831 show_interactive_mode (struct ui_file *file, int from_tty,
1832 struct cmd_list_element *c,
1833 const char *value)
1835 if (interactive_mode == AUTO_BOOLEAN_AUTO)
1836 gdb_printf (file, "Debugger's interactive mode "
1837 "is %s (currently %s).\n",
1838 value, current_ui->input_interactive_p () ? "on" : "off");
1839 else
1840 gdb_printf (file, "Debugger's interactive mode is %s.\n", value);
1843 static void
1844 dont_repeat_command (const char *ignored, int from_tty)
1846 /* Can't call dont_repeat here because we're not necessarily reading
1847 from stdin. */
1848 *saved_command_line = 0;
1851 /* Functions to manipulate command line editing control variables. */
1853 /* Number of commands to print in each call to show_commands. */
1854 #define Hist_print 10
1855 void
1856 show_commands (const char *args, int from_tty)
1858 /* Index for history commands. Relative to history_base. */
1859 int offset;
1861 /* Number of the history entry which we are planning to display next.
1862 Relative to history_base. */
1863 static int num = 0;
1865 /* Print out some of the commands from the command history. */
1867 if (args)
1869 if (args[0] == '+' && args[1] == '\0')
1870 /* "info editing +" should print from the stored position. */
1872 else
1873 /* "info editing <exp>" should print around command number <exp>. */
1874 num = (parse_and_eval_long (args) - history_base) - Hist_print / 2;
1876 /* "show commands" means print the last Hist_print commands. */
1877 else
1879 num = history_length - Hist_print;
1882 if (num < 0)
1883 num = 0;
1885 /* If there are at least Hist_print commands, we want to display the last
1886 Hist_print rather than, say, the last 6. */
1887 if (history_length - num < Hist_print)
1889 num = history_length - Hist_print;
1890 if (num < 0)
1891 num = 0;
1894 for (offset = num;
1895 offset < num + Hist_print && offset < history_length;
1896 offset++)
1898 gdb_printf ("%5d %s\n", history_base + offset,
1899 (history_get (history_base + offset))->line);
1902 /* The next command we want to display is the next one that we haven't
1903 displayed yet. */
1904 num += Hist_print;
1906 /* If the user repeats this command with return, it should do what
1907 "show commands +" does. This is unnecessary if arg is null,
1908 because "show commands +" is not useful after "show commands". */
1909 if (from_tty && args)
1910 set_repeat_arguments ("+");
1913 /* Update the size of our command history file to HISTORY_SIZE.
1915 A HISTORY_SIZE of -1 stands for unlimited. */
1917 static void
1918 set_readline_history_size (int history_size)
1920 gdb_assert (history_size >= -1);
1922 if (history_size == -1)
1923 unstifle_history ();
1924 else
1925 stifle_history (history_size);
1928 /* Called by do_setshow_command. */
1929 static void
1930 set_history_size_command (const char *args,
1931 int from_tty, struct cmd_list_element *c)
1933 set_readline_history_size (history_size_setshow_var);
1936 bool info_verbose = false; /* Default verbose msgs off. */
1938 /* Called by do_set_command. An elaborate joke. */
1939 void
1940 set_verbose (const char *args, int from_tty, struct cmd_list_element *c)
1942 const char *cmdname = "verbose";
1943 struct cmd_list_element *showcmd;
1945 showcmd = lookup_cmd_1 (&cmdname, showlist, NULL, NULL, 1);
1946 gdb_assert (showcmd != NULL && showcmd != CMD_LIST_AMBIGUOUS);
1948 if (c->doc && c->doc_allocated)
1949 xfree ((char *) c->doc);
1950 if (showcmd->doc && showcmd->doc_allocated)
1951 xfree ((char *) showcmd->doc);
1952 if (info_verbose)
1954 c->doc = _("Set verbose printing of informational messages.");
1955 showcmd->doc = _("Show verbose printing of informational messages.");
1957 else
1959 c->doc = _("Set verbosity.");
1960 showcmd->doc = _("Show verbosity.");
1962 c->doc_allocated = 0;
1963 showcmd->doc_allocated = 0;
1966 /* Init the history buffer. Note that we are called after the init file(s)
1967 have been read so that the user can change the history file via his
1968 .gdbinit file (for instance). The GDBHISTFILE environment variable
1969 overrides all of this. */
1971 void
1972 init_history (void)
1974 const char *tmpenv;
1976 tmpenv = getenv ("GDBHISTSIZE");
1977 if (tmpenv)
1979 long var;
1980 int saved_errno;
1981 char *endptr;
1983 tmpenv = skip_spaces (tmpenv);
1984 errno = 0;
1985 var = strtol (tmpenv, &endptr, 10);
1986 saved_errno = errno;
1987 endptr = skip_spaces (endptr);
1989 /* If GDBHISTSIZE is non-numeric then ignore it. If GDBHISTSIZE is the
1990 empty string, a negative number or a huge positive number (larger than
1991 INT_MAX) then set the history size to unlimited. Otherwise set our
1992 history size to the number we have read. This behavior is consistent
1993 with how bash handles HISTSIZE. */
1994 if (*endptr != '\0')
1996 else if (*tmpenv == '\0'
1997 || var < 0
1998 || var > INT_MAX
1999 /* On targets where INT_MAX == LONG_MAX, we have to look at
2000 errno after calling strtol to distinguish between a value that
2001 is exactly INT_MAX and an overflowing value that was clamped
2002 to INT_MAX. */
2003 || (var == INT_MAX && saved_errno == ERANGE))
2004 history_size_setshow_var = -1;
2005 else
2006 history_size_setshow_var = var;
2009 /* If neither the init file nor GDBHISTSIZE has set a size yet, pick the
2010 default. */
2011 if (history_size_setshow_var == -2)
2012 history_size_setshow_var = 256;
2014 set_readline_history_size (history_size_setshow_var);
2016 if (!history_filename.empty ())
2017 read_history (history_filename.c_str ());
2020 static void
2021 show_prompt (struct ui_file *file, int from_tty,
2022 struct cmd_list_element *c, const char *value)
2024 gdb_printf (file, _("Gdb's prompt is \"%s\".\n"), value);
2027 /* "set editing" command. */
2029 static void
2030 set_editing (const char *args, int from_tty, struct cmd_list_element *c)
2032 change_line_handler (set_editing_cmd_var);
2033 /* Update the control variable so that MI's =cmd-param-changed event
2034 shows the correct value. */
2035 set_editing_cmd_var = current_ui->command_editing;
2038 static void
2039 show_editing (struct ui_file *file, int from_tty,
2040 struct cmd_list_element *c, const char *value)
2042 gdb_printf (file, _("Editing of command lines as "
2043 "they are typed is %s.\n"),
2044 current_ui->command_editing ? _("on") : _("off"));
2047 static void
2048 show_annotation_level (struct ui_file *file, int from_tty,
2049 struct cmd_list_element *c, const char *value)
2051 gdb_printf (file, _("Annotation_level is %s.\n"), value);
2054 static void
2055 show_exec_done_display_p (struct ui_file *file, int from_tty,
2056 struct cmd_list_element *c, const char *value)
2058 gdb_printf (file, _("Notification of completion for "
2059 "asynchronous execution commands is %s.\n"),
2060 value);
2063 /* New values of the "data-directory" parameter are staged here.
2064 Extension languages, for example Python's gdb.parameter API, will read
2065 the value directory from this variable, so we must ensure that this
2066 always contains the correct value. */
2067 static std::string staged_gdb_datadir;
2069 /* "set" command for the gdb_datadir configuration variable. */
2071 static void
2072 set_gdb_datadir (const char *args, int from_tty, struct cmd_list_element *c)
2074 set_gdb_data_directory (staged_gdb_datadir.c_str ());
2076 /* SET_GDB_DATA_DIRECTORY will resolve relative paths in
2077 STAGED_GDB_DATADIR, so we now copy the value from GDB_DATADIR
2078 back into STAGED_GDB_DATADIR so the extension languages can read the
2079 correct value. */
2080 staged_gdb_datadir = gdb_datadir;
2082 gdb::observers::gdb_datadir_changed.notify ();
2085 /* "show" command for the gdb_datadir configuration variable. */
2087 static void
2088 show_gdb_datadir (struct ui_file *file, int from_tty,
2089 struct cmd_list_element *c, const char *value)
2091 gdb_printf (file, _("GDB's data directory is \"%ps\".\n"),
2092 styled_string (file_name_style.style (),
2093 gdb_datadir.c_str ()));
2096 /* Implement 'set history filename'. */
2098 static void
2099 set_history_filename (const char *args,
2100 int from_tty, struct cmd_list_element *c)
2102 /* We include the current directory so that if the user changes
2103 directories the file written will be the same as the one
2104 that was read. */
2105 if (!history_filename.empty ()
2106 && !IS_ABSOLUTE_PATH (history_filename.c_str ()))
2107 history_filename = gdb_abspath (history_filename);
2110 /* Whether we're in quiet startup mode. */
2112 static bool startup_quiet;
2114 /* See top.h. */
2116 bool
2117 check_quiet_mode ()
2119 return startup_quiet;
2122 /* Show whether GDB should start up in quiet mode. */
2124 static void
2125 show_startup_quiet (struct ui_file *file, int from_tty,
2126 struct cmd_list_element *c, const char *value)
2128 gdb_printf (file, _("Whether to start up quietly is %s.\n"),
2129 value);
2132 static void
2133 init_colorsupport_var ()
2135 const std::vector<color_space> &cs = colorsupport ();
2136 std::string s;
2137 for (color_space c : cs)
2138 s.append (s.empty () ? "" : ",").append (color_space_name (c));
2139 struct internalvar *colorsupport_var = create_internalvar ("_colorsupport");
2140 set_internalvar_string (colorsupport_var, s.c_str ());
2143 static void
2144 init_main (void)
2146 /* Initialize the prompt to a simple "(gdb) " prompt or to whatever
2147 the DEFAULT_PROMPT is. */
2148 set_prompt (DEFAULT_PROMPT);
2150 /* Set the important stuff up for command editing. */
2151 command_editing_p = 1;
2152 history_expansion_p = 0;
2153 write_history_p = 0;
2155 /* Setup important stuff for command line editing. */
2156 rl_completion_display_matches_hook = cli_display_match_list;
2157 rl_readline_name = "gdb";
2158 rl_terminal_name = getenv ("TERM");
2159 rl_deprep_term_function = gdb_rl_deprep_term_function;
2161 /* The name for this defun comes from Bash, where it originated.
2162 15 is Control-o, the same binding this function has in Bash. */
2163 rl_add_defun ("operate-and-get-next", gdb_rl_operate_and_get_next, 15);
2165 add_setshow_string_cmd ("prompt", class_support,
2166 &top_prompt,
2167 _("Set gdb's prompt."),
2168 _("Show gdb's prompt."),
2169 NULL, NULL,
2170 show_prompt,
2171 &setlist, &showlist);
2173 add_com ("dont-repeat", class_support, dont_repeat_command, _("\
2174 Don't repeat this command.\nPrimarily \
2175 used inside of user-defined commands that should not be repeated when\n\
2176 hitting return."));
2178 add_setshow_boolean_cmd ("editing", class_support,
2179 &set_editing_cmd_var, _("\
2180 Set editing of command lines as they are typed."), _("\
2181 Show editing of command lines as they are typed."), _("\
2182 Use \"on\" to enable the editing, and \"off\" to disable it.\n\
2183 Without an argument, command line editing is enabled. To edit, use\n\
2184 EMACS-like or VI-like commands like control-P or ESC."),
2185 set_editing,
2186 show_editing,
2187 &setlist, &showlist);
2189 add_setshow_boolean_cmd ("save", no_class, &write_history_p, _("\
2190 Set saving of the history record on exit."), _("\
2191 Show saving of the history record on exit."), _("\
2192 Use \"on\" to enable the saving, and \"off\" to disable it.\n\
2193 Without an argument, saving is enabled."),
2194 NULL,
2195 show_write_history_p,
2196 &sethistlist, &showhistlist);
2198 add_setshow_zuinteger_unlimited_cmd ("size", no_class,
2199 &history_size_setshow_var, _("\
2200 Set the size of the command history."), _("\
2201 Show the size of the command history."), _("\
2202 This is the number of previous commands to keep a record of.\n\
2203 If set to \"unlimited\", the number of commands kept in the history\n\
2204 list is unlimited. This defaults to the value of the environment\n\
2205 variable \"GDBHISTSIZE\", or to 256 if this variable is not set."),
2206 set_history_size_command,
2207 show_history_size,
2208 &sethistlist, &showhistlist);
2210 add_setshow_zuinteger_unlimited_cmd ("remove-duplicates", no_class,
2211 &history_remove_duplicates, _("\
2212 Set how far back in history to look for and remove duplicate entries."), _("\
2213 Show how far back in history to look for and remove duplicate entries."), _("\
2214 If set to a nonzero value N, GDB will look back at the last N history entries\n\
2215 and remove the first history entry that is a duplicate of the most recent\n\
2216 entry, each time a new history entry is added.\n\
2217 If set to \"unlimited\", this lookbehind is unbounded.\n\
2218 Only history entries added during this session are considered for removal.\n\
2219 If set to 0, removal of duplicate history entries is disabled.\n\
2220 By default this option is set to 0."),
2221 NULL,
2222 show_history_remove_duplicates,
2223 &sethistlist, &showhistlist);
2225 add_setshow_optional_filename_cmd ("filename", no_class, &history_filename, _("\
2226 Set the filename in which to record the command history."), _("\
2227 Show the filename in which to record the command history."), _("\
2228 (the list of previous commands of which a record is kept)."),
2229 set_history_filename,
2230 show_history_filename,
2231 &sethistlist, &showhistlist);
2233 add_setshow_boolean_cmd ("confirm", class_support, &confirm, _("\
2234 Set whether to confirm potentially dangerous operations."), _("\
2235 Show whether to confirm potentially dangerous operations."), NULL,
2236 NULL,
2237 show_confirm,
2238 &setlist, &showlist);
2240 add_setshow_zinteger_cmd ("annotate", class_obscure, &annotation_level, _("\
2241 Set annotation_level."), _("\
2242 Show annotation_level."), _("\
2243 0 == normal; 1 == fullname (for use when running under emacs)\n\
2244 2 == output annotated suitably for use by programs that control GDB."),
2245 NULL,
2246 show_annotation_level,
2247 &setlist, &showlist);
2249 add_setshow_boolean_cmd ("exec-done-display", class_support,
2250 &exec_done_display_p, _("\
2251 Set notification of completion for asynchronous execution commands."), _("\
2252 Show notification of completion for asynchronous execution commands."), _("\
2253 Use \"on\" to enable the notification, and \"off\" to disable it."),
2254 NULL,
2255 show_exec_done_display_p,
2256 &setlist, &showlist);
2258 add_setshow_filename_cmd ("data-directory", class_maintenance,
2259 &staged_gdb_datadir, _("Set GDB's data directory."),
2260 _("Show GDB's data directory."),
2261 _("\
2262 When set, GDB uses the specified path to search for data files."),
2263 set_gdb_datadir, show_gdb_datadir,
2264 &setlist,
2265 &showlist);
2266 /* Prime the initial value for data-directory. */
2267 staged_gdb_datadir = gdb_datadir;
2269 add_setshow_auto_boolean_cmd ("interactive-mode", class_support,
2270 &interactive_mode, _("\
2271 Set whether GDB's standard input is a terminal."), _("\
2272 Show whether GDB's standard input is a terminal."), _("\
2273 If on, GDB assumes that standard input is a terminal. In practice, it\n\
2274 means that GDB should wait for the user to answer queries associated to\n\
2275 commands entered at the command prompt. If off, GDB assumes that standard\n\
2276 input is not a terminal, and uses the default answer to all queries.\n\
2277 If auto (the default), determine which mode to use based on the standard\n\
2278 input settings."),
2279 NULL,
2280 show_interactive_mode,
2281 &setlist, &showlist);
2283 add_setshow_boolean_cmd ("startup-quietly", class_support,
2284 &startup_quiet, _("\
2285 Set whether GDB should start up quietly."), _("\
2286 Show whether GDB should start up quietly."), _("\
2287 This setting will not affect the current session. Instead this command\n\
2288 should be added to the .gdbearlyinit file in the users home directory to\n\
2289 affect future GDB sessions."),
2290 NULL,
2291 show_startup_quiet,
2292 &setlist, &showlist);
2294 struct internalvar *major_version_var = create_internalvar ("_gdb_major");
2295 struct internalvar *minor_version_var = create_internalvar ("_gdb_minor");
2296 int vmajor = 0, vminor = 0, vrevision = 0;
2297 sscanf (version, "%d.%d.%d", &vmajor, &vminor, &vrevision);
2298 set_internalvar_integer (major_version_var, vmajor);
2299 set_internalvar_integer (minor_version_var, vminor + (vrevision > 0));
2302 /* See top.h. */
2304 void
2305 gdb_init ()
2307 saved_command_line = xstrdup ("");
2308 previous_saved_command_line = xstrdup ("");
2310 /* Run the init function of each source file. */
2312 #ifdef __MSDOS__
2313 /* Make sure we return to the original directory upon exit, come
2314 what may, since the OS doesn't do that for us. */
2315 make_final_cleanup (do_chdir_cleanup, xstrdup (current_directory));
2316 #endif
2318 init_page_info ();
2320 /* Here is where we call all the _initialize_foo routines. */
2321 initialize_all_files ();
2323 /* This creates the current_program_space. Do this after all the
2324 _initialize_foo routines have had a chance to install their
2325 per-sspace data keys. Also do this before
2326 initialize_current_architecture is called, because it accesses
2327 exec_bfd of the current program space. */
2328 initialize_progspace ();
2329 initialize_inferiors ();
2330 initialize_current_architecture ();
2331 init_main (); /* But that omits this file! Do it now. */
2333 initialize_stdin_serial ();
2335 /* Take a snapshot of our tty state before readline/ncurses have had a chance
2336 to alter it. */
2337 set_initial_gdb_ttystate ();
2339 gdb_init_signals ();
2341 /* We need a default language for parsing expressions, so simple
2342 things like "set width 0" won't fail if no language is explicitly
2343 set in a config file or implicitly set by reading an executable
2344 during startup. */
2345 set_language (language_c);
2346 expected_language = current_language; /* Don't warn about the change. */
2348 /* Create $_colorsupport convenience variable. */
2349 init_colorsupport_var ();
2352 void _initialize_top ();
2353 void
2354 _initialize_top ()
2356 /* Determine a default value for the history filename. */
2357 const char *tmpenv = getenv ("GDBHISTFILE");
2358 if (tmpenv != nullptr)
2359 history_filename = tmpenv;
2360 else
2362 /* We include the current directory so that if the user changes
2363 directories the file written will be the same as the one
2364 that was read. */
2365 #ifdef __MSDOS__
2366 /* No leading dots in file names are allowed on MSDOS. */
2367 const char *fname = "_gdb_history";
2368 #else
2369 const char *fname = ".gdb_history";
2370 #endif
2372 history_filename = gdb_abspath (fname);