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