Eliminate make_cleanup_ui_file_delete / make ui_file a class hierarchy
[external/binutils.git] / gdb / typeprint.c
1 /* Language independent support for printing types for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2017 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "gdb_obstack.h"
22 #include "bfd.h"                /* Binary File Description */
23 #include "symtab.h"
24 #include "gdbtypes.h"
25 #include "expression.h"
26 #include "value.h"
27 #include "gdbcore.h"
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "target.h"
31 #include "language.h"
32 #include "cp-abi.h"
33 #include "typeprint.h"
34 #include "valprint.h"
35 #include <ctype.h>
36 #include "cli/cli-utils.h"
37 #include "extension.h"
38 #include "completer.h"
39
40 extern void _initialize_typeprint (void);
41
42 static void ptype_command (char *, int);
43
44 static void whatis_command (char *, int);
45
46 static void whatis_exp (char *, int);
47
48 const struct type_print_options type_print_raw_options =
49 {
50   1,                            /* raw */
51   1,                            /* print_methods */
52   1,                            /* print_typedefs */
53   NULL,                         /* local_typedefs */
54   NULL,                         /* global_table */
55   NULL                          /* global_printers */
56 };
57
58 /* The default flags for 'ptype' and 'whatis'.  */
59
60 static struct type_print_options default_ptype_flags =
61 {
62   0,                            /* raw */
63   1,                            /* print_methods */
64   1,                            /* print_typedefs */
65   NULL,                         /* local_typedefs */
66   NULL,                         /* global_table */
67   NULL                          /* global_printers */
68 };
69
70 \f
71
72 /* A hash table holding typedef_field objects.  This is more
73    complicated than an ordinary hash because it must also track the
74    lifetime of some -- but not all -- of the contained objects.  */
75
76 struct typedef_hash_table
77 {
78   /* The actual hash table.  */
79   htab_t table;
80
81   /* Storage for typedef_field objects that must be synthesized.  */
82   struct obstack storage;
83 };
84
85 /* A hash function for a typedef_field.  */
86
87 static hashval_t
88 hash_typedef_field (const void *p)
89 {
90   const struct typedef_field *tf = (const struct typedef_field *) p;
91   struct type *t = check_typedef (tf->type);
92
93   return htab_hash_string (TYPE_SAFE_NAME (t));
94 }
95
96 /* An equality function for a typedef field.  */
97
98 static int
99 eq_typedef_field (const void *a, const void *b)
100 {
101   const struct typedef_field *tfa = (const struct typedef_field *) a;
102   const struct typedef_field *tfb = (const struct typedef_field *) b;
103
104   return types_equal (tfa->type, tfb->type);
105 }
106
107 /* Add typedefs from T to the hash table TABLE.  */
108
109 void
110 recursively_update_typedef_hash (struct typedef_hash_table *table,
111                                  struct type *t)
112 {
113   int i;
114
115   if (table == NULL)
116     return;
117
118   for (i = 0; i < TYPE_TYPEDEF_FIELD_COUNT (t); ++i)
119     {
120       struct typedef_field *tdef = &TYPE_TYPEDEF_FIELD (t, i);
121       void **slot;
122
123       slot = htab_find_slot (table->table, tdef, INSERT);
124       /* Only add a given typedef name once.  Really this shouldn't
125          happen; but it is safe enough to do the updates breadth-first
126          and thus use the most specific typedef.  */
127       if (*slot == NULL)
128         *slot = tdef;
129     }
130
131   /* Recurse into superclasses.  */
132   for (i = 0; i < TYPE_N_BASECLASSES (t); ++i)
133     recursively_update_typedef_hash (table, TYPE_BASECLASS (t, i));
134 }
135
136 /* Add template parameters from T to the typedef hash TABLE.  */
137
138 void
139 add_template_parameters (struct typedef_hash_table *table, struct type *t)
140 {
141   int i;
142
143   if (table == NULL)
144     return;
145
146   for (i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (t); ++i)
147     {
148       struct typedef_field *tf;
149       void **slot;
150
151       /* We only want type-valued template parameters in the hash.  */
152       if (SYMBOL_CLASS (TYPE_TEMPLATE_ARGUMENT (t, i)) != LOC_TYPEDEF)
153         continue;
154
155       tf = XOBNEW (&table->storage, struct typedef_field);
156       tf->name = SYMBOL_LINKAGE_NAME (TYPE_TEMPLATE_ARGUMENT (t, i));
157       tf->type = SYMBOL_TYPE (TYPE_TEMPLATE_ARGUMENT (t, i));
158
159       slot = htab_find_slot (table->table, tf, INSERT);
160       if (*slot == NULL)
161         *slot = tf;
162     }
163 }
164
165 /* Create a new typedef-lookup hash table.  */
166
167 struct typedef_hash_table *
168 create_typedef_hash (void)
169 {
170   struct typedef_hash_table *result;
171
172   result = XNEW (struct typedef_hash_table);
173   result->table = htab_create_alloc (10, hash_typedef_field, eq_typedef_field,
174                                      NULL, xcalloc, xfree);
175   obstack_init (&result->storage);
176
177   return result;
178 }
179
180 /* Free a typedef field table.  */
181
182 void
183 free_typedef_hash (struct typedef_hash_table *table)
184 {
185   if (table != NULL)
186     {
187       htab_delete (table->table);
188       obstack_free (&table->storage, NULL);
189       xfree (table);
190     }
191 }
192
193 /* A cleanup for freeing a typedef_hash_table.  */
194
195 static void
196 do_free_typedef_hash (void *arg)
197 {
198   free_typedef_hash ((struct typedef_hash_table *) arg);
199 }
200
201 /* Return a new cleanup that frees TABLE.  */
202
203 struct cleanup *
204 make_cleanup_free_typedef_hash (struct typedef_hash_table *table)
205 {
206   return make_cleanup (do_free_typedef_hash, table);
207 }
208
209 /* Helper function for copy_typedef_hash.  */
210
211 static int
212 copy_typedef_hash_element (void **slot, void *nt)
213 {
214   htab_t new_table = (htab_t) nt;
215   void **new_slot;
216
217   new_slot = htab_find_slot (new_table, *slot, INSERT);
218   if (*new_slot == NULL)
219     *new_slot = *slot;
220
221   return 1;
222 }
223
224 /* Copy a typedef hash.  */
225
226 struct typedef_hash_table *
227 copy_typedef_hash (struct typedef_hash_table *table)
228 {
229   struct typedef_hash_table *result;
230
231   if (table == NULL)
232     return NULL;
233
234   result = create_typedef_hash ();
235   htab_traverse_noresize (table->table, copy_typedef_hash_element,
236                           result->table);
237   return result;
238 }
239
240 /* A cleanup to free the global typedef hash.  */
241
242 static void
243 do_free_global_table (void *arg)
244 {
245   struct type_print_options *flags = (struct type_print_options *) arg;
246
247   free_typedef_hash (flags->global_typedefs);
248   free_ext_lang_type_printers (flags->global_printers);
249 }
250
251 /* Create the global typedef hash.  */
252
253 static struct cleanup *
254 create_global_typedef_table (struct type_print_options *flags)
255 {
256   gdb_assert (flags->global_typedefs == NULL && flags->global_printers == NULL);
257   flags->global_typedefs = create_typedef_hash ();
258   flags->global_printers = start_ext_lang_type_printers ();
259   return make_cleanup (do_free_global_table, flags);
260 }
261
262 /* Look up the type T in the global typedef hash.  If it is found,
263    return the typedef name.  If it is not found, apply the
264    type-printers, if any, given by start_script_type_printers and return the
265    result.  A NULL return means that the name was not found.  */
266
267 static const char *
268 find_global_typedef (const struct type_print_options *flags,
269                      struct type *t)
270 {
271   char *applied;
272   void **slot;
273   struct typedef_field tf, *new_tf;
274
275   if (flags->global_typedefs == NULL)
276     return NULL;
277
278   tf.name = NULL;
279   tf.type = t;
280
281   slot = htab_find_slot (flags->global_typedefs->table, &tf, INSERT);
282   if (*slot != NULL)
283     {
284       new_tf = (struct typedef_field *) *slot;
285       return new_tf->name;
286     }
287
288   /* Put an entry into the hash table now, in case
289      apply_ext_lang_type_printers recurses.  */
290   new_tf = XOBNEW (&flags->global_typedefs->storage, struct typedef_field);
291   new_tf->name = NULL;
292   new_tf->type = t;
293
294   *slot = new_tf;
295
296   applied = apply_ext_lang_type_printers (flags->global_printers, t);
297
298   if (applied != NULL)
299     {
300       new_tf->name
301         = (const char *) obstack_copy0 (&flags->global_typedefs->storage,
302                                         applied, strlen (applied));
303       xfree (applied);
304     }
305
306   return new_tf->name;
307 }
308
309 /* Look up the type T in the typedef hash table in with FLAGS.  If T
310    is in the table, return its short (class-relative) typedef name.
311    Otherwise return NULL.  If the table is NULL, this always returns
312    NULL.  */
313
314 const char *
315 find_typedef_in_hash (const struct type_print_options *flags, struct type *t)
316 {
317   if (flags->local_typedefs != NULL)
318     {
319       struct typedef_field tf, *found;
320
321       tf.name = NULL;
322       tf.type = t;
323       found = (struct typedef_field *) htab_find (flags->local_typedefs->table,
324                                                   &tf);
325
326       if (found != NULL)
327         return found->name;
328     }
329
330   return find_global_typedef (flags, t);
331 }
332
333 \f
334
335 /* Print a description of a type in the format of a 
336    typedef for the current language.
337    NEW is the new name for a type TYPE.  */
338
339 void
340 typedef_print (struct type *type, struct symbol *newobj, struct ui_file *stream)
341 {
342   LA_PRINT_TYPEDEF (type, newobj, stream);
343 }
344
345 /* The default way to print a typedef.  */
346
347 void
348 default_print_typedef (struct type *type, struct symbol *new_symbol,
349                        struct ui_file *stream)
350 {
351   error (_("Language not supported."));
352 }
353
354 /* Print a description of a type TYPE in the form of a declaration of a
355    variable named VARSTRING.  (VARSTRING is demangled if necessary.)
356    Output goes to STREAM (via stdio).
357    If SHOW is positive, we show the contents of the outermost level
358    of structure even if there is a type name that could be used instead.
359    If SHOW is negative, we never show the details of elements' types.  */
360
361 void
362 type_print (struct type *type, const char *varstring, struct ui_file *stream,
363             int show)
364 {
365   LA_PRINT_TYPE (type, varstring, stream, show, 0, &default_ptype_flags);
366 }
367
368 /* Print TYPE to a string, returning it.  The caller is responsible for
369    freeing the string.  */
370
371 std::string
372 type_to_string (struct type *type)
373 {
374   TRY
375     {
376       string_file stb;
377
378       type_print (type, "", &stb, -1);
379       return std::move (stb.string ());
380     }
381   CATCH (except, RETURN_MASK_ALL)
382     {
383     }
384   END_CATCH
385
386   return {};
387 }
388
389 /* Print type of EXP, or last thing in value history if EXP == NULL.
390    show is passed to type_print.  */
391
392 static void
393 whatis_exp (char *exp, int show)
394 {
395   struct value *val;
396   struct cleanup *old_chain;
397   struct type *real_type = NULL;
398   struct type *type;
399   int full = 0;
400   LONGEST top = -1;
401   int using_enc = 0;
402   struct value_print_options opts;
403   struct type_print_options flags = default_ptype_flags;
404
405   old_chain = make_cleanup (null_cleanup, NULL);
406
407   if (exp)
408     {
409       if (*exp == '/')
410         {
411           int seen_one = 0;
412
413           for (++exp; *exp && !isspace (*exp); ++exp)
414             {
415               switch (*exp)
416                 {
417                 case 'r':
418                   flags.raw = 1;
419                   break;
420                 case 'm':
421                   flags.print_methods = 0;
422                   break;
423                 case 'M':
424                   flags.print_methods = 1;
425                   break;
426                 case 't':
427                   flags.print_typedefs = 0;
428                   break;
429                 case 'T':
430                   flags.print_typedefs = 1;
431                   break;
432                 default:
433                   error (_("unrecognized flag '%c'"), *exp);
434                 }
435               seen_one = 1;
436             }
437
438           if (!*exp && !seen_one)
439             error (_("flag expected"));
440           if (!isspace (*exp))
441             error (_("expected space after format"));
442           exp = skip_spaces (exp);
443         }
444
445       expression_up expr = parse_expression (exp);
446       val = evaluate_type (expr.get ());
447     }
448   else
449     val = access_value_history (0);
450
451   type = value_type (val);
452
453   get_user_print_options (&opts);
454   if (opts.objectprint)
455     {
456       if (((TYPE_CODE (type) == TYPE_CODE_PTR)
457            || (TYPE_CODE (type) == TYPE_CODE_REF))
458           && (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_STRUCT))
459         real_type = value_rtti_indirect_type (val, &full, &top, &using_enc);
460       else if (TYPE_CODE (type) == TYPE_CODE_STRUCT)
461         real_type = value_rtti_type (val, &full, &top, &using_enc);
462     }
463
464   printf_filtered ("type = ");
465
466   if (!flags.raw)
467     create_global_typedef_table (&flags);
468
469   if (real_type)
470     {
471       printf_filtered ("/* real type = ");
472       type_print (real_type, "", gdb_stdout, -1);
473       if (! full)
474         printf_filtered (" (incomplete object)");
475       printf_filtered (" */\n");    
476     }
477
478   LA_PRINT_TYPE (type, "", gdb_stdout, show, 0, &flags);
479   printf_filtered ("\n");
480
481   do_cleanups (old_chain);
482 }
483
484 static void
485 whatis_command (char *exp, int from_tty)
486 {
487   /* Most of the time users do not want to see all the fields
488      in a structure.  If they do they can use the "ptype" command.
489      Hence the "-1" below.  */
490   whatis_exp (exp, -1);
491 }
492
493 /* TYPENAME is either the name of a type, or an expression.  */
494
495 static void
496 ptype_command (char *type_name, int from_tty)
497 {
498   whatis_exp (type_name, 1);
499 }
500
501 /* Print integral scalar data VAL, of type TYPE, onto stdio stream STREAM.
502    Used to print data from type structures in a specified type.  For example,
503    array bounds may be characters or booleans in some languages, and this
504    allows the ranges to be printed in their "natural" form rather than as
505    decimal integer values.
506
507    FIXME:  This is here simply because only the type printing routines
508    currently use it, and it wasn't clear if it really belonged somewhere
509    else (like printcmd.c).  There are a lot of other gdb routines that do
510    something similar, but they are generally concerned with printing values
511    that come from the inferior in target byte order and target size.  */
512
513 void
514 print_type_scalar (struct type *type, LONGEST val, struct ui_file *stream)
515 {
516   unsigned int i;
517   unsigned len;
518
519   type = check_typedef (type);
520
521   switch (TYPE_CODE (type))
522     {
523
524     case TYPE_CODE_ENUM:
525       len = TYPE_NFIELDS (type);
526       for (i = 0; i < len; i++)
527         {
528           if (TYPE_FIELD_ENUMVAL (type, i) == val)
529             {
530               break;
531             }
532         }
533       if (i < len)
534         {
535           fputs_filtered (TYPE_FIELD_NAME (type, i), stream);
536         }
537       else
538         {
539           print_longest (stream, 'd', 0, val);
540         }
541       break;
542
543     case TYPE_CODE_INT:
544       print_longest (stream, TYPE_UNSIGNED (type) ? 'u' : 'd', 0, val);
545       break;
546
547     case TYPE_CODE_CHAR:
548       LA_PRINT_CHAR ((unsigned char) val, type, stream);
549       break;
550
551     case TYPE_CODE_BOOL:
552       fprintf_filtered (stream, val ? "TRUE" : "FALSE");
553       break;
554
555     case TYPE_CODE_RANGE:
556       print_type_scalar (TYPE_TARGET_TYPE (type), val, stream);
557       return;
558
559     case TYPE_CODE_UNDEF:
560     case TYPE_CODE_PTR:
561     case TYPE_CODE_ARRAY:
562     case TYPE_CODE_STRUCT:
563     case TYPE_CODE_UNION:
564     case TYPE_CODE_FUNC:
565     case TYPE_CODE_FLT:
566     case TYPE_CODE_VOID:
567     case TYPE_CODE_SET:
568     case TYPE_CODE_STRING:
569     case TYPE_CODE_ERROR:
570     case TYPE_CODE_MEMBERPTR:
571     case TYPE_CODE_METHODPTR:
572     case TYPE_CODE_METHOD:
573     case TYPE_CODE_REF:
574     case TYPE_CODE_NAMESPACE:
575       error (_("internal error: unhandled type in print_type_scalar"));
576       break;
577
578     default:
579       error (_("Invalid type code in symbol table."));
580     }
581   gdb_flush (stream);
582 }
583
584 /* Dump details of a type specified either directly or indirectly.
585    Uses the same sort of type lookup mechanism as ptype_command()
586    and whatis_command().  */
587
588 void
589 maintenance_print_type (char *type_name, int from_tty)
590 {
591   struct value *val;
592   struct type *type;
593
594   if (type_name != NULL)
595     {
596       expression_up expr = parse_expression (type_name);
597       if (expr->elts[0].opcode == OP_TYPE)
598         {
599           /* The user expression names a type directly, just use that type.  */
600           type = expr->elts[1].type;
601         }
602       else
603         {
604           /* The user expression may name a type indirectly by naming an
605              object of that type.  Find that indirectly named type.  */
606           val = evaluate_type (expr.get ());
607           type = value_type (val);
608         }
609       if (type != NULL)
610         {
611           recursive_dump_type (type, 0);
612         }
613     }
614 }
615 \f
616
617 struct cmd_list_element *setprinttypelist;
618
619 struct cmd_list_element *showprinttypelist;
620
621 static void
622 set_print_type (char *arg, int from_tty)
623 {
624   printf_unfiltered (
625      "\"set print type\" must be followed by the name of a subcommand.\n");
626   help_list (setprintlist, "set print type ", all_commands, gdb_stdout);
627 }
628
629 static void
630 show_print_type (char *args, int from_tty)
631 {
632   cmd_show_list (showprinttypelist, from_tty, "");
633 }
634
635 static int print_methods = 1;
636
637 static void
638 set_print_type_methods (char *args, int from_tty, struct cmd_list_element *c)
639 {
640   default_ptype_flags.print_methods = print_methods;
641 }
642
643 static void
644 show_print_type_methods (struct ui_file *file, int from_tty,
645                          struct cmd_list_element *c, const char *value)
646 {
647   fprintf_filtered (file, _("Printing of methods defined in a class in %s\n"),
648                     value);
649 }
650
651 static int print_typedefs = 1;
652
653 static void
654 set_print_type_typedefs (char *args, int from_tty, struct cmd_list_element *c)
655 {
656   default_ptype_flags.print_typedefs = print_typedefs;
657 }
658
659 static void
660 show_print_type_typedefs (struct ui_file *file, int from_tty,
661                          struct cmd_list_element *c, const char *value)
662 {
663   fprintf_filtered (file, _("Printing of typedefs defined in a class in %s\n"),
664                     value);
665 }
666
667 void
668 _initialize_typeprint (void)
669 {
670   struct cmd_list_element *c;
671
672   c = add_com ("ptype", class_vars, ptype_command, _("\
673 Print definition of type TYPE.\n\
674 Usage: ptype[/FLAGS] TYPE | EXPRESSION\n\
675 Argument may be any type (for example a type name defined by typedef,\n\
676 or \"struct STRUCT-TAG\" or \"class CLASS-NAME\" or \"union UNION-TAG\"\n\
677 or \"enum ENUM-TAG\") or an expression.\n\
678 The selected stack frame's lexical context is used to look up the name.\n\
679 Contrary to \"whatis\", \"ptype\" always unrolls any typedefs.\n\
680 \n\
681 Available FLAGS are:\n\
682   /r    print in \"raw\" form; do not substitute typedefs\n\
683   /m    do not print methods defined in a class\n\
684   /M    print methods defined in a class\n\
685   /t    do not print typedefs defined in a class\n\
686   /T    print typedefs defined in a class"));
687   set_cmd_completer (c, expression_completer);
688
689   c = add_com ("whatis", class_vars, whatis_command,
690                _("Print data type of expression EXP.\n\
691 Only one level of typedefs is unrolled.  See also \"ptype\"."));
692   set_cmd_completer (c, expression_completer);
693
694   add_prefix_cmd ("type", no_class, show_print_type,
695                   _("Generic command for showing type-printing settings."),
696                   &showprinttypelist, "show print type ", 0, &showprintlist);
697   add_prefix_cmd ("type", no_class, set_print_type,
698                   _("Generic command for setting how types print."),
699                   &setprinttypelist, "show print type ", 0, &setprintlist);
700
701   add_setshow_boolean_cmd ("methods", no_class, &print_methods,
702                            _("\
703 Set printing of methods defined in classes."), _("\
704 Show printing of methods defined in classes."), NULL,
705                            set_print_type_methods,
706                            show_print_type_methods,
707                            &setprinttypelist, &showprinttypelist);
708   add_setshow_boolean_cmd ("typedefs", no_class, &print_typedefs,
709                            _("\
710 Set printing of typedefs defined in classes."), _("\
711 Show printing of typedefs defined in classes."), NULL,
712                            set_print_type_typedefs,
713                            show_print_type_typedefs,
714                            &setprinttypelist, &showprinttypelist);
715 }
716
717 /* Print <not allocated> status to stream STREAM.  */
718
719 void
720 val_print_not_allocated (struct ui_file *stream)
721 {
722   fprintf_filtered (stream, _("<not allocated>"));
723 }
724
725 /* Print <not associated> status to stream STREAM.  */
726
727 void
728 val_print_not_associated (struct ui_file *stream)
729 {
730   fprintf_filtered (stream, _("<not associated>"));
731 }
732