Add generated source files and fix thinko in aarch64-asm.c
[binutils-gdb.git] / gdb / valops.c
blob93e2dfedad08739e3f3da149bed7a3e4944e9977
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, 0, VAR_DOMAIN, 0);
122 if (sym.symbol != NULL)
124 if (sym.symbol->aclass () != LOC_BLOCK)
126 error (_("\"%s\" exists in this program but is not a function."),
127 name);
130 if (objf_p)
131 *objf_p = sym.symbol->objfile ();
133 return value_of_variable (sym.symbol, sym.block);
135 else
137 struct bound_minimal_symbol msymbol =
138 lookup_bound_minimal_symbol (name);
140 if (msymbol.minsym != NULL)
142 struct objfile *objfile = msymbol.objfile;
143 struct gdbarch *gdbarch = objfile->arch ();
145 struct type *type;
146 CORE_ADDR maddr;
147 type = lookup_pointer_type (builtin_type (gdbarch)->builtin_char);
148 type = lookup_function_type (type);
149 type = lookup_pointer_type (type);
150 maddr = msymbol.value_address ();
152 if (objf_p)
153 *objf_p = objfile;
155 return value_from_pointer (type, maddr);
157 else
159 if (!target_has_execution ())
160 error (_("evaluation of this expression "
161 "requires the target program to be active"));
162 else
163 error (_("evaluation of this expression requires the "
164 "program to have a function \"%s\"."),
165 name);
170 /* Allocate NBYTES of space in the inferior using the inferior's
171 malloc and return a value that is a pointer to the allocated
172 space. */
174 struct value *
175 value_allocate_space_in_inferior (int len)
177 struct objfile *objf;
178 struct value *val = find_function_in_inferior ("malloc", &objf);
179 struct gdbarch *gdbarch = objf->arch ();
180 struct value *blocklen;
182 blocklen = value_from_longest (builtin_type (gdbarch)->builtin_int, len);
183 val = call_function_by_hand (val, NULL, blocklen);
184 if (value_logical_not (val))
186 if (!target_has_execution ())
187 error (_("No memory available to program now: "
188 "you need to start the target first"));
189 else
190 error (_("No memory available to program: call to malloc failed"));
192 return val;
195 static CORE_ADDR
196 allocate_space_in_inferior (int len)
198 return value_as_long (value_allocate_space_in_inferior (len));
201 /* Cast struct value VAL to type TYPE and return as a value.
202 Both type and val must be of TYPE_CODE_STRUCT or TYPE_CODE_UNION
203 for this to work. Typedef to one of the codes is permitted.
204 Returns NULL if the cast is neither an upcast nor a downcast. */
206 static struct value *
207 value_cast_structs (struct type *type, struct value *v2)
209 struct type *t1;
210 struct type *t2;
211 struct value *v;
213 gdb_assert (type != NULL && v2 != NULL);
215 t1 = check_typedef (type);
216 t2 = check_typedef (v2->type ());
218 /* Check preconditions. */
219 gdb_assert ((t1->code () == TYPE_CODE_STRUCT
220 || t1->code () == TYPE_CODE_UNION)
221 && !!"Precondition is that type is of STRUCT or UNION kind.");
222 gdb_assert ((t2->code () == TYPE_CODE_STRUCT
223 || t2->code () == TYPE_CODE_UNION)
224 && !!"Precondition is that value is of STRUCT or UNION kind");
226 if (t1->name () != NULL
227 && t2->name () != NULL
228 && !strcmp (t1->name (), t2->name ()))
229 return NULL;
231 /* Upcasting: look in the type of the source to see if it contains the
232 type of the target as a superclass. If so, we'll need to
233 offset the pointer rather than just change its type. */
234 if (t1->name () != NULL)
236 v = search_struct_field (t1->name (),
237 v2, t2, 1);
238 if (v)
239 return v;
242 /* Downcasting: look in the type of the target to see if it contains the
243 type of the source as a superclass. If so, we'll need to
244 offset the pointer rather than just change its type. */
245 if (t2->name () != NULL)
247 /* Try downcasting using the run-time type of the value. */
248 int full, using_enc;
249 LONGEST top;
250 struct type *real_type;
252 real_type = value_rtti_type (v2, &full, &top, &using_enc);
253 if (real_type)
255 v = value_full_object (v2, real_type, full, top, using_enc);
256 v = value_at_lazy (real_type, v->address ());
257 real_type = v->type ();
259 /* We might be trying to cast to the outermost enclosing
260 type, in which case search_struct_field won't work. */
261 if (real_type->name () != NULL
262 && !strcmp (real_type->name (), t1->name ()))
263 return v;
265 v = search_struct_field (t2->name (), v, real_type, 1);
266 if (v)
267 return v;
270 /* Try downcasting using information from the destination type
271 T2. This wouldn't work properly for classes with virtual
272 bases, but those were handled above. */
273 v = search_struct_field (t2->name (),
274 value::zero (t1, not_lval), t1, 1);
275 if (v)
277 /* Downcasting is possible (t1 is superclass of v2). */
278 CORE_ADDR addr2 = v2->address () + v2->embedded_offset ();
280 addr2 -= v->address () + v->embedded_offset ();
281 return value_at (type, addr2);
285 return NULL;
288 /* Cast one pointer or reference type to another. Both TYPE and
289 the type of ARG2 should be pointer types, or else both should be
290 reference types. If SUBCLASS_CHECK is non-zero, this will force a
291 check to see whether TYPE is a superclass of ARG2's type. If
292 SUBCLASS_CHECK is zero, then the subclass check is done only when
293 ARG2 is itself non-zero. Returns the new pointer or reference. */
295 struct value *
296 value_cast_pointers (struct type *type, struct value *arg2,
297 int subclass_check)
299 struct type *type1 = check_typedef (type);
300 struct type *type2 = check_typedef (arg2->type ());
301 struct type *t1 = check_typedef (type1->target_type ());
302 struct type *t2 = check_typedef (type2->target_type ());
304 if (t1->code () == TYPE_CODE_STRUCT
305 && t2->code () == TYPE_CODE_STRUCT
306 && (subclass_check || !value_logical_not (arg2)))
308 struct value *v2;
310 if (TYPE_IS_REFERENCE (type2))
311 v2 = coerce_ref (arg2);
312 else
313 v2 = value_ind (arg2);
314 gdb_assert (check_typedef (v2->type ())->code ()
315 == TYPE_CODE_STRUCT && !!"Why did coercion fail?");
316 v2 = value_cast_structs (t1, v2);
317 /* At this point we have what we can have, un-dereference if needed. */
318 if (v2)
320 struct value *v = value_addr (v2);
322 v->deprecated_set_type (type);
323 return v;
327 /* No superclass found, just change the pointer type. */
328 arg2 = arg2->copy ();
329 arg2->deprecated_set_type (type);
330 arg2->set_enclosing_type (type);
331 arg2->set_pointed_to_offset (0); /* pai: chk_val */
332 return arg2;
335 /* See value.h. */
337 gdb_mpq
338 value_to_gdb_mpq (struct value *value)
340 struct type *type = check_typedef (value->type ());
342 gdb_mpq result;
343 if (is_floating_type (type))
344 result = target_float_to_host_double (value->contents ().data (), type);
345 else
347 gdb_assert (is_integral_type (type)
348 || is_fixed_point_type (type));
350 gdb_mpz vz;
351 vz.read (value->contents (), type_byte_order (type),
352 type->is_unsigned ());
353 result = vz;
355 if (is_fixed_point_type (type))
356 result *= type->fixed_point_scaling_factor ();
359 return result;
362 /* Assuming that TO_TYPE is a fixed point type, return a value
363 corresponding to the cast of FROM_VAL to that type. */
365 static struct value *
366 value_cast_to_fixed_point (struct type *to_type, struct value *from_val)
368 struct type *from_type = from_val->type ();
370 if (from_type == to_type)
371 return from_val;
373 if (!is_floating_type (from_type)
374 && !is_integral_type (from_type)
375 && !is_fixed_point_type (from_type))
376 error (_("Invalid conversion from type %s to fixed point type %s"),
377 from_type->name (), to_type->name ());
379 gdb_mpq vq = value_to_gdb_mpq (from_val);
381 /* Divide that value by the scaling factor to obtain the unscaled
382 value, first in rational form, and then in integer form. */
384 vq /= to_type->fixed_point_scaling_factor ();
385 gdb_mpz unscaled = vq.get_rounded ();
387 /* Finally, create the result value, and pack the unscaled value
388 in it. */
389 struct value *result = value::allocate (to_type);
390 unscaled.write (result->contents_raw (),
391 type_byte_order (to_type),
392 to_type->is_unsigned ());
394 return result;
397 /* Cast value ARG2 to type TYPE and return as a value.
398 More general than a C cast: accepts any two types of the same length,
399 and if ARG2 is an lvalue it can be cast into anything at all. */
400 /* In C++, casts may change pointer or object representations. */
402 struct value *
403 value_cast (struct type *type, struct value *arg2)
405 enum type_code code1;
406 enum type_code code2;
407 int scalar;
408 struct type *type2;
410 int convert_to_boolean = 0;
412 /* TYPE might be equal in meaning to the existing type of ARG2, but for
413 many reasons, might be a different type object (e.g. TYPE might be a
414 gdbarch owned type, while ARG2->type () could be an objfile owned
415 type).
417 In this case we want to preserve the LVAL of ARG2 as this allows the
418 resulting value to be used in more places. We do this by calling
419 VALUE_COPY if appropriate. */
420 if (types_deeply_equal (arg2->type (), type))
422 /* If the types are exactly equal then we can avoid creating a new
423 value completely. */
424 if (arg2->type () != type)
426 arg2 = arg2->copy ();
427 arg2->deprecated_set_type (type);
429 return arg2;
432 if (is_fixed_point_type (type))
433 return value_cast_to_fixed_point (type, arg2);
435 /* Check if we are casting struct reference to struct reference. */
436 if (TYPE_IS_REFERENCE (check_typedef (type)))
438 /* We dereference type; then we recurse and finally
439 we generate value of the given reference. Nothing wrong with
440 that. */
441 struct type *t1 = check_typedef (type);
442 struct type *dereftype = check_typedef (t1->target_type ());
443 struct value *val = value_cast (dereftype, arg2);
445 return value_ref (val, t1->code ());
448 if (TYPE_IS_REFERENCE (check_typedef (arg2->type ())))
449 /* We deref the value and then do the cast. */
450 return value_cast (type, coerce_ref (arg2));
452 /* Strip typedefs / resolve stubs in order to get at the type's
453 code/length, but remember the original type, to use as the
454 resulting type of the cast, in case it was a typedef. */
455 struct type *to_type = type;
457 type = check_typedef (type);
458 code1 = type->code ();
459 arg2 = coerce_ref (arg2);
460 type2 = check_typedef (arg2->type ());
462 /* You can't cast to a reference type. See value_cast_pointers
463 instead. */
464 gdb_assert (!TYPE_IS_REFERENCE (type));
466 /* A cast to an undetermined-length array_type, such as
467 (TYPE [])OBJECT, is treated like a cast to (TYPE [N])OBJECT,
468 where N is sizeof(OBJECT)/sizeof(TYPE). */
469 if (code1 == TYPE_CODE_ARRAY)
471 struct type *element_type = type->target_type ();
472 unsigned element_length = check_typedef (element_type)->length ();
474 if (element_length > 0 && type->bounds ()->high.kind () == PROP_UNDEFINED)
476 struct type *range_type = type->index_type ();
477 int val_length = type2->length ();
478 LONGEST low_bound, high_bound, new_length;
480 if (!get_discrete_bounds (range_type, &low_bound, &high_bound))
481 low_bound = 0, high_bound = 0;
482 new_length = val_length / element_length;
483 if (val_length % element_length != 0)
484 warning (_("array element type size does not "
485 "divide object size in cast"));
486 /* FIXME-type-allocation: need a way to free this type when
487 we are done with it. */
488 type_allocator alloc (range_type->target_type ());
489 range_type = create_static_range_type (alloc,
490 range_type->target_type (),
491 low_bound,
492 new_length + low_bound - 1);
493 arg2->deprecated_set_type (create_array_type (alloc,
494 element_type,
495 range_type));
496 return arg2;
500 if (current_language->c_style_arrays_p ()
501 && type2->code () == TYPE_CODE_ARRAY
502 && !type2->is_vector ())
503 arg2 = value_coerce_array (arg2);
505 if (type2->code () == TYPE_CODE_FUNC)
506 arg2 = value_coerce_function (arg2);
508 type2 = check_typedef (arg2->type ());
509 code2 = type2->code ();
511 if (code1 == TYPE_CODE_COMPLEX)
512 return cast_into_complex (to_type, arg2);
513 if (code1 == TYPE_CODE_BOOL)
515 code1 = TYPE_CODE_INT;
516 convert_to_boolean = 1;
518 if (code1 == TYPE_CODE_CHAR)
519 code1 = TYPE_CODE_INT;
520 if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
521 code2 = TYPE_CODE_INT;
523 scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
524 || code2 == TYPE_CODE_DECFLOAT || code2 == TYPE_CODE_ENUM
525 || code2 == TYPE_CODE_RANGE
526 || is_fixed_point_type (type2));
528 if ((code1 == TYPE_CODE_STRUCT || code1 == TYPE_CODE_UNION)
529 && (code2 == TYPE_CODE_STRUCT || code2 == TYPE_CODE_UNION)
530 && type->name () != 0)
532 struct value *v = value_cast_structs (to_type, arg2);
534 if (v)
535 return v;
538 if (is_floating_type (type) && scalar)
540 if (is_floating_value (arg2))
542 struct value *v = value::allocate (to_type);
543 target_float_convert (arg2->contents ().data (), type2,
544 v->contents_raw ().data (), type);
545 return v;
547 else if (is_fixed_point_type (type2))
549 gdb_mpq fp_val;
551 fp_val.read_fixed_point (arg2->contents (),
552 type_byte_order (type2),
553 type2->is_unsigned (),
554 type2->fixed_point_scaling_factor ());
556 struct value *v = value::allocate (to_type);
557 target_float_from_host_double (v->contents_raw ().data (),
558 to_type, fp_val.as_double ());
559 return v;
562 /* The only option left is an integral type. */
563 if (type2->is_unsigned ())
564 return value_from_ulongest (to_type, value_as_long (arg2));
565 else
566 return value_from_longest (to_type, value_as_long (arg2));
568 else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
569 || code1 == TYPE_CODE_RANGE)
570 && (scalar || code2 == TYPE_CODE_PTR
571 || code2 == TYPE_CODE_MEMBERPTR))
573 gdb_mpz longest;
575 /* When we cast pointers to integers, we mustn't use
576 gdbarch_pointer_to_address to find the address the pointer
577 represents, as value_as_long would. GDB should evaluate
578 expressions just as the compiler would --- and the compiler
579 sees a cast as a simple reinterpretation of the pointer's
580 bits. */
581 if (code2 == TYPE_CODE_PTR)
582 longest = extract_unsigned_integer (arg2->contents (),
583 type_byte_order (type2));
584 else
585 longest = value_as_mpz (arg2);
586 if (convert_to_boolean)
587 longest = bool (longest);
589 return value_from_mpz (to_type, longest);
591 else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT
592 || code2 == TYPE_CODE_ENUM
593 || code2 == TYPE_CODE_RANGE))
595 /* type->length () is the length of a pointer, but we really
596 want the length of an address! -- we are really dealing with
597 addresses (i.e., gdb representations) not pointers (i.e.,
598 target representations) here.
600 This allows things like "print *(int *)0x01000234" to work
601 without printing a misleading message -- which would
602 otherwise occur when dealing with a target having two byte
603 pointers and four byte addresses. */
605 int addr_bit = gdbarch_addr_bit (type2->arch ());
606 gdb_mpz longest = value_as_mpz (arg2);
608 gdb_mpz addr_val = gdb_mpz (1) << addr_bit;
609 if (longest >= addr_val || longest <= -addr_val)
610 warning (_("value truncated"));
612 return value_from_mpz (to_type, longest);
614 else if (code1 == TYPE_CODE_METHODPTR && code2 == TYPE_CODE_INT
615 && value_as_long (arg2) == 0)
617 struct value *result = value::allocate (to_type);
619 cplus_make_method_ptr (to_type,
620 result->contents_writeable ().data (), 0, 0);
621 return result;
623 else if (code1 == TYPE_CODE_MEMBERPTR && code2 == TYPE_CODE_INT
624 && value_as_long (arg2) == 0)
626 /* The Itanium C++ ABI represents NULL pointers to members as
627 minus one, instead of biasing the normal case. */
628 return value_from_longest (to_type, -1);
630 else if (code1 == TYPE_CODE_ARRAY && type->is_vector ()
631 && code2 == TYPE_CODE_ARRAY && type2->is_vector ()
632 && type->length () != type2->length ())
633 error (_("Cannot convert between vector values of different sizes"));
634 else if (code1 == TYPE_CODE_ARRAY && type->is_vector () && scalar
635 && type->length () != type2->length ())
636 error (_("can only cast scalar to vector of same size"));
637 else if (code1 == TYPE_CODE_VOID)
639 return value::zero (to_type, not_lval);
641 else if (type->length () == type2->length ())
643 if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
644 return value_cast_pointers (to_type, arg2, 0);
646 arg2 = arg2->copy ();
647 arg2->deprecated_set_type (to_type);
648 arg2->set_enclosing_type (to_type);
649 arg2->set_pointed_to_offset (0); /* pai: chk_val */
650 return arg2;
652 else if (arg2->lval () == lval_memory)
653 return value_at_lazy (to_type, arg2->address ());
654 else
656 if (current_language->la_language == language_ada)
657 error (_("Invalid type conversion."));
658 error (_("Invalid cast."));
662 /* The C++ reinterpret_cast operator. */
664 struct value *
665 value_reinterpret_cast (struct type *type, struct value *arg)
667 struct value *result;
668 struct type *real_type = check_typedef (type);
669 struct type *arg_type, *dest_type;
670 int is_ref = 0;
671 enum type_code dest_code, arg_code;
673 /* Do reference, function, and array conversion. */
674 arg = coerce_array (arg);
676 /* Attempt to preserve the type the user asked for. */
677 dest_type = type;
679 /* If we are casting to a reference type, transform
680 reinterpret_cast<T&[&]>(V) to *reinterpret_cast<T*>(&V). */
681 if (TYPE_IS_REFERENCE (real_type))
683 is_ref = 1;
684 arg = value_addr (arg);
685 dest_type = lookup_pointer_type (dest_type->target_type ());
686 real_type = lookup_pointer_type (real_type);
689 arg_type = arg->type ();
691 dest_code = real_type->code ();
692 arg_code = arg_type->code ();
694 /* We can convert pointer types, or any pointer type to int, or int
695 type to pointer. */
696 if ((dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_INT)
697 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_PTR)
698 || (dest_code == TYPE_CODE_METHODPTR && arg_code == TYPE_CODE_INT)
699 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_METHODPTR)
700 || (dest_code == TYPE_CODE_MEMBERPTR && arg_code == TYPE_CODE_INT)
701 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_MEMBERPTR)
702 || (dest_code == arg_code
703 && (dest_code == TYPE_CODE_PTR
704 || dest_code == TYPE_CODE_METHODPTR
705 || dest_code == TYPE_CODE_MEMBERPTR)))
706 result = value_cast (dest_type, arg);
707 else
708 error (_("Invalid reinterpret_cast"));
710 if (is_ref)
711 result = value_cast (type, value_ref (value_ind (result),
712 type->code ()));
714 return result;
717 /* A helper for value_dynamic_cast. This implements the first of two
718 runtime checks: we iterate over all the base classes of the value's
719 class which are equal to the desired class; if only one of these
720 holds the value, then it is the answer. */
722 static int
723 dynamic_cast_check_1 (struct type *desired_type,
724 const gdb_byte *valaddr,
725 LONGEST embedded_offset,
726 CORE_ADDR address,
727 struct value *val,
728 struct type *search_type,
729 CORE_ADDR arg_addr,
730 struct type *arg_type,
731 struct value **result)
733 int i, result_count = 0;
735 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
737 LONGEST offset = baseclass_offset (search_type, i, valaddr,
738 embedded_offset,
739 address, val);
741 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
743 if (address + embedded_offset + offset >= arg_addr
744 && address + embedded_offset + offset < arg_addr + arg_type->length ())
746 ++result_count;
747 if (!*result)
748 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
749 address + embedded_offset + offset);
752 else
753 result_count += dynamic_cast_check_1 (desired_type,
754 valaddr,
755 embedded_offset + offset,
756 address, val,
757 TYPE_BASECLASS (search_type, i),
758 arg_addr,
759 arg_type,
760 result);
763 return result_count;
766 /* A helper for value_dynamic_cast. This implements the second of two
767 runtime checks: we look for a unique public sibling class of the
768 argument's declared class. */
770 static int
771 dynamic_cast_check_2 (struct type *desired_type,
772 const gdb_byte *valaddr,
773 LONGEST embedded_offset,
774 CORE_ADDR address,
775 struct value *val,
776 struct type *search_type,
777 struct value **result)
779 int i, result_count = 0;
781 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
783 LONGEST offset;
785 if (! BASETYPE_VIA_PUBLIC (search_type, i))
786 continue;
788 offset = baseclass_offset (search_type, i, valaddr, embedded_offset,
789 address, val);
790 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
792 ++result_count;
793 if (*result == NULL)
794 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
795 address + embedded_offset + offset);
797 else
798 result_count += dynamic_cast_check_2 (desired_type,
799 valaddr,
800 embedded_offset + offset,
801 address, val,
802 TYPE_BASECLASS (search_type, i),
803 result);
806 return result_count;
809 /* The C++ dynamic_cast operator. */
811 struct value *
812 value_dynamic_cast (struct type *type, struct value *arg)
814 int full, using_enc;
815 LONGEST top;
816 struct type *resolved_type = check_typedef (type);
817 struct type *arg_type = check_typedef (arg->type ());
818 struct type *class_type, *rtti_type;
819 struct value *result, *tem, *original_arg = arg;
820 CORE_ADDR addr;
821 int is_ref = TYPE_IS_REFERENCE (resolved_type);
823 if (resolved_type->code () != TYPE_CODE_PTR
824 && !TYPE_IS_REFERENCE (resolved_type))
825 error (_("Argument to dynamic_cast must be a pointer or reference type"));
826 if (resolved_type->target_type ()->code () != TYPE_CODE_VOID
827 && resolved_type->target_type ()->code () != TYPE_CODE_STRUCT)
828 error (_("Argument to dynamic_cast must be pointer to class or `void *'"));
830 class_type = check_typedef (resolved_type->target_type ());
831 if (resolved_type->code () == TYPE_CODE_PTR)
833 if (arg_type->code () != TYPE_CODE_PTR
834 && ! (arg_type->code () == TYPE_CODE_INT
835 && value_as_long (arg) == 0))
836 error (_("Argument to dynamic_cast does not have pointer type"));
837 if (arg_type->code () == TYPE_CODE_PTR)
839 arg_type = check_typedef (arg_type->target_type ());
840 if (arg_type->code () != TYPE_CODE_STRUCT)
841 error (_("Argument to dynamic_cast does "
842 "not have pointer to class type"));
845 /* Handle NULL pointers. */
846 if (value_as_long (arg) == 0)
847 return value::zero (type, not_lval);
849 arg = value_ind (arg);
851 else
853 if (arg_type->code () != TYPE_CODE_STRUCT)
854 error (_("Argument to dynamic_cast does not have class type"));
857 /* If the classes are the same, just return the argument. */
858 if (class_types_same_p (class_type, arg_type))
859 return value_cast (type, original_arg);
861 /* If the target type is a unique base class of the argument's
862 declared type, just cast it. */
863 if (is_ancestor (class_type, arg_type))
865 if (is_unique_ancestor (class_type, arg))
866 return value_cast (type, original_arg);
867 error (_("Ambiguous dynamic_cast"));
870 rtti_type = value_rtti_type (arg, &full, &top, &using_enc);
871 if (! rtti_type)
872 error (_("Couldn't determine value's most derived type for dynamic_cast"));
874 /* Compute the most derived object's address. */
875 addr = arg->address ();
876 if (full)
878 /* Done. */
880 else if (using_enc)
881 addr += top;
882 else
883 addr += top + arg->embedded_offset ();
885 /* dynamic_cast<void *> means to return a pointer to the
886 most-derived object. */
887 if (resolved_type->code () == TYPE_CODE_PTR
888 && resolved_type->target_type ()->code () == TYPE_CODE_VOID)
889 return value_at_lazy (type, addr);
891 tem = value_at (resolved_type->target_type (), addr);
892 type = (is_ref
893 ? lookup_reference_type (tem->type (), resolved_type->code ())
894 : lookup_pointer_type (tem->type ()));
896 /* The first dynamic check specified in 5.2.7. */
897 if (is_public_ancestor (arg_type, resolved_type->target_type ()))
899 if (class_types_same_p (rtti_type, resolved_type->target_type ()))
900 return (is_ref
901 ? value_ref (tem, resolved_type->code ())
902 : value_addr (tem));
903 result = NULL;
904 if (dynamic_cast_check_1 (resolved_type->target_type (),
905 tem->contents_for_printing ().data (),
906 tem->embedded_offset (),
907 tem->address (), tem,
908 rtti_type, addr,
909 arg_type,
910 &result) == 1)
911 return value_cast (type,
912 is_ref
913 ? value_ref (result, resolved_type->code ())
914 : value_addr (result));
917 /* The second dynamic check specified in 5.2.7. */
918 result = NULL;
919 if (is_public_ancestor (arg_type, rtti_type)
920 && dynamic_cast_check_2 (resolved_type->target_type (),
921 tem->contents_for_printing ().data (),
922 tem->embedded_offset (),
923 tem->address (), tem,
924 rtti_type, &result) == 1)
925 return value_cast (type,
926 is_ref
927 ? value_ref (result, resolved_type->code ())
928 : value_addr (result));
930 if (resolved_type->code () == TYPE_CODE_PTR)
931 return value::zero (type, not_lval);
933 error (_("dynamic_cast failed"));
936 /* Create a not_lval value of numeric type TYPE that is one, and return it. */
938 struct value *
939 value_one (struct type *type)
941 struct type *type1 = check_typedef (type);
942 struct value *val;
944 if (is_integral_type (type1) || is_floating_type (type1))
946 val = value_from_longest (type, (LONGEST) 1);
948 else if (type1->code () == TYPE_CODE_ARRAY && type1->is_vector ())
950 struct type *eltype = check_typedef (type1->target_type ());
951 int i;
952 LONGEST low_bound, high_bound;
954 if (!get_array_bounds (type1, &low_bound, &high_bound))
955 error (_("Could not determine the vector bounds"));
957 val = value::allocate (type);
958 gdb::array_view<gdb_byte> val_contents = val->contents_writeable ();
959 int elt_len = eltype->length ();
961 for (i = 0; i < high_bound - low_bound + 1; i++)
963 value *tmp = value_one (eltype);
964 copy (tmp->contents_all (),
965 val_contents.slice (i * elt_len, elt_len));
968 else
970 error (_("Not a numeric type."));
973 /* value_one result is never used for assignments to. */
974 gdb_assert (val->lval () == not_lval);
976 return val;
979 /* Helper function for value_at, value_at_lazy, and value_at_lazy_stack.
980 The type of the created value may differ from the passed type TYPE.
981 Make sure to retrieve the returned values's new type after this call
982 e.g. in case the type is a variable length array. */
984 static struct value *
985 get_value_at (struct type *type, CORE_ADDR addr, frame_info_ptr frame,
986 int lazy)
988 struct value *val;
990 if (check_typedef (type)->code () == TYPE_CODE_VOID)
991 error (_("Attempt to dereference a generic pointer."));
993 val = value_from_contents_and_address (type, NULL, addr, frame);
995 if (!lazy)
996 val->fetch_lazy ();
998 return val;
1001 /* Return a value with type TYPE located at ADDR.
1003 Call value_at only if the data needs to be fetched immediately;
1004 if we can be 'lazy' and defer the fetch, perhaps indefinitely, call
1005 value_at_lazy instead. value_at_lazy simply records the address of
1006 the data and sets the lazy-evaluation-required flag. The lazy flag
1007 is tested in the value_contents macro, which is used if and when
1008 the contents are actually required. The type of the created value
1009 may differ from the passed type TYPE. Make sure to retrieve the
1010 returned values's new type after this call e.g. in case the type
1011 is a variable length array.
1013 Note: value_at does *NOT* handle embedded offsets; perform such
1014 adjustments before or after calling it. */
1016 struct value *
1017 value_at (struct type *type, CORE_ADDR addr)
1019 return get_value_at (type, addr, nullptr, 0);
1022 /* See value.h. */
1024 struct value *
1025 value_at_non_lval (struct type *type, CORE_ADDR addr)
1027 struct value *result = value_at (type, addr);
1028 result->set_lval (not_lval);
1029 return result;
1032 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).
1033 The type of the created value may differ from the passed type TYPE.
1034 Make sure to retrieve the returned values's new type after this call
1035 e.g. in case the type is a variable length array. */
1037 struct value *
1038 value_at_lazy (struct type *type, CORE_ADDR addr, frame_info_ptr frame)
1040 return get_value_at (type, addr, frame, 1);
1043 void
1044 read_value_memory (struct value *val, LONGEST bit_offset,
1045 bool stack, CORE_ADDR memaddr,
1046 gdb_byte *buffer, size_t length)
1048 ULONGEST xfered_total = 0;
1049 struct gdbarch *arch = val->arch ();
1050 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1051 enum target_object object;
1053 object = stack ? TARGET_OBJECT_STACK_MEMORY : TARGET_OBJECT_MEMORY;
1055 while (xfered_total < length)
1057 enum target_xfer_status status;
1058 ULONGEST xfered_partial;
1060 status = target_xfer_partial (current_inferior ()->top_target (),
1061 object, NULL,
1062 buffer + xfered_total * unit_size, NULL,
1063 memaddr + xfered_total,
1064 length - xfered_total,
1065 &xfered_partial);
1067 if (status == TARGET_XFER_OK)
1068 /* nothing */;
1069 else if (status == TARGET_XFER_UNAVAILABLE)
1070 val->mark_bits_unavailable ((xfered_total * HOST_CHAR_BIT
1071 + bit_offset),
1072 xfered_partial * HOST_CHAR_BIT);
1073 else if (status == TARGET_XFER_EOF)
1074 memory_error (TARGET_XFER_E_IO, memaddr + xfered_total);
1075 else
1076 memory_error (status, memaddr + xfered_total);
1078 xfered_total += xfered_partial;
1079 QUIT;
1083 /* Store the contents of FROMVAL into the location of TOVAL.
1084 Return a new value with the location of TOVAL and contents of FROMVAL. */
1086 struct value *
1087 value_assign (struct value *toval, struct value *fromval)
1089 struct type *type;
1090 struct value *val;
1091 struct frame_id old_frame;
1093 if (!toval->deprecated_modifiable ())
1094 error (_("Left operand of assignment is not a modifiable lvalue."));
1096 toval = coerce_ref (toval);
1098 type = toval->type ();
1099 if (toval->lval () != lval_internalvar)
1100 fromval = value_cast (type, fromval);
1101 else
1103 /* Coerce arrays and functions to pointers, except for arrays
1104 which only live in GDB's storage. */
1105 if (!value_must_coerce_to_target (fromval))
1106 fromval = coerce_array (fromval);
1109 type = check_typedef (type);
1111 /* Since modifying a register can trash the frame chain, and
1112 modifying memory can trash the frame cache, we save the old frame
1113 and then restore the new frame afterwards. */
1114 old_frame = get_frame_id (deprecated_safe_get_selected_frame ());
1116 switch (toval->lval ())
1118 case lval_internalvar:
1119 set_internalvar (VALUE_INTERNALVAR (toval), fromval);
1120 return value_of_internalvar (type->arch (),
1121 VALUE_INTERNALVAR (toval));
1123 case lval_internalvar_component:
1125 LONGEST offset = toval->offset ();
1127 /* Are we dealing with a bitfield?
1129 It is important to mention that `toval->parent ()' is
1130 non-NULL iff `toval->bitsize ()' is non-zero. */
1131 if (toval->bitsize ())
1133 /* VALUE_INTERNALVAR below refers to the parent value, while
1134 the offset is relative to this parent value. */
1135 gdb_assert (toval->parent ()->parent () == NULL);
1136 offset += toval->parent ()->offset ();
1139 set_internalvar_component (VALUE_INTERNALVAR (toval),
1140 offset,
1141 toval->bitpos (),
1142 toval->bitsize (),
1143 fromval);
1145 break;
1147 case lval_memory:
1149 const gdb_byte *dest_buffer;
1150 CORE_ADDR changed_addr;
1151 int changed_len;
1152 gdb_byte buffer[sizeof (LONGEST)];
1154 if (toval->bitsize ())
1156 struct value *parent = toval->parent ();
1158 changed_addr = parent->address () + toval->offset ();
1159 changed_len = (toval->bitpos ()
1160 + toval->bitsize ()
1161 + HOST_CHAR_BIT - 1)
1162 / HOST_CHAR_BIT;
1164 /* If we can read-modify-write exactly the size of the
1165 containing type (e.g. short or int) then do so. This
1166 is safer for volatile bitfields mapped to hardware
1167 registers. */
1168 if (changed_len < type->length ()
1169 && type->length () <= (int) sizeof (LONGEST)
1170 && ((LONGEST) changed_addr % type->length ()) == 0)
1171 changed_len = type->length ();
1173 if (changed_len > (int) sizeof (LONGEST))
1174 error (_("Can't handle bitfields which "
1175 "don't fit in a %d bit word."),
1176 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1178 read_memory (changed_addr, buffer, changed_len);
1179 modify_field (type, buffer, value_as_long (fromval),
1180 toval->bitpos (), toval->bitsize ());
1181 dest_buffer = buffer;
1183 else
1185 changed_addr = toval->address ();
1186 changed_len = type_length_units (type);
1187 dest_buffer = fromval->contents ().data ();
1190 write_memory_with_notification (changed_addr, dest_buffer, changed_len);
1192 break;
1194 case lval_register:
1196 frame_info_ptr next_frame = frame_find_by_id (toval->next_frame_id ());
1197 int value_reg = toval->regnum ();
1199 if (next_frame == nullptr)
1200 error (_("Value being assigned to is no longer active."));
1202 gdbarch *gdbarch = frame_unwind_arch (next_frame);
1204 if (toval->bitsize ())
1206 struct value *parent = toval->parent ();
1207 LONGEST offset = parent->offset () + toval->offset ();
1208 size_t changed_len;
1209 gdb_byte buffer[sizeof (LONGEST)];
1210 int optim, unavail;
1212 changed_len = (toval->bitpos ()
1213 + toval->bitsize ()
1214 + HOST_CHAR_BIT - 1)
1215 / HOST_CHAR_BIT;
1217 if (changed_len > sizeof (LONGEST))
1218 error (_("Can't handle bitfields which "
1219 "don't fit in a %d bit word."),
1220 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1222 if (!get_frame_register_bytes (next_frame, value_reg, offset,
1223 { buffer, changed_len }, &optim,
1224 &unavail))
1226 if (optim)
1227 throw_error (OPTIMIZED_OUT_ERROR,
1228 _("value has been optimized out"));
1229 if (unavail)
1230 throw_error (NOT_AVAILABLE_ERROR,
1231 _("value is not available"));
1234 modify_field (type, buffer, value_as_long (fromval),
1235 toval->bitpos (), toval->bitsize ());
1237 put_frame_register_bytes (next_frame, value_reg, offset,
1238 { buffer, changed_len });
1240 else
1242 if (gdbarch_convert_register_p (gdbarch, toval->regnum (), type))
1244 /* If TOVAL is a special machine register requiring
1245 conversion of program values to a special raw
1246 format. */
1247 gdbarch_value_to_register (gdbarch,
1248 get_prev_frame_always (next_frame),
1249 toval->regnum (), type,
1250 fromval->contents ().data ());
1252 else
1253 put_frame_register_bytes (next_frame, value_reg,
1254 toval->offset (),
1255 fromval->contents ());
1258 gdb::observers::register_changed.notify
1259 (get_prev_frame_always (next_frame), value_reg);
1260 break;
1263 case lval_computed:
1265 const struct lval_funcs *funcs = toval->computed_funcs ();
1267 if (funcs->write != NULL)
1269 funcs->write (toval, fromval);
1270 break;
1273 [[fallthrough]];
1275 default:
1276 error (_("Left operand of assignment is not an lvalue."));
1279 /* Assigning to the stack pointer, frame pointer, and other
1280 (architecture and calling convention specific) registers may
1281 cause the frame cache and regcache to be out of date. Assigning to memory
1282 also can. We just do this on all assignments to registers or
1283 memory, for simplicity's sake; I doubt the slowdown matters. */
1284 switch (toval->lval ())
1286 case lval_memory:
1287 case lval_register:
1288 case lval_computed:
1290 gdb::observers::target_changed.notify
1291 (current_inferior ()->top_target ());
1293 /* Having destroyed the frame cache, restore the selected
1294 frame. */
1296 /* FIXME: cagney/2002-11-02: There has to be a better way of
1297 doing this. Instead of constantly saving/restoring the
1298 frame. Why not create a get_selected_frame() function that,
1299 having saved the selected frame's ID can automatically
1300 re-find the previously selected frame automatically. */
1303 frame_info_ptr fi = frame_find_by_id (old_frame);
1305 if (fi != NULL)
1306 select_frame (fi);
1309 break;
1310 default:
1311 break;
1314 /* If the field does not entirely fill a LONGEST, then zero the sign
1315 bits. If the field is signed, and is negative, then sign
1316 extend. */
1317 if ((toval->bitsize () > 0)
1318 && (toval->bitsize () < 8 * (int) sizeof (LONGEST)))
1320 LONGEST fieldval = value_as_long (fromval);
1321 LONGEST valmask = (((ULONGEST) 1) << toval->bitsize ()) - 1;
1323 fieldval &= valmask;
1324 if (!type->is_unsigned ()
1325 && (fieldval & (valmask ^ (valmask >> 1))))
1326 fieldval |= ~valmask;
1328 fromval = value_from_longest (type, fieldval);
1331 /* The return value is a copy of TOVAL so it shares its location
1332 information, but its contents are updated from FROMVAL. This
1333 implies the returned value is not lazy, even if TOVAL was. */
1334 val = toval->copy ();
1335 val->set_lazy (false);
1336 copy (fromval->contents (), val->contents_raw ());
1338 /* We copy over the enclosing type and pointed-to offset from FROMVAL
1339 in the case of pointer types. For object types, the enclosing type
1340 and embedded offset must *not* be copied: the target object referred
1341 to by TOVAL retains its original dynamic type after assignment. */
1342 if (type->code () == TYPE_CODE_PTR)
1344 val->set_enclosing_type (fromval->enclosing_type ());
1345 val->set_pointed_to_offset (fromval->pointed_to_offset ());
1348 return val;
1351 /* Extend a value ARG1 to COUNT repetitions of its type. */
1353 struct value *
1354 value_repeat (struct value *arg1, int count)
1356 struct value *val;
1358 if (arg1->lval () != lval_memory)
1359 error (_("Only values in memory can be extended with '@'."));
1360 if (count < 1)
1361 error (_("Invalid number %d of repetitions."), count);
1363 val = allocate_repeat_value (arg1->enclosing_type (), count);
1365 val->set_lval (lval_memory);
1366 val->set_address (arg1->address ());
1368 read_value_memory (val, 0, val->stack (), val->address (),
1369 val->contents_all_raw ().data (),
1370 type_length_units (val->enclosing_type ()));
1372 return val;
1375 struct value *
1376 value_of_variable (struct symbol *var, const struct block *b)
1378 frame_info_ptr frame = NULL;
1380 if (symbol_read_needs_frame (var))
1381 frame = get_selected_frame (_("No frame selected."));
1383 return read_var_value (var, b, frame);
1386 struct value *
1387 address_of_variable (struct symbol *var, const struct block *b)
1389 struct type *type = var->type ();
1390 struct value *val;
1392 /* Evaluate it first; if the result is a memory address, we're fine.
1393 Lazy evaluation pays off here. */
1395 val = value_of_variable (var, b);
1396 type = val->type ();
1398 if ((val->lval () == lval_memory && val->lazy ())
1399 || type->code () == TYPE_CODE_FUNC)
1401 CORE_ADDR addr = val->address ();
1403 return value_from_pointer (lookup_pointer_type (type), addr);
1406 /* Not a memory address; check what the problem was. */
1407 switch (val->lval ())
1409 case lval_register:
1411 const char *regname;
1413 frame_info_ptr frame = frame_find_by_id (val->next_frame_id ());
1414 gdb_assert (frame != nullptr);
1416 regname
1417 = gdbarch_register_name (get_frame_arch (frame), val->regnum ());
1418 gdb_assert (regname != nullptr && *regname != '\0');
1420 error (_("Address requested for identifier "
1421 "\"%s\" which is in register $%s"),
1422 var->print_name (), regname);
1423 break;
1426 default:
1427 error (_("Can't take address of \"%s\" which isn't an lvalue."),
1428 var->print_name ());
1429 break;
1432 return val;
1435 /* See value.h. */
1437 bool
1438 value_must_coerce_to_target (struct value *val)
1440 struct type *valtype;
1442 /* The only lval kinds which do not live in target memory. */
1443 if (val->lval () != not_lval
1444 && val->lval () != lval_internalvar
1445 && val->lval () != lval_xcallable)
1446 return false;
1448 valtype = check_typedef (val->type ());
1450 switch (valtype->code ())
1452 case TYPE_CODE_ARRAY:
1453 return valtype->is_vector () ? 0 : 1;
1454 case TYPE_CODE_STRING:
1455 return true;
1456 default:
1457 return false;
1461 /* Make sure that VAL lives in target memory if it's supposed to. For
1462 instance, strings are constructed as character arrays in GDB's
1463 storage, and this function copies them to the target. */
1465 struct value *
1466 value_coerce_to_target (struct value *val)
1468 LONGEST length;
1469 CORE_ADDR addr;
1471 if (!value_must_coerce_to_target (val))
1472 return val;
1474 length = check_typedef (val->type ())->length ();
1475 addr = allocate_space_in_inferior (length);
1476 write_memory (addr, val->contents ().data (), length);
1477 return value_at_lazy (val->type (), addr);
1480 /* Given a value which is an array, return a value which is a pointer
1481 to its first element, regardless of whether or not the array has a
1482 nonzero lower bound.
1484 FIXME: A previous comment here indicated that this routine should
1485 be substracting the array's lower bound. It's not clear to me that
1486 this is correct. Given an array subscripting operation, it would
1487 certainly work to do the adjustment here, essentially computing:
1489 (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
1491 However I believe a more appropriate and logical place to account
1492 for the lower bound is to do so in value_subscript, essentially
1493 computing:
1495 (&array[0] + ((index - lowerbound) * sizeof array[0]))
1497 As further evidence consider what would happen with operations
1498 other than array subscripting, where the caller would get back a
1499 value that had an address somewhere before the actual first element
1500 of the array, and the information about the lower bound would be
1501 lost because of the coercion to pointer type. */
1503 struct value *
1504 value_coerce_array (struct value *arg1)
1506 struct type *type = check_typedef (arg1->type ());
1508 /* If the user tries to do something requiring a pointer with an
1509 array that has not yet been pushed to the target, then this would
1510 be a good time to do so. */
1511 arg1 = value_coerce_to_target (arg1);
1513 if (arg1->lval () != lval_memory)
1514 error (_("Attempt to take address of value not located in memory."));
1516 return value_from_pointer (lookup_pointer_type (type->target_type ()),
1517 arg1->address ());
1520 /* Given a value which is a function, return a value which is a pointer
1521 to it. */
1523 struct value *
1524 value_coerce_function (struct value *arg1)
1526 struct value *retval;
1528 if (arg1->lval () != lval_memory)
1529 error (_("Attempt to take address of value not located in memory."));
1531 retval = value_from_pointer (lookup_pointer_type (arg1->type ()),
1532 arg1->address ());
1533 return retval;
1536 /* Return a pointer value for the object for which ARG1 is the
1537 contents. */
1539 struct value *
1540 value_addr (struct value *arg1)
1542 struct value *arg2;
1543 struct type *type = check_typedef (arg1->type ());
1545 if (TYPE_IS_REFERENCE (type))
1547 if (arg1->bits_synthetic_pointer (arg1->embedded_offset (),
1548 TARGET_CHAR_BIT * type->length ()))
1549 arg1 = coerce_ref (arg1);
1550 else
1552 /* Copy the value, but change the type from (T&) to (T*). We
1553 keep the same location information, which is efficient, and
1554 allows &(&X) to get the location containing the reference.
1555 Do the same to its enclosing type for consistency. */
1556 struct type *type_ptr
1557 = lookup_pointer_type (type->target_type ());
1558 struct type *enclosing_type
1559 = check_typedef (arg1->enclosing_type ());
1560 struct type *enclosing_type_ptr
1561 = lookup_pointer_type (enclosing_type->target_type ());
1563 arg2 = arg1->copy ();
1564 arg2->deprecated_set_type (type_ptr);
1565 arg2->set_enclosing_type (enclosing_type_ptr);
1567 return arg2;
1570 if (type->code () == TYPE_CODE_FUNC)
1571 return value_coerce_function (arg1);
1573 /* If this is an array that has not yet been pushed to the target,
1574 then this would be a good time to force it to memory. */
1575 arg1 = value_coerce_to_target (arg1);
1577 if (arg1->lval () != lval_memory)
1578 error (_("Attempt to take address of value not located in memory."));
1580 /* Get target memory address. */
1581 arg2 = value_from_pointer (lookup_pointer_type (arg1->type ()),
1582 (arg1->address ()
1583 + arg1->embedded_offset ()));
1585 /* This may be a pointer to a base subobject; so remember the
1586 full derived object's type ... */
1587 arg2->set_enclosing_type (lookup_pointer_type (arg1->enclosing_type ()));
1588 /* ... and also the relative position of the subobject in the full
1589 object. */
1590 arg2->set_pointed_to_offset (arg1->embedded_offset ());
1591 return arg2;
1594 /* Return a reference value for the object for which ARG1 is the
1595 contents. */
1597 struct value *
1598 value_ref (struct value *arg1, enum type_code refcode)
1600 struct value *arg2;
1601 struct type *type = check_typedef (arg1->type ());
1603 gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1605 if ((type->code () == TYPE_CODE_REF
1606 || type->code () == TYPE_CODE_RVALUE_REF)
1607 && type->code () == refcode)
1608 return arg1;
1610 arg2 = value_addr (arg1);
1611 arg2->deprecated_set_type (lookup_reference_type (type, refcode));
1612 return arg2;
1615 /* Given a value of a pointer type, apply the C unary * operator to
1616 it. */
1618 struct value *
1619 value_ind (struct value *arg1)
1621 struct type *base_type;
1622 struct value *arg2;
1624 arg1 = coerce_array (arg1);
1626 base_type = check_typedef (arg1->type ());
1628 if (arg1->lval () == lval_computed)
1630 const struct lval_funcs *funcs = arg1->computed_funcs ();
1632 if (funcs->indirect)
1634 struct value *result = funcs->indirect (arg1);
1636 if (result)
1637 return result;
1641 if (base_type->code () == TYPE_CODE_PTR)
1643 struct type *enc_type;
1645 /* We may be pointing to something embedded in a larger object.
1646 Get the real type of the enclosing object. */
1647 enc_type = check_typedef (arg1->enclosing_type ());
1648 enc_type = enc_type->target_type ();
1650 CORE_ADDR base_addr;
1651 if (check_typedef (enc_type)->code () == TYPE_CODE_FUNC
1652 || check_typedef (enc_type)->code () == TYPE_CODE_METHOD)
1654 /* For functions, go through find_function_addr, which knows
1655 how to handle function descriptors. */
1656 base_addr = find_function_addr (arg1, NULL);
1658 else
1660 /* Retrieve the enclosing object pointed to. */
1661 base_addr = (value_as_address (arg1)
1662 - arg1->pointed_to_offset ());
1664 arg2 = value_at_lazy (enc_type, base_addr);
1665 enc_type = arg2->type ();
1666 return readjust_indirect_value_type (arg2, enc_type, base_type,
1667 arg1, base_addr);
1670 error (_("Attempt to take contents of a non-pointer value."));
1673 /* Create a value for an array by allocating space in GDB, copying the
1674 data into that space, and then setting up an array value.
1676 The array bounds are set from LOWBOUND and the size of ELEMVEC, and
1677 the array is populated from the values passed in ELEMVEC.
1679 The element type of the array is inherited from the type of the
1680 first element, and all elements must have the same size (though we
1681 don't currently enforce any restriction on their types). */
1683 struct value *
1684 value_array (int lowbound, gdb::array_view<struct value *> elemvec)
1686 int idx;
1687 ULONGEST typelength;
1688 struct value *val;
1689 struct type *arraytype;
1691 /* Validate that the bounds are reasonable and that each of the
1692 elements have the same size. */
1694 typelength = type_length_units (elemvec[0]->enclosing_type ());
1695 for (struct value *other : elemvec.slice (1))
1697 if (type_length_units (other->enclosing_type ()) != typelength)
1699 error (_("array elements must all be the same size"));
1703 arraytype = lookup_array_range_type (elemvec[0]->enclosing_type (),
1704 lowbound,
1705 lowbound + elemvec.size () - 1);
1707 if (!current_language->c_style_arrays_p ())
1709 val = value::allocate (arraytype);
1710 for (idx = 0; idx < elemvec.size (); idx++)
1711 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1712 return val;
1715 /* Allocate space to store the array, and then initialize it by
1716 copying in each element. */
1718 val = value::allocate (arraytype);
1719 for (idx = 0; idx < elemvec.size (); idx++)
1720 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1721 return val;
1724 /* See value.h. */
1726 struct value *
1727 value_cstring (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1729 struct value *val;
1730 int lowbound = current_language->string_lower_bound ();
1731 ssize_t highbound = count + 1;
1732 struct type *stringtype
1733 = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1735 val = value::allocate (stringtype);
1736 ssize_t len = count * char_type->length ();
1737 memcpy (val->contents_raw ().data (), ptr, len);
1738 /* Write the terminating null-character. */
1739 memset (val->contents_raw ().data () + len, 0, char_type->length ());
1740 return val;
1743 /* See value.h. */
1745 struct value *
1746 value_string (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1748 struct value *val;
1749 int lowbound = current_language->string_lower_bound ();
1750 ssize_t highbound = count;
1751 struct type *stringtype
1752 = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1754 val = value::allocate (stringtype);
1755 ssize_t len = count * char_type->length ();
1756 memcpy (val->contents_raw ().data (), ptr, len);
1757 return val;
1761 /* See if we can pass arguments in T2 to a function which takes arguments
1762 of types T1. T1 is a list of NARGS arguments, and T2 is an array_view
1763 of the values we're trying to pass. If some arguments need coercion of
1764 some sort, then the coerced values are written into T2. Return value is
1765 0 if the arguments could be matched, or the position at which they
1766 differ if not.
1768 STATICP is nonzero if the T1 argument list came from a static
1769 member function. T2 must still include the ``this'' pointer, but
1770 it will be skipped.
1772 For non-static member functions, we ignore the first argument,
1773 which is the type of the instance variable. This is because we
1774 want to handle calls with objects from derived classes. This is
1775 not entirely correct: we should actually check to make sure that a
1776 requested operation is type secure, shouldn't we? FIXME. */
1778 static int
1779 typecmp (bool staticp, bool varargs, int nargs,
1780 struct field t1[], gdb::array_view<value *> t2)
1782 int i;
1784 /* Skip ``this'' argument if applicable. T2 will always include
1785 THIS. */
1786 if (staticp)
1787 t2 = t2.slice (1);
1789 for (i = 0;
1790 (i < nargs) && t1[i].type ()->code () != TYPE_CODE_VOID;
1791 i++)
1793 struct type *tt1, *tt2;
1795 if (i == t2.size ())
1796 return i + 1;
1798 tt1 = check_typedef (t1[i].type ());
1799 tt2 = check_typedef (t2[i]->type ());
1801 if (TYPE_IS_REFERENCE (tt1)
1802 /* We should be doing hairy argument matching, as below. */
1803 && (check_typedef (tt1->target_type ())->code ()
1804 == tt2->code ()))
1806 if (tt2->code () == TYPE_CODE_ARRAY)
1807 t2[i] = value_coerce_array (t2[i]);
1808 else
1809 t2[i] = value_ref (t2[i], tt1->code ());
1810 continue;
1813 /* djb - 20000715 - Until the new type structure is in the
1814 place, and we can attempt things like implicit conversions,
1815 we need to do this so you can take something like a map<const
1816 char *>, and properly access map["hello"], because the
1817 argument to [] will be a reference to a pointer to a char,
1818 and the argument will be a pointer to a char. */
1819 while (TYPE_IS_REFERENCE (tt1) || tt1->code () == TYPE_CODE_PTR)
1821 tt1 = check_typedef ( tt1->target_type () );
1823 while (tt2->code () == TYPE_CODE_ARRAY
1824 || tt2->code () == TYPE_CODE_PTR
1825 || TYPE_IS_REFERENCE (tt2))
1827 tt2 = check_typedef (tt2->target_type ());
1829 if (tt1->code () == tt2->code ())
1830 continue;
1831 /* Array to pointer is a `trivial conversion' according to the
1832 ARM. */
1834 /* We should be doing much hairier argument matching (see
1835 section 13.2 of the ARM), but as a quick kludge, just check
1836 for the same type code. */
1837 if (t1[i].type ()->code () != t2[i]->type ()->code ())
1838 return i + 1;
1840 if (varargs || i == t2.size ())
1841 return 0;
1842 return i + 1;
1845 /* Helper class for search_struct_field that keeps track of found
1846 results and possibly throws an exception if the search yields
1847 ambiguous results. See search_struct_field for description of
1848 LOOKING_FOR_BASECLASS. */
1850 struct struct_field_searcher
1852 /* A found field. */
1853 struct found_field
1855 /* Path to the structure where the field was found. */
1856 std::vector<struct type *> path;
1858 /* The field found. */
1859 struct value *field_value;
1862 /* See corresponding fields for description of parameters. */
1863 struct_field_searcher (const char *name,
1864 struct type *outermost_type,
1865 bool looking_for_baseclass)
1866 : m_name (name),
1867 m_looking_for_baseclass (looking_for_baseclass),
1868 m_outermost_type (outermost_type)
1872 /* The search entry point. If LOOKING_FOR_BASECLASS is true and the
1873 base class search yields ambiguous results, this throws an
1874 exception. If LOOKING_FOR_BASECLASS is false, the found fields
1875 are accumulated and the caller (search_struct_field) takes care
1876 of throwing an error if the field search yields ambiguous
1877 results. The latter is done that way so that the error message
1878 can include a list of all the found candidates. */
1879 void search (struct value *arg, LONGEST offset, struct type *type);
1881 const std::vector<found_field> &fields ()
1883 return m_fields;
1886 struct value *baseclass ()
1888 return m_baseclass;
1891 private:
1892 /* Update results to include V, a found field/baseclass. */
1893 void update_result (struct value *v, LONGEST boffset);
1895 /* The name of the field/baseclass we're searching for. */
1896 const char *m_name;
1898 /* Whether we're looking for a baseclass, or a field. */
1899 const bool m_looking_for_baseclass;
1901 /* The offset of the baseclass containing the field/baseclass we
1902 last recorded. */
1903 LONGEST m_last_boffset = 0;
1905 /* If looking for a baseclass, then the result is stored here. */
1906 struct value *m_baseclass = nullptr;
1908 /* When looking for fields, the found candidates are stored
1909 here. */
1910 std::vector<found_field> m_fields;
1912 /* The type of the initial type passed to search_struct_field; this
1913 is used for error reporting when the lookup is ambiguous. */
1914 struct type *m_outermost_type;
1916 /* The full path to the struct being inspected. E.g. for field 'x'
1917 defined in class B inherited by class A, we have A and B pushed
1918 on the path. */
1919 std::vector <struct type *> m_struct_path;
1922 void
1923 struct_field_searcher::update_result (struct value *v, LONGEST boffset)
1925 if (v != NULL)
1927 if (m_looking_for_baseclass)
1929 if (m_baseclass != nullptr
1930 /* The result is not ambiguous if all the classes that are
1931 found occupy the same space. */
1932 && m_last_boffset != boffset)
1933 error (_("base class '%s' is ambiguous in type '%s'"),
1934 m_name, TYPE_SAFE_NAME (m_outermost_type));
1936 m_baseclass = v;
1937 m_last_boffset = boffset;
1939 else
1941 /* The field is not ambiguous if it occupies the same
1942 space. */
1943 if (m_fields.empty () || m_last_boffset != boffset)
1944 m_fields.push_back ({m_struct_path, v});
1945 else
1947 /*Fields can occupy the same space and have the same name (be
1948 ambiguous). This can happen when fields in two different base
1949 classes are marked [[no_unique_address]] and have the same name.
1950 The C++ standard says that such fields can only occupy the same
1951 space if they are of different type, but we don't rely on that in
1952 the following code. */
1953 bool ambiguous = false, insert = true;
1954 for (const found_field &field: m_fields)
1956 if(field.path.back () != m_struct_path.back ())
1958 /* Same boffset points to members of different classes.
1959 We have found an ambiguity and should record it. */
1960 ambiguous = true;
1962 else
1964 /* We don't need to insert this value again, because a
1965 non-ambiguous path already leads to it. */
1966 insert = false;
1967 break;
1970 if (ambiguous && insert)
1971 m_fields.push_back ({m_struct_path, v});
1977 /* A helper for search_struct_field. This does all the work; most
1978 arguments are as passed to search_struct_field. */
1980 void
1981 struct_field_searcher::search (struct value *arg1, LONGEST offset,
1982 struct type *type)
1984 int i;
1985 int nbases;
1987 m_struct_path.push_back (type);
1988 SCOPE_EXIT { m_struct_path.pop_back (); };
1990 type = check_typedef (type);
1991 nbases = TYPE_N_BASECLASSES (type);
1993 if (!m_looking_for_baseclass)
1994 for (i = type->num_fields () - 1; i >= nbases; i--)
1996 const char *t_field_name = type->field (i).name ();
1998 if (t_field_name && (strcmp_iw (t_field_name, m_name) == 0))
2000 struct value *v;
2002 if (type->field (i).is_static ())
2003 v = value_static_field (type, i);
2004 else
2005 v = arg1->primitive_field (offset, i, type);
2007 update_result (v, offset);
2008 return;
2011 if (t_field_name
2012 && t_field_name[0] == '\0')
2014 struct type *field_type = type->field (i).type ();
2016 if (field_type->code () == TYPE_CODE_UNION
2017 || field_type->code () == TYPE_CODE_STRUCT)
2019 /* Look for a match through the fields of an anonymous
2020 union, or anonymous struct. C++ provides anonymous
2021 unions.
2023 In the GNU Chill (now deleted from GDB)
2024 implementation of variant record types, each
2025 <alternative field> has an (anonymous) union type,
2026 each member of the union represents a <variant
2027 alternative>. Each <variant alternative> is
2028 represented as a struct, with a member for each
2029 <variant field>. */
2031 LONGEST new_offset = offset;
2033 /* This is pretty gross. In G++, the offset in an
2034 anonymous union is relative to the beginning of the
2035 enclosing struct. In the GNU Chill (now deleted
2036 from GDB) implementation of variant records, the
2037 bitpos is zero in an anonymous union field, so we
2038 have to add the offset of the union here. */
2039 if (field_type->code () == TYPE_CODE_STRUCT
2040 || (field_type->num_fields () > 0
2041 && field_type->field (0).loc_bitpos () == 0))
2042 new_offset += type->field (i).loc_bitpos () / 8;
2044 search (arg1, new_offset, field_type);
2049 for (i = 0; i < nbases; i++)
2051 struct value *v = NULL;
2052 struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
2053 /* If we are looking for baseclasses, this is what we get when
2054 we hit them. But it could happen that the base part's member
2055 name is not yet filled in. */
2056 int found_baseclass = (m_looking_for_baseclass
2057 && TYPE_BASECLASS_NAME (type, i) != NULL
2058 && (strcmp_iw (m_name, basetype->name ()) == 0));
2059 LONGEST boffset = arg1->embedded_offset () + offset;
2061 if (BASETYPE_VIA_VIRTUAL (type, i))
2063 struct value *v2;
2065 boffset = baseclass_offset (type, i,
2066 arg1->contents_for_printing ().data (),
2067 arg1->embedded_offset () + offset,
2068 arg1->address (),
2069 arg1);
2071 /* The virtual base class pointer might have been clobbered
2072 by the user program. Make sure that it still points to a
2073 valid memory location. */
2075 boffset += arg1->embedded_offset () + offset;
2076 if (boffset < 0
2077 || boffset >= arg1->enclosing_type ()->length ())
2079 CORE_ADDR base_addr;
2081 base_addr = arg1->address () + boffset;
2082 v2 = value_at_lazy (basetype, base_addr);
2083 if (target_read_memory (base_addr,
2084 v2->contents_raw ().data (),
2085 v2->type ()->length ()) != 0)
2086 error (_("virtual baseclass botch"));
2088 else
2090 v2 = arg1->copy ();
2091 v2->deprecated_set_type (basetype);
2092 v2->set_embedded_offset (boffset);
2095 if (found_baseclass)
2096 v = v2;
2097 else
2098 search (v2, 0, TYPE_BASECLASS (type, i));
2100 else if (found_baseclass)
2101 v = arg1->primitive_field (offset, i, type);
2102 else
2104 search (arg1, offset + TYPE_BASECLASS_BITPOS (type, i) / 8,
2105 basetype);
2108 update_result (v, boffset);
2112 /* Helper function used by value_struct_elt to recurse through
2113 baseclasses. Look for a field NAME in ARG1. Search in it assuming
2114 it has (class) type TYPE. If found, return value, else return NULL.
2116 If LOOKING_FOR_BASECLASS, then instead of looking for struct
2117 fields, look for a baseclass named NAME. */
2119 static struct value *
2120 search_struct_field (const char *name, struct value *arg1,
2121 struct type *type, int looking_for_baseclass)
2123 struct_field_searcher searcher (name, type, looking_for_baseclass);
2125 searcher.search (arg1, 0, type);
2127 if (!looking_for_baseclass)
2129 const auto &fields = searcher.fields ();
2131 if (fields.empty ())
2132 return nullptr;
2133 else if (fields.size () == 1)
2134 return fields[0].field_value;
2135 else
2137 std::string candidates;
2139 for (auto &&candidate : fields)
2141 gdb_assert (!candidate.path.empty ());
2143 struct type *field_type = candidate.field_value->type ();
2144 struct type *struct_type = candidate.path.back ();
2146 std::string path;
2147 bool first = true;
2148 for (struct type *t : candidate.path)
2150 if (first)
2151 first = false;
2152 else
2153 path += " -> ";
2154 path += t->name ();
2157 candidates += string_printf ("\n '%s %s::%s' (%s)",
2158 TYPE_SAFE_NAME (field_type),
2159 TYPE_SAFE_NAME (struct_type),
2160 name,
2161 path.c_str ());
2164 error (_("Request for member '%s' is ambiguous in type '%s'."
2165 " Candidates are:%s"),
2166 name, TYPE_SAFE_NAME (type),
2167 candidates.c_str ());
2170 else
2171 return searcher.baseclass ();
2174 /* Helper function used by value_struct_elt to recurse through
2175 baseclasses. Look for a field NAME in ARG1. Adjust the address of
2176 ARG1 by OFFSET bytes, and search in it assuming it has (class) type
2177 TYPE.
2179 ARGS is an optional array of argument values used to help finding NAME.
2180 The contents of ARGS can be adjusted if type coercion is required in
2181 order to find a matching NAME.
2183 If found, return value, else if name matched and args not return
2184 (value) -1, else return NULL. */
2186 static struct value *
2187 search_struct_method (const char *name, struct value **arg1p,
2188 std::optional<gdb::array_view<value *>> args,
2189 LONGEST offset, int *static_memfuncp,
2190 struct type *type)
2192 int i;
2193 struct value *v;
2194 int name_matched = 0;
2196 type = check_typedef (type);
2197 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2199 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2201 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2203 int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2204 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2206 name_matched = 1;
2207 check_stub_method_group (type, i);
2208 if (j > 0 && !args.has_value ())
2209 error (_("cannot resolve overloaded method "
2210 "`%s': no arguments supplied"), name);
2211 else if (j == 0 && !args.has_value ())
2213 v = value_fn_field (arg1p, f, j, type, offset);
2214 if (v != NULL)
2215 return v;
2217 else
2218 while (j >= 0)
2220 gdb_assert (args.has_value ());
2221 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2222 TYPE_FN_FIELD_TYPE (f, j)->has_varargs (),
2223 TYPE_FN_FIELD_TYPE (f, j)->num_fields (),
2224 TYPE_FN_FIELD_ARGS (f, j), *args))
2226 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2227 return value_virtual_fn_field (arg1p, f, j,
2228 type, offset);
2229 if (TYPE_FN_FIELD_STATIC_P (f, j)
2230 && static_memfuncp)
2231 *static_memfuncp = 1;
2232 v = value_fn_field (arg1p, f, j, type, offset);
2233 if (v != NULL)
2234 return v;
2236 j--;
2241 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2243 LONGEST base_offset;
2244 LONGEST this_offset;
2246 if (BASETYPE_VIA_VIRTUAL (type, i))
2248 struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2249 struct value *base_val;
2250 const gdb_byte *base_valaddr;
2252 /* The virtual base class pointer might have been
2253 clobbered by the user program. Make sure that it
2254 still points to a valid memory location. */
2256 if (offset < 0 || offset >= type->length ())
2258 CORE_ADDR address;
2260 gdb::byte_vector tmp (baseclass->length ());
2261 address = (*arg1p)->address ();
2263 if (target_read_memory (address + offset,
2264 tmp.data (), baseclass->length ()) != 0)
2265 error (_("virtual baseclass botch"));
2267 base_val = value_from_contents_and_address (baseclass,
2268 tmp.data (),
2269 address + offset);
2270 base_valaddr = base_val->contents_for_printing ().data ();
2271 this_offset = 0;
2273 else
2275 base_val = *arg1p;
2276 base_valaddr = (*arg1p)->contents_for_printing ().data ();
2277 this_offset = offset;
2280 base_offset = baseclass_offset (type, i, base_valaddr,
2281 this_offset, base_val->address (),
2282 base_val);
2284 else
2286 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2288 v = search_struct_method (name, arg1p, args, base_offset + offset,
2289 static_memfuncp, TYPE_BASECLASS (type, i));
2290 if (v == (struct value *) - 1)
2292 name_matched = 1;
2294 else if (v)
2296 /* FIXME-bothner: Why is this commented out? Why is it here? */
2297 /* *arg1p = arg1_tmp; */
2298 return v;
2301 if (name_matched)
2302 return (struct value *) - 1;
2303 else
2304 return NULL;
2307 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2308 extract the component named NAME from the ultimate target
2309 structure/union and return it as a value with its appropriate type.
2310 ERR is used in the error message if *ARGP's type is wrong.
2312 C++: ARGS is a list of argument types to aid in the selection of
2313 an appropriate method. Also, handle derived types.
2315 STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2316 where the truthvalue of whether the function that was resolved was
2317 a static member function or not is stored.
2319 ERR is an error message to be printed in case the field is not
2320 found. */
2322 struct value *
2323 value_struct_elt (struct value **argp,
2324 std::optional<gdb::array_view<value *>> args,
2325 const char *name, int *static_memfuncp, const char *err)
2327 struct type *t;
2328 struct value *v;
2330 *argp = coerce_array (*argp);
2332 t = check_typedef ((*argp)->type ());
2334 /* Follow pointers until we get to a non-pointer. */
2336 while (t->is_pointer_or_reference ())
2338 *argp = value_ind (*argp);
2339 /* Don't coerce fn pointer to fn and then back again! */
2340 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2341 *argp = coerce_array (*argp);
2342 t = check_typedef ((*argp)->type ());
2345 if (t->code () != TYPE_CODE_STRUCT
2346 && t->code () != TYPE_CODE_UNION)
2347 error (_("Attempt to extract a component of a value that is not a %s."),
2348 err);
2350 /* Assume it's not, unless we see that it is. */
2351 if (static_memfuncp)
2352 *static_memfuncp = 0;
2354 if (!args.has_value ())
2356 /* if there are no arguments ...do this... */
2358 /* Try as a field first, because if we succeed, there is less
2359 work to be done. */
2360 v = search_struct_field (name, *argp, t, 0);
2361 if (v)
2362 return v;
2364 if (current_language->la_language == language_fortran)
2366 /* If it is not a field it is the type name of an inherited
2367 structure. */
2368 v = search_struct_field (name, *argp, t, 1);
2369 if (v)
2370 return v;
2373 /* C++: If it was not found as a data field, then try to
2374 return it as a pointer to a method. */
2375 v = search_struct_method (name, argp, args, 0,
2376 static_memfuncp, t);
2378 if (v == (struct value *) - 1)
2379 error (_("Cannot take address of method %s."), name);
2380 else if (v == 0)
2382 if (TYPE_NFN_FIELDS (t))
2383 error (_("There is no member or method named %s."), name);
2384 else
2385 error (_("There is no member named %s."), name);
2387 return v;
2390 v = search_struct_method (name, argp, args, 0,
2391 static_memfuncp, t);
2393 if (v == (struct value *) - 1)
2395 error (_("One of the arguments you tried to pass to %s could not "
2396 "be converted to what the function wants."), name);
2398 else if (v == 0)
2400 /* See if user tried to invoke data as function. If so, hand it
2401 back. If it's not callable (i.e., a pointer to function),
2402 gdb should give an error. */
2403 v = search_struct_field (name, *argp, t, 0);
2404 /* If we found an ordinary field, then it is not a method call.
2405 So, treat it as if it were a static member function. */
2406 if (v && static_memfuncp)
2407 *static_memfuncp = 1;
2410 if (!v)
2411 throw_error (NOT_FOUND_ERROR,
2412 _("Structure has no component named %s."), name);
2413 return v;
2416 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2417 to a structure or union, extract and return its component (field) of
2418 type FTYPE at the specified BITPOS.
2419 Throw an exception on error. */
2421 struct value *
2422 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2423 const char *err)
2425 struct type *t;
2426 int i;
2428 *argp = coerce_array (*argp);
2430 t = check_typedef ((*argp)->type ());
2432 while (t->is_pointer_or_reference ())
2434 *argp = value_ind (*argp);
2435 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2436 *argp = coerce_array (*argp);
2437 t = check_typedef ((*argp)->type ());
2440 if (t->code () != TYPE_CODE_STRUCT
2441 && t->code () != TYPE_CODE_UNION)
2442 error (_("Attempt to extract a component of a value that is not a %s."),
2443 err);
2445 for (i = TYPE_N_BASECLASSES (t); i < t->num_fields (); i++)
2447 if (!t->field (i).is_static ()
2448 && bitpos == t->field (i).loc_bitpos ()
2449 && types_equal (ftype, t->field (i).type ()))
2450 return (*argp)->primitive_field (0, i, t);
2453 error (_("No field with matching bitpos and type."));
2455 /* Never hit. */
2456 return NULL;
2459 /* Search through the methods of an object (and its bases) to find a
2460 specified method. Return a reference to the fn_field list METHODS of
2461 overloaded instances defined in the source language. If available
2462 and matching, a vector of matching xmethods defined in extension
2463 languages are also returned in XMETHODS.
2465 Helper function for value_find_oload_list.
2466 ARGP is a pointer to a pointer to a value (the object).
2467 METHOD is a string containing the method name.
2468 OFFSET is the offset within the value.
2469 TYPE is the assumed type of the object.
2470 METHODS is a pointer to the matching overloaded instances defined
2471 in the source language. Since this is a recursive function,
2472 *METHODS should be set to NULL when calling this function.
2473 NUM_FNS is the number of overloaded instances. *NUM_FNS should be set to
2474 0 when calling this function.
2475 XMETHODS is the vector of matching xmethod workers. *XMETHODS
2476 should also be set to NULL when calling this function.
2477 BASETYPE is set to the actual type of the subobject where the
2478 method is found.
2479 BOFFSET is the offset of the base subobject where the method is found. */
2481 static void
2482 find_method_list (struct value **argp, const char *method,
2483 LONGEST offset, struct type *type,
2484 gdb::array_view<fn_field> *methods,
2485 std::vector<xmethod_worker_up> *xmethods,
2486 struct type **basetype, LONGEST *boffset)
2488 int i;
2489 struct fn_field *f = NULL;
2491 gdb_assert (methods != NULL && xmethods != NULL);
2492 type = check_typedef (type);
2494 /* First check in object itself.
2495 This function is called recursively to search through base classes.
2496 If there is a source method match found at some stage, then we need not
2497 look for source methods in consequent recursive calls. */
2498 if (methods->empty ())
2500 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2502 /* pai: FIXME What about operators and type conversions? */
2503 const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2505 if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2507 int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2508 f = TYPE_FN_FIELDLIST1 (type, i);
2509 *methods = gdb::make_array_view (f, len);
2511 *basetype = type;
2512 *boffset = offset;
2514 /* Resolve any stub methods. */
2515 check_stub_method_group (type, i);
2517 break;
2522 /* Unlike source methods, xmethods can be accumulated over successive
2523 recursive calls. In other words, an xmethod named 'm' in a class
2524 will not hide an xmethod named 'm' in its base class(es). We want
2525 it to be this way because xmethods are after all convenience functions
2526 and hence there is no point restricting them with something like method
2527 hiding. Moreover, if hiding is done for xmethods as well, then we will
2528 have to provide a mechanism to un-hide (like the 'using' construct). */
2529 get_matching_xmethod_workers (type, method, xmethods);
2531 /* If source methods are not found in current class, look for them in the
2532 base classes. We also have to go through the base classes to gather
2533 extension methods. */
2534 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2536 LONGEST base_offset;
2538 if (BASETYPE_VIA_VIRTUAL (type, i))
2540 base_offset = baseclass_offset (type, i,
2541 (*argp)->contents_for_printing ().data (),
2542 (*argp)->offset () + offset,
2543 (*argp)->address (), *argp);
2545 else /* Non-virtual base, simply use bit position from debug
2546 info. */
2548 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2551 find_method_list (argp, method, base_offset + offset,
2552 TYPE_BASECLASS (type, i), methods,
2553 xmethods, basetype, boffset);
2557 /* Return the list of overloaded methods of a specified name. The methods
2558 could be those GDB finds in the binary, or xmethod. Methods found in
2559 the binary are returned in METHODS, and xmethods are returned in
2560 XMETHODS.
2562 ARGP is a pointer to a pointer to a value (the object).
2563 METHOD is the method name.
2564 OFFSET is the offset within the value contents.
2565 METHODS is the list of matching overloaded instances defined in
2566 the source language.
2567 XMETHODS is the vector of matching xmethod workers defined in
2568 extension languages.
2569 BASETYPE is set to the type of the base subobject that defines the
2570 method.
2571 BOFFSET is the offset of the base subobject which defines the method. */
2573 static void
2574 value_find_oload_method_list (struct value **argp, const char *method,
2575 LONGEST offset,
2576 gdb::array_view<fn_field> *methods,
2577 std::vector<xmethod_worker_up> *xmethods,
2578 struct type **basetype, LONGEST *boffset)
2580 struct type *t;
2582 t = check_typedef ((*argp)->type ());
2584 /* Code snarfed from value_struct_elt. */
2585 while (t->is_pointer_or_reference ())
2587 *argp = value_ind (*argp);
2588 /* Don't coerce fn pointer to fn and then back again! */
2589 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2590 *argp = coerce_array (*argp);
2591 t = check_typedef ((*argp)->type ());
2594 if (t->code () != TYPE_CODE_STRUCT
2595 && t->code () != TYPE_CODE_UNION)
2596 error (_("Attempt to extract a component of a "
2597 "value that is not a struct or union"));
2599 gdb_assert (methods != NULL && xmethods != NULL);
2601 /* Clear the lists. */
2602 *methods = {};
2603 xmethods->clear ();
2605 find_method_list (argp, method, 0, t, methods, xmethods,
2606 basetype, boffset);
2609 /* Helper function for find_overload_match. If no matches were
2610 found, this function may generate a hint for the user that some
2611 of the relevant types are incomplete, so GDB can't evaluate
2612 type relationships to properly evaluate overloads.
2614 If no incomplete types are present, an empty string is returned. */
2615 static std::string
2616 incomplete_type_hint (gdb::array_view<value *> args)
2618 int incomplete_types = 0;
2619 std::string incomplete_arg_names;
2620 for (const struct value *arg : args)
2622 struct type *t = arg->type ();
2623 while (t->code () == TYPE_CODE_PTR)
2624 t = t->target_type ();
2625 if (t->is_stub ())
2627 string_file buffer;
2628 if (incomplete_types > 0)
2629 incomplete_arg_names += ", ";
2631 current_language->print_type (arg->type (), "", &buffer,
2632 -1, 0, &type_print_raw_options);
2634 incomplete_types++;
2635 incomplete_arg_names += buffer.string ();
2638 std::string hint;
2639 if (incomplete_types > 1)
2640 hint = string_printf (_("\nThe types: '%s' aren't fully known to GDB."
2641 " Please cast them directly to the desired"
2642 " typed in the function call."),
2643 incomplete_arg_names.c_str ());
2644 else if (incomplete_types == 1)
2645 hint = string_printf (_("\nThe type: '%s' isn't fully known to GDB."
2646 " Please cast it directly to the desired"
2647 " typed in the function call."),
2648 incomplete_arg_names.c_str ());
2649 return hint;
2652 /* Given an array of arguments (ARGS) (which includes an entry for
2653 "this" in the case of C++ methods), the NAME of a function, and
2654 whether it's a method or not (METHOD), find the best function that
2655 matches on the argument types according to the overload resolution
2656 rules.
2658 METHOD can be one of three values:
2659 NON_METHOD for non-member functions.
2660 METHOD: for member functions.
2661 BOTH: used for overload resolution of operators where the
2662 candidates are expected to be either member or non member
2663 functions. In this case the first argument ARGTYPES
2664 (representing 'this') is expected to be a reference to the
2665 target object, and will be dereferenced when attempting the
2666 non-member search.
2668 In the case of class methods, the parameter OBJ is an object value
2669 in which to search for overloaded methods.
2671 In the case of non-method functions, the parameter FSYM is a symbol
2672 corresponding to one of the overloaded functions.
2674 Return value is an integer: 0 -> good match, 10 -> debugger applied
2675 non-standard coercions, 100 -> incompatible.
2677 If a method is being searched for, VALP will hold the value.
2678 If a non-method is being searched for, SYMP will hold the symbol
2679 for it.
2681 If a method is being searched for, and it is a static method,
2682 then STATICP will point to a non-zero value.
2684 If NO_ADL argument dependent lookup is disabled. This is used to prevent
2685 ADL overload candidates when performing overload resolution for a fully
2686 qualified name.
2688 If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2689 read while picking the best overload match (it may be all zeroes and thus
2690 not have a vtable pointer), in which case skip virtual function lookup.
2691 This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2692 the result type.
2694 Note: This function does *not* check the value of
2695 overload_resolution. Caller must check it to see whether overload
2696 resolution is permitted. */
2699 find_overload_match (gdb::array_view<value *> args,
2700 const char *name, enum oload_search_type method,
2701 struct value **objp, struct symbol *fsym,
2702 struct value **valp, struct symbol **symp,
2703 int *staticp, const int no_adl,
2704 const enum noside noside)
2706 struct value *obj = (objp ? *objp : NULL);
2707 struct type *obj_type = obj ? obj->type () : NULL;
2708 /* Index of best overloaded function. */
2709 int func_oload_champ = -1;
2710 int method_oload_champ = -1;
2711 int src_method_oload_champ = -1;
2712 int ext_method_oload_champ = -1;
2714 /* The measure for the current best match. */
2715 badness_vector method_badness;
2716 badness_vector func_badness;
2717 badness_vector ext_method_badness;
2718 badness_vector src_method_badness;
2720 struct value *temp = obj;
2721 /* For methods, the list of overloaded methods. */
2722 gdb::array_view<fn_field> methods;
2723 /* For non-methods, the list of overloaded function symbols. */
2724 std::vector<symbol *> functions;
2725 /* For xmethods, the vector of xmethod workers. */
2726 std::vector<xmethod_worker_up> xmethods;
2727 struct type *basetype = NULL;
2728 LONGEST boffset;
2730 const char *obj_type_name = NULL;
2731 const char *func_name = NULL;
2732 gdb::unique_xmalloc_ptr<char> temp_func;
2733 enum oload_classification match_quality;
2734 enum oload_classification method_match_quality = INCOMPATIBLE;
2735 enum oload_classification src_method_match_quality = INCOMPATIBLE;
2736 enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2737 enum oload_classification func_match_quality = INCOMPATIBLE;
2739 /* Get the list of overloaded methods or functions. */
2740 if (method == METHOD || method == BOTH)
2742 gdb_assert (obj);
2744 /* OBJ may be a pointer value rather than the object itself. */
2745 obj = coerce_ref (obj);
2746 while (check_typedef (obj->type ())->code () == TYPE_CODE_PTR)
2747 obj = coerce_ref (value_ind (obj));
2748 obj_type_name = obj->type ()->name ();
2750 /* First check whether this is a data member, e.g. a pointer to
2751 a function. */
2752 if (check_typedef (obj->type ())->code () == TYPE_CODE_STRUCT)
2754 *valp = search_struct_field (name, obj,
2755 check_typedef (obj->type ()), 0);
2756 if (*valp)
2758 *staticp = 1;
2759 return 0;
2763 /* Retrieve the list of methods with the name NAME. */
2764 value_find_oload_method_list (&temp, name, 0, &methods,
2765 &xmethods, &basetype, &boffset);
2766 /* If this is a method only search, and no methods were found
2767 the search has failed. */
2768 if (method == METHOD && methods.empty () && xmethods.empty ())
2769 error (_("Couldn't find method %s%s%s"),
2770 obj_type_name,
2771 (obj_type_name && *obj_type_name) ? "::" : "",
2772 name);
2773 /* If we are dealing with stub method types, they should have
2774 been resolved by find_method_list via
2775 value_find_oload_method_list above. */
2776 if (!methods.empty ())
2778 gdb_assert (TYPE_SELF_TYPE (methods[0].type) != NULL);
2780 src_method_oload_champ
2781 = find_oload_champ (args,
2782 methods.size (),
2783 methods.data (), NULL, NULL,
2784 &src_method_badness);
2786 src_method_match_quality = classify_oload_match
2787 (src_method_badness, args.size (),
2788 oload_method_static_p (methods.data (), src_method_oload_champ));
2791 if (!xmethods.empty ())
2793 ext_method_oload_champ
2794 = find_oload_champ (args,
2795 xmethods.size (),
2796 NULL, xmethods.data (), NULL,
2797 &ext_method_badness);
2798 ext_method_match_quality = classify_oload_match (ext_method_badness,
2799 args.size (), 0);
2802 if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2804 switch (compare_badness (ext_method_badness, src_method_badness))
2806 case 0: /* Src method and xmethod are equally good. */
2807 /* If src method and xmethod are equally good, then
2808 xmethod should be the winner. Hence, fall through to the
2809 case where a xmethod is better than the source
2810 method, except when the xmethod match quality is
2811 non-standard. */
2812 [[fallthrough]];
2813 case 1: /* Src method and ext method are incompatible. */
2814 /* If ext method match is not standard, then let source method
2815 win. Otherwise, fallthrough to let xmethod win. */
2816 if (ext_method_match_quality != STANDARD)
2818 method_oload_champ = src_method_oload_champ;
2819 method_badness = src_method_badness;
2820 ext_method_oload_champ = -1;
2821 method_match_quality = src_method_match_quality;
2822 break;
2824 [[fallthrough]];
2825 case 2: /* Ext method is champion. */
2826 method_oload_champ = ext_method_oload_champ;
2827 method_badness = ext_method_badness;
2828 src_method_oload_champ = -1;
2829 method_match_quality = ext_method_match_quality;
2830 break;
2831 case 3: /* Src method is champion. */
2832 method_oload_champ = src_method_oload_champ;
2833 method_badness = src_method_badness;
2834 ext_method_oload_champ = -1;
2835 method_match_quality = src_method_match_quality;
2836 break;
2837 default:
2838 gdb_assert_not_reached ("Unexpected overload comparison "
2839 "result");
2840 break;
2843 else if (src_method_oload_champ >= 0)
2845 method_oload_champ = src_method_oload_champ;
2846 method_badness = src_method_badness;
2847 method_match_quality = src_method_match_quality;
2849 else if (ext_method_oload_champ >= 0)
2851 method_oload_champ = ext_method_oload_champ;
2852 method_badness = ext_method_badness;
2853 method_match_quality = ext_method_match_quality;
2857 if (method == NON_METHOD || method == BOTH)
2859 const char *qualified_name = NULL;
2861 /* If the overload match is being search for both as a method
2862 and non member function, the first argument must now be
2863 dereferenced. */
2864 if (method == BOTH)
2865 args[0] = value_ind (args[0]);
2867 if (fsym)
2869 qualified_name = fsym->natural_name ();
2871 /* If we have a function with a C++ name, try to extract just
2872 the function part. Do not try this for non-functions (e.g.
2873 function pointers). */
2874 if (qualified_name
2875 && (check_typedef (fsym->type ())->code ()
2876 == TYPE_CODE_FUNC))
2878 temp_func = cp_func_name (qualified_name);
2880 /* If cp_func_name did not remove anything, the name of the
2881 symbol did not include scope or argument types - it was
2882 probably a C-style function. */
2883 if (temp_func != nullptr)
2885 if (strcmp (temp_func.get (), qualified_name) == 0)
2886 func_name = NULL;
2887 else
2888 func_name = temp_func.get ();
2892 else
2894 func_name = name;
2895 qualified_name = name;
2898 /* If there was no C++ name, this must be a C-style function or
2899 not a function at all. Just return the same symbol. Do the
2900 same if cp_func_name fails for some reason. */
2901 if (func_name == NULL)
2903 *symp = fsym;
2904 return 0;
2907 func_oload_champ = find_oload_champ_namespace (args,
2908 func_name,
2909 qualified_name,
2910 &functions,
2911 &func_badness,
2912 no_adl);
2914 if (func_oload_champ >= 0)
2915 func_match_quality = classify_oload_match (func_badness,
2916 args.size (), 0);
2919 /* Did we find a match ? */
2920 if (method_oload_champ == -1 && func_oload_champ == -1)
2921 throw_error (NOT_FOUND_ERROR,
2922 _("No symbol \"%s\" in current context."),
2923 name);
2925 /* If we have found both a method match and a function
2926 match, find out which one is better, and calculate match
2927 quality. */
2928 if (method_oload_champ >= 0 && func_oload_champ >= 0)
2930 switch (compare_badness (func_badness, method_badness))
2932 case 0: /* Top two contenders are equally good. */
2933 /* FIXME: GDB does not support the general ambiguous case.
2934 All candidates should be collected and presented the
2935 user. */
2936 error (_("Ambiguous overload resolution"));
2937 break;
2938 case 1: /* Incomparable top contenders. */
2939 /* This is an error incompatible candidates
2940 should not have been proposed. */
2941 error (_("Internal error: incompatible "
2942 "overload candidates proposed"));
2943 break;
2944 case 2: /* Function champion. */
2945 method_oload_champ = -1;
2946 match_quality = func_match_quality;
2947 break;
2948 case 3: /* Method champion. */
2949 func_oload_champ = -1;
2950 match_quality = method_match_quality;
2951 break;
2952 default:
2953 error (_("Internal error: unexpected overload comparison result"));
2954 break;
2957 else
2959 /* We have either a method match or a function match. */
2960 if (method_oload_champ >= 0)
2961 match_quality = method_match_quality;
2962 else
2963 match_quality = func_match_quality;
2966 if (match_quality == INCOMPATIBLE)
2968 std::string hint = incomplete_type_hint (args);
2969 if (method == METHOD)
2970 error (_("Cannot resolve method %s%s%s to any overloaded instance%s"),
2971 obj_type_name,
2972 (obj_type_name && *obj_type_name) ? "::" : "",
2973 name, hint.c_str ());
2974 else
2975 error (_("Cannot resolve function %s to any overloaded instance%s"),
2976 func_name, hint.c_str ());
2978 else if (match_quality == NON_STANDARD)
2980 if (method == METHOD)
2981 warning (_("Using non-standard conversion to match "
2982 "method %s%s%s to supplied arguments"),
2983 obj_type_name,
2984 (obj_type_name && *obj_type_name) ? "::" : "",
2985 name);
2986 else
2987 warning (_("Using non-standard conversion to match "
2988 "function %s to supplied arguments"),
2989 func_name);
2992 if (staticp != NULL)
2993 *staticp = oload_method_static_p (methods.data (), method_oload_champ);
2995 if (method_oload_champ >= 0)
2997 if (src_method_oload_champ >= 0)
2999 if (TYPE_FN_FIELD_VIRTUAL_P (methods, method_oload_champ)
3000 && noside != EVAL_AVOID_SIDE_EFFECTS)
3002 *valp = value_virtual_fn_field (&temp, methods.data (),
3003 method_oload_champ, basetype,
3004 boffset);
3006 else
3007 *valp = value_fn_field (&temp, methods.data (),
3008 method_oload_champ, basetype, boffset);
3010 else
3011 *valp = value::from_xmethod
3012 (std::move (xmethods[ext_method_oload_champ]));
3014 else
3015 *symp = functions[func_oload_champ];
3017 if (objp)
3019 struct type *temp_type = check_typedef (temp->type ());
3020 struct type *objtype = check_typedef (obj_type);
3022 if (temp_type->code () != TYPE_CODE_PTR
3023 && objtype->is_pointer_or_reference ())
3025 temp = value_addr (temp);
3027 *objp = temp;
3030 switch (match_quality)
3032 case INCOMPATIBLE:
3033 return 100;
3034 case NON_STANDARD:
3035 return 10;
3036 default: /* STANDARD */
3037 return 0;
3041 /* Find the best overload match, searching for FUNC_NAME in namespaces
3042 contained in QUALIFIED_NAME until it either finds a good match or
3043 runs out of namespaces. It stores the overloaded functions in
3044 *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV. If NO_ADL,
3045 argument dependent lookup is not performed. */
3047 static int
3048 find_oload_champ_namespace (gdb::array_view<value *> args,
3049 const char *func_name,
3050 const char *qualified_name,
3051 std::vector<symbol *> *oload_syms,
3052 badness_vector *oload_champ_bv,
3053 const int no_adl)
3055 int oload_champ;
3057 find_oload_champ_namespace_loop (args,
3058 func_name,
3059 qualified_name, 0,
3060 oload_syms, oload_champ_bv,
3061 &oload_champ,
3062 no_adl);
3064 return oload_champ;
3067 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
3068 how deep we've looked for namespaces, and the champ is stored in
3069 OLOAD_CHAMP. The return value is 1 if the champ is a good one, 0
3070 if it isn't. Other arguments are the same as in
3071 find_oload_champ_namespace. */
3073 static int
3074 find_oload_champ_namespace_loop (gdb::array_view<value *> args,
3075 const char *func_name,
3076 const char *qualified_name,
3077 int namespace_len,
3078 std::vector<symbol *> *oload_syms,
3079 badness_vector *oload_champ_bv,
3080 int *oload_champ,
3081 const int no_adl)
3083 int next_namespace_len = namespace_len;
3084 int searched_deeper = 0;
3085 int new_oload_champ;
3086 char *new_namespace;
3088 if (next_namespace_len != 0)
3090 gdb_assert (qualified_name[next_namespace_len] == ':');
3091 next_namespace_len += 2;
3093 next_namespace_len +=
3094 cp_find_first_component (qualified_name + next_namespace_len);
3096 /* First, see if we have a deeper namespace we can search in.
3097 If we get a good match there, use it. */
3099 if (qualified_name[next_namespace_len] == ':')
3101 searched_deeper = 1;
3103 if (find_oload_champ_namespace_loop (args,
3104 func_name, qualified_name,
3105 next_namespace_len,
3106 oload_syms, oload_champ_bv,
3107 oload_champ, no_adl))
3109 return 1;
3113 /* If we reach here, either we're in the deepest namespace or we
3114 didn't find a good match in a deeper namespace. But, in the
3115 latter case, we still have a bad match in a deeper namespace;
3116 note that we might not find any match at all in the current
3117 namespace. (There's always a match in the deepest namespace,
3118 because this overload mechanism only gets called if there's a
3119 function symbol to start off with.) */
3121 new_namespace = (char *) alloca (namespace_len + 1);
3122 strncpy (new_namespace, qualified_name, namespace_len);
3123 new_namespace[namespace_len] = '\0';
3125 std::vector<symbol *> new_oload_syms
3126 = make_symbol_overload_list (func_name, new_namespace);
3128 /* If we have reached the deepest level perform argument
3129 determined lookup. */
3130 if (!searched_deeper && !no_adl)
3132 int ix;
3133 struct type **arg_types;
3135 /* Prepare list of argument types for overload resolution. */
3136 arg_types = (struct type **)
3137 alloca (args.size () * (sizeof (struct type *)));
3138 for (ix = 0; ix < args.size (); ix++)
3139 arg_types[ix] = args[ix]->type ();
3140 add_symbol_overload_list_adl ({arg_types, args.size ()}, func_name,
3141 &new_oload_syms);
3144 badness_vector new_oload_champ_bv;
3145 new_oload_champ = find_oload_champ (args,
3146 new_oload_syms.size (),
3147 NULL, NULL, new_oload_syms.data (),
3148 &new_oload_champ_bv);
3150 /* Case 1: We found a good match. Free earlier matches (if any),
3151 and return it. Case 2: We didn't find a good match, but we're
3152 not the deepest function. Then go with the bad match that the
3153 deeper function found. Case 3: We found a bad match, and we're
3154 the deepest function. Then return what we found, even though
3155 it's a bad match. */
3157 if (new_oload_champ != -1
3158 && classify_oload_match (new_oload_champ_bv, args.size (), 0) == STANDARD)
3160 *oload_syms = std::move (new_oload_syms);
3161 *oload_champ = new_oload_champ;
3162 *oload_champ_bv = std::move (new_oload_champ_bv);
3163 return 1;
3165 else if (searched_deeper)
3167 return 0;
3169 else
3171 *oload_syms = std::move (new_oload_syms);
3172 *oload_champ = new_oload_champ;
3173 *oload_champ_bv = std::move (new_oload_champ_bv);
3174 return 0;
3178 /* Look for a function to take ARGS. Find the best match from among
3179 the overloaded methods or functions given by METHODS or FUNCTIONS
3180 or XMETHODS, respectively. One, and only one of METHODS, FUNCTIONS
3181 and XMETHODS can be non-NULL.
3183 NUM_FNS is the length of the array pointed at by METHODS, FUNCTIONS
3184 or XMETHODS, whichever is non-NULL.
3186 Return the index of the best match; store an indication of the
3187 quality of the match in OLOAD_CHAMP_BV. */
3189 static int
3190 find_oload_champ (gdb::array_view<value *> args,
3191 size_t num_fns,
3192 fn_field *methods,
3193 xmethod_worker_up *xmethods,
3194 symbol **functions,
3195 badness_vector *oload_champ_bv)
3197 /* A measure of how good an overloaded instance is. */
3198 badness_vector bv;
3199 /* Index of best overloaded function. */
3200 int oload_champ = -1;
3201 /* Current ambiguity state for overload resolution. */
3202 int oload_ambiguous = 0;
3203 /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs. */
3205 /* A champion can be found among methods alone, or among functions
3206 alone, or in xmethods alone, but not in more than one of these
3207 groups. */
3208 gdb_assert ((methods != NULL) + (functions != NULL) + (xmethods != NULL)
3209 == 1);
3211 /* Consider each candidate in turn. */
3212 for (size_t ix = 0; ix < num_fns; ix++)
3214 int jj;
3215 int static_offset = 0;
3216 bool varargs = false;
3217 std::vector<type *> parm_types;
3219 if (xmethods != NULL)
3220 parm_types = xmethods[ix]->get_arg_types ();
3221 else
3223 size_t nparms;
3225 if (methods != NULL)
3227 nparms = TYPE_FN_FIELD_TYPE (methods, ix)->num_fields ();
3228 static_offset = oload_method_static_p (methods, ix);
3229 varargs = TYPE_FN_FIELD_TYPE (methods, ix)->has_varargs ();
3231 else
3233 nparms = functions[ix]->type ()->num_fields ();
3234 varargs = functions[ix]->type ()->has_varargs ();
3237 parm_types.reserve (nparms);
3238 for (jj = 0; jj < nparms; jj++)
3240 type *t = (methods != NULL
3241 ? (TYPE_FN_FIELD_ARGS (methods, ix)[jj].type ())
3242 : functions[ix]->type ()->field (jj).type ());
3243 parm_types.push_back (t);
3247 /* Compare parameter types to supplied argument types. Skip
3248 THIS for static methods. */
3249 bv = rank_function (parm_types,
3250 args.slice (static_offset),
3251 varargs);
3253 if (overload_debug)
3255 if (methods != NULL)
3256 gdb_printf (gdb_stderr,
3257 "Overloaded method instance %s, # of parms %d\n",
3258 methods[ix].physname, (int) parm_types.size ());
3259 else if (xmethods != NULL)
3260 gdb_printf (gdb_stderr,
3261 "Xmethod worker, # of parms %d\n",
3262 (int) parm_types.size ());
3263 else
3264 gdb_printf (gdb_stderr,
3265 "Overloaded function instance "
3266 "%s # of parms %d\n",
3267 functions[ix]->demangled_name (),
3268 (int) parm_types.size ());
3270 gdb_printf (gdb_stderr,
3271 "...Badness of length : {%d, %d}\n",
3272 bv[0].rank, bv[0].subrank);
3274 for (jj = 1; jj < bv.size (); jj++)
3275 gdb_printf (gdb_stderr,
3276 "...Badness of arg %d : {%d, %d}\n",
3277 jj, bv[jj].rank, bv[jj].subrank);
3280 if (oload_champ_bv->empty ())
3282 *oload_champ_bv = std::move (bv);
3283 oload_champ = 0;
3285 else /* See whether current candidate is better or worse than
3286 previous best. */
3287 switch (compare_badness (bv, *oload_champ_bv))
3289 case 0: /* Top two contenders are equally good. */
3290 oload_ambiguous = 1;
3291 break;
3292 case 1: /* Incomparable top contenders. */
3293 oload_ambiguous = 2;
3294 break;
3295 case 2: /* New champion, record details. */
3296 *oload_champ_bv = std::move (bv);
3297 oload_ambiguous = 0;
3298 oload_champ = ix;
3299 break;
3300 case 3:
3301 default:
3302 break;
3304 if (overload_debug)
3305 gdb_printf (gdb_stderr, "Overload resolution "
3306 "champion is %d, ambiguous? %d\n",
3307 oload_champ, oload_ambiguous);
3310 return oload_champ;
3313 /* Return 1 if we're looking at a static method, 0 if we're looking at
3314 a non-static method or a function that isn't a method. */
3316 static int
3317 oload_method_static_p (struct fn_field *fns_ptr, int index)
3319 if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3320 return 1;
3321 else
3322 return 0;
3325 /* Check how good an overload match OLOAD_CHAMP_BV represents. */
3327 static enum oload_classification
3328 classify_oload_match (const badness_vector &oload_champ_bv,
3329 int nargs,
3330 int static_offset)
3332 int ix;
3333 enum oload_classification worst = STANDARD;
3335 for (ix = 1; ix <= nargs - static_offset; ix++)
3337 /* If this conversion is as bad as INCOMPATIBLE_TYPE_BADNESS
3338 or worse return INCOMPATIBLE. */
3339 if (compare_ranks (oload_champ_bv[ix],
3340 INCOMPATIBLE_TYPE_BADNESS) <= 0)
3341 return INCOMPATIBLE; /* Truly mismatched types. */
3342 /* Otherwise If this conversion is as bad as
3343 NS_POINTER_CONVERSION_BADNESS or worse return NON_STANDARD. */
3344 else if (compare_ranks (oload_champ_bv[ix],
3345 NS_POINTER_CONVERSION_BADNESS) <= 0)
3346 worst = NON_STANDARD; /* Non-standard type conversions
3347 needed. */
3350 /* If no INCOMPATIBLE classification was found, return the worst one
3351 that was found (if any). */
3352 return worst;
3355 /* C++: return 1 is NAME is a legitimate name for the destructor of
3356 type TYPE. If TYPE does not have a destructor, or if NAME is
3357 inappropriate for TYPE, an error is signaled. Parameter TYPE should not yet
3358 have CHECK_TYPEDEF applied, this function will apply it itself. */
3361 destructor_name_p (const char *name, struct type *type)
3363 if (name[0] == '~')
3365 const char *dname = type_name_or_error (type);
3366 const char *cp = strchr (dname, '<');
3367 unsigned int len;
3369 /* Do not compare the template part for template classes. */
3370 if (cp == NULL)
3371 len = strlen (dname);
3372 else
3373 len = cp - dname;
3374 if (strlen (name + 1) != len || strncmp (dname, name + 1, len) != 0)
3375 error (_("name of destructor must equal name of class"));
3376 else
3377 return 1;
3379 return 0;
3382 /* Find an enum constant named NAME in TYPE. TYPE must be an "enum
3383 class". If the name is found, return a value representing it;
3384 otherwise throw an exception. */
3386 static struct value *
3387 enum_constant_from_type (struct type *type, const char *name)
3389 int i;
3390 int name_len = strlen (name);
3392 gdb_assert (type->code () == TYPE_CODE_ENUM
3393 && type->is_declared_class ());
3395 for (i = TYPE_N_BASECLASSES (type); i < type->num_fields (); ++i)
3397 const char *fname = type->field (i).name ();
3398 int len;
3400 if (type->field (i).loc_kind () != FIELD_LOC_KIND_ENUMVAL
3401 || fname == NULL)
3402 continue;
3404 /* Look for the trailing "::NAME", since enum class constant
3405 names are qualified here. */
3406 len = strlen (fname);
3407 if (len + 2 >= name_len
3408 && fname[len - name_len - 2] == ':'
3409 && fname[len - name_len - 1] == ':'
3410 && strcmp (&fname[len - name_len], name) == 0)
3411 return value_from_longest (type, type->field (i).loc_enumval ());
3414 error (_("no constant named \"%s\" in enum \"%s\""),
3415 name, type->name ());
3418 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3419 return the appropriate member (or the address of the member, if
3420 WANT_ADDRESS). This function is used to resolve user expressions
3421 of the form "DOMAIN::NAME". For more details on what happens, see
3422 the comment before value_struct_elt_for_reference. */
3424 struct value *
3425 value_aggregate_elt (struct type *curtype, const char *name,
3426 struct type *expect_type, int want_address,
3427 enum noside noside)
3429 switch (curtype->code ())
3431 case TYPE_CODE_STRUCT:
3432 case TYPE_CODE_UNION:
3433 return value_struct_elt_for_reference (curtype, 0, curtype,
3434 name, expect_type,
3435 want_address, noside);
3436 case TYPE_CODE_NAMESPACE:
3437 return value_namespace_elt (curtype, name,
3438 want_address, noside);
3440 case TYPE_CODE_ENUM:
3441 return enum_constant_from_type (curtype, name);
3443 default:
3444 internal_error (_("non-aggregate type in value_aggregate_elt"));
3448 /* Compares the two method/function types T1 and T2 for "equality"
3449 with respect to the methods' parameters. If the types of the
3450 two parameter lists are the same, returns 1; 0 otherwise. This
3451 comparison may ignore any artificial parameters in T1 if
3452 SKIP_ARTIFICIAL is non-zero. This function will ALWAYS skip
3453 the first artificial parameter in T1, assumed to be a 'this' pointer.
3455 The type T2 is expected to have come from make_params (in eval.c). */
3457 static int
3458 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3460 int start = 0;
3462 if (t1->num_fields () > 0 && t1->field (0).is_artificial ())
3463 ++start;
3465 /* If skipping artificial fields, find the first real field
3466 in T1. */
3467 if (skip_artificial)
3469 while (start < t1->num_fields ()
3470 && t1->field (start).is_artificial ())
3471 ++start;
3474 /* Now compare parameters. */
3476 /* Special case: a method taking void. T1 will contain no
3477 non-artificial fields, and T2 will contain TYPE_CODE_VOID. */
3478 if ((t1->num_fields () - start) == 0 && t2->num_fields () == 1
3479 && t2->field (0).type ()->code () == TYPE_CODE_VOID)
3480 return 1;
3482 if ((t1->num_fields () - start) == t2->num_fields ())
3484 int i;
3486 for (i = 0; i < t2->num_fields (); ++i)
3488 if (compare_ranks (rank_one_type (t1->field (start + i).type (),
3489 t2->field (i).type (), NULL),
3490 EXACT_MATCH_BADNESS) != 0)
3491 return 0;
3494 return 1;
3497 return 0;
3500 /* C++: Given an aggregate type VT, and a class type CLS, search
3501 recursively for CLS using value V; If found, store the offset
3502 which is either fetched from the virtual base pointer if CLS
3503 is virtual or accumulated offset of its parent classes if
3504 CLS is non-virtual in *BOFFS, set ISVIRT to indicate if CLS
3505 is virtual, and return true. If not found, return false. */
3507 static bool
3508 get_baseclass_offset (struct type *vt, struct type *cls,
3509 struct value *v, int *boffs, bool *isvirt)
3511 for (int i = 0; i < TYPE_N_BASECLASSES (vt); i++)
3513 struct type *t = vt->field (i).type ();
3514 if (types_equal (t, cls))
3516 if (BASETYPE_VIA_VIRTUAL (vt, i))
3518 const gdb_byte *adr = v->contents_for_printing ().data ();
3519 *boffs = baseclass_offset (vt, i, adr, v->offset (),
3520 value_as_long (v), v);
3521 *isvirt = true;
3523 else
3524 *isvirt = false;
3525 return true;
3528 if (get_baseclass_offset (check_typedef (t), cls, v, boffs, isvirt))
3530 if (*isvirt == false) /* Add non-virtual base offset. */
3532 const gdb_byte *adr = v->contents_for_printing ().data ();
3533 *boffs += baseclass_offset (vt, i, adr, v->offset (),
3534 value_as_long (v), v);
3536 return true;
3540 return false;
3543 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3544 return the address of this member as a "pointer to member" type.
3545 If INTYPE is non-null, then it will be the type of the member we
3546 are looking for. This will help us resolve "pointers to member
3547 functions". This function is used to resolve user expressions of
3548 the form "DOMAIN::NAME". */
3550 static struct value *
3551 value_struct_elt_for_reference (struct type *domain, int offset,
3552 struct type *curtype, const char *name,
3553 struct type *intype,
3554 int want_address,
3555 enum noside noside)
3557 struct type *t = check_typedef (curtype);
3558 int i;
3559 struct value *result;
3561 if (t->code () != TYPE_CODE_STRUCT
3562 && t->code () != TYPE_CODE_UNION)
3563 error (_("Internal error: non-aggregate type "
3564 "to value_struct_elt_for_reference"));
3566 for (i = t->num_fields () - 1; i >= TYPE_N_BASECLASSES (t); i--)
3568 const char *t_field_name = t->field (i).name ();
3570 if (t_field_name && strcmp (t_field_name, name) == 0)
3572 if (t->field (i).is_static ())
3574 struct value *v = value_static_field (t, i);
3575 if (want_address)
3576 v = value_addr (v);
3577 return v;
3579 if (t->field (i).is_packed ())
3580 error (_("pointers to bitfield members not allowed"));
3582 if (want_address)
3583 return value_from_longest
3584 (lookup_memberptr_type (t->field (i).type (), domain),
3585 offset + (LONGEST) (t->field (i).loc_bitpos () >> 3));
3586 else if (noside != EVAL_NORMAL)
3587 return value::allocate (t->field (i).type ());
3588 else
3590 /* Try to evaluate NAME as a qualified name with implicit
3591 this pointer. In this case, attempt to return the
3592 equivalent to `this->*(&TYPE::NAME)'. */
3593 struct value *v = value_of_this_silent (current_language);
3594 if (v != NULL)
3596 struct value *ptr, *this_v = v;
3597 long mem_offset;
3598 struct type *type, *tmp;
3600 ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3601 type = check_typedef (ptr->type ());
3602 gdb_assert (type != NULL
3603 && type->code () == TYPE_CODE_MEMBERPTR);
3604 tmp = lookup_pointer_type (TYPE_SELF_TYPE (type));
3605 v = value_cast_pointers (tmp, v, 1);
3606 mem_offset = value_as_long (ptr);
3607 if (domain != curtype)
3609 /* Find class offset of type CURTYPE from either its
3610 parent type DOMAIN or the type of implied this. */
3611 int boff = 0;
3612 bool isvirt = false;
3613 if (get_baseclass_offset (domain, curtype, v, &boff,
3614 &isvirt))
3615 mem_offset += boff;
3616 else
3618 struct type *p = check_typedef (this_v->type ());
3619 p = check_typedef (p->target_type ());
3620 if (get_baseclass_offset (p, curtype, this_v,
3621 &boff, &isvirt))
3622 mem_offset += boff;
3625 tmp = lookup_pointer_type (type->target_type ());
3626 result = value_from_pointer (tmp,
3627 value_as_long (v) + mem_offset);
3628 return value_ind (result);
3631 error (_("Cannot reference non-static field \"%s\""), name);
3636 /* C++: If it was not found as a data field, then try to return it
3637 as a pointer to a method. */
3639 /* Perform all necessary dereferencing. */
3640 while (intype && intype->code () == TYPE_CODE_PTR)
3641 intype = intype->target_type ();
3643 for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3645 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3647 if (t_field_name && strcmp (t_field_name, name) == 0)
3649 int j;
3650 int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3651 struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3653 check_stub_method_group (t, i);
3655 if (intype)
3657 for (j = 0; j < len; ++j)
3659 if (TYPE_CONST (intype) != TYPE_FN_FIELD_CONST (f, j))
3660 continue;
3661 if (TYPE_VOLATILE (intype) != TYPE_FN_FIELD_VOLATILE (f, j))
3662 continue;
3664 if (compare_parameters (TYPE_FN_FIELD_TYPE (f, j), intype, 0)
3665 || compare_parameters (TYPE_FN_FIELD_TYPE (f, j),
3666 intype, 1))
3667 break;
3670 if (j == len)
3671 error (_("no member function matches "
3672 "that type instantiation"));
3674 else
3676 int ii;
3678 j = -1;
3679 for (ii = 0; ii < len; ++ii)
3681 /* Skip artificial methods. This is necessary if,
3682 for example, the user wants to "print
3683 subclass::subclass" with only one user-defined
3684 constructor. There is no ambiguity in this case.
3685 We are careful here to allow artificial methods
3686 if they are the unique result. */
3687 if (TYPE_FN_FIELD_ARTIFICIAL (f, ii))
3689 if (j == -1)
3690 j = ii;
3691 continue;
3694 /* Desired method is ambiguous if more than one
3695 method is defined. */
3696 if (j != -1 && !TYPE_FN_FIELD_ARTIFICIAL (f, j))
3697 error (_("non-unique member `%s' requires "
3698 "type instantiation"), name);
3700 j = ii;
3703 if (j == -1)
3704 error (_("no matching member function"));
3707 if (TYPE_FN_FIELD_STATIC_P (f, j))
3709 struct symbol *s =
3710 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3711 0, VAR_DOMAIN, 0).symbol;
3713 if (s == NULL)
3714 return NULL;
3716 if (want_address)
3717 return value_addr (read_var_value (s, 0, 0));
3718 else
3719 return read_var_value (s, 0, 0);
3722 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3724 if (want_address)
3726 result = value::allocate
3727 (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3728 cplus_make_method_ptr (result->type (),
3729 result->contents_writeable ().data (),
3730 TYPE_FN_FIELD_VOFFSET (f, j), 1);
3732 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3733 return value::allocate (TYPE_FN_FIELD_TYPE (f, j));
3734 else
3735 error (_("Cannot reference virtual member function \"%s\""),
3736 name);
3738 else
3740 struct symbol *s =
3741 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3742 0, VAR_DOMAIN, 0).symbol;
3744 if (s == NULL)
3745 return NULL;
3747 struct value *v = read_var_value (s, 0, 0);
3748 if (!want_address)
3749 result = v;
3750 else
3752 result = value::allocate (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3753 cplus_make_method_ptr (result->type (),
3754 result->contents_writeable ().data (),
3755 v->address (), 0);
3758 return result;
3761 for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3763 struct value *v;
3764 int base_offset;
3766 if (BASETYPE_VIA_VIRTUAL (t, i))
3767 base_offset = 0;
3768 else
3769 base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3770 v = value_struct_elt_for_reference (domain,
3771 offset + base_offset,
3772 TYPE_BASECLASS (t, i),
3773 name, intype,
3774 want_address, noside);
3775 if (v)
3776 return v;
3779 /* As a last chance, pretend that CURTYPE is a namespace, and look
3780 it up that way; this (frequently) works for types nested inside
3781 classes. */
3783 return value_maybe_namespace_elt (curtype, name,
3784 want_address, noside);
3787 /* C++: Return the member NAME of the namespace given by the type
3788 CURTYPE. */
3790 static struct value *
3791 value_namespace_elt (const struct type *curtype,
3792 const char *name, int want_address,
3793 enum noside noside)
3795 struct value *retval = value_maybe_namespace_elt (curtype, name,
3796 want_address,
3797 noside);
3799 if (retval == NULL)
3800 error (_("No symbol \"%s\" in namespace \"%s\"."),
3801 name, curtype->name ());
3803 return retval;
3806 /* A helper function used by value_namespace_elt and
3807 value_struct_elt_for_reference. It looks up NAME inside the
3808 context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
3809 is a class and NAME refers to a type in CURTYPE itself (as opposed
3810 to, say, some base class of CURTYPE). */
3812 static struct value *
3813 value_maybe_namespace_elt (const struct type *curtype,
3814 const char *name, int want_address,
3815 enum noside noside)
3817 const char *namespace_name = curtype->name ();
3818 struct block_symbol sym;
3819 struct value *result;
3821 sym = cp_lookup_symbol_namespace (namespace_name, name,
3822 get_selected_block (0), VAR_DOMAIN);
3824 if (sym.symbol == NULL)
3825 return NULL;
3826 else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3827 && (sym.symbol->aclass () == LOC_TYPEDEF))
3828 result = value::allocate (sym.symbol->type ());
3829 else
3830 result = value_of_variable (sym.symbol, sym.block);
3832 if (want_address)
3833 result = value_addr (result);
3835 return result;
3838 /* Given a pointer or a reference value V, find its real (RTTI) type.
3840 Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3841 and refer to the values computed for the object pointed to. */
3843 struct type *
3844 value_rtti_indirect_type (struct value *v, int *full,
3845 LONGEST *top, int *using_enc)
3847 struct value *target = NULL;
3848 struct type *type, *real_type, *target_type;
3850 type = v->type ();
3851 type = check_typedef (type);
3852 if (TYPE_IS_REFERENCE (type))
3853 target = coerce_ref (v);
3854 else if (type->code () == TYPE_CODE_PTR)
3859 target = value_ind (v);
3861 catch (const gdb_exception_error &except)
3863 if (except.error == MEMORY_ERROR)
3865 /* value_ind threw a memory error. The pointer is NULL or
3866 contains an uninitialized value: we can't determine any
3867 type. */
3868 return NULL;
3870 throw;
3873 else
3874 return NULL;
3876 real_type = value_rtti_type (target, full, top, using_enc);
3878 if (real_type)
3880 /* Copy qualifiers to the referenced object. */
3881 target_type = target->type ();
3882 real_type = make_cv_type (TYPE_CONST (target_type),
3883 TYPE_VOLATILE (target_type), real_type, NULL);
3884 if (TYPE_IS_REFERENCE (type))
3885 real_type = lookup_reference_type (real_type, type->code ());
3886 else if (type->code () == TYPE_CODE_PTR)
3887 real_type = lookup_pointer_type (real_type);
3888 else
3889 internal_error (_("Unexpected value type."));
3891 /* Copy qualifiers to the pointer/reference. */
3892 real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3893 real_type, NULL);
3896 return real_type;
3899 /* Given a value pointed to by ARGP, check its real run-time type, and
3900 if that is different from the enclosing type, create a new value
3901 using the real run-time type as the enclosing type (and of the same
3902 type as ARGP) and return it, with the embedded offset adjusted to
3903 be the correct offset to the enclosed object. RTYPE is the type,
3904 and XFULL, XTOP, and XUSING_ENC are the other parameters, computed
3905 by value_rtti_type(). If these are available, they can be supplied
3906 and a second call to value_rtti_type() is avoided. (Pass RTYPE ==
3907 NULL if they're not available. */
3909 struct value *
3910 value_full_object (struct value *argp,
3911 struct type *rtype,
3912 int xfull, int xtop,
3913 int xusing_enc)
3915 struct type *real_type;
3916 int full = 0;
3917 LONGEST top = -1;
3918 int using_enc = 0;
3919 struct value *new_val;
3921 if (rtype)
3923 real_type = rtype;
3924 full = xfull;
3925 top = xtop;
3926 using_enc = xusing_enc;
3928 else
3929 real_type = value_rtti_type (argp, &full, &top, &using_enc);
3931 /* If no RTTI data, or if object is already complete, do nothing. */
3932 if (!real_type || real_type == argp->enclosing_type ())
3933 return argp;
3935 /* In a destructor we might see a real type that is a superclass of
3936 the object's type. In this case it is better to leave the object
3937 as-is. */
3938 if (full
3939 && real_type->length () < argp->enclosing_type ()->length ())
3940 return argp;
3942 /* If we have the full object, but for some reason the enclosing
3943 type is wrong, set it. */
3944 /* pai: FIXME -- sounds iffy */
3945 if (full)
3947 argp = argp->copy ();
3948 argp->set_enclosing_type (real_type);
3949 return argp;
3952 /* Check if object is in memory. */
3953 if (argp->lval () != lval_memory)
3955 warning (_("Couldn't retrieve complete object of RTTI "
3956 "type %s; object may be in register(s)."),
3957 real_type->name ());
3959 return argp;
3962 /* All other cases -- retrieve the complete object. */
3963 /* Go back by the computed top_offset from the beginning of the
3964 object, adjusting for the embedded offset of argp if that's what
3965 value_rtti_type used for its computation. */
3966 new_val = value_at_lazy (real_type, argp->address () - top +
3967 (using_enc ? 0 : argp->embedded_offset ()));
3968 new_val->deprecated_set_type (argp->type ());
3969 new_val->set_embedded_offset ((using_enc
3970 ? top + argp->embedded_offset ()
3971 : top));
3972 return new_val;
3976 /* Return the value of the local variable, if one exists. Throw error
3977 otherwise, such as if the request is made in an inappropriate context. */
3979 struct value *
3980 value_of_this (const struct language_defn *lang)
3982 struct block_symbol sym;
3983 const struct block *b;
3984 frame_info_ptr frame;
3986 if (lang->name_of_this () == NULL)
3987 error (_("no `this' in current language"));
3989 frame = get_selected_frame (_("no frame selected"));
3991 b = get_frame_block (frame, NULL);
3993 sym = lookup_language_this (lang, b);
3994 if (sym.symbol == NULL)
3995 error (_("current stack frame does not contain a variable named `%s'"),
3996 lang->name_of_this ());
3998 return read_var_value (sym.symbol, sym.block, frame);
4001 /* Return the value of the local variable, if one exists. Return NULL
4002 otherwise. Never throw error. */
4004 struct value *
4005 value_of_this_silent (const struct language_defn *lang)
4007 struct value *ret = NULL;
4011 ret = value_of_this (lang);
4013 catch (const gdb_exception_error &except)
4017 return ret;
4020 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH
4021 elements long, starting at LOWBOUND. The result has the same lower
4022 bound as the original ARRAY. */
4024 struct value *
4025 value_slice (struct value *array, int lowbound, int length)
4027 struct type *slice_range_type, *slice_type, *range_type;
4028 LONGEST lowerbound, upperbound;
4029 struct value *slice;
4030 struct type *array_type;
4032 array_type = check_typedef (array->type ());
4033 if (array_type->code () != TYPE_CODE_ARRAY
4034 && array_type->code () != TYPE_CODE_STRING)
4035 error (_("cannot take slice of non-array"));
4037 if (type_not_allocated (array_type))
4038 error (_("array not allocated"));
4039 if (type_not_associated (array_type))
4040 error (_("array not associated"));
4042 range_type = array_type->index_type ();
4043 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
4044 error (_("slice from bad array or bitstring"));
4046 if (lowbound < lowerbound || length < 0
4047 || lowbound + length - 1 > upperbound)
4048 error (_("slice out of range"));
4050 /* FIXME-type-allocation: need a way to free this type when we are
4051 done with it. */
4052 type_allocator alloc (range_type->target_type ());
4053 slice_range_type = create_static_range_type (alloc,
4054 range_type->target_type (),
4055 lowbound,
4056 lowbound + length - 1);
4059 struct type *element_type = array_type->target_type ();
4060 LONGEST offset
4061 = (lowbound - lowerbound) * check_typedef (element_type)->length ();
4063 slice_type = create_array_type (alloc,
4064 element_type,
4065 slice_range_type);
4066 slice_type->set_code (array_type->code ());
4068 if (array->lval () == lval_memory && array->lazy ())
4069 slice = value::allocate_lazy (slice_type);
4070 else
4072 slice = value::allocate (slice_type);
4073 array->contents_copy (slice, 0, offset,
4074 type_length_units (slice_type));
4077 slice->set_component_location (array);
4078 slice->set_offset (array->offset () + offset);
4081 return slice;
4084 /* See value.h. */
4086 struct value *
4087 value_literal_complex (struct value *arg1,
4088 struct value *arg2,
4089 struct type *type)
4091 struct value *val;
4092 struct type *real_type = type->target_type ();
4094 val = value::allocate (type);
4095 arg1 = value_cast (real_type, arg1);
4096 arg2 = value_cast (real_type, arg2);
4098 int len = real_type->length ();
4100 copy (arg1->contents (),
4101 val->contents_raw ().slice (0, len));
4102 copy (arg2->contents (),
4103 val->contents_raw ().slice (len, len));
4105 return val;
4108 /* See value.h. */
4110 struct value *
4111 value_real_part (struct value *value)
4113 struct type *type = check_typedef (value->type ());
4114 struct type *ttype = type->target_type ();
4116 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4117 return value_from_component (value, ttype, 0);
4120 /* See value.h. */
4122 struct value *
4123 value_imaginary_part (struct value *value)
4125 struct type *type = check_typedef (value->type ());
4126 struct type *ttype = type->target_type ();
4128 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4129 return value_from_component (value, ttype,
4130 check_typedef (ttype)->length ());
4133 /* Cast a value into the appropriate complex data type. */
4135 static struct value *
4136 cast_into_complex (struct type *type, struct value *val)
4138 struct type *real_type = type->target_type ();
4140 if (val->type ()->code () == TYPE_CODE_COMPLEX)
4142 struct type *val_real_type = val->type ()->target_type ();
4143 struct value *re_val = value::allocate (val_real_type);
4144 struct value *im_val = value::allocate (val_real_type);
4145 int len = val_real_type->length ();
4147 copy (val->contents ().slice (0, len),
4148 re_val->contents_raw ());
4149 copy (val->contents ().slice (len, len),
4150 im_val->contents_raw ());
4152 return value_literal_complex (re_val, im_val, type);
4154 else if (val->type ()->code () == TYPE_CODE_FLT
4155 || val->type ()->code () == TYPE_CODE_INT)
4156 return value_literal_complex (val,
4157 value::zero (real_type, not_lval),
4158 type);
4159 else
4160 error (_("cannot cast non-number to complex"));
4163 void _initialize_valops ();
4164 void
4165 _initialize_valops ()
4167 add_setshow_boolean_cmd ("overload-resolution", class_support,
4168 &overload_resolution, _("\
4169 Set overload resolution in evaluating C++ functions."), _("\
4170 Show overload resolution in evaluating C++ functions."),
4171 NULL, NULL,
4172 show_overload_resolution,
4173 &setlist, &showlist);
4174 overload_resolution = 1;