Regenerate AArch64 opcodes files
[binutils-gdb.git] / gdb / valops.c
blobbe907440a59ba75f8eac7fed6c97b9997bd47ef0
1 /* Perform non-arithmetic operations on values, for GDB.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "defs.h"
21 #include "symtab.h"
22 #include "gdbtypes.h"
23 #include "value.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "gdbcore.h"
27 #include "target.h"
28 #include "demangle.h"
29 #include "language.h"
30 #include "gdbcmd.h"
31 #include "regcache.h"
32 #include "cp-abi.h"
33 #include "block.h"
34 #include "infcall.h"
35 #include "dictionary.h"
36 #include "cp-support.h"
37 #include "target-float.h"
38 #include "tracepoint.h"
39 #include "observable.h"
40 #include "objfiles.h"
41 #include "extension.h"
42 #include "gdbtypes.h"
43 #include "gdbsupport/byte-vector.h"
44 #include "typeprint.h"
46 /* Local functions. */
48 static int typecmp (bool staticp, bool varargs, int nargs,
49 struct field t1[], const gdb::array_view<value *> t2);
51 static struct value *search_struct_field (const char *, struct value *,
52 struct type *, int);
54 static struct value *search_struct_method (const char *, struct value **,
55 std::optional<gdb::array_view<value *>>,
56 LONGEST, int *, struct type *);
58 static int find_oload_champ_namespace (gdb::array_view<value *> args,
59 const char *, const char *,
60 std::vector<symbol *> *oload_syms,
61 badness_vector *,
62 const int no_adl);
64 static int find_oload_champ_namespace_loop (gdb::array_view<value *> args,
65 const char *, const char *,
66 int, std::vector<symbol *> *oload_syms,
67 badness_vector *, int *,
68 const int no_adl);
70 static int find_oload_champ (gdb::array_view<value *> args,
71 size_t num_fns,
72 fn_field *methods,
73 xmethod_worker_up *xmethods,
74 symbol **functions,
75 badness_vector *oload_champ_bv);
77 static int oload_method_static_p (struct fn_field *, int);
79 enum oload_classification { STANDARD, NON_STANDARD, INCOMPATIBLE };
81 static enum oload_classification classify_oload_match
82 (const badness_vector &, int, int);
84 static struct value *value_struct_elt_for_reference (struct type *,
85 int, struct type *,
86 const char *,
87 struct type *,
88 int, enum noside);
90 static struct value *value_namespace_elt (const struct type *,
91 const char *, int , enum noside);
93 static struct value *value_maybe_namespace_elt (const struct type *,
94 const char *, int,
95 enum noside);
97 static CORE_ADDR allocate_space_in_inferior (int);
99 static struct value *cast_into_complex (struct type *, struct value *);
101 bool overload_resolution = false;
102 static void
103 show_overload_resolution (struct ui_file *file, int from_tty,
104 struct cmd_list_element *c,
105 const char *value)
107 gdb_printf (file, _("Overload resolution in evaluating "
108 "C++ functions is %s.\n"),
109 value);
112 /* Find the address of function name NAME in the inferior. If OBJF_P
113 is non-NULL, *OBJF_P will be set to the OBJFILE where the function
114 is defined. */
116 struct value *
117 find_function_in_inferior (const char *name, struct objfile **objf_p)
119 struct block_symbol sym;
121 sym = lookup_symbol (name, nullptr, SEARCH_TYPE_DOMAIN, nullptr);
122 if (sym.symbol != NULL)
124 if (objf_p)
125 *objf_p = sym.symbol->objfile ();
127 return value_of_variable (sym.symbol, sym.block);
129 else
131 struct bound_minimal_symbol msymbol =
132 lookup_bound_minimal_symbol (name);
134 if (msymbol.minsym != NULL)
136 struct objfile *objfile = msymbol.objfile;
137 struct gdbarch *gdbarch = objfile->arch ();
139 struct type *type;
140 CORE_ADDR maddr;
141 type = lookup_pointer_type (builtin_type (gdbarch)->builtin_char);
142 type = lookup_function_type (type);
143 type = lookup_pointer_type (type);
144 maddr = msymbol.value_address ();
146 if (objf_p)
147 *objf_p = objfile;
149 return value_from_pointer (type, maddr);
151 else
153 if (!target_has_execution ())
154 error (_("evaluation of this expression "
155 "requires the target program to be active"));
156 else
157 error (_("evaluation of this expression requires the "
158 "program to have a function \"%s\"."),
159 name);
164 /* Allocate NBYTES of space in the inferior using the inferior's
165 malloc and return a value that is a pointer to the allocated
166 space. */
168 struct value *
169 value_allocate_space_in_inferior (int len)
171 struct objfile *objf;
172 struct value *val = find_function_in_inferior ("malloc", &objf);
173 struct gdbarch *gdbarch = objf->arch ();
174 struct value *blocklen;
176 blocklen = value_from_longest (builtin_type (gdbarch)->builtin_int, len);
177 val = call_function_by_hand (val, NULL, blocklen);
178 if (value_logical_not (val))
180 if (!target_has_execution ())
181 error (_("No memory available to program now: "
182 "you need to start the target first"));
183 else
184 error (_("No memory available to program: call to malloc failed"));
186 return val;
189 static CORE_ADDR
190 allocate_space_in_inferior (int len)
192 return value_as_long (value_allocate_space_in_inferior (len));
195 /* Cast struct value VAL to type TYPE and return as a value.
196 Both type and val must be of TYPE_CODE_STRUCT or TYPE_CODE_UNION
197 for this to work. Typedef to one of the codes is permitted.
198 Returns NULL if the cast is neither an upcast nor a downcast. */
200 static struct value *
201 value_cast_structs (struct type *type, struct value *v2)
203 struct type *t1;
204 struct type *t2;
205 struct value *v;
207 gdb_assert (type != NULL && v2 != NULL);
209 t1 = check_typedef (type);
210 t2 = check_typedef (v2->type ());
212 /* Check preconditions. */
213 gdb_assert ((t1->code () == TYPE_CODE_STRUCT
214 || t1->code () == TYPE_CODE_UNION)
215 && !!"Precondition is that type is of STRUCT or UNION kind.");
216 gdb_assert ((t2->code () == TYPE_CODE_STRUCT
217 || t2->code () == TYPE_CODE_UNION)
218 && !!"Precondition is that value is of STRUCT or UNION kind");
220 if (t1->name () != NULL
221 && t2->name () != NULL
222 && !strcmp (t1->name (), t2->name ()))
223 return NULL;
225 /* Upcasting: look in the type of the source to see if it contains the
226 type of the target as a superclass. If so, we'll need to
227 offset the pointer rather than just change its type. */
228 if (t1->name () != NULL)
230 v = search_struct_field (t1->name (),
231 v2, t2, 1);
232 if (v)
233 return v;
236 /* Downcasting: look in the type of the target to see if it contains the
237 type of the source as a superclass. If so, we'll need to
238 offset the pointer rather than just change its type. */
239 if (t2->name () != NULL)
241 /* Try downcasting using the run-time type of the value. */
242 int full, using_enc;
243 LONGEST top;
244 struct type *real_type;
246 real_type = value_rtti_type (v2, &full, &top, &using_enc);
247 if (real_type)
249 v = value_full_object (v2, real_type, full, top, using_enc);
250 v = value_at_lazy (real_type, v->address ());
251 real_type = v->type ();
253 /* We might be trying to cast to the outermost enclosing
254 type, in which case search_struct_field won't work. */
255 if (real_type->name () != NULL
256 && !strcmp (real_type->name (), t1->name ()))
257 return v;
259 v = search_struct_field (t2->name (), v, real_type, 1);
260 if (v)
261 return v;
264 /* Try downcasting using information from the destination type
265 T2. This wouldn't work properly for classes with virtual
266 bases, but those were handled above. */
267 v = search_struct_field (t2->name (),
268 value::zero (t1, not_lval), t1, 1);
269 if (v)
271 /* Downcasting is possible (t1 is superclass of v2). */
272 CORE_ADDR addr2 = v2->address () + v2->embedded_offset ();
274 addr2 -= v->address () + v->embedded_offset ();
275 return value_at (type, addr2);
279 return NULL;
282 /* Cast one pointer or reference type to another. Both TYPE and
283 the type of ARG2 should be pointer types, or else both should be
284 reference types. If SUBCLASS_CHECK is non-zero, this will force a
285 check to see whether TYPE is a superclass of ARG2's type. If
286 SUBCLASS_CHECK is zero, then the subclass check is done only when
287 ARG2 is itself non-zero. Returns the new pointer or reference. */
289 struct value *
290 value_cast_pointers (struct type *type, struct value *arg2,
291 int subclass_check)
293 struct type *type1 = check_typedef (type);
294 struct type *type2 = check_typedef (arg2->type ());
295 struct type *t1 = check_typedef (type1->target_type ());
296 struct type *t2 = check_typedef (type2->target_type ());
298 if (t1->code () == TYPE_CODE_STRUCT
299 && t2->code () == TYPE_CODE_STRUCT
300 && (subclass_check || !value_logical_not (arg2)))
302 struct value *v2;
304 if (TYPE_IS_REFERENCE (type2))
305 v2 = coerce_ref (arg2);
306 else
307 v2 = value_ind (arg2);
308 gdb_assert (check_typedef (v2->type ())->code ()
309 == TYPE_CODE_STRUCT && !!"Why did coercion fail?");
310 v2 = value_cast_structs (t1, v2);
311 /* At this point we have what we can have, un-dereference if needed. */
312 if (v2)
314 struct value *v = value_addr (v2);
316 v->deprecated_set_type (type);
317 return v;
321 /* No superclass found, just change the pointer type. */
322 arg2 = arg2->copy ();
323 arg2->deprecated_set_type (type);
324 arg2->set_enclosing_type (type);
325 arg2->set_pointed_to_offset (0); /* pai: chk_val */
326 return arg2;
329 /* See value.h. */
331 gdb_mpq
332 value_to_gdb_mpq (struct value *value)
334 struct type *type = check_typedef (value->type ());
336 gdb_mpq result;
337 if (is_floating_type (type))
338 result = target_float_to_host_double (value->contents ().data (), type);
339 else
341 gdb_assert (is_integral_type (type)
342 || is_fixed_point_type (type));
344 gdb_mpz vz;
345 vz.read (value->contents (), type_byte_order (type),
346 type->is_unsigned ());
347 result = vz;
349 if (is_fixed_point_type (type))
350 result *= type->fixed_point_scaling_factor ();
353 return result;
356 /* Assuming that TO_TYPE is a fixed point type, return a value
357 corresponding to the cast of FROM_VAL to that type. */
359 static struct value *
360 value_cast_to_fixed_point (struct type *to_type, struct value *from_val)
362 struct type *from_type = from_val->type ();
364 if (from_type == to_type)
365 return from_val;
367 if (!is_floating_type (from_type)
368 && !is_integral_type (from_type)
369 && !is_fixed_point_type (from_type))
370 error (_("Invalid conversion from type %s to fixed point type %s"),
371 from_type->name (), to_type->name ());
373 gdb_mpq vq = value_to_gdb_mpq (from_val);
375 /* Divide that value by the scaling factor to obtain the unscaled
376 value, first in rational form, and then in integer form. */
378 vq /= to_type->fixed_point_scaling_factor ();
379 gdb_mpz unscaled = vq.get_rounded ();
381 /* Finally, create the result value, and pack the unscaled value
382 in it. */
383 struct value *result = value::allocate (to_type);
384 unscaled.write (result->contents_raw (),
385 type_byte_order (to_type),
386 to_type->is_unsigned ());
388 return result;
391 /* Cast value ARG2 to type TYPE and return as a value.
392 More general than a C cast: accepts any two types of the same length,
393 and if ARG2 is an lvalue it can be cast into anything at all. */
394 /* In C++, casts may change pointer or object representations. */
396 struct value *
397 value_cast (struct type *type, struct value *arg2)
399 enum type_code code1;
400 enum type_code code2;
401 int scalar;
402 struct type *type2;
404 int convert_to_boolean = 0;
406 /* TYPE might be equal in meaning to the existing type of ARG2, but for
407 many reasons, might be a different type object (e.g. TYPE might be a
408 gdbarch owned type, while ARG2->type () could be an objfile owned
409 type).
411 In this case we want to preserve the LVAL of ARG2 as this allows the
412 resulting value to be used in more places. We do this by calling
413 VALUE_COPY if appropriate. */
414 if (types_deeply_equal (arg2->type (), type))
416 /* If the types are exactly equal then we can avoid creating a new
417 value completely. */
418 if (arg2->type () != type)
420 arg2 = arg2->copy ();
421 arg2->deprecated_set_type (type);
423 return arg2;
426 if (is_fixed_point_type (type))
427 return value_cast_to_fixed_point (type, arg2);
429 /* Check if we are casting struct reference to struct reference. */
430 if (TYPE_IS_REFERENCE (check_typedef (type)))
432 /* We dereference type; then we recurse and finally
433 we generate value of the given reference. Nothing wrong with
434 that. */
435 struct type *t1 = check_typedef (type);
436 struct type *dereftype = check_typedef (t1->target_type ());
437 struct value *val = value_cast (dereftype, arg2);
439 return value_ref (val, t1->code ());
442 if (TYPE_IS_REFERENCE (check_typedef (arg2->type ())))
443 /* We deref the value and then do the cast. */
444 return value_cast (type, coerce_ref (arg2));
446 /* Strip typedefs / resolve stubs in order to get at the type's
447 code/length, but remember the original type, to use as the
448 resulting type of the cast, in case it was a typedef. */
449 struct type *to_type = type;
451 type = check_typedef (type);
452 code1 = type->code ();
453 arg2 = coerce_ref (arg2);
454 type2 = check_typedef (arg2->type ());
456 /* You can't cast to a reference type. See value_cast_pointers
457 instead. */
458 gdb_assert (!TYPE_IS_REFERENCE (type));
460 /* A cast to an undetermined-length array_type, such as
461 (TYPE [])OBJECT, is treated like a cast to (TYPE [N])OBJECT,
462 where N is sizeof(OBJECT)/sizeof(TYPE). */
463 if (code1 == TYPE_CODE_ARRAY)
465 struct type *element_type = type->target_type ();
466 unsigned element_length = check_typedef (element_type)->length ();
468 if (element_length > 0 && type->bounds ()->high.kind () == PROP_UNDEFINED)
470 struct type *range_type = type->index_type ();
471 int val_length = type2->length ();
472 LONGEST low_bound, high_bound, new_length;
474 if (!get_discrete_bounds (range_type, &low_bound, &high_bound))
475 low_bound = 0, high_bound = 0;
476 new_length = val_length / element_length;
477 if (val_length % element_length != 0)
478 warning (_("array element type size does not "
479 "divide object size in cast"));
480 /* FIXME-type-allocation: need a way to free this type when
481 we are done with it. */
482 type_allocator alloc (range_type->target_type ());
483 range_type = create_static_range_type (alloc,
484 range_type->target_type (),
485 low_bound,
486 new_length + low_bound - 1);
487 arg2->deprecated_set_type (create_array_type (alloc,
488 element_type,
489 range_type));
490 return arg2;
494 if (current_language->c_style_arrays_p ()
495 && type2->code () == TYPE_CODE_ARRAY
496 && !type2->is_vector ())
497 arg2 = value_coerce_array (arg2);
499 if (type2->code () == TYPE_CODE_FUNC)
500 arg2 = value_coerce_function (arg2);
502 type2 = check_typedef (arg2->type ());
503 code2 = type2->code ();
505 if (code1 == TYPE_CODE_COMPLEX)
506 return cast_into_complex (to_type, arg2);
507 if (code1 == TYPE_CODE_BOOL)
509 code1 = TYPE_CODE_INT;
510 convert_to_boolean = 1;
512 if (code1 == TYPE_CODE_CHAR)
513 code1 = TYPE_CODE_INT;
514 if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
515 code2 = TYPE_CODE_INT;
517 scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
518 || code2 == TYPE_CODE_DECFLOAT || code2 == TYPE_CODE_ENUM
519 || code2 == TYPE_CODE_RANGE
520 || is_fixed_point_type (type2));
522 if ((code1 == TYPE_CODE_STRUCT || code1 == TYPE_CODE_UNION)
523 && (code2 == TYPE_CODE_STRUCT || code2 == TYPE_CODE_UNION)
524 && type->name () != 0)
526 struct value *v = value_cast_structs (to_type, arg2);
528 if (v)
529 return v;
532 if (is_floating_type (type) && scalar)
534 if (is_floating_value (arg2))
536 struct value *v = value::allocate (to_type);
537 target_float_convert (arg2->contents ().data (), type2,
538 v->contents_raw ().data (), type);
539 return v;
541 else if (is_fixed_point_type (type2))
543 gdb_mpq fp_val;
545 fp_val.read_fixed_point (arg2->contents (),
546 type_byte_order (type2),
547 type2->is_unsigned (),
548 type2->fixed_point_scaling_factor ());
550 struct value *v = value::allocate (to_type);
551 target_float_from_host_double (v->contents_raw ().data (),
552 to_type, fp_val.as_double ());
553 return v;
556 /* The only option left is an integral type. */
557 if (type2->is_unsigned ())
558 return value_from_ulongest (to_type, value_as_long (arg2));
559 else
560 return value_from_longest (to_type, value_as_long (arg2));
562 else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
563 || code1 == TYPE_CODE_RANGE)
564 && (scalar || code2 == TYPE_CODE_PTR
565 || code2 == TYPE_CODE_MEMBERPTR))
567 gdb_mpz longest;
569 /* When we cast pointers to integers, we mustn't use
570 gdbarch_pointer_to_address to find the address the pointer
571 represents, as value_as_long would. GDB should evaluate
572 expressions just as the compiler would --- and the compiler
573 sees a cast as a simple reinterpretation of the pointer's
574 bits. */
575 if (code2 == TYPE_CODE_PTR)
576 longest = extract_unsigned_integer (arg2->contents (),
577 type_byte_order (type2));
578 else
579 longest = value_as_mpz (arg2);
580 if (convert_to_boolean)
581 longest = bool (longest);
583 return value_from_mpz (to_type, longest);
585 else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT
586 || code2 == TYPE_CODE_ENUM
587 || code2 == TYPE_CODE_RANGE))
589 /* type->length () is the length of a pointer, but we really
590 want the length of an address! -- we are really dealing with
591 addresses (i.e., gdb representations) not pointers (i.e.,
592 target representations) here.
594 This allows things like "print *(int *)0x01000234" to work
595 without printing a misleading message -- which would
596 otherwise occur when dealing with a target having two byte
597 pointers and four byte addresses. */
599 int addr_bit = gdbarch_addr_bit (type2->arch ());
600 gdb_mpz longest = value_as_mpz (arg2);
602 gdb_mpz addr_val = gdb_mpz (1) << addr_bit;
603 if (longest >= addr_val || longest <= -addr_val)
604 warning (_("value truncated"));
606 return value_from_mpz (to_type, longest);
608 else if (code1 == TYPE_CODE_METHODPTR && code2 == TYPE_CODE_INT
609 && value_as_long (arg2) == 0)
611 struct value *result = value::allocate (to_type);
613 cplus_make_method_ptr (to_type,
614 result->contents_writeable ().data (), 0, 0);
615 return result;
617 else if (code1 == TYPE_CODE_MEMBERPTR && code2 == TYPE_CODE_INT
618 && value_as_long (arg2) == 0)
620 /* The Itanium C++ ABI represents NULL pointers to members as
621 minus one, instead of biasing the normal case. */
622 return value_from_longest (to_type, -1);
624 else if (code1 == TYPE_CODE_ARRAY && type->is_vector ()
625 && code2 == TYPE_CODE_ARRAY && type2->is_vector ()
626 && type->length () != type2->length ())
627 error (_("Cannot convert between vector values of different sizes"));
628 else if (code1 == TYPE_CODE_ARRAY && type->is_vector () && scalar
629 && type->length () != type2->length ())
630 error (_("can only cast scalar to vector of same size"));
631 else if (code1 == TYPE_CODE_VOID)
633 return value::zero (to_type, not_lval);
635 else if (type->length () == type2->length ())
637 if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
638 return value_cast_pointers (to_type, arg2, 0);
640 arg2 = arg2->copy ();
641 arg2->deprecated_set_type (to_type);
642 arg2->set_enclosing_type (to_type);
643 arg2->set_pointed_to_offset (0); /* pai: chk_val */
644 return arg2;
646 else if (arg2->lval () == lval_memory)
647 return value_at_lazy (to_type, arg2->address ());
648 else
650 if (current_language->la_language == language_ada)
651 error (_("Invalid type conversion."));
652 error (_("Invalid cast."));
656 /* The C++ reinterpret_cast operator. */
658 struct value *
659 value_reinterpret_cast (struct type *type, struct value *arg)
661 struct value *result;
662 struct type *real_type = check_typedef (type);
663 struct type *arg_type, *dest_type;
664 int is_ref = 0;
665 enum type_code dest_code, arg_code;
667 /* Do reference, function, and array conversion. */
668 arg = coerce_array (arg);
670 /* Attempt to preserve the type the user asked for. */
671 dest_type = type;
673 /* If we are casting to a reference type, transform
674 reinterpret_cast<T&[&]>(V) to *reinterpret_cast<T*>(&V). */
675 if (TYPE_IS_REFERENCE (real_type))
677 is_ref = 1;
678 arg = value_addr (arg);
679 dest_type = lookup_pointer_type (dest_type->target_type ());
680 real_type = lookup_pointer_type (real_type);
683 arg_type = arg->type ();
685 dest_code = real_type->code ();
686 arg_code = arg_type->code ();
688 /* We can convert pointer types, or any pointer type to int, or int
689 type to pointer. */
690 if ((dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_INT)
691 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_PTR)
692 || (dest_code == TYPE_CODE_METHODPTR && arg_code == TYPE_CODE_INT)
693 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_METHODPTR)
694 || (dest_code == TYPE_CODE_MEMBERPTR && arg_code == TYPE_CODE_INT)
695 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_MEMBERPTR)
696 || (dest_code == arg_code
697 && (dest_code == TYPE_CODE_PTR
698 || dest_code == TYPE_CODE_METHODPTR
699 || dest_code == TYPE_CODE_MEMBERPTR)))
700 result = value_cast (dest_type, arg);
701 else
702 error (_("Invalid reinterpret_cast"));
704 if (is_ref)
705 result = value_cast (type, value_ref (value_ind (result),
706 type->code ()));
708 return result;
711 /* A helper for value_dynamic_cast. This implements the first of two
712 runtime checks: we iterate over all the base classes of the value's
713 class which are equal to the desired class; if only one of these
714 holds the value, then it is the answer. */
716 static int
717 dynamic_cast_check_1 (struct type *desired_type,
718 const gdb_byte *valaddr,
719 LONGEST embedded_offset,
720 CORE_ADDR address,
721 struct value *val,
722 struct type *search_type,
723 CORE_ADDR arg_addr,
724 struct type *arg_type,
725 struct value **result)
727 int i, result_count = 0;
729 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
731 LONGEST offset = baseclass_offset (search_type, i, valaddr,
732 embedded_offset,
733 address, val);
735 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
737 if (address + embedded_offset + offset >= arg_addr
738 && address + embedded_offset + offset < arg_addr + arg_type->length ())
740 ++result_count;
741 if (!*result)
742 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
743 address + embedded_offset + offset);
746 else
747 result_count += dynamic_cast_check_1 (desired_type,
748 valaddr,
749 embedded_offset + offset,
750 address, val,
751 TYPE_BASECLASS (search_type, i),
752 arg_addr,
753 arg_type,
754 result);
757 return result_count;
760 /* A helper for value_dynamic_cast. This implements the second of two
761 runtime checks: we look for a unique public sibling class of the
762 argument's declared class. */
764 static int
765 dynamic_cast_check_2 (struct type *desired_type,
766 const gdb_byte *valaddr,
767 LONGEST embedded_offset,
768 CORE_ADDR address,
769 struct value *val,
770 struct type *search_type,
771 struct value **result)
773 int i, result_count = 0;
775 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
777 LONGEST offset;
779 if (! BASETYPE_VIA_PUBLIC (search_type, i))
780 continue;
782 offset = baseclass_offset (search_type, i, valaddr, embedded_offset,
783 address, val);
784 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
786 ++result_count;
787 if (*result == NULL)
788 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
789 address + embedded_offset + offset);
791 else
792 result_count += dynamic_cast_check_2 (desired_type,
793 valaddr,
794 embedded_offset + offset,
795 address, val,
796 TYPE_BASECLASS (search_type, i),
797 result);
800 return result_count;
803 /* The C++ dynamic_cast operator. */
805 struct value *
806 value_dynamic_cast (struct type *type, struct value *arg)
808 int full, using_enc;
809 LONGEST top;
810 struct type *resolved_type = check_typedef (type);
811 struct type *arg_type = check_typedef (arg->type ());
812 struct type *class_type, *rtti_type;
813 struct value *result, *tem, *original_arg = arg;
814 CORE_ADDR addr;
815 int is_ref = TYPE_IS_REFERENCE (resolved_type);
817 if (resolved_type->code () != TYPE_CODE_PTR
818 && !TYPE_IS_REFERENCE (resolved_type))
819 error (_("Argument to dynamic_cast must be a pointer or reference type"));
820 if (resolved_type->target_type ()->code () != TYPE_CODE_VOID
821 && resolved_type->target_type ()->code () != TYPE_CODE_STRUCT)
822 error (_("Argument to dynamic_cast must be pointer to class or `void *'"));
824 class_type = check_typedef (resolved_type->target_type ());
825 if (resolved_type->code () == TYPE_CODE_PTR)
827 if (arg_type->code () != TYPE_CODE_PTR
828 && ! (arg_type->code () == TYPE_CODE_INT
829 && value_as_long (arg) == 0))
830 error (_("Argument to dynamic_cast does not have pointer type"));
831 if (arg_type->code () == TYPE_CODE_PTR)
833 arg_type = check_typedef (arg_type->target_type ());
834 if (arg_type->code () != TYPE_CODE_STRUCT)
835 error (_("Argument to dynamic_cast does "
836 "not have pointer to class type"));
839 /* Handle NULL pointers. */
840 if (value_as_long (arg) == 0)
841 return value::zero (type, not_lval);
843 arg = value_ind (arg);
845 else
847 if (arg_type->code () != TYPE_CODE_STRUCT)
848 error (_("Argument to dynamic_cast does not have class type"));
851 /* If the classes are the same, just return the argument. */
852 if (class_types_same_p (class_type, arg_type))
853 return value_cast (type, original_arg);
855 /* If the target type is a unique base class of the argument's
856 declared type, just cast it. */
857 if (is_ancestor (class_type, arg_type))
859 if (is_unique_ancestor (class_type, arg))
860 return value_cast (type, original_arg);
861 error (_("Ambiguous dynamic_cast"));
864 rtti_type = value_rtti_type (arg, &full, &top, &using_enc);
865 if (! rtti_type)
866 error (_("Couldn't determine value's most derived type for dynamic_cast"));
868 /* Compute the most derived object's address. */
869 addr = arg->address ();
870 if (full)
872 /* Done. */
874 else if (using_enc)
875 addr += top;
876 else
877 addr += top + arg->embedded_offset ();
879 /* dynamic_cast<void *> means to return a pointer to the
880 most-derived object. */
881 if (resolved_type->code () == TYPE_CODE_PTR
882 && resolved_type->target_type ()->code () == TYPE_CODE_VOID)
883 return value_at_lazy (type, addr);
885 tem = value_at (resolved_type->target_type (), addr);
886 type = (is_ref
887 ? lookup_reference_type (tem->type (), resolved_type->code ())
888 : lookup_pointer_type (tem->type ()));
890 /* The first dynamic check specified in 5.2.7. */
891 if (is_public_ancestor (arg_type, resolved_type->target_type ()))
893 if (class_types_same_p (rtti_type, resolved_type->target_type ()))
894 return (is_ref
895 ? value_ref (tem, resolved_type->code ())
896 : value_addr (tem));
897 result = NULL;
898 if (dynamic_cast_check_1 (resolved_type->target_type (),
899 tem->contents_for_printing ().data (),
900 tem->embedded_offset (),
901 tem->address (), tem,
902 rtti_type, addr,
903 arg_type,
904 &result) == 1)
905 return value_cast (type,
906 is_ref
907 ? value_ref (result, resolved_type->code ())
908 : value_addr (result));
911 /* The second dynamic check specified in 5.2.7. */
912 result = NULL;
913 if (is_public_ancestor (arg_type, rtti_type)
914 && dynamic_cast_check_2 (resolved_type->target_type (),
915 tem->contents_for_printing ().data (),
916 tem->embedded_offset (),
917 tem->address (), tem,
918 rtti_type, &result) == 1)
919 return value_cast (type,
920 is_ref
921 ? value_ref (result, resolved_type->code ())
922 : value_addr (result));
924 if (resolved_type->code () == TYPE_CODE_PTR)
925 return value::zero (type, not_lval);
927 error (_("dynamic_cast failed"));
930 /* Create a not_lval value of numeric type TYPE that is one, and return it. */
932 struct value *
933 value_one (struct type *type)
935 struct type *type1 = check_typedef (type);
936 struct value *val;
938 if (is_integral_type (type1) || is_floating_type (type1))
940 val = value_from_longest (type, (LONGEST) 1);
942 else if (type1->code () == TYPE_CODE_ARRAY && type1->is_vector ())
944 struct type *eltype = check_typedef (type1->target_type ());
945 int i;
946 LONGEST low_bound, high_bound;
948 if (!get_array_bounds (type1, &low_bound, &high_bound))
949 error (_("Could not determine the vector bounds"));
951 val = value::allocate (type);
952 gdb::array_view<gdb_byte> val_contents = val->contents_writeable ();
953 int elt_len = eltype->length ();
955 for (i = 0; i < high_bound - low_bound + 1; i++)
957 value *tmp = value_one (eltype);
958 copy (tmp->contents_all (),
959 val_contents.slice (i * elt_len, elt_len));
962 else
964 error (_("Not a numeric type."));
967 /* value_one result is never used for assignments to. */
968 gdb_assert (val->lval () == not_lval);
970 return val;
973 /* Helper function for value_at, value_at_lazy, and value_at_lazy_stack.
974 The type of the created value may differ from the passed type TYPE.
975 Make sure to retrieve the returned values's new type after this call
976 e.g. in case the type is a variable length array. */
978 static struct value *
979 get_value_at (struct type *type, CORE_ADDR addr, const frame_info_ptr &frame,
980 int lazy)
982 struct value *val;
984 if (check_typedef (type)->code () == TYPE_CODE_VOID)
985 error (_("Attempt to dereference a generic pointer."));
987 val = value_from_contents_and_address (type, NULL, addr, frame);
989 if (!lazy)
990 val->fetch_lazy ();
992 return val;
995 /* Return a value with type TYPE located at ADDR.
997 Call value_at only if the data needs to be fetched immediately;
998 if we can be 'lazy' and defer the fetch, perhaps indefinitely, call
999 value_at_lazy instead. value_at_lazy simply records the address of
1000 the data and sets the lazy-evaluation-required flag. The lazy flag
1001 is tested in the value_contents macro, which is used if and when
1002 the contents are actually required. The type of the created value
1003 may differ from the passed type TYPE. Make sure to retrieve the
1004 returned values's new type after this call e.g. in case the type
1005 is a variable length array.
1007 Note: value_at does *NOT* handle embedded offsets; perform such
1008 adjustments before or after calling it. */
1010 struct value *
1011 value_at (struct type *type, CORE_ADDR addr)
1013 return get_value_at (type, addr, nullptr, 0);
1016 /* See value.h. */
1018 struct value *
1019 value_at_non_lval (struct type *type, CORE_ADDR addr)
1021 struct value *result = value_at (type, addr);
1022 result->set_lval (not_lval);
1023 return result;
1026 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).
1027 The type of the created value may differ from the passed type TYPE.
1028 Make sure to retrieve the returned values's new type after this call
1029 e.g. in case the type is a variable length array. */
1031 struct value *
1032 value_at_lazy (struct type *type, CORE_ADDR addr, const frame_info_ptr &frame)
1034 return get_value_at (type, addr, frame, 1);
1037 void
1038 read_value_memory (struct value *val, LONGEST bit_offset,
1039 bool stack, CORE_ADDR memaddr,
1040 gdb_byte *buffer, size_t length)
1042 ULONGEST xfered_total = 0;
1043 struct gdbarch *arch = val->arch ();
1044 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1045 enum target_object object;
1047 object = stack ? TARGET_OBJECT_STACK_MEMORY : TARGET_OBJECT_MEMORY;
1049 while (xfered_total < length)
1051 enum target_xfer_status status;
1052 ULONGEST xfered_partial;
1054 status = target_xfer_partial (current_inferior ()->top_target (),
1055 object, NULL,
1056 buffer + xfered_total * unit_size, NULL,
1057 memaddr + xfered_total,
1058 length - xfered_total,
1059 &xfered_partial);
1061 if (status == TARGET_XFER_OK)
1062 /* nothing */;
1063 else if (status == TARGET_XFER_UNAVAILABLE)
1064 val->mark_bits_unavailable ((xfered_total * HOST_CHAR_BIT
1065 + bit_offset),
1066 xfered_partial * HOST_CHAR_BIT);
1067 else if (status == TARGET_XFER_EOF)
1068 memory_error (TARGET_XFER_E_IO, memaddr + xfered_total);
1069 else
1070 memory_error (status, memaddr + xfered_total);
1072 xfered_total += xfered_partial;
1073 QUIT;
1077 /* Store the contents of FROMVAL into the location of TOVAL.
1078 Return a new value with the location of TOVAL and contents of FROMVAL. */
1080 struct value *
1081 value_assign (struct value *toval, struct value *fromval)
1083 struct type *type;
1084 struct value *val;
1085 struct frame_id old_frame;
1087 if (!toval->deprecated_modifiable ())
1088 error (_("Left operand of assignment is not a modifiable lvalue."));
1090 toval = coerce_ref (toval);
1092 type = toval->type ();
1093 if (toval->lval () != lval_internalvar)
1094 fromval = value_cast (type, fromval);
1095 else
1097 /* Coerce arrays and functions to pointers, except for arrays
1098 which only live in GDB's storage. */
1099 if (!value_must_coerce_to_target (fromval))
1100 fromval = coerce_array (fromval);
1103 type = check_typedef (type);
1105 /* Since modifying a register can trash the frame chain, and
1106 modifying memory can trash the frame cache, we save the old frame
1107 and then restore the new frame afterwards. */
1108 old_frame = get_frame_id (deprecated_safe_get_selected_frame ());
1110 switch (toval->lval ())
1112 case lval_internalvar:
1113 set_internalvar (VALUE_INTERNALVAR (toval), fromval);
1114 return value_of_internalvar (type->arch (),
1115 VALUE_INTERNALVAR (toval));
1117 case lval_internalvar_component:
1119 LONGEST offset = toval->offset ();
1121 /* Are we dealing with a bitfield?
1123 It is important to mention that `toval->parent ()' is
1124 non-NULL iff `toval->bitsize ()' is non-zero. */
1125 if (toval->bitsize ())
1127 /* VALUE_INTERNALVAR below refers to the parent value, while
1128 the offset is relative to this parent value. */
1129 gdb_assert (toval->parent ()->parent () == NULL);
1130 offset += toval->parent ()->offset ();
1133 set_internalvar_component (VALUE_INTERNALVAR (toval),
1134 offset,
1135 toval->bitpos (),
1136 toval->bitsize (),
1137 fromval);
1139 break;
1141 case lval_memory:
1143 const gdb_byte *dest_buffer;
1144 CORE_ADDR changed_addr;
1145 int changed_len;
1146 gdb_byte buffer[sizeof (LONGEST)];
1148 if (toval->bitsize ())
1150 struct value *parent = toval->parent ();
1152 changed_addr = parent->address () + toval->offset ();
1153 changed_len = (toval->bitpos ()
1154 + toval->bitsize ()
1155 + HOST_CHAR_BIT - 1)
1156 / HOST_CHAR_BIT;
1158 /* If we can read-modify-write exactly the size of the
1159 containing type (e.g. short or int) then do so. This
1160 is safer for volatile bitfields mapped to hardware
1161 registers. */
1162 if (changed_len < type->length ()
1163 && type->length () <= (int) sizeof (LONGEST)
1164 && ((LONGEST) changed_addr % type->length ()) == 0)
1165 changed_len = type->length ();
1167 if (changed_len > (int) sizeof (LONGEST))
1168 error (_("Can't handle bitfields which "
1169 "don't fit in a %d bit word."),
1170 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1172 read_memory (changed_addr, buffer, changed_len);
1173 modify_field (type, buffer, value_as_long (fromval),
1174 toval->bitpos (), toval->bitsize ());
1175 dest_buffer = buffer;
1177 else
1179 changed_addr = toval->address ();
1180 changed_len = type_length_units (type);
1181 dest_buffer = fromval->contents ().data ();
1184 write_memory_with_notification (changed_addr, dest_buffer, changed_len);
1186 break;
1188 case lval_register:
1190 frame_info_ptr next_frame = frame_find_by_id (toval->next_frame_id ());
1191 int value_reg = toval->regnum ();
1193 if (next_frame == nullptr)
1194 error (_("Value being assigned to is no longer active."));
1196 gdbarch *gdbarch = frame_unwind_arch (next_frame);
1198 if (toval->bitsize ())
1200 struct value *parent = toval->parent ();
1201 LONGEST offset = parent->offset () + toval->offset ();
1202 size_t changed_len;
1203 gdb_byte buffer[sizeof (LONGEST)];
1204 int optim, unavail;
1206 changed_len = (toval->bitpos ()
1207 + toval->bitsize ()
1208 + HOST_CHAR_BIT - 1)
1209 / HOST_CHAR_BIT;
1211 if (changed_len > sizeof (LONGEST))
1212 error (_("Can't handle bitfields which "
1213 "don't fit in a %d bit word."),
1214 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1216 if (!get_frame_register_bytes (next_frame, value_reg, offset,
1217 { buffer, changed_len }, &optim,
1218 &unavail))
1220 if (optim)
1221 throw_error (OPTIMIZED_OUT_ERROR,
1222 _("value has been optimized out"));
1223 if (unavail)
1224 throw_error (NOT_AVAILABLE_ERROR,
1225 _("value is not available"));
1228 modify_field (type, buffer, value_as_long (fromval),
1229 toval->bitpos (), toval->bitsize ());
1231 put_frame_register_bytes (next_frame, value_reg, offset,
1232 { buffer, changed_len });
1234 else
1236 if (gdbarch_convert_register_p (gdbarch, toval->regnum (), type))
1238 /* If TOVAL is a special machine register requiring
1239 conversion of program values to a special raw
1240 format. */
1241 gdbarch_value_to_register (gdbarch,
1242 get_prev_frame_always (next_frame),
1243 toval->regnum (), type,
1244 fromval->contents ().data ());
1246 else
1247 put_frame_register_bytes (next_frame, value_reg,
1248 toval->offset (),
1249 fromval->contents ());
1252 gdb::observers::register_changed.notify
1253 (get_prev_frame_always (next_frame), value_reg);
1254 break;
1257 case lval_computed:
1259 const struct lval_funcs *funcs = toval->computed_funcs ();
1261 if (funcs->write != NULL)
1263 funcs->write (toval, fromval);
1264 break;
1267 [[fallthrough]];
1269 default:
1270 error (_("Left operand of assignment is not an lvalue."));
1273 /* Assigning to the stack pointer, frame pointer, and other
1274 (architecture and calling convention specific) registers may
1275 cause the frame cache and regcache to be out of date. Assigning to memory
1276 also can. We just do this on all assignments to registers or
1277 memory, for simplicity's sake; I doubt the slowdown matters. */
1278 switch (toval->lval ())
1280 case lval_memory:
1281 case lval_register:
1282 case lval_computed:
1284 gdb::observers::target_changed.notify
1285 (current_inferior ()->top_target ());
1287 /* Having destroyed the frame cache, restore the selected
1288 frame. */
1290 /* FIXME: cagney/2002-11-02: There has to be a better way of
1291 doing this. Instead of constantly saving/restoring the
1292 frame. Why not create a get_selected_frame() function that,
1293 having saved the selected frame's ID can automatically
1294 re-find the previously selected frame automatically. */
1297 frame_info_ptr fi = frame_find_by_id (old_frame);
1299 if (fi != NULL)
1300 select_frame (fi);
1303 break;
1304 default:
1305 break;
1308 /* If the field does not entirely fill a LONGEST, then zero the sign
1309 bits. If the field is signed, and is negative, then sign
1310 extend. */
1311 if ((toval->bitsize () > 0)
1312 && (toval->bitsize () < 8 * (int) sizeof (LONGEST)))
1314 LONGEST fieldval = value_as_long (fromval);
1315 LONGEST valmask = (((ULONGEST) 1) << toval->bitsize ()) - 1;
1317 fieldval &= valmask;
1318 if (!type->is_unsigned ()
1319 && (fieldval & (valmask ^ (valmask >> 1))))
1320 fieldval |= ~valmask;
1322 fromval = value_from_longest (type, fieldval);
1325 /* The return value is a copy of TOVAL so it shares its location
1326 information, but its contents are updated from FROMVAL. This
1327 implies the returned value is not lazy, even if TOVAL was. */
1328 val = toval->copy ();
1329 val->set_lazy (false);
1330 copy (fromval->contents (), val->contents_raw ());
1332 /* We copy over the enclosing type and pointed-to offset from FROMVAL
1333 in the case of pointer types. For object types, the enclosing type
1334 and embedded offset must *not* be copied: the target object referred
1335 to by TOVAL retains its original dynamic type after assignment. */
1336 if (type->code () == TYPE_CODE_PTR)
1338 val->set_enclosing_type (fromval->enclosing_type ());
1339 val->set_pointed_to_offset (fromval->pointed_to_offset ());
1342 return val;
1345 /* Extend a value ARG1 to COUNT repetitions of its type. */
1347 struct value *
1348 value_repeat (struct value *arg1, int count)
1350 struct value *val;
1352 arg1 = coerce_ref (arg1);
1354 if (arg1->lval () != lval_memory)
1355 error (_("Only values in memory can be extended with '@'."));
1356 if (count < 1)
1357 error (_("Invalid number %d of repetitions."), count);
1359 val = allocate_repeat_value (arg1->enclosing_type (), count);
1361 val->set_lval (lval_memory);
1362 val->set_address (arg1->address ());
1364 read_value_memory (val, 0, val->stack (), val->address (),
1365 val->contents_all_raw ().data (),
1366 type_length_units (val->enclosing_type ()));
1368 return val;
1371 struct value *
1372 value_of_variable (struct symbol *var, const struct block *b)
1374 frame_info_ptr frame = NULL;
1376 if (symbol_read_needs_frame (var))
1377 frame = get_selected_frame (_("No frame selected."));
1379 return read_var_value (var, b, frame);
1382 struct value *
1383 address_of_variable (struct symbol *var, const struct block *b)
1385 struct type *type = var->type ();
1386 struct value *val;
1388 /* Evaluate it first; if the result is a memory address, we're fine.
1389 Lazy evaluation pays off here. */
1391 val = value_of_variable (var, b);
1392 type = val->type ();
1394 if ((val->lval () == lval_memory && val->lazy ())
1395 || type->code () == TYPE_CODE_FUNC)
1397 CORE_ADDR addr = val->address ();
1399 return value_from_pointer (lookup_pointer_type (type), addr);
1402 /* Not a memory address; check what the problem was. */
1403 switch (val->lval ())
1405 case lval_register:
1407 const char *regname;
1409 frame_info_ptr frame = frame_find_by_id (val->next_frame_id ());
1410 gdb_assert (frame != nullptr);
1412 regname
1413 = gdbarch_register_name (get_frame_arch (frame), val->regnum ());
1414 gdb_assert (regname != nullptr && *regname != '\0');
1416 error (_("Address requested for identifier "
1417 "\"%s\" which is in register $%s"),
1418 var->print_name (), regname);
1419 break;
1422 default:
1423 error (_("Can't take address of \"%s\" which isn't an lvalue."),
1424 var->print_name ());
1425 break;
1428 return val;
1431 /* See value.h. */
1433 bool
1434 value_must_coerce_to_target (struct value *val)
1436 struct type *valtype;
1438 /* The only lval kinds which do not live in target memory. */
1439 if (val->lval () != not_lval
1440 && val->lval () != lval_internalvar
1441 && val->lval () != lval_xcallable)
1442 return false;
1444 valtype = check_typedef (val->type ());
1446 switch (valtype->code ())
1448 case TYPE_CODE_ARRAY:
1449 return valtype->is_vector () ? 0 : 1;
1450 case TYPE_CODE_STRING:
1451 return true;
1452 default:
1453 return false;
1457 /* Make sure that VAL lives in target memory if it's supposed to. For
1458 instance, strings are constructed as character arrays in GDB's
1459 storage, and this function copies them to the target. */
1461 struct value *
1462 value_coerce_to_target (struct value *val)
1464 LONGEST length;
1465 CORE_ADDR addr;
1467 if (!value_must_coerce_to_target (val))
1468 return val;
1470 length = check_typedef (val->type ())->length ();
1471 addr = allocate_space_in_inferior (length);
1472 write_memory (addr, val->contents ().data (), length);
1473 return value_at_lazy (val->type (), addr);
1476 /* Given a value which is an array, return a value which is a pointer
1477 to its first element, regardless of whether or not the array has a
1478 nonzero lower bound.
1480 FIXME: A previous comment here indicated that this routine should
1481 be substracting the array's lower bound. It's not clear to me that
1482 this is correct. Given an array subscripting operation, it would
1483 certainly work to do the adjustment here, essentially computing:
1485 (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
1487 However I believe a more appropriate and logical place to account
1488 for the lower bound is to do so in value_subscript, essentially
1489 computing:
1491 (&array[0] + ((index - lowerbound) * sizeof array[0]))
1493 As further evidence consider what would happen with operations
1494 other than array subscripting, where the caller would get back a
1495 value that had an address somewhere before the actual first element
1496 of the array, and the information about the lower bound would be
1497 lost because of the coercion to pointer type. */
1499 struct value *
1500 value_coerce_array (struct value *arg1)
1502 struct type *type = check_typedef (arg1->type ());
1504 /* If the user tries to do something requiring a pointer with an
1505 array that has not yet been pushed to the target, then this would
1506 be a good time to do so. */
1507 arg1 = value_coerce_to_target (arg1);
1509 if (arg1->lval () != lval_memory)
1510 error (_("Attempt to take address of value not located in memory."));
1512 return value_from_pointer (lookup_pointer_type (type->target_type ()),
1513 arg1->address ());
1516 /* Given a value which is a function, return a value which is a pointer
1517 to it. */
1519 struct value *
1520 value_coerce_function (struct value *arg1)
1522 struct value *retval;
1524 if (arg1->lval () != lval_memory)
1525 error (_("Attempt to take address of value not located in memory."));
1527 retval = value_from_pointer (lookup_pointer_type (arg1->type ()),
1528 arg1->address ());
1529 return retval;
1532 /* Return a pointer value for the object for which ARG1 is the
1533 contents. */
1535 struct value *
1536 value_addr (struct value *arg1)
1538 struct value *arg2;
1539 struct type *type = check_typedef (arg1->type ());
1541 if (TYPE_IS_REFERENCE (type))
1543 if (arg1->bits_synthetic_pointer (arg1->embedded_offset (),
1544 TARGET_CHAR_BIT * type->length ()))
1545 arg1 = coerce_ref (arg1);
1546 else
1548 /* Copy the value, but change the type from (T&) to (T*). We
1549 keep the same location information, which is efficient, and
1550 allows &(&X) to get the location containing the reference.
1551 Do the same to its enclosing type for consistency. */
1552 struct type *type_ptr
1553 = lookup_pointer_type (type->target_type ());
1554 struct type *enclosing_type
1555 = check_typedef (arg1->enclosing_type ());
1556 struct type *enclosing_type_ptr
1557 = lookup_pointer_type (enclosing_type->target_type ());
1559 arg2 = arg1->copy ();
1560 arg2->deprecated_set_type (type_ptr);
1561 arg2->set_enclosing_type (enclosing_type_ptr);
1563 return arg2;
1566 if (type->code () == TYPE_CODE_FUNC)
1567 return value_coerce_function (arg1);
1569 /* If this is an array that has not yet been pushed to the target,
1570 then this would be a good time to force it to memory. */
1571 arg1 = value_coerce_to_target (arg1);
1573 if (arg1->lval () != lval_memory)
1574 error (_("Attempt to take address of value not located in memory."));
1576 /* Get target memory address. */
1577 arg2 = value_from_pointer (lookup_pointer_type (arg1->type ()),
1578 (arg1->address ()
1579 + arg1->embedded_offset ()));
1581 /* This may be a pointer to a base subobject; so remember the
1582 full derived object's type ... */
1583 arg2->set_enclosing_type (lookup_pointer_type (arg1->enclosing_type ()));
1584 /* ... and also the relative position of the subobject in the full
1585 object. */
1586 arg2->set_pointed_to_offset (arg1->embedded_offset ());
1587 return arg2;
1590 /* Return a reference value for the object for which ARG1 is the
1591 contents. */
1593 struct value *
1594 value_ref (struct value *arg1, enum type_code refcode)
1596 struct value *arg2;
1597 struct type *type = check_typedef (arg1->type ());
1599 gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1601 if ((type->code () == TYPE_CODE_REF
1602 || type->code () == TYPE_CODE_RVALUE_REF)
1603 && type->code () == refcode)
1604 return arg1;
1606 arg2 = value_addr (arg1);
1607 arg2->deprecated_set_type (lookup_reference_type (type, refcode));
1608 return arg2;
1611 /* Given a value of a pointer type, apply the C unary * operator to
1612 it. */
1614 struct value *
1615 value_ind (struct value *arg1)
1617 struct type *base_type;
1618 struct value *arg2;
1620 arg1 = coerce_array (arg1);
1622 base_type = check_typedef (arg1->type ());
1624 if (arg1->lval () == lval_computed)
1626 const struct lval_funcs *funcs = arg1->computed_funcs ();
1628 if (funcs->indirect)
1630 struct value *result = funcs->indirect (arg1);
1632 if (result)
1633 return result;
1637 if (base_type->code () == TYPE_CODE_PTR)
1639 struct type *enc_type;
1641 /* We may be pointing to something embedded in a larger object.
1642 Get the real type of the enclosing object. */
1643 enc_type = check_typedef (arg1->enclosing_type ());
1644 enc_type = enc_type->target_type ();
1646 CORE_ADDR base_addr;
1647 if (check_typedef (enc_type)->code () == TYPE_CODE_FUNC
1648 || check_typedef (enc_type)->code () == TYPE_CODE_METHOD)
1650 /* For functions, go through find_function_addr, which knows
1651 how to handle function descriptors. */
1652 base_addr = find_function_addr (arg1, NULL);
1654 else
1656 /* Retrieve the enclosing object pointed to. */
1657 base_addr = (value_as_address (arg1)
1658 - arg1->pointed_to_offset ());
1660 arg2 = value_at_lazy (enc_type, base_addr);
1661 enc_type = arg2->type ();
1662 return readjust_indirect_value_type (arg2, enc_type, base_type,
1663 arg1, base_addr);
1666 error (_("Attempt to take contents of a non-pointer value."));
1669 /* Create a value for an array by allocating space in GDB, copying the
1670 data into that space, and then setting up an array value.
1672 The array bounds are set from LOWBOUND and the size of ELEMVEC, and
1673 the array is populated from the values passed in ELEMVEC.
1675 The element type of the array is inherited from the type of the
1676 first element, and all elements must have the same size (though we
1677 don't currently enforce any restriction on their types). */
1679 struct value *
1680 value_array (int lowbound, gdb::array_view<struct value *> elemvec)
1682 int idx;
1683 ULONGEST typelength;
1684 struct value *val;
1685 struct type *arraytype;
1687 /* Validate that the bounds are reasonable and that each of the
1688 elements have the same size. */
1690 typelength = type_length_units (elemvec[0]->enclosing_type ());
1691 for (struct value *other : elemvec.slice (1))
1693 if (type_length_units (other->enclosing_type ()) != typelength)
1695 error (_("array elements must all be the same size"));
1699 arraytype = lookup_array_range_type (elemvec[0]->enclosing_type (),
1700 lowbound,
1701 lowbound + elemvec.size () - 1);
1703 if (!current_language->c_style_arrays_p ())
1705 val = value::allocate (arraytype);
1706 for (idx = 0; idx < elemvec.size (); idx++)
1707 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1708 return val;
1711 /* Allocate space to store the array, and then initialize it by
1712 copying in each element. */
1714 val = value::allocate (arraytype);
1715 for (idx = 0; idx < elemvec.size (); idx++)
1716 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1717 return val;
1720 /* See value.h. */
1722 struct value *
1723 value_cstring (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1725 struct value *val;
1726 int lowbound = current_language->string_lower_bound ();
1727 ssize_t highbound = count + 1;
1728 struct type *stringtype
1729 = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1731 val = value::allocate (stringtype);
1732 ssize_t len = count * char_type->length ();
1733 memcpy (val->contents_raw ().data (), ptr, len);
1734 /* Write the terminating null-character. */
1735 memset (val->contents_raw ().data () + len, 0, char_type->length ());
1736 return val;
1739 /* See value.h. */
1741 struct value *
1742 value_string (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1744 struct value *val;
1745 int lowbound = current_language->string_lower_bound ();
1746 ssize_t highbound = count;
1747 struct type *stringtype
1748 = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1750 val = value::allocate (stringtype);
1751 ssize_t len = count * char_type->length ();
1752 memcpy (val->contents_raw ().data (), ptr, len);
1753 return val;
1757 /* See if we can pass arguments in T2 to a function which takes arguments
1758 of types T1. T1 is a list of NARGS arguments, and T2 is an array_view
1759 of the values we're trying to pass. If some arguments need coercion of
1760 some sort, then the coerced values are written into T2. Return value is
1761 0 if the arguments could be matched, or the position at which they
1762 differ if not.
1764 STATICP is nonzero if the T1 argument list came from a static
1765 member function. T2 must still include the ``this'' pointer, but
1766 it will be skipped.
1768 For non-static member functions, we ignore the first argument,
1769 which is the type of the instance variable. This is because we
1770 want to handle calls with objects from derived classes. This is
1771 not entirely correct: we should actually check to make sure that a
1772 requested operation is type secure, shouldn't we? FIXME. */
1774 static int
1775 typecmp (bool staticp, bool varargs, int nargs,
1776 struct field t1[], gdb::array_view<value *> t2)
1778 int i;
1780 /* Skip ``this'' argument if applicable. T2 will always include
1781 THIS. */
1782 if (staticp)
1783 t2 = t2.slice (1);
1785 for (i = 0;
1786 (i < nargs) && t1[i].type ()->code () != TYPE_CODE_VOID;
1787 i++)
1789 struct type *tt1, *tt2;
1791 if (i == t2.size ())
1792 return i + 1;
1794 tt1 = check_typedef (t1[i].type ());
1795 tt2 = check_typedef (t2[i]->type ());
1797 if (TYPE_IS_REFERENCE (tt1)
1798 /* We should be doing hairy argument matching, as below. */
1799 && (check_typedef (tt1->target_type ())->code ()
1800 == tt2->code ()))
1802 if (tt2->code () == TYPE_CODE_ARRAY)
1803 t2[i] = value_coerce_array (t2[i]);
1804 else
1805 t2[i] = value_ref (t2[i], tt1->code ());
1806 continue;
1809 /* djb - 20000715 - Until the new type structure is in the
1810 place, and we can attempt things like implicit conversions,
1811 we need to do this so you can take something like a map<const
1812 char *>, and properly access map["hello"], because the
1813 argument to [] will be a reference to a pointer to a char,
1814 and the argument will be a pointer to a char. */
1815 while (TYPE_IS_REFERENCE (tt1) || tt1->code () == TYPE_CODE_PTR)
1817 tt1 = check_typedef ( tt1->target_type () );
1819 while (tt2->code () == TYPE_CODE_ARRAY
1820 || tt2->code () == TYPE_CODE_PTR
1821 || TYPE_IS_REFERENCE (tt2))
1823 tt2 = check_typedef (tt2->target_type ());
1825 if (tt1->code () == tt2->code ())
1826 continue;
1827 /* Array to pointer is a `trivial conversion' according to the
1828 ARM. */
1830 /* We should be doing much hairier argument matching (see
1831 section 13.2 of the ARM), but as a quick kludge, just check
1832 for the same type code. */
1833 if (t1[i].type ()->code () != t2[i]->type ()->code ())
1834 return i + 1;
1836 if (varargs || i == t2.size ())
1837 return 0;
1838 return i + 1;
1841 /* Helper class for search_struct_field that keeps track of found
1842 results and possibly throws an exception if the search yields
1843 ambiguous results. See search_struct_field for description of
1844 LOOKING_FOR_BASECLASS. */
1846 struct struct_field_searcher
1848 /* A found field. */
1849 struct found_field
1851 /* Path to the structure where the field was found. */
1852 std::vector<struct type *> path;
1854 /* The field found. */
1855 struct value *field_value;
1858 /* See corresponding fields for description of parameters. */
1859 struct_field_searcher (const char *name,
1860 struct type *outermost_type,
1861 bool looking_for_baseclass)
1862 : m_name (name),
1863 m_looking_for_baseclass (looking_for_baseclass),
1864 m_outermost_type (outermost_type)
1868 /* The search entry point. If LOOKING_FOR_BASECLASS is true and the
1869 base class search yields ambiguous results, this throws an
1870 exception. If LOOKING_FOR_BASECLASS is false, the found fields
1871 are accumulated and the caller (search_struct_field) takes care
1872 of throwing an error if the field search yields ambiguous
1873 results. The latter is done that way so that the error message
1874 can include a list of all the found candidates. */
1875 void search (struct value *arg, LONGEST offset, struct type *type);
1877 const std::vector<found_field> &fields ()
1879 return m_fields;
1882 struct value *baseclass ()
1884 return m_baseclass;
1887 private:
1888 /* Update results to include V, a found field/baseclass. */
1889 void update_result (struct value *v, LONGEST boffset);
1891 /* The name of the field/baseclass we're searching for. */
1892 const char *m_name;
1894 /* Whether we're looking for a baseclass, or a field. */
1895 const bool m_looking_for_baseclass;
1897 /* The offset of the baseclass containing the field/baseclass we
1898 last recorded. */
1899 LONGEST m_last_boffset = 0;
1901 /* If looking for a baseclass, then the result is stored here. */
1902 struct value *m_baseclass = nullptr;
1904 /* When looking for fields, the found candidates are stored
1905 here. */
1906 std::vector<found_field> m_fields;
1908 /* The type of the initial type passed to search_struct_field; this
1909 is used for error reporting when the lookup is ambiguous. */
1910 struct type *m_outermost_type;
1912 /* The full path to the struct being inspected. E.g. for field 'x'
1913 defined in class B inherited by class A, we have A and B pushed
1914 on the path. */
1915 std::vector <struct type *> m_struct_path;
1918 void
1919 struct_field_searcher::update_result (struct value *v, LONGEST boffset)
1921 if (v != NULL)
1923 if (m_looking_for_baseclass)
1925 if (m_baseclass != nullptr
1926 /* The result is not ambiguous if all the classes that are
1927 found occupy the same space. */
1928 && m_last_boffset != boffset)
1929 error (_("base class '%s' is ambiguous in type '%s'"),
1930 m_name, TYPE_SAFE_NAME (m_outermost_type));
1932 m_baseclass = v;
1933 m_last_boffset = boffset;
1935 else
1937 /* The field is not ambiguous if it occupies the same
1938 space. */
1939 if (m_fields.empty () || m_last_boffset != boffset)
1940 m_fields.push_back ({m_struct_path, v});
1941 else
1943 /*Fields can occupy the same space and have the same name (be
1944 ambiguous). This can happen when fields in two different base
1945 classes are marked [[no_unique_address]] and have the same name.
1946 The C++ standard says that such fields can only occupy the same
1947 space if they are of different type, but we don't rely on that in
1948 the following code. */
1949 bool ambiguous = false, insert = true;
1950 for (const found_field &field: m_fields)
1952 if(field.path.back () != m_struct_path.back ())
1954 /* Same boffset points to members of different classes.
1955 We have found an ambiguity and should record it. */
1956 ambiguous = true;
1958 else
1960 /* We don't need to insert this value again, because a
1961 non-ambiguous path already leads to it. */
1962 insert = false;
1963 break;
1966 if (ambiguous && insert)
1967 m_fields.push_back ({m_struct_path, v});
1973 /* A helper for search_struct_field. This does all the work; most
1974 arguments are as passed to search_struct_field. */
1976 void
1977 struct_field_searcher::search (struct value *arg1, LONGEST offset,
1978 struct type *type)
1980 int i;
1981 int nbases;
1983 m_struct_path.push_back (type);
1984 SCOPE_EXIT { m_struct_path.pop_back (); };
1986 type = check_typedef (type);
1987 nbases = TYPE_N_BASECLASSES (type);
1989 if (!m_looking_for_baseclass)
1990 for (i = type->num_fields () - 1; i >= nbases; i--)
1992 const char *t_field_name = type->field (i).name ();
1994 if (t_field_name && (strcmp_iw (t_field_name, m_name) == 0))
1996 struct value *v;
1998 if (type->field (i).is_static ())
1999 v = value_static_field (type, i);
2000 else
2001 v = arg1->primitive_field (offset, i, type);
2003 update_result (v, offset);
2004 return;
2007 if (t_field_name
2008 && t_field_name[0] == '\0')
2010 struct type *field_type = type->field (i).type ();
2012 if (field_type->code () == TYPE_CODE_UNION
2013 || field_type->code () == TYPE_CODE_STRUCT)
2015 /* Look for a match through the fields of an anonymous
2016 union, or anonymous struct. C++ provides anonymous
2017 unions.
2019 In the GNU Chill (now deleted from GDB)
2020 implementation of variant record types, each
2021 <alternative field> has an (anonymous) union type,
2022 each member of the union represents a <variant
2023 alternative>. Each <variant alternative> is
2024 represented as a struct, with a member for each
2025 <variant field>. */
2027 LONGEST new_offset = offset;
2029 /* This is pretty gross. In G++, the offset in an
2030 anonymous union is relative to the beginning of the
2031 enclosing struct. In the GNU Chill (now deleted
2032 from GDB) implementation of variant records, the
2033 bitpos is zero in an anonymous union field, so we
2034 have to add the offset of the union here. */
2035 if (field_type->code () == TYPE_CODE_STRUCT
2036 || (field_type->num_fields () > 0
2037 && field_type->field (0).loc_bitpos () == 0))
2038 new_offset += type->field (i).loc_bitpos () / 8;
2040 search (arg1, new_offset, field_type);
2045 for (i = 0; i < nbases; i++)
2047 struct value *v = NULL;
2048 struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
2049 /* If we are looking for baseclasses, this is what we get when
2050 we hit them. But it could happen that the base part's member
2051 name is not yet filled in. */
2052 int found_baseclass = (m_looking_for_baseclass
2053 && TYPE_BASECLASS_NAME (type, i) != NULL
2054 && (strcmp_iw (m_name, basetype->name ()) == 0));
2055 LONGEST boffset = arg1->embedded_offset () + offset;
2057 if (BASETYPE_VIA_VIRTUAL (type, i))
2059 struct value *v2;
2061 boffset = baseclass_offset (type, i,
2062 arg1->contents_for_printing ().data (),
2063 arg1->embedded_offset () + offset,
2064 arg1->address (),
2065 arg1);
2067 /* The virtual base class pointer might have been clobbered
2068 by the user program. Make sure that it still points to a
2069 valid memory location. */
2071 boffset += arg1->embedded_offset () + offset;
2072 if (boffset < 0
2073 || boffset >= arg1->enclosing_type ()->length ())
2075 CORE_ADDR base_addr;
2077 base_addr = arg1->address () + boffset;
2078 v2 = value_at_lazy (basetype, base_addr);
2079 if (target_read_memory (base_addr,
2080 v2->contents_raw ().data (),
2081 v2->type ()->length ()) != 0)
2082 error (_("virtual baseclass botch"));
2084 else
2086 v2 = arg1->copy ();
2087 v2->deprecated_set_type (basetype);
2088 v2->set_embedded_offset (boffset);
2091 if (found_baseclass)
2092 v = v2;
2093 else
2094 search (v2, 0, TYPE_BASECLASS (type, i));
2096 else if (found_baseclass)
2097 v = arg1->primitive_field (offset, i, type);
2098 else
2100 search (arg1, offset + TYPE_BASECLASS_BITPOS (type, i) / 8,
2101 basetype);
2104 update_result (v, boffset);
2108 /* Helper function used by value_struct_elt to recurse through
2109 baseclasses. Look for a field NAME in ARG1. Search in it assuming
2110 it has (class) type TYPE. If found, return value, else return NULL.
2112 If LOOKING_FOR_BASECLASS, then instead of looking for struct
2113 fields, look for a baseclass named NAME. */
2115 static struct value *
2116 search_struct_field (const char *name, struct value *arg1,
2117 struct type *type, int looking_for_baseclass)
2119 struct_field_searcher searcher (name, type, looking_for_baseclass);
2121 searcher.search (arg1, 0, type);
2123 if (!looking_for_baseclass)
2125 const auto &fields = searcher.fields ();
2127 if (fields.empty ())
2128 return nullptr;
2129 else if (fields.size () == 1)
2130 return fields[0].field_value;
2131 else
2133 std::string candidates;
2135 for (auto &&candidate : fields)
2137 gdb_assert (!candidate.path.empty ());
2139 struct type *field_type = candidate.field_value->type ();
2140 struct type *struct_type = candidate.path.back ();
2142 std::string path;
2143 bool first = true;
2144 for (struct type *t : candidate.path)
2146 if (first)
2147 first = false;
2148 else
2149 path += " -> ";
2150 path += t->name ();
2153 candidates += string_printf ("\n '%s %s::%s' (%s)",
2154 TYPE_SAFE_NAME (field_type),
2155 TYPE_SAFE_NAME (struct_type),
2156 name,
2157 path.c_str ());
2160 error (_("Request for member '%s' is ambiguous in type '%s'."
2161 " Candidates are:%s"),
2162 name, TYPE_SAFE_NAME (type),
2163 candidates.c_str ());
2166 else
2167 return searcher.baseclass ();
2170 /* Helper function used by value_struct_elt to recurse through
2171 baseclasses. Look for a field NAME in ARG1. Adjust the address of
2172 ARG1 by OFFSET bytes, and search in it assuming it has (class) type
2173 TYPE.
2175 ARGS is an optional array of argument values used to help finding NAME.
2176 The contents of ARGS can be adjusted if type coercion is required in
2177 order to find a matching NAME.
2179 If found, return value, else if name matched and args not return
2180 (value) -1, else return NULL. */
2182 static struct value *
2183 search_struct_method (const char *name, struct value **arg1p,
2184 std::optional<gdb::array_view<value *>> args,
2185 LONGEST offset, int *static_memfuncp,
2186 struct type *type)
2188 int i;
2189 struct value *v;
2190 int name_matched = 0;
2192 type = check_typedef (type);
2193 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2195 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2197 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2199 int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2200 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2202 name_matched = 1;
2203 check_stub_method_group (type, i);
2204 if (j > 0 && !args.has_value ())
2205 error (_("cannot resolve overloaded method "
2206 "`%s': no arguments supplied"), name);
2207 else if (j == 0 && !args.has_value ())
2209 v = value_fn_field (arg1p, f, j, type, offset);
2210 if (v != NULL)
2211 return v;
2213 else
2214 while (j >= 0)
2216 gdb_assert (args.has_value ());
2217 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2218 TYPE_FN_FIELD_TYPE (f, j)->has_varargs (),
2219 TYPE_FN_FIELD_TYPE (f, j)->num_fields (),
2220 TYPE_FN_FIELD_ARGS (f, j), *args))
2222 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2223 return value_virtual_fn_field (arg1p, f, j,
2224 type, offset);
2225 if (TYPE_FN_FIELD_STATIC_P (f, j)
2226 && static_memfuncp)
2227 *static_memfuncp = 1;
2228 v = value_fn_field (arg1p, f, j, type, offset);
2229 if (v != NULL)
2230 return v;
2232 j--;
2237 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2239 LONGEST base_offset;
2240 LONGEST this_offset;
2242 if (BASETYPE_VIA_VIRTUAL (type, i))
2244 struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2245 struct value *base_val;
2246 const gdb_byte *base_valaddr;
2248 /* The virtual base class pointer might have been
2249 clobbered by the user program. Make sure that it
2250 still points to a valid memory location. */
2252 if (offset < 0 || offset >= type->length ())
2254 CORE_ADDR address;
2256 gdb::byte_vector tmp (baseclass->length ());
2257 address = (*arg1p)->address ();
2259 if (target_read_memory (address + offset,
2260 tmp.data (), baseclass->length ()) != 0)
2261 error (_("virtual baseclass botch"));
2263 base_val = value_from_contents_and_address (baseclass,
2264 tmp.data (),
2265 address + offset);
2266 base_valaddr = base_val->contents_for_printing ().data ();
2267 this_offset = 0;
2269 else
2271 base_val = *arg1p;
2272 base_valaddr = (*arg1p)->contents_for_printing ().data ();
2273 this_offset = offset;
2276 base_offset = baseclass_offset (type, i, base_valaddr,
2277 this_offset, base_val->address (),
2278 base_val);
2280 else
2282 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2284 v = search_struct_method (name, arg1p, args, base_offset + offset,
2285 static_memfuncp, TYPE_BASECLASS (type, i));
2286 if (v == (struct value *) - 1)
2288 name_matched = 1;
2290 else if (v)
2292 /* FIXME-bothner: Why is this commented out? Why is it here? */
2293 /* *arg1p = arg1_tmp; */
2294 return v;
2297 if (name_matched)
2298 return (struct value *) - 1;
2299 else
2300 return NULL;
2303 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2304 extract the component named NAME from the ultimate target
2305 structure/union and return it as a value with its appropriate type.
2306 ERR is used in the error message if *ARGP's type is wrong.
2308 C++: ARGS is a list of argument types to aid in the selection of
2309 an appropriate method. Also, handle derived types.
2311 STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2312 where the truthvalue of whether the function that was resolved was
2313 a static member function or not is stored.
2315 ERR is an error message to be printed in case the field is not
2316 found. */
2318 struct value *
2319 value_struct_elt (struct value **argp,
2320 std::optional<gdb::array_view<value *>> args,
2321 const char *name, int *static_memfuncp, const char *err)
2323 struct type *t;
2324 struct value *v;
2326 *argp = coerce_array (*argp);
2328 t = check_typedef ((*argp)->type ());
2330 /* Follow pointers until we get to a non-pointer. */
2332 while (t->is_pointer_or_reference ())
2334 *argp = value_ind (*argp);
2335 /* Don't coerce fn pointer to fn and then back again! */
2336 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2337 *argp = coerce_array (*argp);
2338 t = check_typedef ((*argp)->type ());
2341 if (t->code () != TYPE_CODE_STRUCT
2342 && t->code () != TYPE_CODE_UNION)
2343 error (_("Attempt to extract a component of a value that is not a %s."),
2344 err);
2346 /* Assume it's not, unless we see that it is. */
2347 if (static_memfuncp)
2348 *static_memfuncp = 0;
2350 if (!args.has_value ())
2352 /* if there are no arguments ...do this... */
2354 /* Try as a field first, because if we succeed, there is less
2355 work to be done. */
2356 v = search_struct_field (name, *argp, t, 0);
2357 if (v)
2358 return v;
2360 if (current_language->la_language == language_fortran)
2362 /* If it is not a field it is the type name of an inherited
2363 structure. */
2364 v = search_struct_field (name, *argp, t, 1);
2365 if (v)
2366 return v;
2369 /* C++: If it was not found as a data field, then try to
2370 return it as a pointer to a method. */
2371 v = search_struct_method (name, argp, args, 0,
2372 static_memfuncp, t);
2374 if (v == (struct value *) - 1)
2375 error (_("Cannot take address of method %s."), name);
2376 else if (v == 0)
2378 if (TYPE_NFN_FIELDS (t))
2379 error (_("There is no member or method named %s."), name);
2380 else
2381 error (_("There is no member named %s."), name);
2383 return v;
2386 v = search_struct_method (name, argp, args, 0,
2387 static_memfuncp, t);
2389 if (v == (struct value *) - 1)
2391 error (_("One of the arguments you tried to pass to %s could not "
2392 "be converted to what the function wants."), name);
2394 else if (v == 0)
2396 /* See if user tried to invoke data as function. If so, hand it
2397 back. If it's not callable (i.e., a pointer to function),
2398 gdb should give an error. */
2399 v = search_struct_field (name, *argp, t, 0);
2400 /* If we found an ordinary field, then it is not a method call.
2401 So, treat it as if it were a static member function. */
2402 if (v && static_memfuncp)
2403 *static_memfuncp = 1;
2406 if (!v)
2407 throw_error (NOT_FOUND_ERROR,
2408 _("Structure has no component named %s."), name);
2409 return v;
2412 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2413 to a structure or union, extract and return its component (field) of
2414 type FTYPE at the specified BITPOS.
2415 Throw an exception on error. */
2417 struct value *
2418 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2419 const char *err)
2421 struct type *t;
2422 int i;
2424 *argp = coerce_array (*argp);
2426 t = check_typedef ((*argp)->type ());
2428 while (t->is_pointer_or_reference ())
2430 *argp = value_ind (*argp);
2431 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2432 *argp = coerce_array (*argp);
2433 t = check_typedef ((*argp)->type ());
2436 if (t->code () != TYPE_CODE_STRUCT
2437 && t->code () != TYPE_CODE_UNION)
2438 error (_("Attempt to extract a component of a value that is not a %s."),
2439 err);
2441 for (i = TYPE_N_BASECLASSES (t); i < t->num_fields (); i++)
2443 if (!t->field (i).is_static ()
2444 && bitpos == t->field (i).loc_bitpos ()
2445 && types_equal (ftype, t->field (i).type ()))
2446 return (*argp)->primitive_field (0, i, t);
2449 error (_("No field with matching bitpos and type."));
2451 /* Never hit. */
2452 return NULL;
2455 /* Search through the methods of an object (and its bases) to find a
2456 specified method. Return a reference to the fn_field list METHODS of
2457 overloaded instances defined in the source language. If available
2458 and matching, a vector of matching xmethods defined in extension
2459 languages are also returned in XMETHODS.
2461 Helper function for value_find_oload_list.
2462 ARGP is a pointer to a pointer to a value (the object).
2463 METHOD is a string containing the method name.
2464 OFFSET is the offset within the value.
2465 TYPE is the assumed type of the object.
2466 METHODS is a pointer to the matching overloaded instances defined
2467 in the source language. Since this is a recursive function,
2468 *METHODS should be set to NULL when calling this function.
2469 NUM_FNS is the number of overloaded instances. *NUM_FNS should be set to
2470 0 when calling this function.
2471 XMETHODS is the vector of matching xmethod workers. *XMETHODS
2472 should also be set to NULL when calling this function.
2473 BASETYPE is set to the actual type of the subobject where the
2474 method is found.
2475 BOFFSET is the offset of the base subobject where the method is found. */
2477 static void
2478 find_method_list (struct value **argp, const char *method,
2479 LONGEST offset, struct type *type,
2480 gdb::array_view<fn_field> *methods,
2481 std::vector<xmethod_worker_up> *xmethods,
2482 struct type **basetype, LONGEST *boffset)
2484 int i;
2485 struct fn_field *f = NULL;
2487 gdb_assert (methods != NULL && xmethods != NULL);
2488 type = check_typedef (type);
2490 /* First check in object itself.
2491 This function is called recursively to search through base classes.
2492 If there is a source method match found at some stage, then we need not
2493 look for source methods in consequent recursive calls. */
2494 if (methods->empty ())
2496 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2498 /* pai: FIXME What about operators and type conversions? */
2499 const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2501 if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2503 int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2504 f = TYPE_FN_FIELDLIST1 (type, i);
2505 *methods = gdb::make_array_view (f, len);
2507 *basetype = type;
2508 *boffset = offset;
2510 /* Resolve any stub methods. */
2511 check_stub_method_group (type, i);
2513 break;
2518 /* Unlike source methods, xmethods can be accumulated over successive
2519 recursive calls. In other words, an xmethod named 'm' in a class
2520 will not hide an xmethod named 'm' in its base class(es). We want
2521 it to be this way because xmethods are after all convenience functions
2522 and hence there is no point restricting them with something like method
2523 hiding. Moreover, if hiding is done for xmethods as well, then we will
2524 have to provide a mechanism to un-hide (like the 'using' construct). */
2525 get_matching_xmethod_workers (type, method, xmethods);
2527 /* If source methods are not found in current class, look for them in the
2528 base classes. We also have to go through the base classes to gather
2529 extension methods. */
2530 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2532 LONGEST base_offset;
2534 if (BASETYPE_VIA_VIRTUAL (type, i))
2536 base_offset = baseclass_offset (type, i,
2537 (*argp)->contents_for_printing ().data (),
2538 (*argp)->offset () + offset,
2539 (*argp)->address (), *argp);
2541 else /* Non-virtual base, simply use bit position from debug
2542 info. */
2544 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2547 find_method_list (argp, method, base_offset + offset,
2548 TYPE_BASECLASS (type, i), methods,
2549 xmethods, basetype, boffset);
2553 /* Return the list of overloaded methods of a specified name. The methods
2554 could be those GDB finds in the binary, or xmethod. Methods found in
2555 the binary are returned in METHODS, and xmethods are returned in
2556 XMETHODS.
2558 ARGP is a pointer to a pointer to a value (the object).
2559 METHOD is the method name.
2560 OFFSET is the offset within the value contents.
2561 METHODS is the list of matching overloaded instances defined in
2562 the source language.
2563 XMETHODS is the vector of matching xmethod workers defined in
2564 extension languages.
2565 BASETYPE is set to the type of the base subobject that defines the
2566 method.
2567 BOFFSET is the offset of the base subobject which defines the method. */
2569 static void
2570 value_find_oload_method_list (struct value **argp, const char *method,
2571 LONGEST offset,
2572 gdb::array_view<fn_field> *methods,
2573 std::vector<xmethod_worker_up> *xmethods,
2574 struct type **basetype, LONGEST *boffset)
2576 struct type *t;
2578 t = check_typedef ((*argp)->type ());
2580 /* Code snarfed from value_struct_elt. */
2581 while (t->is_pointer_or_reference ())
2583 *argp = value_ind (*argp);
2584 /* Don't coerce fn pointer to fn and then back again! */
2585 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2586 *argp = coerce_array (*argp);
2587 t = check_typedef ((*argp)->type ());
2590 if (t->code () != TYPE_CODE_STRUCT
2591 && t->code () != TYPE_CODE_UNION)
2592 error (_("Attempt to extract a component of a "
2593 "value that is not a struct or union"));
2595 gdb_assert (methods != NULL && xmethods != NULL);
2597 /* Clear the lists. */
2598 *methods = {};
2599 xmethods->clear ();
2601 find_method_list (argp, method, 0, t, methods, xmethods,
2602 basetype, boffset);
2605 /* Helper function for find_overload_match. If no matches were
2606 found, this function may generate a hint for the user that some
2607 of the relevant types are incomplete, so GDB can't evaluate
2608 type relationships to properly evaluate overloads.
2610 If no incomplete types are present, an empty string is returned. */
2611 static std::string
2612 incomplete_type_hint (gdb::array_view<value *> args)
2614 int incomplete_types = 0;
2615 std::string incomplete_arg_names;
2616 for (const struct value *arg : args)
2618 struct type *t = arg->type ();
2619 while (t->code () == TYPE_CODE_PTR)
2620 t = t->target_type ();
2621 if (t->is_stub ())
2623 string_file buffer;
2624 if (incomplete_types > 0)
2625 incomplete_arg_names += ", ";
2627 current_language->print_type (arg->type (), "", &buffer,
2628 -1, 0, &type_print_raw_options);
2630 incomplete_types++;
2631 incomplete_arg_names += buffer.string ();
2634 std::string hint;
2635 if (incomplete_types > 1)
2636 hint = string_printf (_("\nThe types: '%s' aren't fully known to GDB."
2637 " Please cast them directly to the desired"
2638 " typed in the function call."),
2639 incomplete_arg_names.c_str ());
2640 else if (incomplete_types == 1)
2641 hint = string_printf (_("\nThe type: '%s' isn't fully known to GDB."
2642 " Please cast it directly to the desired"
2643 " typed in the function call."),
2644 incomplete_arg_names.c_str ());
2645 return hint;
2648 /* Given an array of arguments (ARGS) (which includes an entry for
2649 "this" in the case of C++ methods), the NAME of a function, and
2650 whether it's a method or not (METHOD), find the best function that
2651 matches on the argument types according to the overload resolution
2652 rules.
2654 METHOD can be one of three values:
2655 NON_METHOD for non-member functions.
2656 METHOD: for member functions.
2657 BOTH: used for overload resolution of operators where the
2658 candidates are expected to be either member or non member
2659 functions. In this case the first argument ARGTYPES
2660 (representing 'this') is expected to be a reference to the
2661 target object, and will be dereferenced when attempting the
2662 non-member search.
2664 In the case of class methods, the parameter OBJ is an object value
2665 in which to search for overloaded methods.
2667 In the case of non-method functions, the parameter FSYM is a symbol
2668 corresponding to one of the overloaded functions.
2670 Return value is an integer: 0 -> good match, 10 -> debugger applied
2671 non-standard coercions, 100 -> incompatible.
2673 If a method is being searched for, VALP will hold the value.
2674 If a non-method is being searched for, SYMP will hold the symbol
2675 for it.
2677 If a method is being searched for, and it is a static method,
2678 then STATICP will point to a non-zero value.
2680 If NO_ADL argument dependent lookup is disabled. This is used to prevent
2681 ADL overload candidates when performing overload resolution for a fully
2682 qualified name.
2684 If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2685 read while picking the best overload match (it may be all zeroes and thus
2686 not have a vtable pointer), in which case skip virtual function lookup.
2687 This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2688 the result type.
2690 Note: This function does *not* check the value of
2691 overload_resolution. Caller must check it to see whether overload
2692 resolution is permitted. */
2695 find_overload_match (gdb::array_view<value *> args,
2696 const char *name, enum oload_search_type method,
2697 struct value **objp, struct symbol *fsym,
2698 struct value **valp, struct symbol **symp,
2699 int *staticp, const int no_adl,
2700 const enum noside noside)
2702 struct value *obj = (objp ? *objp : NULL);
2703 struct type *obj_type = obj ? obj->type () : NULL;
2704 /* Index of best overloaded function. */
2705 int func_oload_champ = -1;
2706 int method_oload_champ = -1;
2707 int src_method_oload_champ = -1;
2708 int ext_method_oload_champ = -1;
2710 /* The measure for the current best match. */
2711 badness_vector method_badness;
2712 badness_vector func_badness;
2713 badness_vector ext_method_badness;
2714 badness_vector src_method_badness;
2716 struct value *temp = obj;
2717 /* For methods, the list of overloaded methods. */
2718 gdb::array_view<fn_field> methods;
2719 /* For non-methods, the list of overloaded function symbols. */
2720 std::vector<symbol *> functions;
2721 /* For xmethods, the vector of xmethod workers. */
2722 std::vector<xmethod_worker_up> xmethods;
2723 struct type *basetype = NULL;
2724 LONGEST boffset;
2726 const char *obj_type_name = NULL;
2727 const char *func_name = NULL;
2728 gdb::unique_xmalloc_ptr<char> temp_func;
2729 enum oload_classification match_quality;
2730 enum oload_classification method_match_quality = INCOMPATIBLE;
2731 enum oload_classification src_method_match_quality = INCOMPATIBLE;
2732 enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2733 enum oload_classification func_match_quality = INCOMPATIBLE;
2735 /* Get the list of overloaded methods or functions. */
2736 if (method == METHOD || method == BOTH)
2738 gdb_assert (obj);
2740 /* OBJ may be a pointer value rather than the object itself. */
2741 obj = coerce_ref (obj);
2742 while (check_typedef (obj->type ())->code () == TYPE_CODE_PTR)
2743 obj = coerce_ref (value_ind (obj));
2744 obj_type_name = obj->type ()->name ();
2746 /* First check whether this is a data member, e.g. a pointer to
2747 a function. */
2748 if (check_typedef (obj->type ())->code () == TYPE_CODE_STRUCT)
2750 *valp = search_struct_field (name, obj,
2751 check_typedef (obj->type ()), 0);
2752 if (*valp)
2754 *staticp = 1;
2755 return 0;
2759 /* Retrieve the list of methods with the name NAME. */
2760 value_find_oload_method_list (&temp, name, 0, &methods,
2761 &xmethods, &basetype, &boffset);
2762 /* If this is a method only search, and no methods were found
2763 the search has failed. */
2764 if (method == METHOD && methods.empty () && xmethods.empty ())
2765 error (_("Couldn't find method %s%s%s"),
2766 obj_type_name,
2767 (obj_type_name && *obj_type_name) ? "::" : "",
2768 name);
2769 /* If we are dealing with stub method types, they should have
2770 been resolved by find_method_list via
2771 value_find_oload_method_list above. */
2772 if (!methods.empty ())
2774 gdb_assert (TYPE_SELF_TYPE (methods[0].type) != NULL);
2776 src_method_oload_champ
2777 = find_oload_champ (args,
2778 methods.size (),
2779 methods.data (), NULL, NULL,
2780 &src_method_badness);
2782 src_method_match_quality = classify_oload_match
2783 (src_method_badness, args.size (),
2784 oload_method_static_p (methods.data (), src_method_oload_champ));
2787 if (!xmethods.empty ())
2789 ext_method_oload_champ
2790 = find_oload_champ (args,
2791 xmethods.size (),
2792 NULL, xmethods.data (), NULL,
2793 &ext_method_badness);
2794 ext_method_match_quality = classify_oload_match (ext_method_badness,
2795 args.size (), 0);
2798 if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2800 switch (compare_badness (ext_method_badness, src_method_badness))
2802 case 0: /* Src method and xmethod are equally good. */
2803 /* If src method and xmethod are equally good, then
2804 xmethod should be the winner. Hence, fall through to the
2805 case where a xmethod is better than the source
2806 method, except when the xmethod match quality is
2807 non-standard. */
2808 [[fallthrough]];
2809 case 1: /* Src method and ext method are incompatible. */
2810 /* If ext method match is not standard, then let source method
2811 win. Otherwise, fallthrough to let xmethod win. */
2812 if (ext_method_match_quality != STANDARD)
2814 method_oload_champ = src_method_oload_champ;
2815 method_badness = src_method_badness;
2816 ext_method_oload_champ = -1;
2817 method_match_quality = src_method_match_quality;
2818 break;
2820 [[fallthrough]];
2821 case 2: /* Ext method is champion. */
2822 method_oload_champ = ext_method_oload_champ;
2823 method_badness = ext_method_badness;
2824 src_method_oload_champ = -1;
2825 method_match_quality = ext_method_match_quality;
2826 break;
2827 case 3: /* Src method is champion. */
2828 method_oload_champ = src_method_oload_champ;
2829 method_badness = src_method_badness;
2830 ext_method_oload_champ = -1;
2831 method_match_quality = src_method_match_quality;
2832 break;
2833 default:
2834 gdb_assert_not_reached ("Unexpected overload comparison "
2835 "result");
2836 break;
2839 else if (src_method_oload_champ >= 0)
2841 method_oload_champ = src_method_oload_champ;
2842 method_badness = src_method_badness;
2843 method_match_quality = src_method_match_quality;
2845 else if (ext_method_oload_champ >= 0)
2847 method_oload_champ = ext_method_oload_champ;
2848 method_badness = ext_method_badness;
2849 method_match_quality = ext_method_match_quality;
2853 if (method == NON_METHOD || method == BOTH)
2855 const char *qualified_name = NULL;
2857 /* If the overload match is being search for both as a method
2858 and non member function, the first argument must now be
2859 dereferenced. */
2860 if (method == BOTH)
2861 args[0] = value_ind (args[0]);
2863 if (fsym)
2865 qualified_name = fsym->natural_name ();
2867 /* If we have a function with a C++ name, try to extract just
2868 the function part. Do not try this for non-functions (e.g.
2869 function pointers). */
2870 if (qualified_name
2871 && (check_typedef (fsym->type ())->code ()
2872 == TYPE_CODE_FUNC))
2874 temp_func = cp_func_name (qualified_name);
2876 /* If cp_func_name did not remove anything, the name of the
2877 symbol did not include scope or argument types - it was
2878 probably a C-style function. */
2879 if (temp_func != nullptr)
2881 if (strcmp (temp_func.get (), qualified_name) == 0)
2882 func_name = NULL;
2883 else
2884 func_name = temp_func.get ();
2888 else
2890 func_name = name;
2891 qualified_name = name;
2894 /* If there was no C++ name, this must be a C-style function or
2895 not a function at all. Just return the same symbol. Do the
2896 same if cp_func_name fails for some reason. */
2897 if (func_name == NULL)
2899 *symp = fsym;
2900 return 0;
2903 func_oload_champ = find_oload_champ_namespace (args,
2904 func_name,
2905 qualified_name,
2906 &functions,
2907 &func_badness,
2908 no_adl);
2910 if (func_oload_champ >= 0)
2911 func_match_quality = classify_oload_match (func_badness,
2912 args.size (), 0);
2915 /* Did we find a match ? */
2916 if (method_oload_champ == -1 && func_oload_champ == -1)
2917 throw_error (NOT_FOUND_ERROR,
2918 _("No symbol \"%s\" in current context."),
2919 name);
2921 /* If we have found both a method match and a function
2922 match, find out which one is better, and calculate match
2923 quality. */
2924 if (method_oload_champ >= 0 && func_oload_champ >= 0)
2926 switch (compare_badness (func_badness, method_badness))
2928 case 0: /* Top two contenders are equally good. */
2929 /* FIXME: GDB does not support the general ambiguous case.
2930 All candidates should be collected and presented the
2931 user. */
2932 error (_("Ambiguous overload resolution"));
2933 break;
2934 case 1: /* Incomparable top contenders. */
2935 /* This is an error incompatible candidates
2936 should not have been proposed. */
2937 error (_("Internal error: incompatible "
2938 "overload candidates proposed"));
2939 break;
2940 case 2: /* Function champion. */
2941 method_oload_champ = -1;
2942 match_quality = func_match_quality;
2943 break;
2944 case 3: /* Method champion. */
2945 func_oload_champ = -1;
2946 match_quality = method_match_quality;
2947 break;
2948 default:
2949 error (_("Internal error: unexpected overload comparison result"));
2950 break;
2953 else
2955 /* We have either a method match or a function match. */
2956 if (method_oload_champ >= 0)
2957 match_quality = method_match_quality;
2958 else
2959 match_quality = func_match_quality;
2962 if (match_quality == INCOMPATIBLE)
2964 std::string hint = incomplete_type_hint (args);
2965 if (method == METHOD)
2966 error (_("Cannot resolve method %s%s%s to any overloaded instance%s"),
2967 obj_type_name,
2968 (obj_type_name && *obj_type_name) ? "::" : "",
2969 name, hint.c_str ());
2970 else
2971 error (_("Cannot resolve function %s to any overloaded instance%s"),
2972 func_name, hint.c_str ());
2974 else if (match_quality == NON_STANDARD)
2976 if (method == METHOD)
2977 warning (_("Using non-standard conversion to match "
2978 "method %s%s%s to supplied arguments"),
2979 obj_type_name,
2980 (obj_type_name && *obj_type_name) ? "::" : "",
2981 name);
2982 else
2983 warning (_("Using non-standard conversion to match "
2984 "function %s to supplied arguments"),
2985 func_name);
2988 if (staticp != NULL)
2989 *staticp = oload_method_static_p (methods.data (), method_oload_champ);
2991 if (method_oload_champ >= 0)
2993 if (src_method_oload_champ >= 0)
2995 if (TYPE_FN_FIELD_VIRTUAL_P (methods, method_oload_champ)
2996 && noside != EVAL_AVOID_SIDE_EFFECTS)
2998 *valp = value_virtual_fn_field (&temp, methods.data (),
2999 method_oload_champ, basetype,
3000 boffset);
3002 else
3003 *valp = value_fn_field (&temp, methods.data (),
3004 method_oload_champ, basetype, boffset);
3006 else
3007 *valp = value::from_xmethod
3008 (std::move (xmethods[ext_method_oload_champ]));
3010 else
3011 *symp = functions[func_oload_champ];
3013 if (objp)
3015 struct type *temp_type = check_typedef (temp->type ());
3016 struct type *objtype = check_typedef (obj_type);
3018 if (temp_type->code () != TYPE_CODE_PTR
3019 && objtype->is_pointer_or_reference ())
3021 temp = value_addr (temp);
3023 *objp = temp;
3026 switch (match_quality)
3028 case INCOMPATIBLE:
3029 return 100;
3030 case NON_STANDARD:
3031 return 10;
3032 default: /* STANDARD */
3033 return 0;
3037 /* Find the best overload match, searching for FUNC_NAME in namespaces
3038 contained in QUALIFIED_NAME until it either finds a good match or
3039 runs out of namespaces. It stores the overloaded functions in
3040 *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV. If NO_ADL,
3041 argument dependent lookup is not performed. */
3043 static int
3044 find_oload_champ_namespace (gdb::array_view<value *> args,
3045 const char *func_name,
3046 const char *qualified_name,
3047 std::vector<symbol *> *oload_syms,
3048 badness_vector *oload_champ_bv,
3049 const int no_adl)
3051 int oload_champ;
3053 find_oload_champ_namespace_loop (args,
3054 func_name,
3055 qualified_name, 0,
3056 oload_syms, oload_champ_bv,
3057 &oload_champ,
3058 no_adl);
3060 return oload_champ;
3063 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
3064 how deep we've looked for namespaces, and the champ is stored in
3065 OLOAD_CHAMP. The return value is 1 if the champ is a good one, 0
3066 if it isn't. Other arguments are the same as in
3067 find_oload_champ_namespace. */
3069 static int
3070 find_oload_champ_namespace_loop (gdb::array_view<value *> args,
3071 const char *func_name,
3072 const char *qualified_name,
3073 int namespace_len,
3074 std::vector<symbol *> *oload_syms,
3075 badness_vector *oload_champ_bv,
3076 int *oload_champ,
3077 const int no_adl)
3079 int next_namespace_len = namespace_len;
3080 int searched_deeper = 0;
3081 int new_oload_champ;
3082 char *new_namespace;
3084 if (next_namespace_len != 0)
3086 gdb_assert (qualified_name[next_namespace_len] == ':');
3087 next_namespace_len += 2;
3089 next_namespace_len +=
3090 cp_find_first_component (qualified_name + next_namespace_len);
3092 /* First, see if we have a deeper namespace we can search in.
3093 If we get a good match there, use it. */
3095 if (qualified_name[next_namespace_len] == ':')
3097 searched_deeper = 1;
3099 if (find_oload_champ_namespace_loop (args,
3100 func_name, qualified_name,
3101 next_namespace_len,
3102 oload_syms, oload_champ_bv,
3103 oload_champ, no_adl))
3105 return 1;
3109 /* If we reach here, either we're in the deepest namespace or we
3110 didn't find a good match in a deeper namespace. But, in the
3111 latter case, we still have a bad match in a deeper namespace;
3112 note that we might not find any match at all in the current
3113 namespace. (There's always a match in the deepest namespace,
3114 because this overload mechanism only gets called if there's a
3115 function symbol to start off with.) */
3117 new_namespace = (char *) alloca (namespace_len + 1);
3118 strncpy (new_namespace, qualified_name, namespace_len);
3119 new_namespace[namespace_len] = '\0';
3121 std::vector<symbol *> new_oload_syms
3122 = make_symbol_overload_list (func_name, new_namespace);
3124 /* If we have reached the deepest level perform argument
3125 determined lookup. */
3126 if (!searched_deeper && !no_adl)
3128 int ix;
3129 struct type **arg_types;
3131 /* Prepare list of argument types for overload resolution. */
3132 arg_types = (struct type **)
3133 alloca (args.size () * (sizeof (struct type *)));
3134 for (ix = 0; ix < args.size (); ix++)
3135 arg_types[ix] = args[ix]->type ();
3136 add_symbol_overload_list_adl ({arg_types, args.size ()}, func_name,
3137 &new_oload_syms);
3140 badness_vector new_oload_champ_bv;
3141 new_oload_champ = find_oload_champ (args,
3142 new_oload_syms.size (),
3143 NULL, NULL, new_oload_syms.data (),
3144 &new_oload_champ_bv);
3146 /* Case 1: We found a good match. Free earlier matches (if any),
3147 and return it. Case 2: We didn't find a good match, but we're
3148 not the deepest function. Then go with the bad match that the
3149 deeper function found. Case 3: We found a bad match, and we're
3150 the deepest function. Then return what we found, even though
3151 it's a bad match. */
3153 if (new_oload_champ != -1
3154 && classify_oload_match (new_oload_champ_bv, args.size (), 0) == STANDARD)
3156 *oload_syms = std::move (new_oload_syms);
3157 *oload_champ = new_oload_champ;
3158 *oload_champ_bv = std::move (new_oload_champ_bv);
3159 return 1;
3161 else if (searched_deeper)
3163 return 0;
3165 else
3167 *oload_syms = std::move (new_oload_syms);
3168 *oload_champ = new_oload_champ;
3169 *oload_champ_bv = std::move (new_oload_champ_bv);
3170 return 0;
3174 /* Look for a function to take ARGS. Find the best match from among
3175 the overloaded methods or functions given by METHODS or FUNCTIONS
3176 or XMETHODS, respectively. One, and only one of METHODS, FUNCTIONS
3177 and XMETHODS can be non-NULL.
3179 NUM_FNS is the length of the array pointed at by METHODS, FUNCTIONS
3180 or XMETHODS, whichever is non-NULL.
3182 Return the index of the best match; store an indication of the
3183 quality of the match in OLOAD_CHAMP_BV. */
3185 static int
3186 find_oload_champ (gdb::array_view<value *> args,
3187 size_t num_fns,
3188 fn_field *methods,
3189 xmethod_worker_up *xmethods,
3190 symbol **functions,
3191 badness_vector *oload_champ_bv)
3193 /* A measure of how good an overloaded instance is. */
3194 badness_vector bv;
3195 /* Index of best overloaded function. */
3196 int oload_champ = -1;
3197 /* Current ambiguity state for overload resolution. */
3198 int oload_ambiguous = 0;
3199 /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs. */
3201 /* A champion can be found among methods alone, or among functions
3202 alone, or in xmethods alone, but not in more than one of these
3203 groups. */
3204 gdb_assert ((methods != NULL) + (functions != NULL) + (xmethods != NULL)
3205 == 1);
3207 /* Consider each candidate in turn. */
3208 for (size_t ix = 0; ix < num_fns; ix++)
3210 int jj;
3211 int static_offset = 0;
3212 bool varargs = false;
3213 std::vector<type *> parm_types;
3215 if (xmethods != NULL)
3216 parm_types = xmethods[ix]->get_arg_types ();
3217 else
3219 size_t nparms;
3221 if (methods != NULL)
3223 nparms = TYPE_FN_FIELD_TYPE (methods, ix)->num_fields ();
3224 static_offset = oload_method_static_p (methods, ix);
3225 varargs = TYPE_FN_FIELD_TYPE (methods, ix)->has_varargs ();
3227 else
3229 nparms = functions[ix]->type ()->num_fields ();
3230 varargs = functions[ix]->type ()->has_varargs ();
3233 parm_types.reserve (nparms);
3234 for (jj = 0; jj < nparms; jj++)
3236 type *t = (methods != NULL
3237 ? (TYPE_FN_FIELD_ARGS (methods, ix)[jj].type ())
3238 : functions[ix]->type ()->field (jj).type ());
3239 parm_types.push_back (t);
3243 /* Compare parameter types to supplied argument types. Skip
3244 THIS for static methods. */
3245 bv = rank_function (parm_types,
3246 args.slice (static_offset),
3247 varargs);
3249 if (overload_debug)
3251 if (methods != NULL)
3252 gdb_printf (gdb_stderr,
3253 "Overloaded method instance %s, # of parms %d\n",
3254 methods[ix].physname, (int) parm_types.size ());
3255 else if (xmethods != NULL)
3256 gdb_printf (gdb_stderr,
3257 "Xmethod worker, # of parms %d\n",
3258 (int) parm_types.size ());
3259 else
3260 gdb_printf (gdb_stderr,
3261 "Overloaded function instance "
3262 "%s # of parms %d\n",
3263 functions[ix]->demangled_name (),
3264 (int) parm_types.size ());
3266 gdb_printf (gdb_stderr,
3267 "...Badness of length : {%d, %d}\n",
3268 bv[0].rank, bv[0].subrank);
3270 for (jj = 1; jj < bv.size (); jj++)
3271 gdb_printf (gdb_stderr,
3272 "...Badness of arg %d : {%d, %d}\n",
3273 jj, bv[jj].rank, bv[jj].subrank);
3276 if (oload_champ_bv->empty ())
3278 *oload_champ_bv = std::move (bv);
3279 oload_champ = 0;
3281 else /* See whether current candidate is better or worse than
3282 previous best. */
3283 switch (compare_badness (bv, *oload_champ_bv))
3285 case 0: /* Top two contenders are equally good. */
3286 oload_ambiguous = 1;
3287 break;
3288 case 1: /* Incomparable top contenders. */
3289 oload_ambiguous = 2;
3290 break;
3291 case 2: /* New champion, record details. */
3292 *oload_champ_bv = std::move (bv);
3293 oload_ambiguous = 0;
3294 oload_champ = ix;
3295 break;
3296 case 3:
3297 default:
3298 break;
3300 if (overload_debug)
3301 gdb_printf (gdb_stderr, "Overload resolution "
3302 "champion is %d, ambiguous? %d\n",
3303 oload_champ, oload_ambiguous);
3306 return oload_champ;
3309 /* Return 1 if we're looking at a static method, 0 if we're looking at
3310 a non-static method or a function that isn't a method. */
3312 static int
3313 oload_method_static_p (struct fn_field *fns_ptr, int index)
3315 if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3316 return 1;
3317 else
3318 return 0;
3321 /* Check how good an overload match OLOAD_CHAMP_BV represents. */
3323 static enum oload_classification
3324 classify_oload_match (const badness_vector &oload_champ_bv,
3325 int nargs,
3326 int static_offset)
3328 int ix;
3329 enum oload_classification worst = STANDARD;
3331 for (ix = 1; ix <= nargs - static_offset; ix++)
3333 /* If this conversion is as bad as INCOMPATIBLE_TYPE_BADNESS
3334 or worse return INCOMPATIBLE. */
3335 if (compare_ranks (oload_champ_bv[ix],
3336 INCOMPATIBLE_TYPE_BADNESS) <= 0)
3337 return INCOMPATIBLE; /* Truly mismatched types. */
3338 /* Otherwise If this conversion is as bad as
3339 NS_POINTER_CONVERSION_BADNESS or worse return NON_STANDARD. */
3340 else if (compare_ranks (oload_champ_bv[ix],
3341 NS_POINTER_CONVERSION_BADNESS) <= 0)
3342 worst = NON_STANDARD; /* Non-standard type conversions
3343 needed. */
3346 /* If no INCOMPATIBLE classification was found, return the worst one
3347 that was found (if any). */
3348 return worst;
3351 /* C++: return 1 is NAME is a legitimate name for the destructor of
3352 type TYPE. If TYPE does not have a destructor, or if NAME is
3353 inappropriate for TYPE, an error is signaled. Parameter TYPE should not yet
3354 have CHECK_TYPEDEF applied, this function will apply it itself. */
3357 destructor_name_p (const char *name, struct type *type)
3359 if (name[0] == '~')
3361 const char *dname = type_name_or_error (type);
3362 const char *cp = strchr (dname, '<');
3363 unsigned int len;
3365 /* Do not compare the template part for template classes. */
3366 if (cp == NULL)
3367 len = strlen (dname);
3368 else
3369 len = cp - dname;
3370 if (strlen (name + 1) != len || strncmp (dname, name + 1, len) != 0)
3371 error (_("name of destructor must equal name of class"));
3372 else
3373 return 1;
3375 return 0;
3378 /* Find an enum constant named NAME in TYPE. TYPE must be an "enum
3379 class". If the name is found, return a value representing it;
3380 otherwise throw an exception. */
3382 static struct value *
3383 enum_constant_from_type (struct type *type, const char *name)
3385 int i;
3386 int name_len = strlen (name);
3388 gdb_assert (type->code () == TYPE_CODE_ENUM
3389 && type->is_declared_class ());
3391 for (i = TYPE_N_BASECLASSES (type); i < type->num_fields (); ++i)
3393 const char *fname = type->field (i).name ();
3394 int len;
3396 if (type->field (i).loc_kind () != FIELD_LOC_KIND_ENUMVAL
3397 || fname == NULL)
3398 continue;
3400 /* Look for the trailing "::NAME", since enum class constant
3401 names are qualified here. */
3402 len = strlen (fname);
3403 if (len + 2 >= name_len
3404 && fname[len - name_len - 2] == ':'
3405 && fname[len - name_len - 1] == ':'
3406 && strcmp (&fname[len - name_len], name) == 0)
3407 return value_from_longest (type, type->field (i).loc_enumval ());
3410 error (_("no constant named \"%s\" in enum \"%s\""),
3411 name, type->name ());
3414 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3415 return the appropriate member (or the address of the member, if
3416 WANT_ADDRESS). This function is used to resolve user expressions
3417 of the form "DOMAIN::NAME". For more details on what happens, see
3418 the comment before value_struct_elt_for_reference. */
3420 struct value *
3421 value_aggregate_elt (struct type *curtype, const char *name,
3422 struct type *expect_type, int want_address,
3423 enum noside noside)
3425 switch (curtype->code ())
3427 case TYPE_CODE_STRUCT:
3428 case TYPE_CODE_UNION:
3429 return value_struct_elt_for_reference (curtype, 0, curtype,
3430 name, expect_type,
3431 want_address, noside);
3432 case TYPE_CODE_NAMESPACE:
3433 return value_namespace_elt (curtype, name,
3434 want_address, noside);
3436 case TYPE_CODE_ENUM:
3437 return enum_constant_from_type (curtype, name);
3439 default:
3440 internal_error (_("non-aggregate type in value_aggregate_elt"));
3444 /* Compares the two method/function types T1 and T2 for "equality"
3445 with respect to the methods' parameters. If the types of the
3446 two parameter lists are the same, returns 1; 0 otherwise. This
3447 comparison may ignore any artificial parameters in T1 if
3448 SKIP_ARTIFICIAL is non-zero. This function will ALWAYS skip
3449 the first artificial parameter in T1, assumed to be a 'this' pointer.
3451 The type T2 is expected to have come from make_params (in eval.c). */
3453 static int
3454 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3456 int start = 0;
3458 if (t1->num_fields () > 0 && t1->field (0).is_artificial ())
3459 ++start;
3461 /* If skipping artificial fields, find the first real field
3462 in T1. */
3463 if (skip_artificial)
3465 while (start < t1->num_fields ()
3466 && t1->field (start).is_artificial ())
3467 ++start;
3470 /* Now compare parameters. */
3472 /* Special case: a method taking void. T1 will contain no
3473 non-artificial fields, and T2 will contain TYPE_CODE_VOID. */
3474 if ((t1->num_fields () - start) == 0 && t2->num_fields () == 1
3475 && t2->field (0).type ()->code () == TYPE_CODE_VOID)
3476 return 1;
3478 if ((t1->num_fields () - start) == t2->num_fields ())
3480 int i;
3482 for (i = 0; i < t2->num_fields (); ++i)
3484 if (compare_ranks (rank_one_type (t1->field (start + i).type (),
3485 t2->field (i).type (), NULL),
3486 EXACT_MATCH_BADNESS) != 0)
3487 return 0;
3490 return 1;
3493 return 0;
3496 /* C++: Given an aggregate type VT, and a class type CLS, search
3497 recursively for CLS using value V; If found, store the offset
3498 which is either fetched from the virtual base pointer if CLS
3499 is virtual or accumulated offset of its parent classes if
3500 CLS is non-virtual in *BOFFS, set ISVIRT to indicate if CLS
3501 is virtual, and return true. If not found, return false. */
3503 static bool
3504 get_baseclass_offset (struct type *vt, struct type *cls,
3505 struct value *v, int *boffs, bool *isvirt)
3507 for (int i = 0; i < TYPE_N_BASECLASSES (vt); i++)
3509 struct type *t = vt->field (i).type ();
3510 if (types_equal (t, cls))
3512 if (BASETYPE_VIA_VIRTUAL (vt, i))
3514 const gdb_byte *adr = v->contents_for_printing ().data ();
3515 *boffs = baseclass_offset (vt, i, adr, v->offset (),
3516 value_as_long (v), v);
3517 *isvirt = true;
3519 else
3520 *isvirt = false;
3521 return true;
3524 if (get_baseclass_offset (check_typedef (t), cls, v, boffs, isvirt))
3526 if (*isvirt == false) /* Add non-virtual base offset. */
3528 const gdb_byte *adr = v->contents_for_printing ().data ();
3529 *boffs += baseclass_offset (vt, i, adr, v->offset (),
3530 value_as_long (v), v);
3532 return true;
3536 return false;
3539 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3540 return the address of this member as a "pointer to member" type.
3541 If INTYPE is non-null, then it will be the type of the member we
3542 are looking for. This will help us resolve "pointers to member
3543 functions". This function is used to resolve user expressions of
3544 the form "DOMAIN::NAME". */
3546 static struct value *
3547 value_struct_elt_for_reference (struct type *domain, int offset,
3548 struct type *curtype, const char *name,
3549 struct type *intype,
3550 int want_address,
3551 enum noside noside)
3553 struct type *t = check_typedef (curtype);
3554 int i;
3555 struct value *result;
3557 if (t->code () != TYPE_CODE_STRUCT
3558 && t->code () != TYPE_CODE_UNION)
3559 error (_("Internal error: non-aggregate type "
3560 "to value_struct_elt_for_reference"));
3562 for (i = t->num_fields () - 1; i >= TYPE_N_BASECLASSES (t); i--)
3564 const char *t_field_name = t->field (i).name ();
3566 if (t_field_name && strcmp (t_field_name, name) == 0)
3568 if (t->field (i).is_static ())
3570 struct value *v = value_static_field (t, i);
3571 if (want_address)
3572 v = value_addr (v);
3573 return v;
3575 if (t->field (i).is_packed ())
3576 error (_("pointers to bitfield members not allowed"));
3578 if (want_address)
3579 return value_from_longest
3580 (lookup_memberptr_type (t->field (i).type (), domain),
3581 offset + (LONGEST) (t->field (i).loc_bitpos () >> 3));
3582 else if (noside != EVAL_NORMAL)
3583 return value::allocate (t->field (i).type ());
3584 else
3586 /* Try to evaluate NAME as a qualified name with implicit
3587 this pointer. In this case, attempt to return the
3588 equivalent to `this->*(&TYPE::NAME)'. */
3589 struct value *v = value_of_this_silent (current_language);
3590 if (v != NULL)
3592 struct value *ptr, *this_v = v;
3593 long mem_offset;
3594 struct type *type, *tmp;
3596 ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3597 type = check_typedef (ptr->type ());
3598 gdb_assert (type != NULL
3599 && type->code () == TYPE_CODE_MEMBERPTR);
3600 tmp = lookup_pointer_type (TYPE_SELF_TYPE (type));
3601 v = value_cast_pointers (tmp, v, 1);
3602 mem_offset = value_as_long (ptr);
3603 if (domain != curtype)
3605 /* Find class offset of type CURTYPE from either its
3606 parent type DOMAIN or the type of implied this. */
3607 int boff = 0;
3608 bool isvirt = false;
3609 if (get_baseclass_offset (domain, curtype, v, &boff,
3610 &isvirt))
3611 mem_offset += boff;
3612 else
3614 struct type *p = check_typedef (this_v->type ());
3615 p = check_typedef (p->target_type ());
3616 if (get_baseclass_offset (p, curtype, this_v,
3617 &boff, &isvirt))
3618 mem_offset += boff;
3621 tmp = lookup_pointer_type (type->target_type ());
3622 result = value_from_pointer (tmp,
3623 value_as_long (v) + mem_offset);
3624 return value_ind (result);
3627 error (_("Cannot reference non-static field \"%s\""), name);
3632 /* C++: If it was not found as a data field, then try to return it
3633 as a pointer to a method. */
3635 /* Perform all necessary dereferencing. */
3636 while (intype && intype->code () == TYPE_CODE_PTR)
3637 intype = intype->target_type ();
3639 for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3641 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3643 if (t_field_name && strcmp (t_field_name, name) == 0)
3645 int j;
3646 int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3647 struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3649 check_stub_method_group (t, i);
3651 if (intype)
3653 for (j = 0; j < len; ++j)
3655 if (TYPE_CONST (intype) != TYPE_FN_FIELD_CONST (f, j))
3656 continue;
3657 if (TYPE_VOLATILE (intype) != TYPE_FN_FIELD_VOLATILE (f, j))
3658 continue;
3660 if (compare_parameters (TYPE_FN_FIELD_TYPE (f, j), intype, 0)
3661 || compare_parameters (TYPE_FN_FIELD_TYPE (f, j),
3662 intype, 1))
3663 break;
3666 if (j == len)
3667 error (_("no member function matches "
3668 "that type instantiation"));
3670 else
3672 int ii;
3674 j = -1;
3675 for (ii = 0; ii < len; ++ii)
3677 /* Skip artificial methods. This is necessary if,
3678 for example, the user wants to "print
3679 subclass::subclass" with only one user-defined
3680 constructor. There is no ambiguity in this case.
3681 We are careful here to allow artificial methods
3682 if they are the unique result. */
3683 if (TYPE_FN_FIELD_ARTIFICIAL (f, ii))
3685 if (j == -1)
3686 j = ii;
3687 continue;
3690 /* Desired method is ambiguous if more than one
3691 method is defined. */
3692 if (j != -1 && !TYPE_FN_FIELD_ARTIFICIAL (f, j))
3693 error (_("non-unique member `%s' requires "
3694 "type instantiation"), name);
3696 j = ii;
3699 if (j == -1)
3700 error (_("no matching member function"));
3703 if (TYPE_FN_FIELD_STATIC_P (f, j))
3705 struct symbol *s =
3706 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3707 0, SEARCH_FUNCTION_DOMAIN, 0).symbol;
3709 if (s == NULL)
3710 return NULL;
3712 if (want_address)
3713 return value_addr (read_var_value (s, 0, 0));
3714 else
3715 return read_var_value (s, 0, 0);
3718 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3720 if (want_address)
3722 result = value::allocate
3723 (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3724 cplus_make_method_ptr (result->type (),
3725 result->contents_writeable ().data (),
3726 TYPE_FN_FIELD_VOFFSET (f, j), 1);
3728 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3729 return value::allocate (TYPE_FN_FIELD_TYPE (f, j));
3730 else
3731 error (_("Cannot reference virtual member function \"%s\""),
3732 name);
3734 else
3736 struct symbol *s =
3737 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3738 0, SEARCH_FUNCTION_DOMAIN, 0).symbol;
3740 if (s == NULL)
3741 return NULL;
3743 struct value *v = read_var_value (s, 0, 0);
3744 if (!want_address)
3745 result = v;
3746 else
3748 result = value::allocate (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3749 cplus_make_method_ptr (result->type (),
3750 result->contents_writeable ().data (),
3751 v->address (), 0);
3754 return result;
3757 for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3759 struct value *v;
3760 int base_offset;
3762 if (BASETYPE_VIA_VIRTUAL (t, i))
3763 base_offset = 0;
3764 else
3765 base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3766 v = value_struct_elt_for_reference (domain,
3767 offset + base_offset,
3768 TYPE_BASECLASS (t, i),
3769 name, intype,
3770 want_address, noside);
3771 if (v)
3772 return v;
3775 /* As a last chance, pretend that CURTYPE is a namespace, and look
3776 it up that way; this (frequently) works for types nested inside
3777 classes. */
3779 return value_maybe_namespace_elt (curtype, name,
3780 want_address, noside);
3783 /* C++: Return the member NAME of the namespace given by the type
3784 CURTYPE. */
3786 static struct value *
3787 value_namespace_elt (const struct type *curtype,
3788 const char *name, int want_address,
3789 enum noside noside)
3791 struct value *retval = value_maybe_namespace_elt (curtype, name,
3792 want_address,
3793 noside);
3795 if (retval == NULL)
3796 error (_("No symbol \"%s\" in namespace \"%s\"."),
3797 name, curtype->name ());
3799 return retval;
3802 /* A helper function used by value_namespace_elt and
3803 value_struct_elt_for_reference. It looks up NAME inside the
3804 context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
3805 is a class and NAME refers to a type in CURTYPE itself (as opposed
3806 to, say, some base class of CURTYPE). */
3808 static struct value *
3809 value_maybe_namespace_elt (const struct type *curtype,
3810 const char *name, int want_address,
3811 enum noside noside)
3813 const char *namespace_name = curtype->name ();
3814 struct block_symbol sym;
3815 struct value *result;
3817 sym = cp_lookup_symbol_namespace (namespace_name, name,
3818 get_selected_block (0), SEARCH_VFT);
3820 if (sym.symbol == NULL)
3821 return NULL;
3822 else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3823 && (sym.symbol->aclass () == LOC_TYPEDEF))
3824 result = value::allocate (sym.symbol->type ());
3825 else
3826 result = value_of_variable (sym.symbol, sym.block);
3828 if (want_address)
3829 result = value_addr (result);
3831 return result;
3834 /* Given a pointer or a reference value V, find its real (RTTI) type.
3836 Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3837 and refer to the values computed for the object pointed to. */
3839 struct type *
3840 value_rtti_indirect_type (struct value *v, int *full,
3841 LONGEST *top, int *using_enc)
3843 struct value *target = NULL;
3844 struct type *type, *real_type, *target_type;
3846 type = v->type ();
3847 type = check_typedef (type);
3848 if (TYPE_IS_REFERENCE (type))
3849 target = coerce_ref (v);
3850 else if (type->code () == TYPE_CODE_PTR)
3855 target = value_ind (v);
3857 catch (const gdb_exception_error &except)
3859 if (except.error == MEMORY_ERROR)
3861 /* value_ind threw a memory error. The pointer is NULL or
3862 contains an uninitialized value: we can't determine any
3863 type. */
3864 return NULL;
3866 throw;
3869 else
3870 return NULL;
3872 real_type = value_rtti_type (target, full, top, using_enc);
3874 if (real_type)
3876 /* Copy qualifiers to the referenced object. */
3877 target_type = target->type ();
3878 real_type = make_cv_type (TYPE_CONST (target_type),
3879 TYPE_VOLATILE (target_type), real_type, NULL);
3880 if (TYPE_IS_REFERENCE (type))
3881 real_type = lookup_reference_type (real_type, type->code ());
3882 else if (type->code () == TYPE_CODE_PTR)
3883 real_type = lookup_pointer_type (real_type);
3884 else
3885 internal_error (_("Unexpected value type."));
3887 /* Copy qualifiers to the pointer/reference. */
3888 real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3889 real_type, NULL);
3892 return real_type;
3895 /* Given a value pointed to by ARGP, check its real run-time type, and
3896 if that is different from the enclosing type, create a new value
3897 using the real run-time type as the enclosing type (and of the same
3898 type as ARGP) and return it, with the embedded offset adjusted to
3899 be the correct offset to the enclosed object. RTYPE is the type,
3900 and XFULL, XTOP, and XUSING_ENC are the other parameters, computed
3901 by value_rtti_type(). If these are available, they can be supplied
3902 and a second call to value_rtti_type() is avoided. (Pass RTYPE ==
3903 NULL if they're not available. */
3905 struct value *
3906 value_full_object (struct value *argp,
3907 struct type *rtype,
3908 int xfull, int xtop,
3909 int xusing_enc)
3911 struct type *real_type;
3912 int full = 0;
3913 LONGEST top = -1;
3914 int using_enc = 0;
3915 struct value *new_val;
3917 if (rtype)
3919 real_type = rtype;
3920 full = xfull;
3921 top = xtop;
3922 using_enc = xusing_enc;
3924 else
3925 real_type = value_rtti_type (argp, &full, &top, &using_enc);
3927 /* If no RTTI data, or if object is already complete, do nothing. */
3928 if (!real_type || real_type == argp->enclosing_type ())
3929 return argp;
3931 /* In a destructor we might see a real type that is a superclass of
3932 the object's type. In this case it is better to leave the object
3933 as-is. */
3934 if (full
3935 && real_type->length () < argp->enclosing_type ()->length ())
3936 return argp;
3938 /* If we have the full object, but for some reason the enclosing
3939 type is wrong, set it. */
3940 /* pai: FIXME -- sounds iffy */
3941 if (full)
3943 argp = argp->copy ();
3944 argp->set_enclosing_type (real_type);
3945 return argp;
3948 /* Check if object is in memory. */
3949 if (argp->lval () != lval_memory)
3951 warning (_("Couldn't retrieve complete object of RTTI "
3952 "type %s; object may be in register(s)."),
3953 real_type->name ());
3955 return argp;
3958 /* All other cases -- retrieve the complete object. */
3959 /* Go back by the computed top_offset from the beginning of the
3960 object, adjusting for the embedded offset of argp if that's what
3961 value_rtti_type used for its computation. */
3962 new_val = value_at_lazy (real_type, argp->address () - top +
3963 (using_enc ? 0 : argp->embedded_offset ()));
3964 new_val->deprecated_set_type (argp->type ());
3965 new_val->set_embedded_offset ((using_enc
3966 ? top + argp->embedded_offset ()
3967 : top));
3968 return new_val;
3972 /* Return the value of the local variable, if one exists. Throw error
3973 otherwise, such as if the request is made in an inappropriate context. */
3975 struct value *
3976 value_of_this (const struct language_defn *lang)
3978 struct block_symbol sym;
3979 const struct block *b;
3980 frame_info_ptr frame;
3982 if (lang->name_of_this () == NULL)
3983 error (_("no `this' in current language"));
3985 frame = get_selected_frame (_("no frame selected"));
3987 b = get_frame_block (frame, NULL);
3989 sym = lookup_language_this (lang, b);
3990 if (sym.symbol == NULL)
3991 error (_("current stack frame does not contain a variable named `%s'"),
3992 lang->name_of_this ());
3994 return read_var_value (sym.symbol, sym.block, frame);
3997 /* Return the value of the local variable, if one exists. Return NULL
3998 otherwise. Never throw error. */
4000 struct value *
4001 value_of_this_silent (const struct language_defn *lang)
4003 struct value *ret = NULL;
4007 ret = value_of_this (lang);
4009 catch (const gdb_exception_error &except)
4013 return ret;
4016 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH
4017 elements long, starting at LOWBOUND. The result has the same lower
4018 bound as the original ARRAY. */
4020 struct value *
4021 value_slice (struct value *array, int lowbound, int length)
4023 struct type *slice_range_type, *slice_type, *range_type;
4024 LONGEST lowerbound, upperbound;
4025 struct value *slice;
4026 struct type *array_type;
4028 array_type = check_typedef (array->type ());
4029 if (array_type->code () != TYPE_CODE_ARRAY
4030 && array_type->code () != TYPE_CODE_STRING)
4031 error (_("cannot take slice of non-array"));
4033 if (type_not_allocated (array_type))
4034 error (_("array not allocated"));
4035 if (type_not_associated (array_type))
4036 error (_("array not associated"));
4038 range_type = array_type->index_type ();
4039 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
4040 error (_("slice from bad array or bitstring"));
4042 if (lowbound < lowerbound || length < 0
4043 || lowbound + length - 1 > upperbound)
4044 error (_("slice out of range"));
4046 /* FIXME-type-allocation: need a way to free this type when we are
4047 done with it. */
4048 type_allocator alloc (range_type->target_type ());
4049 slice_range_type = create_static_range_type (alloc,
4050 range_type->target_type (),
4051 lowbound,
4052 lowbound + length - 1);
4055 struct type *element_type = array_type->target_type ();
4056 LONGEST offset
4057 = (lowbound - lowerbound) * check_typedef (element_type)->length ();
4059 slice_type = create_array_type (alloc,
4060 element_type,
4061 slice_range_type);
4062 slice_type->set_code (array_type->code ());
4064 if (array->lval () == lval_memory && array->lazy ())
4065 slice = value::allocate_lazy (slice_type);
4066 else
4068 slice = value::allocate (slice_type);
4069 array->contents_copy (slice, 0, offset,
4070 type_length_units (slice_type));
4073 slice->set_component_location (array);
4074 slice->set_offset (array->offset () + offset);
4077 return slice;
4080 /* See value.h. */
4082 struct value *
4083 value_literal_complex (struct value *arg1,
4084 struct value *arg2,
4085 struct type *type)
4087 struct value *val;
4088 struct type *real_type = type->target_type ();
4090 val = value::allocate (type);
4091 arg1 = value_cast (real_type, arg1);
4092 arg2 = value_cast (real_type, arg2);
4094 int len = real_type->length ();
4096 copy (arg1->contents (),
4097 val->contents_raw ().slice (0, len));
4098 copy (arg2->contents (),
4099 val->contents_raw ().slice (len, len));
4101 return val;
4104 /* See value.h. */
4106 struct value *
4107 value_real_part (struct value *value)
4109 struct type *type = check_typedef (value->type ());
4110 struct type *ttype = type->target_type ();
4112 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4113 return value_from_component (value, ttype, 0);
4116 /* See value.h. */
4118 struct value *
4119 value_imaginary_part (struct value *value)
4121 struct type *type = check_typedef (value->type ());
4122 struct type *ttype = type->target_type ();
4124 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4125 return value_from_component (value, ttype,
4126 check_typedef (ttype)->length ());
4129 /* Cast a value into the appropriate complex data type. */
4131 static struct value *
4132 cast_into_complex (struct type *type, struct value *val)
4134 struct type *real_type = type->target_type ();
4136 if (val->type ()->code () == TYPE_CODE_COMPLEX)
4138 struct type *val_real_type = val->type ()->target_type ();
4139 struct value *re_val = value::allocate (val_real_type);
4140 struct value *im_val = value::allocate (val_real_type);
4141 int len = val_real_type->length ();
4143 copy (val->contents ().slice (0, len),
4144 re_val->contents_raw ());
4145 copy (val->contents ().slice (len, len),
4146 im_val->contents_raw ());
4148 return value_literal_complex (re_val, im_val, type);
4150 else if (val->type ()->code () == TYPE_CODE_FLT
4151 || val->type ()->code () == TYPE_CODE_INT)
4152 return value_literal_complex (val,
4153 value::zero (real_type, not_lval),
4154 type);
4155 else
4156 error (_("cannot cast non-number to complex"));
4159 void _initialize_valops ();
4160 void
4161 _initialize_valops ()
4163 add_setshow_boolean_cmd ("overload-resolution", class_support,
4164 &overload_resolution, _("\
4165 Set overload resolution in evaluating C++ functions."), _("\
4166 Show overload resolution in evaluating C++ functions."),
4167 NULL, NULL,
4168 show_overload_resolution,
4169 &setlist, &showlist);
4170 overload_resolution = 1;