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