Automatic date update in version.in
[binutils-gdb.git] / gdb / valops.c
bloba17b937a963198d0f9a940197d08f2e8d450fcd8
1 /* Perform non-arithmetic operations on values, for GDB.
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "symtab.h"
21 #include "gdbtypes.h"
22 #include "value.h"
23 #include "frame.h"
24 #include "inferior.h"
25 #include "gdbcore.h"
26 #include "target.h"
27 #include "demangle.h"
28 #include "language.h"
29 #include "gdbcmd.h"
30 #include "regcache.h"
31 #include "cp-abi.h"
32 #include "block.h"
33 #include "infcall.h"
34 #include "dictionary.h"
35 #include "cp-support.h"
36 #include "target-float.h"
37 #include "tracepoint.h"
38 #include "observable.h"
39 #include "objfiles.h"
40 #include "extension.h"
41 #include "gdbtypes.h"
42 #include "gdbsupport/byte-vector.h"
43 #include "typeprint.h"
45 /* Local functions. */
47 static int typecmp (bool staticp, bool varargs, int nargs,
48 struct field t1[], const gdb::array_view<value *> t2);
50 static struct value *search_struct_field (const char *, struct value *,
51 struct type *, int);
53 static struct value *search_struct_method (const char *, struct value **,
54 std::optional<gdb::array_view<value *>>,
55 LONGEST, int *, struct type *);
57 static int find_oload_champ_namespace (gdb::array_view<value *> args,
58 const char *, const char *,
59 std::vector<symbol *> *oload_syms,
60 badness_vector *,
61 const int no_adl);
63 static int find_oload_champ_namespace_loop (gdb::array_view<value *> args,
64 const char *, const char *,
65 int, std::vector<symbol *> *oload_syms,
66 badness_vector *, int *,
67 const int no_adl);
69 static int find_oload_champ (gdb::array_view<value *> args,
70 size_t num_fns,
71 fn_field *methods,
72 xmethod_worker_up *xmethods,
73 symbol **functions,
74 badness_vector *oload_champ_bv);
76 static int oload_method_static_p (struct fn_field *, int);
78 enum oload_classification { STANDARD, NON_STANDARD, INCOMPATIBLE };
80 static enum oload_classification classify_oload_match
81 (const badness_vector &, int, int);
83 static struct value *value_struct_elt_for_reference (struct type *,
84 int, struct type *,
85 const char *,
86 struct type *,
87 int, enum noside);
89 static struct value *value_namespace_elt (const struct type *,
90 const char *, int , enum noside);
92 static struct value *value_maybe_namespace_elt (const struct type *,
93 const char *, int,
94 enum noside);
96 static CORE_ADDR allocate_space_in_inferior (int);
98 static struct value *cast_into_complex (struct type *, struct value *);
100 bool overload_resolution = false;
101 static void
102 show_overload_resolution (struct ui_file *file, int from_tty,
103 struct cmd_list_element *c,
104 const char *value)
106 gdb_printf (file, _("Overload resolution in evaluating "
107 "C++ functions is %s.\n"),
108 value);
111 /* Find the address of function name NAME in the inferior. If OBJF_P
112 is non-NULL, *OBJF_P will be set to the OBJFILE where the function
113 is defined. */
115 struct value *
116 find_function_in_inferior (const char *name, struct objfile **objf_p)
118 struct block_symbol sym;
120 sym = lookup_symbol (name, nullptr, SEARCH_TYPE_DOMAIN, nullptr);
121 if (sym.symbol != NULL)
123 if (objf_p)
124 *objf_p = sym.symbol->objfile ();
126 return value_of_variable (sym.symbol, sym.block);
128 else
130 struct bound_minimal_symbol msymbol =
131 lookup_bound_minimal_symbol (name);
133 if (msymbol.minsym != NULL)
135 struct objfile *objfile = msymbol.objfile;
136 struct gdbarch *gdbarch = objfile->arch ();
138 struct type *type;
139 CORE_ADDR maddr;
140 type = lookup_pointer_type (builtin_type (gdbarch)->builtin_char);
141 type = lookup_function_type (type);
142 type = lookup_pointer_type (type);
143 maddr = msymbol.value_address ();
145 if (objf_p)
146 *objf_p = objfile;
148 return value_from_pointer (type, maddr);
150 else
152 if (!target_has_execution ())
153 error (_("evaluation of this expression "
154 "requires the target program to be active"));
155 else
156 error (_("evaluation of this expression requires the "
157 "program to have a function \"%s\"."),
158 name);
163 /* Allocate NBYTES of space in the inferior using the inferior's
164 malloc and return a value that is a pointer to the allocated
165 space. */
167 struct value *
168 value_allocate_space_in_inferior (int len)
170 struct objfile *objf;
171 struct value *val = find_function_in_inferior ("malloc", &objf);
172 struct gdbarch *gdbarch = objf->arch ();
173 struct value *blocklen;
175 blocklen = value_from_longest (builtin_type (gdbarch)->builtin_int, len);
176 val = call_function_by_hand (val, NULL, blocklen);
177 if (value_logical_not (val))
179 if (!target_has_execution ())
180 error (_("No memory available to program now: "
181 "you need to start the target first"));
182 else
183 error (_("No memory available to program: call to malloc failed"));
185 return val;
188 static CORE_ADDR
189 allocate_space_in_inferior (int len)
191 return value_as_long (value_allocate_space_in_inferior (len));
194 /* Cast struct value VAL to type TYPE and return as a value.
195 Both type and val must be of TYPE_CODE_STRUCT or TYPE_CODE_UNION
196 for this to work. Typedef to one of the codes is permitted.
197 Returns NULL if the cast is neither an upcast nor a downcast. */
199 static struct value *
200 value_cast_structs (struct type *type, struct value *v2)
202 struct type *t1;
203 struct type *t2;
204 struct value *v;
206 gdb_assert (type != NULL && v2 != NULL);
208 t1 = check_typedef (type);
209 t2 = check_typedef (v2->type ());
211 /* Check preconditions. */
212 gdb_assert ((t1->code () == TYPE_CODE_STRUCT
213 || t1->code () == TYPE_CODE_UNION)
214 && !!"Precondition is that type is of STRUCT or UNION kind.");
215 gdb_assert ((t2->code () == TYPE_CODE_STRUCT
216 || t2->code () == TYPE_CODE_UNION)
217 && !!"Precondition is that value is of STRUCT or UNION kind");
219 if (t1->name () != NULL
220 && t2->name () != NULL
221 && !strcmp (t1->name (), t2->name ()))
222 return NULL;
224 /* Upcasting: look in the type of the source to see if it contains the
225 type of the target as a superclass. If so, we'll need to
226 offset the pointer rather than just change its type. */
227 if (t1->name () != NULL)
229 v = search_struct_field (t1->name (),
230 v2, t2, 1);
231 if (v)
232 return v;
235 /* Downcasting: look in the type of the target to see if it contains the
236 type of the source as a superclass. If so, we'll need to
237 offset the pointer rather than just change its type. */
238 if (t2->name () != NULL)
240 /* Try downcasting using the run-time type of the value. */
241 int full, using_enc;
242 LONGEST top;
243 struct type *real_type;
245 real_type = value_rtti_type (v2, &full, &top, &using_enc);
246 if (real_type)
248 v = value_full_object (v2, real_type, full, top, using_enc);
249 v = value_at_lazy (real_type, v->address ());
250 real_type = v->type ();
252 /* We might be trying to cast to the outermost enclosing
253 type, in which case search_struct_field won't work. */
254 if (real_type->name () != NULL
255 && !strcmp (real_type->name (), t1->name ()))
256 return v;
258 v = search_struct_field (t2->name (), v, real_type, 1);
259 if (v)
260 return v;
263 /* Try downcasting using information from the destination type
264 T2. This wouldn't work properly for classes with virtual
265 bases, but those were handled above. */
266 v = search_struct_field (t2->name (),
267 value::zero (t1, not_lval), t1, 1);
268 if (v)
270 /* Downcasting is possible (t1 is superclass of v2). */
271 CORE_ADDR addr2 = v2->address () + v2->embedded_offset ();
273 addr2 -= v->address () + v->embedded_offset ();
274 return value_at (type, addr2);
278 return NULL;
281 /* Cast one pointer or reference type to another. Both TYPE and
282 the type of ARG2 should be pointer types, or else both should be
283 reference types. If SUBCLASS_CHECK is non-zero, this will force a
284 check to see whether TYPE is a superclass of ARG2's type. If
285 SUBCLASS_CHECK is zero, then the subclass check is done only when
286 ARG2 is itself non-zero. Returns the new pointer or reference. */
288 struct value *
289 value_cast_pointers (struct type *type, struct value *arg2,
290 int subclass_check)
292 struct type *type1 = check_typedef (type);
293 struct type *type2 = check_typedef (arg2->type ());
294 struct type *t1 = check_typedef (type1->target_type ());
295 struct type *t2 = check_typedef (type2->target_type ());
297 if (t1->code () == TYPE_CODE_STRUCT
298 && t2->code () == TYPE_CODE_STRUCT
299 && (subclass_check || !value_logical_not (arg2)))
301 struct value *v2;
303 if (TYPE_IS_REFERENCE (type2))
304 v2 = coerce_ref (arg2);
305 else
306 v2 = value_ind (arg2);
307 gdb_assert (check_typedef (v2->type ())->code ()
308 == TYPE_CODE_STRUCT && !!"Why did coercion fail?");
309 v2 = value_cast_structs (t1, v2);
310 /* At this point we have what we can have, un-dereference if needed. */
311 if (v2)
313 struct value *v = value_addr (v2);
315 v->deprecated_set_type (type);
316 return v;
320 /* No superclass found, just change the pointer type. */
321 arg2 = arg2->copy ();
322 arg2->deprecated_set_type (type);
323 arg2->set_enclosing_type (type);
324 arg2->set_pointed_to_offset (0); /* pai: chk_val */
325 return arg2;
328 /* See value.h. */
330 gdb_mpq
331 value_to_gdb_mpq (struct value *value)
333 struct type *type = check_typedef (value->type ());
335 gdb_mpq result;
336 if (is_floating_type (type))
337 result = target_float_to_host_double (value->contents ().data (), type);
338 else
340 gdb_assert (is_integral_type (type)
341 || is_fixed_point_type (type));
343 gdb_mpz vz;
344 vz.read (value->contents (), type_byte_order (type),
345 type->is_unsigned ());
346 result = vz;
348 if (is_fixed_point_type (type))
349 result *= type->fixed_point_scaling_factor ();
352 return result;
355 /* Assuming that TO_TYPE is a fixed point type, return a value
356 corresponding to the cast of FROM_VAL to that type. */
358 static struct value *
359 value_cast_to_fixed_point (struct type *to_type, struct value *from_val)
361 struct type *from_type = from_val->type ();
363 if (from_type == to_type)
364 return from_val;
366 if (!is_floating_type (from_type)
367 && !is_integral_type (from_type)
368 && !is_fixed_point_type (from_type))
369 error (_("Invalid conversion from type %s to fixed point type %s"),
370 from_type->name (), to_type->name ());
372 gdb_mpq vq = value_to_gdb_mpq (from_val);
374 /* Divide that value by the scaling factor to obtain the unscaled
375 value, first in rational form, and then in integer form. */
377 vq /= to_type->fixed_point_scaling_factor ();
378 gdb_mpz unscaled = vq.get_rounded ();
380 /* Finally, create the result value, and pack the unscaled value
381 in it. */
382 struct value *result = value::allocate (to_type);
383 unscaled.write (result->contents_raw (),
384 type_byte_order (to_type),
385 to_type->is_unsigned ());
387 return result;
390 /* Cast value ARG2 to type TYPE and return as a value.
391 More general than a C cast: accepts any two types of the same length,
392 and if ARG2 is an lvalue it can be cast into anything at all. */
393 /* In C++, casts may change pointer or object representations. */
395 struct value *
396 value_cast (struct type *type, struct value *arg2)
398 enum type_code code1;
399 enum type_code code2;
400 int scalar;
401 struct type *type2;
403 int convert_to_boolean = 0;
405 /* TYPE might be equal in meaning to the existing type of ARG2, but for
406 many reasons, might be a different type object (e.g. TYPE might be a
407 gdbarch owned type, while ARG2->type () could be an objfile owned
408 type).
410 In this case we want to preserve the LVAL of ARG2 as this allows the
411 resulting value to be used in more places. We do this by calling
412 VALUE_COPY if appropriate. */
413 if (types_deeply_equal (make_unqualified_type (arg2->type ()),
414 make_unqualified_type (type)))
416 /* If the types are exactly equal then we can avoid creating a new
417 value completely. */
418 if (arg2->type () != type)
420 arg2 = arg2->copy ();
421 arg2->deprecated_set_type (type);
423 return arg2;
426 if (is_fixed_point_type (type))
427 return value_cast_to_fixed_point (type, arg2);
429 /* Check if we are casting struct reference to struct reference. */
430 if (TYPE_IS_REFERENCE (check_typedef (type)))
432 /* We dereference type; then we recurse and finally
433 we generate value of the given reference. Nothing wrong with
434 that. */
435 struct type *t1 = check_typedef (type);
436 struct type *dereftype = check_typedef (t1->target_type ());
437 struct value *val = value_cast (dereftype, arg2);
439 return value_ref (val, t1->code ());
442 if (TYPE_IS_REFERENCE (check_typedef (arg2->type ())))
443 /* We deref the value and then do the cast. */
444 return value_cast (type, coerce_ref (arg2));
446 /* Strip typedefs / resolve stubs in order to get at the type's
447 code/length, but remember the original type, to use as the
448 resulting type of the cast, in case it was a typedef. */
449 struct type *to_type = type;
451 type = check_typedef (type);
452 code1 = type->code ();
453 arg2 = coerce_ref (arg2);
454 type2 = check_typedef (arg2->type ());
456 /* You can't cast to a reference type. See value_cast_pointers
457 instead. */
458 gdb_assert (!TYPE_IS_REFERENCE (type));
460 /* A cast to an undetermined-length array_type, such as
461 (TYPE [])OBJECT, is treated like a cast to (TYPE [N])OBJECT,
462 where N is sizeof(OBJECT)/sizeof(TYPE). */
463 if (code1 == TYPE_CODE_ARRAY)
465 struct type *element_type = type->target_type ();
466 unsigned element_length = check_typedef (element_type)->length ();
468 if (element_length > 0 && type->bounds ()->high.kind () == PROP_UNDEFINED)
470 struct type *range_type = type->index_type ();
471 int val_length = type2->length ();
472 LONGEST low_bound, high_bound, new_length;
474 if (!get_discrete_bounds (range_type, &low_bound, &high_bound))
475 low_bound = 0, high_bound = 0;
476 new_length = val_length / element_length;
477 if (val_length % element_length != 0)
478 warning (_("array element type size does not "
479 "divide object size in cast"));
480 /* FIXME-type-allocation: need a way to free this type when
481 we are done with it. */
482 type_allocator alloc (range_type->target_type ());
483 range_type = create_static_range_type (alloc,
484 range_type->target_type (),
485 low_bound,
486 new_length + low_bound - 1);
487 arg2->deprecated_set_type (create_array_type (alloc,
488 element_type,
489 range_type));
490 return arg2;
494 if (current_language->c_style_arrays_p ()
495 && type2->code () == TYPE_CODE_ARRAY
496 && !type2->is_vector ())
497 arg2 = value_coerce_array (arg2);
499 if (type2->code () == TYPE_CODE_FUNC)
500 arg2 = value_coerce_function (arg2);
502 type2 = check_typedef (arg2->type ());
503 code2 = type2->code ();
505 if (code1 == TYPE_CODE_COMPLEX)
506 return cast_into_complex (to_type, arg2);
507 if (code1 == TYPE_CODE_BOOL)
509 code1 = TYPE_CODE_INT;
510 convert_to_boolean = 1;
512 if (code1 == TYPE_CODE_CHAR)
513 code1 = TYPE_CODE_INT;
514 if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
515 code2 = TYPE_CODE_INT;
517 scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
518 || code2 == TYPE_CODE_DECFLOAT || code2 == TYPE_CODE_ENUM
519 || code2 == TYPE_CODE_RANGE
520 || is_fixed_point_type (type2));
522 if ((code1 == TYPE_CODE_STRUCT || code1 == TYPE_CODE_UNION)
523 && (code2 == TYPE_CODE_STRUCT || code2 == TYPE_CODE_UNION)
524 && type->name () != 0)
526 struct value *v = value_cast_structs (to_type, arg2);
528 if (v)
529 return v;
532 if (is_floating_type (type) && scalar)
534 if (is_floating_value (arg2))
536 struct value *v = value::allocate (to_type);
537 target_float_convert (arg2->contents ().data (), type2,
538 v->contents_raw ().data (), type);
539 return v;
541 else if (is_fixed_point_type (type2))
543 gdb_mpq fp_val;
545 fp_val.read_fixed_point (arg2->contents (),
546 type_byte_order (type2),
547 type2->is_unsigned (),
548 type2->fixed_point_scaling_factor ());
550 struct value *v = value::allocate (to_type);
551 target_float_from_host_double (v->contents_raw ().data (),
552 to_type, fp_val.as_double ());
553 return v;
556 /* The only option left is an integral type. */
557 if (type2->is_unsigned ())
558 return value_from_ulongest (to_type, value_as_long (arg2));
559 else
560 return value_from_longest (to_type, value_as_long (arg2));
562 else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
563 || code1 == TYPE_CODE_RANGE)
564 && (scalar || code2 == TYPE_CODE_PTR
565 || code2 == TYPE_CODE_MEMBERPTR))
567 gdb_mpz longest;
569 /* When we cast pointers to integers, we mustn't use
570 gdbarch_pointer_to_address to find the address the pointer
571 represents, as value_as_long would. GDB should evaluate
572 expressions just as the compiler would --- and the compiler
573 sees a cast as a simple reinterpretation of the pointer's
574 bits. */
575 if (code2 == TYPE_CODE_PTR)
576 longest = extract_unsigned_integer (arg2->contents (),
577 type_byte_order (type2));
578 else
579 longest = value_as_mpz (arg2);
580 if (convert_to_boolean)
581 longest = bool (longest);
583 return value_from_mpz (to_type, longest);
585 else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT
586 || code2 == TYPE_CODE_ENUM
587 || code2 == TYPE_CODE_RANGE))
589 /* type->length () is the length of a pointer, but we really
590 want the length of an address! -- we are really dealing with
591 addresses (i.e., gdb representations) not pointers (i.e.,
592 target representations) here.
594 This allows things like "print *(int *)0x01000234" to work
595 without printing a misleading message -- which would
596 otherwise occur when dealing with a target having two byte
597 pointers and four byte addresses. */
599 int addr_bit = gdbarch_addr_bit (type2->arch ());
600 gdb_mpz longest = value_as_mpz (arg2);
602 gdb_mpz addr_val = gdb_mpz (1) << addr_bit;
603 if (longest >= addr_val || longest <= -addr_val)
604 warning (_("value truncated"));
606 return value_from_mpz (to_type, longest);
608 else if (code1 == TYPE_CODE_METHODPTR && code2 == TYPE_CODE_INT
609 && value_as_long (arg2) == 0)
611 struct value *result = value::allocate (to_type);
613 cplus_make_method_ptr (to_type,
614 result->contents_writeable ().data (), 0, 0);
615 return result;
617 else if (code1 == TYPE_CODE_MEMBERPTR && code2 == TYPE_CODE_INT
618 && value_as_long (arg2) == 0)
620 /* The Itanium C++ ABI represents NULL pointers to members as
621 minus one, instead of biasing the normal case. */
622 return value_from_longest (to_type, -1);
624 else if (code1 == TYPE_CODE_ARRAY && type->is_vector ()
625 && code2 == TYPE_CODE_ARRAY && type2->is_vector ()
626 && type->length () != type2->length ())
627 error (_("Cannot convert between vector values of different sizes"));
628 else if (code1 == TYPE_CODE_ARRAY && type->is_vector () && scalar
629 && type->length () != type2->length ())
630 error (_("can only cast scalar to vector of same size"));
631 else if (code1 == TYPE_CODE_VOID)
633 return value::zero (to_type, not_lval);
635 else if (type->length () == type2->length ())
637 if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
638 return value_cast_pointers (to_type, arg2, 0);
640 arg2 = arg2->copy ();
641 arg2->deprecated_set_type (to_type);
642 arg2->set_enclosing_type (to_type);
643 arg2->set_pointed_to_offset (0); /* pai: chk_val */
644 return arg2;
646 else if (arg2->lval () == lval_memory)
647 return value_at_lazy (to_type, arg2->address ());
648 else
650 if (current_language->la_language == language_ada)
651 error (_("Invalid type conversion."));
652 error (_("Invalid cast."));
656 /* The C++ reinterpret_cast operator. */
658 struct value *
659 value_reinterpret_cast (struct type *type, struct value *arg)
661 struct value *result;
662 struct type *real_type = check_typedef (type);
663 struct type *arg_type, *dest_type;
664 int is_ref = 0;
665 enum type_code dest_code, arg_code;
667 /* Do reference, function, and array conversion. */
668 arg = coerce_array (arg);
670 /* Attempt to preserve the type the user asked for. */
671 dest_type = type;
673 /* If we are casting to a reference type, transform
674 reinterpret_cast<T&[&]>(V) to *reinterpret_cast<T*>(&V). */
675 if (TYPE_IS_REFERENCE (real_type))
677 is_ref = 1;
678 arg = value_addr (arg);
679 dest_type = lookup_pointer_type (dest_type->target_type ());
680 real_type = lookup_pointer_type (real_type);
683 arg_type = arg->type ();
685 dest_code = real_type->code ();
686 arg_code = arg_type->code ();
688 /* We can convert pointer types, or any pointer type to int, or int
689 type to pointer. */
690 if ((dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_INT)
691 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_PTR)
692 || (dest_code == TYPE_CODE_METHODPTR && arg_code == TYPE_CODE_INT)
693 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_METHODPTR)
694 || (dest_code == TYPE_CODE_MEMBERPTR && arg_code == TYPE_CODE_INT)
695 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_MEMBERPTR)
696 || (dest_code == arg_code
697 && (dest_code == TYPE_CODE_METHODPTR
698 || dest_code == TYPE_CODE_MEMBERPTR)))
699 result = value_cast (dest_type, arg);
700 else if (dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_PTR)
702 /* Don't do any up- or downcasting. */
703 result = arg->copy ();
704 result->deprecated_set_type (dest_type);
705 result->set_enclosing_type (dest_type);
706 result->set_pointed_to_offset (0);
708 else
709 error (_("Invalid reinterpret_cast"));
711 if (is_ref)
712 result = value_cast (type, value_ref (value_ind (result),
713 type->code ()));
715 return result;
718 /* A helper for value_dynamic_cast. This implements the first of two
719 runtime checks: we iterate over all the base classes of the value's
720 class which are equal to the desired class; if only one of these
721 holds the value, then it is the answer. */
723 static int
724 dynamic_cast_check_1 (struct type *desired_type,
725 const gdb_byte *valaddr,
726 LONGEST embedded_offset,
727 CORE_ADDR address,
728 struct value *val,
729 struct type *search_type,
730 CORE_ADDR arg_addr,
731 struct type *arg_type,
732 struct value **result)
734 int i, result_count = 0;
736 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
738 LONGEST offset = baseclass_offset (search_type, i, valaddr,
739 embedded_offset,
740 address, val);
742 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
744 if (address + embedded_offset + offset >= arg_addr
745 && address + embedded_offset + offset < arg_addr + arg_type->length ())
747 ++result_count;
748 if (!*result)
749 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
750 address + embedded_offset + offset);
753 else
754 result_count += dynamic_cast_check_1 (desired_type,
755 valaddr,
756 embedded_offset + offset,
757 address, val,
758 TYPE_BASECLASS (search_type, i),
759 arg_addr,
760 arg_type,
761 result);
764 return result_count;
767 /* A helper for value_dynamic_cast. This implements the second of two
768 runtime checks: we look for a unique public sibling class of the
769 argument's declared class. */
771 static int
772 dynamic_cast_check_2 (struct type *desired_type,
773 const gdb_byte *valaddr,
774 LONGEST embedded_offset,
775 CORE_ADDR address,
776 struct value *val,
777 struct type *search_type,
778 struct value **result)
780 int i, result_count = 0;
782 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
784 LONGEST offset;
786 if (! BASETYPE_VIA_PUBLIC (search_type, i))
787 continue;
789 offset = baseclass_offset (search_type, i, valaddr, embedded_offset,
790 address, val);
791 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
793 ++result_count;
794 if (*result == NULL)
795 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
796 address + embedded_offset + offset);
798 else
799 result_count += dynamic_cast_check_2 (desired_type,
800 valaddr,
801 embedded_offset + offset,
802 address, val,
803 TYPE_BASECLASS (search_type, i),
804 result);
807 return result_count;
810 /* The C++ dynamic_cast operator. */
812 struct value *
813 value_dynamic_cast (struct type *type, struct value *arg)
815 int full, using_enc;
816 LONGEST top;
817 struct type *resolved_type = check_typedef (type);
818 struct type *arg_type = check_typedef (arg->type ());
819 struct type *class_type, *rtti_type;
820 struct value *result, *tem, *original_arg = arg;
821 CORE_ADDR addr;
822 int is_ref = TYPE_IS_REFERENCE (resolved_type);
824 if (resolved_type->code () != TYPE_CODE_PTR
825 && !TYPE_IS_REFERENCE (resolved_type))
826 error (_("Argument to dynamic_cast must be a pointer or reference type"));
827 if (resolved_type->target_type ()->code () != TYPE_CODE_VOID
828 && resolved_type->target_type ()->code () != TYPE_CODE_STRUCT)
829 error (_("Argument to dynamic_cast must be pointer to class or `void *'"));
831 class_type = check_typedef (resolved_type->target_type ());
832 if (resolved_type->code () == TYPE_CODE_PTR)
834 if (arg_type->code () != TYPE_CODE_PTR
835 && ! (arg_type->code () == TYPE_CODE_INT
836 && value_as_long (arg) == 0))
837 error (_("Argument to dynamic_cast does not have pointer type"));
838 if (arg_type->code () == TYPE_CODE_PTR)
840 arg_type = check_typedef (arg_type->target_type ());
841 if (arg_type->code () != TYPE_CODE_STRUCT)
842 error (_("Argument to dynamic_cast does "
843 "not have pointer to class type"));
846 /* Handle NULL pointers. */
847 if (value_as_long (arg) == 0)
848 return value::zero (type, not_lval);
850 arg = value_ind (arg);
852 else
854 if (arg_type->code () != TYPE_CODE_STRUCT)
855 error (_("Argument to dynamic_cast does not have class type"));
858 /* If the classes are the same, just return the argument. */
859 if (class_types_same_p (class_type, arg_type))
860 return value_cast (type, original_arg);
862 /* If the target type is a unique base class of the argument's
863 declared type, just cast it. */
864 if (is_ancestor (class_type, arg_type))
866 if (is_unique_ancestor (class_type, arg))
867 return value_cast (type, original_arg);
868 error (_("Ambiguous dynamic_cast"));
871 rtti_type = value_rtti_type (arg, &full, &top, &using_enc);
872 if (! rtti_type)
873 error (_("Couldn't determine value's most derived type for dynamic_cast"));
875 /* Compute the most derived object's address. */
876 addr = arg->address ();
877 if (full)
879 /* Done. */
881 else if (using_enc)
882 addr += top;
883 else
884 addr += top + arg->embedded_offset ();
886 /* dynamic_cast<void *> means to return a pointer to the
887 most-derived object. */
888 if (resolved_type->code () == TYPE_CODE_PTR
889 && resolved_type->target_type ()->code () == TYPE_CODE_VOID)
890 return value_at_lazy (type, addr);
892 tem = value_at (resolved_type->target_type (), addr);
893 type = (is_ref
894 ? lookup_reference_type (tem->type (), resolved_type->code ())
895 : lookup_pointer_type (tem->type ()));
897 /* The first dynamic check specified in 5.2.7. */
898 if (is_public_ancestor (arg_type, resolved_type->target_type ()))
900 if (class_types_same_p (rtti_type, resolved_type->target_type ()))
901 return (is_ref
902 ? value_ref (tem, resolved_type->code ())
903 : value_addr (tem));
904 result = NULL;
905 if (dynamic_cast_check_1 (resolved_type->target_type (),
906 tem->contents_for_printing ().data (),
907 tem->embedded_offset (),
908 tem->address (), tem,
909 rtti_type, addr,
910 arg_type,
911 &result) == 1)
912 return value_cast (type,
913 is_ref
914 ? value_ref (result, resolved_type->code ())
915 : value_addr (result));
918 /* The second dynamic check specified in 5.2.7. */
919 result = NULL;
920 if (is_public_ancestor (arg_type, rtti_type)
921 && dynamic_cast_check_2 (resolved_type->target_type (),
922 tem->contents_for_printing ().data (),
923 tem->embedded_offset (),
924 tem->address (), tem,
925 rtti_type, &result) == 1)
926 return value_cast (type,
927 is_ref
928 ? value_ref (result, resolved_type->code ())
929 : value_addr (result));
931 if (resolved_type->code () == TYPE_CODE_PTR)
932 return value::zero (type, not_lval);
934 error (_("dynamic_cast failed"));
937 /* Create a not_lval value of numeric type TYPE that is one, and return it. */
939 struct value *
940 value_one (struct type *type)
942 struct type *type1 = check_typedef (type);
943 struct value *val;
945 if (is_integral_type (type1) || is_floating_type (type1))
947 val = value_from_longest (type, (LONGEST) 1);
949 else if (type1->code () == TYPE_CODE_ARRAY && type1->is_vector ())
951 struct type *eltype = check_typedef (type1->target_type ());
952 int i;
953 LONGEST low_bound, high_bound;
955 if (!get_array_bounds (type1, &low_bound, &high_bound))
956 error (_("Could not determine the vector bounds"));
958 val = value::allocate (type);
959 gdb::array_view<gdb_byte> val_contents = val->contents_writeable ();
960 int elt_len = eltype->length ();
962 for (i = 0; i < high_bound - low_bound + 1; i++)
964 value *tmp = value_one (eltype);
965 copy (tmp->contents_all (),
966 val_contents.slice (i * elt_len, elt_len));
969 else
971 error (_("Not a numeric type."));
974 /* value_one result is never used for assignments to. */
975 gdb_assert (val->lval () == not_lval);
977 return val;
980 /* Helper function for value_at, value_at_lazy, and value_at_lazy_stack.
981 The type of the created value may differ from the passed type TYPE.
982 Make sure to retrieve the returned values's new type after this call
983 e.g. in case the type is a variable length array. */
985 static struct value *
986 get_value_at (struct type *type, CORE_ADDR addr, const frame_info_ptr &frame,
987 int lazy)
989 struct value *val;
991 if (check_typedef (type)->code () == TYPE_CODE_VOID)
992 error (_("Attempt to dereference a generic pointer."));
994 val = value_from_contents_and_address (type, NULL, addr, frame);
996 if (!lazy)
997 val->fetch_lazy ();
999 return val;
1002 /* Return a value with type TYPE located at ADDR.
1004 Call value_at only if the data needs to be fetched immediately;
1005 if we can be 'lazy' and defer the fetch, perhaps indefinitely, call
1006 value_at_lazy instead. value_at_lazy simply records the address of
1007 the data and sets the lazy-evaluation-required flag. The lazy flag
1008 is tested in the value_contents macro, which is used if and when
1009 the contents are actually required. The type of the created value
1010 may differ from the passed type TYPE. Make sure to retrieve the
1011 returned values's new type after this call e.g. in case the type
1012 is a variable length array.
1014 Note: value_at does *NOT* handle embedded offsets; perform such
1015 adjustments before or after calling it. */
1017 struct value *
1018 value_at (struct type *type, CORE_ADDR addr)
1020 return get_value_at (type, addr, nullptr, 0);
1023 /* See value.h. */
1025 struct value *
1026 value_at_non_lval (struct type *type, CORE_ADDR addr)
1028 struct value *result = value_at (type, addr);
1029 result->set_lval (not_lval);
1030 return result;
1033 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).
1034 The type of the created value may differ from the passed type TYPE.
1035 Make sure to retrieve the returned values's new type after this call
1036 e.g. in case the type is a variable length array. */
1038 struct value *
1039 value_at_lazy (struct type *type, CORE_ADDR addr, const frame_info_ptr &frame)
1041 return get_value_at (type, addr, frame, 1);
1044 void
1045 read_value_memory (struct value *val, LONGEST bit_offset,
1046 bool stack, CORE_ADDR memaddr,
1047 gdb_byte *buffer, size_t length)
1049 ULONGEST xfered_total = 0;
1050 struct gdbarch *arch = val->arch ();
1051 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1052 enum target_object object;
1054 object = stack ? TARGET_OBJECT_STACK_MEMORY : TARGET_OBJECT_MEMORY;
1056 while (xfered_total < length)
1058 enum target_xfer_status status;
1059 ULONGEST xfered_partial;
1061 status = target_xfer_partial (current_inferior ()->top_target (),
1062 object, NULL,
1063 buffer + xfered_total * unit_size, NULL,
1064 memaddr + xfered_total,
1065 length - xfered_total,
1066 &xfered_partial);
1068 if (status == TARGET_XFER_OK)
1069 /* nothing */;
1070 else if (status == TARGET_XFER_UNAVAILABLE)
1071 val->mark_bits_unavailable ((xfered_total * HOST_CHAR_BIT
1072 + bit_offset),
1073 xfered_partial * HOST_CHAR_BIT);
1074 else if (status == TARGET_XFER_EOF)
1075 memory_error (TARGET_XFER_E_IO, memaddr + xfered_total);
1076 else
1077 memory_error (status, memaddr + xfered_total);
1079 xfered_total += xfered_partial;
1080 QUIT;
1084 /* Store the contents of FROMVAL into the location of TOVAL.
1085 Return a new value with the location of TOVAL and contents of FROMVAL. */
1087 struct value *
1088 value_assign (struct value *toval, struct value *fromval)
1090 struct type *type;
1091 struct value *val;
1092 struct frame_id old_frame;
1094 if (!toval->deprecated_modifiable ())
1095 error (_("Left operand of assignment is not a modifiable lvalue."));
1097 toval = coerce_ref (toval);
1099 type = toval->type ();
1100 if (toval->lval () != lval_internalvar)
1101 fromval = value_cast (type, fromval);
1102 else
1104 /* Coerce arrays and functions to pointers, except for arrays
1105 which only live in GDB's storage. */
1106 if (!value_must_coerce_to_target (fromval))
1107 fromval = coerce_array (fromval);
1110 type = check_typedef (type);
1112 /* Since modifying a register can trash the frame chain, and
1113 modifying memory can trash the frame cache, we save the old frame
1114 and then restore the new frame afterwards. */
1115 old_frame = get_frame_id (deprecated_safe_get_selected_frame ());
1117 switch (toval->lval ())
1119 case lval_internalvar:
1120 set_internalvar (VALUE_INTERNALVAR (toval), fromval);
1121 return value_of_internalvar (type->arch (),
1122 VALUE_INTERNALVAR (toval));
1124 case lval_internalvar_component:
1126 LONGEST offset = toval->offset ();
1128 /* Are we dealing with a bitfield?
1130 It is important to mention that `toval->parent ()' is
1131 non-NULL iff `toval->bitsize ()' is non-zero. */
1132 if (toval->bitsize ())
1134 /* VALUE_INTERNALVAR below refers to the parent value, while
1135 the offset is relative to this parent value. */
1136 gdb_assert (toval->parent ()->parent () == NULL);
1137 offset += toval->parent ()->offset ();
1140 set_internalvar_component (VALUE_INTERNALVAR (toval),
1141 offset,
1142 toval->bitpos (),
1143 toval->bitsize (),
1144 fromval);
1146 break;
1148 case lval_memory:
1150 const gdb_byte *dest_buffer;
1151 CORE_ADDR changed_addr;
1152 int changed_len;
1153 gdb_byte buffer[sizeof (LONGEST)];
1155 if (toval->bitsize ())
1157 struct value *parent = toval->parent ();
1159 changed_addr = parent->address () + toval->offset ();
1160 changed_len = (toval->bitpos ()
1161 + toval->bitsize ()
1162 + HOST_CHAR_BIT - 1)
1163 / HOST_CHAR_BIT;
1165 /* If we can read-modify-write exactly the size of the
1166 containing type (e.g. short or int) then do so. This
1167 is safer for volatile bitfields mapped to hardware
1168 registers. */
1169 if (changed_len < type->length ()
1170 && type->length () <= (int) sizeof (LONGEST)
1171 && ((LONGEST) changed_addr % type->length ()) == 0)
1172 changed_len = type->length ();
1174 if (changed_len > (int) sizeof (LONGEST))
1175 error (_("Can't handle bitfields which "
1176 "don't fit in a %d bit word."),
1177 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1179 read_memory (changed_addr, buffer, changed_len);
1180 modify_field (type, buffer, value_as_long (fromval),
1181 toval->bitpos (), toval->bitsize ());
1182 dest_buffer = buffer;
1184 else
1186 changed_addr = toval->address ();
1187 changed_len = type_length_units (type);
1188 dest_buffer = fromval->contents ().data ();
1191 write_memory_with_notification (changed_addr, dest_buffer, changed_len);
1193 break;
1195 case lval_register:
1197 frame_info_ptr next_frame = frame_find_by_id (toval->next_frame_id ());
1198 int value_reg = toval->regnum ();
1200 if (next_frame == nullptr)
1201 error (_("Value being assigned to is no longer active."));
1203 gdbarch *gdbarch = frame_unwind_arch (next_frame);
1205 if (toval->bitsize ())
1207 struct value *parent = toval->parent ();
1208 LONGEST offset = parent->offset () + toval->offset ();
1209 size_t changed_len;
1210 gdb_byte buffer[sizeof (LONGEST)];
1211 int optim, unavail;
1213 changed_len = (toval->bitpos ()
1214 + toval->bitsize ()
1215 + HOST_CHAR_BIT - 1)
1216 / HOST_CHAR_BIT;
1218 if (changed_len > sizeof (LONGEST))
1219 error (_("Can't handle bitfields which "
1220 "don't fit in a %d bit word."),
1221 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1223 if (!get_frame_register_bytes (next_frame, value_reg, offset,
1224 { buffer, changed_len }, &optim,
1225 &unavail))
1227 if (optim)
1228 throw_error (OPTIMIZED_OUT_ERROR,
1229 _("value has been optimized out"));
1230 if (unavail)
1231 throw_error (NOT_AVAILABLE_ERROR,
1232 _("value is not available"));
1235 modify_field (type, buffer, value_as_long (fromval),
1236 toval->bitpos (), toval->bitsize ());
1238 put_frame_register_bytes (next_frame, value_reg, offset,
1239 { buffer, changed_len });
1241 else
1243 if (gdbarch_convert_register_p (gdbarch, toval->regnum (), type))
1245 /* If TOVAL is a special machine register requiring
1246 conversion of program values to a special raw
1247 format. */
1248 gdbarch_value_to_register (gdbarch,
1249 get_prev_frame_always (next_frame),
1250 toval->regnum (), type,
1251 fromval->contents ().data ());
1253 else
1254 put_frame_register_bytes (next_frame, value_reg,
1255 toval->offset (),
1256 fromval->contents ());
1259 gdb::observers::register_changed.notify
1260 (get_prev_frame_always (next_frame), value_reg);
1261 break;
1264 case lval_computed:
1266 const struct lval_funcs *funcs = toval->computed_funcs ();
1268 if (funcs->write != NULL)
1270 funcs->write (toval, fromval);
1271 break;
1274 [[fallthrough]];
1276 default:
1277 error (_("Left operand of assignment is not an lvalue."));
1280 /* Assigning to the stack pointer, frame pointer, and other
1281 (architecture and calling convention specific) registers may
1282 cause the frame cache and regcache to be out of date. Assigning to memory
1283 also can. We just do this on all assignments to registers or
1284 memory, for simplicity's sake; I doubt the slowdown matters. */
1285 switch (toval->lval ())
1287 case lval_memory:
1288 case lval_register:
1289 case lval_computed:
1291 gdb::observers::target_changed.notify
1292 (current_inferior ()->top_target ());
1294 /* Having destroyed the frame cache, restore the selected
1295 frame. */
1297 /* FIXME: cagney/2002-11-02: There has to be a better way of
1298 doing this. Instead of constantly saving/restoring the
1299 frame. Why not create a get_selected_frame() function that,
1300 having saved the selected frame's ID can automatically
1301 re-find the previously selected frame automatically. */
1304 frame_info_ptr fi = frame_find_by_id (old_frame);
1306 if (fi != NULL)
1307 select_frame (fi);
1310 break;
1311 default:
1312 break;
1315 /* If the field does not entirely fill a LONGEST, then zero the sign
1316 bits. If the field is signed, and is negative, then sign
1317 extend. */
1318 if ((toval->bitsize () > 0)
1319 && (toval->bitsize () < 8 * (int) sizeof (LONGEST)))
1321 LONGEST fieldval = value_as_long (fromval);
1322 LONGEST valmask = (((ULONGEST) 1) << toval->bitsize ()) - 1;
1324 fieldval &= valmask;
1325 if (!type->is_unsigned ()
1326 && (fieldval & (valmask ^ (valmask >> 1))))
1327 fieldval |= ~valmask;
1329 fromval = value_from_longest (type, fieldval);
1332 /* The return value is a copy of TOVAL so it shares its location
1333 information, but its contents are updated from FROMVAL. This
1334 implies the returned value is not lazy, even if TOVAL was. */
1335 val = toval->copy ();
1336 val->set_lazy (false);
1337 copy (fromval->contents (), val->contents_raw ());
1339 /* We copy over the enclosing type and pointed-to offset from FROMVAL
1340 in the case of pointer types. For object types, the enclosing type
1341 and embedded offset must *not* be copied: the target object referred
1342 to by TOVAL retains its original dynamic type after assignment. */
1343 if (type->code () == TYPE_CODE_PTR)
1345 val->set_enclosing_type (fromval->enclosing_type ());
1346 val->set_pointed_to_offset (fromval->pointed_to_offset ());
1349 return val;
1352 /* Extend a value ARG1 to COUNT repetitions of its type. */
1354 struct value *
1355 value_repeat (struct value *arg1, int count)
1357 struct value *val;
1359 arg1 = coerce_ref (arg1);
1361 if (arg1->lval () != lval_memory)
1362 error (_("Only values in memory can be extended with '@'."));
1363 if (count < 1)
1364 error (_("Invalid number %d of repetitions."), count);
1366 val = allocate_repeat_value (arg1->enclosing_type (), count);
1368 val->set_lval (lval_memory);
1369 val->set_address (arg1->address ());
1371 read_value_memory (val, 0, val->stack (), val->address (),
1372 val->contents_all_raw ().data (),
1373 type_length_units (val->enclosing_type ()));
1375 return val;
1378 struct value *
1379 value_of_variable (struct symbol *var, const struct block *b)
1381 frame_info_ptr frame = NULL;
1383 if (symbol_read_needs_frame (var))
1384 frame = get_selected_frame (_("No frame selected."));
1386 return read_var_value (var, b, frame);
1389 struct value *
1390 address_of_variable (struct symbol *var, const struct block *b)
1392 struct type *type = var->type ();
1393 struct value *val;
1395 /* Evaluate it first; if the result is a memory address, we're fine.
1396 Lazy evaluation pays off here. */
1398 val = value_of_variable (var, b);
1399 type = val->type ();
1401 if ((val->lval () == lval_memory && val->lazy ())
1402 || type->code () == TYPE_CODE_FUNC)
1404 CORE_ADDR addr = val->address ();
1406 return value_from_pointer (lookup_pointer_type (type), addr);
1409 /* Not a memory address; check what the problem was. */
1410 switch (val->lval ())
1412 case lval_register:
1414 const char *regname;
1416 frame_info_ptr frame = frame_find_by_id (val->next_frame_id ());
1417 gdb_assert (frame != nullptr);
1419 regname
1420 = gdbarch_register_name (get_frame_arch (frame), val->regnum ());
1421 gdb_assert (regname != nullptr && *regname != '\0');
1423 error (_("Address requested for identifier "
1424 "\"%s\" which is in register $%s"),
1425 var->print_name (), regname);
1426 break;
1429 default:
1430 error (_("Can't take address of \"%s\" which isn't an lvalue."),
1431 var->print_name ());
1432 break;
1435 return val;
1438 /* See value.h. */
1440 bool
1441 value_must_coerce_to_target (struct value *val)
1443 struct type *valtype;
1445 /* The only lval kinds which do not live in target memory. */
1446 if (val->lval () != not_lval
1447 && val->lval () != lval_internalvar
1448 && val->lval () != lval_xcallable)
1449 return false;
1451 valtype = check_typedef (val->type ());
1453 switch (valtype->code ())
1455 case TYPE_CODE_ARRAY:
1456 return valtype->is_vector () ? 0 : 1;
1457 case TYPE_CODE_STRING:
1458 return true;
1459 default:
1460 return false;
1464 /* Make sure that VAL lives in target memory if it's supposed to. For
1465 instance, strings are constructed as character arrays in GDB's
1466 storage, and this function copies them to the target. */
1468 struct value *
1469 value_coerce_to_target (struct value *val)
1471 LONGEST length;
1472 CORE_ADDR addr;
1474 if (!value_must_coerce_to_target (val))
1475 return val;
1477 length = check_typedef (val->type ())->length ();
1478 addr = allocate_space_in_inferior (length);
1479 write_memory (addr, val->contents ().data (), length);
1480 return value_at_lazy (val->type (), addr);
1483 /* Given a value which is an array, return a value which is a pointer
1484 to its first element, regardless of whether or not the array has a
1485 nonzero lower bound.
1487 FIXME: A previous comment here indicated that this routine should
1488 be substracting the array's lower bound. It's not clear to me that
1489 this is correct. Given an array subscripting operation, it would
1490 certainly work to do the adjustment here, essentially computing:
1492 (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
1494 However I believe a more appropriate and logical place to account
1495 for the lower bound is to do so in value_subscript, essentially
1496 computing:
1498 (&array[0] + ((index - lowerbound) * sizeof array[0]))
1500 As further evidence consider what would happen with operations
1501 other than array subscripting, where the caller would get back a
1502 value that had an address somewhere before the actual first element
1503 of the array, and the information about the lower bound would be
1504 lost because of the coercion to pointer type. */
1506 struct value *
1507 value_coerce_array (struct value *arg1)
1509 struct type *type = check_typedef (arg1->type ());
1511 /* If the user tries to do something requiring a pointer with an
1512 array that has not yet been pushed to the target, then this would
1513 be a good time to do so. */
1514 arg1 = value_coerce_to_target (arg1);
1516 if (arg1->lval () != lval_memory)
1517 error (_("Attempt to take address of value not located in memory."));
1519 return value_from_pointer (lookup_pointer_type (type->target_type ()),
1520 arg1->address ());
1523 /* Given a value which is a function, return a value which is a pointer
1524 to it. */
1526 struct value *
1527 value_coerce_function (struct value *arg1)
1529 struct value *retval;
1531 if (arg1->lval () != lval_memory)
1532 error (_("Attempt to take address of value not located in memory."));
1534 retval = value_from_pointer (lookup_pointer_type (arg1->type ()),
1535 arg1->address ());
1536 return retval;
1539 /* Return a pointer value for the object for which ARG1 is the
1540 contents. */
1542 struct value *
1543 value_addr (struct value *arg1)
1545 struct value *arg2;
1546 struct type *type = check_typedef (arg1->type ());
1548 if (TYPE_IS_REFERENCE (type))
1550 if (arg1->bits_synthetic_pointer (arg1->embedded_offset (),
1551 TARGET_CHAR_BIT * type->length ()))
1552 arg1 = coerce_ref (arg1);
1553 else
1555 /* Copy the value, but change the type from (T&) to (T*). We
1556 keep the same location information, which is efficient, and
1557 allows &(&X) to get the location containing the reference.
1558 Do the same to its enclosing type for consistency. */
1559 struct type *type_ptr
1560 = lookup_pointer_type (type->target_type ());
1561 struct type *enclosing_type
1562 = check_typedef (arg1->enclosing_type ());
1563 struct type *enclosing_type_ptr
1564 = lookup_pointer_type (enclosing_type->target_type ());
1566 arg2 = arg1->copy ();
1567 arg2->deprecated_set_type (type_ptr);
1568 arg2->set_enclosing_type (enclosing_type_ptr);
1570 return arg2;
1573 if (type->code () == TYPE_CODE_FUNC)
1574 return value_coerce_function (arg1);
1576 /* If this is an array that has not yet been pushed to the target,
1577 then this would be a good time to force it to memory. */
1578 arg1 = value_coerce_to_target (arg1);
1580 if (arg1->lval () != lval_memory)
1581 error (_("Attempt to take address of value not located in memory."));
1583 /* Get target memory address. */
1584 arg2 = value_from_pointer (lookup_pointer_type (arg1->type ()),
1585 (arg1->address ()
1586 + arg1->embedded_offset ()));
1588 /* This may be a pointer to a base subobject; so remember the
1589 full derived object's type ... */
1590 arg2->set_enclosing_type (lookup_pointer_type (arg1->enclosing_type ()));
1591 /* ... and also the relative position of the subobject in the full
1592 object. */
1593 arg2->set_pointed_to_offset (arg1->embedded_offset ());
1594 return arg2;
1597 /* Return a reference value for the object for which ARG1 is the
1598 contents. */
1600 struct value *
1601 value_ref (struct value *arg1, enum type_code refcode)
1603 struct value *arg2;
1604 struct type *type = check_typedef (arg1->type ());
1606 gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1608 if ((type->code () == TYPE_CODE_REF
1609 || type->code () == TYPE_CODE_RVALUE_REF)
1610 && type->code () == refcode)
1611 return arg1;
1613 arg2 = value_addr (arg1);
1614 arg2->deprecated_set_type (lookup_reference_type (type, refcode));
1615 return arg2;
1618 /* Given a value of a pointer type, apply the C unary * operator to
1619 it. */
1621 struct value *
1622 value_ind (struct value *arg1)
1624 struct type *base_type;
1625 struct value *arg2;
1627 arg1 = coerce_array (arg1);
1629 base_type = check_typedef (arg1->type ());
1631 if (arg1->lval () == lval_computed)
1633 const struct lval_funcs *funcs = arg1->computed_funcs ();
1635 if (funcs->indirect)
1637 struct value *result = funcs->indirect (arg1);
1639 if (result)
1640 return result;
1644 if (base_type->code () == TYPE_CODE_PTR)
1646 struct type *enc_type;
1648 /* We may be pointing to something embedded in a larger object.
1649 Get the real type of the enclosing object. */
1650 enc_type = check_typedef (arg1->enclosing_type ());
1651 enc_type = enc_type->target_type ();
1653 CORE_ADDR base_addr;
1654 if (check_typedef (enc_type)->code () == TYPE_CODE_FUNC
1655 || check_typedef (enc_type)->code () == TYPE_CODE_METHOD)
1657 /* For functions, go through find_function_addr, which knows
1658 how to handle function descriptors. */
1659 base_addr = find_function_addr (arg1, NULL);
1661 else
1663 /* Retrieve the enclosing object pointed to. */
1664 base_addr = (value_as_address (arg1)
1665 - arg1->pointed_to_offset ());
1667 arg2 = value_at_lazy (enc_type, base_addr);
1668 enc_type = arg2->type ();
1669 return readjust_indirect_value_type (arg2, enc_type, base_type,
1670 arg1, base_addr);
1673 error (_("Attempt to take contents of a non-pointer value."));
1676 /* Create a value for an array by allocating space in GDB, copying the
1677 data into that space, and then setting up an array value.
1679 The array bounds are set from LOWBOUND and the size of ELEMVEC, and
1680 the array is populated from the values passed in ELEMVEC.
1682 The element type of the array is inherited from the type of the
1683 first element, and all elements must have the same size (though we
1684 don't currently enforce any restriction on their types). */
1686 struct value *
1687 value_array (int lowbound, gdb::array_view<struct value *> elemvec)
1689 int idx;
1690 ULONGEST typelength;
1691 struct value *val;
1692 struct type *arraytype;
1694 /* Validate that the bounds are reasonable and that each of the
1695 elements have the same size. */
1697 typelength = type_length_units (elemvec[0]->enclosing_type ());
1698 for (struct value *other : elemvec.slice (1))
1700 if (type_length_units (other->enclosing_type ()) != typelength)
1702 error (_("array elements must all be the same size"));
1706 arraytype = lookup_array_range_type (elemvec[0]->enclosing_type (),
1707 lowbound,
1708 lowbound + elemvec.size () - 1);
1710 if (!current_language->c_style_arrays_p ())
1712 val = value::allocate (arraytype);
1713 for (idx = 0; idx < elemvec.size (); idx++)
1714 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1715 return val;
1718 /* Allocate space to store the array, and then initialize it by
1719 copying in each element. */
1721 val = value::allocate (arraytype);
1722 for (idx = 0; idx < elemvec.size (); idx++)
1723 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1724 return val;
1727 /* See value.h. */
1729 struct value *
1730 value_cstring (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1732 struct value *val;
1733 int lowbound = current_language->string_lower_bound ();
1734 ssize_t highbound = count + 1;
1735 struct type *stringtype
1736 = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1738 val = value::allocate (stringtype);
1739 ssize_t len = count * char_type->length ();
1740 memcpy (val->contents_raw ().data (), ptr, len);
1741 /* Write the terminating null-character. */
1742 memset (val->contents_raw ().data () + len, 0, char_type->length ());
1743 return val;
1746 /* See value.h. */
1748 struct value *
1749 value_string (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1751 struct value *val;
1752 int lowbound = current_language->string_lower_bound ();
1753 ssize_t highbound = count;
1754 struct type *stringtype
1755 = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1757 val = value::allocate (stringtype);
1758 ssize_t len = count * char_type->length ();
1759 memcpy (val->contents_raw ().data (), ptr, len);
1760 return val;
1764 /* See if we can pass arguments in T2 to a function which takes arguments
1765 of types T1. T1 is a list of NARGS arguments, and T2 is an array_view
1766 of the values we're trying to pass. If some arguments need coercion of
1767 some sort, then the coerced values are written into T2. Return value is
1768 0 if the arguments could be matched, or the position at which they
1769 differ if not.
1771 STATICP is nonzero if the T1 argument list came from a static
1772 member function. T2 must still include the ``this'' pointer, but
1773 it will be skipped.
1775 For non-static member functions, we ignore the first argument,
1776 which is the type of the instance variable. This is because we
1777 want to handle calls with objects from derived classes. This is
1778 not entirely correct: we should actually check to make sure that a
1779 requested operation is type secure, shouldn't we? FIXME. */
1781 static int
1782 typecmp (bool staticp, bool varargs, int nargs,
1783 struct field t1[], gdb::array_view<value *> t2)
1785 int i;
1787 /* Skip ``this'' argument if applicable. T2 will always include
1788 THIS. */
1789 if (staticp)
1790 t2 = t2.slice (1);
1792 for (i = 0;
1793 (i < nargs) && t1[i].type ()->code () != TYPE_CODE_VOID;
1794 i++)
1796 struct type *tt1, *tt2;
1798 if (i == t2.size ())
1799 return i + 1;
1801 tt1 = check_typedef (t1[i].type ());
1802 tt2 = check_typedef (t2[i]->type ());
1804 if (TYPE_IS_REFERENCE (tt1)
1805 /* We should be doing hairy argument matching, as below. */
1806 && (check_typedef (tt1->target_type ())->code ()
1807 == tt2->code ()))
1809 if (tt2->code () == TYPE_CODE_ARRAY)
1810 t2[i] = value_coerce_array (t2[i]);
1811 else
1812 t2[i] = value_ref (t2[i], tt1->code ());
1813 continue;
1816 /* djb - 20000715 - Until the new type structure is in the
1817 place, and we can attempt things like implicit conversions,
1818 we need to do this so you can take something like a map<const
1819 char *>, and properly access map["hello"], because the
1820 argument to [] will be a reference to a pointer to a char,
1821 and the argument will be a pointer to a char. */
1822 while (TYPE_IS_REFERENCE (tt1) || tt1->code () == TYPE_CODE_PTR)
1824 tt1 = check_typedef ( tt1->target_type () );
1826 while (tt2->code () == TYPE_CODE_ARRAY
1827 || tt2->code () == TYPE_CODE_PTR
1828 || TYPE_IS_REFERENCE (tt2))
1830 tt2 = check_typedef (tt2->target_type ());
1832 if (tt1->code () == tt2->code ())
1833 continue;
1834 /* Array to pointer is a `trivial conversion' according to the
1835 ARM. */
1837 /* We should be doing much hairier argument matching (see
1838 section 13.2 of the ARM), but as a quick kludge, just check
1839 for the same type code. */
1840 if (t1[i].type ()->code () != t2[i]->type ()->code ())
1841 return i + 1;
1843 if (varargs || i == t2.size ())
1844 return 0;
1845 return i + 1;
1848 /* Helper class for search_struct_field that keeps track of found
1849 results and possibly throws an exception if the search yields
1850 ambiguous results. See search_struct_field for description of
1851 LOOKING_FOR_BASECLASS. */
1853 struct struct_field_searcher
1855 /* A found field. */
1856 struct found_field
1858 /* Path to the structure where the field was found. */
1859 std::vector<struct type *> path;
1861 /* The field found. */
1862 struct value *field_value;
1865 /* See corresponding fields for description of parameters. */
1866 struct_field_searcher (const char *name,
1867 struct type *outermost_type,
1868 bool looking_for_baseclass)
1869 : m_name (name),
1870 m_looking_for_baseclass (looking_for_baseclass),
1871 m_outermost_type (outermost_type)
1875 /* The search entry point. If LOOKING_FOR_BASECLASS is true and the
1876 base class search yields ambiguous results, this throws an
1877 exception. If LOOKING_FOR_BASECLASS is false, the found fields
1878 are accumulated and the caller (search_struct_field) takes care
1879 of throwing an error if the field search yields ambiguous
1880 results. The latter is done that way so that the error message
1881 can include a list of all the found candidates. */
1882 void search (struct value *arg, LONGEST offset, struct type *type);
1884 const std::vector<found_field> &fields ()
1886 return m_fields;
1889 struct value *baseclass ()
1891 return m_baseclass;
1894 private:
1895 /* Update results to include V, a found field/baseclass. */
1896 void update_result (struct value *v, LONGEST boffset);
1898 /* The name of the field/baseclass we're searching for. */
1899 const char *m_name;
1901 /* Whether we're looking for a baseclass, or a field. */
1902 const bool m_looking_for_baseclass;
1904 /* The offset of the baseclass containing the field/baseclass we
1905 last recorded. */
1906 LONGEST m_last_boffset = 0;
1908 /* If looking for a baseclass, then the result is stored here. */
1909 struct value *m_baseclass = nullptr;
1911 /* When looking for fields, the found candidates are stored
1912 here. */
1913 std::vector<found_field> m_fields;
1915 /* The type of the initial type passed to search_struct_field; this
1916 is used for error reporting when the lookup is ambiguous. */
1917 struct type *m_outermost_type;
1919 /* The full path to the struct being inspected. E.g. for field 'x'
1920 defined in class B inherited by class A, we have A and B pushed
1921 on the path. */
1922 std::vector <struct type *> m_struct_path;
1925 void
1926 struct_field_searcher::update_result (struct value *v, LONGEST boffset)
1928 if (v != NULL)
1930 if (m_looking_for_baseclass)
1932 if (m_baseclass != nullptr
1933 /* The result is not ambiguous if all the classes that are
1934 found occupy the same space. */
1935 && m_last_boffset != boffset)
1936 error (_("base class '%s' is ambiguous in type '%s'"),
1937 m_name, TYPE_SAFE_NAME (m_outermost_type));
1939 m_baseclass = v;
1940 m_last_boffset = boffset;
1942 else
1944 /* The field is not ambiguous if it occupies the same
1945 space. */
1946 if (m_fields.empty () || m_last_boffset != boffset)
1947 m_fields.push_back ({m_struct_path, v});
1948 else
1950 /*Fields can occupy the same space and have the same name (be
1951 ambiguous). This can happen when fields in two different base
1952 classes are marked [[no_unique_address]] and have the same name.
1953 The C++ standard says that such fields can only occupy the same
1954 space if they are of different type, but we don't rely on that in
1955 the following code. */
1956 bool ambiguous = false, insert = true;
1957 for (const found_field &field: m_fields)
1959 if(field.path.back () != m_struct_path.back ())
1961 /* Same boffset points to members of different classes.
1962 We have found an ambiguity and should record it. */
1963 ambiguous = true;
1965 else
1967 /* We don't need to insert this value again, because a
1968 non-ambiguous path already leads to it. */
1969 insert = false;
1970 break;
1973 if (ambiguous && insert)
1974 m_fields.push_back ({m_struct_path, v});
1980 /* A helper for search_struct_field. This does all the work; most
1981 arguments are as passed to search_struct_field. */
1983 void
1984 struct_field_searcher::search (struct value *arg1, LONGEST offset,
1985 struct type *type)
1987 int i;
1988 int nbases;
1990 m_struct_path.push_back (type);
1991 SCOPE_EXIT { m_struct_path.pop_back (); };
1993 type = check_typedef (type);
1994 nbases = TYPE_N_BASECLASSES (type);
1996 if (!m_looking_for_baseclass)
1997 for (i = type->num_fields () - 1; i >= nbases; i--)
1999 const char *t_field_name = type->field (i).name ();
2001 if (t_field_name && (strcmp_iw (t_field_name, m_name) == 0))
2003 struct value *v;
2005 if (type->field (i).is_static ())
2006 v = value_static_field (type, i);
2007 else
2008 v = arg1->primitive_field (offset, i, type);
2010 update_result (v, offset);
2011 return;
2014 if (t_field_name
2015 && t_field_name[0] == '\0')
2017 struct type *field_type = type->field (i).type ();
2019 if (field_type->code () == TYPE_CODE_UNION
2020 || field_type->code () == TYPE_CODE_STRUCT)
2022 /* Look for a match through the fields of an anonymous
2023 union, or anonymous struct. C++ provides anonymous
2024 unions.
2026 In the GNU Chill (now deleted from GDB)
2027 implementation of variant record types, each
2028 <alternative field> has an (anonymous) union type,
2029 each member of the union represents a <variant
2030 alternative>. Each <variant alternative> is
2031 represented as a struct, with a member for each
2032 <variant field>. */
2034 LONGEST new_offset = offset;
2036 /* This is pretty gross. In G++, the offset in an
2037 anonymous union is relative to the beginning of the
2038 enclosing struct. In the GNU Chill (now deleted
2039 from GDB) implementation of variant records, the
2040 bitpos is zero in an anonymous union field, so we
2041 have to add the offset of the union here. */
2042 if (field_type->code () == TYPE_CODE_STRUCT
2043 || (field_type->num_fields () > 0
2044 && field_type->field (0).loc_bitpos () == 0))
2045 new_offset += type->field (i).loc_bitpos () / 8;
2047 search (arg1, new_offset, field_type);
2052 for (i = 0; i < nbases; i++)
2054 struct value *v = NULL;
2055 struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
2056 /* If we are looking for baseclasses, this is what we get when
2057 we hit them. But it could happen that the base part's member
2058 name is not yet filled in. */
2059 int found_baseclass = (m_looking_for_baseclass
2060 && TYPE_BASECLASS_NAME (type, i) != NULL
2061 && (strcmp_iw (m_name, basetype->name ()) == 0));
2062 LONGEST boffset = arg1->embedded_offset () + offset;
2064 if (BASETYPE_VIA_VIRTUAL (type, i))
2066 struct value *v2;
2068 boffset = baseclass_offset (type, i,
2069 arg1->contents_for_printing ().data (),
2070 arg1->embedded_offset () + offset,
2071 arg1->address (),
2072 arg1);
2074 /* The virtual base class pointer might have been clobbered
2075 by the user program. Make sure that it still points to a
2076 valid memory location. */
2078 boffset += arg1->embedded_offset () + offset;
2079 if (boffset < 0
2080 || boffset >= arg1->enclosing_type ()->length ())
2082 CORE_ADDR base_addr;
2084 base_addr = arg1->address () + boffset;
2085 v2 = value_at_lazy (basetype, base_addr);
2086 if (target_read_memory (base_addr,
2087 v2->contents_raw ().data (),
2088 v2->type ()->length ()) != 0)
2089 error (_("virtual baseclass botch"));
2091 else
2093 v2 = arg1->copy ();
2094 v2->deprecated_set_type (basetype);
2095 v2->set_embedded_offset (boffset);
2098 if (found_baseclass)
2099 v = v2;
2100 else
2101 search (v2, 0, TYPE_BASECLASS (type, i));
2103 else if (found_baseclass)
2104 v = arg1->primitive_field (offset, i, type);
2105 else
2107 search (arg1, offset + TYPE_BASECLASS_BITPOS (type, i) / 8,
2108 basetype);
2111 update_result (v, boffset);
2115 /* Helper function used by value_struct_elt to recurse through
2116 baseclasses. Look for a field NAME in ARG1. Search in it assuming
2117 it has (class) type TYPE. If found, return value, else return NULL.
2119 If LOOKING_FOR_BASECLASS, then instead of looking for struct
2120 fields, look for a baseclass named NAME. */
2122 static struct value *
2123 search_struct_field (const char *name, struct value *arg1,
2124 struct type *type, int looking_for_baseclass)
2126 struct_field_searcher searcher (name, type, looking_for_baseclass);
2128 searcher.search (arg1, 0, type);
2130 if (!looking_for_baseclass)
2132 const auto &fields = searcher.fields ();
2134 if (fields.empty ())
2135 return nullptr;
2136 else if (fields.size () == 1)
2137 return fields[0].field_value;
2138 else
2140 std::string candidates;
2142 for (auto &&candidate : fields)
2144 gdb_assert (!candidate.path.empty ());
2146 struct type *field_type = candidate.field_value->type ();
2147 struct type *struct_type = candidate.path.back ();
2149 std::string path;
2150 bool first = true;
2151 for (struct type *t : candidate.path)
2153 if (first)
2154 first = false;
2155 else
2156 path += " -> ";
2157 path += t->name ();
2160 candidates += string_printf ("\n '%s %s::%s' (%s)",
2161 TYPE_SAFE_NAME (field_type),
2162 TYPE_SAFE_NAME (struct_type),
2163 name,
2164 path.c_str ());
2167 error (_("Request for member '%s' is ambiguous in type '%s'."
2168 " Candidates are:%s"),
2169 name, TYPE_SAFE_NAME (type),
2170 candidates.c_str ());
2173 else
2174 return searcher.baseclass ();
2177 /* Helper function used by value_struct_elt to recurse through
2178 baseclasses. Look for a field NAME in ARG1. Adjust the address of
2179 ARG1 by OFFSET bytes, and search in it assuming it has (class) type
2180 TYPE.
2182 ARGS is an optional array of argument values used to help finding NAME.
2183 The contents of ARGS can be adjusted if type coercion is required in
2184 order to find a matching NAME.
2186 If found, return value, else if name matched and args not return
2187 (value) -1, else return NULL. */
2189 static struct value *
2190 search_struct_method (const char *name, struct value **arg1p,
2191 std::optional<gdb::array_view<value *>> args,
2192 LONGEST offset, int *static_memfuncp,
2193 struct type *type)
2195 int i;
2196 struct value *v;
2197 int name_matched = 0;
2199 type = check_typedef (type);
2200 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2202 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2204 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2206 int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2207 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2209 name_matched = 1;
2210 check_stub_method_group (type, i);
2211 if (j > 0 && !args.has_value ())
2212 error (_("cannot resolve overloaded method "
2213 "`%s': no arguments supplied"), name);
2214 else if (j == 0 && !args.has_value ())
2216 v = value_fn_field (arg1p, f, j, type, offset);
2217 if (v != NULL)
2218 return v;
2220 else
2221 while (j >= 0)
2223 gdb_assert (args.has_value ());
2224 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2225 TYPE_FN_FIELD_TYPE (f, j)->has_varargs (),
2226 TYPE_FN_FIELD_TYPE (f, j)->num_fields (),
2227 TYPE_FN_FIELD_ARGS (f, j), *args))
2229 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2230 return value_virtual_fn_field (arg1p, f, j,
2231 type, offset);
2232 if (TYPE_FN_FIELD_STATIC_P (f, j)
2233 && static_memfuncp)
2234 *static_memfuncp = 1;
2235 v = value_fn_field (arg1p, f, j, type, offset);
2236 if (v != NULL)
2237 return v;
2239 j--;
2244 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2246 LONGEST base_offset;
2247 LONGEST this_offset;
2249 if (BASETYPE_VIA_VIRTUAL (type, i))
2251 struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2252 struct value *base_val;
2253 const gdb_byte *base_valaddr;
2255 /* The virtual base class pointer might have been
2256 clobbered by the user program. Make sure that it
2257 still points to a valid memory location. */
2259 if (offset < 0 || offset >= type->length ())
2261 CORE_ADDR address;
2263 gdb::byte_vector tmp (baseclass->length ());
2264 address = (*arg1p)->address ();
2266 if (target_read_memory (address + offset,
2267 tmp.data (), baseclass->length ()) != 0)
2268 error (_("virtual baseclass botch"));
2270 base_val = value_from_contents_and_address (baseclass,
2271 tmp.data (),
2272 address + offset);
2273 base_valaddr = base_val->contents_for_printing ().data ();
2274 this_offset = 0;
2276 else
2278 base_val = *arg1p;
2279 base_valaddr = (*arg1p)->contents_for_printing ().data ();
2280 this_offset = offset;
2283 base_offset = baseclass_offset (type, i, base_valaddr,
2284 this_offset, base_val->address (),
2285 base_val);
2287 else
2289 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2291 v = search_struct_method (name, arg1p, args, base_offset + offset,
2292 static_memfuncp, TYPE_BASECLASS (type, i));
2293 if (v == (struct value *) - 1)
2295 name_matched = 1;
2297 else if (v)
2299 /* FIXME-bothner: Why is this commented out? Why is it here? */
2300 /* *arg1p = arg1_tmp; */
2301 return v;
2304 if (name_matched)
2305 return (struct value *) - 1;
2306 else
2307 return NULL;
2310 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2311 extract the component named NAME from the ultimate target
2312 structure/union and return it as a value with its appropriate type.
2313 ERR is used in the error message if *ARGP's type is wrong.
2315 C++: ARGS is a list of argument types to aid in the selection of
2316 an appropriate method. Also, handle derived types.
2318 STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2319 where the truthvalue of whether the function that was resolved was
2320 a static member function or not is stored.
2322 ERR is an error message to be printed in case the field is not
2323 found. */
2325 struct value *
2326 value_struct_elt (struct value **argp,
2327 std::optional<gdb::array_view<value *>> args,
2328 const char *name, int *static_memfuncp, const char *err)
2330 struct type *t;
2331 struct value *v;
2333 *argp = coerce_array (*argp);
2335 t = check_typedef ((*argp)->type ());
2337 /* Follow pointers until we get to a non-pointer. */
2339 while (t->is_pointer_or_reference ())
2341 *argp = value_ind (*argp);
2342 /* Don't coerce fn pointer to fn and then back again! */
2343 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2344 *argp = coerce_array (*argp);
2345 t = check_typedef ((*argp)->type ());
2348 if (t->code () != TYPE_CODE_STRUCT
2349 && t->code () != TYPE_CODE_UNION)
2350 error (_("Attempt to extract a component of a value that is not a %s."),
2351 err);
2353 /* Assume it's not, unless we see that it is. */
2354 if (static_memfuncp)
2355 *static_memfuncp = 0;
2357 if (!args.has_value ())
2359 /* if there are no arguments ...do this... */
2361 /* Try as a field first, because if we succeed, there is less
2362 work to be done. */
2363 v = search_struct_field (name, *argp, t, 0);
2364 if (v)
2365 return v;
2367 if (current_language->la_language == language_fortran)
2369 /* If it is not a field it is the type name of an inherited
2370 structure. */
2371 v = search_struct_field (name, *argp, t, 1);
2372 if (v)
2373 return v;
2376 /* C++: If it was not found as a data field, then try to
2377 return it as a pointer to a method. */
2378 v = search_struct_method (name, argp, args, 0,
2379 static_memfuncp, t);
2381 if (v == (struct value *) - 1)
2382 error (_("Cannot take address of method %s."), name);
2383 else if (v == 0)
2385 if (TYPE_NFN_FIELDS (t))
2386 error (_("There is no member or method named %s."), name);
2387 else
2388 error (_("There is no member named %s."), name);
2390 return v;
2393 v = search_struct_method (name, argp, args, 0,
2394 static_memfuncp, t);
2396 if (v == (struct value *) - 1)
2398 error (_("One of the arguments you tried to pass to %s could not "
2399 "be converted to what the function wants."), name);
2401 else if (v == 0)
2403 /* See if user tried to invoke data as function. If so, hand it
2404 back. If it's not callable (i.e., a pointer to function),
2405 gdb should give an error. */
2406 v = search_struct_field (name, *argp, t, 0);
2407 /* If we found an ordinary field, then it is not a method call.
2408 So, treat it as if it were a static member function. */
2409 if (v && static_memfuncp)
2410 *static_memfuncp = 1;
2413 if (!v)
2414 throw_error (NOT_FOUND_ERROR,
2415 _("Structure has no component named %s."), name);
2416 return v;
2419 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2420 to a structure or union, extract and return its component (field) of
2421 type FTYPE at the specified BITPOS.
2422 Throw an exception on error. */
2424 struct value *
2425 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2426 const char *err)
2428 struct type *t;
2429 int i;
2431 *argp = coerce_array (*argp);
2433 t = check_typedef ((*argp)->type ());
2435 while (t->is_pointer_or_reference ())
2437 *argp = value_ind (*argp);
2438 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2439 *argp = coerce_array (*argp);
2440 t = check_typedef ((*argp)->type ());
2443 if (t->code () != TYPE_CODE_STRUCT
2444 && t->code () != TYPE_CODE_UNION)
2445 error (_("Attempt to extract a component of a value that is not a %s."),
2446 err);
2448 for (i = TYPE_N_BASECLASSES (t); i < t->num_fields (); i++)
2450 if (!t->field (i).is_static ()
2451 && bitpos == t->field (i).loc_bitpos ()
2452 && types_equal (ftype, t->field (i).type ()))
2453 return (*argp)->primitive_field (0, i, t);
2456 error (_("No field with matching bitpos and type."));
2458 /* Never hit. */
2459 return NULL;
2462 /* Search through the methods of an object (and its bases) to find a
2463 specified method. Return a reference to the fn_field list METHODS of
2464 overloaded instances defined in the source language. If available
2465 and matching, a vector of matching xmethods defined in extension
2466 languages are also returned in XMETHODS.
2468 Helper function for value_find_oload_list.
2469 ARGP is a pointer to a pointer to a value (the object).
2470 METHOD is a string containing the method name.
2471 OFFSET is the offset within the value.
2472 TYPE is the assumed type of the object.
2473 METHODS is a pointer to the matching overloaded instances defined
2474 in the source language. Since this is a recursive function,
2475 *METHODS should be set to NULL when calling this function.
2476 NUM_FNS is the number of overloaded instances. *NUM_FNS should be set to
2477 0 when calling this function.
2478 XMETHODS is the vector of matching xmethod workers. *XMETHODS
2479 should also be set to NULL when calling this function.
2480 BASETYPE is set to the actual type of the subobject where the
2481 method is found.
2482 BOFFSET is the offset of the base subobject where the method is found. */
2484 static void
2485 find_method_list (struct value **argp, const char *method,
2486 LONGEST offset, struct type *type,
2487 gdb::array_view<fn_field> *methods,
2488 std::vector<xmethod_worker_up> *xmethods,
2489 struct type **basetype, LONGEST *boffset)
2491 int i;
2492 struct fn_field *f = NULL;
2494 gdb_assert (methods != NULL && xmethods != NULL);
2495 type = check_typedef (type);
2497 /* First check in object itself.
2498 This function is called recursively to search through base classes.
2499 If there is a source method match found at some stage, then we need not
2500 look for source methods in consequent recursive calls. */
2501 if (methods->empty ())
2503 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2505 /* pai: FIXME What about operators and type conversions? */
2506 const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2508 if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2510 int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2511 f = TYPE_FN_FIELDLIST1 (type, i);
2512 *methods = gdb::make_array_view (f, len);
2514 *basetype = type;
2515 *boffset = offset;
2517 /* Resolve any stub methods. */
2518 check_stub_method_group (type, i);
2520 break;
2525 /* Unlike source methods, xmethods can be accumulated over successive
2526 recursive calls. In other words, an xmethod named 'm' in a class
2527 will not hide an xmethod named 'm' in its base class(es). We want
2528 it to be this way because xmethods are after all convenience functions
2529 and hence there is no point restricting them with something like method
2530 hiding. Moreover, if hiding is done for xmethods as well, then we will
2531 have to provide a mechanism to un-hide (like the 'using' construct). */
2532 get_matching_xmethod_workers (type, method, xmethods);
2534 /* If source methods are not found in current class, look for them in the
2535 base classes. We also have to go through the base classes to gather
2536 extension methods. */
2537 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2539 LONGEST base_offset;
2541 if (BASETYPE_VIA_VIRTUAL (type, i))
2543 base_offset = baseclass_offset (type, i,
2544 (*argp)->contents_for_printing ().data (),
2545 (*argp)->offset () + offset,
2546 (*argp)->address (), *argp);
2548 else /* Non-virtual base, simply use bit position from debug
2549 info. */
2551 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2554 find_method_list (argp, method, base_offset + offset,
2555 TYPE_BASECLASS (type, i), methods,
2556 xmethods, basetype, boffset);
2560 /* Return the list of overloaded methods of a specified name. The methods
2561 could be those GDB finds in the binary, or xmethod. Methods found in
2562 the binary are returned in METHODS, and xmethods are returned in
2563 XMETHODS.
2565 ARGP is a pointer to a pointer to a value (the object).
2566 METHOD is the method name.
2567 OFFSET is the offset within the value contents.
2568 METHODS is the list of matching overloaded instances defined in
2569 the source language.
2570 XMETHODS is the vector of matching xmethod workers defined in
2571 extension languages.
2572 BASETYPE is set to the type of the base subobject that defines the
2573 method.
2574 BOFFSET is the offset of the base subobject which defines the method. */
2576 static void
2577 value_find_oload_method_list (struct value **argp, const char *method,
2578 LONGEST offset,
2579 gdb::array_view<fn_field> *methods,
2580 std::vector<xmethod_worker_up> *xmethods,
2581 struct type **basetype, LONGEST *boffset)
2583 struct type *t;
2585 t = check_typedef ((*argp)->type ());
2587 /* Code snarfed from value_struct_elt. */
2588 while (t->is_pointer_or_reference ())
2590 *argp = value_ind (*argp);
2591 /* Don't coerce fn pointer to fn and then back again! */
2592 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2593 *argp = coerce_array (*argp);
2594 t = check_typedef ((*argp)->type ());
2597 if (t->code () != TYPE_CODE_STRUCT
2598 && t->code () != TYPE_CODE_UNION)
2599 error (_("Attempt to extract a component of a "
2600 "value that is not a struct or union"));
2602 gdb_assert (methods != NULL && xmethods != NULL);
2604 /* Clear the lists. */
2605 *methods = {};
2606 xmethods->clear ();
2608 find_method_list (argp, method, 0, t, methods, xmethods,
2609 basetype, boffset);
2612 /* Helper function for find_overload_match. If no matches were
2613 found, this function may generate a hint for the user that some
2614 of the relevant types are incomplete, so GDB can't evaluate
2615 type relationships to properly evaluate overloads.
2617 If no incomplete types are present, an empty string is returned. */
2618 static std::string
2619 incomplete_type_hint (gdb::array_view<value *> args)
2621 int incomplete_types = 0;
2622 std::string incomplete_arg_names;
2623 for (const struct value *arg : args)
2625 struct type *t = arg->type ();
2626 while (t->code () == TYPE_CODE_PTR)
2627 t = t->target_type ();
2628 if (t->is_stub ())
2630 string_file buffer;
2631 if (incomplete_types > 0)
2632 incomplete_arg_names += ", ";
2634 current_language->print_type (arg->type (), "", &buffer,
2635 -1, 0, &type_print_raw_options);
2637 incomplete_types++;
2638 incomplete_arg_names += buffer.string ();
2641 std::string hint;
2642 if (incomplete_types > 1)
2643 hint = string_printf (_("\nThe types: '%s' aren't fully known to GDB."
2644 " Please cast them directly to the desired"
2645 " typed in the function call."),
2646 incomplete_arg_names.c_str ());
2647 else if (incomplete_types == 1)
2648 hint = string_printf (_("\nThe type: '%s' isn't fully known to GDB."
2649 " Please cast it directly to the desired"
2650 " typed in the function call."),
2651 incomplete_arg_names.c_str ());
2652 return hint;
2655 /* Given an array of arguments (ARGS) (which includes an entry for
2656 "this" in the case of C++ methods), the NAME of a function, and
2657 whether it's a method or not (METHOD), find the best function that
2658 matches on the argument types according to the overload resolution
2659 rules.
2661 METHOD can be one of three values:
2662 NON_METHOD for non-member functions.
2663 METHOD: for member functions.
2664 BOTH: used for overload resolution of operators where the
2665 candidates are expected to be either member or non member
2666 functions. In this case the first argument ARGTYPES
2667 (representing 'this') is expected to be a reference to the
2668 target object, and will be dereferenced when attempting the
2669 non-member search.
2671 In the case of class methods, the parameter OBJ is an object value
2672 in which to search for overloaded methods.
2674 In the case of non-method functions, the parameter FSYM is a symbol
2675 corresponding to one of the overloaded functions.
2677 Return value is an integer: 0 -> good match, 10 -> debugger applied
2678 non-standard coercions, 100 -> incompatible.
2680 If a method is being searched for, VALP will hold the value.
2681 If a non-method is being searched for, SYMP will hold the symbol
2682 for it.
2684 If a method is being searched for, and it is a static method,
2685 then STATICP will point to a non-zero value.
2687 If NO_ADL argument dependent lookup is disabled. This is used to prevent
2688 ADL overload candidates when performing overload resolution for a fully
2689 qualified name.
2691 If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2692 read while picking the best overload match (it may be all zeroes and thus
2693 not have a vtable pointer), in which case skip virtual function lookup.
2694 This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2695 the result type.
2697 Note: This function does *not* check the value of
2698 overload_resolution. Caller must check it to see whether overload
2699 resolution is permitted. */
2702 find_overload_match (gdb::array_view<value *> args,
2703 const char *name, enum oload_search_type method,
2704 struct value **objp, struct symbol *fsym,
2705 struct value **valp, struct symbol **symp,
2706 int *staticp, const int no_adl,
2707 const enum noside noside)
2709 struct value *obj = (objp ? *objp : NULL);
2710 struct type *obj_type = obj ? obj->type () : NULL;
2711 /* Index of best overloaded function. */
2712 int func_oload_champ = -1;
2713 int method_oload_champ = -1;
2714 int src_method_oload_champ = -1;
2715 int ext_method_oload_champ = -1;
2717 /* The measure for the current best match. */
2718 badness_vector method_badness;
2719 badness_vector func_badness;
2720 badness_vector ext_method_badness;
2721 badness_vector src_method_badness;
2723 struct value *temp = obj;
2724 /* For methods, the list of overloaded methods. */
2725 gdb::array_view<fn_field> methods;
2726 /* For non-methods, the list of overloaded function symbols. */
2727 std::vector<symbol *> functions;
2728 /* For xmethods, the vector of xmethod workers. */
2729 std::vector<xmethod_worker_up> xmethods;
2730 struct type *basetype = NULL;
2731 LONGEST boffset;
2733 const char *obj_type_name = NULL;
2734 const char *func_name = NULL;
2735 gdb::unique_xmalloc_ptr<char> temp_func;
2736 enum oload_classification match_quality;
2737 enum oload_classification method_match_quality = INCOMPATIBLE;
2738 enum oload_classification src_method_match_quality = INCOMPATIBLE;
2739 enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2740 enum oload_classification func_match_quality = INCOMPATIBLE;
2742 /* Get the list of overloaded methods or functions. */
2743 if (method == METHOD || method == BOTH)
2745 gdb_assert (obj);
2747 /* OBJ may be a pointer value rather than the object itself. */
2748 obj = coerce_ref (obj);
2749 while (check_typedef (obj->type ())->code () == TYPE_CODE_PTR)
2750 obj = coerce_ref (value_ind (obj));
2751 obj_type_name = obj->type ()->name ();
2753 /* First check whether this is a data member, e.g. a pointer to
2754 a function. */
2755 if (check_typedef (obj->type ())->code () == TYPE_CODE_STRUCT)
2757 *valp = search_struct_field (name, obj,
2758 check_typedef (obj->type ()), 0);
2759 if (*valp)
2761 *staticp = 1;
2762 return 0;
2766 /* Retrieve the list of methods with the name NAME. */
2767 value_find_oload_method_list (&temp, name, 0, &methods,
2768 &xmethods, &basetype, &boffset);
2769 /* If this is a method only search, and no methods were found
2770 the search has failed. */
2771 if (method == METHOD && methods.empty () && xmethods.empty ())
2772 error (_("Couldn't find method %s%s%s"),
2773 obj_type_name,
2774 (obj_type_name && *obj_type_name) ? "::" : "",
2775 name);
2776 /* If we are dealing with stub method types, they should have
2777 been resolved by find_method_list via
2778 value_find_oload_method_list above. */
2779 if (!methods.empty ())
2781 gdb_assert (TYPE_SELF_TYPE (methods[0].type) != NULL);
2783 src_method_oload_champ
2784 = find_oload_champ (args,
2785 methods.size (),
2786 methods.data (), NULL, NULL,
2787 &src_method_badness);
2789 src_method_match_quality = classify_oload_match
2790 (src_method_badness, args.size (),
2791 oload_method_static_p (methods.data (), src_method_oload_champ));
2794 if (!xmethods.empty ())
2796 ext_method_oload_champ
2797 = find_oload_champ (args,
2798 xmethods.size (),
2799 NULL, xmethods.data (), NULL,
2800 &ext_method_badness);
2801 ext_method_match_quality = classify_oload_match (ext_method_badness,
2802 args.size (), 0);
2805 if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2807 switch (compare_badness (ext_method_badness, src_method_badness))
2809 case 0: /* Src method and xmethod are equally good. */
2810 /* If src method and xmethod are equally good, then
2811 xmethod should be the winner. Hence, fall through to the
2812 case where a xmethod is better than the source
2813 method, except when the xmethod match quality is
2814 non-standard. */
2815 [[fallthrough]];
2816 case 1: /* Src method and ext method are incompatible. */
2817 /* If ext method match is not standard, then let source method
2818 win. Otherwise, fallthrough to let xmethod win. */
2819 if (ext_method_match_quality != STANDARD)
2821 method_oload_champ = src_method_oload_champ;
2822 method_badness = src_method_badness;
2823 ext_method_oload_champ = -1;
2824 method_match_quality = src_method_match_quality;
2825 break;
2827 [[fallthrough]];
2828 case 2: /* Ext method is champion. */
2829 method_oload_champ = ext_method_oload_champ;
2830 method_badness = ext_method_badness;
2831 src_method_oload_champ = -1;
2832 method_match_quality = ext_method_match_quality;
2833 break;
2834 case 3: /* Src method is champion. */
2835 method_oload_champ = src_method_oload_champ;
2836 method_badness = src_method_badness;
2837 ext_method_oload_champ = -1;
2838 method_match_quality = src_method_match_quality;
2839 break;
2840 default:
2841 gdb_assert_not_reached ("Unexpected overload comparison "
2842 "result");
2843 break;
2846 else if (src_method_oload_champ >= 0)
2848 method_oload_champ = src_method_oload_champ;
2849 method_badness = src_method_badness;
2850 method_match_quality = src_method_match_quality;
2852 else if (ext_method_oload_champ >= 0)
2854 method_oload_champ = ext_method_oload_champ;
2855 method_badness = ext_method_badness;
2856 method_match_quality = ext_method_match_quality;
2860 if (method == NON_METHOD || method == BOTH)
2862 const char *qualified_name = NULL;
2864 /* If the overload match is being search for both as a method
2865 and non member function, the first argument must now be
2866 dereferenced. */
2867 if (method == BOTH)
2868 args[0] = value_ind (args[0]);
2870 if (fsym)
2872 qualified_name = fsym->natural_name ();
2874 /* If we have a function with a C++ name, try to extract just
2875 the function part. Do not try this for non-functions (e.g.
2876 function pointers). */
2877 if (qualified_name
2878 && (check_typedef (fsym->type ())->code ()
2879 == TYPE_CODE_FUNC))
2881 temp_func = cp_func_name (qualified_name);
2883 /* If cp_func_name did not remove anything, the name of the
2884 symbol did not include scope or argument types - it was
2885 probably a C-style function. */
2886 if (temp_func != nullptr)
2888 if (strcmp (temp_func.get (), qualified_name) == 0)
2889 func_name = NULL;
2890 else
2891 func_name = temp_func.get ();
2895 else
2897 func_name = name;
2898 qualified_name = name;
2901 /* If there was no C++ name, this must be a C-style function or
2902 not a function at all. Just return the same symbol. Do the
2903 same if cp_func_name fails for some reason. */
2904 if (func_name == NULL)
2906 *symp = fsym;
2907 return 0;
2910 func_oload_champ = find_oload_champ_namespace (args,
2911 func_name,
2912 qualified_name,
2913 &functions,
2914 &func_badness,
2915 no_adl);
2917 if (func_oload_champ >= 0)
2918 func_match_quality = classify_oload_match (func_badness,
2919 args.size (), 0);
2922 /* Did we find a match ? */
2923 if (method_oload_champ == -1 && func_oload_champ == -1)
2924 throw_error (NOT_FOUND_ERROR,
2925 _("No symbol \"%s\" in current context."),
2926 name);
2928 /* If we have found both a method match and a function
2929 match, find out which one is better, and calculate match
2930 quality. */
2931 if (method_oload_champ >= 0 && func_oload_champ >= 0)
2933 switch (compare_badness (func_badness, method_badness))
2935 case 0: /* Top two contenders are equally good. */
2936 /* FIXME: GDB does not support the general ambiguous case.
2937 All candidates should be collected and presented the
2938 user. */
2939 error (_("Ambiguous overload resolution"));
2940 break;
2941 case 1: /* Incomparable top contenders. */
2942 /* This is an error incompatible candidates
2943 should not have been proposed. */
2944 error (_("Internal error: incompatible "
2945 "overload candidates proposed"));
2946 break;
2947 case 2: /* Function champion. */
2948 method_oload_champ = -1;
2949 match_quality = func_match_quality;
2950 break;
2951 case 3: /* Method champion. */
2952 func_oload_champ = -1;
2953 match_quality = method_match_quality;
2954 break;
2955 default:
2956 error (_("Internal error: unexpected overload comparison result"));
2957 break;
2960 else
2962 /* We have either a method match or a function match. */
2963 if (method_oload_champ >= 0)
2964 match_quality = method_match_quality;
2965 else
2966 match_quality = func_match_quality;
2969 if (match_quality == INCOMPATIBLE)
2971 std::string hint = incomplete_type_hint (args);
2972 if (method == METHOD)
2973 error (_("Cannot resolve method %s%s%s to any overloaded instance%s"),
2974 obj_type_name,
2975 (obj_type_name && *obj_type_name) ? "::" : "",
2976 name, hint.c_str ());
2977 else
2978 error (_("Cannot resolve function %s to any overloaded instance%s"),
2979 func_name, hint.c_str ());
2981 else if (match_quality == NON_STANDARD)
2983 if (method == METHOD)
2984 warning (_("Using non-standard conversion to match "
2985 "method %s%s%s to supplied arguments"),
2986 obj_type_name,
2987 (obj_type_name && *obj_type_name) ? "::" : "",
2988 name);
2989 else
2990 warning (_("Using non-standard conversion to match "
2991 "function %s to supplied arguments"),
2992 func_name);
2995 if (staticp != NULL)
2996 *staticp = oload_method_static_p (methods.data (), method_oload_champ);
2998 if (method_oload_champ >= 0)
3000 if (src_method_oload_champ >= 0)
3002 if (TYPE_FN_FIELD_VIRTUAL_P (methods, method_oload_champ)
3003 && noside != EVAL_AVOID_SIDE_EFFECTS)
3005 *valp = value_virtual_fn_field (&temp, methods.data (),
3006 method_oload_champ, basetype,
3007 boffset);
3009 else
3010 *valp = value_fn_field (&temp, methods.data (),
3011 method_oload_champ, basetype, boffset);
3013 else
3014 *valp = value::from_xmethod
3015 (std::move (xmethods[ext_method_oload_champ]));
3017 else
3018 *symp = functions[func_oload_champ];
3020 if (objp)
3022 struct type *temp_type = check_typedef (temp->type ());
3023 struct type *objtype = check_typedef (obj_type);
3025 if (temp_type->code () != TYPE_CODE_PTR
3026 && objtype->is_pointer_or_reference ())
3028 temp = value_addr (temp);
3030 *objp = temp;
3033 switch (match_quality)
3035 case INCOMPATIBLE:
3036 return 100;
3037 case NON_STANDARD:
3038 return 10;
3039 default: /* STANDARD */
3040 return 0;
3044 /* Find the best overload match, searching for FUNC_NAME in namespaces
3045 contained in QUALIFIED_NAME until it either finds a good match or
3046 runs out of namespaces. It stores the overloaded functions in
3047 *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV. If NO_ADL,
3048 argument dependent lookup is not performed. */
3050 static int
3051 find_oload_champ_namespace (gdb::array_view<value *> args,
3052 const char *func_name,
3053 const char *qualified_name,
3054 std::vector<symbol *> *oload_syms,
3055 badness_vector *oload_champ_bv,
3056 const int no_adl)
3058 int oload_champ;
3060 find_oload_champ_namespace_loop (args,
3061 func_name,
3062 qualified_name, 0,
3063 oload_syms, oload_champ_bv,
3064 &oload_champ,
3065 no_adl);
3067 return oload_champ;
3070 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
3071 how deep we've looked for namespaces, and the champ is stored in
3072 OLOAD_CHAMP. The return value is 1 if the champ is a good one, 0
3073 if it isn't. Other arguments are the same as in
3074 find_oload_champ_namespace. */
3076 static int
3077 find_oload_champ_namespace_loop (gdb::array_view<value *> args,
3078 const char *func_name,
3079 const char *qualified_name,
3080 int namespace_len,
3081 std::vector<symbol *> *oload_syms,
3082 badness_vector *oload_champ_bv,
3083 int *oload_champ,
3084 const int no_adl)
3086 int next_namespace_len = namespace_len;
3087 int searched_deeper = 0;
3088 int new_oload_champ;
3089 char *new_namespace;
3091 if (next_namespace_len != 0)
3093 gdb_assert (qualified_name[next_namespace_len] == ':');
3094 next_namespace_len += 2;
3096 next_namespace_len +=
3097 cp_find_first_component (qualified_name + next_namespace_len);
3099 /* First, see if we have a deeper namespace we can search in.
3100 If we get a good match there, use it. */
3102 if (qualified_name[next_namespace_len] == ':')
3104 searched_deeper = 1;
3106 if (find_oload_champ_namespace_loop (args,
3107 func_name, qualified_name,
3108 next_namespace_len,
3109 oload_syms, oload_champ_bv,
3110 oload_champ, no_adl))
3112 return 1;
3116 /* If we reach here, either we're in the deepest namespace or we
3117 didn't find a good match in a deeper namespace. But, in the
3118 latter case, we still have a bad match in a deeper namespace;
3119 note that we might not find any match at all in the current
3120 namespace. (There's always a match in the deepest namespace,
3121 because this overload mechanism only gets called if there's a
3122 function symbol to start off with.) */
3124 new_namespace = (char *) alloca (namespace_len + 1);
3125 strncpy (new_namespace, qualified_name, namespace_len);
3126 new_namespace[namespace_len] = '\0';
3128 std::vector<symbol *> new_oload_syms
3129 = make_symbol_overload_list (func_name, new_namespace);
3131 /* If we have reached the deepest level perform argument
3132 determined lookup. */
3133 if (!searched_deeper && !no_adl)
3135 int ix;
3136 struct type **arg_types;
3138 /* Prepare list of argument types for overload resolution. */
3139 arg_types = (struct type **)
3140 alloca (args.size () * (sizeof (struct type *)));
3141 for (ix = 0; ix < args.size (); ix++)
3142 arg_types[ix] = args[ix]->type ();
3143 add_symbol_overload_list_adl ({arg_types, args.size ()}, func_name,
3144 &new_oload_syms);
3147 badness_vector new_oload_champ_bv;
3148 new_oload_champ = find_oload_champ (args,
3149 new_oload_syms.size (),
3150 NULL, NULL, new_oload_syms.data (),
3151 &new_oload_champ_bv);
3153 /* Case 1: We found a good match. Free earlier matches (if any),
3154 and return it. Case 2: We didn't find a good match, but we're
3155 not the deepest function. Then go with the bad match that the
3156 deeper function found. Case 3: We found a bad match, and we're
3157 the deepest function. Then return what we found, even though
3158 it's a bad match. */
3160 if (new_oload_champ != -1
3161 && classify_oload_match (new_oload_champ_bv, args.size (), 0) == STANDARD)
3163 *oload_syms = std::move (new_oload_syms);
3164 *oload_champ = new_oload_champ;
3165 *oload_champ_bv = std::move (new_oload_champ_bv);
3166 return 1;
3168 else if (searched_deeper)
3170 return 0;
3172 else
3174 *oload_syms = std::move (new_oload_syms);
3175 *oload_champ = new_oload_champ;
3176 *oload_champ_bv = std::move (new_oload_champ_bv);
3177 return 0;
3181 /* Look for a function to take ARGS. Find the best match from among
3182 the overloaded methods or functions given by METHODS or FUNCTIONS
3183 or XMETHODS, respectively. One, and only one of METHODS, FUNCTIONS
3184 and XMETHODS can be non-NULL.
3186 NUM_FNS is the length of the array pointed at by METHODS, FUNCTIONS
3187 or XMETHODS, whichever is non-NULL.
3189 Return the index of the best match; store an indication of the
3190 quality of the match in OLOAD_CHAMP_BV. */
3192 static int
3193 find_oload_champ (gdb::array_view<value *> args,
3194 size_t num_fns,
3195 fn_field *methods,
3196 xmethod_worker_up *xmethods,
3197 symbol **functions,
3198 badness_vector *oload_champ_bv)
3200 /* A measure of how good an overloaded instance is. */
3201 badness_vector bv;
3202 /* Index of best overloaded function. */
3203 int oload_champ = -1;
3204 /* Current ambiguity state for overload resolution. */
3205 int oload_ambiguous = 0;
3206 /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs. */
3208 /* A champion can be found among methods alone, or among functions
3209 alone, or in xmethods alone, but not in more than one of these
3210 groups. */
3211 gdb_assert ((methods != NULL) + (functions != NULL) + (xmethods != NULL)
3212 == 1);
3214 /* Consider each candidate in turn. */
3215 for (size_t ix = 0; ix < num_fns; ix++)
3217 int jj;
3218 int static_offset = 0;
3219 bool varargs = false;
3220 std::vector<type *> parm_types;
3222 if (xmethods != NULL)
3223 parm_types = xmethods[ix]->get_arg_types ();
3224 else
3226 size_t nparms;
3228 if (methods != NULL)
3230 nparms = TYPE_FN_FIELD_TYPE (methods, ix)->num_fields ();
3231 static_offset = oload_method_static_p (methods, ix);
3232 varargs = TYPE_FN_FIELD_TYPE (methods, ix)->has_varargs ();
3234 else
3236 nparms = functions[ix]->type ()->num_fields ();
3237 varargs = functions[ix]->type ()->has_varargs ();
3240 parm_types.reserve (nparms);
3241 for (jj = 0; jj < nparms; jj++)
3243 type *t = (methods != NULL
3244 ? (TYPE_FN_FIELD_ARGS (methods, ix)[jj].type ())
3245 : functions[ix]->type ()->field (jj).type ());
3246 parm_types.push_back (t);
3250 /* Compare parameter types to supplied argument types. Skip
3251 THIS for static methods. */
3252 bv = rank_function (parm_types,
3253 args.slice (static_offset),
3254 varargs);
3256 if (overload_debug)
3258 if (methods != NULL)
3259 gdb_printf (gdb_stderr,
3260 "Overloaded method instance %s, # of parms %d\n",
3261 methods[ix].physname, (int) parm_types.size ());
3262 else if (xmethods != NULL)
3263 gdb_printf (gdb_stderr,
3264 "Xmethod worker, # of parms %d\n",
3265 (int) parm_types.size ());
3266 else
3267 gdb_printf (gdb_stderr,
3268 "Overloaded function instance "
3269 "%s # of parms %d\n",
3270 functions[ix]->demangled_name (),
3271 (int) parm_types.size ());
3273 gdb_printf (gdb_stderr,
3274 "...Badness of length : {%d, %d}\n",
3275 bv[0].rank, bv[0].subrank);
3277 for (jj = 1; jj < bv.size (); jj++)
3278 gdb_printf (gdb_stderr,
3279 "...Badness of arg %d : {%d, %d}\n",
3280 jj, bv[jj].rank, bv[jj].subrank);
3283 if (oload_champ_bv->empty ())
3285 *oload_champ_bv = std::move (bv);
3286 oload_champ = 0;
3288 else /* See whether current candidate is better or worse than
3289 previous best. */
3290 switch (compare_badness (bv, *oload_champ_bv))
3292 case 0: /* Top two contenders are equally good. */
3293 oload_ambiguous = 1;
3294 break;
3295 case 1: /* Incomparable top contenders. */
3296 oload_ambiguous = 2;
3297 break;
3298 case 2: /* New champion, record details. */
3299 *oload_champ_bv = std::move (bv);
3300 oload_ambiguous = 0;
3301 oload_champ = ix;
3302 break;
3303 case 3:
3304 default:
3305 break;
3307 if (overload_debug)
3308 gdb_printf (gdb_stderr, "Overload resolution "
3309 "champion is %d, ambiguous? %d\n",
3310 oload_champ, oload_ambiguous);
3313 return oload_champ;
3316 /* Return 1 if we're looking at a static method, 0 if we're looking at
3317 a non-static method or a function that isn't a method. */
3319 static int
3320 oload_method_static_p (struct fn_field *fns_ptr, int index)
3322 if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3323 return 1;
3324 else
3325 return 0;
3328 /* Check how good an overload match OLOAD_CHAMP_BV represents. */
3330 static enum oload_classification
3331 classify_oload_match (const badness_vector &oload_champ_bv,
3332 int nargs,
3333 int static_offset)
3335 int ix;
3336 enum oload_classification worst = STANDARD;
3338 for (ix = 1; ix <= nargs - static_offset; ix++)
3340 /* If this conversion is as bad as INCOMPATIBLE_TYPE_BADNESS
3341 or worse return INCOMPATIBLE. */
3342 if (compare_ranks (oload_champ_bv[ix],
3343 INCOMPATIBLE_TYPE_BADNESS) <= 0)
3344 return INCOMPATIBLE; /* Truly mismatched types. */
3345 /* Otherwise If this conversion is as bad as
3346 NS_POINTER_CONVERSION_BADNESS or worse return NON_STANDARD. */
3347 else if (compare_ranks (oload_champ_bv[ix],
3348 NS_POINTER_CONVERSION_BADNESS) <= 0)
3349 worst = NON_STANDARD; /* Non-standard type conversions
3350 needed. */
3353 /* If no INCOMPATIBLE classification was found, return the worst one
3354 that was found (if any). */
3355 return worst;
3358 /* C++: return 1 is NAME is a legitimate name for the destructor of
3359 type TYPE. If TYPE does not have a destructor, or if NAME is
3360 inappropriate for TYPE, an error is signaled. Parameter TYPE should not yet
3361 have CHECK_TYPEDEF applied, this function will apply it itself. */
3364 destructor_name_p (const char *name, struct type *type)
3366 if (name[0] == '~')
3368 const char *dname = type_name_or_error (type);
3369 const char *cp = strchr (dname, '<');
3370 unsigned int len;
3372 /* Do not compare the template part for template classes. */
3373 if (cp == NULL)
3374 len = strlen (dname);
3375 else
3376 len = cp - dname;
3377 if (strlen (name + 1) != len || strncmp (dname, name + 1, len) != 0)
3378 error (_("name of destructor must equal name of class"));
3379 else
3380 return 1;
3382 return 0;
3385 /* Find an enum constant named NAME in TYPE. TYPE must be an "enum
3386 class". If the name is found, return a value representing it;
3387 otherwise throw an exception. */
3389 static struct value *
3390 enum_constant_from_type (struct type *type, const char *name)
3392 int i;
3393 int name_len = strlen (name);
3395 gdb_assert (type->code () == TYPE_CODE_ENUM
3396 && type->is_declared_class ());
3398 for (i = TYPE_N_BASECLASSES (type); i < type->num_fields (); ++i)
3400 const char *fname = type->field (i).name ();
3401 int len;
3403 if (type->field (i).loc_kind () != FIELD_LOC_KIND_ENUMVAL
3404 || fname == NULL)
3405 continue;
3407 /* Look for the trailing "::NAME", since enum class constant
3408 names are qualified here. */
3409 len = strlen (fname);
3410 if (len + 2 >= name_len
3411 && fname[len - name_len - 2] == ':'
3412 && fname[len - name_len - 1] == ':'
3413 && strcmp (&fname[len - name_len], name) == 0)
3414 return value_from_longest (type, type->field (i).loc_enumval ());
3417 error (_("no constant named \"%s\" in enum \"%s\""),
3418 name, type->name ());
3421 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3422 return the appropriate member (or the address of the member, if
3423 WANT_ADDRESS). This function is used to resolve user expressions
3424 of the form "DOMAIN::NAME". For more details on what happens, see
3425 the comment before value_struct_elt_for_reference. */
3427 struct value *
3428 value_aggregate_elt (struct type *curtype, const char *name,
3429 struct type *expect_type, int want_address,
3430 enum noside noside)
3432 switch (curtype->code ())
3434 case TYPE_CODE_STRUCT:
3435 case TYPE_CODE_UNION:
3436 return value_struct_elt_for_reference (curtype, 0, curtype,
3437 name, expect_type,
3438 want_address, noside);
3439 case TYPE_CODE_NAMESPACE:
3440 return value_namespace_elt (curtype, name,
3441 want_address, noside);
3443 case TYPE_CODE_ENUM:
3444 return enum_constant_from_type (curtype, name);
3446 default:
3447 internal_error (_("non-aggregate type in value_aggregate_elt"));
3451 /* Compares the two method/function types T1 and T2 for "equality"
3452 with respect to the methods' parameters. If the types of the
3453 two parameter lists are the same, returns 1; 0 otherwise. This
3454 comparison may ignore any artificial parameters in T1 if
3455 SKIP_ARTIFICIAL is non-zero. This function will ALWAYS skip
3456 the first artificial parameter in T1, assumed to be a 'this' pointer.
3458 The type T2 is expected to have come from make_params (in eval.c). */
3460 static int
3461 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3463 int start = 0;
3465 if (t1->num_fields () > 0 && t1->field (0).is_artificial ())
3466 ++start;
3468 /* If skipping artificial fields, find the first real field
3469 in T1. */
3470 if (skip_artificial)
3472 while (start < t1->num_fields ()
3473 && t1->field (start).is_artificial ())
3474 ++start;
3477 /* Now compare parameters. */
3479 /* Special case: a method taking void. T1 will contain no
3480 non-artificial fields, and T2 will contain TYPE_CODE_VOID. */
3481 if ((t1->num_fields () - start) == 0 && t2->num_fields () == 1
3482 && t2->field (0).type ()->code () == TYPE_CODE_VOID)
3483 return 1;
3485 if ((t1->num_fields () - start) == t2->num_fields ())
3487 int i;
3489 for (i = 0; i < t2->num_fields (); ++i)
3491 if (compare_ranks (rank_one_type (t1->field (start + i).type (),
3492 t2->field (i).type (), NULL),
3493 EXACT_MATCH_BADNESS) != 0)
3494 return 0;
3497 return 1;
3500 return 0;
3503 /* C++: Given an aggregate type VT, and a class type CLS, search
3504 recursively for CLS using value V; If found, store the offset
3505 which is either fetched from the virtual base pointer if CLS
3506 is virtual or accumulated offset of its parent classes if
3507 CLS is non-virtual in *BOFFS, set ISVIRT to indicate if CLS
3508 is virtual, and return true. If not found, return false. */
3510 static bool
3511 get_baseclass_offset (struct type *vt, struct type *cls,
3512 struct value *v, int *boffs, bool *isvirt)
3514 for (int i = 0; i < TYPE_N_BASECLASSES (vt); i++)
3516 struct type *t = vt->field (i).type ();
3517 if (types_equal (t, cls))
3519 if (BASETYPE_VIA_VIRTUAL (vt, i))
3521 const gdb_byte *adr = v->contents_for_printing ().data ();
3522 *boffs = baseclass_offset (vt, i, adr, v->offset (),
3523 value_as_long (v), v);
3524 *isvirt = true;
3526 else
3527 *isvirt = false;
3528 return true;
3531 if (get_baseclass_offset (check_typedef (t), cls, v, boffs, isvirt))
3533 if (*isvirt == false) /* Add non-virtual base offset. */
3535 const gdb_byte *adr = v->contents_for_printing ().data ();
3536 *boffs += baseclass_offset (vt, i, adr, v->offset (),
3537 value_as_long (v), v);
3539 return true;
3543 return false;
3546 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3547 return the address of this member as a "pointer to member" type.
3548 If INTYPE is non-null, then it will be the type of the member we
3549 are looking for. This will help us resolve "pointers to member
3550 functions". This function is used to resolve user expressions of
3551 the form "DOMAIN::NAME". */
3553 static struct value *
3554 value_struct_elt_for_reference (struct type *domain, int offset,
3555 struct type *curtype, const char *name,
3556 struct type *intype,
3557 int want_address,
3558 enum noside noside)
3560 struct type *t = check_typedef (curtype);
3561 int i;
3562 struct value *result;
3564 if (t->code () != TYPE_CODE_STRUCT
3565 && t->code () != TYPE_CODE_UNION)
3566 error (_("Internal error: non-aggregate type "
3567 "to value_struct_elt_for_reference"));
3569 for (i = t->num_fields () - 1; i >= TYPE_N_BASECLASSES (t); i--)
3571 const char *t_field_name = t->field (i).name ();
3573 if (t_field_name && strcmp (t_field_name, name) == 0)
3575 if (t->field (i).is_static ())
3577 struct value *v = value_static_field (t, i);
3578 if (want_address)
3579 v = value_addr (v);
3580 return v;
3582 if (t->field (i).is_packed ())
3583 error (_("pointers to bitfield members not allowed"));
3585 if (want_address)
3586 return value_from_longest
3587 (lookup_memberptr_type (t->field (i).type (), domain),
3588 offset + (LONGEST) (t->field (i).loc_bitpos () >> 3));
3589 else if (noside != EVAL_NORMAL)
3590 return value::allocate (t->field (i).type ());
3591 else
3593 /* Try to evaluate NAME as a qualified name with implicit
3594 this pointer. In this case, attempt to return the
3595 equivalent to `this->*(&TYPE::NAME)'. */
3596 struct value *v = value_of_this_silent (current_language);
3597 if (v != NULL)
3599 struct value *ptr, *this_v = v;
3600 long mem_offset;
3601 struct type *type, *tmp;
3603 ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3604 type = check_typedef (ptr->type ());
3605 gdb_assert (type != NULL
3606 && type->code () == TYPE_CODE_MEMBERPTR);
3607 tmp = lookup_pointer_type (TYPE_SELF_TYPE (type));
3608 v = value_cast_pointers (tmp, v, 1);
3609 mem_offset = value_as_long (ptr);
3610 if (domain != curtype)
3612 /* Find class offset of type CURTYPE from either its
3613 parent type DOMAIN or the type of implied this. */
3614 int boff = 0;
3615 bool isvirt = false;
3616 if (get_baseclass_offset (domain, curtype, v, &boff,
3617 &isvirt))
3618 mem_offset += boff;
3619 else
3621 struct type *p = check_typedef (this_v->type ());
3622 p = check_typedef (p->target_type ());
3623 if (get_baseclass_offset (p, curtype, this_v,
3624 &boff, &isvirt))
3625 mem_offset += boff;
3628 tmp = lookup_pointer_type (type->target_type ());
3629 result = value_from_pointer (tmp,
3630 value_as_long (v) + mem_offset);
3631 return value_ind (result);
3634 error (_("Cannot reference non-static field \"%s\""), name);
3639 /* C++: If it was not found as a data field, then try to return it
3640 as a pointer to a method. */
3642 /* Perform all necessary dereferencing. */
3643 while (intype && intype->code () == TYPE_CODE_PTR)
3644 intype = intype->target_type ();
3646 for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3648 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3650 if (t_field_name && strcmp (t_field_name, name) == 0)
3652 int j;
3653 int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3654 struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3656 check_stub_method_group (t, i);
3658 if (intype)
3660 for (j = 0; j < len; ++j)
3662 if (TYPE_CONST (intype) != TYPE_FN_FIELD_CONST (f, j))
3663 continue;
3664 if (TYPE_VOLATILE (intype) != TYPE_FN_FIELD_VOLATILE (f, j))
3665 continue;
3667 if (compare_parameters (TYPE_FN_FIELD_TYPE (f, j), intype, 0)
3668 || compare_parameters (TYPE_FN_FIELD_TYPE (f, j),
3669 intype, 1))
3670 break;
3673 if (j == len)
3674 error (_("no member function matches "
3675 "that type instantiation"));
3677 else
3679 int ii;
3681 j = -1;
3682 for (ii = 0; ii < len; ++ii)
3684 /* Skip artificial methods. This is necessary if,
3685 for example, the user wants to "print
3686 subclass::subclass" with only one user-defined
3687 constructor. There is no ambiguity in this case.
3688 We are careful here to allow artificial methods
3689 if they are the unique result. */
3690 if (TYPE_FN_FIELD_ARTIFICIAL (f, ii))
3692 if (j == -1)
3693 j = ii;
3694 continue;
3697 /* Desired method is ambiguous if more than one
3698 method is defined. */
3699 if (j != -1 && !TYPE_FN_FIELD_ARTIFICIAL (f, j))
3700 error (_("non-unique member `%s' requires "
3701 "type instantiation"), name);
3703 j = ii;
3706 if (j == -1)
3707 error (_("no matching member function"));
3710 if (TYPE_FN_FIELD_STATIC_P (f, j))
3712 struct symbol *s =
3713 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3714 0, SEARCH_FUNCTION_DOMAIN, 0).symbol;
3716 if (s == NULL)
3717 return NULL;
3719 if (want_address)
3720 return value_addr (read_var_value (s, 0, 0));
3721 else
3722 return read_var_value (s, 0, 0);
3725 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3727 if (want_address)
3729 result = value::allocate
3730 (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3731 cplus_make_method_ptr (result->type (),
3732 result->contents_writeable ().data (),
3733 TYPE_FN_FIELD_VOFFSET (f, j), 1);
3735 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3736 return value::allocate (TYPE_FN_FIELD_TYPE (f, j));
3737 else
3738 error (_("Cannot reference virtual member function \"%s\""),
3739 name);
3741 else
3743 struct symbol *s =
3744 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3745 0, SEARCH_FUNCTION_DOMAIN, 0).symbol;
3747 if (s == NULL)
3748 return NULL;
3750 struct value *v = read_var_value (s, 0, 0);
3751 if (!want_address)
3752 result = v;
3753 else
3755 result = value::allocate (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3756 cplus_make_method_ptr (result->type (),
3757 result->contents_writeable ().data (),
3758 v->address (), 0);
3761 return result;
3764 for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3766 struct value *v;
3767 int base_offset;
3769 if (BASETYPE_VIA_VIRTUAL (t, i))
3770 base_offset = 0;
3771 else
3772 base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3773 v = value_struct_elt_for_reference (domain,
3774 offset + base_offset,
3775 TYPE_BASECLASS (t, i),
3776 name, intype,
3777 want_address, noside);
3778 if (v)
3779 return v;
3782 /* As a last chance, pretend that CURTYPE is a namespace, and look
3783 it up that way; this (frequently) works for types nested inside
3784 classes. */
3786 return value_maybe_namespace_elt (curtype, name,
3787 want_address, noside);
3790 /* C++: Return the member NAME of the namespace given by the type
3791 CURTYPE. */
3793 static struct value *
3794 value_namespace_elt (const struct type *curtype,
3795 const char *name, int want_address,
3796 enum noside noside)
3798 struct value *retval = value_maybe_namespace_elt (curtype, name,
3799 want_address,
3800 noside);
3802 if (retval == NULL)
3803 error (_("No symbol \"%s\" in namespace \"%s\"."),
3804 name, curtype->name ());
3806 return retval;
3809 /* A helper function used by value_namespace_elt and
3810 value_struct_elt_for_reference. It looks up NAME inside the
3811 context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
3812 is a class and NAME refers to a type in CURTYPE itself (as opposed
3813 to, say, some base class of CURTYPE). */
3815 static struct value *
3816 value_maybe_namespace_elt (const struct type *curtype,
3817 const char *name, int want_address,
3818 enum noside noside)
3820 const char *namespace_name = curtype->name ();
3821 struct block_symbol sym;
3822 struct value *result;
3824 sym = cp_lookup_symbol_namespace (namespace_name, name,
3825 get_selected_block (0), SEARCH_VFT);
3827 if (sym.symbol == NULL)
3828 return NULL;
3829 else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3830 && (sym.symbol->aclass () == LOC_TYPEDEF))
3831 result = value::allocate (sym.symbol->type ());
3832 else
3833 result = value_of_variable (sym.symbol, sym.block);
3835 if (want_address)
3836 result = value_addr (result);
3838 return result;
3841 /* Given a pointer or a reference value V, find its real (RTTI) type.
3843 Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3844 and refer to the values computed for the object pointed to. */
3846 struct type *
3847 value_rtti_indirect_type (struct value *v, int *full,
3848 LONGEST *top, int *using_enc)
3850 struct value *target = NULL;
3851 struct type *type, *real_type, *target_type;
3853 type = v->type ();
3854 type = check_typedef (type);
3855 if (TYPE_IS_REFERENCE (type))
3856 target = coerce_ref (v);
3857 else if (type->code () == TYPE_CODE_PTR)
3862 target = value_ind (v);
3864 catch (const gdb_exception_error &except)
3866 if (except.error == MEMORY_ERROR)
3868 /* value_ind threw a memory error. The pointer is NULL or
3869 contains an uninitialized value: we can't determine any
3870 type. */
3871 return NULL;
3873 throw;
3876 else
3877 return NULL;
3879 real_type = value_rtti_type (target, full, top, using_enc);
3881 if (real_type)
3883 /* Copy qualifiers to the referenced object. */
3884 target_type = target->type ();
3885 real_type = make_cv_type (TYPE_CONST (target_type),
3886 TYPE_VOLATILE (target_type), real_type, NULL);
3887 if (TYPE_IS_REFERENCE (type))
3888 real_type = lookup_reference_type (real_type, type->code ());
3889 else if (type->code () == TYPE_CODE_PTR)
3890 real_type = lookup_pointer_type (real_type);
3891 else
3892 internal_error (_("Unexpected value type."));
3894 /* Copy qualifiers to the pointer/reference. */
3895 real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3896 real_type, NULL);
3899 return real_type;
3902 /* Given a value pointed to by ARGP, check its real run-time type, and
3903 if that is different from the enclosing type, create a new value
3904 using the real run-time type as the enclosing type (and of the same
3905 type as ARGP) and return it, with the embedded offset adjusted to
3906 be the correct offset to the enclosed object. RTYPE is the type,
3907 and XFULL, XTOP, and XUSING_ENC are the other parameters, computed
3908 by value_rtti_type(). If these are available, they can be supplied
3909 and a second call to value_rtti_type() is avoided. (Pass RTYPE ==
3910 NULL if they're not available. */
3912 struct value *
3913 value_full_object (struct value *argp,
3914 struct type *rtype,
3915 int xfull, int xtop,
3916 int xusing_enc)
3918 struct type *real_type;
3919 int full = 0;
3920 LONGEST top = -1;
3921 int using_enc = 0;
3922 struct value *new_val;
3924 if (rtype)
3926 real_type = rtype;
3927 full = xfull;
3928 top = xtop;
3929 using_enc = xusing_enc;
3931 else
3932 real_type = value_rtti_type (argp, &full, &top, &using_enc);
3934 /* If no RTTI data, or if object is already complete, do nothing. */
3935 if (!real_type || real_type == argp->enclosing_type ())
3936 return argp;
3938 /* In a destructor we might see a real type that is a superclass of
3939 the object's type. In this case it is better to leave the object
3940 as-is. */
3941 if (full
3942 && real_type->length () < argp->enclosing_type ()->length ())
3943 return argp;
3945 /* If we have the full object, but for some reason the enclosing
3946 type is wrong, set it. */
3947 /* pai: FIXME -- sounds iffy */
3948 if (full)
3950 argp = argp->copy ();
3951 argp->set_enclosing_type (real_type);
3952 return argp;
3955 /* Check if object is in memory. */
3956 if (argp->lval () != lval_memory)
3958 warning (_("Couldn't retrieve complete object of RTTI "
3959 "type %s; object may be in register(s)."),
3960 real_type->name ());
3962 return argp;
3965 /* All other cases -- retrieve the complete object. */
3966 /* Go back by the computed top_offset from the beginning of the
3967 object, adjusting for the embedded offset of argp if that's what
3968 value_rtti_type used for its computation. */
3969 new_val = value_at_lazy (real_type, argp->address () - top +
3970 (using_enc ? 0 : argp->embedded_offset ()));
3971 new_val->deprecated_set_type (argp->type ());
3972 new_val->set_embedded_offset ((using_enc
3973 ? top + argp->embedded_offset ()
3974 : top));
3975 return new_val;
3979 /* Return the value of the local variable, if one exists. Throw error
3980 otherwise, such as if the request is made in an inappropriate context. */
3982 struct value *
3983 value_of_this (const struct language_defn *lang)
3985 struct block_symbol sym;
3986 const struct block *b;
3987 frame_info_ptr frame;
3989 if (lang->name_of_this () == NULL)
3990 error (_("no `this' in current language"));
3992 frame = get_selected_frame (_("no frame selected"));
3994 b = get_frame_block (frame, NULL);
3996 sym = lookup_language_this (lang, b);
3997 if (sym.symbol == NULL)
3998 error (_("current stack frame does not contain a variable named `%s'"),
3999 lang->name_of_this ());
4001 return read_var_value (sym.symbol, sym.block, frame);
4004 /* Return the value of the local variable, if one exists. Return NULL
4005 otherwise. Never throw error. */
4007 struct value *
4008 value_of_this_silent (const struct language_defn *lang)
4010 struct value *ret = NULL;
4014 ret = value_of_this (lang);
4016 catch (const gdb_exception_error &except)
4020 return ret;
4023 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH
4024 elements long, starting at LOWBOUND. The result has the same lower
4025 bound as the original ARRAY. */
4027 struct value *
4028 value_slice (struct value *array, int lowbound, int length)
4030 struct type *slice_range_type, *slice_type, *range_type;
4031 LONGEST lowerbound, upperbound;
4032 struct value *slice;
4033 struct type *array_type;
4035 array_type = check_typedef (array->type ());
4036 if (array_type->code () != TYPE_CODE_ARRAY
4037 && array_type->code () != TYPE_CODE_STRING)
4038 error (_("cannot take slice of non-array"));
4040 if (type_not_allocated (array_type))
4041 error (_("array not allocated"));
4042 if (type_not_associated (array_type))
4043 error (_("array not associated"));
4045 range_type = array_type->index_type ();
4046 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
4047 error (_("slice from bad array or bitstring"));
4049 if (lowbound < lowerbound || length < 0
4050 || lowbound + length - 1 > upperbound)
4051 error (_("slice out of range"));
4053 /* FIXME-type-allocation: need a way to free this type when we are
4054 done with it. */
4055 type_allocator alloc (range_type->target_type ());
4056 slice_range_type = create_static_range_type (alloc,
4057 range_type->target_type (),
4058 lowbound,
4059 lowbound + length - 1);
4062 struct type *element_type = array_type->target_type ();
4063 LONGEST offset
4064 = (lowbound - lowerbound) * check_typedef (element_type)->length ();
4066 slice_type = create_array_type (alloc,
4067 element_type,
4068 slice_range_type);
4069 slice_type->set_code (array_type->code ());
4071 if (array->lval () == lval_memory && array->lazy ())
4072 slice = value::allocate_lazy (slice_type);
4073 else
4075 slice = value::allocate (slice_type);
4076 array->contents_copy (slice, 0, offset,
4077 type_length_units (slice_type));
4080 slice->set_component_location (array);
4081 slice->set_offset (array->offset () + offset);
4084 return slice;
4087 /* See value.h. */
4089 struct value *
4090 value_literal_complex (struct value *arg1,
4091 struct value *arg2,
4092 struct type *type)
4094 struct value *val;
4095 struct type *real_type = type->target_type ();
4097 val = value::allocate (type);
4098 arg1 = value_cast (real_type, arg1);
4099 arg2 = value_cast (real_type, arg2);
4101 int len = real_type->length ();
4103 copy (arg1->contents (),
4104 val->contents_raw ().slice (0, len));
4105 copy (arg2->contents (),
4106 val->contents_raw ().slice (len, len));
4108 return val;
4111 /* See value.h. */
4113 struct value *
4114 value_real_part (struct value *value)
4116 struct type *type = check_typedef (value->type ());
4117 struct type *ttype = type->target_type ();
4119 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4120 return value_from_component (value, ttype, 0);
4123 /* See value.h. */
4125 struct value *
4126 value_imaginary_part (struct value *value)
4128 struct type *type = check_typedef (value->type ());
4129 struct type *ttype = type->target_type ();
4131 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4132 return value_from_component (value, ttype,
4133 check_typedef (ttype)->length ());
4136 /* Cast a value into the appropriate complex data type. */
4138 static struct value *
4139 cast_into_complex (struct type *type, struct value *val)
4141 struct type *real_type = type->target_type ();
4143 if (val->type ()->code () == TYPE_CODE_COMPLEX)
4145 struct type *val_real_type = val->type ()->target_type ();
4146 struct value *re_val = value::allocate (val_real_type);
4147 struct value *im_val = value::allocate (val_real_type);
4148 int len = val_real_type->length ();
4150 copy (val->contents ().slice (0, len),
4151 re_val->contents_raw ());
4152 copy (val->contents ().slice (len, len),
4153 im_val->contents_raw ());
4155 return value_literal_complex (re_val, im_val, type);
4157 else if (val->type ()->code () == TYPE_CODE_FLT
4158 || val->type ()->code () == TYPE_CODE_INT)
4159 return value_literal_complex (val,
4160 value::zero (real_type, not_lval),
4161 type);
4162 else
4163 error (_("cannot cast non-number to complex"));
4166 void _initialize_valops ();
4167 void
4168 _initialize_valops ()
4170 add_setshow_boolean_cmd ("overload-resolution", class_support,
4171 &overload_resolution, _("\
4172 Set overload resolution in evaluating C++ functions."), _("\
4173 Show overload resolution in evaluating C++ functions."),
4174 NULL, NULL,
4175 show_overload_resolution,
4176 &setlist, &showlist);
4177 overload_resolution = 1;