* ada-lang.c (user_select_syms, ada_print_subexp): Pass flags
[external/binutils.git] / gdb / gnu-v3-abi.c
1 /* Abstraction of GNU v3 abi.
2    Contributed by Jim Blandy <jimb@redhat.com>
3
4    Copyright (C) 2001-2003, 2005-2012 Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "value.h"
23 #include "cp-abi.h"
24 #include "cp-support.h"
25 #include "demangle.h"
26 #include "objfiles.h"
27 #include "valprint.h"
28 #include "c-lang.h"
29 #include "exceptions.h"
30 #include "typeprint.h"
31
32 #include "gdb_assert.h"
33 #include "gdb_string.h"
34
35 static struct cp_abi_ops gnu_v3_abi_ops;
36
37 static int
38 gnuv3_is_vtable_name (const char *name)
39 {
40   return strncmp (name, "_ZTV", 4) == 0;
41 }
42
43 static int
44 gnuv3_is_operator_name (const char *name)
45 {
46   return strncmp (name, "operator", 8) == 0;
47 }
48
49
50 /* To help us find the components of a vtable, we build ourselves a
51    GDB type object representing the vtable structure.  Following the
52    V3 ABI, it goes something like this:
53
54    struct gdb_gnu_v3_abi_vtable {
55
56      / * An array of virtual call and virtual base offsets.  The real
57          length of this array depends on the class hierarchy; we use
58          negative subscripts to access the elements.  Yucky, but
59          better than the alternatives.  * /
60      ptrdiff_t vcall_and_vbase_offsets[0];
61
62      / * The offset from a virtual pointer referring to this table
63          to the top of the complete object.  * /
64      ptrdiff_t offset_to_top;
65
66      / * The type_info pointer for this class.  This is really a
67          std::type_info *, but GDB doesn't really look at the
68          type_info object itself, so we don't bother to get the type
69          exactly right.  * /
70      void *type_info;
71
72      / * Virtual table pointers in objects point here.  * /
73
74      / * Virtual function pointers.  Like the vcall/vbase array, the
75          real length of this table depends on the class hierarchy.  * /
76      void (*virtual_functions[0]) ();
77
78    };
79
80    The catch, of course, is that the exact layout of this table
81    depends on the ABI --- word size, endianness, alignment, etc.  So
82    the GDB type object is actually a per-architecture kind of thing.
83
84    vtable_type_gdbarch_data is a gdbarch per-architecture data pointer
85    which refers to the struct type * for this structure, laid out
86    appropriately for the architecture.  */
87 static struct gdbarch_data *vtable_type_gdbarch_data;
88
89
90 /* Human-readable names for the numbers of the fields above.  */
91 enum {
92   vtable_field_vcall_and_vbase_offsets,
93   vtable_field_offset_to_top,
94   vtable_field_type_info,
95   vtable_field_virtual_functions
96 };
97
98
99 /* Return a GDB type representing `struct gdb_gnu_v3_abi_vtable',
100    described above, laid out appropriately for ARCH.
101
102    We use this function as the gdbarch per-architecture data
103    initialization function.  */
104 static void *
105 build_gdb_vtable_type (struct gdbarch *arch)
106 {
107   struct type *t;
108   struct field *field_list, *field;
109   int offset;
110
111   struct type *void_ptr_type
112     = builtin_type (arch)->builtin_data_ptr;
113   struct type *ptr_to_void_fn_type
114     = builtin_type (arch)->builtin_func_ptr;
115
116   /* ARCH can't give us the true ptrdiff_t type, so we guess.  */
117   struct type *ptrdiff_type
118     = arch_integer_type (arch, gdbarch_ptr_bit (arch), 0, "ptrdiff_t");
119
120   /* We assume no padding is necessary, since GDB doesn't know
121      anything about alignment at the moment.  If this assumption bites
122      us, we should add a gdbarch method which, given a type, returns
123      the alignment that type requires, and then use that here.  */
124
125   /* Build the field list.  */
126   field_list = xmalloc (sizeof (struct field [4]));
127   memset (field_list, 0, sizeof (struct field [4]));
128   field = &field_list[0];
129   offset = 0;
130
131   /* ptrdiff_t vcall_and_vbase_offsets[0]; */
132   FIELD_NAME (*field) = "vcall_and_vbase_offsets";
133   FIELD_TYPE (*field) = lookup_array_range_type (ptrdiff_type, 0, -1);
134   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
135   offset += TYPE_LENGTH (FIELD_TYPE (*field));
136   field++;
137
138   /* ptrdiff_t offset_to_top; */
139   FIELD_NAME (*field) = "offset_to_top";
140   FIELD_TYPE (*field) = ptrdiff_type;
141   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
142   offset += TYPE_LENGTH (FIELD_TYPE (*field));
143   field++;
144
145   /* void *type_info; */
146   FIELD_NAME (*field) = "type_info";
147   FIELD_TYPE (*field) = void_ptr_type;
148   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
149   offset += TYPE_LENGTH (FIELD_TYPE (*field));
150   field++;
151
152   /* void (*virtual_functions[0]) (); */
153   FIELD_NAME (*field) = "virtual_functions";
154   FIELD_TYPE (*field) = lookup_array_range_type (ptr_to_void_fn_type, 0, -1);
155   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
156   offset += TYPE_LENGTH (FIELD_TYPE (*field));
157   field++;
158
159   /* We assumed in the allocation above that there were four fields.  */
160   gdb_assert (field == (field_list + 4));
161
162   t = arch_type (arch, TYPE_CODE_STRUCT, offset, NULL);
163   TYPE_NFIELDS (t) = field - field_list;
164   TYPE_FIELDS (t) = field_list;
165   TYPE_TAG_NAME (t) = "gdb_gnu_v3_abi_vtable";
166   INIT_CPLUS_SPECIFIC (t);
167
168   return t;
169 }
170
171
172 /* Return the ptrdiff_t type used in the vtable type.  */
173 static struct type *
174 vtable_ptrdiff_type (struct gdbarch *gdbarch)
175 {
176   struct type *vtable_type = gdbarch_data (gdbarch, vtable_type_gdbarch_data);
177
178   /* The "offset_to_top" field has the appropriate (ptrdiff_t) type.  */
179   return TYPE_FIELD_TYPE (vtable_type, vtable_field_offset_to_top);
180 }
181
182 /* Return the offset from the start of the imaginary `struct
183    gdb_gnu_v3_abi_vtable' object to the vtable's "address point"
184    (i.e., where objects' virtual table pointers point).  */
185 static int
186 vtable_address_point_offset (struct gdbarch *gdbarch)
187 {
188   struct type *vtable_type = gdbarch_data (gdbarch, vtable_type_gdbarch_data);
189
190   return (TYPE_FIELD_BITPOS (vtable_type, vtable_field_virtual_functions)
191           / TARGET_CHAR_BIT);
192 }
193
194
195 /* Determine whether structure TYPE is a dynamic class.  Cache the
196    result.  */
197
198 static int
199 gnuv3_dynamic_class (struct type *type)
200 {
201   int fieldnum, fieldelem;
202
203   if (TYPE_CPLUS_DYNAMIC (type))
204     return TYPE_CPLUS_DYNAMIC (type) == 1;
205
206   ALLOCATE_CPLUS_STRUCT_TYPE (type);
207
208   for (fieldnum = 0; fieldnum < TYPE_N_BASECLASSES (type); fieldnum++)
209     if (BASETYPE_VIA_VIRTUAL (type, fieldnum)
210         || gnuv3_dynamic_class (TYPE_FIELD_TYPE (type, fieldnum)))
211       {
212         TYPE_CPLUS_DYNAMIC (type) = 1;
213         return 1;
214       }
215
216   for (fieldnum = 0; fieldnum < TYPE_NFN_FIELDS (type); fieldnum++)
217     for (fieldelem = 0; fieldelem < TYPE_FN_FIELDLIST_LENGTH (type, fieldnum);
218          fieldelem++)
219       {
220         struct fn_field *f = TYPE_FN_FIELDLIST1 (type, fieldnum);
221
222         if (TYPE_FN_FIELD_VIRTUAL_P (f, fieldelem))
223           {
224             TYPE_CPLUS_DYNAMIC (type) = 1;
225             return 1;
226           }
227       }
228
229   TYPE_CPLUS_DYNAMIC (type) = -1;
230   return 0;
231 }
232
233 /* Find the vtable for a value of CONTAINER_TYPE located at
234    CONTAINER_ADDR.  Return a value of the correct vtable type for this
235    architecture, or NULL if CONTAINER does not have a vtable.  */
236
237 static struct value *
238 gnuv3_get_vtable (struct gdbarch *gdbarch,
239                   struct type *container_type, CORE_ADDR container_addr)
240 {
241   struct type *vtable_type = gdbarch_data (gdbarch,
242                                            vtable_type_gdbarch_data);
243   struct type *vtable_pointer_type;
244   struct value *vtable_pointer;
245   CORE_ADDR vtable_address;
246
247   /* If this type does not have a virtual table, don't read the first
248      field.  */
249   if (!gnuv3_dynamic_class (check_typedef (container_type)))
250     return NULL;
251
252   /* We do not consult the debug information to find the virtual table.
253      The ABI specifies that it is always at offset zero in any class,
254      and debug information may not represent it.
255
256      We avoid using value_contents on principle, because the object might
257      be large.  */
258
259   /* Find the type "pointer to virtual table".  */
260   vtable_pointer_type = lookup_pointer_type (vtable_type);
261
262   /* Load it from the start of the class.  */
263   vtable_pointer = value_at (vtable_pointer_type, container_addr);
264   vtable_address = value_as_address (vtable_pointer);
265
266   /* Correct it to point at the start of the virtual table, rather
267      than the address point.  */
268   return value_at_lazy (vtable_type,
269                         vtable_address
270                         - vtable_address_point_offset (gdbarch));
271 }
272
273
274 static struct type *
275 gnuv3_rtti_type (struct value *value,
276                  int *full_p, int *top_p, int *using_enc_p)
277 {
278   struct gdbarch *gdbarch;
279   struct type *values_type = check_typedef (value_type (value));
280   struct value *vtable;
281   struct minimal_symbol *vtable_symbol;
282   const char *vtable_symbol_name;
283   const char *class_name;
284   struct type *run_time_type;
285   LONGEST offset_to_top;
286
287   /* We only have RTTI for class objects.  */
288   if (TYPE_CODE (values_type) != TYPE_CODE_CLASS)
289     return NULL;
290
291   /* Java doesn't have RTTI following the C++ ABI.  */
292   if (TYPE_CPLUS_REALLY_JAVA (values_type))
293     return NULL;
294
295   /* Determine architecture.  */
296   gdbarch = get_type_arch (values_type);
297
298   if (using_enc_p)
299     *using_enc_p = 0;
300
301   vtable = gnuv3_get_vtable (gdbarch, value_type (value),
302                              value_as_address (value_addr (value)));
303   if (vtable == NULL)
304     return NULL;
305
306   /* Find the linker symbol for this vtable.  */
307   vtable_symbol
308     = lookup_minimal_symbol_by_pc (value_address (vtable)
309                                    + value_embedded_offset (vtable));
310   if (! vtable_symbol)
311     return NULL;
312   
313   /* The symbol's demangled name should be something like "vtable for
314      CLASS", where CLASS is the name of the run-time type of VALUE.
315      If we didn't like this approach, we could instead look in the
316      type_info object itself to get the class name.  But this way
317      should work just as well, and doesn't read target memory.  */
318   vtable_symbol_name = SYMBOL_DEMANGLED_NAME (vtable_symbol);
319   if (vtable_symbol_name == NULL
320       || strncmp (vtable_symbol_name, "vtable for ", 11))
321     {
322       warning (_("can't find linker symbol for virtual table for `%s' value"),
323                TYPE_SAFE_NAME (values_type));
324       if (vtable_symbol_name)
325         warning (_("  found `%s' instead"), vtable_symbol_name);
326       return NULL;
327     }
328   class_name = vtable_symbol_name + 11;
329
330   /* Try to look up the class name as a type name.  */
331   /* FIXME: chastain/2003-11-26: block=NULL is bogus.  See pr gdb/1465.  */
332   run_time_type = cp_lookup_rtti_type (class_name, NULL);
333   if (run_time_type == NULL)
334     return NULL;
335
336   /* Get the offset from VALUE to the top of the complete object.
337      NOTE: this is the reverse of the meaning of *TOP_P.  */
338   offset_to_top
339     = value_as_long (value_field (vtable, vtable_field_offset_to_top));
340
341   if (full_p)
342     *full_p = (- offset_to_top == value_embedded_offset (value)
343                && (TYPE_LENGTH (value_enclosing_type (value))
344                    >= TYPE_LENGTH (run_time_type)));
345   if (top_p)
346     *top_p = - offset_to_top;
347   return run_time_type;
348 }
349
350 /* Return a function pointer for CONTAINER's VTABLE_INDEX'th virtual
351    function, of type FNTYPE.  */
352
353 static struct value *
354 gnuv3_get_virtual_fn (struct gdbarch *gdbarch, struct value *container,
355                       struct type *fntype, int vtable_index)
356 {
357   struct value *vtable, *vfn;
358
359   /* Every class with virtual functions must have a vtable.  */
360   vtable = gnuv3_get_vtable (gdbarch, value_type (container),
361                              value_as_address (value_addr (container)));
362   gdb_assert (vtable != NULL);
363
364   /* Fetch the appropriate function pointer from the vtable.  */
365   vfn = value_subscript (value_field (vtable, vtable_field_virtual_functions),
366                          vtable_index);
367
368   /* If this architecture uses function descriptors directly in the vtable,
369      then the address of the vtable entry is actually a "function pointer"
370      (i.e. points to the descriptor).  We don't need to scale the index
371      by the size of a function descriptor; GCC does that before outputing
372      debug information.  */
373   if (gdbarch_vtable_function_descriptors (gdbarch))
374     vfn = value_addr (vfn);
375
376   /* Cast the function pointer to the appropriate type.  */
377   vfn = value_cast (lookup_pointer_type (fntype), vfn);
378
379   return vfn;
380 }
381
382 /* GNU v3 implementation of value_virtual_fn_field.  See cp-abi.h
383    for a description of the arguments.  */
384
385 static struct value *
386 gnuv3_virtual_fn_field (struct value **value_p,
387                         struct fn_field *f, int j,
388                         struct type *vfn_base, int offset)
389 {
390   struct type *values_type = check_typedef (value_type (*value_p));
391   struct gdbarch *gdbarch;
392
393   /* Some simple sanity checks.  */
394   if (TYPE_CODE (values_type) != TYPE_CODE_CLASS)
395     error (_("Only classes can have virtual functions."));
396
397   /* Determine architecture.  */
398   gdbarch = get_type_arch (values_type);
399
400   /* Cast our value to the base class which defines this virtual
401      function.  This takes care of any necessary `this'
402      adjustments.  */
403   if (vfn_base != values_type)
404     *value_p = value_cast (vfn_base, *value_p);
405
406   return gnuv3_get_virtual_fn (gdbarch, *value_p, TYPE_FN_FIELD_TYPE (f, j),
407                                TYPE_FN_FIELD_VOFFSET (f, j));
408 }
409
410 /* Compute the offset of the baseclass which is
411    the INDEXth baseclass of class TYPE,
412    for value at VALADDR (in host) at ADDRESS (in target).
413    The result is the offset of the baseclass value relative
414    to (the address of)(ARG) + OFFSET.
415
416    -1 is returned on error.  */
417
418 static int
419 gnuv3_baseclass_offset (struct type *type, int index,
420                         const bfd_byte *valaddr, int embedded_offset,
421                         CORE_ADDR address, const struct value *val)
422 {
423   struct gdbarch *gdbarch;
424   struct type *ptr_type;
425   struct value *vtable;
426   struct value *vbase_array;
427   long int cur_base_offset, base_offset;
428
429   /* Determine architecture.  */
430   gdbarch = get_type_arch (type);
431   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
432
433   /* If it isn't a virtual base, this is easy.  The offset is in the
434      type definition.  Likewise for Java, which doesn't really have
435      virtual inheritance in the C++ sense.  */
436   if (!BASETYPE_VIA_VIRTUAL (type, index) || TYPE_CPLUS_REALLY_JAVA (type))
437     return TYPE_BASECLASS_BITPOS (type, index) / 8;
438
439   /* To access a virtual base, we need to use the vbase offset stored in
440      our vtable.  Recent GCC versions provide this information.  If it isn't
441      available, we could get what we needed from RTTI, or from drawing the
442      complete inheritance graph based on the debug info.  Neither is
443      worthwhile.  */
444   cur_base_offset = TYPE_BASECLASS_BITPOS (type, index) / 8;
445   if (cur_base_offset >= - vtable_address_point_offset (gdbarch))
446     error (_("Expected a negative vbase offset (old compiler?)"));
447
448   cur_base_offset = cur_base_offset + vtable_address_point_offset (gdbarch);
449   if ((- cur_base_offset) % TYPE_LENGTH (ptr_type) != 0)
450     error (_("Misaligned vbase offset."));
451   cur_base_offset = cur_base_offset / ((int) TYPE_LENGTH (ptr_type));
452
453   vtable = gnuv3_get_vtable (gdbarch, type, address + embedded_offset);
454   gdb_assert (vtable != NULL);
455   vbase_array = value_field (vtable, vtable_field_vcall_and_vbase_offsets);
456   base_offset = value_as_long (value_subscript (vbase_array, cur_base_offset));
457   return base_offset;
458 }
459
460 /* Locate a virtual method in DOMAIN or its non-virtual base classes
461    which has virtual table index VOFFSET.  The method has an associated
462    "this" adjustment of ADJUSTMENT bytes.  */
463
464 static const char *
465 gnuv3_find_method_in (struct type *domain, CORE_ADDR voffset,
466                       LONGEST adjustment)
467 {
468   int i;
469
470   /* Search this class first.  */
471   if (adjustment == 0)
472     {
473       int len;
474
475       len = TYPE_NFN_FIELDS (domain);
476       for (i = 0; i < len; i++)
477         {
478           int len2, j;
479           struct fn_field *f;
480
481           f = TYPE_FN_FIELDLIST1 (domain, i);
482           len2 = TYPE_FN_FIELDLIST_LENGTH (domain, i);
483
484           check_stub_method_group (domain, i);
485           for (j = 0; j < len2; j++)
486             if (TYPE_FN_FIELD_VOFFSET (f, j) == voffset)
487               return TYPE_FN_FIELD_PHYSNAME (f, j);
488         }
489     }
490
491   /* Next search non-virtual bases.  If it's in a virtual base,
492      we're out of luck.  */
493   for (i = 0; i < TYPE_N_BASECLASSES (domain); i++)
494     {
495       int pos;
496       struct type *basetype;
497
498       if (BASETYPE_VIA_VIRTUAL (domain, i))
499         continue;
500
501       pos = TYPE_BASECLASS_BITPOS (domain, i) / 8;
502       basetype = TYPE_FIELD_TYPE (domain, i);
503       /* Recurse with a modified adjustment.  We don't need to adjust
504          voffset.  */
505       if (adjustment >= pos && adjustment < pos + TYPE_LENGTH (basetype))
506         return gnuv3_find_method_in (basetype, voffset, adjustment - pos);
507     }
508
509   return NULL;
510 }
511
512 /* Decode GNU v3 method pointer.  */
513
514 static int
515 gnuv3_decode_method_ptr (struct gdbarch *gdbarch,
516                          const gdb_byte *contents,
517                          CORE_ADDR *value_p,
518                          LONGEST *adjustment_p)
519 {
520   struct type *funcptr_type = builtin_type (gdbarch)->builtin_func_ptr;
521   struct type *offset_type = vtable_ptrdiff_type (gdbarch);
522   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
523   CORE_ADDR ptr_value;
524   LONGEST voffset, adjustment;
525   int vbit;
526
527   /* Extract the pointer to member.  The first element is either a pointer
528      or a vtable offset.  For pointers, we need to use extract_typed_address
529      to allow the back-end to convert the pointer to a GDB address -- but
530      vtable offsets we must handle as integers.  At this point, we do not
531      yet know which case we have, so we extract the value under both
532      interpretations and choose the right one later on.  */
533   ptr_value = extract_typed_address (contents, funcptr_type);
534   voffset = extract_signed_integer (contents,
535                                     TYPE_LENGTH (funcptr_type), byte_order);
536   contents += TYPE_LENGTH (funcptr_type);
537   adjustment = extract_signed_integer (contents,
538                                        TYPE_LENGTH (offset_type), byte_order);
539
540   if (!gdbarch_vbit_in_delta (gdbarch))
541     {
542       vbit = voffset & 1;
543       voffset = voffset ^ vbit;
544     }
545   else
546     {
547       vbit = adjustment & 1;
548       adjustment = adjustment >> 1;
549     }
550
551   *value_p = vbit? voffset : ptr_value;
552   *adjustment_p = adjustment;
553   return vbit;
554 }
555
556 /* GNU v3 implementation of cplus_print_method_ptr.  */
557
558 static void
559 gnuv3_print_method_ptr (const gdb_byte *contents,
560                         struct type *type,
561                         struct ui_file *stream)
562 {
563   struct type *domain = TYPE_DOMAIN_TYPE (type);
564   struct gdbarch *gdbarch = get_type_arch (domain);
565   CORE_ADDR ptr_value;
566   LONGEST adjustment;
567   int vbit;
568
569   /* Extract the pointer to member.  */
570   vbit = gnuv3_decode_method_ptr (gdbarch, contents, &ptr_value, &adjustment);
571
572   /* Check for NULL.  */
573   if (ptr_value == 0 && vbit == 0)
574     {
575       fprintf_filtered (stream, "NULL");
576       return;
577     }
578
579   /* Search for a virtual method.  */
580   if (vbit)
581     {
582       CORE_ADDR voffset;
583       const char *physname;
584
585       /* It's a virtual table offset, maybe in this class.  Search
586          for a field with the correct vtable offset.  First convert it
587          to an index, as used in TYPE_FN_FIELD_VOFFSET.  */
588       voffset = ptr_value / TYPE_LENGTH (vtable_ptrdiff_type (gdbarch));
589
590       physname = gnuv3_find_method_in (domain, voffset, adjustment);
591
592       /* If we found a method, print that.  We don't bother to disambiguate
593          possible paths to the method based on the adjustment.  */
594       if (physname)
595         {
596           char *demangled_name = cplus_demangle (physname,
597                                                  DMGL_ANSI | DMGL_PARAMS);
598
599           fprintf_filtered (stream, "&virtual ");
600           if (demangled_name == NULL)
601             fputs_filtered (physname, stream);
602           else
603             {
604               fputs_filtered (demangled_name, stream);
605               xfree (demangled_name);
606             }
607           return;
608         }
609     }
610   else if (ptr_value != 0)
611     {
612       /* Found a non-virtual function: print out the type.  */
613       fputs_filtered ("(", stream);
614       c_print_type (type, "", stream, -1, 0, &type_print_raw_options);
615       fputs_filtered (") ", stream);
616     }
617
618   /* We didn't find it; print the raw data.  */
619   if (vbit)
620     {
621       fprintf_filtered (stream, "&virtual table offset ");
622       print_longest (stream, 'd', 1, ptr_value);
623     }
624   else
625     {
626       struct value_print_options opts;
627
628       get_user_print_options (&opts);
629       print_address_demangle (&opts, gdbarch, ptr_value, stream, demangle);
630     }
631
632   if (adjustment)
633     {
634       fprintf_filtered (stream, ", this adjustment ");
635       print_longest (stream, 'd', 1, adjustment);
636     }
637 }
638
639 /* GNU v3 implementation of cplus_method_ptr_size.  */
640
641 static int
642 gnuv3_method_ptr_size (struct type *type)
643 {
644   struct gdbarch *gdbarch = get_type_arch (type);
645
646   return 2 * TYPE_LENGTH (builtin_type (gdbarch)->builtin_data_ptr);
647 }
648
649 /* GNU v3 implementation of cplus_make_method_ptr.  */
650
651 static void
652 gnuv3_make_method_ptr (struct type *type, gdb_byte *contents,
653                        CORE_ADDR value, int is_virtual)
654 {
655   struct gdbarch *gdbarch = get_type_arch (type);
656   int size = TYPE_LENGTH (builtin_type (gdbarch)->builtin_data_ptr);
657   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
658
659   /* FIXME drow/2006-12-24: The adjustment of "this" is currently
660      always zero, since the method pointer is of the correct type.
661      But if the method pointer came from a base class, this is
662      incorrect - it should be the offset to the base.  The best
663      fix might be to create the pointer to member pointing at the
664      base class and cast it to the derived class, but that requires
665      support for adjusting pointers to members when casting them -
666      not currently supported by GDB.  */
667
668   if (!gdbarch_vbit_in_delta (gdbarch))
669     {
670       store_unsigned_integer (contents, size, byte_order, value | is_virtual);
671       store_unsigned_integer (contents + size, size, byte_order, 0);
672     }
673   else
674     {
675       store_unsigned_integer (contents, size, byte_order, value);
676       store_unsigned_integer (contents + size, size, byte_order, is_virtual);
677     }
678 }
679
680 /* GNU v3 implementation of cplus_method_ptr_to_value.  */
681
682 static struct value *
683 gnuv3_method_ptr_to_value (struct value **this_p, struct value *method_ptr)
684 {
685   struct gdbarch *gdbarch;
686   const gdb_byte *contents = value_contents (method_ptr);
687   CORE_ADDR ptr_value;
688   struct type *domain_type, *final_type, *method_type;
689   LONGEST adjustment;
690   int vbit;
691
692   domain_type = TYPE_DOMAIN_TYPE (check_typedef (value_type (method_ptr)));
693   final_type = lookup_pointer_type (domain_type);
694
695   method_type = TYPE_TARGET_TYPE (check_typedef (value_type (method_ptr)));
696
697   /* Extract the pointer to member.  */
698   gdbarch = get_type_arch (domain_type);
699   vbit = gnuv3_decode_method_ptr (gdbarch, contents, &ptr_value, &adjustment);
700
701   /* First convert THIS to match the containing type of the pointer to
702      member.  This cast may adjust the value of THIS.  */
703   *this_p = value_cast (final_type, *this_p);
704
705   /* Then apply whatever adjustment is necessary.  This creates a somewhat
706      strange pointer: it claims to have type FINAL_TYPE, but in fact it
707      might not be a valid FINAL_TYPE.  For instance, it might be a
708      base class of FINAL_TYPE.  And if it's not the primary base class,
709      then printing it out as a FINAL_TYPE object would produce some pretty
710      garbage.
711
712      But we don't really know the type of the first argument in
713      METHOD_TYPE either, which is why this happens.  We can't
714      dereference this later as a FINAL_TYPE, but once we arrive in the
715      called method we'll have debugging information for the type of
716      "this" - and that'll match the value we produce here.
717
718      You can provoke this case by casting a Base::* to a Derived::*, for
719      instance.  */
720   *this_p = value_cast (builtin_type (gdbarch)->builtin_data_ptr, *this_p);
721   *this_p = value_ptradd (*this_p, adjustment);
722   *this_p = value_cast (final_type, *this_p);
723
724   if (vbit)
725     {
726       LONGEST voffset;
727
728       voffset = ptr_value / TYPE_LENGTH (vtable_ptrdiff_type (gdbarch));
729       return gnuv3_get_virtual_fn (gdbarch, value_ind (*this_p),
730                                    method_type, voffset);
731     }
732   else
733     return value_from_pointer (lookup_pointer_type (method_type), ptr_value);
734 }
735
736 /* Objects of this type are stored in a hash table and a vector when
737    printing the vtables for a class.  */
738
739 struct value_and_voffset
740 {
741   /* The value representing the object.  */
742   struct value *value;
743
744   /* The maximum vtable offset we've found for any object at this
745      offset in the outermost object.  */
746   int max_voffset;
747 };
748
749 typedef struct value_and_voffset *value_and_voffset_p;
750 DEF_VEC_P (value_and_voffset_p);
751
752 /* Hash function for value_and_voffset.  */
753
754 static hashval_t
755 hash_value_and_voffset (const void *p)
756 {
757   const struct value_and_voffset *o = p;
758
759   return value_address (o->value) + value_embedded_offset (o->value);
760 }
761
762 /* Equality function for value_and_voffset.  */
763
764 static int
765 eq_value_and_voffset (const void *a, const void *b)
766 {
767   const struct value_and_voffset *ova = a;
768   const struct value_and_voffset *ovb = b;
769
770   return (value_address (ova->value) + value_embedded_offset (ova->value)
771           == value_address (ovb->value) + value_embedded_offset (ovb->value));
772 }
773
774 /* qsort comparison function for value_and_voffset.  */
775
776 static int
777 compare_value_and_voffset (const void *a, const void *b)
778 {
779   const struct value_and_voffset * const *ova = a;
780   CORE_ADDR addra = (value_address ((*ova)->value)
781                      + value_embedded_offset ((*ova)->value));
782   const struct value_and_voffset * const *ovb = b;
783   CORE_ADDR addrb = (value_address ((*ovb)->value)
784                      + value_embedded_offset ((*ovb)->value));
785
786   if (addra < addrb)
787     return -1;
788   if (addra > addrb)
789     return 1;
790   return 0;
791 }
792
793 /* A helper function used when printing vtables.  This determines the
794    key (most derived) sub-object at each address and also computes the
795    maximum vtable offset seen for the corresponding vtable.  Updates
796    OFFSET_HASH and OFFSET_VEC with a new value_and_voffset object, if
797    needed.  VALUE is the object to examine.  */
798
799 static void
800 compute_vtable_size (htab_t offset_hash,
801                      VEC (value_and_voffset_p) **offset_vec,
802                      struct value *value)
803 {
804   int i;
805   struct type *type = check_typedef (value_type (value));
806   void **slot;
807   struct value_and_voffset search_vo, *current_vo;
808   CORE_ADDR addr = value_address (value) + value_embedded_offset (value);
809
810   /* If the object is not dynamic, then we are done; as it cannot have
811      dynamic base types either.  */
812   if (!gnuv3_dynamic_class (type))
813     return;
814
815   /* Update the hash and the vec, if needed.  */
816   search_vo.value = value;
817   slot = htab_find_slot (offset_hash, &search_vo, INSERT);
818   if (*slot)
819     current_vo = *slot;
820   else
821     {
822       current_vo = XNEW (struct value_and_voffset);
823       current_vo->value = value;
824       current_vo->max_voffset = -1;
825       *slot = current_vo;
826       VEC_safe_push (value_and_voffset_p, *offset_vec, current_vo);
827     }
828
829   /* Update the value_and_voffset object with the highest vtable
830      offset from this class.  */
831   for (i = 0; i < TYPE_NFN_FIELDS (type); ++i)
832     {
833       int j;
834       struct fn_field *fn = TYPE_FN_FIELDLIST1 (type, i);
835
836       for (j = 0; j < TYPE_FN_FIELDLIST_LENGTH (type, i); ++j)
837         {
838           if (TYPE_FN_FIELD_VIRTUAL_P (fn, j))
839             {
840               int voffset = TYPE_FN_FIELD_VOFFSET (fn, j);
841
842               if (voffset > current_vo->max_voffset)
843                 current_vo->max_voffset = voffset;
844             }
845         }
846     }
847
848   /* Recurse into base classes.  */
849   for (i = 0; i < TYPE_N_BASECLASSES (type); ++i)
850     compute_vtable_size (offset_hash, offset_vec, value_field (value, i));
851 }
852
853 /* Helper for gnuv3_print_vtable that prints a single vtable.  */
854
855 static void
856 print_one_vtable (struct gdbarch *gdbarch, struct value *value,
857                   int max_voffset,
858                   struct value_print_options *opts)
859 {
860   int i;
861   struct type *type = check_typedef (value_type (value));
862   struct value *vtable;
863   CORE_ADDR vt_addr;
864
865   vtable = gnuv3_get_vtable (gdbarch, type,
866                              value_address (value)
867                              + value_embedded_offset (value));
868   vt_addr = value_address (value_field (vtable,
869                                         vtable_field_virtual_functions));
870
871   printf_filtered (_("vtable for '%s' @ %s (subobject @ %s):\n"),
872                    TYPE_SAFE_NAME (type),
873                    paddress (gdbarch, vt_addr),
874                    paddress (gdbarch, (value_address (value)
875                                        + value_embedded_offset (value))));
876
877   for (i = 0; i <= max_voffset; ++i)
878     {
879       /* Initialize it just to avoid a GCC false warning.  */
880       CORE_ADDR addr = 0;
881       struct value *vfn;
882       volatile struct gdb_exception ex;
883
884       printf_filtered ("[%d]: ", i);
885
886       vfn = value_subscript (value_field (vtable,
887                                           vtable_field_virtual_functions),
888                              i);
889
890       if (gdbarch_vtable_function_descriptors (gdbarch))
891         vfn = value_addr (vfn);
892
893       TRY_CATCH (ex, RETURN_MASK_ERROR)
894         {
895           addr = value_as_address (vfn);
896         }
897       if (ex.reason < 0)
898         printf_filtered (_("<error: %s>"), ex.message);
899       else
900         print_function_pointer_address (opts, gdbarch, addr, gdb_stdout);
901       printf_filtered ("\n");
902     }
903 }
904
905 /* Implementation of the print_vtable method.  */
906
907 static void
908 gnuv3_print_vtable (struct value *value)
909 {
910   struct gdbarch *gdbarch;
911   struct type *type;
912   struct value *vtable;
913   struct value_print_options opts;
914   htab_t offset_hash;
915   struct cleanup *cleanup;
916   VEC (value_and_voffset_p) *result_vec = NULL;
917   struct value_and_voffset *iter;
918   int i, count;
919
920   value = coerce_ref (value);
921   type = check_typedef (value_type (value));
922   if (TYPE_CODE (type) == TYPE_CODE_PTR)
923     {
924       value = value_ind (value);
925       type = check_typedef (value_type (value));
926     }
927
928   get_user_print_options (&opts);
929
930   /* Respect 'set print object'.  */
931   if (opts.objectprint)
932     {
933       value = value_full_object (value, NULL, 0, 0, 0);
934       type = check_typedef (value_type (value));
935     }
936
937   gdbarch = get_type_arch (type);
938   vtable = gnuv3_get_vtable (gdbarch, type,
939                              value_as_address (value_addr (value)));
940
941   if (!vtable)
942     {
943       printf_filtered (_("This object does not have a virtual function table\n"));
944       return;
945     }
946
947   offset_hash = htab_create_alloc (1, hash_value_and_voffset,
948                                    eq_value_and_voffset,
949                                    xfree, xcalloc, xfree);
950   cleanup = make_cleanup_htab_delete (offset_hash);
951   make_cleanup (VEC_cleanup (value_and_voffset_p), &result_vec);
952
953   compute_vtable_size (offset_hash, &result_vec, value);
954
955   qsort (VEC_address (value_and_voffset_p, result_vec),
956          VEC_length (value_and_voffset_p, result_vec),
957          sizeof (value_and_voffset_p),
958          compare_value_and_voffset);
959
960   count = 0;
961   for (i = 0; VEC_iterate (value_and_voffset_p, result_vec, i, iter); ++i)
962     {
963       if (iter->max_voffset >= 0)
964         {
965           if (count > 0)
966             printf_filtered ("\n");
967           print_one_vtable (gdbarch, iter->value, iter->max_voffset, &opts);
968           ++count;
969         }
970     }
971
972   do_cleanups (cleanup);
973 }
974
975 /* Determine if we are currently in a C++ thunk.  If so, get the address
976    of the routine we are thunking to and continue to there instead.  */
977
978 static CORE_ADDR 
979 gnuv3_skip_trampoline (struct frame_info *frame, CORE_ADDR stop_pc)
980 {
981   CORE_ADDR real_stop_pc, method_stop_pc;
982   struct gdbarch *gdbarch = get_frame_arch (frame);
983   struct minimal_symbol *thunk_sym, *fn_sym;
984   struct obj_section *section;
985   const char *thunk_name, *fn_name;
986   
987   real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
988   if (real_stop_pc == 0)
989     real_stop_pc = stop_pc;
990
991   /* Find the linker symbol for this potential thunk.  */
992   thunk_sym = lookup_minimal_symbol_by_pc (real_stop_pc);
993   section = find_pc_section (real_stop_pc);
994   if (thunk_sym == NULL || section == NULL)
995     return 0;
996
997   /* The symbol's demangled name should be something like "virtual
998      thunk to FUNCTION", where FUNCTION is the name of the function
999      being thunked to.  */
1000   thunk_name = SYMBOL_DEMANGLED_NAME (thunk_sym);
1001   if (thunk_name == NULL || strstr (thunk_name, " thunk to ") == NULL)
1002     return 0;
1003
1004   fn_name = strstr (thunk_name, " thunk to ") + strlen (" thunk to ");
1005   fn_sym = lookup_minimal_symbol (fn_name, NULL, section->objfile);
1006   if (fn_sym == NULL)
1007     return 0;
1008
1009   method_stop_pc = SYMBOL_VALUE_ADDRESS (fn_sym);
1010   real_stop_pc = gdbarch_skip_trampoline_code
1011                    (gdbarch, frame, method_stop_pc);
1012   if (real_stop_pc == 0)
1013     real_stop_pc = method_stop_pc;
1014
1015   return real_stop_pc;
1016 }
1017
1018 /* Return nonzero if a type should be passed by reference.
1019
1020    The rule in the v3 ABI document comes from section 3.1.1.  If the
1021    type has a non-trivial copy constructor or destructor, then the
1022    caller must make a copy (by calling the copy constructor if there
1023    is one or perform the copy itself otherwise), pass the address of
1024    the copy, and then destroy the temporary (if necessary).
1025
1026    For return values with non-trivial copy constructors or
1027    destructors, space will be allocated in the caller, and a pointer
1028    will be passed as the first argument (preceding "this").
1029
1030    We don't have a bulletproof mechanism for determining whether a
1031    constructor or destructor is trivial.  For GCC and DWARF2 debug
1032    information, we can check the artificial flag.
1033
1034    We don't do anything with the constructors or destructors,
1035    but we have to get the argument passing right anyway.  */
1036 static int
1037 gnuv3_pass_by_reference (struct type *type)
1038 {
1039   int fieldnum, fieldelem;
1040
1041   CHECK_TYPEDEF (type);
1042
1043   /* We're only interested in things that can have methods.  */
1044   if (TYPE_CODE (type) != TYPE_CODE_STRUCT
1045       && TYPE_CODE (type) != TYPE_CODE_CLASS
1046       && TYPE_CODE (type) != TYPE_CODE_UNION)
1047     return 0;
1048
1049   for (fieldnum = 0; fieldnum < TYPE_NFN_FIELDS (type); fieldnum++)
1050     for (fieldelem = 0; fieldelem < TYPE_FN_FIELDLIST_LENGTH (type, fieldnum);
1051          fieldelem++)
1052       {
1053         struct fn_field *fn = TYPE_FN_FIELDLIST1 (type, fieldnum);
1054         const char *name = TYPE_FN_FIELDLIST_NAME (type, fieldnum);
1055         struct type *fieldtype = TYPE_FN_FIELD_TYPE (fn, fieldelem);
1056
1057         /* If this function is marked as artificial, it is compiler-generated,
1058            and we assume it is trivial.  */
1059         if (TYPE_FN_FIELD_ARTIFICIAL (fn, fieldelem))
1060           continue;
1061
1062         /* If we've found a destructor, we must pass this by reference.  */
1063         if (name[0] == '~')
1064           return 1;
1065
1066         /* If the mangled name of this method doesn't indicate that it
1067            is a constructor, we're not interested.
1068
1069            FIXME drow/2007-09-23: We could do this using the name of
1070            the method and the name of the class instead of dealing
1071            with the mangled name.  We don't have a convenient function
1072            to strip off both leading scope qualifiers and trailing
1073            template arguments yet.  */
1074         if (!is_constructor_name (TYPE_FN_FIELD_PHYSNAME (fn, fieldelem)))
1075           continue;
1076
1077         /* If this method takes two arguments, and the second argument is
1078            a reference to this class, then it is a copy constructor.  */
1079         if (TYPE_NFIELDS (fieldtype) == 2
1080             && TYPE_CODE (TYPE_FIELD_TYPE (fieldtype, 1)) == TYPE_CODE_REF
1081             && check_typedef (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (fieldtype,
1082                                                                  1))) == type)
1083           return 1;
1084       }
1085
1086   /* Even if all the constructors and destructors were artificial, one
1087      of them may have invoked a non-artificial constructor or
1088      destructor in a base class.  If any base class needs to be passed
1089      by reference, so does this class.  Similarly for members, which
1090      are constructed whenever this class is.  We do not need to worry
1091      about recursive loops here, since we are only looking at members
1092      of complete class type.  Also ignore any static members.  */
1093   for (fieldnum = 0; fieldnum < TYPE_NFIELDS (type); fieldnum++)
1094     if (! field_is_static (&TYPE_FIELD (type, fieldnum))
1095         && gnuv3_pass_by_reference (TYPE_FIELD_TYPE (type, fieldnum)))
1096       return 1;
1097
1098   return 0;
1099 }
1100
1101 static void
1102 init_gnuv3_ops (void)
1103 {
1104   vtable_type_gdbarch_data
1105     = gdbarch_data_register_post_init (build_gdb_vtable_type);
1106
1107   gnu_v3_abi_ops.shortname = "gnu-v3";
1108   gnu_v3_abi_ops.longname = "GNU G++ Version 3 ABI";
1109   gnu_v3_abi_ops.doc = "G++ Version 3 ABI";
1110   gnu_v3_abi_ops.is_destructor_name =
1111     (enum dtor_kinds (*) (const char *))is_gnu_v3_mangled_dtor;
1112   gnu_v3_abi_ops.is_constructor_name =
1113     (enum ctor_kinds (*) (const char *))is_gnu_v3_mangled_ctor;
1114   gnu_v3_abi_ops.is_vtable_name = gnuv3_is_vtable_name;
1115   gnu_v3_abi_ops.is_operator_name = gnuv3_is_operator_name;
1116   gnu_v3_abi_ops.rtti_type = gnuv3_rtti_type;
1117   gnu_v3_abi_ops.virtual_fn_field = gnuv3_virtual_fn_field;
1118   gnu_v3_abi_ops.baseclass_offset = gnuv3_baseclass_offset;
1119   gnu_v3_abi_ops.print_method_ptr = gnuv3_print_method_ptr;
1120   gnu_v3_abi_ops.method_ptr_size = gnuv3_method_ptr_size;
1121   gnu_v3_abi_ops.make_method_ptr = gnuv3_make_method_ptr;
1122   gnu_v3_abi_ops.method_ptr_to_value = gnuv3_method_ptr_to_value;
1123   gnu_v3_abi_ops.print_vtable = gnuv3_print_vtable;
1124   gnu_v3_abi_ops.skip_trampoline = gnuv3_skip_trampoline;
1125   gnu_v3_abi_ops.pass_by_reference = gnuv3_pass_by_reference;
1126 }
1127
1128 extern initialize_file_ftype _initialize_gnu_v3_abi; /* -Wmissing-prototypes */
1129
1130 void
1131 _initialize_gnu_v3_abi (void)
1132 {
1133   init_gnuv3_ops ();
1134
1135   register_cp_abi (&gnu_v3_abi_ops);
1136 }