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