Automatic date update in version.in
[binutils-gdb.git] / gdb / valops.c
blob16cdf1f45530f4da2bf8fa4a185a5744a980fe39
1 /* Perform non-arithmetic operations on values, for GDB.
3 Copyright (C) 1986-2023 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, next_frame,
1248 toval->regnum (), type,
1249 fromval->contents ().data ());
1251 else
1252 put_frame_register_bytes (next_frame, value_reg,
1253 toval->offset (),
1254 fromval->contents ());
1257 gdb::observers::register_changed.notify
1258 (get_prev_frame_always (next_frame), value_reg);
1259 break;
1262 case lval_computed:
1264 const struct lval_funcs *funcs = toval->computed_funcs ();
1266 if (funcs->write != NULL)
1268 funcs->write (toval, fromval);
1269 break;
1272 [[fallthrough]];
1274 default:
1275 error (_("Left operand of assignment is not an lvalue."));
1278 /* Assigning to the stack pointer, frame pointer, and other
1279 (architecture and calling convention specific) registers may
1280 cause the frame cache and regcache to be out of date. Assigning to memory
1281 also can. We just do this on all assignments to registers or
1282 memory, for simplicity's sake; I doubt the slowdown matters. */
1283 switch (toval->lval ())
1285 case lval_memory:
1286 case lval_register:
1287 case lval_computed:
1289 gdb::observers::target_changed.notify
1290 (current_inferior ()->top_target ());
1292 /* Having destroyed the frame cache, restore the selected
1293 frame. */
1295 /* FIXME: cagney/2002-11-02: There has to be a better way of
1296 doing this. Instead of constantly saving/restoring the
1297 frame. Why not create a get_selected_frame() function that,
1298 having saved the selected frame's ID can automatically
1299 re-find the previously selected frame automatically. */
1302 frame_info_ptr fi = frame_find_by_id (old_frame);
1304 if (fi != NULL)
1305 select_frame (fi);
1308 break;
1309 default:
1310 break;
1313 /* If the field does not entirely fill a LONGEST, then zero the sign
1314 bits. If the field is signed, and is negative, then sign
1315 extend. */
1316 if ((toval->bitsize () > 0)
1317 && (toval->bitsize () < 8 * (int) sizeof (LONGEST)))
1319 LONGEST fieldval = value_as_long (fromval);
1320 LONGEST valmask = (((ULONGEST) 1) << toval->bitsize ()) - 1;
1322 fieldval &= valmask;
1323 if (!type->is_unsigned ()
1324 && (fieldval & (valmask ^ (valmask >> 1))))
1325 fieldval |= ~valmask;
1327 fromval = value_from_longest (type, fieldval);
1330 /* The return value is a copy of TOVAL so it shares its location
1331 information, but its contents are updated from FROMVAL. This
1332 implies the returned value is not lazy, even if TOVAL was. */
1333 val = toval->copy ();
1334 val->set_lazy (false);
1335 copy (fromval->contents (), val->contents_raw ());
1337 /* We copy over the enclosing type and pointed-to offset from FROMVAL
1338 in the case of pointer types. For object types, the enclosing type
1339 and embedded offset must *not* be copied: the target object referred
1340 to by TOVAL retains its original dynamic type after assignment. */
1341 if (type->code () == TYPE_CODE_PTR)
1343 val->set_enclosing_type (fromval->enclosing_type ());
1344 val->set_pointed_to_offset (fromval->pointed_to_offset ());
1347 return val;
1350 /* Extend a value ARG1 to COUNT repetitions of its type. */
1352 struct value *
1353 value_repeat (struct value *arg1, int count)
1355 struct value *val;
1357 if (arg1->lval () != lval_memory)
1358 error (_("Only values in memory can be extended with '@'."));
1359 if (count < 1)
1360 error (_("Invalid number %d of repetitions."), count);
1362 val = allocate_repeat_value (arg1->enclosing_type (), count);
1364 val->set_lval (lval_memory);
1365 val->set_address (arg1->address ());
1367 read_value_memory (val, 0, val->stack (), val->address (),
1368 val->contents_all_raw ().data (),
1369 type_length_units (val->enclosing_type ()));
1371 return val;
1374 struct value *
1375 value_of_variable (struct symbol *var, const struct block *b)
1377 frame_info_ptr frame = NULL;
1379 if (symbol_read_needs_frame (var))
1380 frame = get_selected_frame (_("No frame selected."));
1382 return read_var_value (var, b, frame);
1385 struct value *
1386 address_of_variable (struct symbol *var, const struct block *b)
1388 struct type *type = var->type ();
1389 struct value *val;
1391 /* Evaluate it first; if the result is a memory address, we're fine.
1392 Lazy evaluation pays off here. */
1394 val = value_of_variable (var, b);
1395 type = val->type ();
1397 if ((val->lval () == lval_memory && val->lazy ())
1398 || type->code () == TYPE_CODE_FUNC)
1400 CORE_ADDR addr = val->address ();
1402 return value_from_pointer (lookup_pointer_type (type), addr);
1405 /* Not a memory address; check what the problem was. */
1406 switch (val->lval ())
1408 case lval_register:
1410 const char *regname;
1412 frame_info_ptr frame = frame_find_by_id (val->next_frame_id ());
1413 gdb_assert (frame != nullptr);
1415 regname
1416 = gdbarch_register_name (get_frame_arch (frame), val->regnum ());
1417 gdb_assert (regname != nullptr && *regname != '\0');
1419 error (_("Address requested for identifier "
1420 "\"%s\" which is in register $%s"),
1421 var->print_name (), regname);
1422 break;
1425 default:
1426 error (_("Can't take address of \"%s\" which isn't an lvalue."),
1427 var->print_name ());
1428 break;
1431 return val;
1434 /* See value.h. */
1436 bool
1437 value_must_coerce_to_target (struct value *val)
1439 struct type *valtype;
1441 /* The only lval kinds which do not live in target memory. */
1442 if (val->lval () != not_lval
1443 && val->lval () != lval_internalvar
1444 && val->lval () != lval_xcallable)
1445 return false;
1447 valtype = check_typedef (val->type ());
1449 switch (valtype->code ())
1451 case TYPE_CODE_ARRAY:
1452 return valtype->is_vector () ? 0 : 1;
1453 case TYPE_CODE_STRING:
1454 return true;
1455 default:
1456 return false;
1460 /* Make sure that VAL lives in target memory if it's supposed to. For
1461 instance, strings are constructed as character arrays in GDB's
1462 storage, and this function copies them to the target. */
1464 struct value *
1465 value_coerce_to_target (struct value *val)
1467 LONGEST length;
1468 CORE_ADDR addr;
1470 if (!value_must_coerce_to_target (val))
1471 return val;
1473 length = check_typedef (val->type ())->length ();
1474 addr = allocate_space_in_inferior (length);
1475 write_memory (addr, val->contents ().data (), length);
1476 return value_at_lazy (val->type (), addr);
1479 /* Given a value which is an array, return a value which is a pointer
1480 to its first element, regardless of whether or not the array has a
1481 nonzero lower bound.
1483 FIXME: A previous comment here indicated that this routine should
1484 be substracting the array's lower bound. It's not clear to me that
1485 this is correct. Given an array subscripting operation, it would
1486 certainly work to do the adjustment here, essentially computing:
1488 (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
1490 However I believe a more appropriate and logical place to account
1491 for the lower bound is to do so in value_subscript, essentially
1492 computing:
1494 (&array[0] + ((index - lowerbound) * sizeof array[0]))
1496 As further evidence consider what would happen with operations
1497 other than array subscripting, where the caller would get back a
1498 value that had an address somewhere before the actual first element
1499 of the array, and the information about the lower bound would be
1500 lost because of the coercion to pointer type. */
1502 struct value *
1503 value_coerce_array (struct value *arg1)
1505 struct type *type = check_typedef (arg1->type ());
1507 /* If the user tries to do something requiring a pointer with an
1508 array that has not yet been pushed to the target, then this would
1509 be a good time to do so. */
1510 arg1 = value_coerce_to_target (arg1);
1512 if (arg1->lval () != lval_memory)
1513 error (_("Attempt to take address of value not located in memory."));
1515 return value_from_pointer (lookup_pointer_type (type->target_type ()),
1516 arg1->address ());
1519 /* Given a value which is a function, return a value which is a pointer
1520 to it. */
1522 struct value *
1523 value_coerce_function (struct value *arg1)
1525 struct value *retval;
1527 if (arg1->lval () != lval_memory)
1528 error (_("Attempt to take address of value not located in memory."));
1530 retval = value_from_pointer (lookup_pointer_type (arg1->type ()),
1531 arg1->address ());
1532 return retval;
1535 /* Return a pointer value for the object for which ARG1 is the
1536 contents. */
1538 struct value *
1539 value_addr (struct value *arg1)
1541 struct value *arg2;
1542 struct type *type = check_typedef (arg1->type ());
1544 if (TYPE_IS_REFERENCE (type))
1546 if (arg1->bits_synthetic_pointer (arg1->embedded_offset (),
1547 TARGET_CHAR_BIT * type->length ()))
1548 arg1 = coerce_ref (arg1);
1549 else
1551 /* Copy the value, but change the type from (T&) to (T*). We
1552 keep the same location information, which is efficient, and
1553 allows &(&X) to get the location containing the reference.
1554 Do the same to its enclosing type for consistency. */
1555 struct type *type_ptr
1556 = lookup_pointer_type (type->target_type ());
1557 struct type *enclosing_type
1558 = check_typedef (arg1->enclosing_type ());
1559 struct type *enclosing_type_ptr
1560 = lookup_pointer_type (enclosing_type->target_type ());
1562 arg2 = arg1->copy ();
1563 arg2->deprecated_set_type (type_ptr);
1564 arg2->set_enclosing_type (enclosing_type_ptr);
1566 return arg2;
1569 if (type->code () == TYPE_CODE_FUNC)
1570 return value_coerce_function (arg1);
1572 /* If this is an array that has not yet been pushed to the target,
1573 then this would be a good time to force it to memory. */
1574 arg1 = value_coerce_to_target (arg1);
1576 if (arg1->lval () != lval_memory)
1577 error (_("Attempt to take address of value not located in memory."));
1579 /* Get target memory address. */
1580 arg2 = value_from_pointer (lookup_pointer_type (arg1->type ()),
1581 (arg1->address ()
1582 + arg1->embedded_offset ()));
1584 /* This may be a pointer to a base subobject; so remember the
1585 full derived object's type ... */
1586 arg2->set_enclosing_type (lookup_pointer_type (arg1->enclosing_type ()));
1587 /* ... and also the relative position of the subobject in the full
1588 object. */
1589 arg2->set_pointed_to_offset (arg1->embedded_offset ());
1590 return arg2;
1593 /* Return a reference value for the object for which ARG1 is the
1594 contents. */
1596 struct value *
1597 value_ref (struct value *arg1, enum type_code refcode)
1599 struct value *arg2;
1600 struct type *type = check_typedef (arg1->type ());
1602 gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1604 if ((type->code () == TYPE_CODE_REF
1605 || type->code () == TYPE_CODE_RVALUE_REF)
1606 && type->code () == refcode)
1607 return arg1;
1609 arg2 = value_addr (arg1);
1610 arg2->deprecated_set_type (lookup_reference_type (type, refcode));
1611 return arg2;
1614 /* Given a value of a pointer type, apply the C unary * operator to
1615 it. */
1617 struct value *
1618 value_ind (struct value *arg1)
1620 struct type *base_type;
1621 struct value *arg2;
1623 arg1 = coerce_array (arg1);
1625 base_type = check_typedef (arg1->type ());
1627 if (arg1->lval () == lval_computed)
1629 const struct lval_funcs *funcs = arg1->computed_funcs ();
1631 if (funcs->indirect)
1633 struct value *result = funcs->indirect (arg1);
1635 if (result)
1636 return result;
1640 if (base_type->code () == TYPE_CODE_PTR)
1642 struct type *enc_type;
1644 /* We may be pointing to something embedded in a larger object.
1645 Get the real type of the enclosing object. */
1646 enc_type = check_typedef (arg1->enclosing_type ());
1647 enc_type = enc_type->target_type ();
1649 CORE_ADDR base_addr;
1650 if (check_typedef (enc_type)->code () == TYPE_CODE_FUNC
1651 || check_typedef (enc_type)->code () == TYPE_CODE_METHOD)
1653 /* For functions, go through find_function_addr, which knows
1654 how to handle function descriptors. */
1655 base_addr = find_function_addr (arg1, NULL);
1657 else
1659 /* Retrieve the enclosing object pointed to. */
1660 base_addr = (value_as_address (arg1)
1661 - arg1->pointed_to_offset ());
1663 arg2 = value_at_lazy (enc_type, base_addr);
1664 enc_type = arg2->type ();
1665 return readjust_indirect_value_type (arg2, enc_type, base_type,
1666 arg1, base_addr);
1669 error (_("Attempt to take contents of a non-pointer value."));
1672 /* Create a value for an array by allocating space in GDB, copying the
1673 data into that space, and then setting up an array value.
1675 The array bounds are set from LOWBOUND and the size of ELEMVEC, and
1676 the array is populated from the values passed in ELEMVEC.
1678 The element type of the array is inherited from the type of the
1679 first element, and all elements must have the same size (though we
1680 don't currently enforce any restriction on their types). */
1682 struct value *
1683 value_array (int lowbound, gdb::array_view<struct value *> elemvec)
1685 int idx;
1686 ULONGEST typelength;
1687 struct value *val;
1688 struct type *arraytype;
1690 /* Validate that the bounds are reasonable and that each of the
1691 elements have the same size. */
1693 typelength = type_length_units (elemvec[0]->enclosing_type ());
1694 for (struct value *other : elemvec.slice (1))
1696 if (type_length_units (other->enclosing_type ()) != typelength)
1698 error (_("array elements must all be the same size"));
1702 arraytype = lookup_array_range_type (elemvec[0]->enclosing_type (),
1703 lowbound,
1704 lowbound + elemvec.size () - 1);
1706 if (!current_language->c_style_arrays_p ())
1708 val = value::allocate (arraytype);
1709 for (idx = 0; idx < elemvec.size (); idx++)
1710 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1711 return val;
1714 /* Allocate space to store the array, and then initialize it by
1715 copying in each element. */
1717 val = value::allocate (arraytype);
1718 for (idx = 0; idx < elemvec.size (); idx++)
1719 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1720 return val;
1723 /* See value.h. */
1725 struct value *
1726 value_cstring (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1728 struct value *val;
1729 int lowbound = current_language->string_lower_bound ();
1730 ssize_t highbound = count + 1;
1731 struct type *stringtype
1732 = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1734 val = value::allocate (stringtype);
1735 ssize_t len = count * char_type->length ();
1736 memcpy (val->contents_raw ().data (), ptr, len);
1737 /* Write the terminating null-character. */
1738 memset (val->contents_raw ().data () + len, 0, char_type->length ());
1739 return val;
1742 /* See value.h. */
1744 struct value *
1745 value_string (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1747 struct value *val;
1748 int lowbound = current_language->string_lower_bound ();
1749 ssize_t highbound = count;
1750 struct type *stringtype
1751 = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1753 val = value::allocate (stringtype);
1754 ssize_t len = count * char_type->length ();
1755 memcpy (val->contents_raw ().data (), ptr, len);
1756 return val;
1760 /* See if we can pass arguments in T2 to a function which takes arguments
1761 of types T1. T1 is a list of NARGS arguments, and T2 is an array_view
1762 of the values we're trying to pass. If some arguments need coercion of
1763 some sort, then the coerced values are written into T2. Return value is
1764 0 if the arguments could be matched, or the position at which they
1765 differ if not.
1767 STATICP is nonzero if the T1 argument list came from a static
1768 member function. T2 must still include the ``this'' pointer, but
1769 it will be skipped.
1771 For non-static member functions, we ignore the first argument,
1772 which is the type of the instance variable. This is because we
1773 want to handle calls with objects from derived classes. This is
1774 not entirely correct: we should actually check to make sure that a
1775 requested operation is type secure, shouldn't we? FIXME. */
1777 static int
1778 typecmp (bool staticp, bool varargs, int nargs,
1779 struct field t1[], gdb::array_view<value *> t2)
1781 int i;
1783 /* Skip ``this'' argument if applicable. T2 will always include
1784 THIS. */
1785 if (staticp)
1786 t2 = t2.slice (1);
1788 for (i = 0;
1789 (i < nargs) && t1[i].type ()->code () != TYPE_CODE_VOID;
1790 i++)
1792 struct type *tt1, *tt2;
1794 if (i == t2.size ())
1795 return i + 1;
1797 tt1 = check_typedef (t1[i].type ());
1798 tt2 = check_typedef (t2[i]->type ());
1800 if (TYPE_IS_REFERENCE (tt1)
1801 /* We should be doing hairy argument matching, as below. */
1802 && (check_typedef (tt1->target_type ())->code ()
1803 == tt2->code ()))
1805 if (tt2->code () == TYPE_CODE_ARRAY)
1806 t2[i] = value_coerce_array (t2[i]);
1807 else
1808 t2[i] = value_ref (t2[i], tt1->code ());
1809 continue;
1812 /* djb - 20000715 - Until the new type structure is in the
1813 place, and we can attempt things like implicit conversions,
1814 we need to do this so you can take something like a map<const
1815 char *>, and properly access map["hello"], because the
1816 argument to [] will be a reference to a pointer to a char,
1817 and the argument will be a pointer to a char. */
1818 while (TYPE_IS_REFERENCE (tt1) || tt1->code () == TYPE_CODE_PTR)
1820 tt1 = check_typedef ( tt1->target_type () );
1822 while (tt2->code () == TYPE_CODE_ARRAY
1823 || tt2->code () == TYPE_CODE_PTR
1824 || TYPE_IS_REFERENCE (tt2))
1826 tt2 = check_typedef (tt2->target_type ());
1828 if (tt1->code () == tt2->code ())
1829 continue;
1830 /* Array to pointer is a `trivial conversion' according to the
1831 ARM. */
1833 /* We should be doing much hairier argument matching (see
1834 section 13.2 of the ARM), but as a quick kludge, just check
1835 for the same type code. */
1836 if (t1[i].type ()->code () != t2[i]->type ()->code ())
1837 return i + 1;
1839 if (varargs || i == t2.size ())
1840 return 0;
1841 return i + 1;
1844 /* Helper class for search_struct_field that keeps track of found
1845 results and possibly throws an exception if the search yields
1846 ambiguous results. See search_struct_field for description of
1847 LOOKING_FOR_BASECLASS. */
1849 struct struct_field_searcher
1851 /* A found field. */
1852 struct found_field
1854 /* Path to the structure where the field was found. */
1855 std::vector<struct type *> path;
1857 /* The field found. */
1858 struct value *field_value;
1861 /* See corresponding fields for description of parameters. */
1862 struct_field_searcher (const char *name,
1863 struct type *outermost_type,
1864 bool looking_for_baseclass)
1865 : m_name (name),
1866 m_looking_for_baseclass (looking_for_baseclass),
1867 m_outermost_type (outermost_type)
1871 /* The search entry point. If LOOKING_FOR_BASECLASS is true and the
1872 base class search yields ambiguous results, this throws an
1873 exception. If LOOKING_FOR_BASECLASS is false, the found fields
1874 are accumulated and the caller (search_struct_field) takes care
1875 of throwing an error if the field search yields ambiguous
1876 results. The latter is done that way so that the error message
1877 can include a list of all the found candidates. */
1878 void search (struct value *arg, LONGEST offset, struct type *type);
1880 const std::vector<found_field> &fields ()
1882 return m_fields;
1885 struct value *baseclass ()
1887 return m_baseclass;
1890 private:
1891 /* Update results to include V, a found field/baseclass. */
1892 void update_result (struct value *v, LONGEST boffset);
1894 /* The name of the field/baseclass we're searching for. */
1895 const char *m_name;
1897 /* Whether we're looking for a baseclass, or a field. */
1898 const bool m_looking_for_baseclass;
1900 /* The offset of the baseclass containing the field/baseclass we
1901 last recorded. */
1902 LONGEST m_last_boffset = 0;
1904 /* If looking for a baseclass, then the result is stored here. */
1905 struct value *m_baseclass = nullptr;
1907 /* When looking for fields, the found candidates are stored
1908 here. */
1909 std::vector<found_field> m_fields;
1911 /* The type of the initial type passed to search_struct_field; this
1912 is used for error reporting when the lookup is ambiguous. */
1913 struct type *m_outermost_type;
1915 /* The full path to the struct being inspected. E.g. for field 'x'
1916 defined in class B inherited by class A, we have A and B pushed
1917 on the path. */
1918 std::vector <struct type *> m_struct_path;
1921 void
1922 struct_field_searcher::update_result (struct value *v, LONGEST boffset)
1924 if (v != NULL)
1926 if (m_looking_for_baseclass)
1928 if (m_baseclass != nullptr
1929 /* The result is not ambiguous if all the classes that are
1930 found occupy the same space. */
1931 && m_last_boffset != boffset)
1932 error (_("base class '%s' is ambiguous in type '%s'"),
1933 m_name, TYPE_SAFE_NAME (m_outermost_type));
1935 m_baseclass = v;
1936 m_last_boffset = boffset;
1938 else
1940 /* The field is not ambiguous if it occupies the same
1941 space. */
1942 if (m_fields.empty () || m_last_boffset != boffset)
1943 m_fields.push_back ({m_struct_path, v});
1944 else
1946 /*Fields can occupy the same space and have the same name (be
1947 ambiguous). This can happen when fields in two different base
1948 classes are marked [[no_unique_address]] and have the same name.
1949 The C++ standard says that such fields can only occupy the same
1950 space if they are of different type, but we don't rely on that in
1951 the following code. */
1952 bool ambiguous = false, insert = true;
1953 for (const found_field &field: m_fields)
1955 if(field.path.back () != m_struct_path.back ())
1957 /* Same boffset points to members of different classes.
1958 We have found an ambiguity and should record it. */
1959 ambiguous = true;
1961 else
1963 /* We don't need to insert this value again, because a
1964 non-ambiguous path already leads to it. */
1965 insert = false;
1966 break;
1969 if (ambiguous && insert)
1970 m_fields.push_back ({m_struct_path, v});
1976 /* A helper for search_struct_field. This does all the work; most
1977 arguments are as passed to search_struct_field. */
1979 void
1980 struct_field_searcher::search (struct value *arg1, LONGEST offset,
1981 struct type *type)
1983 int i;
1984 int nbases;
1986 m_struct_path.push_back (type);
1987 SCOPE_EXIT { m_struct_path.pop_back (); };
1989 type = check_typedef (type);
1990 nbases = TYPE_N_BASECLASSES (type);
1992 if (!m_looking_for_baseclass)
1993 for (i = type->num_fields () - 1; i >= nbases; i--)
1995 const char *t_field_name = type->field (i).name ();
1997 if (t_field_name && (strcmp_iw (t_field_name, m_name) == 0))
1999 struct value *v;
2001 if (type->field (i).is_static ())
2002 v = value_static_field (type, i);
2003 else
2004 v = arg1->primitive_field (offset, i, type);
2006 update_result (v, offset);
2007 return;
2010 if (t_field_name
2011 && t_field_name[0] == '\0')
2013 struct type *field_type = type->field (i).type ();
2015 if (field_type->code () == TYPE_CODE_UNION
2016 || field_type->code () == TYPE_CODE_STRUCT)
2018 /* Look for a match through the fields of an anonymous
2019 union, or anonymous struct. C++ provides anonymous
2020 unions.
2022 In the GNU Chill (now deleted from GDB)
2023 implementation of variant record types, each
2024 <alternative field> has an (anonymous) union type,
2025 each member of the union represents a <variant
2026 alternative>. Each <variant alternative> is
2027 represented as a struct, with a member for each
2028 <variant field>. */
2030 LONGEST new_offset = offset;
2032 /* This is pretty gross. In G++, the offset in an
2033 anonymous union is relative to the beginning of the
2034 enclosing struct. In the GNU Chill (now deleted
2035 from GDB) implementation of variant records, the
2036 bitpos is zero in an anonymous union field, so we
2037 have to add the offset of the union here. */
2038 if (field_type->code () == TYPE_CODE_STRUCT
2039 || (field_type->num_fields () > 0
2040 && field_type->field (0).loc_bitpos () == 0))
2041 new_offset += type->field (i).loc_bitpos () / 8;
2043 search (arg1, new_offset, field_type);
2048 for (i = 0; i < nbases; i++)
2050 struct value *v = NULL;
2051 struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
2052 /* If we are looking for baseclasses, this is what we get when
2053 we hit them. But it could happen that the base part's member
2054 name is not yet filled in. */
2055 int found_baseclass = (m_looking_for_baseclass
2056 && TYPE_BASECLASS_NAME (type, i) != NULL
2057 && (strcmp_iw (m_name, basetype->name ()) == 0));
2058 LONGEST boffset = arg1->embedded_offset () + offset;
2060 if (BASETYPE_VIA_VIRTUAL (type, i))
2062 struct value *v2;
2064 boffset = baseclass_offset (type, i,
2065 arg1->contents_for_printing ().data (),
2066 arg1->embedded_offset () + offset,
2067 arg1->address (),
2068 arg1);
2070 /* The virtual base class pointer might have been clobbered
2071 by the user program. Make sure that it still points to a
2072 valid memory location. */
2074 boffset += arg1->embedded_offset () + offset;
2075 if (boffset < 0
2076 || boffset >= arg1->enclosing_type ()->length ())
2078 CORE_ADDR base_addr;
2080 base_addr = arg1->address () + boffset;
2081 v2 = value_at_lazy (basetype, base_addr);
2082 if (target_read_memory (base_addr,
2083 v2->contents_raw ().data (),
2084 v2->type ()->length ()) != 0)
2085 error (_("virtual baseclass botch"));
2087 else
2089 v2 = arg1->copy ();
2090 v2->deprecated_set_type (basetype);
2091 v2->set_embedded_offset (boffset);
2094 if (found_baseclass)
2095 v = v2;
2096 else
2097 search (v2, 0, TYPE_BASECLASS (type, i));
2099 else if (found_baseclass)
2100 v = arg1->primitive_field (offset, i, type);
2101 else
2103 search (arg1, offset + TYPE_BASECLASS_BITPOS (type, i) / 8,
2104 basetype);
2107 update_result (v, boffset);
2111 /* Helper function used by value_struct_elt to recurse through
2112 baseclasses. Look for a field NAME in ARG1. Search in it assuming
2113 it has (class) type TYPE. If found, return value, else return NULL.
2115 If LOOKING_FOR_BASECLASS, then instead of looking for struct
2116 fields, look for a baseclass named NAME. */
2118 static struct value *
2119 search_struct_field (const char *name, struct value *arg1,
2120 struct type *type, int looking_for_baseclass)
2122 struct_field_searcher searcher (name, type, looking_for_baseclass);
2124 searcher.search (arg1, 0, type);
2126 if (!looking_for_baseclass)
2128 const auto &fields = searcher.fields ();
2130 if (fields.empty ())
2131 return nullptr;
2132 else if (fields.size () == 1)
2133 return fields[0].field_value;
2134 else
2136 std::string candidates;
2138 for (auto &&candidate : fields)
2140 gdb_assert (!candidate.path.empty ());
2142 struct type *field_type = candidate.field_value->type ();
2143 struct type *struct_type = candidate.path.back ();
2145 std::string path;
2146 bool first = true;
2147 for (struct type *t : candidate.path)
2149 if (first)
2150 first = false;
2151 else
2152 path += " -> ";
2153 path += t->name ();
2156 candidates += string_printf ("\n '%s %s::%s' (%s)",
2157 TYPE_SAFE_NAME (field_type),
2158 TYPE_SAFE_NAME (struct_type),
2159 name,
2160 path.c_str ());
2163 error (_("Request for member '%s' is ambiguous in type '%s'."
2164 " Candidates are:%s"),
2165 name, TYPE_SAFE_NAME (type),
2166 candidates.c_str ());
2169 else
2170 return searcher.baseclass ();
2173 /* Helper function used by value_struct_elt to recurse through
2174 baseclasses. Look for a field NAME in ARG1. Adjust the address of
2175 ARG1 by OFFSET bytes, and search in it assuming it has (class) type
2176 TYPE.
2178 ARGS is an optional array of argument values used to help finding NAME.
2179 The contents of ARGS can be adjusted if type coercion is required in
2180 order to find a matching NAME.
2182 If found, return value, else if name matched and args not return
2183 (value) -1, else return NULL. */
2185 static struct value *
2186 search_struct_method (const char *name, struct value **arg1p,
2187 std::optional<gdb::array_view<value *>> args,
2188 LONGEST offset, int *static_memfuncp,
2189 struct type *type)
2191 int i;
2192 struct value *v;
2193 int name_matched = 0;
2195 type = check_typedef (type);
2196 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2198 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2200 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2202 int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2203 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2205 name_matched = 1;
2206 check_stub_method_group (type, i);
2207 if (j > 0 && !args.has_value ())
2208 error (_("cannot resolve overloaded method "
2209 "`%s': no arguments supplied"), name);
2210 else if (j == 0 && !args.has_value ())
2212 v = value_fn_field (arg1p, f, j, type, offset);
2213 if (v != NULL)
2214 return v;
2216 else
2217 while (j >= 0)
2219 gdb_assert (args.has_value ());
2220 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2221 TYPE_FN_FIELD_TYPE (f, j)->has_varargs (),
2222 TYPE_FN_FIELD_TYPE (f, j)->num_fields (),
2223 TYPE_FN_FIELD_ARGS (f, j), *args))
2225 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2226 return value_virtual_fn_field (arg1p, f, j,
2227 type, offset);
2228 if (TYPE_FN_FIELD_STATIC_P (f, j)
2229 && static_memfuncp)
2230 *static_memfuncp = 1;
2231 v = value_fn_field (arg1p, f, j, type, offset);
2232 if (v != NULL)
2233 return v;
2235 j--;
2240 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2242 LONGEST base_offset;
2243 LONGEST this_offset;
2245 if (BASETYPE_VIA_VIRTUAL (type, i))
2247 struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2248 struct value *base_val;
2249 const gdb_byte *base_valaddr;
2251 /* The virtual base class pointer might have been
2252 clobbered by the user program. Make sure that it
2253 still points to a valid memory location. */
2255 if (offset < 0 || offset >= type->length ())
2257 CORE_ADDR address;
2259 gdb::byte_vector tmp (baseclass->length ());
2260 address = (*arg1p)->address ();
2262 if (target_read_memory (address + offset,
2263 tmp.data (), baseclass->length ()) != 0)
2264 error (_("virtual baseclass botch"));
2266 base_val = value_from_contents_and_address (baseclass,
2267 tmp.data (),
2268 address + offset);
2269 base_valaddr = base_val->contents_for_printing ().data ();
2270 this_offset = 0;
2272 else
2274 base_val = *arg1p;
2275 base_valaddr = (*arg1p)->contents_for_printing ().data ();
2276 this_offset = offset;
2279 base_offset = baseclass_offset (type, i, base_valaddr,
2280 this_offset, base_val->address (),
2281 base_val);
2283 else
2285 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2287 v = search_struct_method (name, arg1p, args, base_offset + offset,
2288 static_memfuncp, TYPE_BASECLASS (type, i));
2289 if (v == (struct value *) - 1)
2291 name_matched = 1;
2293 else if (v)
2295 /* FIXME-bothner: Why is this commented out? Why is it here? */
2296 /* *arg1p = arg1_tmp; */
2297 return v;
2300 if (name_matched)
2301 return (struct value *) - 1;
2302 else
2303 return NULL;
2306 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2307 extract the component named NAME from the ultimate target
2308 structure/union and return it as a value with its appropriate type.
2309 ERR is used in the error message if *ARGP's type is wrong.
2311 C++: ARGS is a list of argument types to aid in the selection of
2312 an appropriate method. Also, handle derived types.
2314 STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2315 where the truthvalue of whether the function that was resolved was
2316 a static member function or not is stored.
2318 ERR is an error message to be printed in case the field is not
2319 found. */
2321 struct value *
2322 value_struct_elt (struct value **argp,
2323 std::optional<gdb::array_view<value *>> args,
2324 const char *name, int *static_memfuncp, const char *err)
2326 struct type *t;
2327 struct value *v;
2329 *argp = coerce_array (*argp);
2331 t = check_typedef ((*argp)->type ());
2333 /* Follow pointers until we get to a non-pointer. */
2335 while (t->is_pointer_or_reference ())
2337 *argp = value_ind (*argp);
2338 /* Don't coerce fn pointer to fn and then back again! */
2339 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2340 *argp = coerce_array (*argp);
2341 t = check_typedef ((*argp)->type ());
2344 if (t->code () != TYPE_CODE_STRUCT
2345 && t->code () != TYPE_CODE_UNION)
2346 error (_("Attempt to extract a component of a value that is not a %s."),
2347 err);
2349 /* Assume it's not, unless we see that it is. */
2350 if (static_memfuncp)
2351 *static_memfuncp = 0;
2353 if (!args.has_value ())
2355 /* if there are no arguments ...do this... */
2357 /* Try as a field first, because if we succeed, there is less
2358 work to be done. */
2359 v = search_struct_field (name, *argp, t, 0);
2360 if (v)
2361 return v;
2363 if (current_language->la_language == language_fortran)
2365 /* If it is not a field it is the type name of an inherited
2366 structure. */
2367 v = search_struct_field (name, *argp, t, 1);
2368 if (v)
2369 return v;
2372 /* C++: If it was not found as a data field, then try to
2373 return it as a pointer to a method. */
2374 v = search_struct_method (name, argp, args, 0,
2375 static_memfuncp, t);
2377 if (v == (struct value *) - 1)
2378 error (_("Cannot take address of method %s."), name);
2379 else if (v == 0)
2381 if (TYPE_NFN_FIELDS (t))
2382 error (_("There is no member or method named %s."), name);
2383 else
2384 error (_("There is no member named %s."), name);
2386 return v;
2389 v = search_struct_method (name, argp, args, 0,
2390 static_memfuncp, t);
2392 if (v == (struct value *) - 1)
2394 error (_("One of the arguments you tried to pass to %s could not "
2395 "be converted to what the function wants."), name);
2397 else if (v == 0)
2399 /* See if user tried to invoke data as function. If so, hand it
2400 back. If it's not callable (i.e., a pointer to function),
2401 gdb should give an error. */
2402 v = search_struct_field (name, *argp, t, 0);
2403 /* If we found an ordinary field, then it is not a method call.
2404 So, treat it as if it were a static member function. */
2405 if (v && static_memfuncp)
2406 *static_memfuncp = 1;
2409 if (!v)
2410 throw_error (NOT_FOUND_ERROR,
2411 _("Structure has no component named %s."), name);
2412 return v;
2415 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2416 to a structure or union, extract and return its component (field) of
2417 type FTYPE at the specified BITPOS.
2418 Throw an exception on error. */
2420 struct value *
2421 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2422 const char *err)
2424 struct type *t;
2425 int i;
2427 *argp = coerce_array (*argp);
2429 t = check_typedef ((*argp)->type ());
2431 while (t->is_pointer_or_reference ())
2433 *argp = value_ind (*argp);
2434 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2435 *argp = coerce_array (*argp);
2436 t = check_typedef ((*argp)->type ());
2439 if (t->code () != TYPE_CODE_STRUCT
2440 && t->code () != TYPE_CODE_UNION)
2441 error (_("Attempt to extract a component of a value that is not a %s."),
2442 err);
2444 for (i = TYPE_N_BASECLASSES (t); i < t->num_fields (); i++)
2446 if (!t->field (i).is_static ()
2447 && bitpos == t->field (i).loc_bitpos ()
2448 && types_equal (ftype, t->field (i).type ()))
2449 return (*argp)->primitive_field (0, i, t);
2452 error (_("No field with matching bitpos and type."));
2454 /* Never hit. */
2455 return NULL;
2458 /* Search through the methods of an object (and its bases) to find a
2459 specified method. Return a reference to the fn_field list METHODS of
2460 overloaded instances defined in the source language. If available
2461 and matching, a vector of matching xmethods defined in extension
2462 languages are also returned in XMETHODS.
2464 Helper function for value_find_oload_list.
2465 ARGP is a pointer to a pointer to a value (the object).
2466 METHOD is a string containing the method name.
2467 OFFSET is the offset within the value.
2468 TYPE is the assumed type of the object.
2469 METHODS is a pointer to the matching overloaded instances defined
2470 in the source language. Since this is a recursive function,
2471 *METHODS should be set to NULL when calling this function.
2472 NUM_FNS is the number of overloaded instances. *NUM_FNS should be set to
2473 0 when calling this function.
2474 XMETHODS is the vector of matching xmethod workers. *XMETHODS
2475 should also be set to NULL when calling this function.
2476 BASETYPE is set to the actual type of the subobject where the
2477 method is found.
2478 BOFFSET is the offset of the base subobject where the method is found. */
2480 static void
2481 find_method_list (struct value **argp, const char *method,
2482 LONGEST offset, struct type *type,
2483 gdb::array_view<fn_field> *methods,
2484 std::vector<xmethod_worker_up> *xmethods,
2485 struct type **basetype, LONGEST *boffset)
2487 int i;
2488 struct fn_field *f = NULL;
2490 gdb_assert (methods != NULL && xmethods != NULL);
2491 type = check_typedef (type);
2493 /* First check in object itself.
2494 This function is called recursively to search through base classes.
2495 If there is a source method match found at some stage, then we need not
2496 look for source methods in consequent recursive calls. */
2497 if (methods->empty ())
2499 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2501 /* pai: FIXME What about operators and type conversions? */
2502 const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2504 if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2506 int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2507 f = TYPE_FN_FIELDLIST1 (type, i);
2508 *methods = gdb::make_array_view (f, len);
2510 *basetype = type;
2511 *boffset = offset;
2513 /* Resolve any stub methods. */
2514 check_stub_method_group (type, i);
2516 break;
2521 /* Unlike source methods, xmethods can be accumulated over successive
2522 recursive calls. In other words, an xmethod named 'm' in a class
2523 will not hide an xmethod named 'm' in its base class(es). We want
2524 it to be this way because xmethods are after all convenience functions
2525 and hence there is no point restricting them with something like method
2526 hiding. Moreover, if hiding is done for xmethods as well, then we will
2527 have to provide a mechanism to un-hide (like the 'using' construct). */
2528 get_matching_xmethod_workers (type, method, xmethods);
2530 /* If source methods are not found in current class, look for them in the
2531 base classes. We also have to go through the base classes to gather
2532 extension methods. */
2533 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2535 LONGEST base_offset;
2537 if (BASETYPE_VIA_VIRTUAL (type, i))
2539 base_offset = baseclass_offset (type, i,
2540 (*argp)->contents_for_printing ().data (),
2541 (*argp)->offset () + offset,
2542 (*argp)->address (), *argp);
2544 else /* Non-virtual base, simply use bit position from debug
2545 info. */
2547 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2550 find_method_list (argp, method, base_offset + offset,
2551 TYPE_BASECLASS (type, i), methods,
2552 xmethods, basetype, boffset);
2556 /* Return the list of overloaded methods of a specified name. The methods
2557 could be those GDB finds in the binary, or xmethod. Methods found in
2558 the binary are returned in METHODS, and xmethods are returned in
2559 XMETHODS.
2561 ARGP is a pointer to a pointer to a value (the object).
2562 METHOD is the method name.
2563 OFFSET is the offset within the value contents.
2564 METHODS is the list of matching overloaded instances defined in
2565 the source language.
2566 XMETHODS is the vector of matching xmethod workers defined in
2567 extension languages.
2568 BASETYPE is set to the type of the base subobject that defines the
2569 method.
2570 BOFFSET is the offset of the base subobject which defines the method. */
2572 static void
2573 value_find_oload_method_list (struct value **argp, const char *method,
2574 LONGEST offset,
2575 gdb::array_view<fn_field> *methods,
2576 std::vector<xmethod_worker_up> *xmethods,
2577 struct type **basetype, LONGEST *boffset)
2579 struct type *t;
2581 t = check_typedef ((*argp)->type ());
2583 /* Code snarfed from value_struct_elt. */
2584 while (t->is_pointer_or_reference ())
2586 *argp = value_ind (*argp);
2587 /* Don't coerce fn pointer to fn and then back again! */
2588 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2589 *argp = coerce_array (*argp);
2590 t = check_typedef ((*argp)->type ());
2593 if (t->code () != TYPE_CODE_STRUCT
2594 && t->code () != TYPE_CODE_UNION)
2595 error (_("Attempt to extract a component of a "
2596 "value that is not a struct or union"));
2598 gdb_assert (methods != NULL && xmethods != NULL);
2600 /* Clear the lists. */
2601 *methods = {};
2602 xmethods->clear ();
2604 find_method_list (argp, method, 0, t, methods, xmethods,
2605 basetype, boffset);
2608 /* Helper function for find_overload_match. If no matches were
2609 found, this function may generate a hint for the user that some
2610 of the relevant types are incomplete, so GDB can't evaluate
2611 type relationships to properly evaluate overloads.
2613 If no incomplete types are present, an empty string is returned. */
2614 static std::string
2615 incomplete_type_hint (gdb::array_view<value *> args)
2617 int incomplete_types = 0;
2618 std::string incomplete_arg_names;
2619 for (const struct value *arg : args)
2621 struct type *t = arg->type ();
2622 while (t->code () == TYPE_CODE_PTR)
2623 t = t->target_type ();
2624 if (t->is_stub ())
2626 string_file buffer;
2627 if (incomplete_types > 0)
2628 incomplete_arg_names += ", ";
2630 current_language->print_type (arg->type (), "", &buffer,
2631 -1, 0, &type_print_raw_options);
2633 incomplete_types++;
2634 incomplete_arg_names += buffer.string ();
2637 std::string hint;
2638 if (incomplete_types > 1)
2639 hint = string_printf (_("\nThe types: '%s' aren't fully known to GDB."
2640 " Please cast them directly to the desired"
2641 " typed in the function call."),
2642 incomplete_arg_names.c_str ());
2643 else if (incomplete_types == 1)
2644 hint = string_printf (_("\nThe type: '%s' isn't fully known to GDB."
2645 " Please cast it directly to the desired"
2646 " typed in the function call."),
2647 incomplete_arg_names.c_str ());
2648 return hint;
2651 /* Given an array of arguments (ARGS) (which includes an entry for
2652 "this" in the case of C++ methods), the NAME of a function, and
2653 whether it's a method or not (METHOD), find the best function that
2654 matches on the argument types according to the overload resolution
2655 rules.
2657 METHOD can be one of three values:
2658 NON_METHOD for non-member functions.
2659 METHOD: for member functions.
2660 BOTH: used for overload resolution of operators where the
2661 candidates are expected to be either member or non member
2662 functions. In this case the first argument ARGTYPES
2663 (representing 'this') is expected to be a reference to the
2664 target object, and will be dereferenced when attempting the
2665 non-member search.
2667 In the case of class methods, the parameter OBJ is an object value
2668 in which to search for overloaded methods.
2670 In the case of non-method functions, the parameter FSYM is a symbol
2671 corresponding to one of the overloaded functions.
2673 Return value is an integer: 0 -> good match, 10 -> debugger applied
2674 non-standard coercions, 100 -> incompatible.
2676 If a method is being searched for, VALP will hold the value.
2677 If a non-method is being searched for, SYMP will hold the symbol
2678 for it.
2680 If a method is being searched for, and it is a static method,
2681 then STATICP will point to a non-zero value.
2683 If NO_ADL argument dependent lookup is disabled. This is used to prevent
2684 ADL overload candidates when performing overload resolution for a fully
2685 qualified name.
2687 If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2688 read while picking the best overload match (it may be all zeroes and thus
2689 not have a vtable pointer), in which case skip virtual function lookup.
2690 This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2691 the result type.
2693 Note: This function does *not* check the value of
2694 overload_resolution. Caller must check it to see whether overload
2695 resolution is permitted. */
2698 find_overload_match (gdb::array_view<value *> args,
2699 const char *name, enum oload_search_type method,
2700 struct value **objp, struct symbol *fsym,
2701 struct value **valp, struct symbol **symp,
2702 int *staticp, const int no_adl,
2703 const enum noside noside)
2705 struct value *obj = (objp ? *objp : NULL);
2706 struct type *obj_type = obj ? obj->type () : NULL;
2707 /* Index of best overloaded function. */
2708 int func_oload_champ = -1;
2709 int method_oload_champ = -1;
2710 int src_method_oload_champ = -1;
2711 int ext_method_oload_champ = -1;
2713 /* The measure for the current best match. */
2714 badness_vector method_badness;
2715 badness_vector func_badness;
2716 badness_vector ext_method_badness;
2717 badness_vector src_method_badness;
2719 struct value *temp = obj;
2720 /* For methods, the list of overloaded methods. */
2721 gdb::array_view<fn_field> methods;
2722 /* For non-methods, the list of overloaded function symbols. */
2723 std::vector<symbol *> functions;
2724 /* For xmethods, the vector of xmethod workers. */
2725 std::vector<xmethod_worker_up> xmethods;
2726 struct type *basetype = NULL;
2727 LONGEST boffset;
2729 const char *obj_type_name = NULL;
2730 const char *func_name = NULL;
2731 gdb::unique_xmalloc_ptr<char> temp_func;
2732 enum oload_classification match_quality;
2733 enum oload_classification method_match_quality = INCOMPATIBLE;
2734 enum oload_classification src_method_match_quality = INCOMPATIBLE;
2735 enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2736 enum oload_classification func_match_quality = INCOMPATIBLE;
2738 /* Get the list of overloaded methods or functions. */
2739 if (method == METHOD || method == BOTH)
2741 gdb_assert (obj);
2743 /* OBJ may be a pointer value rather than the object itself. */
2744 obj = coerce_ref (obj);
2745 while (check_typedef (obj->type ())->code () == TYPE_CODE_PTR)
2746 obj = coerce_ref (value_ind (obj));
2747 obj_type_name = obj->type ()->name ();
2749 /* First check whether this is a data member, e.g. a pointer to
2750 a function. */
2751 if (check_typedef (obj->type ())->code () == TYPE_CODE_STRUCT)
2753 *valp = search_struct_field (name, obj,
2754 check_typedef (obj->type ()), 0);
2755 if (*valp)
2757 *staticp = 1;
2758 return 0;
2762 /* Retrieve the list of methods with the name NAME. */
2763 value_find_oload_method_list (&temp, name, 0, &methods,
2764 &xmethods, &basetype, &boffset);
2765 /* If this is a method only search, and no methods were found
2766 the search has failed. */
2767 if (method == METHOD && methods.empty () && xmethods.empty ())
2768 error (_("Couldn't find method %s%s%s"),
2769 obj_type_name,
2770 (obj_type_name && *obj_type_name) ? "::" : "",
2771 name);
2772 /* If we are dealing with stub method types, they should have
2773 been resolved by find_method_list via
2774 value_find_oload_method_list above. */
2775 if (!methods.empty ())
2777 gdb_assert (TYPE_SELF_TYPE (methods[0].type) != NULL);
2779 src_method_oload_champ
2780 = find_oload_champ (args,
2781 methods.size (),
2782 methods.data (), NULL, NULL,
2783 &src_method_badness);
2785 src_method_match_quality = classify_oload_match
2786 (src_method_badness, args.size (),
2787 oload_method_static_p (methods.data (), src_method_oload_champ));
2790 if (!xmethods.empty ())
2792 ext_method_oload_champ
2793 = find_oload_champ (args,
2794 xmethods.size (),
2795 NULL, xmethods.data (), NULL,
2796 &ext_method_badness);
2797 ext_method_match_quality = classify_oload_match (ext_method_badness,
2798 args.size (), 0);
2801 if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2803 switch (compare_badness (ext_method_badness, src_method_badness))
2805 case 0: /* Src method and xmethod are equally good. */
2806 /* If src method and xmethod are equally good, then
2807 xmethod should be the winner. Hence, fall through to the
2808 case where a xmethod is better than the source
2809 method, except when the xmethod match quality is
2810 non-standard. */
2811 [[fallthrough]];
2812 case 1: /* Src method and ext method are incompatible. */
2813 /* If ext method match is not standard, then let source method
2814 win. Otherwise, fallthrough to let xmethod win. */
2815 if (ext_method_match_quality != STANDARD)
2817 method_oload_champ = src_method_oload_champ;
2818 method_badness = src_method_badness;
2819 ext_method_oload_champ = -1;
2820 method_match_quality = src_method_match_quality;
2821 break;
2823 [[fallthrough]];
2824 case 2: /* Ext method is champion. */
2825 method_oload_champ = ext_method_oload_champ;
2826 method_badness = ext_method_badness;
2827 src_method_oload_champ = -1;
2828 method_match_quality = ext_method_match_quality;
2829 break;
2830 case 3: /* Src method is champion. */
2831 method_oload_champ = src_method_oload_champ;
2832 method_badness = src_method_badness;
2833 ext_method_oload_champ = -1;
2834 method_match_quality = src_method_match_quality;
2835 break;
2836 default:
2837 gdb_assert_not_reached ("Unexpected overload comparison "
2838 "result");
2839 break;
2842 else if (src_method_oload_champ >= 0)
2844 method_oload_champ = src_method_oload_champ;
2845 method_badness = src_method_badness;
2846 method_match_quality = src_method_match_quality;
2848 else if (ext_method_oload_champ >= 0)
2850 method_oload_champ = ext_method_oload_champ;
2851 method_badness = ext_method_badness;
2852 method_match_quality = ext_method_match_quality;
2856 if (method == NON_METHOD || method == BOTH)
2858 const char *qualified_name = NULL;
2860 /* If the overload match is being search for both as a method
2861 and non member function, the first argument must now be
2862 dereferenced. */
2863 if (method == BOTH)
2864 args[0] = value_ind (args[0]);
2866 if (fsym)
2868 qualified_name = fsym->natural_name ();
2870 /* If we have a function with a C++ name, try to extract just
2871 the function part. Do not try this for non-functions (e.g.
2872 function pointers). */
2873 if (qualified_name
2874 && (check_typedef (fsym->type ())->code ()
2875 == TYPE_CODE_FUNC))
2877 temp_func = cp_func_name (qualified_name);
2879 /* If cp_func_name did not remove anything, the name of the
2880 symbol did not include scope or argument types - it was
2881 probably a C-style function. */
2882 if (temp_func != nullptr)
2884 if (strcmp (temp_func.get (), qualified_name) == 0)
2885 func_name = NULL;
2886 else
2887 func_name = temp_func.get ();
2891 else
2893 func_name = name;
2894 qualified_name = name;
2897 /* If there was no C++ name, this must be a C-style function or
2898 not a function at all. Just return the same symbol. Do the
2899 same if cp_func_name fails for some reason. */
2900 if (func_name == NULL)
2902 *symp = fsym;
2903 return 0;
2906 func_oload_champ = find_oload_champ_namespace (args,
2907 func_name,
2908 qualified_name,
2909 &functions,
2910 &func_badness,
2911 no_adl);
2913 if (func_oload_champ >= 0)
2914 func_match_quality = classify_oload_match (func_badness,
2915 args.size (), 0);
2918 /* Did we find a match ? */
2919 if (method_oload_champ == -1 && func_oload_champ == -1)
2920 throw_error (NOT_FOUND_ERROR,
2921 _("No symbol \"%s\" in current context."),
2922 name);
2924 /* If we have found both a method match and a function
2925 match, find out which one is better, and calculate match
2926 quality. */
2927 if (method_oload_champ >= 0 && func_oload_champ >= 0)
2929 switch (compare_badness (func_badness, method_badness))
2931 case 0: /* Top two contenders are equally good. */
2932 /* FIXME: GDB does not support the general ambiguous case.
2933 All candidates should be collected and presented the
2934 user. */
2935 error (_("Ambiguous overload resolution"));
2936 break;
2937 case 1: /* Incomparable top contenders. */
2938 /* This is an error incompatible candidates
2939 should not have been proposed. */
2940 error (_("Internal error: incompatible "
2941 "overload candidates proposed"));
2942 break;
2943 case 2: /* Function champion. */
2944 method_oload_champ = -1;
2945 match_quality = func_match_quality;
2946 break;
2947 case 3: /* Method champion. */
2948 func_oload_champ = -1;
2949 match_quality = method_match_quality;
2950 break;
2951 default:
2952 error (_("Internal error: unexpected overload comparison result"));
2953 break;
2956 else
2958 /* We have either a method match or a function match. */
2959 if (method_oload_champ >= 0)
2960 match_quality = method_match_quality;
2961 else
2962 match_quality = func_match_quality;
2965 if (match_quality == INCOMPATIBLE)
2967 std::string hint = incomplete_type_hint (args);
2968 if (method == METHOD)
2969 error (_("Cannot resolve method %s%s%s to any overloaded instance%s"),
2970 obj_type_name,
2971 (obj_type_name && *obj_type_name) ? "::" : "",
2972 name, hint.c_str ());
2973 else
2974 error (_("Cannot resolve function %s to any overloaded instance%s"),
2975 func_name, hint.c_str ());
2977 else if (match_quality == NON_STANDARD)
2979 if (method == METHOD)
2980 warning (_("Using non-standard conversion to match "
2981 "method %s%s%s to supplied arguments"),
2982 obj_type_name,
2983 (obj_type_name && *obj_type_name) ? "::" : "",
2984 name);
2985 else
2986 warning (_("Using non-standard conversion to match "
2987 "function %s to supplied arguments"),
2988 func_name);
2991 if (staticp != NULL)
2992 *staticp = oload_method_static_p (methods.data (), method_oload_champ);
2994 if (method_oload_champ >= 0)
2996 if (src_method_oload_champ >= 0)
2998 if (TYPE_FN_FIELD_VIRTUAL_P (methods, method_oload_champ)
2999 && noside != EVAL_AVOID_SIDE_EFFECTS)
3001 *valp = value_virtual_fn_field (&temp, methods.data (),
3002 method_oload_champ, basetype,
3003 boffset);
3005 else
3006 *valp = value_fn_field (&temp, methods.data (),
3007 method_oload_champ, basetype, boffset);
3009 else
3010 *valp = value::from_xmethod
3011 (std::move (xmethods[ext_method_oload_champ]));
3013 else
3014 *symp = functions[func_oload_champ];
3016 if (objp)
3018 struct type *temp_type = check_typedef (temp->type ());
3019 struct type *objtype = check_typedef (obj_type);
3021 if (temp_type->code () != TYPE_CODE_PTR
3022 && objtype->is_pointer_or_reference ())
3024 temp = value_addr (temp);
3026 *objp = temp;
3029 switch (match_quality)
3031 case INCOMPATIBLE:
3032 return 100;
3033 case NON_STANDARD:
3034 return 10;
3035 default: /* STANDARD */
3036 return 0;
3040 /* Find the best overload match, searching for FUNC_NAME in namespaces
3041 contained in QUALIFIED_NAME until it either finds a good match or
3042 runs out of namespaces. It stores the overloaded functions in
3043 *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV. If NO_ADL,
3044 argument dependent lookup is not performed. */
3046 static int
3047 find_oload_champ_namespace (gdb::array_view<value *> args,
3048 const char *func_name,
3049 const char *qualified_name,
3050 std::vector<symbol *> *oload_syms,
3051 badness_vector *oload_champ_bv,
3052 const int no_adl)
3054 int oload_champ;
3056 find_oload_champ_namespace_loop (args,
3057 func_name,
3058 qualified_name, 0,
3059 oload_syms, oload_champ_bv,
3060 &oload_champ,
3061 no_adl);
3063 return oload_champ;
3066 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
3067 how deep we've looked for namespaces, and the champ is stored in
3068 OLOAD_CHAMP. The return value is 1 if the champ is a good one, 0
3069 if it isn't. Other arguments are the same as in
3070 find_oload_champ_namespace. */
3072 static int
3073 find_oload_champ_namespace_loop (gdb::array_view<value *> args,
3074 const char *func_name,
3075 const char *qualified_name,
3076 int namespace_len,
3077 std::vector<symbol *> *oload_syms,
3078 badness_vector *oload_champ_bv,
3079 int *oload_champ,
3080 const int no_adl)
3082 int next_namespace_len = namespace_len;
3083 int searched_deeper = 0;
3084 int new_oload_champ;
3085 char *new_namespace;
3087 if (next_namespace_len != 0)
3089 gdb_assert (qualified_name[next_namespace_len] == ':');
3090 next_namespace_len += 2;
3092 next_namespace_len +=
3093 cp_find_first_component (qualified_name + next_namespace_len);
3095 /* First, see if we have a deeper namespace we can search in.
3096 If we get a good match there, use it. */
3098 if (qualified_name[next_namespace_len] == ':')
3100 searched_deeper = 1;
3102 if (find_oload_champ_namespace_loop (args,
3103 func_name, qualified_name,
3104 next_namespace_len,
3105 oload_syms, oload_champ_bv,
3106 oload_champ, no_adl))
3108 return 1;
3112 /* If we reach here, either we're in the deepest namespace or we
3113 didn't find a good match in a deeper namespace. But, in the
3114 latter case, we still have a bad match in a deeper namespace;
3115 note that we might not find any match at all in the current
3116 namespace. (There's always a match in the deepest namespace,
3117 because this overload mechanism only gets called if there's a
3118 function symbol to start off with.) */
3120 new_namespace = (char *) alloca (namespace_len + 1);
3121 strncpy (new_namespace, qualified_name, namespace_len);
3122 new_namespace[namespace_len] = '\0';
3124 std::vector<symbol *> new_oload_syms
3125 = make_symbol_overload_list (func_name, new_namespace);
3127 /* If we have reached the deepest level perform argument
3128 determined lookup. */
3129 if (!searched_deeper && !no_adl)
3131 int ix;
3132 struct type **arg_types;
3134 /* Prepare list of argument types for overload resolution. */
3135 arg_types = (struct type **)
3136 alloca (args.size () * (sizeof (struct type *)));
3137 for (ix = 0; ix < args.size (); ix++)
3138 arg_types[ix] = args[ix]->type ();
3139 add_symbol_overload_list_adl ({arg_types, args.size ()}, func_name,
3140 &new_oload_syms);
3143 badness_vector new_oload_champ_bv;
3144 new_oload_champ = find_oload_champ (args,
3145 new_oload_syms.size (),
3146 NULL, NULL, new_oload_syms.data (),
3147 &new_oload_champ_bv);
3149 /* Case 1: We found a good match. Free earlier matches (if any),
3150 and return it. Case 2: We didn't find a good match, but we're
3151 not the deepest function. Then go with the bad match that the
3152 deeper function found. Case 3: We found a bad match, and we're
3153 the deepest function. Then return what we found, even though
3154 it's a bad match. */
3156 if (new_oload_champ != -1
3157 && classify_oload_match (new_oload_champ_bv, args.size (), 0) == STANDARD)
3159 *oload_syms = std::move (new_oload_syms);
3160 *oload_champ = new_oload_champ;
3161 *oload_champ_bv = std::move (new_oload_champ_bv);
3162 return 1;
3164 else if (searched_deeper)
3166 return 0;
3168 else
3170 *oload_syms = std::move (new_oload_syms);
3171 *oload_champ = new_oload_champ;
3172 *oload_champ_bv = std::move (new_oload_champ_bv);
3173 return 0;
3177 /* Look for a function to take ARGS. Find the best match from among
3178 the overloaded methods or functions given by METHODS or FUNCTIONS
3179 or XMETHODS, respectively. One, and only one of METHODS, FUNCTIONS
3180 and XMETHODS can be non-NULL.
3182 NUM_FNS is the length of the array pointed at by METHODS, FUNCTIONS
3183 or XMETHODS, whichever is non-NULL.
3185 Return the index of the best match; store an indication of the
3186 quality of the match in OLOAD_CHAMP_BV. */
3188 static int
3189 find_oload_champ (gdb::array_view<value *> args,
3190 size_t num_fns,
3191 fn_field *methods,
3192 xmethod_worker_up *xmethods,
3193 symbol **functions,
3194 badness_vector *oload_champ_bv)
3196 /* A measure of how good an overloaded instance is. */
3197 badness_vector bv;
3198 /* Index of best overloaded function. */
3199 int oload_champ = -1;
3200 /* Current ambiguity state for overload resolution. */
3201 int oload_ambiguous = 0;
3202 /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs. */
3204 /* A champion can be found among methods alone, or among functions
3205 alone, or in xmethods alone, but not in more than one of these
3206 groups. */
3207 gdb_assert ((methods != NULL) + (functions != NULL) + (xmethods != NULL)
3208 == 1);
3210 /* Consider each candidate in turn. */
3211 for (size_t ix = 0; ix < num_fns; ix++)
3213 int jj;
3214 int static_offset = 0;
3215 bool varargs = false;
3216 std::vector<type *> parm_types;
3218 if (xmethods != NULL)
3219 parm_types = xmethods[ix]->get_arg_types ();
3220 else
3222 size_t nparms;
3224 if (methods != NULL)
3226 nparms = TYPE_FN_FIELD_TYPE (methods, ix)->num_fields ();
3227 static_offset = oload_method_static_p (methods, ix);
3228 varargs = TYPE_FN_FIELD_TYPE (methods, ix)->has_varargs ();
3230 else
3232 nparms = functions[ix]->type ()->num_fields ();
3233 varargs = functions[ix]->type ()->has_varargs ();
3236 parm_types.reserve (nparms);
3237 for (jj = 0; jj < nparms; jj++)
3239 type *t = (methods != NULL
3240 ? (TYPE_FN_FIELD_ARGS (methods, ix)[jj].type ())
3241 : functions[ix]->type ()->field (jj).type ());
3242 parm_types.push_back (t);
3246 /* Compare parameter types to supplied argument types. Skip
3247 THIS for static methods. */
3248 bv = rank_function (parm_types,
3249 args.slice (static_offset),
3250 varargs);
3252 if (overload_debug)
3254 if (methods != NULL)
3255 gdb_printf (gdb_stderr,
3256 "Overloaded method instance %s, # of parms %d\n",
3257 methods[ix].physname, (int) parm_types.size ());
3258 else if (xmethods != NULL)
3259 gdb_printf (gdb_stderr,
3260 "Xmethod worker, # of parms %d\n",
3261 (int) parm_types.size ());
3262 else
3263 gdb_printf (gdb_stderr,
3264 "Overloaded function instance "
3265 "%s # of parms %d\n",
3266 functions[ix]->demangled_name (),
3267 (int) parm_types.size ());
3269 gdb_printf (gdb_stderr,
3270 "...Badness of length : {%d, %d}\n",
3271 bv[0].rank, bv[0].subrank);
3273 for (jj = 1; jj < bv.size (); jj++)
3274 gdb_printf (gdb_stderr,
3275 "...Badness of arg %d : {%d, %d}\n",
3276 jj, bv[jj].rank, bv[jj].subrank);
3279 if (oload_champ_bv->empty ())
3281 *oload_champ_bv = std::move (bv);
3282 oload_champ = 0;
3284 else /* See whether current candidate is better or worse than
3285 previous best. */
3286 switch (compare_badness (bv, *oload_champ_bv))
3288 case 0: /* Top two contenders are equally good. */
3289 oload_ambiguous = 1;
3290 break;
3291 case 1: /* Incomparable top contenders. */
3292 oload_ambiguous = 2;
3293 break;
3294 case 2: /* New champion, record details. */
3295 *oload_champ_bv = std::move (bv);
3296 oload_ambiguous = 0;
3297 oload_champ = ix;
3298 break;
3299 case 3:
3300 default:
3301 break;
3303 if (overload_debug)
3304 gdb_printf (gdb_stderr, "Overload resolution "
3305 "champion is %d, ambiguous? %d\n",
3306 oload_champ, oload_ambiguous);
3309 return oload_champ;
3312 /* Return 1 if we're looking at a static method, 0 if we're looking at
3313 a non-static method or a function that isn't a method. */
3315 static int
3316 oload_method_static_p (struct fn_field *fns_ptr, int index)
3318 if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3319 return 1;
3320 else
3321 return 0;
3324 /* Check how good an overload match OLOAD_CHAMP_BV represents. */
3326 static enum oload_classification
3327 classify_oload_match (const badness_vector &oload_champ_bv,
3328 int nargs,
3329 int static_offset)
3331 int ix;
3332 enum oload_classification worst = STANDARD;
3334 for (ix = 1; ix <= nargs - static_offset; ix++)
3336 /* If this conversion is as bad as INCOMPATIBLE_TYPE_BADNESS
3337 or worse return INCOMPATIBLE. */
3338 if (compare_ranks (oload_champ_bv[ix],
3339 INCOMPATIBLE_TYPE_BADNESS) <= 0)
3340 return INCOMPATIBLE; /* Truly mismatched types. */
3341 /* Otherwise If this conversion is as bad as
3342 NS_POINTER_CONVERSION_BADNESS or worse return NON_STANDARD. */
3343 else if (compare_ranks (oload_champ_bv[ix],
3344 NS_POINTER_CONVERSION_BADNESS) <= 0)
3345 worst = NON_STANDARD; /* Non-standard type conversions
3346 needed. */
3349 /* If no INCOMPATIBLE classification was found, return the worst one
3350 that was found (if any). */
3351 return worst;
3354 /* C++: return 1 is NAME is a legitimate name for the destructor of
3355 type TYPE. If TYPE does not have a destructor, or if NAME is
3356 inappropriate for TYPE, an error is signaled. Parameter TYPE should not yet
3357 have CHECK_TYPEDEF applied, this function will apply it itself. */
3360 destructor_name_p (const char *name, struct type *type)
3362 if (name[0] == '~')
3364 const char *dname = type_name_or_error (type);
3365 const char *cp = strchr (dname, '<');
3366 unsigned int len;
3368 /* Do not compare the template part for template classes. */
3369 if (cp == NULL)
3370 len = strlen (dname);
3371 else
3372 len = cp - dname;
3373 if (strlen (name + 1) != len || strncmp (dname, name + 1, len) != 0)
3374 error (_("name of destructor must equal name of class"));
3375 else
3376 return 1;
3378 return 0;
3381 /* Find an enum constant named NAME in TYPE. TYPE must be an "enum
3382 class". If the name is found, return a value representing it;
3383 otherwise throw an exception. */
3385 static struct value *
3386 enum_constant_from_type (struct type *type, const char *name)
3388 int i;
3389 int name_len = strlen (name);
3391 gdb_assert (type->code () == TYPE_CODE_ENUM
3392 && type->is_declared_class ());
3394 for (i = TYPE_N_BASECLASSES (type); i < type->num_fields (); ++i)
3396 const char *fname = type->field (i).name ();
3397 int len;
3399 if (type->field (i).loc_kind () != FIELD_LOC_KIND_ENUMVAL
3400 || fname == NULL)
3401 continue;
3403 /* Look for the trailing "::NAME", since enum class constant
3404 names are qualified here. */
3405 len = strlen (fname);
3406 if (len + 2 >= name_len
3407 && fname[len - name_len - 2] == ':'
3408 && fname[len - name_len - 1] == ':'
3409 && strcmp (&fname[len - name_len], name) == 0)
3410 return value_from_longest (type, type->field (i).loc_enumval ());
3413 error (_("no constant named \"%s\" in enum \"%s\""),
3414 name, type->name ());
3417 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3418 return the appropriate member (or the address of the member, if
3419 WANT_ADDRESS). This function is used to resolve user expressions
3420 of the form "DOMAIN::NAME". For more details on what happens, see
3421 the comment before value_struct_elt_for_reference. */
3423 struct value *
3424 value_aggregate_elt (struct type *curtype, const char *name,
3425 struct type *expect_type, int want_address,
3426 enum noside noside)
3428 switch (curtype->code ())
3430 case TYPE_CODE_STRUCT:
3431 case TYPE_CODE_UNION:
3432 return value_struct_elt_for_reference (curtype, 0, curtype,
3433 name, expect_type,
3434 want_address, noside);
3435 case TYPE_CODE_NAMESPACE:
3436 return value_namespace_elt (curtype, name,
3437 want_address, noside);
3439 case TYPE_CODE_ENUM:
3440 return enum_constant_from_type (curtype, name);
3442 default:
3443 internal_error (_("non-aggregate type in value_aggregate_elt"));
3447 /* Compares the two method/function types T1 and T2 for "equality"
3448 with respect to the methods' parameters. If the types of the
3449 two parameter lists are the same, returns 1; 0 otherwise. This
3450 comparison may ignore any artificial parameters in T1 if
3451 SKIP_ARTIFICIAL is non-zero. This function will ALWAYS skip
3452 the first artificial parameter in T1, assumed to be a 'this' pointer.
3454 The type T2 is expected to have come from make_params (in eval.c). */
3456 static int
3457 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3459 int start = 0;
3461 if (t1->num_fields () > 0 && t1->field (0).is_artificial ())
3462 ++start;
3464 /* If skipping artificial fields, find the first real field
3465 in T1. */
3466 if (skip_artificial)
3468 while (start < t1->num_fields ()
3469 && t1->field (start).is_artificial ())
3470 ++start;
3473 /* Now compare parameters. */
3475 /* Special case: a method taking void. T1 will contain no
3476 non-artificial fields, and T2 will contain TYPE_CODE_VOID. */
3477 if ((t1->num_fields () - start) == 0 && t2->num_fields () == 1
3478 && t2->field (0).type ()->code () == TYPE_CODE_VOID)
3479 return 1;
3481 if ((t1->num_fields () - start) == t2->num_fields ())
3483 int i;
3485 for (i = 0; i < t2->num_fields (); ++i)
3487 if (compare_ranks (rank_one_type (t1->field (start + i).type (),
3488 t2->field (i).type (), NULL),
3489 EXACT_MATCH_BADNESS) != 0)
3490 return 0;
3493 return 1;
3496 return 0;
3499 /* C++: Given an aggregate type VT, and a class type CLS, search
3500 recursively for CLS using value V; If found, store the offset
3501 which is either fetched from the virtual base pointer if CLS
3502 is virtual or accumulated offset of its parent classes if
3503 CLS is non-virtual in *BOFFS, set ISVIRT to indicate if CLS
3504 is virtual, and return true. If not found, return false. */
3506 static bool
3507 get_baseclass_offset (struct type *vt, struct type *cls,
3508 struct value *v, int *boffs, bool *isvirt)
3510 for (int i = 0; i < TYPE_N_BASECLASSES (vt); i++)
3512 struct type *t = vt->field (i).type ();
3513 if (types_equal (t, cls))
3515 if (BASETYPE_VIA_VIRTUAL (vt, i))
3517 const gdb_byte *adr = v->contents_for_printing ().data ();
3518 *boffs = baseclass_offset (vt, i, adr, v->offset (),
3519 value_as_long (v), v);
3520 *isvirt = true;
3522 else
3523 *isvirt = false;
3524 return true;
3527 if (get_baseclass_offset (check_typedef (t), cls, v, boffs, isvirt))
3529 if (*isvirt == false) /* Add non-virtual base offset. */
3531 const gdb_byte *adr = v->contents_for_printing ().data ();
3532 *boffs += baseclass_offset (vt, i, adr, v->offset (),
3533 value_as_long (v), v);
3535 return true;
3539 return false;
3542 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3543 return the address of this member as a "pointer to member" type.
3544 If INTYPE is non-null, then it will be the type of the member we
3545 are looking for. This will help us resolve "pointers to member
3546 functions". This function is used to resolve user expressions of
3547 the form "DOMAIN::NAME". */
3549 static struct value *
3550 value_struct_elt_for_reference (struct type *domain, int offset,
3551 struct type *curtype, const char *name,
3552 struct type *intype,
3553 int want_address,
3554 enum noside noside)
3556 struct type *t = check_typedef (curtype);
3557 int i;
3558 struct value *result;
3560 if (t->code () != TYPE_CODE_STRUCT
3561 && t->code () != TYPE_CODE_UNION)
3562 error (_("Internal error: non-aggregate type "
3563 "to value_struct_elt_for_reference"));
3565 for (i = t->num_fields () - 1; i >= TYPE_N_BASECLASSES (t); i--)
3567 const char *t_field_name = t->field (i).name ();
3569 if (t_field_name && strcmp (t_field_name, name) == 0)
3571 if (t->field (i).is_static ())
3573 struct value *v = value_static_field (t, i);
3574 if (want_address)
3575 v = value_addr (v);
3576 return v;
3578 if (t->field (i).is_packed ())
3579 error (_("pointers to bitfield members not allowed"));
3581 if (want_address)
3582 return value_from_longest
3583 (lookup_memberptr_type (t->field (i).type (), domain),
3584 offset + (LONGEST) (t->field (i).loc_bitpos () >> 3));
3585 else if (noside != EVAL_NORMAL)
3586 return value::allocate (t->field (i).type ());
3587 else
3589 /* Try to evaluate NAME as a qualified name with implicit
3590 this pointer. In this case, attempt to return the
3591 equivalent to `this->*(&TYPE::NAME)'. */
3592 struct value *v = value_of_this_silent (current_language);
3593 if (v != NULL)
3595 struct value *ptr, *this_v = v;
3596 long mem_offset;
3597 struct type *type, *tmp;
3599 ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3600 type = check_typedef (ptr->type ());
3601 gdb_assert (type != NULL
3602 && type->code () == TYPE_CODE_MEMBERPTR);
3603 tmp = lookup_pointer_type (TYPE_SELF_TYPE (type));
3604 v = value_cast_pointers (tmp, v, 1);
3605 mem_offset = value_as_long (ptr);
3606 if (domain != curtype)
3608 /* Find class offset of type CURTYPE from either its
3609 parent type DOMAIN or the type of implied this. */
3610 int boff = 0;
3611 bool isvirt = false;
3612 if (get_baseclass_offset (domain, curtype, v, &boff,
3613 &isvirt))
3614 mem_offset += boff;
3615 else
3617 struct type *p = check_typedef (this_v->type ());
3618 p = check_typedef (p->target_type ());
3619 if (get_baseclass_offset (p, curtype, this_v,
3620 &boff, &isvirt))
3621 mem_offset += boff;
3624 tmp = lookup_pointer_type (type->target_type ());
3625 result = value_from_pointer (tmp,
3626 value_as_long (v) + mem_offset);
3627 return value_ind (result);
3630 error (_("Cannot reference non-static field \"%s\""), name);
3635 /* C++: If it was not found as a data field, then try to return it
3636 as a pointer to a method. */
3638 /* Perform all necessary dereferencing. */
3639 while (intype && intype->code () == TYPE_CODE_PTR)
3640 intype = intype->target_type ();
3642 for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3644 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3646 if (t_field_name && strcmp (t_field_name, name) == 0)
3648 int j;
3649 int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3650 struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3652 check_stub_method_group (t, i);
3654 if (intype)
3656 for (j = 0; j < len; ++j)
3658 if (TYPE_CONST (intype) != TYPE_FN_FIELD_CONST (f, j))
3659 continue;
3660 if (TYPE_VOLATILE (intype) != TYPE_FN_FIELD_VOLATILE (f, j))
3661 continue;
3663 if (compare_parameters (TYPE_FN_FIELD_TYPE (f, j), intype, 0)
3664 || compare_parameters (TYPE_FN_FIELD_TYPE (f, j),
3665 intype, 1))
3666 break;
3669 if (j == len)
3670 error (_("no member function matches "
3671 "that type instantiation"));
3673 else
3675 int ii;
3677 j = -1;
3678 for (ii = 0; ii < len; ++ii)
3680 /* Skip artificial methods. This is necessary if,
3681 for example, the user wants to "print
3682 subclass::subclass" with only one user-defined
3683 constructor. There is no ambiguity in this case.
3684 We are careful here to allow artificial methods
3685 if they are the unique result. */
3686 if (TYPE_FN_FIELD_ARTIFICIAL (f, ii))
3688 if (j == -1)
3689 j = ii;
3690 continue;
3693 /* Desired method is ambiguous if more than one
3694 method is defined. */
3695 if (j != -1 && !TYPE_FN_FIELD_ARTIFICIAL (f, j))
3696 error (_("non-unique member `%s' requires "
3697 "type instantiation"), name);
3699 j = ii;
3702 if (j == -1)
3703 error (_("no matching member function"));
3706 if (TYPE_FN_FIELD_STATIC_P (f, j))
3708 struct symbol *s =
3709 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3710 0, VAR_DOMAIN, 0).symbol;
3712 if (s == NULL)
3713 return NULL;
3715 if (want_address)
3716 return value_addr (read_var_value (s, 0, 0));
3717 else
3718 return read_var_value (s, 0, 0);
3721 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3723 if (want_address)
3725 result = value::allocate
3726 (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3727 cplus_make_method_ptr (result->type (),
3728 result->contents_writeable ().data (),
3729 TYPE_FN_FIELD_VOFFSET (f, j), 1);
3731 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3732 return value::allocate (TYPE_FN_FIELD_TYPE (f, j));
3733 else
3734 error (_("Cannot reference virtual member function \"%s\""),
3735 name);
3737 else
3739 struct symbol *s =
3740 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3741 0, VAR_DOMAIN, 0).symbol;
3743 if (s == NULL)
3744 return NULL;
3746 struct value *v = read_var_value (s, 0, 0);
3747 if (!want_address)
3748 result = v;
3749 else
3751 result = value::allocate (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3752 cplus_make_method_ptr (result->type (),
3753 result->contents_writeable ().data (),
3754 v->address (), 0);
3757 return result;
3760 for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3762 struct value *v;
3763 int base_offset;
3765 if (BASETYPE_VIA_VIRTUAL (t, i))
3766 base_offset = 0;
3767 else
3768 base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3769 v = value_struct_elt_for_reference (domain,
3770 offset + base_offset,
3771 TYPE_BASECLASS (t, i),
3772 name, intype,
3773 want_address, noside);
3774 if (v)
3775 return v;
3778 /* As a last chance, pretend that CURTYPE is a namespace, and look
3779 it up that way; this (frequently) works for types nested inside
3780 classes. */
3782 return value_maybe_namespace_elt (curtype, name,
3783 want_address, noside);
3786 /* C++: Return the member NAME of the namespace given by the type
3787 CURTYPE. */
3789 static struct value *
3790 value_namespace_elt (const struct type *curtype,
3791 const char *name, int want_address,
3792 enum noside noside)
3794 struct value *retval = value_maybe_namespace_elt (curtype, name,
3795 want_address,
3796 noside);
3798 if (retval == NULL)
3799 error (_("No symbol \"%s\" in namespace \"%s\"."),
3800 name, curtype->name ());
3802 return retval;
3805 /* A helper function used by value_namespace_elt and
3806 value_struct_elt_for_reference. It looks up NAME inside the
3807 context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
3808 is a class and NAME refers to a type in CURTYPE itself (as opposed
3809 to, say, some base class of CURTYPE). */
3811 static struct value *
3812 value_maybe_namespace_elt (const struct type *curtype,
3813 const char *name, int want_address,
3814 enum noside noside)
3816 const char *namespace_name = curtype->name ();
3817 struct block_symbol sym;
3818 struct value *result;
3820 sym = cp_lookup_symbol_namespace (namespace_name, name,
3821 get_selected_block (0), VAR_DOMAIN);
3823 if (sym.symbol == NULL)
3824 return NULL;
3825 else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3826 && (sym.symbol->aclass () == LOC_TYPEDEF))
3827 result = value::allocate (sym.symbol->type ());
3828 else
3829 result = value_of_variable (sym.symbol, sym.block);
3831 if (want_address)
3832 result = value_addr (result);
3834 return result;
3837 /* Given a pointer or a reference value V, find its real (RTTI) type.
3839 Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3840 and refer to the values computed for the object pointed to. */
3842 struct type *
3843 value_rtti_indirect_type (struct value *v, int *full,
3844 LONGEST *top, int *using_enc)
3846 struct value *target = NULL;
3847 struct type *type, *real_type, *target_type;
3849 type = v->type ();
3850 type = check_typedef (type);
3851 if (TYPE_IS_REFERENCE (type))
3852 target = coerce_ref (v);
3853 else if (type->code () == TYPE_CODE_PTR)
3858 target = value_ind (v);
3860 catch (const gdb_exception_error &except)
3862 if (except.error == MEMORY_ERROR)
3864 /* value_ind threw a memory error. The pointer is NULL or
3865 contains an uninitialized value: we can't determine any
3866 type. */
3867 return NULL;
3869 throw;
3872 else
3873 return NULL;
3875 real_type = value_rtti_type (target, full, top, using_enc);
3877 if (real_type)
3879 /* Copy qualifiers to the referenced object. */
3880 target_type = target->type ();
3881 real_type = make_cv_type (TYPE_CONST (target_type),
3882 TYPE_VOLATILE (target_type), real_type, NULL);
3883 if (TYPE_IS_REFERENCE (type))
3884 real_type = lookup_reference_type (real_type, type->code ());
3885 else if (type->code () == TYPE_CODE_PTR)
3886 real_type = lookup_pointer_type (real_type);
3887 else
3888 internal_error (_("Unexpected value type."));
3890 /* Copy qualifiers to the pointer/reference. */
3891 real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3892 real_type, NULL);
3895 return real_type;
3898 /* Given a value pointed to by ARGP, check its real run-time type, and
3899 if that is different from the enclosing type, create a new value
3900 using the real run-time type as the enclosing type (and of the same
3901 type as ARGP) and return it, with the embedded offset adjusted to
3902 be the correct offset to the enclosed object. RTYPE is the type,
3903 and XFULL, XTOP, and XUSING_ENC are the other parameters, computed
3904 by value_rtti_type(). If these are available, they can be supplied
3905 and a second call to value_rtti_type() is avoided. (Pass RTYPE ==
3906 NULL if they're not available. */
3908 struct value *
3909 value_full_object (struct value *argp,
3910 struct type *rtype,
3911 int xfull, int xtop,
3912 int xusing_enc)
3914 struct type *real_type;
3915 int full = 0;
3916 LONGEST top = -1;
3917 int using_enc = 0;
3918 struct value *new_val;
3920 if (rtype)
3922 real_type = rtype;
3923 full = xfull;
3924 top = xtop;
3925 using_enc = xusing_enc;
3927 else
3928 real_type = value_rtti_type (argp, &full, &top, &using_enc);
3930 /* If no RTTI data, or if object is already complete, do nothing. */
3931 if (!real_type || real_type == argp->enclosing_type ())
3932 return argp;
3934 /* In a destructor we might see a real type that is a superclass of
3935 the object's type. In this case it is better to leave the object
3936 as-is. */
3937 if (full
3938 && real_type->length () < argp->enclosing_type ()->length ())
3939 return argp;
3941 /* If we have the full object, but for some reason the enclosing
3942 type is wrong, set it. */
3943 /* pai: FIXME -- sounds iffy */
3944 if (full)
3946 argp = argp->copy ();
3947 argp->set_enclosing_type (real_type);
3948 return argp;
3951 /* Check if object is in memory. */
3952 if (argp->lval () != lval_memory)
3954 warning (_("Couldn't retrieve complete object of RTTI "
3955 "type %s; object may be in register(s)."),
3956 real_type->name ());
3958 return argp;
3961 /* All other cases -- retrieve the complete object. */
3962 /* Go back by the computed top_offset from the beginning of the
3963 object, adjusting for the embedded offset of argp if that's what
3964 value_rtti_type used for its computation. */
3965 new_val = value_at_lazy (real_type, argp->address () - top +
3966 (using_enc ? 0 : argp->embedded_offset ()));
3967 new_val->deprecated_set_type (argp->type ());
3968 new_val->set_embedded_offset ((using_enc
3969 ? top + argp->embedded_offset ()
3970 : top));
3971 return new_val;
3975 /* Return the value of the local variable, if one exists. Throw error
3976 otherwise, such as if the request is made in an inappropriate context. */
3978 struct value *
3979 value_of_this (const struct language_defn *lang)
3981 struct block_symbol sym;
3982 const struct block *b;
3983 frame_info_ptr frame;
3985 if (lang->name_of_this () == NULL)
3986 error (_("no `this' in current language"));
3988 frame = get_selected_frame (_("no frame selected"));
3990 b = get_frame_block (frame, NULL);
3992 sym = lookup_language_this (lang, b);
3993 if (sym.symbol == NULL)
3994 error (_("current stack frame does not contain a variable named `%s'"),
3995 lang->name_of_this ());
3997 return read_var_value (sym.symbol, sym.block, frame);
4000 /* Return the value of the local variable, if one exists. Return NULL
4001 otherwise. Never throw error. */
4003 struct value *
4004 value_of_this_silent (const struct language_defn *lang)
4006 struct value *ret = NULL;
4010 ret = value_of_this (lang);
4012 catch (const gdb_exception_error &except)
4016 return ret;
4019 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH
4020 elements long, starting at LOWBOUND. The result has the same lower
4021 bound as the original ARRAY. */
4023 struct value *
4024 value_slice (struct value *array, int lowbound, int length)
4026 struct type *slice_range_type, *slice_type, *range_type;
4027 LONGEST lowerbound, upperbound;
4028 struct value *slice;
4029 struct type *array_type;
4031 array_type = check_typedef (array->type ());
4032 if (array_type->code () != TYPE_CODE_ARRAY
4033 && array_type->code () != TYPE_CODE_STRING)
4034 error (_("cannot take slice of non-array"));
4036 if (type_not_allocated (array_type))
4037 error (_("array not allocated"));
4038 if (type_not_associated (array_type))
4039 error (_("array not associated"));
4041 range_type = array_type->index_type ();
4042 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
4043 error (_("slice from bad array or bitstring"));
4045 if (lowbound < lowerbound || length < 0
4046 || lowbound + length - 1 > upperbound)
4047 error (_("slice out of range"));
4049 /* FIXME-type-allocation: need a way to free this type when we are
4050 done with it. */
4051 type_allocator alloc (range_type->target_type ());
4052 slice_range_type = create_static_range_type (alloc,
4053 range_type->target_type (),
4054 lowbound,
4055 lowbound + length - 1);
4058 struct type *element_type = array_type->target_type ();
4059 LONGEST offset
4060 = (lowbound - lowerbound) * check_typedef (element_type)->length ();
4062 slice_type = create_array_type (alloc,
4063 element_type,
4064 slice_range_type);
4065 slice_type->set_code (array_type->code ());
4067 if (array->lval () == lval_memory && array->lazy ())
4068 slice = value::allocate_lazy (slice_type);
4069 else
4071 slice = value::allocate (slice_type);
4072 array->contents_copy (slice, 0, offset,
4073 type_length_units (slice_type));
4076 slice->set_component_location (array);
4077 slice->set_offset (array->offset () + offset);
4080 return slice;
4083 /* See value.h. */
4085 struct value *
4086 value_literal_complex (struct value *arg1,
4087 struct value *arg2,
4088 struct type *type)
4090 struct value *val;
4091 struct type *real_type = type->target_type ();
4093 val = value::allocate (type);
4094 arg1 = value_cast (real_type, arg1);
4095 arg2 = value_cast (real_type, arg2);
4097 int len = real_type->length ();
4099 copy (arg1->contents (),
4100 val->contents_raw ().slice (0, len));
4101 copy (arg2->contents (),
4102 val->contents_raw ().slice (len, len));
4104 return val;
4107 /* See value.h. */
4109 struct value *
4110 value_real_part (struct value *value)
4112 struct type *type = check_typedef (value->type ());
4113 struct type *ttype = type->target_type ();
4115 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4116 return value_from_component (value, ttype, 0);
4119 /* See value.h. */
4121 struct value *
4122 value_imaginary_part (struct value *value)
4124 struct type *type = check_typedef (value->type ());
4125 struct type *ttype = type->target_type ();
4127 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4128 return value_from_component (value, ttype,
4129 check_typedef (ttype)->length ());
4132 /* Cast a value into the appropriate complex data type. */
4134 static struct value *
4135 cast_into_complex (struct type *type, struct value *val)
4137 struct type *real_type = type->target_type ();
4139 if (val->type ()->code () == TYPE_CODE_COMPLEX)
4141 struct type *val_real_type = val->type ()->target_type ();
4142 struct value *re_val = value::allocate (val_real_type);
4143 struct value *im_val = value::allocate (val_real_type);
4144 int len = val_real_type->length ();
4146 copy (val->contents ().slice (0, len),
4147 re_val->contents_raw ());
4148 copy (val->contents ().slice (len, len),
4149 im_val->contents_raw ());
4151 return value_literal_complex (re_val, im_val, type);
4153 else if (val->type ()->code () == TYPE_CODE_FLT
4154 || val->type ()->code () == TYPE_CODE_INT)
4155 return value_literal_complex (val,
4156 value::zero (real_type, not_lval),
4157 type);
4158 else
4159 error (_("cannot cast non-number to complex"));
4162 void _initialize_valops ();
4163 void
4164 _initialize_valops ()
4166 add_setshow_boolean_cmd ("overload-resolution", class_support,
4167 &overload_resolution, _("\
4168 Set overload resolution in evaluating C++ functions."), _("\
4169 Show overload resolution in evaluating C++ functions."),
4170 NULL, NULL,
4171 show_overload_resolution,
4172 &setlist, &showlist);
4173 overload_resolution = 1;