Introduce the "with" command
[external/binutils.git] / gdb / maint.c
1 /* Support for GDB maintenance commands.
2
3    Copyright (C) 1992-2019 Free Software Foundation, Inc.
4
5    Written by Fred Fish at Cygnus Support.
6
7    This file is part of GDB.
8
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.
13
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.
18
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/>.  */
21
22
23 #include "defs.h"
24 #include "arch-utils.h"
25 #include <ctype.h>
26 #include <signal.h>
27 #include "command.h"
28 #include "gdbcmd.h"
29 #include "symtab.h"
30 #include "block.h"
31 #include "gdbtypes.h"
32 #include "demangle.h"
33 #include "gdbcore.h"
34 #include "expression.h"         /* For language.h */
35 #include "language.h"
36 #include "symfile.h"
37 #include "objfiles.h"
38 #include "value.h"
39 #include "top.h"
40 #include "maint.h"
41 #include "common/selftest.h"
42
43 #include "cli/cli-decode.h"
44 #include "cli/cli-utils.h"
45 #include "cli/cli-setshow.h"
46 #include "cli/cli-cmds.h"
47
48 static void maintenance_do_deprecate (const char *, int);
49
50 /* Access the maintenance subcommands.  */
51
52 static void
53 maintenance_command (const char *args, int from_tty)
54 {
55   printf_unfiltered (_("\"maintenance\" must be followed by "
56                        "the name of a maintenance command.\n"));
57   help_list (maintenancelist, "maintenance ", all_commands, gdb_stdout);
58 }
59
60 #ifndef _WIN32
61 static void
62 maintenance_dump_me (const char *args, int from_tty)
63 {
64   if (query (_("Should GDB dump core? ")))
65     {
66 #ifdef __DJGPP__
67       /* SIGQUIT by default is ignored, so use SIGABRT instead.  */
68       signal (SIGABRT, SIG_DFL);
69       kill (getpid (), SIGABRT);
70 #else
71       signal (SIGQUIT, SIG_DFL);
72       kill (getpid (), SIGQUIT);
73 #endif
74     }
75 }
76 #endif
77
78 /* Stimulate the internal error mechanism that GDB uses when an
79    internal problem is detected.  Allows testing of the mechanism.
80    Also useful when the user wants to drop a core file but not exit
81    GDB.  */
82
83 static void
84 maintenance_internal_error (const char *args, int from_tty)
85 {
86   internal_error (__FILE__, __LINE__, "%s", (args == NULL ? "" : args));
87 }
88
89 /* Stimulate the internal error mechanism that GDB uses when an
90    internal problem is detected.  Allows testing of the mechanism.
91    Also useful when the user wants to drop a core file but not exit
92    GDB.  */
93
94 static void
95 maintenance_internal_warning (const char *args, int from_tty)
96 {
97   internal_warning (__FILE__, __LINE__, "%s", (args == NULL ? "" : args));
98 }
99
100 /* Stimulate the internal error mechanism that GDB uses when an
101    demangler problem is detected.  Allows testing of the mechanism.  */
102
103 static void
104 maintenance_demangler_warning (const char *args, int from_tty)
105 {
106   demangler_warning (__FILE__, __LINE__, "%s", (args == NULL ? "" : args));
107 }
108
109 /* Old command to demangle a string.  The command has been moved to "demangle".
110    It is kept for now because otherwise "mt demangle" gets interpreted as
111    "mt demangler-warning" which artificially creates an internal gdb error.  */
112
113 static void
114 maintenance_demangle (const char *args, int from_tty)
115 {
116   printf_filtered (_("This command has been moved to \"demangle\".\n"));
117 }
118
119 static void
120 maintenance_time_display (const char *args, int from_tty)
121 {
122   if (args == NULL || *args == '\0')
123     printf_unfiltered (_("\"maintenance time\" takes a numeric argument.\n"));
124   else
125     set_per_command_time (strtol (args, NULL, 10));
126 }
127
128 static void
129 maintenance_space_display (const char *args, int from_tty)
130 {
131   if (args == NULL || *args == '\0')
132     printf_unfiltered ("\"maintenance space\" takes a numeric argument.\n");
133   else
134     set_per_command_space (strtol (args, NULL, 10));
135 }
136
137 /* The "maintenance info" command is defined as a prefix, with
138    allow_unknown 0.  Therefore, its own definition is called only for
139    "maintenance info" with no args.  */
140
141 static void
142 maintenance_info_command (const char *arg, int from_tty)
143 {
144   printf_unfiltered (_("\"maintenance info\" must be followed "
145                        "by the name of an info command.\n"));
146   help_list (maintenanceinfolist, "maintenance info ", all_commands,
147              gdb_stdout);
148 }
149
150 /* The "maintenance check" command is defined as a prefix, with
151    allow_unknown 0.  Therefore, its own definition is called only for
152    "maintenance check" with no args.  */
153
154 static void
155 maintenance_check_command (const char *arg, int from_tty)
156 {
157   printf_unfiltered (_("\"maintenance check\" must be followed "
158                        "by the name of a check command.\n"));
159   help_list (maintenancechecklist, "maintenance check ", all_commands,
160              gdb_stdout);
161 }
162
163 /* Mini tokenizing lexer for 'maint info sections' command.  */
164
165 static int
166 match_substring (const char *string, const char *substr)
167 {
168   int substr_len = strlen(substr);
169   const char *tok;
170
171   while ((tok = strstr (string, substr)) != NULL)
172     {
173       /* Got a partial match.  Is it a whole word?  */
174       if (tok == string
175           || tok[-1] == ' '
176           || tok[-1] == '\t')
177       {
178         /* Token is delimited at the front...  */
179         if (tok[substr_len] == ' '
180             || tok[substr_len] == '\t'
181             || tok[substr_len] == '\0')
182         {
183           /* Token is delimited at the rear.  Got a whole-word match.  */
184           return 1;
185         }
186       }
187       /* Token didn't match as a whole word.  Advance and try again.  */
188       string = tok + 1;
189     }
190   return 0;
191 }
192
193 static int 
194 match_bfd_flags (const char *string, flagword flags)
195 {
196   if (flags & SEC_ALLOC)
197     if (match_substring (string, "ALLOC"))
198       return 1;
199   if (flags & SEC_LOAD)
200     if (match_substring (string, "LOAD"))
201       return 1;
202   if (flags & SEC_RELOC)
203     if (match_substring (string, "RELOC"))
204       return 1;
205   if (flags & SEC_READONLY)
206     if (match_substring (string, "READONLY"))
207       return 1;
208   if (flags & SEC_CODE)
209     if (match_substring (string, "CODE"))
210       return 1;
211   if (flags & SEC_DATA)
212     if (match_substring (string, "DATA"))
213       return 1;
214   if (flags & SEC_ROM)
215     if (match_substring (string, "ROM"))
216       return 1;
217   if (flags & SEC_CONSTRUCTOR)
218     if (match_substring (string, "CONSTRUCTOR"))
219       return 1;
220   if (flags & SEC_HAS_CONTENTS)
221     if (match_substring (string, "HAS_CONTENTS"))
222       return 1;
223   if (flags & SEC_NEVER_LOAD)
224     if (match_substring (string, "NEVER_LOAD"))
225       return 1;
226   if (flags & SEC_COFF_SHARED_LIBRARY)
227     if (match_substring (string, "COFF_SHARED_LIBRARY"))
228       return 1;
229   if (flags & SEC_IS_COMMON)
230     if (match_substring (string, "IS_COMMON"))
231       return 1;
232
233   return 0;
234 }
235
236 static void
237 print_bfd_flags (flagword flags)
238 {
239   if (flags & SEC_ALLOC)
240     printf_filtered (" ALLOC");
241   if (flags & SEC_LOAD)
242     printf_filtered (" LOAD");
243   if (flags & SEC_RELOC)
244     printf_filtered (" RELOC");
245   if (flags & SEC_READONLY)
246     printf_filtered (" READONLY");
247   if (flags & SEC_CODE)
248     printf_filtered (" CODE");
249   if (flags & SEC_DATA)
250     printf_filtered (" DATA");
251   if (flags & SEC_ROM)
252     printf_filtered (" ROM");
253   if (flags & SEC_CONSTRUCTOR)
254     printf_filtered (" CONSTRUCTOR");
255   if (flags & SEC_HAS_CONTENTS)
256     printf_filtered (" HAS_CONTENTS");
257   if (flags & SEC_NEVER_LOAD)
258     printf_filtered (" NEVER_LOAD");
259   if (flags & SEC_COFF_SHARED_LIBRARY)
260     printf_filtered (" COFF_SHARED_LIBRARY");
261   if (flags & SEC_IS_COMMON)
262     printf_filtered (" IS_COMMON");
263 }
264
265 static void
266 maint_print_section_info (const char *name, flagword flags, 
267                           CORE_ADDR addr, CORE_ADDR endaddr, 
268                           unsigned long filepos, int addr_size)
269 {
270   printf_filtered ("    %s", hex_string_custom (addr, addr_size));
271   printf_filtered ("->%s", hex_string_custom (endaddr, addr_size));
272   printf_filtered (" at %s",
273                    hex_string_custom ((unsigned long) filepos, 8));
274   printf_filtered (": %s", name);
275   print_bfd_flags (flags);
276   printf_filtered ("\n");
277 }
278
279 static void
280 print_bfd_section_info (bfd *abfd, 
281                         asection *asect, 
282                         void *datum)
283 {
284   flagword flags = bfd_get_section_flags (abfd, asect);
285   const char *name = bfd_section_name (abfd, asect);
286   const char *arg = (const char *) datum;
287
288   if (arg == NULL || *arg == '\0'
289       || match_substring (arg, name)
290       || match_bfd_flags (arg, flags))
291     {
292       struct gdbarch *gdbarch = gdbarch_from_bfd (abfd);
293       int addr_size = gdbarch_addr_bit (gdbarch) / 8;
294       CORE_ADDR addr, endaddr;
295
296       addr = bfd_section_vma (abfd, asect);
297       endaddr = addr + bfd_section_size (abfd, asect);
298       printf_filtered (" [%d] ", gdb_bfd_section_index (abfd, asect));
299       maint_print_section_info (name, flags, addr, endaddr,
300                                 asect->filepos, addr_size);
301     }
302 }
303
304 static void
305 print_objfile_section_info (bfd *abfd, 
306                             struct obj_section *asect, 
307                             const char *string)
308 {
309   flagword flags = bfd_get_section_flags (abfd, asect->the_bfd_section);
310   const char *name = bfd_section_name (abfd, asect->the_bfd_section);
311
312   if (string == NULL || *string == '\0'
313       || match_substring (string, name)
314       || match_bfd_flags (string, flags))
315     {
316       struct gdbarch *gdbarch = gdbarch_from_bfd (abfd);
317       int addr_size = gdbarch_addr_bit (gdbarch) / 8;
318
319       maint_print_section_info (name, flags,
320                                 obj_section_addr (asect),
321                                 obj_section_endaddr (asect),
322                                 asect->the_bfd_section->filepos,
323                                 addr_size);
324     }
325 }
326
327 static void
328 maintenance_info_sections (const char *arg, int from_tty)
329 {
330   if (exec_bfd)
331     {
332       printf_filtered (_("Exec file:\n"));
333       printf_filtered ("    `%s', ", bfd_get_filename (exec_bfd));
334       wrap_here ("        ");
335       printf_filtered (_("file type %s.\n"), bfd_get_target (exec_bfd));
336       if (arg && *arg && match_substring (arg, "ALLOBJ"))
337         {
338           struct obj_section *osect;
339
340           /* Only this function cares about the 'ALLOBJ' argument; 
341              if 'ALLOBJ' is the only argument, discard it rather than
342              passing it down to print_objfile_section_info (which 
343              wouldn't know how to handle it).  */
344           if (strcmp (arg, "ALLOBJ") == 0)
345             arg = NULL;
346
347           for (objfile *ofile : current_program_space->objfiles ())
348             {
349               printf_filtered (_("  Object file: %s\n"), 
350                                bfd_get_filename (ofile->obfd));
351               ALL_OBJFILE_OSECTIONS (ofile, osect)
352                 {
353                   print_objfile_section_info (ofile->obfd, osect, arg);
354                 }
355             }
356         }
357       else 
358         bfd_map_over_sections (exec_bfd, print_bfd_section_info, (void *) arg);
359     }
360
361   if (core_bfd)
362     {
363       printf_filtered (_("Core file:\n"));
364       printf_filtered ("    `%s', ", bfd_get_filename (core_bfd));
365       wrap_here ("        ");
366       printf_filtered (_("file type %s.\n"), bfd_get_target (core_bfd));
367       bfd_map_over_sections (core_bfd, print_bfd_section_info, (void *) arg);
368     }
369 }
370
371 static void
372 maintenance_print_statistics (const char *args, int from_tty)
373 {
374   print_objfile_statistics ();
375   print_symbol_bcache_statistics ();
376 }
377
378 static void
379 maintenance_print_architecture (const char *args, int from_tty)
380 {
381   struct gdbarch *gdbarch = get_current_arch ();
382
383   if (args == NULL)
384     gdbarch_dump (gdbarch, gdb_stdout);
385   else
386     {
387       stdio_file file;
388
389       if (!file.open (args, "w"))
390         perror_with_name (_("maintenance print architecture"));
391       gdbarch_dump (gdbarch, &file);
392     }
393 }
394
395 /* The "maintenance print" command is defined as a prefix, with
396    allow_unknown 0.  Therefore, its own definition is called only for
397    "maintenance print" with no args.  */
398
399 static void
400 maintenance_print_command (const char *arg, int from_tty)
401 {
402   printf_unfiltered (_("\"maintenance print\" must be followed "
403                        "by the name of a print command.\n"));
404   help_list (maintenanceprintlist, "maintenance print ", all_commands,
405              gdb_stdout);
406 }
407
408 /* The "maintenance translate-address" command converts a section and address
409    to a symbol.  This can be called in two ways:
410    maintenance translate-address <secname> <addr>
411    or   maintenance translate-address <addr>.  */
412
413 static void
414 maintenance_translate_address (const char *arg, int from_tty)
415 {
416   CORE_ADDR address;
417   struct obj_section *sect;
418   const char *p;
419   struct bound_minimal_symbol sym;
420
421   if (arg == NULL || *arg == 0)
422     error (_("requires argument (address or section + address)"));
423
424   sect = NULL;
425   p = arg;
426
427   if (!isdigit (*p))
428     {                           /* See if we have a valid section name.  */
429       while (*p && !isspace (*p))       /* Find end of section name.  */
430         p++;
431       if (*p == '\000')         /* End of command?  */
432         error (_("Need to specify section name and address"));
433
434       int arg_len = p - arg;
435       p = skip_spaces (p + 1);
436
437       for (objfile *objfile : current_program_space->objfiles ())
438         ALL_OBJFILE_OSECTIONS (objfile, sect)
439           {
440             if (strncmp (sect->the_bfd_section->name, arg, arg_len) == 0)
441               goto found;
442           }
443
444       error (_("Unknown section %s."), arg);
445     found: ;
446     }
447
448   address = parse_and_eval_address (p);
449
450   if (sect)
451     sym = lookup_minimal_symbol_by_pc_section (address, sect);
452   else
453     sym = lookup_minimal_symbol_by_pc (address);
454
455   if (sym.minsym)
456     {
457       const char *symbol_name = MSYMBOL_PRINT_NAME (sym.minsym);
458       const char *symbol_offset
459         = pulongest (address - BMSYMBOL_VALUE_ADDRESS (sym));
460
461       sect = MSYMBOL_OBJ_SECTION(sym.objfile, sym.minsym);
462       if (sect != NULL)
463         {
464           const char *section_name;
465           const char *obj_name;
466
467           gdb_assert (sect->the_bfd_section && sect->the_bfd_section->name);
468           section_name = sect->the_bfd_section->name;
469
470           gdb_assert (sect->objfile && objfile_name (sect->objfile));
471           obj_name = objfile_name (sect->objfile);
472
473           if (MULTI_OBJFILE_P ())
474             printf_filtered (_("%s + %s in section %s of %s\n"),
475                              symbol_name, symbol_offset,
476                              section_name, obj_name);
477           else
478             printf_filtered (_("%s + %s in section %s\n"),
479                              symbol_name, symbol_offset, section_name);
480         }
481       else
482         printf_filtered (_("%s + %s\n"), symbol_name, symbol_offset);
483     }
484   else if (sect)
485     printf_filtered (_("no symbol at %s:%s\n"),
486                      sect->the_bfd_section->name, hex_string (address));
487   else
488     printf_filtered (_("no symbol at %s\n"), hex_string (address));
489
490   return;
491 }
492
493
494 /* When a command is deprecated the user will be warned the first time
495    the command is used.  If possible, a replacement will be
496    offered.  */
497
498 static void
499 maintenance_deprecate (const char *args, int from_tty)
500 {
501   if (args == NULL || *args == '\0')
502     {
503       printf_unfiltered (_("\"maintenance deprecate\" takes an argument,\n\
504 the command you want to deprecate, and optionally the replacement command\n\
505 enclosed in quotes.\n"));
506     }
507
508   maintenance_do_deprecate (args, 1);
509 }
510
511
512 static void
513 maintenance_undeprecate (const char *args, int from_tty)
514 {
515   if (args == NULL || *args == '\0')
516     {
517       printf_unfiltered (_("\"maintenance undeprecate\" takes an argument, \n\
518 the command you want to undeprecate.\n"));
519     }
520
521   maintenance_do_deprecate (args, 0);
522 }
523
524 /* You really shouldn't be using this.  It is just for the testsuite.
525    Rather, you should use deprecate_cmd() when the command is created
526    in _initialize_blah().
527
528    This function deprecates a command and optionally assigns it a
529    replacement.  */
530
531 static void
532 maintenance_do_deprecate (const char *text, int deprecate)
533 {
534   struct cmd_list_element *alias = NULL;
535   struct cmd_list_element *prefix_cmd = NULL;
536   struct cmd_list_element *cmd = NULL;
537
538   const char *start_ptr = NULL;
539   const char *end_ptr = NULL;
540   int len;
541   char *replacement = NULL;
542
543   if (text == NULL)
544     return;
545
546   if (!lookup_cmd_composition (text, &alias, &prefix_cmd, &cmd))
547     {
548       printf_filtered (_("Can't find command '%s' to deprecate.\n"), text);
549       return;
550     }
551
552   if (deprecate)
553     {
554       /* Look for a replacement command.  */
555       start_ptr = strchr (text, '\"');
556       if (start_ptr != NULL)
557         {
558           start_ptr++;
559           end_ptr = strrchr (start_ptr, '\"');
560           if (end_ptr != NULL)
561             {
562               len = end_ptr - start_ptr;
563               replacement = savestring (start_ptr, len);
564             }
565         }
566     }
567
568   if (!start_ptr || !end_ptr)
569     replacement = NULL;
570
571
572   /* If they used an alias, we only want to deprecate the alias.
573
574      Note the MALLOCED_REPLACEMENT test.  If the command's replacement
575      string was allocated at compile time we don't want to free the
576      memory.  */
577   if (alias)
578     {
579       if (alias->malloced_replacement)
580         xfree ((char *) alias->replacement);
581
582       if (deprecate)
583         {
584           alias->deprecated_warn_user = 1;
585           alias->cmd_deprecated = 1;
586         }
587       else
588         {
589           alias->deprecated_warn_user = 0;
590           alias->cmd_deprecated = 0;
591         }
592       alias->replacement = replacement;
593       alias->malloced_replacement = 1;
594       return;
595     }
596   else if (cmd)
597     {
598       if (cmd->malloced_replacement)
599         xfree ((char *) cmd->replacement);
600
601       if (deprecate)
602         {
603           cmd->deprecated_warn_user = 1;
604           cmd->cmd_deprecated = 1;
605         }
606       else
607         {
608           cmd->deprecated_warn_user = 0;
609           cmd->cmd_deprecated = 0;
610         }
611       cmd->replacement = replacement;
612       cmd->malloced_replacement = 1;
613       return;
614     }
615   xfree (replacement);
616 }
617
618 /* Maintenance set/show framework.  */
619
620 struct cmd_list_element *maintenance_set_cmdlist;
621 struct cmd_list_element *maintenance_show_cmdlist;
622
623 static void
624 maintenance_set_cmd (const char *args, int from_tty)
625 {
626   printf_unfiltered (_("\"maintenance set\" must be followed "
627                        "by the name of a set command.\n"));
628   help_list (maintenance_set_cmdlist, "maintenance set ", all_commands,
629              gdb_stdout);
630 }
631
632 static void
633 maintenance_show_cmd (const char *args, int from_tty)
634 {
635   cmd_show_list (maintenance_show_cmdlist, from_tty, "");
636 }
637
638 /* "maintenance with" command.  */
639
640 static void
641 maintenance_with_cmd (const char *args, int from_tty)
642 {
643   with_command_1 ("maintenance set ", maintenance_set_cmdlist, args, from_tty);
644 }
645
646 /* "maintenance with" command completer.  */
647
648 static void
649 maintenance_with_cmd_completer (struct cmd_list_element *ignore,
650                                 completion_tracker &tracker,
651                                 const char *text, const char * /*word*/)
652 {
653   with_command_completer_1 ("maintenance set ", tracker,  text);
654 }
655
656 /* Profiling support.  */
657
658 static int maintenance_profile_p;
659 static void
660 show_maintenance_profile_p (struct ui_file *file, int from_tty,
661                             struct cmd_list_element *c, const char *value)
662 {
663   fprintf_filtered (file, _("Internal profiling is %s.\n"), value);
664 }
665
666 #ifdef HAVE__ETEXT
667 extern char _etext;
668 #define TEXTEND &_etext
669 #elif defined (HAVE_ETEXT)
670 extern char etext;
671 #define TEXTEND &etext
672 #endif
673
674 #if defined (HAVE_MONSTARTUP) && defined (HAVE__MCLEANUP) && defined (TEXTEND)
675
676 static int profiling_state;
677
678 EXTERN_C void _mcleanup (void);
679
680 static void
681 mcleanup_wrapper (void)
682 {
683   if (profiling_state)
684     _mcleanup ();
685 }
686
687 EXTERN_C void monstartup (unsigned long, unsigned long);
688 extern int main ();
689
690 static void
691 maintenance_set_profile_cmd (const char *args, int from_tty,
692                              struct cmd_list_element *c)
693 {
694   if (maintenance_profile_p == profiling_state)
695     return;
696
697   profiling_state = maintenance_profile_p;
698
699   if (maintenance_profile_p)
700     {
701       static int profiling_initialized;
702
703       if (!profiling_initialized)
704         {
705           atexit (mcleanup_wrapper);
706           profiling_initialized = 1;
707         }
708
709       /* "main" is now always the first function in the text segment, so use
710          its address for monstartup.  */
711       monstartup ((unsigned long) &main, (unsigned long) TEXTEND);
712     }
713   else
714     {
715       extern void _mcleanup (void);
716
717       _mcleanup ();
718     }
719 }
720 #else
721 static void
722 maintenance_set_profile_cmd (const char *args, int from_tty,
723                              struct cmd_list_element *c)
724 {
725   error (_("Profiling support is not available on this system."));
726 }
727 #endif
728 \f
729 /* If nonzero, display time usage both at startup and for each command.  */
730
731 static int per_command_time;
732
733 /* If nonzero, display space usage both at startup and for each command.  */
734
735 static int per_command_space;
736
737 /* If nonzero, display basic symtab stats for each command.  */
738
739 static int per_command_symtab;
740
741 /* mt per-command commands.  */
742
743 static struct cmd_list_element *per_command_setlist;
744 static struct cmd_list_element *per_command_showlist;
745
746 /* Set whether to display time statistics to NEW_VALUE
747    (non-zero means true).  */
748
749 void
750 set_per_command_time (int new_value)
751 {
752   per_command_time = new_value;
753 }
754
755 /* Set whether to display space statistics to NEW_VALUE
756    (non-zero means true).  */
757
758 void
759 set_per_command_space (int new_value)
760 {
761   per_command_space = new_value;
762 }
763
764 /* Count the number of symtabs and blocks.  */
765
766 static void
767 count_symtabs_and_blocks (int *nr_symtabs_ptr, int *nr_compunit_symtabs_ptr,
768                           int *nr_blocks_ptr)
769 {
770   int nr_symtabs = 0;
771   int nr_compunit_symtabs = 0;
772   int nr_blocks = 0;
773
774   /* When collecting statistics during startup, this is called before
775      pretty much anything in gdb has been initialized, and thus
776      current_program_space may be NULL.  */
777   if (current_program_space != NULL)
778     {
779       for (objfile *o : current_program_space->objfiles ())
780         {
781           for (compunit_symtab *cu : o->compunits ())
782             {
783               ++nr_compunit_symtabs;
784               nr_blocks += BLOCKVECTOR_NBLOCKS (COMPUNIT_BLOCKVECTOR (cu));
785               nr_symtabs += std::distance (compunit_filetabs (cu).begin (),
786                                            compunit_filetabs (cu).end ());
787             }
788         }
789     }
790
791   *nr_symtabs_ptr = nr_symtabs;
792   *nr_compunit_symtabs_ptr = nr_compunit_symtabs;
793   *nr_blocks_ptr = nr_blocks;
794 }
795
796 /* As indicated by display_time and display_space, report GDB's
797    elapsed time and space usage from the base time and space recorded
798    in this object.  */
799
800 scoped_command_stats::~scoped_command_stats ()
801 {
802   /* Early exit if we're not reporting any stats.  It can be expensive to
803      compute the pre-command values so don't collect them at all if we're
804      not reporting stats.  Alas this doesn't work in the startup case because
805      we don't know yet whether we will be reporting the stats.  For the
806      startup case collect the data anyway (it should be cheap at this point),
807      and leave it to the reporter to decide whether to print them.  */
808   if (m_msg_type
809       && !per_command_time
810       && !per_command_space
811       && !per_command_symtab)
812     return;
813
814   if (m_time_enabled && per_command_time)
815     {
816       print_time (_("command finished"));
817
818       using namespace std::chrono;
819
820       run_time_clock::duration cmd_time
821         = run_time_clock::now () - m_start_cpu_time;
822
823       steady_clock::duration wall_time
824         = steady_clock::now () - m_start_wall_time;
825       /* Subtract time spend in prompt_for_continue from walltime.  */
826       wall_time -= get_prompt_for_continue_wait_time ();
827
828       printf_unfiltered (!m_msg_type
829                          ? _("Startup time: %.6f (cpu), %.6f (wall)\n")
830                          : _("Command execution time: %.6f (cpu), %.6f (wall)\n"),
831                          duration<double> (cmd_time).count (),
832                          duration<double> (wall_time).count ());
833     }
834
835   if (m_space_enabled && per_command_space)
836     {
837 #ifdef HAVE_USEFUL_SBRK
838       char *lim = (char *) sbrk (0);
839
840       long space_now = lim - lim_at_start;
841       long space_diff = space_now - m_start_space;
842
843       printf_unfiltered (!m_msg_type
844                          ? _("Space used: %ld (%s%ld during startup)\n")
845                          : _("Space used: %ld (%s%ld for this command)\n"),
846                          space_now,
847                          (space_diff >= 0 ? "+" : ""),
848                          space_diff);
849 #endif
850     }
851
852   if (m_symtab_enabled && per_command_symtab)
853     {
854       int nr_symtabs, nr_compunit_symtabs, nr_blocks;
855
856       count_symtabs_and_blocks (&nr_symtabs, &nr_compunit_symtabs, &nr_blocks);
857       printf_unfiltered (_("#symtabs: %d (+%d),"
858                            " #compunits: %d (+%d),"
859                            " #blocks: %d (+%d)\n"),
860                          nr_symtabs,
861                          nr_symtabs - m_start_nr_symtabs,
862                          nr_compunit_symtabs,
863                          (nr_compunit_symtabs
864                           - m_start_nr_compunit_symtabs),
865                          nr_blocks,
866                          nr_blocks - m_start_nr_blocks);
867     }
868 }
869
870 scoped_command_stats::scoped_command_stats (bool msg_type)
871 : m_msg_type (msg_type)
872 {
873   if (!m_msg_type || per_command_space)
874     {
875 #ifdef HAVE_USEFUL_SBRK
876       char *lim = (char *) sbrk (0);
877       m_start_space = lim - lim_at_start;
878       m_space_enabled = 1;
879 #endif
880     }
881   else
882     m_space_enabled = 0;
883
884   if (msg_type == 0 || per_command_time)
885     {
886       using namespace std::chrono;
887
888       m_start_cpu_time = run_time_clock::now ();
889       m_start_wall_time = steady_clock::now ();
890       m_time_enabled = 1;
891
892       if (per_command_time)
893         print_time (_("command started"));
894     }
895   else
896     m_time_enabled = 0;
897
898   if (msg_type == 0 || per_command_symtab)
899     {
900       int nr_symtabs, nr_compunit_symtabs, nr_blocks;
901
902       count_symtabs_and_blocks (&nr_symtabs, &nr_compunit_symtabs, &nr_blocks);
903       m_start_nr_symtabs = nr_symtabs;
904       m_start_nr_compunit_symtabs = nr_compunit_symtabs;
905       m_start_nr_blocks = nr_blocks;
906       m_symtab_enabled = 1;
907     }
908   else
909     m_symtab_enabled = 0;
910
911   /* Initialize timer to keep track of how long we waited for the user.  */
912   reset_prompt_for_continue_wait_time ();
913 }
914
915 /* See maint.h.  */
916
917 void
918 scoped_command_stats::print_time (const char *msg)
919 {
920   using namespace std::chrono;
921
922   auto now = system_clock::now ();
923   auto ticks = now.time_since_epoch ().count () / (1000 * 1000);
924   auto millis = ticks % 1000;
925
926   std::time_t as_time = system_clock::to_time_t (now);
927   struct tm *tm = localtime (&as_time);
928
929   char out[100];
930   strftime (out, sizeof (out), "%F %H:%M:%S", tm);
931
932   printf_unfiltered ("%s.%03d - %s\n", out, (int) millis, msg);
933 }
934
935 /* Handle unknown "mt set per-command" arguments.
936    In this case have "mt set per-command on|off" affect every setting.  */
937
938 static void
939 set_per_command_cmd (const char *args, int from_tty)
940 {
941   struct cmd_list_element *list;
942   int val;
943
944   val = parse_cli_boolean_value (args);
945   if (val < 0)
946     error (_("Bad value for 'mt set per-command no'."));
947
948   for (list = per_command_setlist; list != NULL; list = list->next)
949     if (list->var_type == var_boolean)
950       {
951         gdb_assert (list->type == set_cmd);
952         do_set_command (args, from_tty, list);
953       }
954 }
955
956 /* Command "show per-command" displays summary of all the current
957    "show per-command " settings.  */
958
959 static void
960 show_per_command_cmd (const char *args, int from_tty)
961 {
962   cmd_show_list (per_command_showlist, from_tty, "");
963 }
964 \f
965
966 /* The "maintenance selftest" command.  */
967
968 static void
969 maintenance_selftest (const char *args, int from_tty)
970 {
971 #if GDB_SELF_TEST
972   selftests::run_tests (args);
973 #else
974   printf_filtered (_("\
975 Selftests have been disabled for this build.\n"));
976 #endif
977 }
978
979 static void
980 maintenance_info_selftests (const char *arg, int from_tty)
981 {
982 #if GDB_SELF_TEST
983   printf_filtered ("Registered selftests:\n");
984   selftests::for_each_selftest ([] (const std::string &name) {
985     printf_filtered (" - %s\n", name.c_str ());
986   });
987 #else
988   printf_filtered (_("\
989 Selftests have been disabled for this build.\n"));
990 #endif
991 }
992
993 \f
994 void
995 _initialize_maint_cmds (void)
996 {
997   struct cmd_list_element *cmd;
998
999   add_prefix_cmd ("maintenance", class_maintenance, maintenance_command, _("\
1000 Commands for use by GDB maintainers.\n\
1001 Includes commands to dump specific internal GDB structures in\n\
1002 a human readable form, to cause GDB to deliberately dump core, etc."),
1003                   &maintenancelist, "maintenance ", 0,
1004                   &cmdlist);
1005
1006   add_com_alias ("mt", "maintenance", class_maintenance, 1);
1007
1008   add_prefix_cmd ("info", class_maintenance, maintenance_info_command, _("\
1009 Commands for showing internal info about the program being debugged."),
1010                   &maintenanceinfolist, "maintenance info ", 0,
1011                   &maintenancelist);
1012   add_alias_cmd ("i", "info", class_maintenance, 1, &maintenancelist);
1013
1014   add_cmd ("sections", class_maintenance, maintenance_info_sections, _("\
1015 List the BFD sections of the exec and core files. \n\
1016 Arguments may be any combination of:\n\
1017         [one or more section names]\n\
1018         ALLOC LOAD RELOC READONLY CODE DATA ROM CONSTRUCTOR\n\
1019         HAS_CONTENTS NEVER_LOAD COFF_SHARED_LIBRARY IS_COMMON\n\
1020 Sections matching any argument will be listed (no argument\n\
1021 implies all sections).  In addition, the special argument\n\
1022         ALLOBJ\n\
1023 lists all sections from all object files, including shared libraries."),
1024            &maintenanceinfolist);
1025
1026   add_prefix_cmd ("print", class_maintenance, maintenance_print_command,
1027                   _("Maintenance command for printing GDB internal state."),
1028                   &maintenanceprintlist, "maintenance print ", 0,
1029                   &maintenancelist);
1030
1031   add_prefix_cmd ("set", class_maintenance, maintenance_set_cmd, _("\
1032 Set GDB internal variables used by the GDB maintainer.\n\
1033 Configure variables internal to GDB that aid in GDB's maintenance"),
1034                   &maintenance_set_cmdlist, "maintenance set ",
1035                   0/*allow-unknown*/,
1036                   &maintenancelist);
1037
1038   add_prefix_cmd ("show", class_maintenance, maintenance_show_cmd, _("\
1039 Show GDB internal variables used by the GDB maintainer.\n\
1040 Configure variables internal to GDB that aid in GDB's maintenance"),
1041                   &maintenance_show_cmdlist, "maintenance show ",
1042                   0/*allow-unknown*/,
1043                   &maintenancelist);
1044
1045   cmd = add_cmd ("with", class_maintenance, maintenance_with_cmd, _("\
1046 Like \"with\", but works with \"maintenance set\" variables.\n\
1047 Usage: maintenance with SETTING [VALUE] [-- COMMAND]\n\
1048 With no COMMAND, repeats the last executed command.\n\
1049 SETTING is any setting you can change with the \"maintenance set\"\n\
1050 subcommands."),
1051                  &maintenancelist);
1052   set_cmd_completer_handle_brkchars (cmd, maintenance_with_cmd_completer);
1053
1054 #ifndef _WIN32
1055   add_cmd ("dump-me", class_maintenance, maintenance_dump_me, _("\
1056 Get fatal error; make debugger dump its core.\n\
1057 GDB sets its handling of SIGQUIT back to SIG_DFL and then sends\n\
1058 itself a SIGQUIT signal."),
1059            &maintenancelist);
1060 #endif
1061
1062   add_cmd ("internal-error", class_maintenance,
1063            maintenance_internal_error, _("\
1064 Give GDB an internal error.\n\
1065 Cause GDB to behave as if an internal error was detected."),
1066            &maintenancelist);
1067
1068   add_cmd ("internal-warning", class_maintenance,
1069            maintenance_internal_warning, _("\
1070 Give GDB an internal warning.\n\
1071 Cause GDB to behave as if an internal warning was reported."),
1072            &maintenancelist);
1073
1074   add_cmd ("demangler-warning", class_maintenance,
1075            maintenance_demangler_warning, _("\
1076 Give GDB a demangler warning.\n\
1077 Cause GDB to behave as if a demangler warning was reported."),
1078            &maintenancelist);
1079
1080   cmd = add_cmd ("demangle", class_maintenance, maintenance_demangle, _("\
1081 This command has been moved to \"demangle\"."),
1082                  &maintenancelist);
1083   deprecate_cmd (cmd, "demangle");
1084
1085   add_prefix_cmd ("per-command", class_maintenance, set_per_command_cmd, _("\
1086 Per-command statistics settings."),
1087                     &per_command_setlist, "maintenance set per-command ",
1088                     1/*allow-unknown*/, &maintenance_set_cmdlist);
1089
1090   add_prefix_cmd ("per-command", class_maintenance, show_per_command_cmd, _("\
1091 Show per-command statistics settings."),
1092                     &per_command_showlist, "maintenance show per-command ",
1093                     0/*allow-unknown*/, &maintenance_show_cmdlist);
1094
1095   add_setshow_boolean_cmd ("time", class_maintenance,
1096                            &per_command_time, _("\
1097 Set whether to display per-command execution time."), _("\
1098 Show whether to display per-command execution time."),
1099                            _("\
1100 If enabled, the execution time for each command will be\n\
1101 displayed following the command's output."),
1102                            NULL, NULL,
1103                            &per_command_setlist, &per_command_showlist);
1104
1105   add_setshow_boolean_cmd ("space", class_maintenance,
1106                            &per_command_space, _("\
1107 Set whether to display per-command space usage."), _("\
1108 Show whether to display per-command space usage."),
1109                            _("\
1110 If enabled, the space usage for each command will be\n\
1111 displayed following the command's output."),
1112                            NULL, NULL,
1113                            &per_command_setlist, &per_command_showlist);
1114
1115   add_setshow_boolean_cmd ("symtab", class_maintenance,
1116                            &per_command_symtab, _("\
1117 Set whether to display per-command symtab statistics."), _("\
1118 Show whether to display per-command symtab statistics."),
1119                            _("\
1120 If enabled, the basic symtab statistics for each command will be\n\
1121 displayed following the command's output."),
1122                            NULL, NULL,
1123                            &per_command_setlist, &per_command_showlist);
1124
1125   /* This is equivalent to "mt set per-command time on".
1126      Kept because some people are used to typing "mt time 1".  */
1127   add_cmd ("time", class_maintenance, maintenance_time_display, _("\
1128 Set the display of time usage.\n\
1129 If nonzero, will cause the execution time for each command to be\n\
1130 displayed, following the command's output."),
1131            &maintenancelist);
1132
1133   /* This is equivalent to "mt set per-command space on".
1134      Kept because some people are used to typing "mt space 1".  */
1135   add_cmd ("space", class_maintenance, maintenance_space_display, _("\
1136 Set the display of space usage.\n\
1137 If nonzero, will cause the execution space for each command to be\n\
1138 displayed, following the command's output."),
1139            &maintenancelist);
1140
1141   add_cmd ("type", class_maintenance, maintenance_print_type, _("\
1142 Print a type chain for a given symbol.\n\
1143 For each node in a type chain, print the raw data for each member of\n\
1144 the type structure, and the interpretation of the data."),
1145            &maintenanceprintlist);
1146
1147   add_cmd ("statistics", class_maintenance, maintenance_print_statistics,
1148            _("Print statistics about internal gdb state."),
1149            &maintenanceprintlist);
1150
1151   add_cmd ("architecture", class_maintenance,
1152            maintenance_print_architecture, _("\
1153 Print the internal architecture configuration.\n\
1154 Takes an optional file parameter."),
1155            &maintenanceprintlist);
1156
1157   add_prefix_cmd ("check", class_maintenance, maintenance_check_command, _("\
1158 Commands for checking internal gdb state."),
1159                   &maintenancechecklist, "maintenance check ", 0,
1160                   &maintenancelist);
1161
1162   add_cmd ("translate-address", class_maintenance,
1163            maintenance_translate_address,
1164            _("Translate a section name and address to a symbol."),
1165            &maintenancelist);
1166
1167   add_cmd ("deprecate", class_maintenance, maintenance_deprecate, _("\
1168 Deprecate a command.  Note that this is just in here so the \n\
1169 testsuite can check the command deprecator. You probably shouldn't use this,\n\
1170 rather you should use the C function deprecate_cmd().  If you decide you \n\
1171 want to use it: maintenance deprecate 'commandname' \"replacement\". The \n\
1172 replacement is optional."), &maintenancelist);
1173
1174   add_cmd ("undeprecate", class_maintenance, maintenance_undeprecate, _("\
1175 Undeprecate a command.  Note that this is just in here so the \n\
1176 testsuite can check the command deprecator. You probably shouldn't use this,\n\
1177 If you decide you want to use it: maintenance undeprecate 'commandname'"),
1178            &maintenancelist);
1179
1180   add_cmd ("selftest", class_maintenance, maintenance_selftest, _("\
1181 Run gdb's unit tests.\n\
1182 Usage: maintenance selftest [filter]\n\
1183 This will run any unit tests that were built in to gdb.\n\
1184 If a filter is given, only the tests with that value in their name will ran."),
1185            &maintenancelist);
1186
1187   add_cmd ("selftests", class_maintenance, maintenance_info_selftests,
1188          _("List the registered selftests."), &maintenanceinfolist);
1189
1190   add_setshow_boolean_cmd ("profile", class_maintenance,
1191                            &maintenance_profile_p, _("\
1192 Set internal profiling."), _("\
1193 Show internal profiling."), _("\
1194 When enabled GDB is profiled."),
1195                            maintenance_set_profile_cmd,
1196                            show_maintenance_profile_p,
1197                            &maintenance_set_cmdlist,
1198                            &maintenance_show_cmdlist);
1199 }