Regenerate AArch64 opcodes files
[binutils-gdb.git] / gdb / maint.c
blobf410cf11e69709e82bd994f206dba36bfab21a78
1 /* Support for GDB maintenance commands.
3 Copyright (C) 1992-2024 Free Software Foundation, Inc.
5 Written by Fred Fish at Cygnus Support.
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "defs.h"
24 #include "arch-utils.h"
25 #include <ctype.h>
26 #include <cmath>
27 #include <signal.h>
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "symtab.h"
31 #include "block.h"
32 #include "gdbtypes.h"
33 #include "demangle.h"
34 #include "gdbcore.h"
35 #include "expression.h"
36 #include "language.h"
37 #include "symfile.h"
38 #include "objfiles.h"
39 #include "value.h"
40 #include "top.h"
41 #include "maint.h"
42 #include "gdbsupport/selftest.h"
43 #include "inferior.h"
44 #include "gdbsupport/thread-pool.h"
46 #include "cli/cli-decode.h"
47 #include "cli/cli-utils.h"
48 #include "cli/cli-setshow.h"
49 #include "cli/cli-cmds.h"
51 static void maintenance_do_deprecate (const char *, int);
53 #ifndef _WIN32
54 static void
55 maintenance_dump_me (const char *args, int from_tty)
57 if (query (_("Should GDB dump core? ")))
59 #ifdef __DJGPP__
60 /* SIGQUIT by default is ignored, so use SIGABRT instead. */
61 signal (SIGABRT, SIG_DFL);
62 kill (getpid (), SIGABRT);
63 #else
64 signal (SIGQUIT, SIG_DFL);
65 kill (getpid (), SIGQUIT);
66 #endif
69 #endif
71 /* Stimulate the internal error mechanism that GDB uses when an
72 internal problem is detected. Allows testing of the mechanism.
73 Also useful when the user wants to drop a core file but not exit
74 GDB. */
76 static void
77 maintenance_internal_error (const char *args, int from_tty)
79 internal_error ("%s", (args == NULL ? "" : args));
82 /* Stimulate the internal error mechanism that GDB uses when an
83 internal problem is detected. Allows testing of the mechanism.
84 Also useful when the user wants to drop a core file but not exit
85 GDB. */
87 static void
88 maintenance_internal_warning (const char *args, int from_tty)
90 internal_warning ("%s", (args == NULL ? "" : args));
93 /* Stimulate the internal error mechanism that GDB uses when an
94 demangler problem is detected. Allows testing of the mechanism. */
96 static void
97 maintenance_demangler_warning (const char *args, int from_tty)
99 demangler_warning (__FILE__, __LINE__, "%s", (args == NULL ? "" : args));
102 /* Old command to demangle a string. The command has been moved to "demangle".
103 It is kept for now because otherwise "mt demangle" gets interpreted as
104 "mt demangler-warning" which artificially creates an internal gdb error. */
106 static void
107 maintenance_demangle (const char *args, int from_tty)
109 gdb_printf (_("This command has been moved to \"demangle\".\n"));
112 static void
113 maintenance_time_display (const char *args, int from_tty)
115 if (args == NULL || *args == '\0')
116 gdb_printf (_("\"maintenance time\" takes a numeric argument.\n"));
117 else
118 set_per_command_time (strtol (args, NULL, 10));
121 static void
122 maintenance_space_display (const char *args, int from_tty)
124 if (args == NULL || *args == '\0')
125 gdb_printf ("\"maintenance space\" takes a numeric argument.\n");
126 else
127 set_per_command_space (strtol (args, NULL, 10));
130 /* Mini tokenizing lexer for 'maint info sections' command. */
132 static bool
133 match_substring (const char *string, const char *substr)
135 int substr_len = strlen (substr);
136 const char *tok;
138 while ((tok = strstr (string, substr)) != NULL)
140 /* Got a partial match. Is it a whole word? */
141 if (tok == string
142 || tok[-1] == ' '
143 || tok[-1] == '\t')
145 /* Token is delimited at the front... */
146 if (tok[substr_len] == ' '
147 || tok[substr_len] == '\t'
148 || tok[substr_len] == '\0')
150 /* Token is delimited at the rear. Got a whole-word match. */
151 return true;
154 /* Token didn't match as a whole word. Advance and try again. */
155 string = tok + 1;
157 return false;
160 /* Structure holding information about a single bfd section flag. This is
161 used by the "maintenance info sections" command to print the sections,
162 and for filtering which sections are printed. */
164 struct single_bfd_flag_info
166 /* The name of the section. This is what is printed for the flag, and
167 what the user enter in order to filter by flag. */
168 const char *name;
170 /* The bfd defined SEC_* flagword value for this flag. */
171 flagword value;
174 /* Vector of all the known bfd flags. */
176 static const single_bfd_flag_info bfd_flag_info[] =
178 { "ALLOC", SEC_ALLOC },
179 { "LOAD", SEC_LOAD },
180 { "RELOC", SEC_RELOC },
181 { "READONLY", SEC_READONLY },
182 { "CODE", SEC_CODE },
183 { "DATA", SEC_DATA },
184 { "ROM", SEC_ROM },
185 { "CONSTRUCTOR", SEC_CONSTRUCTOR },
186 { "HAS_CONTENTS", SEC_HAS_CONTENTS },
187 { "NEVER_LOAD", SEC_NEVER_LOAD },
188 { "COFF_SHARED_LIBRARY", SEC_COFF_SHARED_LIBRARY },
189 { "IS_COMMON", SEC_IS_COMMON }
192 /* For each flag in the global BFD_FLAG_INFO list, if FLAGS has a flag's
193 flagword value set, and STRING contains the flag's name then return
194 true, otherwise return false. STRING is never nullptr. */
196 static bool
197 match_bfd_flags (const char *string, flagword flags)
199 gdb_assert (string != nullptr);
201 for (const auto &f : bfd_flag_info)
203 if (flags & f.value
204 && match_substring (string, f.name))
205 return true;
208 return false;
211 /* Print the names of all flags set in FLAGS. The names are taken from the
212 BFD_FLAG_INFO global. */
214 static void
215 print_bfd_flags (flagword flags)
217 for (const auto &f : bfd_flag_info)
219 if (flags & f.value)
220 gdb_printf (" %s", f.name);
224 static void
225 maint_print_section_info (const char *name, flagword flags,
226 CORE_ADDR addr, CORE_ADDR endaddr,
227 unsigned long filepos, int addr_size)
229 gdb_printf (" %s", hex_string_custom (addr, addr_size));
230 gdb_printf ("->%s", hex_string_custom (endaddr, addr_size));
231 gdb_printf (" at %s",
232 hex_string_custom ((unsigned long) filepos, 8));
233 gdb_printf (": %s", name);
234 print_bfd_flags (flags);
235 gdb_printf ("\n");
238 /* Return the number of digits required to display COUNT in decimal.
240 Used when pretty printing index numbers to ensure all of the indexes line
241 up.*/
243 static int
244 index_digits (int count)
246 return ((int) log10 ((float) count)) + 1;
249 /* Helper function to pretty-print the section index of ASECT from ABFD.
250 The INDEX_DIGITS is the number of digits in the largest index that will
251 be printed, and is used to pretty-print the resulting string. */
253 static void
254 print_section_index (bfd *abfd,
255 asection *asect,
256 int index_digits)
258 std::string result
259 = string_printf (" [%d] ", gdb_bfd_section_index (abfd, asect));
260 /* The '+ 4' for the leading and trailing characters. */
261 gdb_printf ("%-*s", (index_digits + 4), result.c_str ());
264 /* Print information about ASECT from ABFD. The section will be printed using
265 the VMA's from the bfd, which will not be the relocated addresses for bfds
266 that should be relocated. The information must be printed with the same
267 layout as PRINT_OBJFILE_SECTION_INFO below.
269 ARG is the argument string passed by the user to the top level maintenance
270 info sections command. Used for filtering which sections are printed. */
272 static void
273 print_bfd_section_info (bfd *abfd, asection *asect, const char *arg,
274 int index_digits)
276 flagword flags = bfd_section_flags (asect);
277 const char *name = bfd_section_name (asect);
279 if (arg == NULL || *arg == '\0'
280 || match_substring (arg, name)
281 || match_bfd_flags (arg, flags))
283 struct gdbarch *gdbarch = gdbarch_from_bfd (abfd);
284 int addr_size = gdbarch_addr_bit (gdbarch) / 8;
285 CORE_ADDR addr, endaddr;
287 addr = bfd_section_vma (asect);
288 endaddr = addr + bfd_section_size (asect);
289 print_section_index (abfd, asect, index_digits);
290 maint_print_section_info (name, flags, addr, endaddr,
291 asect->filepos, addr_size);
295 /* Print information about ASECT which is GDB's wrapper around a section
296 from ABFD. The information must be printed with the same layout as
297 PRINT_BFD_SECTION_INFO above. PRINT_DATA holds information used to
298 filter which sections are printed, and for formatting the output.
300 ARG is the argument string passed by the user to the top level maintenance
301 info sections command. Used for filtering which sections are printed. */
303 static void
304 print_objfile_section_info (bfd *abfd, struct obj_section *asect,
305 const char *arg, int index_digits)
307 flagword flags = bfd_section_flags (asect->the_bfd_section);
308 const char *name = bfd_section_name (asect->the_bfd_section);
310 if (arg == NULL || *arg == '\0'
311 || match_substring (arg, name)
312 || match_bfd_flags (arg, flags))
314 struct gdbarch *gdbarch = gdbarch_from_bfd (abfd);
315 int addr_size = gdbarch_addr_bit (gdbarch) / 8;
317 print_section_index (abfd, asect->the_bfd_section, index_digits);
318 maint_print_section_info (name, flags,
319 asect->addr (), asect->endaddr (),
320 asect->the_bfd_section->filepos,
321 addr_size);
325 /* Find an obj_section, GDB's wrapper around a bfd section for ASECTION
326 from ABFD. It might be that no such wrapper exists (for example debug
327 sections don't have such wrappers) in which case nullptr is returned. */
329 obj_section *
330 maint_obj_section_from_bfd_section (bfd *abfd,
331 asection *asection,
332 objfile *ofile)
334 if (ofile->sections_start == nullptr)
335 return nullptr;
337 obj_section *osect
338 = &ofile->sections_start[gdb_bfd_section_index (abfd, asection)];
340 if (osect >= ofile->sections_end)
341 return nullptr;
343 return osect;
346 /* Print information about all sections from ABFD, which is the bfd
347 corresponding to OBJFILE. It is fine for OBJFILE to be nullptr, but
348 ABFD must never be nullptr. If OBJFILE is provided then the sections of
349 ABFD will (potentially) be displayed relocated (i.e. the object file was
350 loaded with add-symbol-file and custom offsets were provided).
352 HEADER is a string that describes this file, e.g. 'Exec file: ', or
353 'Core file: '.
355 ARG is a string used for filtering which sections are printed, this can
356 be nullptr for no filtering. See the top level 'maint info sections'
357 for a fuller description of the possible filtering strings. */
359 static void
360 maint_print_all_sections (const char *header, bfd *abfd, objfile *objfile,
361 const char *arg)
363 gdb_puts (header);
364 gdb_stdout->wrap_here (8);
365 gdb_printf ("`%s', ", bfd_get_filename (abfd));
366 gdb_stdout->wrap_here (8);
367 gdb_printf (_("file type %s.\n"), bfd_get_target (abfd));
369 int section_count = gdb_bfd_count_sections (abfd);
370 int digits = index_digits (section_count);
372 for (asection *sect : gdb_bfd_sections (abfd))
374 obj_section *osect = nullptr;
376 if (objfile != nullptr)
378 gdb_assert (objfile->sections_start != nullptr);
379 osect
380 = maint_obj_section_from_bfd_section (abfd, sect, objfile);
381 if (osect->the_bfd_section == nullptr)
382 osect = nullptr;
385 if (osect == nullptr)
386 print_bfd_section_info (abfd, sect, arg, digits);
387 else
388 print_objfile_section_info (abfd, osect, arg, digits);
392 /* The options for the "maintenance info sections" command. */
394 struct maint_info_sections_opts
396 /* For "-all-objects". */
397 bool all_objects = false;
400 static const gdb::option::option_def maint_info_sections_option_defs[] = {
402 gdb::option::flag_option_def<maint_info_sections_opts> {
403 "all-objects",
404 [] (maint_info_sections_opts *opts) { return &opts->all_objects; },
405 N_("Display information from all loaded object files."),
409 /* Create an option_def_group for the "maintenance info sections" options,
410 with CC_OPTS as context. */
412 static inline gdb::option::option_def_group
413 make_maint_info_sections_options_def_group (maint_info_sections_opts *cc_opts)
415 return {{maint_info_sections_option_defs}, cc_opts};
418 /* Completion for the "maintenance info sections" command. */
420 static void
421 maint_info_sections_completer (struct cmd_list_element *cmd,
422 completion_tracker &tracker,
423 const char *text, const char * /* word */)
425 /* Complete command options. */
426 const auto group = make_maint_info_sections_options_def_group (nullptr);
427 if (gdb::option::complete_options
428 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group))
429 return;
430 const char *word = advance_to_expression_complete_word_point (tracker, text);
432 /* Offer completion for section flags, but not section names. This is
433 only a maintenance command after all, no point going over the top. */
434 std::vector<const char *> flags;
435 for (const auto &f : bfd_flag_info)
436 flags.push_back (f.name);
437 flags.push_back (nullptr);
438 complete_on_enum (tracker, flags.data (), text, word);
441 /* Implement the "maintenance info sections" command. */
443 static void
444 maintenance_info_sections (const char *arg, int from_tty)
446 /* Check if the "-all-objects" flag was passed. */
447 maint_info_sections_opts opts;
448 const auto group = make_maint_info_sections_options_def_group (&opts);
449 gdb::option::process_options
450 (&arg, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, group);
452 for (objfile *ofile : current_program_space->objfiles ())
454 if (ofile->obfd == current_program_space->exec_bfd ())
455 maint_print_all_sections (_("Exec file: "), ofile->obfd.get (),
456 ofile, arg);
457 else if (opts.all_objects)
458 maint_print_all_sections (_("Object file: "), ofile->obfd.get (),
459 ofile, arg);
462 if (current_program_space->core_bfd () != nullptr)
463 maint_print_all_sections (_("Core file: "),
464 current_program_space->core_bfd (), nullptr, arg);
467 /* Implement the "maintenance info target-sections" command. */
469 static void
470 maintenance_info_target_sections (const char *arg, int from_tty)
472 bfd *abfd = nullptr;
473 int digits = 0;
474 const std::vector<target_section> *table
475 = target_get_section_table (current_inferior ()->top_target ());
476 if (table == nullptr)
477 return;
479 for (const target_section &sec : *table)
481 if (abfd == nullptr || sec.the_bfd_section->owner != abfd)
483 abfd = sec.the_bfd_section->owner;
484 digits = std::max (index_digits (gdb_bfd_count_sections (abfd)),
485 digits);
489 struct gdbarch *gdbarch = nullptr;
490 int addr_size = 0;
491 abfd = nullptr;
492 for (const target_section &sec : *table)
494 if (sec.the_bfd_section->owner != abfd)
496 abfd = sec.the_bfd_section->owner;
497 gdbarch = gdbarch_from_bfd (abfd);
498 addr_size = gdbarch_addr_bit (gdbarch) / 8;
500 gdb_printf (_("From '%s', file type %s:\n"),
501 bfd_get_filename (abfd), bfd_get_target (abfd));
503 print_bfd_section_info (abfd,
504 sec.the_bfd_section,
505 nullptr,
506 digits);
507 /* The magic '8 + digits' here ensures that the 'Start' is aligned
508 with the output of print_bfd_section_info. */
509 gdb_printf ("%*sStart: %s, End: %s, Owner token: %p\n",
510 (8 + digits), "",
511 hex_string_custom (sec.addr, addr_size),
512 hex_string_custom (sec.endaddr, addr_size),
513 sec.owner.v ());
517 static void
518 maintenance_print_statistics (const char *args, int from_tty)
520 print_objfile_statistics ();
523 static void
524 maintenance_print_architecture (const char *args, int from_tty)
526 struct gdbarch *gdbarch = get_current_arch ();
528 if (args == NULL)
529 gdbarch_dump (gdbarch, gdb_stdout);
530 else
532 stdio_file file;
534 if (!file.open (args, "w"))
535 perror_with_name (_("maintenance print architecture"));
536 gdbarch_dump (gdbarch, &file);
540 /* The "maintenance translate-address" command converts a section and address
541 to a symbol. This can be called in two ways:
542 maintenance translate-address <secname> <addr>
543 or maintenance translate-address <addr>. */
545 static void
546 maintenance_translate_address (const char *arg, int from_tty)
548 CORE_ADDR address;
549 struct obj_section *sect;
550 const char *p;
551 struct bound_minimal_symbol sym;
553 if (arg == NULL || *arg == 0)
554 error (_("requires argument (address or section + address)"));
556 sect = NULL;
557 p = arg;
559 if (!isdigit (*p))
560 { /* See if we have a valid section name. */
561 while (*p && !isspace (*p)) /* Find end of section name. */
562 p++;
563 if (*p == '\000') /* End of command? */
564 error (_("Need to specify section name and address"));
566 int arg_len = p - arg;
567 p = skip_spaces (p + 1);
569 for (objfile *objfile : current_program_space->objfiles ())
570 for (obj_section *iter : objfile->sections ())
572 if (strncmp (iter->the_bfd_section->name, arg, arg_len) == 0)
573 goto found;
576 error (_("Unknown section %s."), arg);
577 found: ;
580 address = parse_and_eval_address (p);
582 if (sect)
583 sym = lookup_minimal_symbol_by_pc_section (address, sect);
584 else
585 sym = lookup_minimal_symbol_by_pc (address);
587 if (sym.minsym)
589 const char *symbol_name = sym.minsym->print_name ();
590 const char *symbol_offset
591 = pulongest (address - sym.value_address ());
593 sect = sym.obj_section ();
594 if (sect != NULL)
596 const char *section_name;
597 const char *obj_name;
599 gdb_assert (sect->the_bfd_section && sect->the_bfd_section->name);
600 section_name = sect->the_bfd_section->name;
602 gdb_assert (sect->objfile && objfile_name (sect->objfile));
603 obj_name = objfile_name (sect->objfile);
605 if (current_program_space->multi_objfile_p ())
606 gdb_printf (_("%s + %s in section %s of %s\n"),
607 symbol_name, symbol_offset,
608 section_name, obj_name);
609 else
610 gdb_printf (_("%s + %s in section %s\n"),
611 symbol_name, symbol_offset, section_name);
613 else
614 gdb_printf (_("%s + %s\n"), symbol_name, symbol_offset);
616 else if (sect)
617 gdb_printf (_("no symbol at %s:%s\n"),
618 sect->the_bfd_section->name, hex_string (address));
619 else
620 gdb_printf (_("no symbol at %s\n"), hex_string (address));
622 return;
626 /* When a command is deprecated the user will be warned the first time
627 the command is used. If possible, a replacement will be
628 offered. */
630 static void
631 maintenance_deprecate (const char *args, int from_tty)
633 if (args == NULL || *args == '\0')
635 gdb_printf (_("\"maintenance deprecate\" takes an argument,\n\
636 the command you want to deprecate, and optionally the replacement command\n\
637 enclosed in quotes.\n"));
640 maintenance_do_deprecate (args, 1);
644 static void
645 maintenance_undeprecate (const char *args, int from_tty)
647 if (args == NULL || *args == '\0')
649 gdb_printf (_("\"maintenance undeprecate\" takes an argument, \n\
650 the command you want to undeprecate.\n"));
653 maintenance_do_deprecate (args, 0);
656 /* You really shouldn't be using this. It is just for the testsuite.
657 Rather, you should use deprecate_cmd() when the command is created
658 in _initialize_blah().
660 This function deprecates a command and optionally assigns it a
661 replacement. */
663 static void
664 maintenance_do_deprecate (const char *text, int deprecate)
666 struct cmd_list_element *alias = NULL;
667 struct cmd_list_element *prefix_cmd = NULL;
668 struct cmd_list_element *cmd = NULL;
670 const char *start_ptr = NULL;
671 const char *end_ptr = NULL;
672 int len;
673 char *replacement = NULL;
675 if (text == NULL)
676 return;
678 if (!lookup_cmd_composition (text, &alias, &prefix_cmd, &cmd))
680 gdb_printf (_("Can't find command '%s' to deprecate.\n"), text);
681 return;
684 if (deprecate)
686 /* Look for a replacement command. */
687 start_ptr = strchr (text, '\"');
688 if (start_ptr != NULL)
690 start_ptr++;
691 end_ptr = strrchr (start_ptr, '\"');
692 if (end_ptr != NULL)
694 len = end_ptr - start_ptr;
695 replacement = savestring (start_ptr, len);
700 if (!start_ptr || !end_ptr)
701 replacement = NULL;
704 /* If they used an alias, we only want to deprecate the alias.
706 Note the MALLOCED_REPLACEMENT test. If the command's replacement
707 string was allocated at compile time we don't want to free the
708 memory. */
709 if (alias)
711 if (alias->malloced_replacement)
712 xfree ((char *) alias->replacement);
714 if (deprecate)
716 alias->deprecated_warn_user = 1;
717 alias->cmd_deprecated = 1;
719 else
721 alias->deprecated_warn_user = 0;
722 alias->cmd_deprecated = 0;
724 alias->replacement = replacement;
725 alias->malloced_replacement = 1;
726 return;
728 else if (cmd)
730 if (cmd->malloced_replacement)
731 xfree ((char *) cmd->replacement);
733 if (deprecate)
735 cmd->deprecated_warn_user = 1;
736 cmd->cmd_deprecated = 1;
738 else
740 cmd->deprecated_warn_user = 0;
741 cmd->cmd_deprecated = 0;
743 cmd->replacement = replacement;
744 cmd->malloced_replacement = 1;
745 return;
747 xfree (replacement);
750 /* Maintenance set/show framework. */
752 struct cmd_list_element *maintenance_set_cmdlist;
753 struct cmd_list_element *maintenance_show_cmdlist;
755 /* "maintenance with" command. */
757 static void
758 maintenance_with_cmd (const char *args, int from_tty)
760 with_command_1 ("maintenance set ", maintenance_set_cmdlist, args, from_tty);
763 /* "maintenance with" command completer. */
765 static void
766 maintenance_with_cmd_completer (struct cmd_list_element *ignore,
767 completion_tracker &tracker,
768 const char *text, const char * /*word*/)
770 with_command_completer_1 ("maintenance set ", tracker, text);
773 /* Profiling support. */
775 static bool maintenance_profile_p;
776 static void
777 show_maintenance_profile_p (struct ui_file *file, int from_tty,
778 struct cmd_list_element *c, const char *value)
780 gdb_printf (file, _("Internal profiling is %s.\n"), value);
783 #ifdef HAVE__ETEXT
784 extern char _etext;
785 #define TEXTEND &_etext
786 #elif defined (HAVE_ETEXT)
787 extern char etext;
788 #define TEXTEND &etext
789 #endif
791 #if defined (HAVE_MONSTARTUP) && defined (HAVE__MCLEANUP) && defined (TEXTEND)
793 static int profiling_state;
795 extern "C" void _mcleanup (void);
797 static void
798 mcleanup_wrapper (void)
800 if (profiling_state)
801 _mcleanup ();
804 extern "C" void monstartup (unsigned long, unsigned long);
805 extern int main (int, char **);
807 static void
808 maintenance_set_profile_cmd (const char *args, int from_tty,
809 struct cmd_list_element *c)
811 if (maintenance_profile_p == profiling_state)
812 return;
814 profiling_state = maintenance_profile_p;
816 if (maintenance_profile_p)
818 static int profiling_initialized;
820 if (!profiling_initialized)
822 atexit (mcleanup_wrapper);
823 profiling_initialized = 1;
826 /* "main" is now always the first function in the text segment, so use
827 its address for monstartup. */
828 monstartup ((unsigned long) &main, (unsigned long) TEXTEND);
830 else
832 extern void _mcleanup (void);
834 _mcleanup ();
837 #else
838 static void
839 maintenance_set_profile_cmd (const char *args, int from_tty,
840 struct cmd_list_element *c)
842 error (_("Profiling support is not available on this system."));
844 #endif
846 static int n_worker_threads = -1;
848 /* See maint.h. */
850 void
851 update_thread_pool_size ()
853 #if CXX_STD_THREAD
854 int n_threads = n_worker_threads;
856 if (n_threads < 0)
858 const int hardware_threads = std::thread::hardware_concurrency ();
859 /* Testing in PR gdb/29959 indicates that parallel efficiency drops
860 between n_threads=5 to 8. Therefore, use no more than 8 threads
861 to avoid an excessive number of threads in the pool on many-core
862 systems. */
863 const int max_thread_count = 8;
864 n_threads = std::min (hardware_threads, max_thread_count);
867 gdb::thread_pool::g_thread_pool->set_thread_count (n_threads);
868 #endif
871 static void
872 maintenance_set_worker_threads (const char *args, int from_tty,
873 struct cmd_list_element *c)
875 update_thread_pool_size ();
878 static void
879 maintenance_show_worker_threads (struct ui_file *file, int from_tty,
880 struct cmd_list_element *c,
881 const char *value)
883 #if CXX_STD_THREAD
884 if (n_worker_threads == -1)
886 gdb_printf (file, _("The number of worker threads GDB "
887 "can use is the default (currently %zu).\n"),
888 gdb::thread_pool::g_thread_pool->thread_count ());
889 return;
891 #endif
893 int report_threads = 0;
894 #if CXX_STD_THREAD
895 report_threads = n_worker_threads;
896 #endif
897 gdb_printf (file, _("The number of worker threads GDB "
898 "can use is %d.\n"),
899 report_threads);
903 /* If true, display time usage both at startup and for each command. */
905 static bool per_command_time;
907 /* If true, display space usage both at startup and for each command. */
909 static bool per_command_space;
911 /* If true, display basic symtab stats for each command. */
913 static bool per_command_symtab;
915 /* mt per-command commands. */
917 static struct cmd_list_element *per_command_setlist;
918 static struct cmd_list_element *per_command_showlist;
920 /* Set whether to display time statistics to NEW_VALUE
921 (non-zero means true). */
923 void
924 set_per_command_time (int new_value)
926 per_command_time = new_value;
929 /* Set whether to display space statistics to NEW_VALUE
930 (non-zero means true). */
932 void
933 set_per_command_space (int new_value)
935 per_command_space = new_value;
938 /* Count the number of symtabs and blocks. */
940 static void
941 count_symtabs_and_blocks (int *nr_symtabs_ptr, int *nr_compunit_symtabs_ptr,
942 int *nr_blocks_ptr)
944 int nr_symtabs = 0;
945 int nr_compunit_symtabs = 0;
946 int nr_blocks = 0;
948 /* When collecting statistics during startup, this is called before
949 pretty much anything in gdb has been initialized, and thus
950 current_program_space may be NULL. */
951 if (current_program_space != NULL)
953 for (objfile *o : current_program_space->objfiles ())
955 for (compunit_symtab *cu : o->compunits ())
957 ++nr_compunit_symtabs;
958 nr_blocks += cu->blockvector ()->num_blocks ();
959 nr_symtabs += std::distance (cu->filetabs ().begin (),
960 cu->filetabs ().end ());
965 *nr_symtabs_ptr = nr_symtabs;
966 *nr_compunit_symtabs_ptr = nr_compunit_symtabs;
967 *nr_blocks_ptr = nr_blocks;
970 /* As indicated by display_time and display_space, report GDB's
971 elapsed time and space usage from the base time and space recorded
972 in this object. */
974 scoped_command_stats::~scoped_command_stats ()
976 /* Early exit if we're not reporting any stats. It can be expensive to
977 compute the pre-command values so don't collect them at all if we're
978 not reporting stats. Alas this doesn't work in the startup case because
979 we don't know yet whether we will be reporting the stats. For the
980 startup case collect the data anyway (it should be cheap at this point),
981 and leave it to the reporter to decide whether to print them. */
982 if (m_msg_type
983 && !per_command_time
984 && !per_command_space
985 && !per_command_symtab)
986 return;
988 if (m_time_enabled && per_command_time)
990 print_time (_("command finished"));
992 using namespace std::chrono;
994 run_time_clock::duration cmd_time
995 = run_time_clock::now () - m_start_cpu_time;
997 steady_clock::duration wall_time
998 = steady_clock::now () - m_start_wall_time;
999 /* Subtract time spend in prompt_for_continue from walltime. */
1000 wall_time -= get_prompt_for_continue_wait_time ();
1002 gdb_printf (gdb_stdlog,
1003 !m_msg_type
1004 ? _("Startup time: %.6f (cpu), %.6f (wall)\n")
1005 : _("Command execution time: %.6f (cpu), %.6f (wall)\n"),
1006 duration<double> (cmd_time).count (),
1007 duration<double> (wall_time).count ());
1010 if (m_space_enabled && per_command_space)
1012 #ifdef HAVE_USEFUL_SBRK
1013 char *lim = (char *) sbrk (0);
1015 long space_now = lim - lim_at_start;
1016 long space_diff = space_now - m_start_space;
1018 gdb_printf (gdb_stdlog,
1019 !m_msg_type
1020 ? _("Space used: %ld (%s%ld during startup)\n")
1021 : _("Space used: %ld (%s%ld for this command)\n"),
1022 space_now,
1023 (space_diff >= 0 ? "+" : ""),
1024 space_diff);
1025 #endif
1028 if (m_symtab_enabled && per_command_symtab)
1030 int nr_symtabs, nr_compunit_symtabs, nr_blocks;
1032 count_symtabs_and_blocks (&nr_symtabs, &nr_compunit_symtabs, &nr_blocks);
1033 gdb_printf (gdb_stdlog,
1034 _("#symtabs: %d (+%d),"
1035 " #compunits: %d (+%d),"
1036 " #blocks: %d (+%d)\n"),
1037 nr_symtabs,
1038 nr_symtabs - m_start_nr_symtabs,
1039 nr_compunit_symtabs,
1040 (nr_compunit_symtabs
1041 - m_start_nr_compunit_symtabs),
1042 nr_blocks,
1043 nr_blocks - m_start_nr_blocks);
1047 scoped_command_stats::scoped_command_stats (bool msg_type)
1048 : m_msg_type (msg_type)
1050 if (!m_msg_type || per_command_space)
1052 #ifdef HAVE_USEFUL_SBRK
1053 char *lim = (char *) sbrk (0);
1054 m_start_space = lim - lim_at_start;
1055 m_space_enabled = true;
1056 #endif
1058 else
1059 m_space_enabled = false;
1061 if (msg_type == 0 || per_command_time)
1063 using namespace std::chrono;
1065 m_start_cpu_time = run_time_clock::now ();
1066 m_start_wall_time = steady_clock::now ();
1067 m_time_enabled = true;
1069 if (per_command_time)
1070 print_time (_("command started"));
1072 else
1073 m_time_enabled = false;
1075 if (msg_type == 0 || per_command_symtab)
1077 int nr_symtabs, nr_compunit_symtabs, nr_blocks;
1079 count_symtabs_and_blocks (&nr_symtabs, &nr_compunit_symtabs, &nr_blocks);
1080 m_start_nr_symtabs = nr_symtabs;
1081 m_start_nr_compunit_symtabs = nr_compunit_symtabs;
1082 m_start_nr_blocks = nr_blocks;
1083 m_symtab_enabled = true;
1085 else
1086 m_symtab_enabled = false;
1088 /* Initialize timer to keep track of how long we waited for the user. */
1089 reset_prompt_for_continue_wait_time ();
1092 /* See maint.h. */
1094 void
1095 scoped_command_stats::print_time (const char *msg)
1097 using namespace std::chrono;
1099 auto now = system_clock::now ();
1100 auto ticks = now.time_since_epoch ().count () / (1000 * 1000);
1101 auto millis = ticks % 1000;
1103 std::time_t as_time = system_clock::to_time_t (now);
1104 struct tm tm;
1105 localtime_r (&as_time, &tm);
1107 char out[100];
1108 strftime (out, sizeof (out), "%F %H:%M:%S", &tm);
1110 gdb_printf (gdb_stdlog, "%s.%03d - %s\n", out, (int) millis, msg);
1113 /* Handle unknown "mt set per-command" arguments.
1114 In this case have "mt set per-command on|off" affect every setting. */
1116 static void
1117 set_per_command_cmd (const char *args, int from_tty)
1119 struct cmd_list_element *list;
1120 int val;
1122 val = parse_cli_boolean_value (args);
1123 if (val < 0)
1124 error (_("Bad value for 'mt set per-command no'."));
1126 for (list = per_command_setlist; list != NULL; list = list->next)
1127 if (list->var->type () == var_boolean)
1129 gdb_assert (list->type == set_cmd);
1130 do_set_command (args, from_tty, list);
1134 /* Options affecting the "maintenance selftest" command. */
1136 struct maintenance_selftest_options
1138 bool verbose = false;
1139 } user_maintenance_selftest_options;
1141 static const gdb::option::option_def maintenance_selftest_option_defs[] = {
1142 gdb::option::boolean_option_def<maintenance_selftest_options> {
1143 "verbose",
1144 [] (maintenance_selftest_options *opt) { return &opt->verbose; },
1145 nullptr,
1146 N_("Set whether selftests run in verbose mode."),
1147 N_("Show whether selftests run in verbose mode."),
1148 N_("\
1149 When on, selftests may print verbose information."),
1153 /* Make option groups for the "maintenance selftest" command. */
1155 static std::array<gdb::option::option_def_group, 1>
1156 make_maintenance_selftest_option_group (maintenance_selftest_options *opts)
1158 return {{
1159 {{maintenance_selftest_option_defs}, opts},
1163 /* The "maintenance selftest" command. */
1165 static void
1166 maintenance_selftest (const char *args, int from_tty)
1168 #if GDB_SELF_TEST
1169 maintenance_selftest_options opts = user_maintenance_selftest_options;
1170 auto grp = make_maintenance_selftest_option_group (&opts);
1171 gdb::option::process_options
1172 (&args, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp);
1173 const gdb_argv argv (args);
1174 selftests::run_tests (argv.as_array_view (), opts.verbose);
1175 #else
1176 gdb_printf (_("\
1177 Selftests have been disabled for this build.\n"));
1178 #endif
1181 /* Completer for the "maintenance selftest" command. */
1183 static void
1184 maintenance_selftest_completer (cmd_list_element *cmd,
1185 completion_tracker &tracker,
1186 const char *text,
1187 const char *word)
1189 auto grp = make_maintenance_selftest_option_group (nullptr);
1191 if (gdb::option::complete_options
1192 (tracker, &text, gdb::option::PROCESS_OPTIONS_UNKNOWN_IS_ERROR, grp))
1193 return;
1195 #if GDB_SELF_TEST
1196 for (const auto &test : selftests::all_selftests ())
1198 if (startswith (test.name.c_str (), text))
1199 tracker.add_completion (make_unique_xstrdup (test.name.c_str ()));
1201 #endif
1204 static void
1205 maintenance_info_selftests (const char *arg, int from_tty)
1207 #if GDB_SELF_TEST
1208 gdb_printf ("Registered selftests:\n");
1209 for (const auto &test : selftests::all_selftests ())
1210 gdb_printf (" - %s\n", test.name.c_str ());
1211 #else
1212 gdb_printf (_("\
1213 Selftests have been disabled for this build.\n"));
1214 #endif
1218 void _initialize_maint_cmds ();
1219 void
1220 _initialize_maint_cmds ()
1222 struct cmd_list_element *cmd;
1224 cmd_list_element *maintenance_cmd
1225 = add_basic_prefix_cmd ("maintenance", class_maintenance, _("\
1226 Commands for use by GDB maintainers.\n\
1227 Includes commands to dump specific internal GDB structures in\n\
1228 a human readable form, to cause GDB to deliberately dump core, etc."),
1229 &maintenancelist, 0,
1230 &cmdlist);
1232 add_com_alias ("mt", maintenance_cmd, class_maintenance, 1);
1234 cmd_list_element *maintenance_info_cmd
1235 = add_basic_prefix_cmd ("info", class_maintenance, _("\
1236 Commands for showing internal info about the program being debugged."),
1237 &maintenanceinfolist, 0,
1238 &maintenancelist);
1239 add_alias_cmd ("i", maintenance_info_cmd, class_maintenance, 1,
1240 &maintenancelist);
1242 const auto opts = make_maint_info_sections_options_def_group (nullptr);
1243 static std::string maint_info_sections_command_help
1244 = gdb::option::build_help (_("\
1245 List the BFD sections of the exec and core files.\n\
1247 Usage: maintenance info sections [-all-objects] [FILTERS]\n\
1249 FILTERS is a list of words, each word is either:\n\
1250 + A section name - any section with this name will be printed, or\n\
1251 + A section flag - any section with this flag will be printed. The\n\
1252 known flags are:\n\
1253 ALLOC LOAD RELOC READONLY CODE DATA ROM CONSTRUCTOR\n\
1254 HAS_CONTENTS NEVER_LOAD COFF_SHARED_LIBRARY IS_COMMON\n\
1256 Sections matching any of the FILTERS will be listed (no FILTERS implies\n\
1257 all sections should be printed).\n\
1259 Options:\n\
1260 %OPTIONS%"), opts);
1261 cmd = add_cmd ("sections", class_maintenance, maintenance_info_sections,
1262 maint_info_sections_command_help.c_str (),
1263 &maintenanceinfolist);
1264 set_cmd_completer_handle_brkchars (cmd, maint_info_sections_completer);
1266 add_cmd ("target-sections", class_maintenance,
1267 maintenance_info_target_sections, _("\
1268 List GDB's internal section table.\n\
1270 Print the current targets section list. This is a sub-set of all\n\
1271 sections, from all objects currently loaded. Usually the ALLOC\n\
1272 sections."),
1273 &maintenanceinfolist);
1275 add_basic_prefix_cmd ("print", class_maintenance,
1276 _("Maintenance command for printing GDB internal state."),
1277 &maintenanceprintlist, 0,
1278 &maintenancelist);
1280 add_basic_prefix_cmd ("flush", class_maintenance,
1281 _("Maintenance command for flushing GDB internal caches."),
1282 &maintenanceflushlist, 0,
1283 &maintenancelist);
1285 add_basic_prefix_cmd ("set", class_maintenance, _("\
1286 Set GDB internal variables used by the GDB maintainer.\n\
1287 Configure variables internal to GDB that aid in GDB's maintenance"),
1288 &maintenance_set_cmdlist,
1289 0/*allow-unknown*/,
1290 &maintenancelist);
1292 add_show_prefix_cmd ("show", class_maintenance, _("\
1293 Show GDB internal variables used by the GDB maintainer.\n\
1294 Configure variables internal to GDB that aid in GDB's maintenance"),
1295 &maintenance_show_cmdlist,
1296 0/*allow-unknown*/,
1297 &maintenancelist);
1299 cmd = add_cmd ("with", class_maintenance, maintenance_with_cmd, _("\
1300 Like \"with\", but works with \"maintenance set\" variables.\n\
1301 Usage: maintenance with SETTING [VALUE] [-- COMMAND]\n\
1302 With no COMMAND, repeats the last executed command.\n\
1303 SETTING is any setting you can change with the \"maintenance set\"\n\
1304 subcommands."),
1305 &maintenancelist);
1306 set_cmd_completer_handle_brkchars (cmd, maintenance_with_cmd_completer);
1308 #ifndef _WIN32
1309 add_cmd ("dump-me", class_maintenance, maintenance_dump_me, _("\
1310 Get fatal error; make debugger dump its core.\n\
1311 GDB sets its handling of SIGQUIT back to SIG_DFL and then sends\n\
1312 itself a SIGQUIT signal."),
1313 &maintenancelist);
1314 #endif
1316 add_cmd ("internal-error", class_maintenance,
1317 maintenance_internal_error, _("\
1318 Give GDB an internal error.\n\
1319 Cause GDB to behave as if an internal error was detected."),
1320 &maintenancelist);
1322 add_cmd ("internal-warning", class_maintenance,
1323 maintenance_internal_warning, _("\
1324 Give GDB an internal warning.\n\
1325 Cause GDB to behave as if an internal warning was reported."),
1326 &maintenancelist);
1328 add_cmd ("demangler-warning", class_maintenance,
1329 maintenance_demangler_warning, _("\
1330 Give GDB a demangler warning.\n\
1331 Cause GDB to behave as if a demangler warning was reported."),
1332 &maintenancelist);
1334 cmd = add_cmd ("demangle", class_maintenance, maintenance_demangle, _("\
1335 This command has been moved to \"demangle\"."),
1336 &maintenancelist);
1337 deprecate_cmd (cmd, "demangle");
1339 add_prefix_cmd ("per-command", class_maintenance, set_per_command_cmd, _("\
1340 Per-command statistics settings."),
1341 &per_command_setlist,
1342 1/*allow-unknown*/, &maintenance_set_cmdlist);
1344 add_show_prefix_cmd ("per-command", class_maintenance, _("\
1345 Show per-command statistics settings."),
1346 &per_command_showlist,
1347 0/*allow-unknown*/, &maintenance_show_cmdlist);
1349 add_setshow_boolean_cmd ("time", class_maintenance,
1350 &per_command_time, _("\
1351 Set whether to display per-command execution time."), _("\
1352 Show whether to display per-command execution time."),
1353 _("\
1354 If enabled, the execution time for each command will be\n\
1355 displayed following the command's output."),
1356 NULL, NULL,
1357 &per_command_setlist, &per_command_showlist);
1359 add_setshow_boolean_cmd ("space", class_maintenance,
1360 &per_command_space, _("\
1361 Set whether to display per-command space usage."), _("\
1362 Show whether to display per-command space usage."),
1363 _("\
1364 If enabled, the space usage for each command will be\n\
1365 displayed following the command's output."),
1366 NULL, NULL,
1367 &per_command_setlist, &per_command_showlist);
1369 add_setshow_boolean_cmd ("symtab", class_maintenance,
1370 &per_command_symtab, _("\
1371 Set whether to display per-command symtab statistics."), _("\
1372 Show whether to display per-command symtab statistics."),
1373 _("\
1374 If enabled, the basic symtab statistics for each command will be\n\
1375 displayed following the command's output."),
1376 NULL, NULL,
1377 &per_command_setlist, &per_command_showlist);
1379 /* This is equivalent to "mt set per-command time on".
1380 Kept because some people are used to typing "mt time 1". */
1381 add_cmd ("time", class_maintenance, maintenance_time_display, _("\
1382 Set the display of time usage.\n\
1383 If nonzero, will cause the execution time for each command to be\n\
1384 displayed, following the command's output."),
1385 &maintenancelist);
1387 /* This is equivalent to "mt set per-command space on".
1388 Kept because some people are used to typing "mt space 1". */
1389 add_cmd ("space", class_maintenance, maintenance_space_display, _("\
1390 Set the display of space usage.\n\
1391 If nonzero, will cause the execution space for each command to be\n\
1392 displayed, following the command's output."),
1393 &maintenancelist);
1395 cmd = add_cmd ("type", class_maintenance, maintenance_print_type, _("\
1396 Print a type chain for a given symbol.\n\
1397 For each node in a type chain, print the raw data for each member of\n\
1398 the type structure, and the interpretation of the data."),
1399 &maintenanceprintlist);
1400 set_cmd_completer (cmd, expression_completer);
1402 add_cmd ("statistics", class_maintenance, maintenance_print_statistics,
1403 _("Print statistics about internal gdb state."),
1404 &maintenanceprintlist);
1406 add_cmd ("architecture", class_maintenance,
1407 maintenance_print_architecture, _("\
1408 Print the internal architecture configuration.\n\
1409 Takes an optional file parameter."),
1410 &maintenanceprintlist);
1412 add_basic_prefix_cmd ("check", class_maintenance, _("\
1413 Commands for checking internal gdb state."),
1414 &maintenancechecklist, 0,
1415 &maintenancelist);
1417 add_cmd ("translate-address", class_maintenance,
1418 maintenance_translate_address,
1419 _("Translate a section name and address to a symbol."),
1420 &maintenancelist);
1422 add_cmd ("deprecate", class_maintenance, maintenance_deprecate, _("\
1423 Deprecate a command (for testing purposes).\n\
1424 Usage: maintenance deprecate COMMANDNAME [\"REPLACEMENT\"]\n\
1425 This is used by the testsuite to check the command deprecator.\n\
1426 You probably shouldn't use this,\n\
1427 rather you should use the C function deprecate_cmd()."), &maintenancelist);
1429 add_cmd ("undeprecate", class_maintenance, maintenance_undeprecate, _("\
1430 Undeprecate a command (for testing purposes).\n\
1431 Usage: maintenance undeprecate COMMANDNAME\n\
1432 This is used by the testsuite to check the command deprecator.\n\
1433 You probably shouldn't use this."),
1434 &maintenancelist);
1436 cmd_list_element *maintenance_selftest_cmd
1437 = add_cmd ("selftest", class_maintenance, maintenance_selftest, _("\
1438 Run gdb's unit tests.\n\
1439 Usage: maintenance selftest [FILTER]\n\
1440 This will run any unit tests that were built in to gdb.\n\
1441 If a filter is given, only the tests with that value in their name will ran."),
1442 &maintenancelist);
1443 set_cmd_completer_handle_brkchars (maintenance_selftest_cmd,
1444 maintenance_selftest_completer);
1446 add_cmd ("selftests", class_maintenance, maintenance_info_selftests,
1447 _("List the registered selftests."), &maintenanceinfolist);
1449 add_setshow_boolean_cmd ("profile", class_maintenance,
1450 &maintenance_profile_p, _("\
1451 Set internal profiling."), _("\
1452 Show internal profiling."), _("\
1453 When enabled GDB is profiled."),
1454 maintenance_set_profile_cmd,
1455 show_maintenance_profile_p,
1456 &maintenance_set_cmdlist,
1457 &maintenance_show_cmdlist);
1459 add_setshow_zuinteger_unlimited_cmd ("worker-threads",
1460 class_maintenance,
1461 &n_worker_threads, _("\
1462 Set the number of worker threads GDB can use."), _("\
1463 Show the number of worker threads GDB can use."), _("\
1464 GDB may use multiple threads to speed up certain CPU-intensive operations,\n\
1465 such as demangling symbol names."),
1466 maintenance_set_worker_threads,
1467 maintenance_show_worker_threads,
1468 &maintenance_set_cmdlist,
1469 &maintenance_show_cmdlist);
1471 /* Add the "maint set/show selftest" commands. */
1472 static cmd_list_element *set_selftest_cmdlist = nullptr;
1473 static cmd_list_element *show_selftest_cmdlist = nullptr;
1475 add_setshow_prefix_cmd ("selftest", class_maintenance,
1476 _("Self tests-related settings."),
1477 _("Self tests-related settings."),
1478 &set_selftest_cmdlist, &show_selftest_cmdlist,
1479 &maintenance_set_cmdlist, &maintenance_show_cmdlist);
1481 /* Add setting commands matching "maintenance selftest" options. */
1482 gdb::option::add_setshow_cmds_for_options (class_maintenance,
1483 &user_maintenance_selftest_options,
1484 maintenance_selftest_option_defs,
1485 &set_selftest_cmdlist,
1486 &show_selftest_cmdlist);