Set development and experimental to false. Update version number to 2.40. Add relea...
[binutils-gdb.git] / gdb / valops.c
blobe90c3947b8d500460691cfe71b73da2db8bc9746
1 /* Perform non-arithmetic operations on values, for GDB.
3 Copyright (C) 1986-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "defs.h"
21 #include "symtab.h"
22 #include "gdbtypes.h"
23 #include "value.h"
24 #include "frame.h"
25 #include "inferior.h"
26 #include "gdbcore.h"
27 #include "target.h"
28 #include "demangle.h"
29 #include "language.h"
30 #include "gdbcmd.h"
31 #include "regcache.h"
32 #include "cp-abi.h"
33 #include "block.h"
34 #include "infcall.h"
35 #include "dictionary.h"
36 #include "cp-support.h"
37 #include "target-float.h"
38 #include "tracepoint.h"
39 #include "observable.h"
40 #include "objfiles.h"
41 #include "extension.h"
42 #include "gdbtypes.h"
43 #include "gdbsupport/byte-vector.h"
44 #include "typeprint.h"
46 /* Local functions. */
48 static int typecmp (bool staticp, bool varargs, int nargs,
49 struct field t1[], const gdb::array_view<value *> t2);
51 static struct value *search_struct_field (const char *, struct value *,
52 struct type *, int);
54 static struct value *search_struct_method (const char *, struct value **,
55 gdb::optional<gdb::array_view<value *>>,
56 LONGEST, int *, struct type *);
58 static int find_oload_champ_namespace (gdb::array_view<value *> args,
59 const char *, const char *,
60 std::vector<symbol *> *oload_syms,
61 badness_vector *,
62 const int no_adl);
64 static int find_oload_champ_namespace_loop (gdb::array_view<value *> args,
65 const char *, const char *,
66 int, std::vector<symbol *> *oload_syms,
67 badness_vector *, int *,
68 const int no_adl);
70 static int find_oload_champ (gdb::array_view<value *> args,
71 size_t num_fns,
72 fn_field *methods,
73 xmethod_worker_up *xmethods,
74 symbol **functions,
75 badness_vector *oload_champ_bv);
77 static int oload_method_static_p (struct fn_field *, int);
79 enum oload_classification { STANDARD, NON_STANDARD, INCOMPATIBLE };
81 static enum oload_classification classify_oload_match
82 (const badness_vector &, int, int);
84 static struct value *value_struct_elt_for_reference (struct type *,
85 int, struct type *,
86 const char *,
87 struct type *,
88 int, enum noside);
90 static struct value *value_namespace_elt (const struct type *,
91 const char *, int , enum noside);
93 static struct value *value_maybe_namespace_elt (const struct type *,
94 const char *, int,
95 enum noside);
97 static CORE_ADDR allocate_space_in_inferior (int);
99 static struct value *cast_into_complex (struct type *, struct value *);
101 bool overload_resolution = false;
102 static void
103 show_overload_resolution (struct ui_file *file, int from_tty,
104 struct cmd_list_element *c,
105 const char *value)
107 gdb_printf (file, _("Overload resolution in evaluating "
108 "C++ functions is %s.\n"),
109 value);
112 /* Find the address of function name NAME in the inferior. If OBJF_P
113 is non-NULL, *OBJF_P will be set to the OBJFILE where the function
114 is defined. */
116 struct value *
117 find_function_in_inferior (const char *name, struct objfile **objf_p)
119 struct block_symbol sym;
121 sym = lookup_symbol (name, 0, VAR_DOMAIN, 0);
122 if (sym.symbol != NULL)
124 if (sym.symbol->aclass () != LOC_BLOCK)
126 error (_("\"%s\" exists in this program but is not a function."),
127 name);
130 if (objf_p)
131 *objf_p = sym.symbol->objfile ();
133 return value_of_variable (sym.symbol, sym.block);
135 else
137 struct bound_minimal_symbol msymbol =
138 lookup_bound_minimal_symbol (name);
140 if (msymbol.minsym != NULL)
142 struct objfile *objfile = msymbol.objfile;
143 struct gdbarch *gdbarch = objfile->arch ();
145 struct type *type;
146 CORE_ADDR maddr;
147 type = lookup_pointer_type (builtin_type (gdbarch)->builtin_char);
148 type = lookup_function_type (type);
149 type = lookup_pointer_type (type);
150 maddr = msymbol.value_address ();
152 if (objf_p)
153 *objf_p = objfile;
155 return value_from_pointer (type, maddr);
157 else
159 if (!target_has_execution ())
160 error (_("evaluation of this expression "
161 "requires the target program to be active"));
162 else
163 error (_("evaluation of this expression requires the "
164 "program to have a function \"%s\"."),
165 name);
170 /* Allocate NBYTES of space in the inferior using the inferior's
171 malloc and return a value that is a pointer to the allocated
172 space. */
174 struct value *
175 value_allocate_space_in_inferior (int len)
177 struct objfile *objf;
178 struct value *val = find_function_in_inferior ("malloc", &objf);
179 struct gdbarch *gdbarch = objf->arch ();
180 struct value *blocklen;
182 blocklen = value_from_longest (builtin_type (gdbarch)->builtin_int, len);
183 val = call_function_by_hand (val, NULL, blocklen);
184 if (value_logical_not (val))
186 if (!target_has_execution ())
187 error (_("No memory available to program now: "
188 "you need to start the target first"));
189 else
190 error (_("No memory available to program: call to malloc failed"));
192 return val;
195 static CORE_ADDR
196 allocate_space_in_inferior (int len)
198 return value_as_long (value_allocate_space_in_inferior (len));
201 /* Cast struct value VAL to type TYPE and return as a value.
202 Both type and val must be of TYPE_CODE_STRUCT or TYPE_CODE_UNION
203 for this to work. Typedef to one of the codes is permitted.
204 Returns NULL if the cast is neither an upcast nor a downcast. */
206 static struct value *
207 value_cast_structs (struct type *type, struct value *v2)
209 struct type *t1;
210 struct type *t2;
211 struct value *v;
213 gdb_assert (type != NULL && v2 != NULL);
215 t1 = check_typedef (type);
216 t2 = check_typedef (value_type (v2));
218 /* Check preconditions. */
219 gdb_assert ((t1->code () == TYPE_CODE_STRUCT
220 || t1->code () == TYPE_CODE_UNION)
221 && !!"Precondition is that type is of STRUCT or UNION kind.");
222 gdb_assert ((t2->code () == TYPE_CODE_STRUCT
223 || t2->code () == TYPE_CODE_UNION)
224 && !!"Precondition is that value is of STRUCT or UNION kind");
226 if (t1->name () != NULL
227 && t2->name () != NULL
228 && !strcmp (t1->name (), t2->name ()))
229 return NULL;
231 /* Upcasting: look in the type of the source to see if it contains the
232 type of the target as a superclass. If so, we'll need to
233 offset the pointer rather than just change its type. */
234 if (t1->name () != NULL)
236 v = search_struct_field (t1->name (),
237 v2, t2, 1);
238 if (v)
239 return v;
242 /* Downcasting: look in the type of the target to see if it contains the
243 type of the source as a superclass. If so, we'll need to
244 offset the pointer rather than just change its type. */
245 if (t2->name () != NULL)
247 /* Try downcasting using the run-time type of the value. */
248 int full, using_enc;
249 LONGEST top;
250 struct type *real_type;
252 real_type = value_rtti_type (v2, &full, &top, &using_enc);
253 if (real_type)
255 v = value_full_object (v2, real_type, full, top, using_enc);
256 v = value_at_lazy (real_type, value_address (v));
257 real_type = value_type (v);
259 /* We might be trying to cast to the outermost enclosing
260 type, in which case search_struct_field won't work. */
261 if (real_type->name () != NULL
262 && !strcmp (real_type->name (), t1->name ()))
263 return v;
265 v = search_struct_field (t2->name (), v, real_type, 1);
266 if (v)
267 return v;
270 /* Try downcasting using information from the destination type
271 T2. This wouldn't work properly for classes with virtual
272 bases, but those were handled above. */
273 v = search_struct_field (t2->name (),
274 value_zero (t1, not_lval), t1, 1);
275 if (v)
277 /* Downcasting is possible (t1 is superclass of v2). */
278 CORE_ADDR addr2 = value_address (v2) + value_embedded_offset (v2);
280 addr2 -= value_address (v) + value_embedded_offset (v);
281 return value_at (type, addr2);
285 return NULL;
288 /* Cast one pointer or reference type to another. Both TYPE and
289 the type of ARG2 should be pointer types, or else both should be
290 reference types. If SUBCLASS_CHECK is non-zero, this will force a
291 check to see whether TYPE is a superclass of ARG2's type. If
292 SUBCLASS_CHECK is zero, then the subclass check is done only when
293 ARG2 is itself non-zero. Returns the new pointer or reference. */
295 struct value *
296 value_cast_pointers (struct type *type, struct value *arg2,
297 int subclass_check)
299 struct type *type1 = check_typedef (type);
300 struct type *type2 = check_typedef (value_type (arg2));
301 struct type *t1 = check_typedef (type1->target_type ());
302 struct type *t2 = check_typedef (type2->target_type ());
304 if (t1->code () == TYPE_CODE_STRUCT
305 && t2->code () == TYPE_CODE_STRUCT
306 && (subclass_check || !value_logical_not (arg2)))
308 struct value *v2;
310 if (TYPE_IS_REFERENCE (type2))
311 v2 = coerce_ref (arg2);
312 else
313 v2 = value_ind (arg2);
314 gdb_assert (check_typedef (value_type (v2))->code ()
315 == TYPE_CODE_STRUCT && !!"Why did coercion fail?");
316 v2 = value_cast_structs (t1, v2);
317 /* At this point we have what we can have, un-dereference if needed. */
318 if (v2)
320 struct value *v = value_addr (v2);
322 deprecated_set_value_type (v, type);
323 return v;
327 /* No superclass found, just change the pointer type. */
328 arg2 = value_copy (arg2);
329 deprecated_set_value_type (arg2, type);
330 set_value_enclosing_type (arg2, type);
331 set_value_pointed_to_offset (arg2, 0); /* pai: chk_val */
332 return arg2;
335 /* See value.h. */
337 gdb_mpq
338 value_to_gdb_mpq (struct value *value)
340 struct type *type = check_typedef (value_type (value));
342 gdb_mpq result;
343 if (is_floating_type (type))
345 double d = target_float_to_host_double (value_contents (value).data (),
346 type);
347 mpq_set_d (result.val, d);
349 else
351 gdb_assert (is_integral_type (type)
352 || is_fixed_point_type (type));
354 gdb_mpz vz;
355 vz.read (value_contents (value), type_byte_order (type),
356 type->is_unsigned ());
357 mpq_set_z (result.val, vz.val);
359 if (is_fixed_point_type (type))
360 mpq_mul (result.val, result.val,
361 type->fixed_point_scaling_factor ().val);
364 return result;
367 /* Assuming that TO_TYPE is a fixed point type, return a value
368 corresponding to the cast of FROM_VAL to that type. */
370 static struct value *
371 value_cast_to_fixed_point (struct type *to_type, struct value *from_val)
373 struct type *from_type = value_type (from_val);
375 if (from_type == to_type)
376 return from_val;
378 if (!is_floating_type (from_type)
379 && !is_integral_type (from_type)
380 && !is_fixed_point_type (from_type))
381 error (_("Invalid conversion from type %s to fixed point type %s"),
382 from_type->name (), to_type->name ());
384 gdb_mpq vq = value_to_gdb_mpq (from_val);
386 /* Divide that value by the scaling factor to obtain the unscaled
387 value, first in rational form, and then in integer form. */
389 mpq_div (vq.val, vq.val, to_type->fixed_point_scaling_factor ().val);
390 gdb_mpz unscaled = vq.get_rounded ();
392 /* Finally, create the result value, and pack the unscaled value
393 in it. */
394 struct value *result = allocate_value (to_type);
395 unscaled.write (value_contents_raw (result),
396 type_byte_order (to_type),
397 to_type->is_unsigned ());
399 return result;
402 /* Cast value ARG2 to type TYPE and return as a value.
403 More general than a C cast: accepts any two types of the same length,
404 and if ARG2 is an lvalue it can be cast into anything at all. */
405 /* In C++, casts may change pointer or object representations. */
407 struct value *
408 value_cast (struct type *type, struct value *arg2)
410 enum type_code code1;
411 enum type_code code2;
412 int scalar;
413 struct type *type2;
415 int convert_to_boolean = 0;
417 /* TYPE might be equal in meaning to the existing type of ARG2, but for
418 many reasons, might be a different type object (e.g. TYPE might be a
419 gdbarch owned type, while VALUE_TYPE (ARG2) could be an objfile owned
420 type).
422 In this case we want to preserve the LVAL of ARG2 as this allows the
423 resulting value to be used in more places. We do this by calling
424 VALUE_COPY if appropriate. */
425 if (types_deeply_equal (value_type (arg2), type))
427 /* If the types are exactly equal then we can avoid creating a new
428 value completely. */
429 if (value_type (arg2) != type)
431 arg2 = value_copy (arg2);
432 deprecated_set_value_type (arg2, type);
434 return arg2;
437 if (is_fixed_point_type (type))
438 return value_cast_to_fixed_point (type, arg2);
440 /* Check if we are casting struct reference to struct reference. */
441 if (TYPE_IS_REFERENCE (check_typedef (type)))
443 /* We dereference type; then we recurse and finally
444 we generate value of the given reference. Nothing wrong with
445 that. */
446 struct type *t1 = check_typedef (type);
447 struct type *dereftype = check_typedef (t1->target_type ());
448 struct value *val = value_cast (dereftype, arg2);
450 return value_ref (val, t1->code ());
453 if (TYPE_IS_REFERENCE (check_typedef (value_type (arg2))))
454 /* We deref the value and then do the cast. */
455 return value_cast (type, coerce_ref (arg2));
457 /* Strip typedefs / resolve stubs in order to get at the type's
458 code/length, but remember the original type, to use as the
459 resulting type of the cast, in case it was a typedef. */
460 struct type *to_type = type;
462 type = check_typedef (type);
463 code1 = type->code ();
464 arg2 = coerce_ref (arg2);
465 type2 = check_typedef (value_type (arg2));
467 /* You can't cast to a reference type. See value_cast_pointers
468 instead. */
469 gdb_assert (!TYPE_IS_REFERENCE (type));
471 /* A cast to an undetermined-length array_type, such as
472 (TYPE [])OBJECT, is treated like a cast to (TYPE [N])OBJECT,
473 where N is sizeof(OBJECT)/sizeof(TYPE). */
474 if (code1 == TYPE_CODE_ARRAY)
476 struct type *element_type = type->target_type ();
477 unsigned element_length = check_typedef (element_type)->length ();
479 if (element_length > 0 && type->bounds ()->high.kind () == PROP_UNDEFINED)
481 struct type *range_type = type->index_type ();
482 int val_length = type2->length ();
483 LONGEST low_bound, high_bound, new_length;
485 if (!get_discrete_bounds (range_type, &low_bound, &high_bound))
486 low_bound = 0, high_bound = 0;
487 new_length = val_length / element_length;
488 if (val_length % element_length != 0)
489 warning (_("array element type size does not "
490 "divide object size in cast"));
491 /* FIXME-type-allocation: need a way to free this type when
492 we are done with it. */
493 range_type = create_static_range_type (NULL,
494 range_type->target_type (),
495 low_bound,
496 new_length + low_bound - 1);
497 deprecated_set_value_type (arg2,
498 create_array_type (NULL,
499 element_type,
500 range_type));
501 return arg2;
505 if (current_language->c_style_arrays_p ()
506 && type2->code () == TYPE_CODE_ARRAY
507 && !type2->is_vector ())
508 arg2 = value_coerce_array (arg2);
510 if (type2->code () == TYPE_CODE_FUNC)
511 arg2 = value_coerce_function (arg2);
513 type2 = check_typedef (value_type (arg2));
514 code2 = type2->code ();
516 if (code1 == TYPE_CODE_COMPLEX)
517 return cast_into_complex (to_type, arg2);
518 if (code1 == TYPE_CODE_BOOL)
520 code1 = TYPE_CODE_INT;
521 convert_to_boolean = 1;
523 if (code1 == TYPE_CODE_CHAR)
524 code1 = TYPE_CODE_INT;
525 if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
526 code2 = TYPE_CODE_INT;
528 scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
529 || code2 == TYPE_CODE_DECFLOAT || code2 == TYPE_CODE_ENUM
530 || code2 == TYPE_CODE_RANGE
531 || is_fixed_point_type (type2));
533 if ((code1 == TYPE_CODE_STRUCT || code1 == TYPE_CODE_UNION)
534 && (code2 == TYPE_CODE_STRUCT || code2 == TYPE_CODE_UNION)
535 && type->name () != 0)
537 struct value *v = value_cast_structs (to_type, arg2);
539 if (v)
540 return v;
543 if (is_floating_type (type) && scalar)
545 if (is_floating_value (arg2))
547 struct value *v = allocate_value (to_type);
548 target_float_convert (value_contents (arg2).data (), type2,
549 value_contents_raw (v).data (), type);
550 return v;
552 else if (is_fixed_point_type (type2))
554 gdb_mpq fp_val;
556 fp_val.read_fixed_point (value_contents (arg2),
557 type_byte_order (type2),
558 type2->is_unsigned (),
559 type2->fixed_point_scaling_factor ());
561 struct value *v = allocate_value (to_type);
562 target_float_from_host_double (value_contents_raw (v).data (),
563 to_type, mpq_get_d (fp_val.val));
564 return v;
567 /* The only option left is an integral type. */
568 if (type2->is_unsigned ())
569 return value_from_ulongest (to_type, value_as_long (arg2));
570 else
571 return value_from_longest (to_type, value_as_long (arg2));
573 else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
574 || code1 == TYPE_CODE_RANGE)
575 && (scalar || code2 == TYPE_CODE_PTR
576 || code2 == TYPE_CODE_MEMBERPTR))
578 LONGEST longest;
580 /* When we cast pointers to integers, we mustn't use
581 gdbarch_pointer_to_address to find the address the pointer
582 represents, as value_as_long would. GDB should evaluate
583 expressions just as the compiler would --- and the compiler
584 sees a cast as a simple reinterpretation of the pointer's
585 bits. */
586 if (code2 == TYPE_CODE_PTR)
587 longest = extract_unsigned_integer
588 (value_contents (arg2), type_byte_order (type2));
589 else
590 longest = value_as_long (arg2);
591 return value_from_longest (to_type, convert_to_boolean ?
592 (LONGEST) (longest ? 1 : 0) : longest);
594 else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT
595 || code2 == TYPE_CODE_ENUM
596 || code2 == TYPE_CODE_RANGE))
598 /* type->length () is the length of a pointer, but we really
599 want the length of an address! -- we are really dealing with
600 addresses (i.e., gdb representations) not pointers (i.e.,
601 target representations) here.
603 This allows things like "print *(int *)0x01000234" to work
604 without printing a misleading message -- which would
605 otherwise occur when dealing with a target having two byte
606 pointers and four byte addresses. */
608 int addr_bit = gdbarch_addr_bit (type2->arch ());
609 LONGEST longest = value_as_long (arg2);
611 if (addr_bit < sizeof (LONGEST) * HOST_CHAR_BIT)
613 if (longest >= ((LONGEST) 1 << addr_bit)
614 || longest <= -((LONGEST) 1 << addr_bit))
615 warning (_("value truncated"));
617 return value_from_longest (to_type, longest);
619 else if (code1 == TYPE_CODE_METHODPTR && code2 == TYPE_CODE_INT
620 && value_as_long (arg2) == 0)
622 struct value *result = allocate_value (to_type);
624 cplus_make_method_ptr (to_type,
625 value_contents_writeable (result).data (), 0, 0);
626 return result;
628 else if (code1 == TYPE_CODE_MEMBERPTR && code2 == TYPE_CODE_INT
629 && value_as_long (arg2) == 0)
631 /* The Itanium C++ ABI represents NULL pointers to members as
632 minus one, instead of biasing the normal case. */
633 return value_from_longest (to_type, -1);
635 else if (code1 == TYPE_CODE_ARRAY && type->is_vector ()
636 && code2 == TYPE_CODE_ARRAY && type2->is_vector ()
637 && type->length () != type2->length ())
638 error (_("Cannot convert between vector values of different sizes"));
639 else if (code1 == TYPE_CODE_ARRAY && type->is_vector () && scalar
640 && type->length () != type2->length ())
641 error (_("can only cast scalar to vector of same size"));
642 else if (code1 == TYPE_CODE_VOID)
644 return value_zero (to_type, not_lval);
646 else if (type->length () == type2->length ())
648 if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
649 return value_cast_pointers (to_type, arg2, 0);
651 arg2 = value_copy (arg2);
652 deprecated_set_value_type (arg2, to_type);
653 set_value_enclosing_type (arg2, to_type);
654 set_value_pointed_to_offset (arg2, 0); /* pai: chk_val */
655 return arg2;
657 else if (VALUE_LVAL (arg2) == lval_memory)
658 return value_at_lazy (to_type, value_address (arg2));
659 else
661 if (current_language->la_language == language_ada)
662 error (_("Invalid type conversion."));
663 error (_("Invalid cast."));
667 /* The C++ reinterpret_cast operator. */
669 struct value *
670 value_reinterpret_cast (struct type *type, struct value *arg)
672 struct value *result;
673 struct type *real_type = check_typedef (type);
674 struct type *arg_type, *dest_type;
675 int is_ref = 0;
676 enum type_code dest_code, arg_code;
678 /* Do reference, function, and array conversion. */
679 arg = coerce_array (arg);
681 /* Attempt to preserve the type the user asked for. */
682 dest_type = type;
684 /* If we are casting to a reference type, transform
685 reinterpret_cast<T&[&]>(V) to *reinterpret_cast<T*>(&V). */
686 if (TYPE_IS_REFERENCE (real_type))
688 is_ref = 1;
689 arg = value_addr (arg);
690 dest_type = lookup_pointer_type (dest_type->target_type ());
691 real_type = lookup_pointer_type (real_type);
694 arg_type = value_type (arg);
696 dest_code = real_type->code ();
697 arg_code = arg_type->code ();
699 /* We can convert pointer types, or any pointer type to int, or int
700 type to pointer. */
701 if ((dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_INT)
702 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_PTR)
703 || (dest_code == TYPE_CODE_METHODPTR && arg_code == TYPE_CODE_INT)
704 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_METHODPTR)
705 || (dest_code == TYPE_CODE_MEMBERPTR && arg_code == TYPE_CODE_INT)
706 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_MEMBERPTR)
707 || (dest_code == arg_code
708 && (dest_code == TYPE_CODE_PTR
709 || dest_code == TYPE_CODE_METHODPTR
710 || dest_code == TYPE_CODE_MEMBERPTR)))
711 result = value_cast (dest_type, arg);
712 else
713 error (_("Invalid reinterpret_cast"));
715 if (is_ref)
716 result = value_cast (type, value_ref (value_ind (result),
717 type->code ()));
719 return result;
722 /* A helper for value_dynamic_cast. This implements the first of two
723 runtime checks: we iterate over all the base classes of the value's
724 class which are equal to the desired class; if only one of these
725 holds the value, then it is the answer. */
727 static int
728 dynamic_cast_check_1 (struct type *desired_type,
729 const gdb_byte *valaddr,
730 LONGEST embedded_offset,
731 CORE_ADDR address,
732 struct value *val,
733 struct type *search_type,
734 CORE_ADDR arg_addr,
735 struct type *arg_type,
736 struct value **result)
738 int i, result_count = 0;
740 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
742 LONGEST offset = baseclass_offset (search_type, i, valaddr,
743 embedded_offset,
744 address, val);
746 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
748 if (address + embedded_offset + offset >= arg_addr
749 && address + embedded_offset + offset < arg_addr + arg_type->length ())
751 ++result_count;
752 if (!*result)
753 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
754 address + embedded_offset + offset);
757 else
758 result_count += dynamic_cast_check_1 (desired_type,
759 valaddr,
760 embedded_offset + offset,
761 address, val,
762 TYPE_BASECLASS (search_type, i),
763 arg_addr,
764 arg_type,
765 result);
768 return result_count;
771 /* A helper for value_dynamic_cast. This implements the second of two
772 runtime checks: we look for a unique public sibling class of the
773 argument's declared class. */
775 static int
776 dynamic_cast_check_2 (struct type *desired_type,
777 const gdb_byte *valaddr,
778 LONGEST embedded_offset,
779 CORE_ADDR address,
780 struct value *val,
781 struct type *search_type,
782 struct value **result)
784 int i, result_count = 0;
786 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
788 LONGEST offset;
790 if (! BASETYPE_VIA_PUBLIC (search_type, i))
791 continue;
793 offset = baseclass_offset (search_type, i, valaddr, embedded_offset,
794 address, val);
795 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
797 ++result_count;
798 if (*result == NULL)
799 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
800 address + embedded_offset + offset);
802 else
803 result_count += dynamic_cast_check_2 (desired_type,
804 valaddr,
805 embedded_offset + offset,
806 address, val,
807 TYPE_BASECLASS (search_type, i),
808 result);
811 return result_count;
814 /* The C++ dynamic_cast operator. */
816 struct value *
817 value_dynamic_cast (struct type *type, struct value *arg)
819 int full, using_enc;
820 LONGEST top;
821 struct type *resolved_type = check_typedef (type);
822 struct type *arg_type = check_typedef (value_type (arg));
823 struct type *class_type, *rtti_type;
824 struct value *result, *tem, *original_arg = arg;
825 CORE_ADDR addr;
826 int is_ref = TYPE_IS_REFERENCE (resolved_type);
828 if (resolved_type->code () != TYPE_CODE_PTR
829 && !TYPE_IS_REFERENCE (resolved_type))
830 error (_("Argument to dynamic_cast must be a pointer or reference type"));
831 if (resolved_type->target_type ()->code () != TYPE_CODE_VOID
832 && resolved_type->target_type ()->code () != TYPE_CODE_STRUCT)
833 error (_("Argument to dynamic_cast must be pointer to class or `void *'"));
835 class_type = check_typedef (resolved_type->target_type ());
836 if (resolved_type->code () == TYPE_CODE_PTR)
838 if (arg_type->code () != TYPE_CODE_PTR
839 && ! (arg_type->code () == TYPE_CODE_INT
840 && value_as_long (arg) == 0))
841 error (_("Argument to dynamic_cast does not have pointer type"));
842 if (arg_type->code () == TYPE_CODE_PTR)
844 arg_type = check_typedef (arg_type->target_type ());
845 if (arg_type->code () != TYPE_CODE_STRUCT)
846 error (_("Argument to dynamic_cast does "
847 "not have pointer to class type"));
850 /* Handle NULL pointers. */
851 if (value_as_long (arg) == 0)
852 return value_zero (type, not_lval);
854 arg = value_ind (arg);
856 else
858 if (arg_type->code () != TYPE_CODE_STRUCT)
859 error (_("Argument to dynamic_cast does not have class type"));
862 /* If the classes are the same, just return the argument. */
863 if (class_types_same_p (class_type, arg_type))
864 return value_cast (type, arg);
866 /* If the target type is a unique base class of the argument's
867 declared type, just cast it. */
868 if (is_ancestor (class_type, arg_type))
870 if (is_unique_ancestor (class_type, arg))
871 return value_cast (type, original_arg);
872 error (_("Ambiguous dynamic_cast"));
875 rtti_type = value_rtti_type (arg, &full, &top, &using_enc);
876 if (! rtti_type)
877 error (_("Couldn't determine value's most derived type for dynamic_cast"));
879 /* Compute the most derived object's address. */
880 addr = value_address (arg);
881 if (full)
883 /* Done. */
885 else if (using_enc)
886 addr += top;
887 else
888 addr += top + value_embedded_offset (arg);
890 /* dynamic_cast<void *> means to return a pointer to the
891 most-derived object. */
892 if (resolved_type->code () == TYPE_CODE_PTR
893 && resolved_type->target_type ()->code () == TYPE_CODE_VOID)
894 return value_at_lazy (type, addr);
896 tem = value_at (type, addr);
897 type = value_type (tem);
899 /* The first dynamic check specified in 5.2.7. */
900 if (is_public_ancestor (arg_type, resolved_type->target_type ()))
902 if (class_types_same_p (rtti_type, resolved_type->target_type ()))
903 return tem;
904 result = NULL;
905 if (dynamic_cast_check_1 (resolved_type->target_type (),
906 value_contents_for_printing (tem).data (),
907 value_embedded_offset (tem),
908 value_address (tem), 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 value_contents_for_printing (tem).data (),
923 value_embedded_offset (tem),
924 value_address (tem), 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 = allocate_value (type);
959 gdb::array_view<gdb_byte> val_contents = value_contents_writeable (val);
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 (value_contents_all (tmp),
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 (VALUE_LVAL (val) == 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, int lazy)
988 struct value *val;
990 if (check_typedef (type)->code () == TYPE_CODE_VOID)
991 error (_("Attempt to dereference a generic pointer."));
993 val = value_from_contents_and_address (type, NULL, addr);
995 if (!lazy)
996 value_fetch_lazy (val);
998 return val;
1001 /* Return a value with type TYPE located at ADDR.
1003 Call value_at only if the data needs to be fetched immediately;
1004 if we can be 'lazy' and defer the fetch, perhaps indefinitely, call
1005 value_at_lazy instead. value_at_lazy simply records the address of
1006 the data and sets the lazy-evaluation-required flag. The lazy flag
1007 is tested in the value_contents macro, which is used if and when
1008 the contents are actually required. The type of the created value
1009 may differ from the passed type TYPE. Make sure to retrieve the
1010 returned values's new type after this call e.g. in case the type
1011 is a variable length array.
1013 Note: value_at does *NOT* handle embedded offsets; perform such
1014 adjustments before or after calling it. */
1016 struct value *
1017 value_at (struct type *type, CORE_ADDR addr)
1019 return get_value_at (type, addr, 0);
1022 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).
1023 The type of the created value may differ from the passed type TYPE.
1024 Make sure to retrieve the returned values's new type after this call
1025 e.g. in case the type is a variable length array. */
1027 struct value *
1028 value_at_lazy (struct type *type, CORE_ADDR addr)
1030 return get_value_at (type, addr, 1);
1033 void
1034 read_value_memory (struct value *val, LONGEST bit_offset,
1035 int stack, CORE_ADDR memaddr,
1036 gdb_byte *buffer, size_t length)
1038 ULONGEST xfered_total = 0;
1039 struct gdbarch *arch = get_value_arch (val);
1040 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1041 enum target_object object;
1043 object = stack ? TARGET_OBJECT_STACK_MEMORY : TARGET_OBJECT_MEMORY;
1045 while (xfered_total < length)
1047 enum target_xfer_status status;
1048 ULONGEST xfered_partial;
1050 status = target_xfer_partial (current_inferior ()->top_target (),
1051 object, NULL,
1052 buffer + xfered_total * unit_size, NULL,
1053 memaddr + xfered_total,
1054 length - xfered_total,
1055 &xfered_partial);
1057 if (status == TARGET_XFER_OK)
1058 /* nothing */;
1059 else if (status == TARGET_XFER_UNAVAILABLE)
1060 mark_value_bits_unavailable (val, (xfered_total * HOST_CHAR_BIT
1061 + bit_offset),
1062 xfered_partial * HOST_CHAR_BIT);
1063 else if (status == TARGET_XFER_EOF)
1064 memory_error (TARGET_XFER_E_IO, memaddr + xfered_total);
1065 else
1066 memory_error (status, memaddr + xfered_total);
1068 xfered_total += xfered_partial;
1069 QUIT;
1073 /* Store the contents of FROMVAL into the location of TOVAL.
1074 Return a new value with the location of TOVAL and contents of FROMVAL. */
1076 struct value *
1077 value_assign (struct value *toval, struct value *fromval)
1079 struct type *type;
1080 struct value *val;
1081 struct frame_id old_frame;
1083 if (!deprecated_value_modifiable (toval))
1084 error (_("Left operand of assignment is not a modifiable lvalue."));
1086 toval = coerce_ref (toval);
1088 type = value_type (toval);
1089 if (VALUE_LVAL (toval) != lval_internalvar)
1090 fromval = value_cast (type, fromval);
1091 else
1093 /* Coerce arrays and functions to pointers, except for arrays
1094 which only live in GDB's storage. */
1095 if (!value_must_coerce_to_target (fromval))
1096 fromval = coerce_array (fromval);
1099 type = check_typedef (type);
1101 /* Since modifying a register can trash the frame chain, and
1102 modifying memory can trash the frame cache, we save the old frame
1103 and then restore the new frame afterwards. */
1104 old_frame = get_frame_id (deprecated_safe_get_selected_frame ());
1106 switch (VALUE_LVAL (toval))
1108 case lval_internalvar:
1109 set_internalvar (VALUE_INTERNALVAR (toval), fromval);
1110 return value_of_internalvar (type->arch (),
1111 VALUE_INTERNALVAR (toval));
1113 case lval_internalvar_component:
1115 LONGEST offset = value_offset (toval);
1117 /* Are we dealing with a bitfield?
1119 It is important to mention that `value_parent (toval)' is
1120 non-NULL iff `value_bitsize (toval)' is non-zero. */
1121 if (value_bitsize (toval))
1123 /* VALUE_INTERNALVAR below refers to the parent value, while
1124 the offset is relative to this parent value. */
1125 gdb_assert (value_parent (value_parent (toval)) == NULL);
1126 offset += value_offset (value_parent (toval));
1129 set_internalvar_component (VALUE_INTERNALVAR (toval),
1130 offset,
1131 value_bitpos (toval),
1132 value_bitsize (toval),
1133 fromval);
1135 break;
1137 case lval_memory:
1139 const gdb_byte *dest_buffer;
1140 CORE_ADDR changed_addr;
1141 int changed_len;
1142 gdb_byte buffer[sizeof (LONGEST)];
1144 if (value_bitsize (toval))
1146 struct value *parent = value_parent (toval);
1148 changed_addr = value_address (parent) + value_offset (toval);
1149 changed_len = (value_bitpos (toval)
1150 + value_bitsize (toval)
1151 + HOST_CHAR_BIT - 1)
1152 / HOST_CHAR_BIT;
1154 /* If we can read-modify-write exactly the size of the
1155 containing type (e.g. short or int) then do so. This
1156 is safer for volatile bitfields mapped to hardware
1157 registers. */
1158 if (changed_len < type->length ()
1159 && type->length () <= (int) sizeof (LONGEST)
1160 && ((LONGEST) changed_addr % type->length ()) == 0)
1161 changed_len = type->length ();
1163 if (changed_len > (int) sizeof (LONGEST))
1164 error (_("Can't handle bitfields which "
1165 "don't fit in a %d bit word."),
1166 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1168 read_memory (changed_addr, buffer, changed_len);
1169 modify_field (type, buffer, value_as_long (fromval),
1170 value_bitpos (toval), value_bitsize (toval));
1171 dest_buffer = buffer;
1173 else
1175 changed_addr = value_address (toval);
1176 changed_len = type_length_units (type);
1177 dest_buffer = value_contents (fromval).data ();
1180 write_memory_with_notification (changed_addr, dest_buffer, changed_len);
1182 break;
1184 case lval_register:
1186 frame_info_ptr frame;
1187 struct gdbarch *gdbarch;
1188 int value_reg;
1190 /* Figure out which frame this register value is in. The value
1191 holds the frame_id for the next frame, that is the frame this
1192 register value was unwound from.
1194 Below we will call put_frame_register_bytes which requires that
1195 we pass it the actual frame in which the register value is
1196 valid, i.e. not the next frame. */
1197 frame = frame_find_by_id (VALUE_NEXT_FRAME_ID (toval));
1198 frame = get_prev_frame_always (frame);
1200 value_reg = VALUE_REGNUM (toval);
1202 if (!frame)
1203 error (_("Value being assigned to is no longer active."));
1205 gdbarch = get_frame_arch (frame);
1207 if (value_bitsize (toval))
1209 struct value *parent = value_parent (toval);
1210 LONGEST offset = value_offset (parent) + value_offset (toval);
1211 size_t changed_len;
1212 gdb_byte buffer[sizeof (LONGEST)];
1213 int optim, unavail;
1215 changed_len = (value_bitpos (toval)
1216 + value_bitsize (toval)
1217 + HOST_CHAR_BIT - 1)
1218 / HOST_CHAR_BIT;
1220 if (changed_len > sizeof (LONGEST))
1221 error (_("Can't handle bitfields which "
1222 "don't fit in a %d bit word."),
1223 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1225 if (!get_frame_register_bytes (frame, value_reg, offset,
1226 {buffer, changed_len},
1227 &optim, &unavail))
1229 if (optim)
1230 throw_error (OPTIMIZED_OUT_ERROR,
1231 _("value has been optimized out"));
1232 if (unavail)
1233 throw_error (NOT_AVAILABLE_ERROR,
1234 _("value is not available"));
1237 modify_field (type, buffer, value_as_long (fromval),
1238 value_bitpos (toval), value_bitsize (toval));
1240 put_frame_register_bytes (frame, value_reg, offset,
1241 {buffer, changed_len});
1243 else
1245 if (gdbarch_convert_register_p (gdbarch, VALUE_REGNUM (toval),
1246 type))
1248 /* If TOVAL is a special machine register requiring
1249 conversion of program values to a special raw
1250 format. */
1251 gdbarch_value_to_register (gdbarch, frame,
1252 VALUE_REGNUM (toval), type,
1253 value_contents (fromval).data ());
1255 else
1256 put_frame_register_bytes (frame, value_reg,
1257 value_offset (toval),
1258 value_contents (fromval));
1261 gdb::observers::register_changed.notify (frame, value_reg);
1262 break;
1265 case lval_computed:
1267 const struct lval_funcs *funcs = value_computed_funcs (toval);
1269 if (funcs->write != NULL)
1271 funcs->write (toval, fromval);
1272 break;
1275 /* Fall through. */
1277 default:
1278 error (_("Left operand of assignment is not an lvalue."));
1281 /* Assigning to the stack pointer, frame pointer, and other
1282 (architecture and calling convention specific) registers may
1283 cause the frame cache and regcache to be out of date. Assigning to memory
1284 also can. We just do this on all assignments to registers or
1285 memory, for simplicity's sake; I doubt the slowdown matters. */
1286 switch (VALUE_LVAL (toval))
1288 case lval_memory:
1289 case lval_register:
1290 case lval_computed:
1292 gdb::observers::target_changed.notify
1293 (current_inferior ()->top_target ());
1295 /* Having destroyed the frame cache, restore the selected
1296 frame. */
1298 /* FIXME: cagney/2002-11-02: There has to be a better way of
1299 doing this. Instead of constantly saving/restoring the
1300 frame. Why not create a get_selected_frame() function that,
1301 having saved the selected frame's ID can automatically
1302 re-find the previously selected frame automatically. */
1305 frame_info_ptr fi = frame_find_by_id (old_frame);
1307 if (fi != NULL)
1308 select_frame (fi);
1311 break;
1312 default:
1313 break;
1316 /* If the field does not entirely fill a LONGEST, then zero the sign
1317 bits. If the field is signed, and is negative, then sign
1318 extend. */
1319 if ((value_bitsize (toval) > 0)
1320 && (value_bitsize (toval) < 8 * (int) sizeof (LONGEST)))
1322 LONGEST fieldval = value_as_long (fromval);
1323 LONGEST valmask = (((ULONGEST) 1) << value_bitsize (toval)) - 1;
1325 fieldval &= valmask;
1326 if (!type->is_unsigned ()
1327 && (fieldval & (valmask ^ (valmask >> 1))))
1328 fieldval |= ~valmask;
1330 fromval = value_from_longest (type, fieldval);
1333 /* The return value is a copy of TOVAL so it shares its location
1334 information, but its contents are updated from FROMVAL. This
1335 implies the returned value is not lazy, even if TOVAL was. */
1336 val = value_copy (toval);
1337 set_value_lazy (val, 0);
1338 copy (value_contents (fromval), value_contents_raw (val));
1340 /* We copy over the enclosing type and pointed-to offset from FROMVAL
1341 in the case of pointer types. For object types, the enclosing type
1342 and embedded offset must *not* be copied: the target object refered
1343 to by TOVAL retains its original dynamic type after assignment. */
1344 if (type->code () == TYPE_CODE_PTR)
1346 set_value_enclosing_type (val, value_enclosing_type (fromval));
1347 set_value_pointed_to_offset (val, value_pointed_to_offset (fromval));
1350 return val;
1353 /* Extend a value ARG1 to COUNT repetitions of its type. */
1355 struct value *
1356 value_repeat (struct value *arg1, int count)
1358 struct value *val;
1360 if (VALUE_LVAL (arg1) != lval_memory)
1361 error (_("Only values in memory can be extended with '@'."));
1362 if (count < 1)
1363 error (_("Invalid number %d of repetitions."), count);
1365 val = allocate_repeat_value (value_enclosing_type (arg1), count);
1367 VALUE_LVAL (val) = lval_memory;
1368 set_value_address (val, value_address (arg1));
1370 read_value_memory (val, 0, value_stack (val), value_address (val),
1371 value_contents_all_raw (val).data (),
1372 type_length_units (value_enclosing_type (val)));
1374 return val;
1377 struct value *
1378 value_of_variable (struct symbol *var, const struct block *b)
1380 frame_info_ptr frame = NULL;
1382 if (symbol_read_needs_frame (var))
1383 frame = get_selected_frame (_("No frame selected."));
1385 return read_var_value (var, b, frame);
1388 struct value *
1389 address_of_variable (struct symbol *var, const struct block *b)
1391 struct type *type = var->type ();
1392 struct value *val;
1394 /* Evaluate it first; if the result is a memory address, we're fine.
1395 Lazy evaluation pays off here. */
1397 val = value_of_variable (var, b);
1398 type = value_type (val);
1400 if ((VALUE_LVAL (val) == lval_memory && value_lazy (val))
1401 || type->code () == TYPE_CODE_FUNC)
1403 CORE_ADDR addr = value_address (val);
1405 return value_from_pointer (lookup_pointer_type (type), addr);
1408 /* Not a memory address; check what the problem was. */
1409 switch (VALUE_LVAL (val))
1411 case lval_register:
1413 frame_info_ptr frame;
1414 const char *regname;
1416 frame = frame_find_by_id (VALUE_NEXT_FRAME_ID (val));
1417 gdb_assert (frame);
1419 regname = gdbarch_register_name (get_frame_arch (frame),
1420 VALUE_REGNUM (val));
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 (VALUE_LVAL (val) != not_lval
1447 && VALUE_LVAL (val) != lval_internalvar
1448 && VALUE_LVAL (val) != lval_xcallable)
1449 return false;
1451 valtype = check_typedef (value_type (val));
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 (value_type (val))->length ();
1478 addr = allocate_space_in_inferior (length);
1479 write_memory (addr, value_contents (val).data (), length);
1480 return value_at_lazy (value_type (val), 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 (value_type (arg1));
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 (VALUE_LVAL (arg1) != 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 value_address (arg1));
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 (VALUE_LVAL (arg1) != lval_memory)
1532 error (_("Attempt to take address of value not located in memory."));
1534 retval = value_from_pointer (lookup_pointer_type (value_type (arg1)),
1535 value_address (arg1));
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 (value_type (arg1));
1548 if (TYPE_IS_REFERENCE (type))
1550 if (value_bits_synthetic_pointer (arg1, value_embedded_offset (arg1),
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 (value_enclosing_type (arg1));
1563 struct type *enclosing_type_ptr
1564 = lookup_pointer_type (enclosing_type->target_type ());
1566 arg2 = value_copy (arg1);
1567 deprecated_set_value_type (arg2, type_ptr);
1568 set_value_enclosing_type (arg2, 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 (VALUE_LVAL (arg1) != 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 (value_type (arg1)),
1585 (value_address (arg1)
1586 + value_embedded_offset (arg1)));
1588 /* This may be a pointer to a base subobject; so remember the
1589 full derived object's type ... */
1590 set_value_enclosing_type (arg2,
1591 lookup_pointer_type (value_enclosing_type (arg1)));
1592 /* ... and also the relative position of the subobject in the full
1593 object. */
1594 set_value_pointed_to_offset (arg2, value_embedded_offset (arg1));
1595 return arg2;
1598 /* Return a reference value for the object for which ARG1 is the
1599 contents. */
1601 struct value *
1602 value_ref (struct value *arg1, enum type_code refcode)
1604 struct value *arg2;
1605 struct type *type = check_typedef (value_type (arg1));
1607 gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1609 if ((type->code () == TYPE_CODE_REF
1610 || type->code () == TYPE_CODE_RVALUE_REF)
1611 && type->code () == refcode)
1612 return arg1;
1614 arg2 = value_addr (arg1);
1615 deprecated_set_value_type (arg2, lookup_reference_type (type, refcode));
1616 return arg2;
1619 /* Given a value of a pointer type, apply the C unary * operator to
1620 it. */
1622 struct value *
1623 value_ind (struct value *arg1)
1625 struct type *base_type;
1626 struct value *arg2;
1628 arg1 = coerce_array (arg1);
1630 base_type = check_typedef (value_type (arg1));
1632 if (VALUE_LVAL (arg1) == lval_computed)
1634 const struct lval_funcs *funcs = value_computed_funcs (arg1);
1636 if (funcs->indirect)
1638 struct value *result = funcs->indirect (arg1);
1640 if (result)
1641 return result;
1645 if (base_type->code () == TYPE_CODE_PTR)
1647 struct type *enc_type;
1649 /* We may be pointing to something embedded in a larger object.
1650 Get the real type of the enclosing object. */
1651 enc_type = check_typedef (value_enclosing_type (arg1));
1652 enc_type = enc_type->target_type ();
1654 CORE_ADDR base_addr;
1655 if (check_typedef (enc_type)->code () == TYPE_CODE_FUNC
1656 || check_typedef (enc_type)->code () == TYPE_CODE_METHOD)
1658 /* For functions, go through find_function_addr, which knows
1659 how to handle function descriptors. */
1660 base_addr = find_function_addr (arg1, NULL);
1662 else
1664 /* Retrieve the enclosing object pointed to. */
1665 base_addr = (value_as_address (arg1)
1666 - value_pointed_to_offset (arg1));
1668 arg2 = value_at_lazy (enc_type, base_addr);
1669 enc_type = value_type (arg2);
1670 return readjust_indirect_value_type (arg2, enc_type, base_type,
1671 arg1, base_addr);
1674 error (_("Attempt to take contents of a non-pointer value."));
1677 /* Create a value for an array by allocating space in GDB, copying the
1678 data into that space, and then setting up an array value.
1680 The array bounds are set from LOWBOUND and HIGHBOUND, and the array
1681 is populated from the values passed in ELEMVEC.
1683 The element type of the array is inherited from the type of the
1684 first element, and all elements must have the same size (though we
1685 don't currently enforce any restriction on their types). */
1687 struct value *
1688 value_array (int lowbound, int highbound, struct value **elemvec)
1690 int nelem;
1691 int idx;
1692 ULONGEST typelength;
1693 struct value *val;
1694 struct type *arraytype;
1696 /* Validate that the bounds are reasonable and that each of the
1697 elements have the same size. */
1699 nelem = highbound - lowbound + 1;
1700 if (nelem <= 0)
1702 error (_("bad array bounds (%d, %d)"), lowbound, highbound);
1704 typelength = type_length_units (value_enclosing_type (elemvec[0]));
1705 for (idx = 1; idx < nelem; idx++)
1707 if (type_length_units (value_enclosing_type (elemvec[idx]))
1708 != typelength)
1710 error (_("array elements must all be the same size"));
1714 arraytype = lookup_array_range_type (value_enclosing_type (elemvec[0]),
1715 lowbound, highbound);
1717 if (!current_language->c_style_arrays_p ())
1719 val = allocate_value (arraytype);
1720 for (idx = 0; idx < nelem; idx++)
1721 value_contents_copy (val, idx * typelength, elemvec[idx], 0,
1722 typelength);
1723 return val;
1726 /* Allocate space to store the array, and then initialize it by
1727 copying in each element. */
1729 val = allocate_value (arraytype);
1730 for (idx = 0; idx < nelem; idx++)
1731 value_contents_copy (val, idx * typelength, elemvec[idx], 0, typelength);
1732 return val;
1735 struct value *
1736 value_cstring (const char *ptr, ssize_t len, struct type *char_type)
1738 struct value *val;
1739 int lowbound = current_language->string_lower_bound ();
1740 ssize_t highbound = len / char_type->length ();
1741 struct type *stringtype
1742 = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1744 val = allocate_value (stringtype);
1745 memcpy (value_contents_raw (val).data (), ptr, len);
1746 return val;
1749 /* Create a value for a string constant by allocating space in the
1750 inferior, copying the data into that space, and returning the
1751 address with type TYPE_CODE_STRING. PTR points to the string
1752 constant data; LEN is number of characters.
1754 Note that string types are like array of char types with a lower
1755 bound of zero and an upper bound of LEN - 1. Also note that the
1756 string may contain embedded null bytes. */
1758 struct value *
1759 value_string (const char *ptr, ssize_t len, struct type *char_type)
1761 struct value *val;
1762 int lowbound = current_language->string_lower_bound ();
1763 ssize_t highbound = len / char_type->length ();
1764 struct type *stringtype
1765 = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1767 val = allocate_value (stringtype);
1768 memcpy (value_contents_raw (val).data (), ptr, len);
1769 return val;
1773 /* See if we can pass arguments in T2 to a function which takes arguments
1774 of types T1. T1 is a list of NARGS arguments, and T2 is an array_view
1775 of the values we're trying to pass. If some arguments need coercion of
1776 some sort, then the coerced values are written into T2. Return value is
1777 0 if the arguments could be matched, or the position at which they
1778 differ if not.
1780 STATICP is nonzero if the T1 argument list came from a static
1781 member function. T2 must still include the ``this'' pointer, but
1782 it will be skipped.
1784 For non-static member functions, we ignore the first argument,
1785 which is the type of the instance variable. This is because we
1786 want to handle calls with objects from derived classes. This is
1787 not entirely correct: we should actually check to make sure that a
1788 requested operation is type secure, shouldn't we? FIXME. */
1790 static int
1791 typecmp (bool staticp, bool varargs, int nargs,
1792 struct field t1[], gdb::array_view<value *> t2)
1794 int i;
1796 /* Skip ``this'' argument if applicable. T2 will always include
1797 THIS. */
1798 if (staticp)
1799 t2 = t2.slice (1);
1801 for (i = 0;
1802 (i < nargs) && t1[i].type ()->code () != TYPE_CODE_VOID;
1803 i++)
1805 struct type *tt1, *tt2;
1807 if (i == t2.size ())
1808 return i + 1;
1810 tt1 = check_typedef (t1[i].type ());
1811 tt2 = check_typedef (value_type (t2[i]));
1813 if (TYPE_IS_REFERENCE (tt1)
1814 /* We should be doing hairy argument matching, as below. */
1815 && (check_typedef (tt1->target_type ())->code ()
1816 == tt2->code ()))
1818 if (tt2->code () == TYPE_CODE_ARRAY)
1819 t2[i] = value_coerce_array (t2[i]);
1820 else
1821 t2[i] = value_ref (t2[i], tt1->code ());
1822 continue;
1825 /* djb - 20000715 - Until the new type structure is in the
1826 place, and we can attempt things like implicit conversions,
1827 we need to do this so you can take something like a map<const
1828 char *>, and properly access map["hello"], because the
1829 argument to [] will be a reference to a pointer to a char,
1830 and the argument will be a pointer to a char. */
1831 while (TYPE_IS_REFERENCE (tt1) || tt1->code () == TYPE_CODE_PTR)
1833 tt1 = check_typedef ( tt1->target_type () );
1835 while (tt2->code () == TYPE_CODE_ARRAY
1836 || tt2->code () == TYPE_CODE_PTR
1837 || TYPE_IS_REFERENCE (tt2))
1839 tt2 = check_typedef (tt2->target_type ());
1841 if (tt1->code () == tt2->code ())
1842 continue;
1843 /* Array to pointer is a `trivial conversion' according to the
1844 ARM. */
1846 /* We should be doing much hairier argument matching (see
1847 section 13.2 of the ARM), but as a quick kludge, just check
1848 for the same type code. */
1849 if (t1[i].type ()->code () != value_type (t2[i])->code ())
1850 return i + 1;
1852 if (varargs || i == t2.size ())
1853 return 0;
1854 return i + 1;
1857 /* Helper class for search_struct_field that keeps track of found
1858 results and possibly throws an exception if the search yields
1859 ambiguous results. See search_struct_field for description of
1860 LOOKING_FOR_BASECLASS. */
1862 struct struct_field_searcher
1864 /* A found field. */
1865 struct found_field
1867 /* Path to the structure where the field was found. */
1868 std::vector<struct type *> path;
1870 /* The field found. */
1871 struct value *field_value;
1874 /* See corresponding fields for description of parameters. */
1875 struct_field_searcher (const char *name,
1876 struct type *outermost_type,
1877 bool looking_for_baseclass)
1878 : m_name (name),
1879 m_looking_for_baseclass (looking_for_baseclass),
1880 m_outermost_type (outermost_type)
1884 /* The search entry point. If LOOKING_FOR_BASECLASS is true and the
1885 base class search yields ambiguous results, this throws an
1886 exception. If LOOKING_FOR_BASECLASS is false, the found fields
1887 are accumulated and the caller (search_struct_field) takes care
1888 of throwing an error if the field search yields ambiguous
1889 results. The latter is done that way so that the error message
1890 can include a list of all the found candidates. */
1891 void search (struct value *arg, LONGEST offset, struct type *type);
1893 const std::vector<found_field> &fields ()
1895 return m_fields;
1898 struct value *baseclass ()
1900 return m_baseclass;
1903 private:
1904 /* Update results to include V, a found field/baseclass. */
1905 void update_result (struct value *v, LONGEST boffset);
1907 /* The name of the field/baseclass we're searching for. */
1908 const char *m_name;
1910 /* Whether we're looking for a baseclass, or a field. */
1911 const bool m_looking_for_baseclass;
1913 /* The offset of the baseclass containing the field/baseclass we
1914 last recorded. */
1915 LONGEST m_last_boffset = 0;
1917 /* If looking for a baseclass, then the result is stored here. */
1918 struct value *m_baseclass = nullptr;
1920 /* When looking for fields, the found candidates are stored
1921 here. */
1922 std::vector<found_field> m_fields;
1924 /* The type of the initial type passed to search_struct_field; this
1925 is used for error reporting when the lookup is ambiguous. */
1926 struct type *m_outermost_type;
1928 /* The full path to the struct being inspected. E.g. for field 'x'
1929 defined in class B inherited by class A, we have A and B pushed
1930 on the path. */
1931 std::vector <struct type *> m_struct_path;
1934 void
1935 struct_field_searcher::update_result (struct value *v, LONGEST boffset)
1937 if (v != NULL)
1939 if (m_looking_for_baseclass)
1941 if (m_baseclass != nullptr
1942 /* The result is not ambiguous if all the classes that are
1943 found occupy the same space. */
1944 && m_last_boffset != boffset)
1945 error (_("base class '%s' is ambiguous in type '%s'"),
1946 m_name, TYPE_SAFE_NAME (m_outermost_type));
1948 m_baseclass = v;
1949 m_last_boffset = boffset;
1951 else
1953 /* The field is not ambiguous if it occupies the same
1954 space. */
1955 if (m_fields.empty () || m_last_boffset != boffset)
1956 m_fields.push_back ({m_struct_path, v});
1957 else
1959 /*Fields can occupy the same space and have the same name (be
1960 ambiguous). This can happen when fields in two different base
1961 classes are marked [[no_unique_address]] and have the same name.
1962 The C++ standard says that such fields can only occupy the same
1963 space if they are of different type, but we don't rely on that in
1964 the following code. */
1965 bool ambiguous = false, insert = true;
1966 for (const found_field &field: m_fields)
1968 if(field.path.back () != m_struct_path.back ())
1970 /* Same boffset points to members of different classes.
1971 We have found an ambiguity and should record it. */
1972 ambiguous = true;
1974 else
1976 /* We don't need to insert this value again, because a
1977 non-ambiguous path already leads to it. */
1978 insert = false;
1979 break;
1982 if (ambiguous && insert)
1983 m_fields.push_back ({m_struct_path, v});
1989 /* A helper for search_struct_field. This does all the work; most
1990 arguments are as passed to search_struct_field. */
1992 void
1993 struct_field_searcher::search (struct value *arg1, LONGEST offset,
1994 struct type *type)
1996 int i;
1997 int nbases;
1999 m_struct_path.push_back (type);
2000 SCOPE_EXIT { m_struct_path.pop_back (); };
2002 type = check_typedef (type);
2003 nbases = TYPE_N_BASECLASSES (type);
2005 if (!m_looking_for_baseclass)
2006 for (i = type->num_fields () - 1; i >= nbases; i--)
2008 const char *t_field_name = type->field (i).name ();
2010 if (t_field_name && (strcmp_iw (t_field_name, m_name) == 0))
2012 struct value *v;
2014 if (field_is_static (&type->field (i)))
2015 v = value_static_field (type, i);
2016 else
2017 v = value_primitive_field (arg1, offset, i, type);
2019 update_result (v, offset);
2020 return;
2023 if (t_field_name
2024 && t_field_name[0] == '\0')
2026 struct type *field_type = type->field (i).type ();
2028 if (field_type->code () == TYPE_CODE_UNION
2029 || field_type->code () == TYPE_CODE_STRUCT)
2031 /* Look for a match through the fields of an anonymous
2032 union, or anonymous struct. C++ provides anonymous
2033 unions.
2035 In the GNU Chill (now deleted from GDB)
2036 implementation of variant record types, each
2037 <alternative field> has an (anonymous) union type,
2038 each member of the union represents a <variant
2039 alternative>. Each <variant alternative> is
2040 represented as a struct, with a member for each
2041 <variant field>. */
2043 LONGEST new_offset = offset;
2045 /* This is pretty gross. In G++, the offset in an
2046 anonymous union is relative to the beginning of the
2047 enclosing struct. In the GNU Chill (now deleted
2048 from GDB) implementation of variant records, the
2049 bitpos is zero in an anonymous union field, so we
2050 have to add the offset of the union here. */
2051 if (field_type->code () == TYPE_CODE_STRUCT
2052 || (field_type->num_fields () > 0
2053 && field_type->field (0).loc_bitpos () == 0))
2054 new_offset += type->field (i).loc_bitpos () / 8;
2056 search (arg1, new_offset, field_type);
2061 for (i = 0; i < nbases; i++)
2063 struct value *v = NULL;
2064 struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
2065 /* If we are looking for baseclasses, this is what we get when
2066 we hit them. But it could happen that the base part's member
2067 name is not yet filled in. */
2068 int found_baseclass = (m_looking_for_baseclass
2069 && TYPE_BASECLASS_NAME (type, i) != NULL
2070 && (strcmp_iw (m_name, basetype->name ()) == 0));
2071 LONGEST boffset = value_embedded_offset (arg1) + offset;
2073 if (BASETYPE_VIA_VIRTUAL (type, i))
2075 struct value *v2;
2077 boffset = baseclass_offset (type, i,
2078 value_contents_for_printing (arg1).data (),
2079 value_embedded_offset (arg1) + offset,
2080 value_address (arg1),
2081 arg1);
2083 /* The virtual base class pointer might have been clobbered
2084 by the user program. Make sure that it still points to a
2085 valid memory location. */
2087 boffset += value_embedded_offset (arg1) + offset;
2088 if (boffset < 0
2089 || boffset >= value_enclosing_type (arg1)->length ())
2091 CORE_ADDR base_addr;
2093 base_addr = value_address (arg1) + boffset;
2094 v2 = value_at_lazy (basetype, base_addr);
2095 if (target_read_memory (base_addr,
2096 value_contents_raw (v2).data (),
2097 value_type (v2)->length ()) != 0)
2098 error (_("virtual baseclass botch"));
2100 else
2102 v2 = value_copy (arg1);
2103 deprecated_set_value_type (v2, basetype);
2104 set_value_embedded_offset (v2, boffset);
2107 if (found_baseclass)
2108 v = v2;
2109 else
2110 search (v2, 0, TYPE_BASECLASS (type, i));
2112 else if (found_baseclass)
2113 v = value_primitive_field (arg1, offset, i, type);
2114 else
2116 search (arg1, offset + TYPE_BASECLASS_BITPOS (type, i) / 8,
2117 basetype);
2120 update_result (v, boffset);
2124 /* Helper function used by value_struct_elt to recurse through
2125 baseclasses. Look for a field NAME in ARG1. Search in it assuming
2126 it has (class) type TYPE. If found, return value, else return NULL.
2128 If LOOKING_FOR_BASECLASS, then instead of looking for struct
2129 fields, look for a baseclass named NAME. */
2131 static struct value *
2132 search_struct_field (const char *name, struct value *arg1,
2133 struct type *type, int looking_for_baseclass)
2135 struct_field_searcher searcher (name, type, looking_for_baseclass);
2137 searcher.search (arg1, 0, type);
2139 if (!looking_for_baseclass)
2141 const auto &fields = searcher.fields ();
2143 if (fields.empty ())
2144 return nullptr;
2145 else if (fields.size () == 1)
2146 return fields[0].field_value;
2147 else
2149 std::string candidates;
2151 for (auto &&candidate : fields)
2153 gdb_assert (!candidate.path.empty ());
2155 struct type *field_type = value_type (candidate.field_value);
2156 struct type *struct_type = candidate.path.back ();
2158 std::string path;
2159 bool first = true;
2160 for (struct type *t : candidate.path)
2162 if (first)
2163 first = false;
2164 else
2165 path += " -> ";
2166 path += t->name ();
2169 candidates += string_printf ("\n '%s %s::%s' (%s)",
2170 TYPE_SAFE_NAME (field_type),
2171 TYPE_SAFE_NAME (struct_type),
2172 name,
2173 path.c_str ());
2176 error (_("Request for member '%s' is ambiguous in type '%s'."
2177 " Candidates are:%s"),
2178 name, TYPE_SAFE_NAME (type),
2179 candidates.c_str ());
2182 else
2183 return searcher.baseclass ();
2186 /* Helper function used by value_struct_elt to recurse through
2187 baseclasses. Look for a field NAME in ARG1. Adjust the address of
2188 ARG1 by OFFSET bytes, and search in it assuming it has (class) type
2189 TYPE.
2191 ARGS is an optional array of argument values used to help finding NAME.
2192 The contents of ARGS can be adjusted if type coercion is required in
2193 order to find a matching NAME.
2195 If found, return value, else if name matched and args not return
2196 (value) -1, else return NULL. */
2198 static struct value *
2199 search_struct_method (const char *name, struct value **arg1p,
2200 gdb::optional<gdb::array_view<value *>> args,
2201 LONGEST offset, int *static_memfuncp,
2202 struct type *type)
2204 int i;
2205 struct value *v;
2206 int name_matched = 0;
2208 type = check_typedef (type);
2209 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2211 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2213 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2215 int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2216 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2218 name_matched = 1;
2219 check_stub_method_group (type, i);
2220 if (j > 0 && !args.has_value ())
2221 error (_("cannot resolve overloaded method "
2222 "`%s': no arguments supplied"), name);
2223 else if (j == 0 && !args.has_value ())
2225 v = value_fn_field (arg1p, f, j, type, offset);
2226 if (v != NULL)
2227 return v;
2229 else
2230 while (j >= 0)
2232 gdb_assert (args.has_value ());
2233 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2234 TYPE_FN_FIELD_TYPE (f, j)->has_varargs (),
2235 TYPE_FN_FIELD_TYPE (f, j)->num_fields (),
2236 TYPE_FN_FIELD_ARGS (f, j), *args))
2238 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2239 return value_virtual_fn_field (arg1p, f, j,
2240 type, offset);
2241 if (TYPE_FN_FIELD_STATIC_P (f, j)
2242 && static_memfuncp)
2243 *static_memfuncp = 1;
2244 v = value_fn_field (arg1p, f, j, type, offset);
2245 if (v != NULL)
2246 return v;
2248 j--;
2253 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2255 LONGEST base_offset;
2256 LONGEST this_offset;
2258 if (BASETYPE_VIA_VIRTUAL (type, i))
2260 struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2261 struct value *base_val;
2262 const gdb_byte *base_valaddr;
2264 /* The virtual base class pointer might have been
2265 clobbered by the user program. Make sure that it
2266 still points to a valid memory location. */
2268 if (offset < 0 || offset >= type->length ())
2270 CORE_ADDR address;
2272 gdb::byte_vector tmp (baseclass->length ());
2273 address = value_address (*arg1p);
2275 if (target_read_memory (address + offset,
2276 tmp.data (), baseclass->length ()) != 0)
2277 error (_("virtual baseclass botch"));
2279 base_val = value_from_contents_and_address (baseclass,
2280 tmp.data (),
2281 address + offset);
2282 base_valaddr = value_contents_for_printing (base_val).data ();
2283 this_offset = 0;
2285 else
2287 base_val = *arg1p;
2288 base_valaddr = value_contents_for_printing (*arg1p).data ();
2289 this_offset = offset;
2292 base_offset = baseclass_offset (type, i, base_valaddr,
2293 this_offset, value_address (base_val),
2294 base_val);
2296 else
2298 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2300 v = search_struct_method (name, arg1p, args, base_offset + offset,
2301 static_memfuncp, TYPE_BASECLASS (type, i));
2302 if (v == (struct value *) - 1)
2304 name_matched = 1;
2306 else if (v)
2308 /* FIXME-bothner: Why is this commented out? Why is it here? */
2309 /* *arg1p = arg1_tmp; */
2310 return v;
2313 if (name_matched)
2314 return (struct value *) - 1;
2315 else
2316 return NULL;
2319 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2320 extract the component named NAME from the ultimate target
2321 structure/union and return it as a value with its appropriate type.
2322 ERR is used in the error message if *ARGP's type is wrong.
2324 C++: ARGS is a list of argument types to aid in the selection of
2325 an appropriate method. Also, handle derived types.
2327 STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2328 where the truthvalue of whether the function that was resolved was
2329 a static member function or not is stored.
2331 ERR is an error message to be printed in case the field is not
2332 found. */
2334 struct value *
2335 value_struct_elt (struct value **argp,
2336 gdb::optional<gdb::array_view<value *>> args,
2337 const char *name, int *static_memfuncp, const char *err)
2339 struct type *t;
2340 struct value *v;
2342 *argp = coerce_array (*argp);
2344 t = check_typedef (value_type (*argp));
2346 /* Follow pointers until we get to a non-pointer. */
2348 while (t->is_pointer_or_reference ())
2350 *argp = value_ind (*argp);
2351 /* Don't coerce fn pointer to fn and then back again! */
2352 if (check_typedef (value_type (*argp))->code () != TYPE_CODE_FUNC)
2353 *argp = coerce_array (*argp);
2354 t = check_typedef (value_type (*argp));
2357 if (t->code () != TYPE_CODE_STRUCT
2358 && t->code () != TYPE_CODE_UNION)
2359 error (_("Attempt to extract a component of a value that is not a %s."),
2360 err);
2362 /* Assume it's not, unless we see that it is. */
2363 if (static_memfuncp)
2364 *static_memfuncp = 0;
2366 if (!args.has_value ())
2368 /* if there are no arguments ...do this... */
2370 /* Try as a field first, because if we succeed, there is less
2371 work to be done. */
2372 v = search_struct_field (name, *argp, t, 0);
2373 if (v)
2374 return v;
2376 if (current_language->la_language == language_fortran)
2378 /* If it is not a field it is the type name of an inherited
2379 structure. */
2380 v = search_struct_field (name, *argp, t, 1);
2381 if (v)
2382 return v;
2385 /* C++: If it was not found as a data field, then try to
2386 return it as a pointer to a method. */
2387 v = search_struct_method (name, argp, args, 0,
2388 static_memfuncp, t);
2390 if (v == (struct value *) - 1)
2391 error (_("Cannot take address of method %s."), name);
2392 else if (v == 0)
2394 if (TYPE_NFN_FIELDS (t))
2395 error (_("There is no member or method named %s."), name);
2396 else
2397 error (_("There is no member named %s."), name);
2399 return v;
2402 v = search_struct_method (name, argp, args, 0,
2403 static_memfuncp, t);
2405 if (v == (struct value *) - 1)
2407 error (_("One of the arguments you tried to pass to %s could not "
2408 "be converted to what the function wants."), name);
2410 else if (v == 0)
2412 /* See if user tried to invoke data as function. If so, hand it
2413 back. If it's not callable (i.e., a pointer to function),
2414 gdb should give an error. */
2415 v = search_struct_field (name, *argp, t, 0);
2416 /* If we found an ordinary field, then it is not a method call.
2417 So, treat it as if it were a static member function. */
2418 if (v && static_memfuncp)
2419 *static_memfuncp = 1;
2422 if (!v)
2423 throw_error (NOT_FOUND_ERROR,
2424 _("Structure has no component named %s."), name);
2425 return v;
2428 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2429 to a structure or union, extract and return its component (field) of
2430 type FTYPE at the specified BITPOS.
2431 Throw an exception on error. */
2433 struct value *
2434 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2435 const char *err)
2437 struct type *t;
2438 int i;
2440 *argp = coerce_array (*argp);
2442 t = check_typedef (value_type (*argp));
2444 while (t->is_pointer_or_reference ())
2446 *argp = value_ind (*argp);
2447 if (check_typedef (value_type (*argp))->code () != TYPE_CODE_FUNC)
2448 *argp = coerce_array (*argp);
2449 t = check_typedef (value_type (*argp));
2452 if (t->code () != TYPE_CODE_STRUCT
2453 && t->code () != TYPE_CODE_UNION)
2454 error (_("Attempt to extract a component of a value that is not a %s."),
2455 err);
2457 for (i = TYPE_N_BASECLASSES (t); i < t->num_fields (); i++)
2459 if (!field_is_static (&t->field (i))
2460 && bitpos == t->field (i).loc_bitpos ()
2461 && types_equal (ftype, t->field (i).type ()))
2462 return value_primitive_field (*argp, 0, i, t);
2465 error (_("No field with matching bitpos and type."));
2467 /* Never hit. */
2468 return NULL;
2471 /* Search through the methods of an object (and its bases) to find a
2472 specified method. Return a reference to the fn_field list METHODS of
2473 overloaded instances defined in the source language. If available
2474 and matching, a vector of matching xmethods defined in extension
2475 languages are also returned in XMETHODS.
2477 Helper function for value_find_oload_list.
2478 ARGP is a pointer to a pointer to a value (the object).
2479 METHOD is a string containing the method name.
2480 OFFSET is the offset within the value.
2481 TYPE is the assumed type of the object.
2482 METHODS is a pointer to the matching overloaded instances defined
2483 in the source language. Since this is a recursive function,
2484 *METHODS should be set to NULL when calling this function.
2485 NUM_FNS is the number of overloaded instances. *NUM_FNS should be set to
2486 0 when calling this function.
2487 XMETHODS is the vector of matching xmethod workers. *XMETHODS
2488 should also be set to NULL when calling this function.
2489 BASETYPE is set to the actual type of the subobject where the
2490 method is found.
2491 BOFFSET is the offset of the base subobject where the method is found. */
2493 static void
2494 find_method_list (struct value **argp, const char *method,
2495 LONGEST offset, struct type *type,
2496 gdb::array_view<fn_field> *methods,
2497 std::vector<xmethod_worker_up> *xmethods,
2498 struct type **basetype, LONGEST *boffset)
2500 int i;
2501 struct fn_field *f = NULL;
2503 gdb_assert (methods != NULL && xmethods != NULL);
2504 type = check_typedef (type);
2506 /* First check in object itself.
2507 This function is called recursively to search through base classes.
2508 If there is a source method match found at some stage, then we need not
2509 look for source methods in consequent recursive calls. */
2510 if (methods->empty ())
2512 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2514 /* pai: FIXME What about operators and type conversions? */
2515 const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2517 if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2519 int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2520 f = TYPE_FN_FIELDLIST1 (type, i);
2521 *methods = gdb::make_array_view (f, len);
2523 *basetype = type;
2524 *boffset = offset;
2526 /* Resolve any stub methods. */
2527 check_stub_method_group (type, i);
2529 break;
2534 /* Unlike source methods, xmethods can be accumulated over successive
2535 recursive calls. In other words, an xmethod named 'm' in a class
2536 will not hide an xmethod named 'm' in its base class(es). We want
2537 it to be this way because xmethods are after all convenience functions
2538 and hence there is no point restricting them with something like method
2539 hiding. Moreover, if hiding is done for xmethods as well, then we will
2540 have to provide a mechanism to un-hide (like the 'using' construct). */
2541 get_matching_xmethod_workers (type, method, xmethods);
2543 /* If source methods are not found in current class, look for them in the
2544 base classes. We also have to go through the base classes to gather
2545 extension methods. */
2546 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2548 LONGEST base_offset;
2550 if (BASETYPE_VIA_VIRTUAL (type, i))
2552 base_offset = baseclass_offset (type, i,
2553 value_contents_for_printing (*argp).data (),
2554 value_offset (*argp) + offset,
2555 value_address (*argp), *argp);
2557 else /* Non-virtual base, simply use bit position from debug
2558 info. */
2560 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2563 find_method_list (argp, method, base_offset + offset,
2564 TYPE_BASECLASS (type, i), methods,
2565 xmethods, basetype, boffset);
2569 /* Return the list of overloaded methods of a specified name. The methods
2570 could be those GDB finds in the binary, or xmethod. Methods found in
2571 the binary are returned in METHODS, and xmethods are returned in
2572 XMETHODS.
2574 ARGP is a pointer to a pointer to a value (the object).
2575 METHOD is the method name.
2576 OFFSET is the offset within the value contents.
2577 METHODS is the list of matching overloaded instances defined in
2578 the source language.
2579 XMETHODS is the vector of matching xmethod workers defined in
2580 extension languages.
2581 BASETYPE is set to the type of the base subobject that defines the
2582 method.
2583 BOFFSET is the offset of the base subobject which defines the method. */
2585 static void
2586 value_find_oload_method_list (struct value **argp, const char *method,
2587 LONGEST offset,
2588 gdb::array_view<fn_field> *methods,
2589 std::vector<xmethod_worker_up> *xmethods,
2590 struct type **basetype, LONGEST *boffset)
2592 struct type *t;
2594 t = check_typedef (value_type (*argp));
2596 /* Code snarfed from value_struct_elt. */
2597 while (t->is_pointer_or_reference ())
2599 *argp = value_ind (*argp);
2600 /* Don't coerce fn pointer to fn and then back again! */
2601 if (check_typedef (value_type (*argp))->code () != TYPE_CODE_FUNC)
2602 *argp = coerce_array (*argp);
2603 t = check_typedef (value_type (*argp));
2606 if (t->code () != TYPE_CODE_STRUCT
2607 && t->code () != TYPE_CODE_UNION)
2608 error (_("Attempt to extract a component of a "
2609 "value that is not a struct or union"));
2611 gdb_assert (methods != NULL && xmethods != NULL);
2613 /* Clear the lists. */
2614 *methods = {};
2615 xmethods->clear ();
2617 find_method_list (argp, method, 0, t, methods, xmethods,
2618 basetype, boffset);
2621 /* Helper function for find_overload_match. If no matches were
2622 found, this function may generate a hint for the user that some
2623 of the relevant types are incomplete, so GDB can't evaluate
2624 type relationships to properly evaluate overloads.
2626 If no incomplete types are present, an empty string is returned. */
2627 static std::string
2628 incomplete_type_hint (gdb::array_view<value *> args)
2630 int incomplete_types = 0;
2631 std::string incomplete_arg_names;
2632 for (const struct value *arg : args)
2634 struct type *t = value_type (arg);
2635 while (t->code () == TYPE_CODE_PTR)
2636 t = t->target_type ();
2637 if (t->is_stub ())
2639 string_file buffer;
2640 if (incomplete_types > 0)
2641 incomplete_arg_names += ", ";
2643 current_language->print_type (value_type (arg), "", &buffer,
2644 -1, 0, &type_print_raw_options);
2646 incomplete_types++;
2647 incomplete_arg_names += buffer.string ();
2650 std::string hint;
2651 if (incomplete_types > 1)
2652 hint = string_printf (_("\nThe types: '%s' aren't fully known to GDB."
2653 " Please cast them directly to the desired"
2654 " typed in the function call."),
2655 incomplete_arg_names.c_str ());
2656 else if (incomplete_types == 1)
2657 hint = string_printf (_("\nThe type: '%s' isn't fully known to GDB."
2658 " Please cast it directly to the desired"
2659 " typed in the function call."),
2660 incomplete_arg_names.c_str ());
2661 return hint;
2664 /* Given an array of arguments (ARGS) (which includes an entry for
2665 "this" in the case of C++ methods), the NAME of a function, and
2666 whether it's a method or not (METHOD), find the best function that
2667 matches on the argument types according to the overload resolution
2668 rules.
2670 METHOD can be one of three values:
2671 NON_METHOD for non-member functions.
2672 METHOD: for member functions.
2673 BOTH: used for overload resolution of operators where the
2674 candidates are expected to be either member or non member
2675 functions. In this case the first argument ARGTYPES
2676 (representing 'this') is expected to be a reference to the
2677 target object, and will be dereferenced when attempting the
2678 non-member search.
2680 In the case of class methods, the parameter OBJ is an object value
2681 in which to search for overloaded methods.
2683 In the case of non-method functions, the parameter FSYM is a symbol
2684 corresponding to one of the overloaded functions.
2686 Return value is an integer: 0 -> good match, 10 -> debugger applied
2687 non-standard coercions, 100 -> incompatible.
2689 If a method is being searched for, VALP will hold the value.
2690 If a non-method is being searched for, SYMP will hold the symbol
2691 for it.
2693 If a method is being searched for, and it is a static method,
2694 then STATICP will point to a non-zero value.
2696 If NO_ADL argument dependent lookup is disabled. This is used to prevent
2697 ADL overload candidates when performing overload resolution for a fully
2698 qualified name.
2700 If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2701 read while picking the best overload match (it may be all zeroes and thus
2702 not have a vtable pointer), in which case skip virtual function lookup.
2703 This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2704 the result type.
2706 Note: This function does *not* check the value of
2707 overload_resolution. Caller must check it to see whether overload
2708 resolution is permitted. */
2711 find_overload_match (gdb::array_view<value *> args,
2712 const char *name, enum oload_search_type method,
2713 struct value **objp, struct symbol *fsym,
2714 struct value **valp, struct symbol **symp,
2715 int *staticp, const int no_adl,
2716 const enum noside noside)
2718 struct value *obj = (objp ? *objp : NULL);
2719 struct type *obj_type = obj ? value_type (obj) : NULL;
2720 /* Index of best overloaded function. */
2721 int func_oload_champ = -1;
2722 int method_oload_champ = -1;
2723 int src_method_oload_champ = -1;
2724 int ext_method_oload_champ = -1;
2726 /* The measure for the current best match. */
2727 badness_vector method_badness;
2728 badness_vector func_badness;
2729 badness_vector ext_method_badness;
2730 badness_vector src_method_badness;
2732 struct value *temp = obj;
2733 /* For methods, the list of overloaded methods. */
2734 gdb::array_view<fn_field> methods;
2735 /* For non-methods, the list of overloaded function symbols. */
2736 std::vector<symbol *> functions;
2737 /* For xmethods, the vector of xmethod workers. */
2738 std::vector<xmethod_worker_up> xmethods;
2739 struct type *basetype = NULL;
2740 LONGEST boffset;
2742 const char *obj_type_name = NULL;
2743 const char *func_name = NULL;
2744 gdb::unique_xmalloc_ptr<char> temp_func;
2745 enum oload_classification match_quality;
2746 enum oload_classification method_match_quality = INCOMPATIBLE;
2747 enum oload_classification src_method_match_quality = INCOMPATIBLE;
2748 enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2749 enum oload_classification func_match_quality = INCOMPATIBLE;
2751 /* Get the list of overloaded methods or functions. */
2752 if (method == METHOD || method == BOTH)
2754 gdb_assert (obj);
2756 /* OBJ may be a pointer value rather than the object itself. */
2757 obj = coerce_ref (obj);
2758 while (check_typedef (value_type (obj))->code () == TYPE_CODE_PTR)
2759 obj = coerce_ref (value_ind (obj));
2760 obj_type_name = value_type (obj)->name ();
2762 /* First check whether this is a data member, e.g. a pointer to
2763 a function. */
2764 if (check_typedef (value_type (obj))->code () == TYPE_CODE_STRUCT)
2766 *valp = search_struct_field (name, obj,
2767 check_typedef (value_type (obj)), 0);
2768 if (*valp)
2770 *staticp = 1;
2771 return 0;
2775 /* Retrieve the list of methods with the name NAME. */
2776 value_find_oload_method_list (&temp, name, 0, &methods,
2777 &xmethods, &basetype, &boffset);
2778 /* If this is a method only search, and no methods were found
2779 the search has failed. */
2780 if (method == METHOD && methods.empty () && xmethods.empty ())
2781 error (_("Couldn't find method %s%s%s"),
2782 obj_type_name,
2783 (obj_type_name && *obj_type_name) ? "::" : "",
2784 name);
2785 /* If we are dealing with stub method types, they should have
2786 been resolved by find_method_list via
2787 value_find_oload_method_list above. */
2788 if (!methods.empty ())
2790 gdb_assert (TYPE_SELF_TYPE (methods[0].type) != NULL);
2792 src_method_oload_champ
2793 = find_oload_champ (args,
2794 methods.size (),
2795 methods.data (), NULL, NULL,
2796 &src_method_badness);
2798 src_method_match_quality = classify_oload_match
2799 (src_method_badness, args.size (),
2800 oload_method_static_p (methods.data (), src_method_oload_champ));
2803 if (!xmethods.empty ())
2805 ext_method_oload_champ
2806 = find_oload_champ (args,
2807 xmethods.size (),
2808 NULL, xmethods.data (), NULL,
2809 &ext_method_badness);
2810 ext_method_match_quality = classify_oload_match (ext_method_badness,
2811 args.size (), 0);
2814 if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2816 switch (compare_badness (ext_method_badness, src_method_badness))
2818 case 0: /* Src method and xmethod are equally good. */
2819 /* If src method and xmethod are equally good, then
2820 xmethod should be the winner. Hence, fall through to the
2821 case where a xmethod is better than the source
2822 method, except when the xmethod match quality is
2823 non-standard. */
2824 /* FALLTHROUGH */
2825 case 1: /* Src method and ext method are incompatible. */
2826 /* If ext method match is not standard, then let source method
2827 win. Otherwise, fallthrough to let xmethod win. */
2828 if (ext_method_match_quality != STANDARD)
2830 method_oload_champ = src_method_oload_champ;
2831 method_badness = src_method_badness;
2832 ext_method_oload_champ = -1;
2833 method_match_quality = src_method_match_quality;
2834 break;
2836 /* FALLTHROUGH */
2837 case 2: /* Ext method is champion. */
2838 method_oload_champ = ext_method_oload_champ;
2839 method_badness = ext_method_badness;
2840 src_method_oload_champ = -1;
2841 method_match_quality = ext_method_match_quality;
2842 break;
2843 case 3: /* Src method is champion. */
2844 method_oload_champ = src_method_oload_champ;
2845 method_badness = src_method_badness;
2846 ext_method_oload_champ = -1;
2847 method_match_quality = src_method_match_quality;
2848 break;
2849 default:
2850 gdb_assert_not_reached ("Unexpected overload comparison "
2851 "result");
2852 break;
2855 else if (src_method_oload_champ >= 0)
2857 method_oload_champ = src_method_oload_champ;
2858 method_badness = src_method_badness;
2859 method_match_quality = src_method_match_quality;
2861 else if (ext_method_oload_champ >= 0)
2863 method_oload_champ = ext_method_oload_champ;
2864 method_badness = ext_method_badness;
2865 method_match_quality = ext_method_match_quality;
2869 if (method == NON_METHOD || method == BOTH)
2871 const char *qualified_name = NULL;
2873 /* If the overload match is being search for both as a method
2874 and non member function, the first argument must now be
2875 dereferenced. */
2876 if (method == BOTH)
2877 args[0] = value_ind (args[0]);
2879 if (fsym)
2881 qualified_name = fsym->natural_name ();
2883 /* If we have a function with a C++ name, try to extract just
2884 the function part. Do not try this for non-functions (e.g.
2885 function pointers). */
2886 if (qualified_name
2887 && (check_typedef (fsym->type ())->code ()
2888 == TYPE_CODE_FUNC))
2890 temp_func = cp_func_name (qualified_name);
2892 /* If cp_func_name did not remove anything, the name of the
2893 symbol did not include scope or argument types - it was
2894 probably a C-style function. */
2895 if (temp_func != nullptr)
2897 if (strcmp (temp_func.get (), qualified_name) == 0)
2898 func_name = NULL;
2899 else
2900 func_name = temp_func.get ();
2904 else
2906 func_name = name;
2907 qualified_name = name;
2910 /* If there was no C++ name, this must be a C-style function or
2911 not a function at all. Just return the same symbol. Do the
2912 same if cp_func_name fails for some reason. */
2913 if (func_name == NULL)
2915 *symp = fsym;
2916 return 0;
2919 func_oload_champ = find_oload_champ_namespace (args,
2920 func_name,
2921 qualified_name,
2922 &functions,
2923 &func_badness,
2924 no_adl);
2926 if (func_oload_champ >= 0)
2927 func_match_quality = classify_oload_match (func_badness,
2928 args.size (), 0);
2931 /* Did we find a match ? */
2932 if (method_oload_champ == -1 && func_oload_champ == -1)
2933 throw_error (NOT_FOUND_ERROR,
2934 _("No symbol \"%s\" in current context."),
2935 name);
2937 /* If we have found both a method match and a function
2938 match, find out which one is better, and calculate match
2939 quality. */
2940 if (method_oload_champ >= 0 && func_oload_champ >= 0)
2942 switch (compare_badness (func_badness, method_badness))
2944 case 0: /* Top two contenders are equally good. */
2945 /* FIXME: GDB does not support the general ambiguous case.
2946 All candidates should be collected and presented the
2947 user. */
2948 error (_("Ambiguous overload resolution"));
2949 break;
2950 case 1: /* Incomparable top contenders. */
2951 /* This is an error incompatible candidates
2952 should not have been proposed. */
2953 error (_("Internal error: incompatible "
2954 "overload candidates proposed"));
2955 break;
2956 case 2: /* Function champion. */
2957 method_oload_champ = -1;
2958 match_quality = func_match_quality;
2959 break;
2960 case 3: /* Method champion. */
2961 func_oload_champ = -1;
2962 match_quality = method_match_quality;
2963 break;
2964 default:
2965 error (_("Internal error: unexpected overload comparison result"));
2966 break;
2969 else
2971 /* We have either a method match or a function match. */
2972 if (method_oload_champ >= 0)
2973 match_quality = method_match_quality;
2974 else
2975 match_quality = func_match_quality;
2978 if (match_quality == INCOMPATIBLE)
2980 std::string hint = incomplete_type_hint (args);
2981 if (method == METHOD)
2982 error (_("Cannot resolve method %s%s%s to any overloaded instance%s"),
2983 obj_type_name,
2984 (obj_type_name && *obj_type_name) ? "::" : "",
2985 name, hint.c_str ());
2986 else
2987 error (_("Cannot resolve function %s to any overloaded instance%s"),
2988 func_name, hint.c_str ());
2990 else if (match_quality == NON_STANDARD)
2992 if (method == METHOD)
2993 warning (_("Using non-standard conversion to match "
2994 "method %s%s%s to supplied arguments"),
2995 obj_type_name,
2996 (obj_type_name && *obj_type_name) ? "::" : "",
2997 name);
2998 else
2999 warning (_("Using non-standard conversion to match "
3000 "function %s to supplied arguments"),
3001 func_name);
3004 if (staticp != NULL)
3005 *staticp = oload_method_static_p (methods.data (), method_oload_champ);
3007 if (method_oload_champ >= 0)
3009 if (src_method_oload_champ >= 0)
3011 if (TYPE_FN_FIELD_VIRTUAL_P (methods, method_oload_champ)
3012 && noside != EVAL_AVOID_SIDE_EFFECTS)
3014 *valp = value_virtual_fn_field (&temp, methods.data (),
3015 method_oload_champ, basetype,
3016 boffset);
3018 else
3019 *valp = value_fn_field (&temp, methods.data (),
3020 method_oload_champ, basetype, boffset);
3022 else
3023 *valp = value_from_xmethod
3024 (std::move (xmethods[ext_method_oload_champ]));
3026 else
3027 *symp = functions[func_oload_champ];
3029 if (objp)
3031 struct type *temp_type = check_typedef (value_type (temp));
3032 struct type *objtype = check_typedef (obj_type);
3034 if (temp_type->code () != TYPE_CODE_PTR
3035 && objtype->is_pointer_or_reference ())
3037 temp = value_addr (temp);
3039 *objp = temp;
3042 switch (match_quality)
3044 case INCOMPATIBLE:
3045 return 100;
3046 case NON_STANDARD:
3047 return 10;
3048 default: /* STANDARD */
3049 return 0;
3053 /* Find the best overload match, searching for FUNC_NAME in namespaces
3054 contained in QUALIFIED_NAME until it either finds a good match or
3055 runs out of namespaces. It stores the overloaded functions in
3056 *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV. If NO_ADL,
3057 argument dependent lookup is not performed. */
3059 static int
3060 find_oload_champ_namespace (gdb::array_view<value *> args,
3061 const char *func_name,
3062 const char *qualified_name,
3063 std::vector<symbol *> *oload_syms,
3064 badness_vector *oload_champ_bv,
3065 const int no_adl)
3067 int oload_champ;
3069 find_oload_champ_namespace_loop (args,
3070 func_name,
3071 qualified_name, 0,
3072 oload_syms, oload_champ_bv,
3073 &oload_champ,
3074 no_adl);
3076 return oload_champ;
3079 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
3080 how deep we've looked for namespaces, and the champ is stored in
3081 OLOAD_CHAMP. The return value is 1 if the champ is a good one, 0
3082 if it isn't. Other arguments are the same as in
3083 find_oload_champ_namespace. */
3085 static int
3086 find_oload_champ_namespace_loop (gdb::array_view<value *> args,
3087 const char *func_name,
3088 const char *qualified_name,
3089 int namespace_len,
3090 std::vector<symbol *> *oload_syms,
3091 badness_vector *oload_champ_bv,
3092 int *oload_champ,
3093 const int no_adl)
3095 int next_namespace_len = namespace_len;
3096 int searched_deeper = 0;
3097 int new_oload_champ;
3098 char *new_namespace;
3100 if (next_namespace_len != 0)
3102 gdb_assert (qualified_name[next_namespace_len] == ':');
3103 next_namespace_len += 2;
3105 next_namespace_len +=
3106 cp_find_first_component (qualified_name + next_namespace_len);
3108 /* First, see if we have a deeper namespace we can search in.
3109 If we get a good match there, use it. */
3111 if (qualified_name[next_namespace_len] == ':')
3113 searched_deeper = 1;
3115 if (find_oload_champ_namespace_loop (args,
3116 func_name, qualified_name,
3117 next_namespace_len,
3118 oload_syms, oload_champ_bv,
3119 oload_champ, no_adl))
3121 return 1;
3125 /* If we reach here, either we're in the deepest namespace or we
3126 didn't find a good match in a deeper namespace. But, in the
3127 latter case, we still have a bad match in a deeper namespace;
3128 note that we might not find any match at all in the current
3129 namespace. (There's always a match in the deepest namespace,
3130 because this overload mechanism only gets called if there's a
3131 function symbol to start off with.) */
3133 new_namespace = (char *) alloca (namespace_len + 1);
3134 strncpy (new_namespace, qualified_name, namespace_len);
3135 new_namespace[namespace_len] = '\0';
3137 std::vector<symbol *> new_oload_syms
3138 = make_symbol_overload_list (func_name, new_namespace);
3140 /* If we have reached the deepest level perform argument
3141 determined lookup. */
3142 if (!searched_deeper && !no_adl)
3144 int ix;
3145 struct type **arg_types;
3147 /* Prepare list of argument types for overload resolution. */
3148 arg_types = (struct type **)
3149 alloca (args.size () * (sizeof (struct type *)));
3150 for (ix = 0; ix < args.size (); ix++)
3151 arg_types[ix] = value_type (args[ix]);
3152 add_symbol_overload_list_adl ({arg_types, args.size ()}, func_name,
3153 &new_oload_syms);
3156 badness_vector new_oload_champ_bv;
3157 new_oload_champ = find_oload_champ (args,
3158 new_oload_syms.size (),
3159 NULL, NULL, new_oload_syms.data (),
3160 &new_oload_champ_bv);
3162 /* Case 1: We found a good match. Free earlier matches (if any),
3163 and return it. Case 2: We didn't find a good match, but we're
3164 not the deepest function. Then go with the bad match that the
3165 deeper function found. Case 3: We found a bad match, and we're
3166 the deepest function. Then return what we found, even though
3167 it's a bad match. */
3169 if (new_oload_champ != -1
3170 && classify_oload_match (new_oload_champ_bv, args.size (), 0) == STANDARD)
3172 *oload_syms = std::move (new_oload_syms);
3173 *oload_champ = new_oload_champ;
3174 *oload_champ_bv = std::move (new_oload_champ_bv);
3175 return 1;
3177 else if (searched_deeper)
3179 return 0;
3181 else
3183 *oload_syms = std::move (new_oload_syms);
3184 *oload_champ = new_oload_champ;
3185 *oload_champ_bv = std::move (new_oload_champ_bv);
3186 return 0;
3190 /* Look for a function to take ARGS. Find the best match from among
3191 the overloaded methods or functions given by METHODS or FUNCTIONS
3192 or XMETHODS, respectively. One, and only one of METHODS, FUNCTIONS
3193 and XMETHODS can be non-NULL.
3195 NUM_FNS is the length of the array pointed at by METHODS, FUNCTIONS
3196 or XMETHODS, whichever is non-NULL.
3198 Return the index of the best match; store an indication of the
3199 quality of the match in OLOAD_CHAMP_BV. */
3201 static int
3202 find_oload_champ (gdb::array_view<value *> args,
3203 size_t num_fns,
3204 fn_field *methods,
3205 xmethod_worker_up *xmethods,
3206 symbol **functions,
3207 badness_vector *oload_champ_bv)
3209 /* A measure of how good an overloaded instance is. */
3210 badness_vector bv;
3211 /* Index of best overloaded function. */
3212 int oload_champ = -1;
3213 /* Current ambiguity state for overload resolution. */
3214 int oload_ambiguous = 0;
3215 /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs. */
3217 /* A champion can be found among methods alone, or among functions
3218 alone, or in xmethods alone, but not in more than one of these
3219 groups. */
3220 gdb_assert ((methods != NULL) + (functions != NULL) + (xmethods != NULL)
3221 == 1);
3223 /* Consider each candidate in turn. */
3224 for (size_t ix = 0; ix < num_fns; ix++)
3226 int jj;
3227 int static_offset = 0;
3228 std::vector<type *> parm_types;
3230 if (xmethods != NULL)
3231 parm_types = xmethods[ix]->get_arg_types ();
3232 else
3234 size_t nparms;
3236 if (methods != NULL)
3238 nparms = TYPE_FN_FIELD_TYPE (methods, ix)->num_fields ();
3239 static_offset = oload_method_static_p (methods, ix);
3241 else
3242 nparms = functions[ix]->type ()->num_fields ();
3244 parm_types.reserve (nparms);
3245 for (jj = 0; jj < nparms; jj++)
3247 type *t = (methods != NULL
3248 ? (TYPE_FN_FIELD_ARGS (methods, ix)[jj].type ())
3249 : functions[ix]->type ()->field (jj).type ());
3250 parm_types.push_back (t);
3254 /* Compare parameter types to supplied argument types. Skip
3255 THIS for static methods. */
3256 bv = rank_function (parm_types,
3257 args.slice (static_offset));
3259 if (overload_debug)
3261 if (methods != NULL)
3262 gdb_printf (gdb_stderr,
3263 "Overloaded method instance %s, # of parms %d\n",
3264 methods[ix].physname, (int) parm_types.size ());
3265 else if (xmethods != NULL)
3266 gdb_printf (gdb_stderr,
3267 "Xmethod worker, # of parms %d\n",
3268 (int) parm_types.size ());
3269 else
3270 gdb_printf (gdb_stderr,
3271 "Overloaded function instance "
3272 "%s # of parms %d\n",
3273 functions[ix]->demangled_name (),
3274 (int) parm_types.size ());
3276 gdb_printf (gdb_stderr,
3277 "...Badness of length : {%d, %d}\n",
3278 bv[0].rank, bv[0].subrank);
3280 for (jj = 1; jj < bv.size (); jj++)
3281 gdb_printf (gdb_stderr,
3282 "...Badness of arg %d : {%d, %d}\n",
3283 jj, bv[jj].rank, bv[jj].subrank);
3286 if (oload_champ_bv->empty ())
3288 *oload_champ_bv = std::move (bv);
3289 oload_champ = 0;
3291 else /* See whether current candidate is better or worse than
3292 previous best. */
3293 switch (compare_badness (bv, *oload_champ_bv))
3295 case 0: /* Top two contenders are equally good. */
3296 oload_ambiguous = 1;
3297 break;
3298 case 1: /* Incomparable top contenders. */
3299 oload_ambiguous = 2;
3300 break;
3301 case 2: /* New champion, record details. */
3302 *oload_champ_bv = std::move (bv);
3303 oload_ambiguous = 0;
3304 oload_champ = ix;
3305 break;
3306 case 3:
3307 default:
3308 break;
3310 if (overload_debug)
3311 gdb_printf (gdb_stderr, "Overload resolution "
3312 "champion is %d, ambiguous? %d\n",
3313 oload_champ, oload_ambiguous);
3316 return oload_champ;
3319 /* Return 1 if we're looking at a static method, 0 if we're looking at
3320 a non-static method or a function that isn't a method. */
3322 static int
3323 oload_method_static_p (struct fn_field *fns_ptr, int index)
3325 if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3326 return 1;
3327 else
3328 return 0;
3331 /* Check how good an overload match OLOAD_CHAMP_BV represents. */
3333 static enum oload_classification
3334 classify_oload_match (const badness_vector &oload_champ_bv,
3335 int nargs,
3336 int static_offset)
3338 int ix;
3339 enum oload_classification worst = STANDARD;
3341 for (ix = 1; ix <= nargs - static_offset; ix++)
3343 /* If this conversion is as bad as INCOMPATIBLE_TYPE_BADNESS
3344 or worse return INCOMPATIBLE. */
3345 if (compare_ranks (oload_champ_bv[ix],
3346 INCOMPATIBLE_TYPE_BADNESS) <= 0)
3347 return INCOMPATIBLE; /* Truly mismatched types. */
3348 /* Otherwise If this conversion is as bad as
3349 NS_POINTER_CONVERSION_BADNESS or worse return NON_STANDARD. */
3350 else if (compare_ranks (oload_champ_bv[ix],
3351 NS_POINTER_CONVERSION_BADNESS) <= 0)
3352 worst = NON_STANDARD; /* Non-standard type conversions
3353 needed. */
3356 /* If no INCOMPATIBLE classification was found, return the worst one
3357 that was found (if any). */
3358 return worst;
3361 /* C++: return 1 is NAME is a legitimate name for the destructor of
3362 type TYPE. If TYPE does not have a destructor, or if NAME is
3363 inappropriate for TYPE, an error is signaled. Parameter TYPE should not yet
3364 have CHECK_TYPEDEF applied, this function will apply it itself. */
3367 destructor_name_p (const char *name, struct type *type)
3369 if (name[0] == '~')
3371 const char *dname = type_name_or_error (type);
3372 const char *cp = strchr (dname, '<');
3373 unsigned int len;
3375 /* Do not compare the template part for template classes. */
3376 if (cp == NULL)
3377 len = strlen (dname);
3378 else
3379 len = cp - dname;
3380 if (strlen (name + 1) != len || strncmp (dname, name + 1, len) != 0)
3381 error (_("name of destructor must equal name of class"));
3382 else
3383 return 1;
3385 return 0;
3388 /* Find an enum constant named NAME in TYPE. TYPE must be an "enum
3389 class". If the name is found, return a value representing it;
3390 otherwise throw an exception. */
3392 static struct value *
3393 enum_constant_from_type (struct type *type, const char *name)
3395 int i;
3396 int name_len = strlen (name);
3398 gdb_assert (type->code () == TYPE_CODE_ENUM
3399 && type->is_declared_class ());
3401 for (i = TYPE_N_BASECLASSES (type); i < type->num_fields (); ++i)
3403 const char *fname = type->field (i).name ();
3404 int len;
3406 if (type->field (i).loc_kind () != FIELD_LOC_KIND_ENUMVAL
3407 || fname == NULL)
3408 continue;
3410 /* Look for the trailing "::NAME", since enum class constant
3411 names are qualified here. */
3412 len = strlen (fname);
3413 if (len + 2 >= name_len
3414 && fname[len - name_len - 2] == ':'
3415 && fname[len - name_len - 1] == ':'
3416 && strcmp (&fname[len - name_len], name) == 0)
3417 return value_from_longest (type, type->field (i).loc_enumval ());
3420 error (_("no constant named \"%s\" in enum \"%s\""),
3421 name, type->name ());
3424 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3425 return the appropriate member (or the address of the member, if
3426 WANT_ADDRESS). This function is used to resolve user expressions
3427 of the form "DOMAIN::NAME". For more details on what happens, see
3428 the comment before value_struct_elt_for_reference. */
3430 struct value *
3431 value_aggregate_elt (struct type *curtype, const char *name,
3432 struct type *expect_type, int want_address,
3433 enum noside noside)
3435 switch (curtype->code ())
3437 case TYPE_CODE_STRUCT:
3438 case TYPE_CODE_UNION:
3439 return value_struct_elt_for_reference (curtype, 0, curtype,
3440 name, expect_type,
3441 want_address, noside);
3442 case TYPE_CODE_NAMESPACE:
3443 return value_namespace_elt (curtype, name,
3444 want_address, noside);
3446 case TYPE_CODE_ENUM:
3447 return enum_constant_from_type (curtype, name);
3449 default:
3450 internal_error (_("non-aggregate type in value_aggregate_elt"));
3454 /* Compares the two method/function types T1 and T2 for "equality"
3455 with respect to the methods' parameters. If the types of the
3456 two parameter lists are the same, returns 1; 0 otherwise. This
3457 comparison may ignore any artificial parameters in T1 if
3458 SKIP_ARTIFICIAL is non-zero. This function will ALWAYS skip
3459 the first artificial parameter in T1, assumed to be a 'this' pointer.
3461 The type T2 is expected to have come from make_params (in eval.c). */
3463 static int
3464 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3466 int start = 0;
3468 if (t1->num_fields () > 0 && TYPE_FIELD_ARTIFICIAL (t1, 0))
3469 ++start;
3471 /* If skipping artificial fields, find the first real field
3472 in T1. */
3473 if (skip_artificial)
3475 while (start < t1->num_fields ()
3476 && TYPE_FIELD_ARTIFICIAL (t1, start))
3477 ++start;
3480 /* Now compare parameters. */
3482 /* Special case: a method taking void. T1 will contain no
3483 non-artificial fields, and T2 will contain TYPE_CODE_VOID. */
3484 if ((t1->num_fields () - start) == 0 && t2->num_fields () == 1
3485 && t2->field (0).type ()->code () == TYPE_CODE_VOID)
3486 return 1;
3488 if ((t1->num_fields () - start) == t2->num_fields ())
3490 int i;
3492 for (i = 0; i < t2->num_fields (); ++i)
3494 if (compare_ranks (rank_one_type (t1->field (start + i).type (),
3495 t2->field (i).type (), NULL),
3496 EXACT_MATCH_BADNESS) != 0)
3497 return 0;
3500 return 1;
3503 return 0;
3506 /* C++: Given an aggregate type VT, and a class type CLS, search
3507 recursively for CLS using value V; If found, store the offset
3508 which is either fetched from the virtual base pointer if CLS
3509 is virtual or accumulated offset of its parent classes if
3510 CLS is non-virtual in *BOFFS, set ISVIRT to indicate if CLS
3511 is virtual, and return true. If not found, return false. */
3513 static bool
3514 get_baseclass_offset (struct type *vt, struct type *cls,
3515 struct value *v, int *boffs, bool *isvirt)
3517 for (int i = 0; i < TYPE_N_BASECLASSES (vt); i++)
3519 struct type *t = vt->field (i).type ();
3520 if (types_equal (t, cls))
3522 if (BASETYPE_VIA_VIRTUAL (vt, i))
3524 const gdb_byte *adr = value_contents_for_printing (v).data ();
3525 *boffs = baseclass_offset (vt, i, adr, value_offset (v),
3526 value_as_long (v), v);
3527 *isvirt = true;
3529 else
3530 *isvirt = false;
3531 return true;
3534 if (get_baseclass_offset (check_typedef (t), cls, v, boffs, isvirt))
3536 if (*isvirt == false) /* Add non-virtual base offset. */
3538 const gdb_byte *adr = value_contents_for_printing (v).data ();
3539 *boffs += baseclass_offset (vt, i, adr, value_offset (v),
3540 value_as_long (v), v);
3542 return true;
3546 return false;
3549 /* C++: Given an aggregate type CURTYPE, and a member name NAME,
3550 return the address of this member as a "pointer to member" type.
3551 If INTYPE is non-null, then it will be the type of the member we
3552 are looking for. This will help us resolve "pointers to member
3553 functions". This function is used to resolve user expressions of
3554 the form "DOMAIN::NAME". */
3556 static struct value *
3557 value_struct_elt_for_reference (struct type *domain, int offset,
3558 struct type *curtype, const char *name,
3559 struct type *intype,
3560 int want_address,
3561 enum noside noside)
3563 struct type *t = check_typedef (curtype);
3564 int i;
3565 struct value *result;
3567 if (t->code () != TYPE_CODE_STRUCT
3568 && t->code () != TYPE_CODE_UNION)
3569 error (_("Internal error: non-aggregate type "
3570 "to value_struct_elt_for_reference"));
3572 for (i = t->num_fields () - 1; i >= TYPE_N_BASECLASSES (t); i--)
3574 const char *t_field_name = t->field (i).name ();
3576 if (t_field_name && strcmp (t_field_name, name) == 0)
3578 if (field_is_static (&t->field (i)))
3580 struct value *v = value_static_field (t, i);
3581 if (want_address)
3582 v = value_addr (v);
3583 return v;
3585 if (TYPE_FIELD_PACKED (t, i))
3586 error (_("pointers to bitfield members not allowed"));
3588 if (want_address)
3589 return value_from_longest
3590 (lookup_memberptr_type (t->field (i).type (), domain),
3591 offset + (LONGEST) (t->field (i).loc_bitpos () >> 3));
3592 else if (noside != EVAL_NORMAL)
3593 return allocate_value (t->field (i).type ());
3594 else
3596 /* Try to evaluate NAME as a qualified name with implicit
3597 this pointer. In this case, attempt to return the
3598 equivalent to `this->*(&TYPE::NAME)'. */
3599 struct value *v = value_of_this_silent (current_language);
3600 if (v != NULL)
3602 struct value *ptr, *this_v = v;
3603 long mem_offset;
3604 struct type *type, *tmp;
3606 ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3607 type = check_typedef (value_type (ptr));
3608 gdb_assert (type != NULL
3609 && type->code () == TYPE_CODE_MEMBERPTR);
3610 tmp = lookup_pointer_type (TYPE_SELF_TYPE (type));
3611 v = value_cast_pointers (tmp, v, 1);
3612 mem_offset = value_as_long (ptr);
3613 if (domain != curtype)
3615 /* Find class offset of type CURTYPE from either its
3616 parent type DOMAIN or the type of implied this. */
3617 int boff = 0;
3618 bool isvirt = false;
3619 if (get_baseclass_offset (domain, curtype, v, &boff,
3620 &isvirt))
3621 mem_offset += boff;
3622 else
3624 struct type *p = check_typedef (value_type (this_v));
3625 p = check_typedef (p->target_type ());
3626 if (get_baseclass_offset (p, curtype, this_v,
3627 &boff, &isvirt))
3628 mem_offset += boff;
3631 tmp = lookup_pointer_type (type->target_type ());
3632 result = value_from_pointer (tmp,
3633 value_as_long (v) + mem_offset);
3634 return value_ind (result);
3637 error (_("Cannot reference non-static field \"%s\""), name);
3642 /* C++: If it was not found as a data field, then try to return it
3643 as a pointer to a method. */
3645 /* Perform all necessary dereferencing. */
3646 while (intype && intype->code () == TYPE_CODE_PTR)
3647 intype = intype->target_type ();
3649 for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3651 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3653 if (t_field_name && strcmp (t_field_name, name) == 0)
3655 int j;
3656 int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3657 struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3659 check_stub_method_group (t, i);
3661 if (intype)
3663 for (j = 0; j < len; ++j)
3665 if (TYPE_CONST (intype) != TYPE_FN_FIELD_CONST (f, j))
3666 continue;
3667 if (TYPE_VOLATILE (intype) != TYPE_FN_FIELD_VOLATILE (f, j))
3668 continue;
3670 if (compare_parameters (TYPE_FN_FIELD_TYPE (f, j), intype, 0)
3671 || compare_parameters (TYPE_FN_FIELD_TYPE (f, j),
3672 intype, 1))
3673 break;
3676 if (j == len)
3677 error (_("no member function matches "
3678 "that type instantiation"));
3680 else
3682 int ii;
3684 j = -1;
3685 for (ii = 0; ii < len; ++ii)
3687 /* Skip artificial methods. This is necessary if,
3688 for example, the user wants to "print
3689 subclass::subclass" with only one user-defined
3690 constructor. There is no ambiguity in this case.
3691 We are careful here to allow artificial methods
3692 if they are the unique result. */
3693 if (TYPE_FN_FIELD_ARTIFICIAL (f, ii))
3695 if (j == -1)
3696 j = ii;
3697 continue;
3700 /* Desired method is ambiguous if more than one
3701 method is defined. */
3702 if (j != -1 && !TYPE_FN_FIELD_ARTIFICIAL (f, j))
3703 error (_("non-unique member `%s' requires "
3704 "type instantiation"), name);
3706 j = ii;
3709 if (j == -1)
3710 error (_("no matching member function"));
3713 if (TYPE_FN_FIELD_STATIC_P (f, j))
3715 struct symbol *s =
3716 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3717 0, VAR_DOMAIN, 0).symbol;
3719 if (s == NULL)
3720 return NULL;
3722 if (want_address)
3723 return value_addr (read_var_value (s, 0, 0));
3724 else
3725 return read_var_value (s, 0, 0);
3728 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3730 if (want_address)
3732 result = allocate_value
3733 (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3734 cplus_make_method_ptr (value_type (result),
3735 value_contents_writeable (result).data (),
3736 TYPE_FN_FIELD_VOFFSET (f, j), 1);
3738 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3739 return allocate_value (TYPE_FN_FIELD_TYPE (f, j));
3740 else
3741 error (_("Cannot reference virtual member function \"%s\""),
3742 name);
3744 else
3746 struct symbol *s =
3747 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3748 0, VAR_DOMAIN, 0).symbol;
3750 if (s == NULL)
3751 return NULL;
3753 struct value *v = read_var_value (s, 0, 0);
3754 if (!want_address)
3755 result = v;
3756 else
3758 result = allocate_value (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3759 cplus_make_method_ptr (value_type (result),
3760 value_contents_writeable (result).data (),
3761 value_address (v), 0);
3764 return result;
3767 for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3769 struct value *v;
3770 int base_offset;
3772 if (BASETYPE_VIA_VIRTUAL (t, i))
3773 base_offset = 0;
3774 else
3775 base_offset = TYPE_BASECLASS_BITPOS (t, i) / 8;
3776 v = value_struct_elt_for_reference (domain,
3777 offset + base_offset,
3778 TYPE_BASECLASS (t, i),
3779 name, intype,
3780 want_address, noside);
3781 if (v)
3782 return v;
3785 /* As a last chance, pretend that CURTYPE is a namespace, and look
3786 it up that way; this (frequently) works for types nested inside
3787 classes. */
3789 return value_maybe_namespace_elt (curtype, name,
3790 want_address, noside);
3793 /* C++: Return the member NAME of the namespace given by the type
3794 CURTYPE. */
3796 static struct value *
3797 value_namespace_elt (const struct type *curtype,
3798 const char *name, int want_address,
3799 enum noside noside)
3801 struct value *retval = value_maybe_namespace_elt (curtype, name,
3802 want_address,
3803 noside);
3805 if (retval == NULL)
3806 error (_("No symbol \"%s\" in namespace \"%s\"."),
3807 name, curtype->name ());
3809 return retval;
3812 /* A helper function used by value_namespace_elt and
3813 value_struct_elt_for_reference. It looks up NAME inside the
3814 context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
3815 is a class and NAME refers to a type in CURTYPE itself (as opposed
3816 to, say, some base class of CURTYPE). */
3818 static struct value *
3819 value_maybe_namespace_elt (const struct type *curtype,
3820 const char *name, int want_address,
3821 enum noside noside)
3823 const char *namespace_name = curtype->name ();
3824 struct block_symbol sym;
3825 struct value *result;
3827 sym = cp_lookup_symbol_namespace (namespace_name, name,
3828 get_selected_block (0), VAR_DOMAIN);
3830 if (sym.symbol == NULL)
3831 return NULL;
3832 else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3833 && (sym.symbol->aclass () == LOC_TYPEDEF))
3834 result = allocate_value (sym.symbol->type ());
3835 else
3836 result = value_of_variable (sym.symbol, sym.block);
3838 if (want_address)
3839 result = value_addr (result);
3841 return result;
3844 /* Given a pointer or a reference value V, find its real (RTTI) type.
3846 Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3847 and refer to the values computed for the object pointed to. */
3849 struct type *
3850 value_rtti_indirect_type (struct value *v, int *full,
3851 LONGEST *top, int *using_enc)
3853 struct value *target = NULL;
3854 struct type *type, *real_type, *target_type;
3856 type = value_type (v);
3857 type = check_typedef (type);
3858 if (TYPE_IS_REFERENCE (type))
3859 target = coerce_ref (v);
3860 else if (type->code () == TYPE_CODE_PTR)
3865 target = value_ind (v);
3867 catch (const gdb_exception_error &except)
3869 if (except.error == MEMORY_ERROR)
3871 /* value_ind threw a memory error. The pointer is NULL or
3872 contains an uninitialized value: we can't determine any
3873 type. */
3874 return NULL;
3876 throw;
3879 else
3880 return NULL;
3882 real_type = value_rtti_type (target, full, top, using_enc);
3884 if (real_type)
3886 /* Copy qualifiers to the referenced object. */
3887 target_type = value_type (target);
3888 real_type = make_cv_type (TYPE_CONST (target_type),
3889 TYPE_VOLATILE (target_type), real_type, NULL);
3890 if (TYPE_IS_REFERENCE (type))
3891 real_type = lookup_reference_type (real_type, type->code ());
3892 else if (type->code () == TYPE_CODE_PTR)
3893 real_type = lookup_pointer_type (real_type);
3894 else
3895 internal_error (_("Unexpected value type."));
3897 /* Copy qualifiers to the pointer/reference. */
3898 real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3899 real_type, NULL);
3902 return real_type;
3905 /* Given a value pointed to by ARGP, check its real run-time type, and
3906 if that is different from the enclosing type, create a new value
3907 using the real run-time type as the enclosing type (and of the same
3908 type as ARGP) and return it, with the embedded offset adjusted to
3909 be the correct offset to the enclosed object. RTYPE is the type,
3910 and XFULL, XTOP, and XUSING_ENC are the other parameters, computed
3911 by value_rtti_type(). If these are available, they can be supplied
3912 and a second call to value_rtti_type() is avoided. (Pass RTYPE ==
3913 NULL if they're not available. */
3915 struct value *
3916 value_full_object (struct value *argp,
3917 struct type *rtype,
3918 int xfull, int xtop,
3919 int xusing_enc)
3921 struct type *real_type;
3922 int full = 0;
3923 LONGEST top = -1;
3924 int using_enc = 0;
3925 struct value *new_val;
3927 if (rtype)
3929 real_type = rtype;
3930 full = xfull;
3931 top = xtop;
3932 using_enc = xusing_enc;
3934 else
3935 real_type = value_rtti_type (argp, &full, &top, &using_enc);
3937 /* If no RTTI data, or if object is already complete, do nothing. */
3938 if (!real_type || real_type == value_enclosing_type (argp))
3939 return argp;
3941 /* In a destructor we might see a real type that is a superclass of
3942 the object's type. In this case it is better to leave the object
3943 as-is. */
3944 if (full
3945 && real_type->length () < value_enclosing_type (argp)->length ())
3946 return argp;
3948 /* If we have the full object, but for some reason the enclosing
3949 type is wrong, set it. */
3950 /* pai: FIXME -- sounds iffy */
3951 if (full)
3953 argp = value_copy (argp);
3954 set_value_enclosing_type (argp, real_type);
3955 return argp;
3958 /* Check if object is in memory. */
3959 if (VALUE_LVAL (argp) != lval_memory)
3961 warning (_("Couldn't retrieve complete object of RTTI "
3962 "type %s; object may be in register(s)."),
3963 real_type->name ());
3965 return argp;
3968 /* All other cases -- retrieve the complete object. */
3969 /* Go back by the computed top_offset from the beginning of the
3970 object, adjusting for the embedded offset of argp if that's what
3971 value_rtti_type used for its computation. */
3972 new_val = value_at_lazy (real_type, value_address (argp) - top +
3973 (using_enc ? 0 : value_embedded_offset (argp)));
3974 deprecated_set_value_type (new_val, value_type (argp));
3975 set_value_embedded_offset (new_val, (using_enc
3976 ? top + value_embedded_offset (argp)
3977 : top));
3978 return new_val;
3982 /* Return the value of the local variable, if one exists. Throw error
3983 otherwise, such as if the request is made in an inappropriate context. */
3985 struct value *
3986 value_of_this (const struct language_defn *lang)
3988 struct block_symbol sym;
3989 const struct block *b;
3990 frame_info_ptr frame;
3992 if (lang->name_of_this () == NULL)
3993 error (_("no `this' in current language"));
3995 frame = get_selected_frame (_("no frame selected"));
3997 b = get_frame_block (frame, NULL);
3999 sym = lookup_language_this (lang, b);
4000 if (sym.symbol == NULL)
4001 error (_("current stack frame does not contain a variable named `%s'"),
4002 lang->name_of_this ());
4004 return read_var_value (sym.symbol, sym.block, frame);
4007 /* Return the value of the local variable, if one exists. Return NULL
4008 otherwise. Never throw error. */
4010 struct value *
4011 value_of_this_silent (const struct language_defn *lang)
4013 struct value *ret = NULL;
4017 ret = value_of_this (lang);
4019 catch (const gdb_exception_error &except)
4023 return ret;
4026 /* Create a slice (sub-string, sub-array) of ARRAY, that is LENGTH
4027 elements long, starting at LOWBOUND. The result has the same lower
4028 bound as the original ARRAY. */
4030 struct value *
4031 value_slice (struct value *array, int lowbound, int length)
4033 struct type *slice_range_type, *slice_type, *range_type;
4034 LONGEST lowerbound, upperbound;
4035 struct value *slice;
4036 struct type *array_type;
4038 array_type = check_typedef (value_type (array));
4039 if (array_type->code () != TYPE_CODE_ARRAY
4040 && array_type->code () != TYPE_CODE_STRING)
4041 error (_("cannot take slice of non-array"));
4043 if (type_not_allocated (array_type))
4044 error (_("array not allocated"));
4045 if (type_not_associated (array_type))
4046 error (_("array not associated"));
4048 range_type = array_type->index_type ();
4049 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
4050 error (_("slice from bad array or bitstring"));
4052 if (lowbound < lowerbound || length < 0
4053 || lowbound + length - 1 > upperbound)
4054 error (_("slice out of range"));
4056 /* FIXME-type-allocation: need a way to free this type when we are
4057 done with it. */
4058 slice_range_type = create_static_range_type (NULL,
4059 range_type->target_type (),
4060 lowbound,
4061 lowbound + length - 1);
4064 struct type *element_type = array_type->target_type ();
4065 LONGEST offset
4066 = (lowbound - lowerbound) * check_typedef (element_type)->length ();
4068 slice_type = create_array_type (NULL,
4069 element_type,
4070 slice_range_type);
4071 slice_type->set_code (array_type->code ());
4073 if (VALUE_LVAL (array) == lval_memory && value_lazy (array))
4074 slice = allocate_value_lazy (slice_type);
4075 else
4077 slice = allocate_value (slice_type);
4078 value_contents_copy (slice, 0, array, offset,
4079 type_length_units (slice_type));
4082 set_value_component_location (slice, array);
4083 set_value_offset (slice, value_offset (array) + offset);
4086 return slice;
4089 /* See value.h. */
4091 struct value *
4092 value_literal_complex (struct value *arg1,
4093 struct value *arg2,
4094 struct type *type)
4096 struct value *val;
4097 struct type *real_type = type->target_type ();
4099 val = allocate_value (type);
4100 arg1 = value_cast (real_type, arg1);
4101 arg2 = value_cast (real_type, arg2);
4103 int len = real_type->length ();
4105 copy (value_contents (arg1),
4106 value_contents_raw (val).slice (0, len));
4107 copy (value_contents (arg2),
4108 value_contents_raw (val).slice (len, len));
4110 return val;
4113 /* See value.h. */
4115 struct value *
4116 value_real_part (struct value *value)
4118 struct type *type = check_typedef (value_type (value));
4119 struct type *ttype = type->target_type ();
4121 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4122 return value_from_component (value, ttype, 0);
4125 /* See value.h. */
4127 struct value *
4128 value_imaginary_part (struct value *value)
4130 struct type *type = check_typedef (value_type (value));
4131 struct type *ttype = type->target_type ();
4133 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4134 return value_from_component (value, ttype,
4135 check_typedef (ttype)->length ());
4138 /* Cast a value into the appropriate complex data type. */
4140 static struct value *
4141 cast_into_complex (struct type *type, struct value *val)
4143 struct type *real_type = type->target_type ();
4145 if (value_type (val)->code () == TYPE_CODE_COMPLEX)
4147 struct type *val_real_type = value_type (val)->target_type ();
4148 struct value *re_val = allocate_value (val_real_type);
4149 struct value *im_val = allocate_value (val_real_type);
4150 int len = val_real_type->length ();
4152 copy (value_contents (val).slice (0, len),
4153 value_contents_raw (re_val));
4154 copy (value_contents (val).slice (len, len),
4155 value_contents_raw (im_val));
4157 return value_literal_complex (re_val, im_val, type);
4159 else if (value_type (val)->code () == TYPE_CODE_FLT
4160 || value_type (val)->code () == TYPE_CODE_INT)
4161 return value_literal_complex (val,
4162 value_zero (real_type, not_lval),
4163 type);
4164 else
4165 error (_("cannot cast non-number to complex"));
4168 void _initialize_valops ();
4169 void
4170 _initialize_valops ()
4172 add_setshow_boolean_cmd ("overload-resolution", class_support,
4173 &overload_resolution, _("\
4174 Set overload resolution in evaluating C++ functions."), _("\
4175 Show overload resolution in evaluating C++ functions."),
4176 NULL, NULL,
4177 show_overload_resolution,
4178 &setlist, &showlist);
4179 overload_resolution = 1;