xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/gnu-v3-abi.c (revision 3f351f34c6d827cf017cdcff3543f6ec0c88b420)
1 /* Abstraction of GNU v3 abi.
2    Contributed by Jim Blandy <jimb@redhat.com>
3 
4    Copyright (C) 2001-2020 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 "dwarf2.h"
27 #include "objfiles.h"
28 #include "valprint.h"
29 #include "c-lang.h"
30 #include "typeprint.h"
31 #include <algorithm>
32 #include "cli/cli-style.h"
33 #include "dwarf2/loc.h"
34 
35 static struct cp_abi_ops gnu_v3_abi_ops;
36 
37 /* A gdbarch key for std::type_info, in the event that it can't be
38    found in the debug info.  */
39 
40 static struct gdbarch_data *std_type_info_gdbarch_data;
41 
42 
43 static int
44 gnuv3_is_vtable_name (const char *name)
45 {
46   return startswith (name, "_ZTV");
47 }
48 
49 static int
50 gnuv3_is_operator_name (const char *name)
51 {
52   return startswith (name, CP_OPERATOR_STR);
53 }
54 
55 
56 /* To help us find the components of a vtable, we build ourselves a
57    GDB type object representing the vtable structure.  Following the
58    V3 ABI, it goes something like this:
59 
60    struct gdb_gnu_v3_abi_vtable {
61 
62      / * An array of virtual call and virtual base offsets.  The real
63          length of this array depends on the class hierarchy; we use
64          negative subscripts to access the elements.  Yucky, but
65          better than the alternatives.  * /
66      ptrdiff_t vcall_and_vbase_offsets[0];
67 
68      / * The offset from a virtual pointer referring to this table
69          to the top of the complete object.  * /
70      ptrdiff_t offset_to_top;
71 
72      / * The type_info pointer for this class.  This is really a
73          std::type_info *, but GDB doesn't really look at the
74          type_info object itself, so we don't bother to get the type
75          exactly right.  * /
76      void *type_info;
77 
78      / * Virtual table pointers in objects point here.  * /
79 
80      / * Virtual function pointers.  Like the vcall/vbase array, the
81          real length of this table depends on the class hierarchy.  * /
82      void (*virtual_functions[0]) ();
83 
84    };
85 
86    The catch, of course, is that the exact layout of this table
87    depends on the ABI --- word size, endianness, alignment, etc.  So
88    the GDB type object is actually a per-architecture kind of thing.
89 
90    vtable_type_gdbarch_data is a gdbarch per-architecture data pointer
91    which refers to the struct type * for this structure, laid out
92    appropriately for the architecture.  */
93 static struct gdbarch_data *vtable_type_gdbarch_data;
94 
95 
96 /* Human-readable names for the numbers of the fields above.  */
97 enum {
98   vtable_field_vcall_and_vbase_offsets,
99   vtable_field_offset_to_top,
100   vtable_field_type_info,
101   vtable_field_virtual_functions
102 };
103 
104 
105 /* Return a GDB type representing `struct gdb_gnu_v3_abi_vtable',
106    described above, laid out appropriately for ARCH.
107 
108    We use this function as the gdbarch per-architecture data
109    initialization function.  */
110 static void *
111 build_gdb_vtable_type (struct gdbarch *arch)
112 {
113   struct type *t;
114   struct field *field_list, *field;
115   int offset;
116 
117   struct type *void_ptr_type
118     = builtin_type (arch)->builtin_data_ptr;
119   struct type *ptr_to_void_fn_type
120     = builtin_type (arch)->builtin_func_ptr;
121 
122   /* ARCH can't give us the true ptrdiff_t type, so we guess.  */
123   struct type *ptrdiff_type
124     = arch_integer_type (arch, gdbarch_ptr_bit (arch), 0, "ptrdiff_t");
125 
126   /* We assume no padding is necessary, since GDB doesn't know
127      anything about alignment at the moment.  If this assumption bites
128      us, we should add a gdbarch method which, given a type, returns
129      the alignment that type requires, and then use that here.  */
130 
131   /* Build the field list.  */
132   field_list = XCNEWVEC (struct field, 4);
133   field = &field_list[0];
134   offset = 0;
135 
136   /* ptrdiff_t vcall_and_vbase_offsets[0]; */
137   FIELD_NAME (*field) = "vcall_and_vbase_offsets";
138   field->set_type (lookup_array_range_type (ptrdiff_type, 0, -1));
139   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
140   offset += TYPE_LENGTH (field->type ());
141   field++;
142 
143   /* ptrdiff_t offset_to_top; */
144   FIELD_NAME (*field) = "offset_to_top";
145   field->set_type (ptrdiff_type);
146   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
147   offset += TYPE_LENGTH (field->type ());
148   field++;
149 
150   /* void *type_info; */
151   FIELD_NAME (*field) = "type_info";
152   field->set_type (void_ptr_type);
153   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
154   offset += TYPE_LENGTH (field->type ());
155   field++;
156 
157   /* void (*virtual_functions[0]) (); */
158   FIELD_NAME (*field) = "virtual_functions";
159   field->set_type (lookup_array_range_type (ptr_to_void_fn_type, 0, -1));
160   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
161   offset += TYPE_LENGTH (field->type ());
162   field++;
163 
164   /* We assumed in the allocation above that there were four fields.  */
165   gdb_assert (field == (field_list + 4));
166 
167   t = arch_type (arch, TYPE_CODE_STRUCT, offset * TARGET_CHAR_BIT, NULL);
168   t->set_num_fields (field - field_list);
169   t->set_fields (field_list);
170   t->set_name ("gdb_gnu_v3_abi_vtable");
171   INIT_CPLUS_SPECIFIC (t);
172 
173   return make_type_with_address_space (t, TYPE_INSTANCE_FLAG_CODE_SPACE);
174 }
175 
176 
177 /* Return the ptrdiff_t type used in the vtable type.  */
178 static struct type *
179 vtable_ptrdiff_type (struct gdbarch *gdbarch)
180 {
181   struct type *vtable_type
182     = (struct type *) gdbarch_data (gdbarch, vtable_type_gdbarch_data);
183 
184   /* The "offset_to_top" field has the appropriate (ptrdiff_t) type.  */
185   return vtable_type->field (vtable_field_offset_to_top).type ();
186 }
187 
188 /* Return the offset from the start of the imaginary `struct
189    gdb_gnu_v3_abi_vtable' object to the vtable's "address point"
190    (i.e., where objects' virtual table pointers point).  */
191 static int
192 vtable_address_point_offset (struct gdbarch *gdbarch)
193 {
194   struct type *vtable_type
195     = (struct type *) gdbarch_data (gdbarch, vtable_type_gdbarch_data);
196 
197   return (TYPE_FIELD_BITPOS (vtable_type, vtable_field_virtual_functions)
198           / TARGET_CHAR_BIT);
199 }
200 
201 
202 /* Determine whether structure TYPE is a dynamic class.  Cache the
203    result.  */
204 
205 static int
206 gnuv3_dynamic_class (struct type *type)
207 {
208   int fieldnum, fieldelem;
209 
210   type = check_typedef (type);
211   gdb_assert (type->code () == TYPE_CODE_STRUCT
212 	      || type->code () == TYPE_CODE_UNION);
213 
214   if (type->code () == TYPE_CODE_UNION)
215     return 0;
216 
217   if (TYPE_CPLUS_DYNAMIC (type))
218     return TYPE_CPLUS_DYNAMIC (type) == 1;
219 
220   ALLOCATE_CPLUS_STRUCT_TYPE (type);
221 
222   for (fieldnum = 0; fieldnum < TYPE_N_BASECLASSES (type); fieldnum++)
223     if (BASETYPE_VIA_VIRTUAL (type, fieldnum)
224 	|| gnuv3_dynamic_class (type->field (fieldnum).type ()))
225       {
226 	TYPE_CPLUS_DYNAMIC (type) = 1;
227 	return 1;
228       }
229 
230   for (fieldnum = 0; fieldnum < TYPE_NFN_FIELDS (type); fieldnum++)
231     for (fieldelem = 0; fieldelem < TYPE_FN_FIELDLIST_LENGTH (type, fieldnum);
232 	 fieldelem++)
233       {
234 	struct fn_field *f = TYPE_FN_FIELDLIST1 (type, fieldnum);
235 
236 	if (TYPE_FN_FIELD_VIRTUAL_P (f, fieldelem))
237 	  {
238 	    TYPE_CPLUS_DYNAMIC (type) = 1;
239 	    return 1;
240 	  }
241       }
242 
243   TYPE_CPLUS_DYNAMIC (type) = -1;
244   return 0;
245 }
246 
247 /* Find the vtable for a value of CONTAINER_TYPE located at
248    CONTAINER_ADDR.  Return a value of the correct vtable type for this
249    architecture, or NULL if CONTAINER does not have a vtable.  */
250 
251 static struct value *
252 gnuv3_get_vtable (struct gdbarch *gdbarch,
253 		  struct type *container_type, CORE_ADDR container_addr)
254 {
255   struct type *vtable_type
256     = (struct type *) gdbarch_data (gdbarch, vtable_type_gdbarch_data);
257   struct type *vtable_pointer_type;
258   struct value *vtable_pointer;
259   CORE_ADDR vtable_address;
260 
261   container_type = check_typedef (container_type);
262   gdb_assert (container_type->code () == TYPE_CODE_STRUCT);
263 
264   /* If this type does not have a virtual table, don't read the first
265      field.  */
266   if (!gnuv3_dynamic_class (container_type))
267     return NULL;
268 
269   /* We do not consult the debug information to find the virtual table.
270      The ABI specifies that it is always at offset zero in any class,
271      and debug information may not represent it.
272 
273      We avoid using value_contents on principle, because the object might
274      be large.  */
275 
276   /* Find the type "pointer to virtual table".  */
277   vtable_pointer_type = lookup_pointer_type (vtable_type);
278 
279   /* Load it from the start of the class.  */
280   vtable_pointer = value_at (vtable_pointer_type, container_addr);
281   vtable_address = value_as_address (vtable_pointer);
282 
283   /* Correct it to point at the start of the virtual table, rather
284      than the address point.  */
285   return value_at_lazy (vtable_type,
286 			vtable_address
287 			- vtable_address_point_offset (gdbarch));
288 }
289 
290 
291 static struct type *
292 gnuv3_rtti_type (struct value *value,
293                  int *full_p, LONGEST *top_p, int *using_enc_p)
294 {
295   struct gdbarch *gdbarch;
296   struct type *values_type = check_typedef (value_type (value));
297   struct value *vtable;
298   struct minimal_symbol *vtable_symbol;
299   const char *vtable_symbol_name;
300   const char *class_name;
301   struct type *run_time_type;
302   LONGEST offset_to_top;
303   const char *atsign;
304 
305   /* We only have RTTI for dynamic class objects.  */
306   if (values_type->code () != TYPE_CODE_STRUCT
307       || !gnuv3_dynamic_class (values_type))
308     return NULL;
309 
310   /* Determine architecture.  */
311   gdbarch = get_type_arch (values_type);
312 
313   if (using_enc_p)
314     *using_enc_p = 0;
315 
316   vtable = gnuv3_get_vtable (gdbarch, values_type,
317 			     value_as_address (value_addr (value)));
318   if (vtable == NULL)
319     return NULL;
320 
321   /* Find the linker symbol for this vtable.  */
322   vtable_symbol
323     = lookup_minimal_symbol_by_pc (value_address (vtable)
324                                    + value_embedded_offset (vtable)).minsym;
325   if (! vtable_symbol)
326     return NULL;
327 
328   /* The symbol's demangled name should be something like "vtable for
329      CLASS", where CLASS is the name of the run-time type of VALUE.
330      If we didn't like this approach, we could instead look in the
331      type_info object itself to get the class name.  But this way
332      should work just as well, and doesn't read target memory.  */
333   vtable_symbol_name = vtable_symbol->demangled_name ();
334   if (vtable_symbol_name == NULL
335       || !startswith (vtable_symbol_name, "vtable for "))
336     {
337       warning (_("can't find linker symbol for virtual table for `%s' value"),
338 	       TYPE_SAFE_NAME (values_type));
339       if (vtable_symbol_name)
340 	warning (_("  found `%s' instead"), vtable_symbol_name);
341       return NULL;
342     }
343   class_name = vtable_symbol_name + 11;
344 
345   /* Strip off @plt and version suffixes.  */
346   atsign = strchr (class_name, '@');
347   if (atsign != NULL)
348     {
349       char *copy;
350 
351       copy = (char *) alloca (atsign - class_name + 1);
352       memcpy (copy, class_name, atsign - class_name);
353       copy[atsign - class_name] = '\0';
354       class_name = copy;
355     }
356 
357   /* Try to look up the class name as a type name.  */
358   /* FIXME: chastain/2003-11-26: block=NULL is bogus.  See pr gdb/1465.  */
359   run_time_type = cp_lookup_rtti_type (class_name, NULL);
360   if (run_time_type == NULL)
361     return NULL;
362 
363   /* Get the offset from VALUE to the top of the complete object.
364      NOTE: this is the reverse of the meaning of *TOP_P.  */
365   offset_to_top
366     = value_as_long (value_field (vtable, vtable_field_offset_to_top));
367 
368   if (full_p)
369     *full_p = (- offset_to_top == value_embedded_offset (value)
370                && (TYPE_LENGTH (value_enclosing_type (value))
371                    >= TYPE_LENGTH (run_time_type)));
372   if (top_p)
373     *top_p = - offset_to_top;
374   return run_time_type;
375 }
376 
377 /* Return a function pointer for CONTAINER's VTABLE_INDEX'th virtual
378    function, of type FNTYPE.  */
379 
380 static struct value *
381 gnuv3_get_virtual_fn (struct gdbarch *gdbarch, struct value *container,
382 		      struct type *fntype, int vtable_index)
383 {
384   struct value *vtable, *vfn;
385 
386   /* Every class with virtual functions must have a vtable.  */
387   vtable = gnuv3_get_vtable (gdbarch, value_type (container),
388 			     value_as_address (value_addr (container)));
389   gdb_assert (vtable != NULL);
390 
391   /* Fetch the appropriate function pointer from the vtable.  */
392   vfn = value_subscript (value_field (vtable, vtable_field_virtual_functions),
393                          vtable_index);
394 
395   /* If this architecture uses function descriptors directly in the vtable,
396      then the address of the vtable entry is actually a "function pointer"
397      (i.e. points to the descriptor).  We don't need to scale the index
398      by the size of a function descriptor; GCC does that before outputting
399      debug information.  */
400   if (gdbarch_vtable_function_descriptors (gdbarch))
401     vfn = value_addr (vfn);
402 
403   /* Cast the function pointer to the appropriate type.  */
404   vfn = value_cast (lookup_pointer_type (fntype), vfn);
405 
406   return vfn;
407 }
408 
409 /* GNU v3 implementation of value_virtual_fn_field.  See cp-abi.h
410    for a description of the arguments.  */
411 
412 static struct value *
413 gnuv3_virtual_fn_field (struct value **value_p,
414                         struct fn_field *f, int j,
415 			struct type *vfn_base, int offset)
416 {
417   struct type *values_type = check_typedef (value_type (*value_p));
418   struct gdbarch *gdbarch;
419 
420   /* Some simple sanity checks.  */
421   if (values_type->code () != TYPE_CODE_STRUCT)
422     error (_("Only classes can have virtual functions."));
423 
424   /* Determine architecture.  */
425   gdbarch = get_type_arch (values_type);
426 
427   /* Cast our value to the base class which defines this virtual
428      function.  This takes care of any necessary `this'
429      adjustments.  */
430   if (vfn_base != values_type)
431     *value_p = value_cast (vfn_base, *value_p);
432 
433   return gnuv3_get_virtual_fn (gdbarch, *value_p, TYPE_FN_FIELD_TYPE (f, j),
434 			       TYPE_FN_FIELD_VOFFSET (f, j));
435 }
436 
437 /* Compute the offset of the baseclass which is
438    the INDEXth baseclass of class TYPE,
439    for value at VALADDR (in host) at ADDRESS (in target).
440    The result is the offset of the baseclass value relative
441    to (the address of)(ARG) + OFFSET.
442 
443    -1 is returned on error.  */
444 
445 static int
446 gnuv3_baseclass_offset (struct type *type, int index,
447 			const bfd_byte *valaddr, LONGEST embedded_offset,
448 			CORE_ADDR address, const struct value *val)
449 {
450   struct gdbarch *gdbarch;
451   struct type *ptr_type;
452   struct value *vtable;
453   struct value *vbase_array;
454   long int cur_base_offset, base_offset;
455 
456   /* Determine architecture.  */
457   gdbarch = get_type_arch (type);
458   ptr_type = builtin_type (gdbarch)->builtin_data_ptr;
459 
460   /* If it isn't a virtual base, this is easy.  The offset is in the
461      type definition.  */
462   if (!BASETYPE_VIA_VIRTUAL (type, index))
463     return TYPE_BASECLASS_BITPOS (type, index) / 8;
464 
465   /* If we have a DWARF expression for the offset, evaluate it.  */
466   if (TYPE_FIELD_LOC_KIND (type, index) == FIELD_LOC_KIND_DWARF_BLOCK)
467     {
468       struct dwarf2_property_baton baton;
469       baton.property_type
470 	= lookup_pointer_type (type->field (index).type ());
471       baton.locexpr = *TYPE_FIELD_DWARF_BLOCK (type, index);
472 
473       struct dynamic_prop prop;
474       prop.set_locexpr (&baton);
475 
476       struct property_addr_info addr_stack;
477       addr_stack.type = type;
478       /* Note that we don't set "valaddr" here.  Doing so causes
479 	 regressions.  FIXME.  */
480       addr_stack.addr = address + embedded_offset;
481       addr_stack.next = nullptr;
482 
483       CORE_ADDR result;
484       if (dwarf2_evaluate_property (&prop, nullptr, &addr_stack, &result,
485 				    true))
486 	return (int) (result - addr_stack.addr);
487     }
488 
489   /* To access a virtual base, we need to use the vbase offset stored in
490      our vtable.  Recent GCC versions provide this information.  If it isn't
491      available, we could get what we needed from RTTI, or from drawing the
492      complete inheritance graph based on the debug info.  Neither is
493      worthwhile.  */
494   cur_base_offset = TYPE_BASECLASS_BITPOS (type, index) / 8;
495   if (cur_base_offset >= - vtable_address_point_offset (gdbarch))
496     error (_("Expected a negative vbase offset (old compiler?)"));
497 
498   cur_base_offset = cur_base_offset + vtable_address_point_offset (gdbarch);
499   if ((- cur_base_offset) % TYPE_LENGTH (ptr_type) != 0)
500     error (_("Misaligned vbase offset."));
501   cur_base_offset = cur_base_offset / ((int) TYPE_LENGTH (ptr_type));
502 
503   vtable = gnuv3_get_vtable (gdbarch, type, address + embedded_offset);
504   gdb_assert (vtable != NULL);
505   vbase_array = value_field (vtable, vtable_field_vcall_and_vbase_offsets);
506   base_offset = value_as_long (value_subscript (vbase_array, cur_base_offset));
507   return base_offset;
508 }
509 
510 /* Locate a virtual method in DOMAIN or its non-virtual base classes
511    which has virtual table index VOFFSET.  The method has an associated
512    "this" adjustment of ADJUSTMENT bytes.  */
513 
514 static const char *
515 gnuv3_find_method_in (struct type *domain, CORE_ADDR voffset,
516 		      LONGEST adjustment)
517 {
518   int i;
519 
520   /* Search this class first.  */
521   if (adjustment == 0)
522     {
523       int len;
524 
525       len = TYPE_NFN_FIELDS (domain);
526       for (i = 0; i < len; i++)
527 	{
528 	  int len2, j;
529 	  struct fn_field *f;
530 
531 	  f = TYPE_FN_FIELDLIST1 (domain, i);
532 	  len2 = TYPE_FN_FIELDLIST_LENGTH (domain, i);
533 
534 	  check_stub_method_group (domain, i);
535 	  for (j = 0; j < len2; j++)
536 	    if (TYPE_FN_FIELD_VOFFSET (f, j) == voffset)
537 	      return TYPE_FN_FIELD_PHYSNAME (f, j);
538 	}
539     }
540 
541   /* Next search non-virtual bases.  If it's in a virtual base,
542      we're out of luck.  */
543   for (i = 0; i < TYPE_N_BASECLASSES (domain); i++)
544     {
545       int pos;
546       struct type *basetype;
547 
548       if (BASETYPE_VIA_VIRTUAL (domain, i))
549 	continue;
550 
551       pos = TYPE_BASECLASS_BITPOS (domain, i) / 8;
552       basetype = domain->field (i).type ();
553       /* Recurse with a modified adjustment.  We don't need to adjust
554 	 voffset.  */
555       if (adjustment >= pos && adjustment < pos + TYPE_LENGTH (basetype))
556 	return gnuv3_find_method_in (basetype, voffset, adjustment - pos);
557     }
558 
559   return NULL;
560 }
561 
562 /* Decode GNU v3 method pointer.  */
563 
564 static int
565 gnuv3_decode_method_ptr (struct gdbarch *gdbarch,
566 			 const gdb_byte *contents,
567 			 CORE_ADDR *value_p,
568 			 LONGEST *adjustment_p)
569 {
570   struct type *funcptr_type = builtin_type (gdbarch)->builtin_func_ptr;
571   struct type *offset_type = vtable_ptrdiff_type (gdbarch);
572   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
573   CORE_ADDR ptr_value;
574   LONGEST voffset, adjustment;
575   int vbit;
576 
577   /* Extract the pointer to member.  The first element is either a pointer
578      or a vtable offset.  For pointers, we need to use extract_typed_address
579      to allow the back-end to convert the pointer to a GDB address -- but
580      vtable offsets we must handle as integers.  At this point, we do not
581      yet know which case we have, so we extract the value under both
582      interpretations and choose the right one later on.  */
583   ptr_value = extract_typed_address (contents, funcptr_type);
584   voffset = extract_signed_integer (contents,
585 				    TYPE_LENGTH (funcptr_type), byte_order);
586   contents += TYPE_LENGTH (funcptr_type);
587   adjustment = extract_signed_integer (contents,
588 				       TYPE_LENGTH (offset_type), byte_order);
589 
590   if (!gdbarch_vbit_in_delta (gdbarch))
591     {
592       vbit = voffset & 1;
593       voffset = voffset ^ vbit;
594     }
595   else
596     {
597       vbit = adjustment & 1;
598       adjustment = adjustment >> 1;
599     }
600 
601   *value_p = vbit? voffset : ptr_value;
602   *adjustment_p = adjustment;
603   return vbit;
604 }
605 
606 /* GNU v3 implementation of cplus_print_method_ptr.  */
607 
608 static void
609 gnuv3_print_method_ptr (const gdb_byte *contents,
610 			struct type *type,
611 			struct ui_file *stream)
612 {
613   struct type *self_type = TYPE_SELF_TYPE (type);
614   struct gdbarch *gdbarch = get_type_arch (self_type);
615   CORE_ADDR ptr_value;
616   LONGEST adjustment;
617   int vbit;
618 
619   /* Extract the pointer to member.  */
620   vbit = gnuv3_decode_method_ptr (gdbarch, contents, &ptr_value, &adjustment);
621 
622   /* Check for NULL.  */
623   if (ptr_value == 0 && vbit == 0)
624     {
625       fprintf_filtered (stream, "NULL");
626       return;
627     }
628 
629   /* Search for a virtual method.  */
630   if (vbit)
631     {
632       CORE_ADDR voffset;
633       const char *physname;
634 
635       /* It's a virtual table offset, maybe in this class.  Search
636 	 for a field with the correct vtable offset.  First convert it
637 	 to an index, as used in TYPE_FN_FIELD_VOFFSET.  */
638       voffset = ptr_value / TYPE_LENGTH (vtable_ptrdiff_type (gdbarch));
639 
640       physname = gnuv3_find_method_in (self_type, voffset, adjustment);
641 
642       /* If we found a method, print that.  We don't bother to disambiguate
643 	 possible paths to the method based on the adjustment.  */
644       if (physname)
645 	{
646 	  char *demangled_name = gdb_demangle (physname,
647 					       DMGL_ANSI | DMGL_PARAMS);
648 
649 	  fprintf_filtered (stream, "&virtual ");
650 	  if (demangled_name == NULL)
651 	    fputs_filtered (physname, stream);
652 	  else
653 	    {
654 	      fputs_filtered (demangled_name, stream);
655 	      xfree (demangled_name);
656 	    }
657 	  return;
658 	}
659     }
660   else if (ptr_value != 0)
661     {
662       /* Found a non-virtual function: print out the type.  */
663       fputs_filtered ("(", stream);
664       c_print_type (type, "", stream, -1, 0, &type_print_raw_options);
665       fputs_filtered (") ", stream);
666     }
667 
668   /* We didn't find it; print the raw data.  */
669   if (vbit)
670     {
671       fprintf_filtered (stream, "&virtual table offset ");
672       print_longest (stream, 'd', 1, ptr_value);
673     }
674   else
675     {
676       struct value_print_options opts;
677 
678       get_user_print_options (&opts);
679       print_address_demangle (&opts, gdbarch, ptr_value, stream, demangle);
680     }
681 
682   if (adjustment)
683     {
684       fprintf_filtered (stream, ", this adjustment ");
685       print_longest (stream, 'd', 1, adjustment);
686     }
687 }
688 
689 /* GNU v3 implementation of cplus_method_ptr_size.  */
690 
691 static int
692 gnuv3_method_ptr_size (struct type *type)
693 {
694   struct gdbarch *gdbarch = get_type_arch (type);
695 
696   return 2 * TYPE_LENGTH (builtin_type (gdbarch)->builtin_data_ptr);
697 }
698 
699 /* GNU v3 implementation of cplus_make_method_ptr.  */
700 
701 static void
702 gnuv3_make_method_ptr (struct type *type, gdb_byte *contents,
703 		       CORE_ADDR value, int is_virtual)
704 {
705   struct gdbarch *gdbarch = get_type_arch (type);
706   int size = TYPE_LENGTH (builtin_type (gdbarch)->builtin_data_ptr);
707   enum bfd_endian byte_order = type_byte_order (type);
708 
709   /* FIXME drow/2006-12-24: The adjustment of "this" is currently
710      always zero, since the method pointer is of the correct type.
711      But if the method pointer came from a base class, this is
712      incorrect - it should be the offset to the base.  The best
713      fix might be to create the pointer to member pointing at the
714      base class and cast it to the derived class, but that requires
715      support for adjusting pointers to members when casting them -
716      not currently supported by GDB.  */
717 
718   if (!gdbarch_vbit_in_delta (gdbarch))
719     {
720       store_unsigned_integer (contents, size, byte_order, value | is_virtual);
721       store_unsigned_integer (contents + size, size, byte_order, 0);
722     }
723   else
724     {
725       store_unsigned_integer (contents, size, byte_order, value);
726       store_unsigned_integer (contents + size, size, byte_order, is_virtual);
727     }
728 }
729 
730 /* GNU v3 implementation of cplus_method_ptr_to_value.  */
731 
732 static struct value *
733 gnuv3_method_ptr_to_value (struct value **this_p, struct value *method_ptr)
734 {
735   struct gdbarch *gdbarch;
736   const gdb_byte *contents = value_contents (method_ptr);
737   CORE_ADDR ptr_value;
738   struct type *self_type, *final_type, *method_type;
739   LONGEST adjustment;
740   int vbit;
741 
742   self_type = TYPE_SELF_TYPE (check_typedef (value_type (method_ptr)));
743   final_type = lookup_pointer_type (self_type);
744 
745   method_type = TYPE_TARGET_TYPE (check_typedef (value_type (method_ptr)));
746 
747   /* Extract the pointer to member.  */
748   gdbarch = get_type_arch (self_type);
749   vbit = gnuv3_decode_method_ptr (gdbarch, contents, &ptr_value, &adjustment);
750 
751   /* First convert THIS to match the containing type of the pointer to
752      member.  This cast may adjust the value of THIS.  */
753   *this_p = value_cast (final_type, *this_p);
754 
755   /* Then apply whatever adjustment is necessary.  This creates a somewhat
756      strange pointer: it claims to have type FINAL_TYPE, but in fact it
757      might not be a valid FINAL_TYPE.  For instance, it might be a
758      base class of FINAL_TYPE.  And if it's not the primary base class,
759      then printing it out as a FINAL_TYPE object would produce some pretty
760      garbage.
761 
762      But we don't really know the type of the first argument in
763      METHOD_TYPE either, which is why this happens.  We can't
764      dereference this later as a FINAL_TYPE, but once we arrive in the
765      called method we'll have debugging information for the type of
766      "this" - and that'll match the value we produce here.
767 
768      You can provoke this case by casting a Base::* to a Derived::*, for
769      instance.  */
770   *this_p = value_cast (builtin_type (gdbarch)->builtin_data_ptr, *this_p);
771   *this_p = value_ptradd (*this_p, adjustment);
772   *this_p = value_cast (final_type, *this_p);
773 
774   if (vbit)
775     {
776       LONGEST voffset;
777 
778       voffset = ptr_value / TYPE_LENGTH (vtable_ptrdiff_type (gdbarch));
779       return gnuv3_get_virtual_fn (gdbarch, value_ind (*this_p),
780 				   method_type, voffset);
781     }
782   else
783     return value_from_pointer (lookup_pointer_type (method_type), ptr_value);
784 }
785 
786 /* Objects of this type are stored in a hash table and a vector when
787    printing the vtables for a class.  */
788 
789 struct value_and_voffset
790 {
791   /* The value representing the object.  */
792   struct value *value;
793 
794   /* The maximum vtable offset we've found for any object at this
795      offset in the outermost object.  */
796   int max_voffset;
797 };
798 
799 /* Hash function for value_and_voffset.  */
800 
801 static hashval_t
802 hash_value_and_voffset (const void *p)
803 {
804   const struct value_and_voffset *o = (const struct value_and_voffset *) p;
805 
806   return value_address (o->value) + value_embedded_offset (o->value);
807 }
808 
809 /* Equality function for value_and_voffset.  */
810 
811 static int
812 eq_value_and_voffset (const void *a, const void *b)
813 {
814   const struct value_and_voffset *ova = (const struct value_and_voffset *) a;
815   const struct value_and_voffset *ovb = (const struct value_and_voffset *) b;
816 
817   return (value_address (ova->value) + value_embedded_offset (ova->value)
818 	  == value_address (ovb->value) + value_embedded_offset (ovb->value));
819 }
820 
821 /* Comparison function for value_and_voffset.  */
822 
823 static bool
824 compare_value_and_voffset (const struct value_and_voffset *va,
825 			   const struct value_and_voffset *vb)
826 {
827   CORE_ADDR addra = (value_address (va->value)
828 		     + value_embedded_offset (va->value));
829   CORE_ADDR addrb = (value_address (vb->value)
830 		     + value_embedded_offset (vb->value));
831 
832   return addra < addrb;
833 }
834 
835 /* A helper function used when printing vtables.  This determines the
836    key (most derived) sub-object at each address and also computes the
837    maximum vtable offset seen for the corresponding vtable.  Updates
838    OFFSET_HASH and OFFSET_VEC with a new value_and_voffset object, if
839    needed.  VALUE is the object to examine.  */
840 
841 static void
842 compute_vtable_size (htab_t offset_hash,
843 		     std::vector<value_and_voffset *> *offset_vec,
844 		     struct value *value)
845 {
846   int i;
847   struct type *type = check_typedef (value_type (value));
848   void **slot;
849   struct value_and_voffset search_vo, *current_vo;
850 
851   gdb_assert (type->code () == TYPE_CODE_STRUCT);
852 
853   /* If the object is not dynamic, then we are done; as it cannot have
854      dynamic base types either.  */
855   if (!gnuv3_dynamic_class (type))
856     return;
857 
858   /* Update the hash and the vec, if needed.  */
859   search_vo.value = value;
860   slot = htab_find_slot (offset_hash, &search_vo, INSERT);
861   if (*slot)
862     current_vo = (struct value_and_voffset *) *slot;
863   else
864     {
865       current_vo = XNEW (struct value_and_voffset);
866       current_vo->value = value;
867       current_vo->max_voffset = -1;
868       *slot = current_vo;
869       offset_vec->push_back (current_vo);
870     }
871 
872   /* Update the value_and_voffset object with the highest vtable
873      offset from this class.  */
874   for (i = 0; i < TYPE_NFN_FIELDS (type); ++i)
875     {
876       int j;
877       struct fn_field *fn = TYPE_FN_FIELDLIST1 (type, i);
878 
879       for (j = 0; j < TYPE_FN_FIELDLIST_LENGTH (type, i); ++j)
880 	{
881 	  if (TYPE_FN_FIELD_VIRTUAL_P (fn, j))
882 	    {
883 	      int voffset = TYPE_FN_FIELD_VOFFSET (fn, j);
884 
885 	      if (voffset > current_vo->max_voffset)
886 		current_vo->max_voffset = voffset;
887 	    }
888 	}
889     }
890 
891   /* Recurse into base classes.  */
892   for (i = 0; i < TYPE_N_BASECLASSES (type); ++i)
893     compute_vtable_size (offset_hash, offset_vec, value_field (value, i));
894 }
895 
896 /* Helper for gnuv3_print_vtable that prints a single vtable.  */
897 
898 static void
899 print_one_vtable (struct gdbarch *gdbarch, struct value *value,
900 		  int max_voffset,
901 		  struct value_print_options *opts)
902 {
903   int i;
904   struct type *type = check_typedef (value_type (value));
905   struct value *vtable;
906   CORE_ADDR vt_addr;
907 
908   vtable = gnuv3_get_vtable (gdbarch, type,
909 			     value_address (value)
910 			     + value_embedded_offset (value));
911   vt_addr = value_address (value_field (vtable,
912 					vtable_field_virtual_functions));
913 
914   printf_filtered (_("vtable for '%s' @ %s (subobject @ %s):\n"),
915 		   TYPE_SAFE_NAME (type),
916 		   paddress (gdbarch, vt_addr),
917 		   paddress (gdbarch, (value_address (value)
918 				       + value_embedded_offset (value))));
919 
920   for (i = 0; i <= max_voffset; ++i)
921     {
922       /* Initialize it just to avoid a GCC false warning.  */
923       CORE_ADDR addr = 0;
924       int got_error = 0;
925       struct value *vfn;
926 
927       printf_filtered ("[%d]: ", i);
928 
929       vfn = value_subscript (value_field (vtable,
930 					  vtable_field_virtual_functions),
931 			     i);
932 
933       if (gdbarch_vtable_function_descriptors (gdbarch))
934 	vfn = value_addr (vfn);
935 
936       try
937 	{
938 	  addr = value_as_address (vfn);
939 	}
940       catch (const gdb_exception_error &ex)
941 	{
942 	  fprintf_styled (gdb_stdout, metadata_style.style (),
943 			  _("<error: %s>"), ex.what ());
944 	  got_error = 1;
945 	}
946 
947       if (!got_error)
948 	print_function_pointer_address (opts, gdbarch, addr, gdb_stdout);
949       printf_filtered ("\n");
950     }
951 }
952 
953 /* Implementation of the print_vtable method.  */
954 
955 static void
956 gnuv3_print_vtable (struct value *value)
957 {
958   struct gdbarch *gdbarch;
959   struct type *type;
960   struct value *vtable;
961   struct value_print_options opts;
962   int count;
963 
964   value = coerce_ref (value);
965   type = check_typedef (value_type (value));
966   if (type->code () == TYPE_CODE_PTR)
967     {
968       value = value_ind (value);
969       type = check_typedef (value_type (value));
970     }
971 
972   get_user_print_options (&opts);
973 
974   /* Respect 'set print object'.  */
975   if (opts.objectprint)
976     {
977       value = value_full_object (value, NULL, 0, 0, 0);
978       type = check_typedef (value_type (value));
979     }
980 
981   gdbarch = get_type_arch (type);
982 
983   vtable = NULL;
984   if (type->code () == TYPE_CODE_STRUCT)
985     vtable = gnuv3_get_vtable (gdbarch, type,
986 			       value_as_address (value_addr (value)));
987 
988   if (!vtable)
989     {
990       printf_filtered (_("This object does not have a virtual function table\n"));
991       return;
992     }
993 
994   htab_up offset_hash (htab_create_alloc (1, hash_value_and_voffset,
995 					  eq_value_and_voffset,
996 					  xfree, xcalloc, xfree));
997   std::vector<value_and_voffset *> result_vec;
998 
999   compute_vtable_size (offset_hash.get (), &result_vec, value);
1000   std::sort (result_vec.begin (), result_vec.end (),
1001 	     compare_value_and_voffset);
1002 
1003   count = 0;
1004   for (value_and_voffset *iter : result_vec)
1005     {
1006       if (iter->max_voffset >= 0)
1007 	{
1008 	  if (count > 0)
1009 	    printf_filtered ("\n");
1010 	  print_one_vtable (gdbarch, iter->value, iter->max_voffset, &opts);
1011 	  ++count;
1012 	}
1013     }
1014 }
1015 
1016 /* Return a GDB type representing `struct std::type_info', laid out
1017    appropriately for ARCH.
1018 
1019    We use this function as the gdbarch per-architecture data
1020    initialization function.  */
1021 
1022 static void *
1023 build_std_type_info_type (struct gdbarch *arch)
1024 {
1025   struct type *t;
1026   struct field *field_list, *field;
1027   int offset;
1028   struct type *void_ptr_type
1029     = builtin_type (arch)->builtin_data_ptr;
1030   struct type *char_type
1031     = builtin_type (arch)->builtin_char;
1032   struct type *char_ptr_type
1033     = make_pointer_type (make_cv_type (1, 0, char_type, NULL), NULL);
1034 
1035   field_list = XCNEWVEC (struct field, 2);
1036   field = &field_list[0];
1037   offset = 0;
1038 
1039   /* The vtable.  */
1040   FIELD_NAME (*field) = "_vptr.type_info";
1041   field->set_type (void_ptr_type);
1042   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
1043   offset += TYPE_LENGTH (field->type ());
1044   field++;
1045 
1046   /* The name.  */
1047   FIELD_NAME (*field) = "__name";
1048   field->set_type (char_ptr_type);
1049   SET_FIELD_BITPOS (*field, offset * TARGET_CHAR_BIT);
1050   offset += TYPE_LENGTH (field->type ());
1051   field++;
1052 
1053   gdb_assert (field == (field_list + 2));
1054 
1055   t = arch_type (arch, TYPE_CODE_STRUCT, offset * TARGET_CHAR_BIT, NULL);
1056   t->set_num_fields (field - field_list);
1057   t->set_fields (field_list);
1058   t->set_name ("gdb_gnu_v3_type_info");
1059   INIT_CPLUS_SPECIFIC (t);
1060 
1061   return t;
1062 }
1063 
1064 /* Implement the 'get_typeid_type' method.  */
1065 
1066 static struct type *
1067 gnuv3_get_typeid_type (struct gdbarch *gdbarch)
1068 {
1069   struct symbol *typeinfo;
1070   struct type *typeinfo_type;
1071 
1072   typeinfo = lookup_symbol ("std::type_info", NULL, STRUCT_DOMAIN,
1073 			    NULL).symbol;
1074   if (typeinfo == NULL)
1075     typeinfo_type
1076       = (struct type *) gdbarch_data (gdbarch, std_type_info_gdbarch_data);
1077   else
1078     typeinfo_type = SYMBOL_TYPE (typeinfo);
1079 
1080   return typeinfo_type;
1081 }
1082 
1083 /* Implement the 'get_typeid' method.  */
1084 
1085 static struct value *
1086 gnuv3_get_typeid (struct value *value)
1087 {
1088   struct type *typeinfo_type;
1089   struct type *type;
1090   struct gdbarch *gdbarch;
1091   struct value *result;
1092   std::string type_name;
1093   gdb::unique_xmalloc_ptr<char> canonical;
1094 
1095   /* We have to handle values a bit trickily here, to allow this code
1096      to work properly with non_lvalue values that are really just
1097      disguised types.  */
1098   if (value_lval_const (value) == lval_memory)
1099     value = coerce_ref (value);
1100 
1101   type = check_typedef (value_type (value));
1102 
1103   /* In the non_lvalue case, a reference might have slipped through
1104      here.  */
1105   if (type->code () == TYPE_CODE_REF)
1106     type = check_typedef (TYPE_TARGET_TYPE (type));
1107 
1108   /* Ignore top-level cv-qualifiers.  */
1109   type = make_cv_type (0, 0, type, NULL);
1110   gdbarch = get_type_arch (type);
1111 
1112   type_name = type_to_string (type);
1113   if (type_name.empty ())
1114     error (_("cannot find typeinfo for unnamed type"));
1115 
1116   /* We need to canonicalize the type name here, because we do lookups
1117      using the demangled name, and so we must match the format it
1118      uses.  E.g., GDB tends to use "const char *" as a type name, but
1119      the demangler uses "char const *".  */
1120   canonical = cp_canonicalize_string (type_name.c_str ());
1121   const char *name = (canonical == nullptr
1122 		      ? type_name.c_str ()
1123 		      : canonical.get ());
1124 
1125   typeinfo_type = gnuv3_get_typeid_type (gdbarch);
1126 
1127   /* We check for lval_memory because in the "typeid (type-id)" case,
1128      the type is passed via a not_lval value object.  */
1129   if (type->code () == TYPE_CODE_STRUCT
1130       && value_lval_const (value) == lval_memory
1131       && gnuv3_dynamic_class (type))
1132     {
1133       struct value *vtable, *typeinfo_value;
1134       CORE_ADDR address = value_address (value) + value_embedded_offset (value);
1135 
1136       vtable = gnuv3_get_vtable (gdbarch, type, address);
1137       if (vtable == NULL)
1138 	error (_("cannot find typeinfo for object of type '%s'"),
1139 	       name);
1140       typeinfo_value = value_field (vtable, vtable_field_type_info);
1141       result = value_ind (value_cast (make_pointer_type (typeinfo_type, NULL),
1142 				      typeinfo_value));
1143     }
1144   else
1145     {
1146       std::string sym_name = std::string ("typeinfo for ") + name;
1147       bound_minimal_symbol minsym
1148 	= lookup_minimal_symbol (sym_name.c_str (), NULL, NULL);
1149 
1150       if (minsym.minsym == NULL)
1151 	error (_("could not find typeinfo symbol for '%s'"), name);
1152 
1153       result = value_at_lazy (typeinfo_type, BMSYMBOL_VALUE_ADDRESS (minsym));
1154     }
1155 
1156   return result;
1157 }
1158 
1159 /* Implement the 'get_typename_from_type_info' method.  */
1160 
1161 static std::string
1162 gnuv3_get_typename_from_type_info (struct value *type_info_ptr)
1163 {
1164   struct gdbarch *gdbarch = get_type_arch (value_type (type_info_ptr));
1165   struct bound_minimal_symbol typeinfo_sym;
1166   CORE_ADDR addr;
1167   const char *symname;
1168   const char *class_name;
1169   const char *atsign;
1170 
1171   addr = value_as_address (type_info_ptr);
1172   typeinfo_sym = lookup_minimal_symbol_by_pc (addr);
1173   if (typeinfo_sym.minsym == NULL)
1174     error (_("could not find minimal symbol for typeinfo address %s"),
1175 	   paddress (gdbarch, addr));
1176 
1177 #define TYPEINFO_PREFIX "typeinfo for "
1178 #define TYPEINFO_PREFIX_LEN (sizeof (TYPEINFO_PREFIX) - 1)
1179   symname = typeinfo_sym.minsym->demangled_name ();
1180   if (symname == NULL || strncmp (symname, TYPEINFO_PREFIX,
1181 				  TYPEINFO_PREFIX_LEN))
1182     error (_("typeinfo symbol '%s' has unexpected name"),
1183 	   typeinfo_sym.minsym->linkage_name ());
1184   class_name = symname + TYPEINFO_PREFIX_LEN;
1185 
1186   /* Strip off @plt and version suffixes.  */
1187   atsign = strchr (class_name, '@');
1188   if (atsign != NULL)
1189     return std::string (class_name, atsign - class_name);
1190   return class_name;
1191 }
1192 
1193 /* Implement the 'get_type_from_type_info' method.  */
1194 
1195 static struct type *
1196 gnuv3_get_type_from_type_info (struct value *type_info_ptr)
1197 {
1198   /* We have to parse the type name, since in general there is not a
1199      symbol for a type.  This is somewhat bogus since there may be a
1200      mis-parse.  Another approach might be to re-use the demangler's
1201      internal form to reconstruct the type somehow.  */
1202   std::string type_name = gnuv3_get_typename_from_type_info (type_info_ptr);
1203   expression_up expr (parse_expression (type_name.c_str ()));
1204   struct value *type_val = evaluate_type (expr.get ());
1205   return value_type (type_val);
1206 }
1207 
1208 /* Determine if we are currently in a C++ thunk.  If so, get the address
1209    of the routine we are thunking to and continue to there instead.  */
1210 
1211 static CORE_ADDR
1212 gnuv3_skip_trampoline (struct frame_info *frame, CORE_ADDR stop_pc)
1213 {
1214   CORE_ADDR real_stop_pc, method_stop_pc, func_addr;
1215   struct gdbarch *gdbarch = get_frame_arch (frame);
1216   struct bound_minimal_symbol thunk_sym, fn_sym;
1217   struct obj_section *section;
1218   const char *thunk_name, *fn_name;
1219 
1220   real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
1221   if (real_stop_pc == 0)
1222     real_stop_pc = stop_pc;
1223 
1224   /* Find the linker symbol for this potential thunk.  */
1225   thunk_sym = lookup_minimal_symbol_by_pc (real_stop_pc);
1226   section = find_pc_section (real_stop_pc);
1227   if (thunk_sym.minsym == NULL || section == NULL)
1228     return 0;
1229 
1230   /* The symbol's demangled name should be something like "virtual
1231      thunk to FUNCTION", where FUNCTION is the name of the function
1232      being thunked to.  */
1233   thunk_name = thunk_sym.minsym->demangled_name ();
1234   if (thunk_name == NULL || strstr (thunk_name, " thunk to ") == NULL)
1235     return 0;
1236 
1237   fn_name = strstr (thunk_name, " thunk to ") + strlen (" thunk to ");
1238   fn_sym = lookup_minimal_symbol (fn_name, NULL, section->objfile);
1239   if (fn_sym.minsym == NULL)
1240     return 0;
1241 
1242   method_stop_pc = BMSYMBOL_VALUE_ADDRESS (fn_sym);
1243 
1244   /* Some targets have minimal symbols pointing to function descriptors
1245      (powerpc 64 for example).  Make sure to retrieve the address
1246      of the real function from the function descriptor before passing on
1247      the address to other layers of GDB.  */
1248   func_addr = gdbarch_convert_from_func_ptr_addr (gdbarch, method_stop_pc,
1249 						  current_top_target ());
1250   if (func_addr != 0)
1251     method_stop_pc = func_addr;
1252 
1253   real_stop_pc = gdbarch_skip_trampoline_code
1254 		   (gdbarch, frame, method_stop_pc);
1255   if (real_stop_pc == 0)
1256     real_stop_pc = method_stop_pc;
1257 
1258   return real_stop_pc;
1259 }
1260 
1261 /* A member function is in one these states.  */
1262 
1263 enum definition_style
1264 {
1265   DOES_NOT_EXIST_IN_SOURCE,
1266   DEFAULTED_INSIDE,
1267   DEFAULTED_OUTSIDE,
1268   DELETED,
1269   EXPLICIT,
1270 };
1271 
1272 /* Return how the given field is defined.  */
1273 
1274 static definition_style
1275 get_def_style (struct fn_field *fn, int fieldelem)
1276 {
1277   if (TYPE_FN_FIELD_DELETED (fn, fieldelem))
1278     return DELETED;
1279 
1280   if (TYPE_FN_FIELD_ARTIFICIAL (fn, fieldelem))
1281     return DOES_NOT_EXIST_IN_SOURCE;
1282 
1283   switch (TYPE_FN_FIELD_DEFAULTED (fn, fieldelem))
1284     {
1285     case DW_DEFAULTED_no:
1286       return EXPLICIT;
1287     case DW_DEFAULTED_in_class:
1288       return DEFAULTED_INSIDE;
1289     case DW_DEFAULTED_out_of_class:
1290       return DEFAULTED_OUTSIDE;
1291     default:
1292       break;
1293     }
1294 
1295   return EXPLICIT;
1296 }
1297 
1298 /* Helper functions to determine whether the given definition style
1299    denotes that the definition is user-provided or implicit.
1300    Being defaulted outside the class decl counts as an explicit
1301    user-definition, while being defaulted inside is implicit.  */
1302 
1303 static bool
1304 is_user_provided_def (definition_style def)
1305 {
1306   return def == EXPLICIT || def == DEFAULTED_OUTSIDE;
1307 }
1308 
1309 static bool
1310 is_implicit_def (definition_style def)
1311 {
1312   return def == DOES_NOT_EXIST_IN_SOURCE || def == DEFAULTED_INSIDE;
1313 }
1314 
1315 /* Helper function to decide if METHOD_TYPE is a copy/move
1316    constructor type for CLASS_TYPE.  EXPECTED is the expected
1317    type code for the "right-hand-side" argument.
1318    This function is supposed to be used by the IS_COPY_CONSTRUCTOR_TYPE
1319    and IS_MOVE_CONSTRUCTOR_TYPE functions below.  Normally, you should
1320    not need to call this directly.  */
1321 
1322 static bool
1323 is_copy_or_move_constructor_type (struct type *class_type,
1324 				  struct type *method_type,
1325 				  type_code expected)
1326 {
1327   /* The method should take at least two arguments...  */
1328   if (method_type->num_fields () < 2)
1329     return false;
1330 
1331   /* ...and the second argument should be the same as the class
1332      type, with the expected type code...  */
1333   struct type *arg_type = method_type->field (1).type ();
1334 
1335   if (arg_type->code () != expected)
1336     return false;
1337 
1338   struct type *target = check_typedef (TYPE_TARGET_TYPE (arg_type));
1339   if (!(class_types_same_p (target, class_type)))
1340     return false;
1341 
1342   /* ...and if any of the remaining arguments don't have a default value
1343      then this is not a copy or move constructor, but just a
1344      constructor.  */
1345   for (int i = 2; i < method_type->num_fields (); i++)
1346     {
1347       arg_type = method_type->field (i).type ();
1348       /* FIXME aktemur/2019-10-31: As of this date, neither
1349 	 clang++-7.0.0 nor g++-8.2.0 produce a DW_AT_default_value
1350 	 attribute.  GDB is also not set to read this attribute, yet.
1351 	 Hence, we immediately return false if there are more than
1352 	 2 parameters.
1353 	 GCC bug link:
1354 	 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=42959
1355       */
1356       return false;
1357     }
1358 
1359   return true;
1360 }
1361 
1362 /* Return true if METHOD_TYPE is a copy ctor type for CLASS_TYPE.  */
1363 
1364 static bool
1365 is_copy_constructor_type (struct type *class_type,
1366 			  struct type *method_type)
1367 {
1368   return is_copy_or_move_constructor_type (class_type, method_type,
1369 					   TYPE_CODE_REF);
1370 }
1371 
1372 /* Return true if METHOD_TYPE is a move ctor type for CLASS_TYPE.  */
1373 
1374 static bool
1375 is_move_constructor_type (struct type *class_type,
1376 			  struct type *method_type)
1377 {
1378   return is_copy_or_move_constructor_type (class_type, method_type,
1379 					   TYPE_CODE_RVALUE_REF);
1380 }
1381 
1382 /* Return pass-by-reference information for the given TYPE.
1383 
1384    The rule in the v3 ABI document comes from section 3.1.1.  If the
1385    type has a non-trivial copy constructor or destructor, then the
1386    caller must make a copy (by calling the copy constructor if there
1387    is one or perform the copy itself otherwise), pass the address of
1388    the copy, and then destroy the temporary (if necessary).
1389 
1390    For return values with non-trivial copy/move constructors or
1391    destructors, space will be allocated in the caller, and a pointer
1392    will be passed as the first argument (preceding "this").
1393 
1394    We don't have a bulletproof mechanism for determining whether a
1395    constructor or destructor is trivial.  For GCC and DWARF5 debug
1396    information, we can check the calling_convention attribute,
1397    the 'artificial' flag, the 'defaulted' attribute, and the
1398    'deleted' attribute.  */
1399 
1400 static struct language_pass_by_ref_info
1401 gnuv3_pass_by_reference (struct type *type)
1402 {
1403   int fieldnum, fieldelem;
1404 
1405   type = check_typedef (type);
1406 
1407   /* Start with the default values.  */
1408   struct language_pass_by_ref_info info;
1409 
1410   bool has_cc_attr = false;
1411   bool is_pass_by_value = false;
1412   bool is_dynamic = false;
1413   definition_style cctor_def = DOES_NOT_EXIST_IN_SOURCE;
1414   definition_style dtor_def = DOES_NOT_EXIST_IN_SOURCE;
1415   definition_style mctor_def = DOES_NOT_EXIST_IN_SOURCE;
1416 
1417   /* We're only interested in things that can have methods.  */
1418   if (type->code () != TYPE_CODE_STRUCT
1419       && type->code () != TYPE_CODE_UNION)
1420     return info;
1421 
1422   /* The compiler may have emitted the calling convention attribute.
1423      Note: GCC does not produce this attribute as of version 9.2.1.
1424      Bug link: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92418  */
1425   if (TYPE_CPLUS_CALLING_CONVENTION (type) == DW_CC_pass_by_value)
1426     {
1427       has_cc_attr = true;
1428       is_pass_by_value = true;
1429       /* Do not return immediately.  We have to find out if this type
1430 	 is copy_constructible and destructible.  */
1431     }
1432 
1433   if (TYPE_CPLUS_CALLING_CONVENTION (type) == DW_CC_pass_by_reference)
1434     {
1435       has_cc_attr = true;
1436       is_pass_by_value = false;
1437     }
1438 
1439   /* A dynamic class has a non-trivial copy constructor.
1440      See c++98 section 12.8 Copying class objects [class.copy].  */
1441   if (gnuv3_dynamic_class (type))
1442     is_dynamic = true;
1443 
1444   for (fieldnum = 0; fieldnum < TYPE_NFN_FIELDS (type); fieldnum++)
1445     for (fieldelem = 0; fieldelem < TYPE_FN_FIELDLIST_LENGTH (type, fieldnum);
1446 	 fieldelem++)
1447       {
1448 	struct fn_field *fn = TYPE_FN_FIELDLIST1 (type, fieldnum);
1449 	const char *name = TYPE_FN_FIELDLIST_NAME (type, fieldnum);
1450 	struct type *fieldtype = TYPE_FN_FIELD_TYPE (fn, fieldelem);
1451 
1452 	if (name[0] == '~')
1453 	  {
1454 	    /* We've found a destructor.
1455 	       There should be at most one dtor definition.  */
1456 	    gdb_assert (dtor_def == DOES_NOT_EXIST_IN_SOURCE);
1457 	    dtor_def = get_def_style (fn, fieldelem);
1458 	  }
1459 	else if (is_constructor_name (TYPE_FN_FIELD_PHYSNAME (fn, fieldelem))
1460 		 || TYPE_FN_FIELD_CONSTRUCTOR (fn, fieldelem))
1461 	  {
1462 	    /* FIXME drow/2007-09-23: We could do this using the name of
1463 	       the method and the name of the class instead of dealing
1464 	       with the mangled name.  We don't have a convenient function
1465 	       to strip off both leading scope qualifiers and trailing
1466 	       template arguments yet.  */
1467 	    if (is_copy_constructor_type (type, fieldtype))
1468 	      {
1469 		/* There may be more than one cctors.  E.g.: one that
1470 		   take a const parameter and another that takes a
1471 		   non-const parameter.  Such as:
1472 
1473 		   class K {
1474 		     K (const K &k)...
1475 		     K (K &k)...
1476 		   };
1477 
1478 		   It is sufficient for the type to be non-trivial
1479 		   even only one of the cctors is explicit.
1480 		   Therefore, update the cctor_def value in the
1481 		   implicit -> explicit direction, not backwards.  */
1482 
1483 		if (is_implicit_def (cctor_def))
1484 		  cctor_def = get_def_style (fn, fieldelem);
1485 	      }
1486 	    else if (is_move_constructor_type (type, fieldtype))
1487 	      {
1488 		/* Again, there may be multiple move ctors.  Update the
1489 		   mctor_def value if we found an explicit def and the
1490 		   existing one is not explicit.  Otherwise retain the
1491 		   existing value.  */
1492 		if (is_implicit_def (mctor_def))
1493 		  mctor_def = get_def_style (fn, fieldelem);
1494 	      }
1495 	  }
1496       }
1497 
1498   bool cctor_implicitly_deleted
1499     = (mctor_def != DOES_NOT_EXIST_IN_SOURCE
1500        && cctor_def == DOES_NOT_EXIST_IN_SOURCE);
1501 
1502   bool cctor_explicitly_deleted = (cctor_def == DELETED);
1503 
1504   if (cctor_implicitly_deleted || cctor_explicitly_deleted)
1505     info.copy_constructible = false;
1506 
1507   if (dtor_def == DELETED)
1508     info.destructible = false;
1509 
1510   info.trivially_destructible = is_implicit_def (dtor_def);
1511 
1512   info.trivially_copy_constructible
1513     = (is_implicit_def (cctor_def)
1514        && !is_dynamic);
1515 
1516   info.trivially_copyable
1517     = (info.trivially_copy_constructible
1518        && info.trivially_destructible
1519        && !is_user_provided_def (mctor_def));
1520 
1521   /* Even if all the constructors and destructors were artificial, one
1522      of them may have invoked a non-artificial constructor or
1523      destructor in a base class.  If any base class needs to be passed
1524      by reference, so does this class.  Similarly for members, which
1525      are constructed whenever this class is.  We do not need to worry
1526      about recursive loops here, since we are only looking at members
1527      of complete class type.  Also ignore any static members.  */
1528   for (fieldnum = 0; fieldnum < type->num_fields (); fieldnum++)
1529     if (!field_is_static (&type->field (fieldnum)))
1530       {
1531 	struct type *field_type = type->field (fieldnum).type ();
1532 
1533 	/* For arrays, make the decision based on the element type.  */
1534 	if (field_type->code () == TYPE_CODE_ARRAY)
1535 	  field_type = check_typedef (TYPE_TARGET_TYPE (field_type));
1536 
1537 	struct language_pass_by_ref_info field_info
1538 	  = gnuv3_pass_by_reference (field_type);
1539 
1540 	if (!field_info.copy_constructible)
1541 	  info.copy_constructible = false;
1542 	if (!field_info.destructible)
1543 	  info.destructible = false;
1544 	if (!field_info.trivially_copyable)
1545 	  info.trivially_copyable = false;
1546 	if (!field_info.trivially_copy_constructible)
1547 	  info.trivially_copy_constructible = false;
1548 	if (!field_info.trivially_destructible)
1549 	  info.trivially_destructible = false;
1550       }
1551 
1552   /* Consistency check.  */
1553   if (has_cc_attr && info.trivially_copyable != is_pass_by_value)
1554     {
1555       /* DWARF CC attribute is not the same as the inferred value;
1556 	 use the DWARF attribute.  */
1557       info.trivially_copyable = is_pass_by_value;
1558     }
1559 
1560   return info;
1561 }
1562 
1563 static void
1564 init_gnuv3_ops (void)
1565 {
1566   vtable_type_gdbarch_data
1567     = gdbarch_data_register_post_init (build_gdb_vtable_type);
1568   std_type_info_gdbarch_data
1569     = gdbarch_data_register_post_init (build_std_type_info_type);
1570 
1571   gnu_v3_abi_ops.shortname = "gnu-v3";
1572   gnu_v3_abi_ops.longname = "GNU G++ Version 3 ABI";
1573   gnu_v3_abi_ops.doc = "G++ Version 3 ABI";
1574   gnu_v3_abi_ops.is_destructor_name =
1575     (enum dtor_kinds (*) (const char *))is_gnu_v3_mangled_dtor;
1576   gnu_v3_abi_ops.is_constructor_name =
1577     (enum ctor_kinds (*) (const char *))is_gnu_v3_mangled_ctor;
1578   gnu_v3_abi_ops.is_vtable_name = gnuv3_is_vtable_name;
1579   gnu_v3_abi_ops.is_operator_name = gnuv3_is_operator_name;
1580   gnu_v3_abi_ops.rtti_type = gnuv3_rtti_type;
1581   gnu_v3_abi_ops.virtual_fn_field = gnuv3_virtual_fn_field;
1582   gnu_v3_abi_ops.baseclass_offset = gnuv3_baseclass_offset;
1583   gnu_v3_abi_ops.print_method_ptr = gnuv3_print_method_ptr;
1584   gnu_v3_abi_ops.method_ptr_size = gnuv3_method_ptr_size;
1585   gnu_v3_abi_ops.make_method_ptr = gnuv3_make_method_ptr;
1586   gnu_v3_abi_ops.method_ptr_to_value = gnuv3_method_ptr_to_value;
1587   gnu_v3_abi_ops.print_vtable = gnuv3_print_vtable;
1588   gnu_v3_abi_ops.get_typeid = gnuv3_get_typeid;
1589   gnu_v3_abi_ops.get_typeid_type = gnuv3_get_typeid_type;
1590   gnu_v3_abi_ops.get_type_from_type_info = gnuv3_get_type_from_type_info;
1591   gnu_v3_abi_ops.get_typename_from_type_info
1592     = gnuv3_get_typename_from_type_info;
1593   gnu_v3_abi_ops.skip_trampoline = gnuv3_skip_trampoline;
1594   gnu_v3_abi_ops.pass_by_reference = gnuv3_pass_by_reference;
1595 }
1596 
1597 void _initialize_gnu_v3_abi ();
1598 void
1599 _initialize_gnu_v3_abi ()
1600 {
1601   init_gnuv3_ops ();
1602 
1603   register_cp_abi (&gnu_v3_abi_ops);
1604   set_cp_abi_as_auto_default (gnu_v3_abi_ops.shortname);
1605 }
1606