valops.c revision 1.12 1 /* Perform non-arithmetic operations on values, for GDB.
2
3 Copyright (C) 1986-2024 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
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.
11
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.
16
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/>. */
19
20 #include "event-top.h"
21 #include "extract-store-integer.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "value.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "gdbcore.h"
28 #include "target.h"
29 #include "demangle.h"
30 #include "language.h"
31 #include "cli/cli-cmds.h"
32 #include "regcache.h"
33 #include "cp-abi.h"
34 #include "block.h"
35 #include "infcall.h"
36 #include "dictionary.h"
37 #include "cp-support.h"
38 #include "target-float.h"
39 #include "tracepoint.h"
40 #include "observable.h"
41 #include "objfiles.h"
42 #include "extension.h"
43 #include "gdbsupport/byte-vector.h"
44 #include "typeprint.h"
45
46 /* Local functions. */
47
48 static int typecmp (bool staticp, bool varargs, int nargs,
49 struct field t1[], const gdb::array_view<value *> t2);
50
51 static struct value *search_struct_field (const char *, struct value *,
52 struct type *, int);
53
54 static struct value *search_struct_method (const char *, struct value **,
55 std::optional<gdb::array_view<value *>>,
56 LONGEST, int *, struct type *);
57
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);
63
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);
69
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);
76
77 static int oload_method_static_p (struct fn_field *, int);
78
79 enum oload_classification { STANDARD, NON_STANDARD, INCOMPATIBLE };
80
81 static enum oload_classification classify_oload_match
82 (const badness_vector &, int, int);
83
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);
89
90 static struct value *value_namespace_elt (const struct type *,
91 const char *, int , enum noside);
92
93 static struct value *value_maybe_namespace_elt (const struct type *,
94 const char *, int,
95 enum noside);
96
97 static CORE_ADDR allocate_space_in_inferior (int);
98
99 static struct value *cast_into_complex (struct type *, struct value *);
100
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)
106 {
107 gdb_printf (file, _("Overload resolution in evaluating "
108 "C++ functions is %s.\n"),
109 value);
110 }
111
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. */
115
116 struct value *
117 find_function_in_inferior (const char *name, struct objfile **objf_p)
118 {
119 struct block_symbol sym;
120
121 sym = lookup_symbol (name, nullptr, SEARCH_TYPE_DOMAIN, nullptr);
122 if (sym.symbol != NULL)
123 {
124 if (objf_p)
125 *objf_p = sym.symbol->objfile ();
126
127 return value_of_variable (sym.symbol, sym.block);
128 }
129 else
130 {
131 bound_minimal_symbol msymbol
132 = lookup_minimal_symbol (current_program_space, name);
133
134 if (msymbol.minsym != NULL)
135 {
136 struct objfile *objfile = msymbol.objfile;
137 struct gdbarch *gdbarch = objfile->arch ();
138
139 struct type *type;
140 CORE_ADDR maddr;
141 type = lookup_pointer_type (builtin_type (gdbarch)->builtin_char);
142 type = lookup_function_type (type);
143 type = lookup_pointer_type (type);
144 maddr = msymbol.value_address ();
145
146 if (objf_p)
147 *objf_p = objfile;
148
149 return value_from_pointer (type, maddr);
150 }
151 else
152 {
153 if (!target_has_execution ())
154 error (_("evaluation of this expression "
155 "requires the target program to be active"));
156 else
157 error (_("evaluation of this expression requires the "
158 "program to have a function \"%s\"."),
159 name);
160 }
161 }
162 }
163
164 /* Allocate NBYTES of space in the inferior using the inferior's
165 malloc and return a value that is a pointer to the allocated
166 space. */
167
168 struct value *
169 value_allocate_space_in_inferior (int len)
170 {
171 struct objfile *objf;
172 struct value *val = find_function_in_inferior ("malloc", &objf);
173 struct gdbarch *gdbarch = objf->arch ();
174 struct value *blocklen;
175
176 blocklen = value_from_longest (builtin_type (gdbarch)->builtin_int, len);
177 val = call_function_by_hand (val, NULL, blocklen);
178 if (value_logical_not (val))
179 {
180 if (!target_has_execution ())
181 error (_("No memory available to program now: "
182 "you need to start the target first"));
183 else
184 error (_("No memory available to program: call to malloc failed"));
185 }
186 return val;
187 }
188
189 static CORE_ADDR
190 allocate_space_in_inferior (int len)
191 {
192 return value_as_long (value_allocate_space_in_inferior (len));
193 }
194
195 /* Cast struct value VAL to type TYPE and return as a value.
196 Both type and val must be of TYPE_CODE_STRUCT or TYPE_CODE_UNION
197 for this to work. Typedef to one of the codes is permitted.
198 Returns NULL if the cast is neither an upcast nor a downcast. */
199
200 static struct value *
201 value_cast_structs (struct type *type, struct value *v2)
202 {
203 struct type *t1;
204 struct type *t2;
205 struct value *v;
206
207 gdb_assert (type != NULL && v2 != NULL);
208
209 t1 = check_typedef (type);
210 t2 = check_typedef (v2->type ());
211
212 /* Check preconditions. */
213 gdb_assert ((t1->code () == TYPE_CODE_STRUCT
214 || t1->code () == TYPE_CODE_UNION)
215 && !!"Precondition is that type is of STRUCT or UNION kind.");
216 gdb_assert ((t2->code () == TYPE_CODE_STRUCT
217 || t2->code () == TYPE_CODE_UNION)
218 && !!"Precondition is that value is of STRUCT or UNION kind");
219
220 if (t1->name () != NULL
221 && t2->name () != NULL
222 && !strcmp (t1->name (), t2->name ()))
223 return NULL;
224
225 /* Upcasting: look in the type of the source to see if it contains the
226 type of the target as a superclass. If so, we'll need to
227 offset the pointer rather than just change its type. */
228 if (t1->name () != NULL)
229 {
230 v = search_struct_field (t1->name (),
231 v2, t2, 1);
232 if (v)
233 return v;
234 }
235
236 /* Downcasting: look in the type of the target to see if it contains the
237 type of the source as a superclass. If so, we'll need to
238 offset the pointer rather than just change its type. */
239 if (t2->name () != NULL)
240 {
241 /* Try downcasting using the run-time type of the value. */
242 int full, using_enc;
243 LONGEST top;
244 struct type *real_type;
245
246 real_type = value_rtti_type (v2, &full, &top, &using_enc);
247 if (real_type)
248 {
249 v = value_full_object (v2, real_type, full, top, using_enc);
250 v = value_at_lazy (real_type, v->address ());
251 real_type = v->type ();
252
253 /* We might be trying to cast to the outermost enclosing
254 type, in which case search_struct_field won't work. */
255 if (real_type->name () != NULL
256 && !strcmp (real_type->name (), t1->name ()))
257 return v;
258
259 v = search_struct_field (t2->name (), v, real_type, 1);
260 if (v)
261 return v;
262 }
263
264 /* Try downcasting using information from the destination type
265 T2. This wouldn't work properly for classes with virtual
266 bases, but those were handled above. */
267 v = search_struct_field (t2->name (),
268 value::zero (t1, not_lval), t1, 1);
269 if (v)
270 {
271 /* Downcasting is possible (t1 is superclass of v2). */
272 CORE_ADDR addr2 = v2->address () + v2->embedded_offset ();
273
274 addr2 -= v->address () + v->embedded_offset ();
275 return value_at (type, addr2);
276 }
277 }
278
279 return NULL;
280 }
281
282 /* Cast one pointer or reference type to another. Both TYPE and
283 the type of ARG2 should be pointer types, or else both should be
284 reference types. If SUBCLASS_CHECK is non-zero, this will force a
285 check to see whether TYPE is a superclass of ARG2's type. If
286 SUBCLASS_CHECK is zero, then the subclass check is done only when
287 ARG2 is itself non-zero. Returns the new pointer or reference. */
288
289 struct value *
290 value_cast_pointers (struct type *type, struct value *arg2,
291 int subclass_check)
292 {
293 struct type *type1 = check_typedef (type);
294 struct type *type2 = check_typedef (arg2->type ());
295 struct type *t1 = check_typedef (type1->target_type ());
296 struct type *t2 = check_typedef (type2->target_type ());
297
298 if (t1->code () == TYPE_CODE_STRUCT
299 && t2->code () == TYPE_CODE_STRUCT
300 && (subclass_check || !value_logical_not (arg2)))
301 {
302 struct value *v2;
303
304 if (TYPE_IS_REFERENCE (type2))
305 v2 = coerce_ref (arg2);
306 else
307 v2 = value_ind (arg2);
308 gdb_assert (check_typedef (v2->type ())->code ()
309 == TYPE_CODE_STRUCT && !!"Why did coercion fail?");
310 v2 = value_cast_structs (t1, v2);
311 /* At this point we have what we can have, un-dereference if needed. */
312 if (v2)
313 {
314 struct value *v = value_addr (v2);
315
316 v->deprecated_set_type (type);
317 return v;
318 }
319 }
320
321 /* No superclass found, just change the pointer type. */
322 arg2 = arg2->copy ();
323 arg2->deprecated_set_type (type);
324 arg2->set_enclosing_type (type);
325 arg2->set_pointed_to_offset (0); /* pai: chk_val */
326 return arg2;
327 }
328
329 /* See value.h. */
330
331 gdb_mpq
332 value_to_gdb_mpq (struct value *value)
333 {
334 struct type *type = check_typedef (value->type ());
335
336 gdb_mpq result;
337 if (is_floating_type (type))
338 result = target_float_to_host_double (value->contents ().data (), type);
339 else
340 {
341 gdb_assert (is_integral_type (type)
342 || is_fixed_point_type (type));
343
344 gdb_mpz vz;
345 vz.read (value->contents (), type_byte_order (type),
346 type->is_unsigned ());
347 result = vz;
348
349 if (is_fixed_point_type (type))
350 result *= type->fixed_point_scaling_factor ();
351 }
352
353 return result;
354 }
355
356 /* Assuming that TO_TYPE is a fixed point type, return a value
357 corresponding to the cast of FROM_VAL to that type. */
358
359 static struct value *
360 value_cast_to_fixed_point (struct type *to_type, struct value *from_val)
361 {
362 struct type *from_type = from_val->type ();
363
364 if (from_type == to_type)
365 return from_val;
366
367 if (!is_floating_type (from_type)
368 && !is_integral_type (from_type)
369 && !is_fixed_point_type (from_type))
370 error (_("Invalid conversion from type %s to fixed point type %s"),
371 from_type->name (), to_type->name ());
372
373 gdb_mpq vq = value_to_gdb_mpq (from_val);
374
375 /* Divide that value by the scaling factor to obtain the unscaled
376 value, first in rational form, and then in integer form. */
377
378 vq /= to_type->fixed_point_scaling_factor ();
379 gdb_mpz unscaled = vq.get_rounded ();
380
381 /* Finally, create the result value, and pack the unscaled value
382 in it. */
383 struct value *result = value::allocate (to_type);
384 unscaled.write (result->contents_raw (),
385 type_byte_order (to_type),
386 to_type->is_unsigned ());
387
388 return result;
389 }
390
391 /* Cast value ARG2 to type TYPE and return as a value.
392 More general than a C cast: accepts any two types of the same length,
393 and if ARG2 is an lvalue it can be cast into anything at all. */
394 /* In C++, casts may change pointer or object representations. */
395
396 struct value *
397 value_cast (struct type *type, struct value *arg2)
398 {
399 enum type_code code1;
400 enum type_code code2;
401 int scalar;
402 struct type *type2;
403
404 int convert_to_boolean = 0;
405
406 /* TYPE might be equal in meaning to the existing type of ARG2, but for
407 many reasons, might be a different type object (e.g. TYPE might be a
408 gdbarch owned type, while ARG2->type () could be an objfile owned
409 type).
410
411 In this case we want to preserve the LVAL of ARG2 as this allows the
412 resulting value to be used in more places. We do this by calling
413 VALUE_COPY if appropriate. */
414 if (types_deeply_equal (make_unqualified_type (arg2->type ()),
415 make_unqualified_type (type)))
416 {
417 /* If the types are exactly equal then we can avoid creating a new
418 value completely. */
419 if (arg2->type () != type)
420 {
421 arg2 = arg2->copy ();
422 arg2->deprecated_set_type (type);
423 }
424 return arg2;
425 }
426
427 if (is_fixed_point_type (type))
428 return value_cast_to_fixed_point (type, arg2);
429
430 /* Check if we are casting struct reference to struct reference. */
431 if (TYPE_IS_REFERENCE (check_typedef (type)))
432 {
433 /* We dereference type; then we recurse and finally
434 we generate value of the given reference. Nothing wrong with
435 that. */
436 struct type *t1 = check_typedef (type);
437 struct type *dereftype = check_typedef (t1->target_type ());
438 struct value *val = value_cast (dereftype, arg2);
439
440 return value_ref (val, t1->code ());
441 }
442
443 if (TYPE_IS_REFERENCE (check_typedef (arg2->type ())))
444 /* We deref the value and then do the cast. */
445 return value_cast (type, coerce_ref (arg2));
446
447 /* Strip typedefs / resolve stubs in order to get at the type's
448 code/length, but remember the original type, to use as the
449 resulting type of the cast, in case it was a typedef. */
450 struct type *to_type = type;
451
452 type = check_typedef (type);
453 code1 = type->code ();
454 arg2 = coerce_ref (arg2);
455 type2 = check_typedef (arg2->type ());
456
457 /* You can't cast to a reference type. See value_cast_pointers
458 instead. */
459 gdb_assert (!TYPE_IS_REFERENCE (type));
460
461 /* A cast to an undetermined-length array_type, such as
462 (TYPE [])OBJECT, is treated like a cast to (TYPE [N])OBJECT,
463 where N is sizeof(OBJECT)/sizeof(TYPE). */
464 if (code1 == TYPE_CODE_ARRAY)
465 {
466 struct type *element_type = type->target_type ();
467 unsigned element_length = check_typedef (element_type)->length ();
468
469 if (element_length > 0 && type->bounds ()->high.kind () == PROP_UNDEFINED)
470 {
471 struct type *range_type = type->index_type ();
472 int val_length = type2->length ();
473 LONGEST low_bound, high_bound, new_length;
474
475 if (!get_discrete_bounds (range_type, &low_bound, &high_bound))
476 low_bound = 0, high_bound = 0;
477 new_length = val_length / element_length;
478 if (val_length % element_length != 0)
479 warning (_("array element type size does not "
480 "divide object size in cast"));
481 /* FIXME-type-allocation: need a way to free this type when
482 we are done with it. */
483 type_allocator alloc (range_type->target_type ());
484 range_type = create_static_range_type (alloc,
485 range_type->target_type (),
486 low_bound,
487 new_length + low_bound - 1);
488 arg2->deprecated_set_type (create_array_type (alloc,
489 element_type,
490 range_type));
491 return arg2;
492 }
493 }
494
495 if (current_language->c_style_arrays_p ()
496 && type2->code () == TYPE_CODE_ARRAY
497 && !type2->is_vector ())
498 arg2 = value_coerce_array (arg2);
499
500 if (type2->code () == TYPE_CODE_FUNC)
501 arg2 = value_coerce_function (arg2);
502
503 type2 = check_typedef (arg2->type ());
504 code2 = type2->code ();
505
506 if (code1 == TYPE_CODE_COMPLEX)
507 return cast_into_complex (to_type, arg2);
508 if (code1 == TYPE_CODE_BOOL)
509 {
510 code1 = TYPE_CODE_INT;
511 convert_to_boolean = 1;
512 }
513 if (code1 == TYPE_CODE_CHAR)
514 code1 = TYPE_CODE_INT;
515 if (code2 == TYPE_CODE_BOOL || code2 == TYPE_CODE_CHAR)
516 code2 = TYPE_CODE_INT;
517
518 scalar = (code2 == TYPE_CODE_INT || code2 == TYPE_CODE_FLT
519 || code2 == TYPE_CODE_DECFLOAT || code2 == TYPE_CODE_ENUM
520 || code2 == TYPE_CODE_RANGE
521 || is_fixed_point_type (type2));
522
523 if ((code1 == TYPE_CODE_STRUCT || code1 == TYPE_CODE_UNION)
524 && (code2 == TYPE_CODE_STRUCT || code2 == TYPE_CODE_UNION)
525 && type->name () != 0)
526 {
527 struct value *v = value_cast_structs (to_type, arg2);
528
529 if (v)
530 return v;
531 }
532
533 if (is_floating_type (type) && scalar)
534 {
535 if (is_floating_value (arg2))
536 {
537 struct value *v = value::allocate (to_type);
538 target_float_convert (arg2->contents ().data (), type2,
539 v->contents_raw ().data (), type);
540 return v;
541 }
542 else if (is_fixed_point_type (type2))
543 {
544 gdb_mpq fp_val;
545
546 fp_val.read_fixed_point (arg2->contents (),
547 type_byte_order (type2),
548 type2->is_unsigned (),
549 type2->fixed_point_scaling_factor ());
550
551 struct value *v = value::allocate (to_type);
552 target_float_from_host_double (v->contents_raw ().data (),
553 to_type, fp_val.as_double ());
554 return v;
555 }
556
557 /* The only option left is an integral type. */
558 if (type2->is_unsigned ())
559 return value_from_ulongest (to_type, value_as_long (arg2));
560 else
561 return value_from_longest (to_type, value_as_long (arg2));
562 }
563 else if ((code1 == TYPE_CODE_INT || code1 == TYPE_CODE_ENUM
564 || code1 == TYPE_CODE_RANGE)
565 && (scalar || code2 == TYPE_CODE_PTR
566 || code2 == TYPE_CODE_MEMBERPTR))
567 {
568 gdb_mpz longest;
569
570 /* When we cast pointers to integers, we mustn't use
571 gdbarch_pointer_to_address to find the address the pointer
572 represents, as value_as_long would. GDB should evaluate
573 expressions just as the compiler would --- and the compiler
574 sees a cast as a simple reinterpretation of the pointer's
575 bits. */
576 if (code2 == TYPE_CODE_PTR)
577 longest = extract_unsigned_integer (arg2->contents (),
578 type_byte_order (type2));
579 else
580 longest = value_as_mpz (arg2);
581 if (convert_to_boolean)
582 longest = bool (longest);
583
584 return value_from_mpz (to_type, longest);
585 }
586 else if (code1 == TYPE_CODE_PTR && (code2 == TYPE_CODE_INT
587 || code2 == TYPE_CODE_ENUM
588 || code2 == TYPE_CODE_RANGE))
589 {
590 /* type->length () is the length of a pointer, but we really
591 want the length of an address! -- we are really dealing with
592 addresses (i.e., gdb representations) not pointers (i.e.,
593 target representations) here.
594
595 This allows things like "print *(int *)0x01000234" to work
596 without printing a misleading message -- which would
597 otherwise occur when dealing with a target having two byte
598 pointers and four byte addresses. */
599
600 int addr_bit = gdbarch_addr_bit (type2->arch ());
601 gdb_mpz longest = value_as_mpz (arg2);
602
603 gdb_mpz addr_val = gdb_mpz (1) << addr_bit;
604 if (longest >= addr_val || longest <= -addr_val)
605 warning (_("value truncated"));
606
607 return value_from_mpz (to_type, longest);
608 }
609 else if (code1 == TYPE_CODE_METHODPTR && code2 == TYPE_CODE_INT
610 && value_as_long (arg2) == 0)
611 {
612 struct value *result = value::allocate (to_type);
613
614 cplus_make_method_ptr (to_type,
615 result->contents_writeable ().data (), 0, 0);
616 return result;
617 }
618 else if (code1 == TYPE_CODE_MEMBERPTR && code2 == TYPE_CODE_INT
619 && value_as_long (arg2) == 0)
620 {
621 /* The Itanium C++ ABI represents NULL pointers to members as
622 minus one, instead of biasing the normal case. */
623 return value_from_longest (to_type, -1);
624 }
625 else if (code1 == TYPE_CODE_ARRAY && type->is_vector ()
626 && code2 == TYPE_CODE_ARRAY && type2->is_vector ()
627 && type->length () != type2->length ())
628 error (_("Cannot convert between vector values of different sizes"));
629 else if (code1 == TYPE_CODE_ARRAY && type->is_vector () && scalar
630 && type->length () != type2->length ())
631 error (_("can only cast scalar to vector of same size"));
632 else if (code1 == TYPE_CODE_VOID)
633 {
634 return value::zero (to_type, not_lval);
635 }
636 else if (type->length () == type2->length ())
637 {
638 if (code1 == TYPE_CODE_PTR && code2 == TYPE_CODE_PTR)
639 return value_cast_pointers (to_type, arg2, 0);
640
641 arg2 = arg2->copy ();
642 arg2->deprecated_set_type (to_type);
643 arg2->set_enclosing_type (to_type);
644 arg2->set_pointed_to_offset (0); /* pai: chk_val */
645 return arg2;
646 }
647 else if (arg2->lval () == lval_memory)
648 return value_at_lazy (to_type, arg2->address ());
649 else
650 {
651 if (current_language->la_language == language_ada)
652 error (_("Invalid type conversion."));
653 error (_("Invalid cast."));
654 }
655 }
656
657 /* The C++ reinterpret_cast operator. */
658
659 struct value *
660 value_reinterpret_cast (struct type *type, struct value *arg)
661 {
662 struct value *result;
663 struct type *real_type = check_typedef (type);
664 struct type *arg_type, *dest_type;
665 int is_ref = 0;
666 enum type_code dest_code, arg_code;
667
668 /* Do reference, function, and array conversion. */
669 arg = coerce_array (arg);
670
671 /* Attempt to preserve the type the user asked for. */
672 dest_type = type;
673
674 /* If we are casting to a reference type, transform
675 reinterpret_cast<T&[&]>(V) to *reinterpret_cast<T*>(&V). */
676 if (TYPE_IS_REFERENCE (real_type))
677 {
678 is_ref = 1;
679 arg = value_addr (arg);
680 dest_type = lookup_pointer_type (dest_type->target_type ());
681 real_type = lookup_pointer_type (real_type);
682 }
683
684 arg_type = arg->type ();
685
686 dest_code = real_type->code ();
687 arg_code = arg_type->code ();
688
689 /* We can convert pointer types, or any pointer type to int, or int
690 type to pointer. */
691 if ((dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_INT)
692 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_PTR)
693 || (dest_code == TYPE_CODE_METHODPTR && arg_code == TYPE_CODE_INT)
694 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_METHODPTR)
695 || (dest_code == TYPE_CODE_MEMBERPTR && arg_code == TYPE_CODE_INT)
696 || (dest_code == TYPE_CODE_INT && arg_code == TYPE_CODE_MEMBERPTR)
697 || (dest_code == arg_code
698 && (dest_code == TYPE_CODE_METHODPTR
699 || dest_code == TYPE_CODE_MEMBERPTR)))
700 result = value_cast (dest_type, arg);
701 else if (dest_code == TYPE_CODE_PTR && arg_code == TYPE_CODE_PTR)
702 {
703 /* Don't do any up- or downcasting. */
704 result = arg->copy ();
705 result->deprecated_set_type (dest_type);
706 result->set_enclosing_type (dest_type);
707 result->set_pointed_to_offset (0);
708 }
709 else
710 error (_("Invalid reinterpret_cast"));
711
712 if (is_ref)
713 result = value_cast (type, value_ref (value_ind (result),
714 type->code ()));
715
716 return result;
717 }
718
719 /* A helper for value_dynamic_cast. This implements the first of two
720 runtime checks: we iterate over all the base classes of the value's
721 class which are equal to the desired class; if only one of these
722 holds the value, then it is the answer. */
723
724 static int
725 dynamic_cast_check_1 (struct type *desired_type,
726 const gdb_byte *valaddr,
727 LONGEST embedded_offset,
728 CORE_ADDR address,
729 struct value *val,
730 struct type *search_type,
731 CORE_ADDR arg_addr,
732 struct type *arg_type,
733 struct value **result)
734 {
735 int i, result_count = 0;
736
737 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
738 {
739 LONGEST offset = baseclass_offset (search_type, i, valaddr,
740 embedded_offset,
741 address, val);
742
743 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
744 {
745 if (address + embedded_offset + offset >= arg_addr
746 && address + embedded_offset + offset < arg_addr + arg_type->length ())
747 {
748 ++result_count;
749 if (!*result)
750 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
751 address + embedded_offset + offset);
752 }
753 }
754 else
755 result_count += dynamic_cast_check_1 (desired_type,
756 valaddr,
757 embedded_offset + offset,
758 address, val,
759 TYPE_BASECLASS (search_type, i),
760 arg_addr,
761 arg_type,
762 result);
763 }
764
765 return result_count;
766 }
767
768 /* A helper for value_dynamic_cast. This implements the second of two
769 runtime checks: we look for a unique public sibling class of the
770 argument's declared class. */
771
772 static int
773 dynamic_cast_check_2 (struct type *desired_type,
774 const gdb_byte *valaddr,
775 LONGEST embedded_offset,
776 CORE_ADDR address,
777 struct value *val,
778 struct type *search_type,
779 struct value **result)
780 {
781 int i, result_count = 0;
782
783 for (i = 0; i < TYPE_N_BASECLASSES (search_type) && result_count < 2; ++i)
784 {
785 LONGEST offset;
786
787 if (! BASETYPE_VIA_PUBLIC (search_type, i))
788 continue;
789
790 offset = baseclass_offset (search_type, i, valaddr, embedded_offset,
791 address, val);
792 if (class_types_same_p (desired_type, TYPE_BASECLASS (search_type, i)))
793 {
794 ++result_count;
795 if (*result == NULL)
796 *result = value_at_lazy (TYPE_BASECLASS (search_type, i),
797 address + embedded_offset + offset);
798 }
799 else
800 result_count += dynamic_cast_check_2 (desired_type,
801 valaddr,
802 embedded_offset + offset,
803 address, val,
804 TYPE_BASECLASS (search_type, i),
805 result);
806 }
807
808 return result_count;
809 }
810
811 /* The C++ dynamic_cast operator. */
812
813 struct value *
814 value_dynamic_cast (struct type *type, struct value *arg)
815 {
816 int full, using_enc;
817 LONGEST top;
818 struct type *resolved_type = check_typedef (type);
819 struct type *arg_type = check_typedef (arg->type ());
820 struct type *class_type, *rtti_type;
821 struct value *result, *tem, *original_arg = arg;
822 CORE_ADDR addr;
823 int is_ref = TYPE_IS_REFERENCE (resolved_type);
824
825 if (resolved_type->code () != TYPE_CODE_PTR
826 && !TYPE_IS_REFERENCE (resolved_type))
827 error (_("Argument to dynamic_cast must be a pointer or reference type"));
828 if (resolved_type->target_type ()->code () != TYPE_CODE_VOID
829 && resolved_type->target_type ()->code () != TYPE_CODE_STRUCT)
830 error (_("Argument to dynamic_cast must be pointer to class or `void *'"));
831
832 class_type = check_typedef (resolved_type->target_type ());
833 if (resolved_type->code () == TYPE_CODE_PTR)
834 {
835 if (arg_type->code () != TYPE_CODE_PTR
836 && ! (arg_type->code () == TYPE_CODE_INT
837 && value_as_long (arg) == 0))
838 error (_("Argument to dynamic_cast does not have pointer type"));
839 if (arg_type->code () == TYPE_CODE_PTR)
840 {
841 arg_type = check_typedef (arg_type->target_type ());
842 if (arg_type->code () != TYPE_CODE_STRUCT)
843 error (_("Argument to dynamic_cast does "
844 "not have pointer to class type"));
845 }
846
847 /* Handle NULL pointers. */
848 if (value_as_long (arg) == 0)
849 return value::zero (type, not_lval);
850
851 arg = value_ind (arg);
852 }
853 else
854 {
855 if (arg_type->code () != TYPE_CODE_STRUCT)
856 error (_("Argument to dynamic_cast does not have class type"));
857 }
858
859 /* If the classes are the same, just return the argument. */
860 if (class_types_same_p (class_type, arg_type))
861 return value_cast (type, original_arg);
862
863 /* If the target type is a unique base class of the argument's
864 declared type, just cast it. */
865 if (is_ancestor (class_type, arg_type))
866 {
867 if (is_unique_ancestor (class_type, arg))
868 return value_cast (type, original_arg);
869 error (_("Ambiguous dynamic_cast"));
870 }
871
872 rtti_type = value_rtti_type (arg, &full, &top, &using_enc);
873 if (! rtti_type)
874 error (_("Couldn't determine value's most derived type for dynamic_cast"));
875
876 /* Compute the most derived object's address. */
877 addr = arg->address ();
878 if (full)
879 {
880 /* Done. */
881 }
882 else if (using_enc)
883 addr += top;
884 else
885 addr += top + arg->embedded_offset ();
886
887 /* dynamic_cast<void *> means to return a pointer to the
888 most-derived object. */
889 if (resolved_type->code () == TYPE_CODE_PTR
890 && resolved_type->target_type ()->code () == TYPE_CODE_VOID)
891 return value_at_lazy (type, addr);
892
893 tem = value_at (resolved_type->target_type (), addr);
894 type = (is_ref
895 ? lookup_reference_type (tem->type (), resolved_type->code ())
896 : lookup_pointer_type (tem->type ()));
897
898 /* The first dynamic check specified in 5.2.7. */
899 if (is_public_ancestor (arg_type, resolved_type->target_type ()))
900 {
901 if (class_types_same_p (rtti_type, resolved_type->target_type ()))
902 return (is_ref
903 ? value_ref (tem, resolved_type->code ())
904 : value_addr (tem));
905 result = NULL;
906 if (dynamic_cast_check_1 (resolved_type->target_type (),
907 tem->contents_for_printing ().data (),
908 tem->embedded_offset (),
909 tem->address (), tem,
910 rtti_type, addr,
911 arg_type,
912 &result) == 1)
913 return value_cast (type,
914 is_ref
915 ? value_ref (result, resolved_type->code ())
916 : value_addr (result));
917 }
918
919 /* The second dynamic check specified in 5.2.7. */
920 result = NULL;
921 if (is_public_ancestor (arg_type, rtti_type)
922 && dynamic_cast_check_2 (resolved_type->target_type (),
923 tem->contents_for_printing ().data (),
924 tem->embedded_offset (),
925 tem->address (), tem,
926 rtti_type, &result) == 1)
927 return value_cast (type,
928 is_ref
929 ? value_ref (result, resolved_type->code ())
930 : value_addr (result));
931
932 if (resolved_type->code () == TYPE_CODE_PTR)
933 return value::zero (type, not_lval);
934
935 error (_("dynamic_cast failed"));
936 }
937
938 /* Create a not_lval value of numeric type TYPE that is one, and return it. */
939
940 struct value *
941 value_one (struct type *type)
942 {
943 struct type *type1 = check_typedef (type);
944 struct value *val;
945
946 if (is_integral_type (type1) || is_floating_type (type1))
947 {
948 val = value_from_longest (type, (LONGEST) 1);
949 }
950 else if (type1->code () == TYPE_CODE_ARRAY && type1->is_vector ())
951 {
952 struct type *eltype = check_typedef (type1->target_type ());
953 int i;
954 LONGEST low_bound, high_bound;
955
956 if (!get_array_bounds (type1, &low_bound, &high_bound))
957 error (_("Could not determine the vector bounds"));
958
959 val = value::allocate (type);
960 gdb::array_view<gdb_byte> val_contents = val->contents_writeable ();
961 int elt_len = eltype->length ();
962
963 for (i = 0; i < high_bound - low_bound + 1; i++)
964 {
965 value *tmp = value_one (eltype);
966 copy (tmp->contents_all (),
967 val_contents.slice (i * elt_len, elt_len));
968 }
969 }
970 else
971 {
972 error (_("Not a numeric type."));
973 }
974
975 /* value_one result is never used for assignments to. */
976 gdb_assert (val->lval () == not_lval);
977
978 return val;
979 }
980
981 /* Helper function for value_at, value_at_lazy, and value_at_lazy_stack.
982 The type of the created value may differ from the passed type TYPE.
983 Make sure to retrieve the returned values's new type after this call
984 e.g. in case the type is a variable length array. */
985
986 static struct value *
987 get_value_at (struct type *type, CORE_ADDR addr, const frame_info_ptr &frame,
988 int lazy)
989 {
990 struct value *val;
991
992 if (check_typedef (type)->code () == TYPE_CODE_VOID)
993 error (_("Attempt to dereference a generic pointer."));
994
995 val = value_from_contents_and_address (type, NULL, addr, frame);
996
997 if (!lazy)
998 val->fetch_lazy ();
999
1000 return val;
1001 }
1002
1003 /* Return a value with type TYPE located at ADDR.
1004
1005 Call value_at only if the data needs to be fetched immediately;
1006 if we can be 'lazy' and defer the fetch, perhaps indefinitely, call
1007 value_at_lazy instead. value_at_lazy simply records the address of
1008 the data and sets the lazy-evaluation-required flag. The lazy flag
1009 is tested in the value_contents macro, which is used if and when
1010 the contents are actually required. The type of the created value
1011 may differ from the passed type TYPE. Make sure to retrieve the
1012 returned values's new type after this call e.g. in case the type
1013 is a variable length array.
1014
1015 Note: value_at does *NOT* handle embedded offsets; perform such
1016 adjustments before or after calling it. */
1017
1018 struct value *
1019 value_at (struct type *type, CORE_ADDR addr)
1020 {
1021 return get_value_at (type, addr, nullptr, 0);
1022 }
1023
1024 /* See value.h. */
1025
1026 struct value *
1027 value_at_non_lval (struct type *type, CORE_ADDR addr)
1028 {
1029 struct value *result = value_at (type, addr);
1030 result->set_lval (not_lval);
1031 return result;
1032 }
1033
1034 /* Return a lazy value with type TYPE located at ADDR (cf. value_at).
1035 The type of the created value may differ from the passed type TYPE.
1036 Make sure to retrieve the returned values's new type after this call
1037 e.g. in case the type is a variable length array. */
1038
1039 struct value *
1040 value_at_lazy (struct type *type, CORE_ADDR addr, const frame_info_ptr &frame)
1041 {
1042 return get_value_at (type, addr, frame, 1);
1043 }
1044
1045 void
1046 read_value_memory (struct value *val, LONGEST bit_offset,
1047 bool stack, CORE_ADDR memaddr,
1048 gdb_byte *buffer, size_t length)
1049 {
1050 ULONGEST xfered_total = 0;
1051 struct gdbarch *arch = val->arch ();
1052 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1053 enum target_object object;
1054
1055 object = stack ? TARGET_OBJECT_STACK_MEMORY : TARGET_OBJECT_MEMORY;
1056
1057 while (xfered_total < length)
1058 {
1059 enum target_xfer_status status;
1060 ULONGEST xfered_partial;
1061
1062 status = target_xfer_partial (current_inferior ()->top_target (),
1063 object, NULL,
1064 buffer + xfered_total * unit_size, NULL,
1065 memaddr + xfered_total,
1066 length - xfered_total,
1067 &xfered_partial);
1068
1069 if (status == TARGET_XFER_OK)
1070 /* nothing */;
1071 else if (status == TARGET_XFER_UNAVAILABLE)
1072 val->mark_bits_unavailable ((xfered_total * HOST_CHAR_BIT
1073 + bit_offset),
1074 xfered_partial * HOST_CHAR_BIT);
1075 else if (status == TARGET_XFER_EOF)
1076 memory_error (TARGET_XFER_E_IO, memaddr + xfered_total);
1077 else
1078 memory_error (status, memaddr + xfered_total);
1079
1080 xfered_total += xfered_partial;
1081 QUIT;
1082 }
1083 }
1084
1085 /* Store the contents of FROMVAL into the location of TOVAL.
1086 Return a new value with the location of TOVAL and contents of FROMVAL. */
1087
1088 struct value *
1089 value_assign (struct value *toval, struct value *fromval)
1090 {
1091 struct type *type;
1092 struct value *val;
1093 struct frame_id old_frame;
1094
1095 if (!toval->deprecated_modifiable ())
1096 error (_("Left operand of assignment is not a modifiable lvalue."));
1097
1098 toval = coerce_ref (toval);
1099
1100 type = toval->type ();
1101 if (toval->lval () != lval_internalvar)
1102 fromval = value_cast (type, fromval);
1103 else
1104 {
1105 /* Coerce arrays and functions to pointers, except for arrays
1106 which only live in GDB's storage. */
1107 if (!value_must_coerce_to_target (fromval))
1108 fromval = coerce_array (fromval);
1109 }
1110
1111 type = check_typedef (type);
1112
1113 /* Since modifying a register can trash the frame chain, and
1114 modifying memory can trash the frame cache, we save the old frame
1115 and then restore the new frame afterwards. */
1116 old_frame = get_frame_id (deprecated_safe_get_selected_frame ());
1117
1118 switch (toval->lval ())
1119 {
1120 case lval_internalvar:
1121 set_internalvar (VALUE_INTERNALVAR (toval), fromval);
1122 return value_of_internalvar (type->arch (),
1123 VALUE_INTERNALVAR (toval));
1124
1125 case lval_internalvar_component:
1126 {
1127 LONGEST offset = toval->offset ();
1128
1129 /* Are we dealing with a bitfield?
1130
1131 It is important to mention that `toval->parent ()' is
1132 non-NULL iff `toval->bitsize ()' is non-zero. */
1133 if (toval->bitsize ())
1134 {
1135 /* VALUE_INTERNALVAR below refers to the parent value, while
1136 the offset is relative to this parent value. */
1137 gdb_assert (toval->parent ()->parent () == NULL);
1138 offset += toval->parent ()->offset ();
1139 }
1140
1141 set_internalvar_component (VALUE_INTERNALVAR (toval),
1142 offset,
1143 toval->bitpos (),
1144 toval->bitsize (),
1145 fromval);
1146 }
1147 break;
1148
1149 case lval_memory:
1150 {
1151 const gdb_byte *dest_buffer;
1152 CORE_ADDR changed_addr;
1153 int changed_len;
1154 gdb_byte buffer[sizeof (LONGEST)];
1155
1156 if (toval->bitsize ())
1157 {
1158 struct value *parent = toval->parent ();
1159
1160 changed_addr = parent->address () + toval->offset ();
1161 changed_len = (toval->bitpos ()
1162 + toval->bitsize ()
1163 + HOST_CHAR_BIT - 1)
1164 / HOST_CHAR_BIT;
1165
1166 /* If we can read-modify-write exactly the size of the
1167 containing type (e.g. short or int) then do so. This
1168 is safer for volatile bitfields mapped to hardware
1169 registers. */
1170 if (changed_len < type->length ()
1171 && type->length () <= (int) sizeof (LONGEST)
1172 && ((LONGEST) changed_addr % type->length ()) == 0)
1173 changed_len = type->length ();
1174
1175 if (changed_len > (int) sizeof (LONGEST))
1176 error (_("Can't handle bitfields which "
1177 "don't fit in a %d bit word."),
1178 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1179
1180 read_memory (changed_addr, buffer, changed_len);
1181 modify_field (type, buffer, value_as_long (fromval),
1182 toval->bitpos (), toval->bitsize ());
1183 dest_buffer = buffer;
1184 }
1185 else
1186 {
1187 changed_addr = toval->address ();
1188 changed_len = type_length_units (type);
1189 dest_buffer = fromval->contents ().data ();
1190 }
1191
1192 write_memory_with_notification (changed_addr, dest_buffer, changed_len);
1193 }
1194 break;
1195
1196 case lval_register:
1197 {
1198 frame_info_ptr next_frame = frame_find_by_id (toval->next_frame_id ());
1199 int value_reg = toval->regnum ();
1200
1201 if (next_frame == nullptr)
1202 error (_("Value being assigned to is no longer active."));
1203
1204 gdbarch *gdbarch = frame_unwind_arch (next_frame);
1205
1206 if (toval->bitsize ())
1207 {
1208 struct value *parent = toval->parent ();
1209 LONGEST offset = parent->offset () + toval->offset ();
1210 size_t changed_len;
1211 gdb_byte buffer[sizeof (LONGEST)];
1212 int optim, unavail;
1213
1214 changed_len = (toval->bitpos ()
1215 + toval->bitsize ()
1216 + HOST_CHAR_BIT - 1)
1217 / HOST_CHAR_BIT;
1218
1219 if (changed_len > sizeof (LONGEST))
1220 error (_("Can't handle bitfields which "
1221 "don't fit in a %d bit word."),
1222 (int) sizeof (LONGEST) * HOST_CHAR_BIT);
1223
1224 if (!get_frame_register_bytes (next_frame, value_reg, offset,
1225 { buffer, changed_len }, &optim,
1226 &unavail))
1227 {
1228 if (optim)
1229 throw_error (OPTIMIZED_OUT_ERROR,
1230 _("value has been optimized out"));
1231 if (unavail)
1232 throw_error (NOT_AVAILABLE_ERROR,
1233 _("value is not available"));
1234 }
1235
1236 modify_field (type, buffer, value_as_long (fromval),
1237 toval->bitpos (), toval->bitsize ());
1238
1239 put_frame_register_bytes (next_frame, value_reg, offset,
1240 { buffer, changed_len });
1241 }
1242 else
1243 {
1244 if (gdbarch_convert_register_p (gdbarch, toval->regnum (), type))
1245 {
1246 /* If TOVAL is a special machine register requiring
1247 conversion of program values to a special raw
1248 format. */
1249 gdbarch_value_to_register (gdbarch,
1250 get_prev_frame_always (next_frame),
1251 toval->regnum (), type,
1252 fromval->contents ().data ());
1253 }
1254 else
1255 put_frame_register_bytes (next_frame, value_reg,
1256 toval->offset (),
1257 fromval->contents ());
1258 }
1259
1260 gdb::observers::register_changed.notify
1261 (get_prev_frame_always (next_frame), value_reg);
1262 break;
1263 }
1264
1265 case lval_computed:
1266 {
1267 const struct lval_funcs *funcs = toval->computed_funcs ();
1268
1269 if (funcs->write != NULL)
1270 {
1271 funcs->write (toval, fromval);
1272 break;
1273 }
1274 }
1275 [[fallthrough]];
1276
1277 default:
1278 error (_("Left operand of assignment is not an lvalue."));
1279 }
1280
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 (toval->lval ())
1287 {
1288 case lval_memory:
1289 case lval_register:
1290 case lval_computed:
1291
1292 gdb::observers::target_changed.notify
1293 (current_inferior ()->top_target ());
1294
1295 /* Having destroyed the frame cache, restore the selected
1296 frame. */
1297
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. */
1303
1304 {
1305 frame_info_ptr fi = frame_find_by_id (old_frame);
1306
1307 if (fi != NULL)
1308 select_frame (fi);
1309 }
1310
1311 break;
1312 default:
1313 break;
1314 }
1315
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 ((toval->bitsize () > 0)
1320 && (toval->bitsize () < 8 * (int) sizeof (LONGEST)))
1321 {
1322 LONGEST fieldval = value_as_long (fromval);
1323 LONGEST valmask = (((ULONGEST) 1) << toval->bitsize ()) - 1;
1324
1325 fieldval &= valmask;
1326 if (!type->is_unsigned ()
1327 && (fieldval & (valmask ^ (valmask >> 1))))
1328 fieldval |= ~valmask;
1329
1330 fromval = value_from_longest (type, fieldval);
1331 }
1332
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 = toval->copy ();
1337 val->set_lazy (false);
1338 copy (fromval->contents (), val->contents_raw ());
1339
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 referred
1343 to by TOVAL retains its original dynamic type after assignment. */
1344 if (type->code () == TYPE_CODE_PTR)
1345 {
1346 val->set_enclosing_type (fromval->enclosing_type ());
1347 val->set_pointed_to_offset (fromval->pointed_to_offset ());
1348 }
1349
1350 return val;
1351 }
1352
1353 /* Extend a value ARG1 to COUNT repetitions of its type. */
1354
1355 struct value *
1356 value_repeat (struct value *arg1, int count)
1357 {
1358 struct value *val;
1359
1360 arg1 = coerce_ref (arg1);
1361
1362 if (arg1->lval () != lval_memory)
1363 error (_("Only values in memory can be extended with '@'."));
1364 if (count < 1)
1365 error (_("Invalid number %d of repetitions."), count);
1366
1367 val = allocate_repeat_value (arg1->enclosing_type (), count);
1368
1369 val->set_lval (lval_memory);
1370 val->set_address (arg1->address ());
1371
1372 read_value_memory (val, 0, val->stack (), val->address (),
1373 val->contents_all_raw ().data (),
1374 type_length_units (val->enclosing_type ()));
1375
1376 return val;
1377 }
1378
1379 struct value *
1380 value_of_variable (struct symbol *var, const struct block *b)
1381 {
1382 frame_info_ptr frame = NULL;
1383
1384 if (symbol_read_needs_frame (var))
1385 frame = get_selected_frame (_("No frame selected."));
1386
1387 return read_var_value (var, b, frame);
1388 }
1389
1390 struct value *
1391 address_of_variable (struct symbol *var, const struct block *b)
1392 {
1393 struct type *type = var->type ();
1394 struct value *val;
1395
1396 /* Evaluate it first; if the result is a memory address, we're fine.
1397 Lazy evaluation pays off here. */
1398
1399 val = value_of_variable (var, b);
1400 type = val->type ();
1401
1402 if ((val->lval () == lval_memory && val->lazy ())
1403 || type->code () == TYPE_CODE_FUNC)
1404 {
1405 CORE_ADDR addr = val->address ();
1406
1407 return value_from_pointer (lookup_pointer_type (type), addr);
1408 }
1409
1410 /* Not a memory address; check what the problem was. */
1411 switch (val->lval ())
1412 {
1413 case lval_register:
1414 {
1415 const char *regname;
1416
1417 frame_info_ptr frame = frame_find_by_id (val->next_frame_id ());
1418 gdb_assert (frame != nullptr);
1419
1420 regname
1421 = gdbarch_register_name (get_frame_arch (frame), val->regnum ());
1422 gdb_assert (regname != nullptr && *regname != '\0');
1423
1424 error (_("Address requested for identifier "
1425 "\"%s\" which is in register $%s"),
1426 var->print_name (), regname);
1427 break;
1428 }
1429
1430 default:
1431 error (_("Can't take address of \"%s\" which isn't an lvalue."),
1432 var->print_name ());
1433 break;
1434 }
1435
1436 return val;
1437 }
1438
1439 /* See value.h. */
1440
1441 bool
1442 value_must_coerce_to_target (struct value *val)
1443 {
1444 struct type *valtype;
1445
1446 /* The only lval kinds which do not live in target memory. */
1447 if (val->lval () != not_lval
1448 && val->lval () != lval_internalvar
1449 && val->lval () != lval_xcallable)
1450 return false;
1451
1452 valtype = check_typedef (val->type ());
1453
1454 switch (valtype->code ())
1455 {
1456 case TYPE_CODE_ARRAY:
1457 return valtype->is_vector () ? 0 : 1;
1458 case TYPE_CODE_STRING:
1459 return true;
1460 default:
1461 return false;
1462 }
1463 }
1464
1465 /* Make sure that VAL lives in target memory if it's supposed to. For
1466 instance, strings are constructed as character arrays in GDB's
1467 storage, and this function copies them to the target. */
1468
1469 struct value *
1470 value_coerce_to_target (struct value *val)
1471 {
1472 LONGEST length;
1473 CORE_ADDR addr;
1474
1475 if (!value_must_coerce_to_target (val))
1476 return val;
1477
1478 length = check_typedef (val->type ())->length ();
1479 addr = allocate_space_in_inferior (length);
1480 write_memory (addr, val->contents ().data (), length);
1481 return value_at_lazy (val->type (), addr);
1482 }
1483
1484 /* Given a value which is an array, return a value which is a pointer
1485 to its first element, regardless of whether or not the array has a
1486 nonzero lower bound.
1487
1488 FIXME: A previous comment here indicated that this routine should
1489 be subtracting the array's lower bound. It's not clear to me that
1490 this is correct. Given an array subscripting operation, it would
1491 certainly work to do the adjustment here, essentially computing:
1492
1493 (&array[0] - (lowerbound * sizeof array[0])) + (index * sizeof array[0])
1494
1495 However I believe a more appropriate and logical place to account
1496 for the lower bound is to do so in value_subscript, essentially
1497 computing:
1498
1499 (&array[0] + ((index - lowerbound) * sizeof array[0]))
1500
1501 As further evidence consider what would happen with operations
1502 other than array subscripting, where the caller would get back a
1503 value that had an address somewhere before the actual first element
1504 of the array, and the information about the lower bound would be
1505 lost because of the coercion to pointer type. */
1506
1507 struct value *
1508 value_coerce_array (struct value *arg1)
1509 {
1510 struct type *type = check_typedef (arg1->type ());
1511
1512 /* If the user tries to do something requiring a pointer with an
1513 array that has not yet been pushed to the target, then this would
1514 be a good time to do so. */
1515 arg1 = value_coerce_to_target (arg1);
1516
1517 if (arg1->lval () != lval_memory)
1518 error (_("Attempt to take address of value not located in memory."));
1519
1520 return value_from_pointer (lookup_pointer_type (type->target_type ()),
1521 arg1->address ());
1522 }
1523
1524 /* Given a value which is a function, return a value which is a pointer
1525 to it. */
1526
1527 struct value *
1528 value_coerce_function (struct value *arg1)
1529 {
1530 struct value *retval;
1531
1532 if (arg1->lval () != lval_memory)
1533 error (_("Attempt to take address of value not located in memory."));
1534
1535 retval = value_from_pointer (lookup_pointer_type (arg1->type ()),
1536 arg1->address ());
1537 return retval;
1538 }
1539
1540 /* Return a pointer value for the object for which ARG1 is the
1541 contents. */
1542
1543 struct value *
1544 value_addr (struct value *arg1)
1545 {
1546 struct value *arg2;
1547 struct type *type = check_typedef (arg1->type ());
1548
1549 if (TYPE_IS_REFERENCE (type))
1550 {
1551 if (arg1->bits_synthetic_pointer (arg1->embedded_offset (),
1552 TARGET_CHAR_BIT * type->length ()))
1553 arg1 = coerce_ref (arg1);
1554 else
1555 {
1556 /* Copy the value, but change the type from (T&) to (T*). We
1557 keep the same location information, which is efficient, and
1558 allows &(&X) to get the location containing the reference.
1559 Do the same to its enclosing type for consistency. */
1560 struct type *type_ptr
1561 = lookup_pointer_type (type->target_type ());
1562 struct type *enclosing_type
1563 = check_typedef (arg1->enclosing_type ());
1564 struct type *enclosing_type_ptr
1565 = lookup_pointer_type (enclosing_type->target_type ());
1566
1567 arg2 = arg1->copy ();
1568 arg2->deprecated_set_type (type_ptr);
1569 arg2->set_enclosing_type (enclosing_type_ptr);
1570
1571 return arg2;
1572 }
1573 }
1574 if (type->code () == TYPE_CODE_FUNC)
1575 return value_coerce_function (arg1);
1576
1577 /* If this is an array that has not yet been pushed to the target,
1578 then this would be a good time to force it to memory. */
1579 arg1 = value_coerce_to_target (arg1);
1580
1581 if (arg1->lval () != lval_memory)
1582 error (_("Attempt to take address of value not located in memory."));
1583
1584 /* Get target memory address. */
1585 arg2 = value_from_pointer (lookup_pointer_type (arg1->type ()),
1586 (arg1->address ()
1587 + arg1->embedded_offset ()));
1588
1589 /* This may be a pointer to a base subobject; so remember the
1590 full derived object's type ... */
1591 arg2->set_enclosing_type (lookup_pointer_type (arg1->enclosing_type ()));
1592 /* ... and also the relative position of the subobject in the full
1593 object. */
1594 arg2->set_pointed_to_offset (arg1->embedded_offset ());
1595 return arg2;
1596 }
1597
1598 /* Return a reference value for the object for which ARG1 is the
1599 contents. */
1600
1601 struct value *
1602 value_ref (struct value *arg1, enum type_code refcode)
1603 {
1604 struct value *arg2;
1605 struct type *type = check_typedef (arg1->type ());
1606
1607 gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
1608
1609 if ((type->code () == TYPE_CODE_REF
1610 || type->code () == TYPE_CODE_RVALUE_REF)
1611 && type->code () == refcode)
1612 return arg1;
1613
1614 arg2 = value_addr (arg1);
1615 arg2->deprecated_set_type (lookup_reference_type (type, refcode));
1616 return arg2;
1617 }
1618
1619 /* Given a value of a pointer type, apply the C unary * operator to
1620 it. */
1621
1622 struct value *
1623 value_ind (struct value *arg1)
1624 {
1625 struct type *base_type;
1626 struct value *arg2;
1627
1628 arg1 = coerce_array (arg1);
1629
1630 base_type = check_typedef (arg1->type ());
1631
1632 if (arg1->lval () == lval_computed)
1633 {
1634 const struct lval_funcs *funcs = arg1->computed_funcs ();
1635
1636 if (funcs->indirect)
1637 {
1638 struct value *result = funcs->indirect (arg1);
1639
1640 if (result)
1641 return result;
1642 }
1643 }
1644
1645 if (base_type->code () == TYPE_CODE_PTR)
1646 {
1647 struct type *enc_type;
1648
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 (arg1->enclosing_type ());
1652 enc_type = enc_type->target_type ();
1653
1654 CORE_ADDR base_addr;
1655 if (check_typedef (enc_type)->code () == TYPE_CODE_FUNC
1656 || check_typedef (enc_type)->code () == TYPE_CODE_METHOD)
1657 {
1658 /* For functions, go through find_function_addr, which knows
1659 how to handle function descriptors. */
1660 base_addr = find_function_addr (arg1, NULL);
1661 }
1662 else
1663 {
1664 /* Retrieve the enclosing object pointed to. */
1665 base_addr = (value_as_address (arg1)
1666 - arg1->pointed_to_offset ());
1667 }
1668 arg2 = value_at_lazy (enc_type, base_addr);
1669 enc_type = arg2->type ();
1670 return readjust_indirect_value_type (arg2, enc_type, base_type,
1671 arg1, base_addr);
1672 }
1673
1674 error (_("Attempt to take contents of a non-pointer value."));
1675 }
1676
1677 /* Create a value for an array by allocating space in GDB, copying the
1679 data into that space, and then setting up an array value.
1680
1681 The array bounds are set from LOWBOUND and the size of ELEMVEC, and
1682 the array is populated from the values passed in ELEMVEC.
1683
1684 The element type of the array is inherited from the type of the
1685 first element, and all elements must have the same size (though we
1686 don't currently enforce any restriction on their types). */
1687
1688 struct value *
1689 value_array (int lowbound, gdb::array_view<struct value *> elemvec)
1690 {
1691 int idx;
1692 ULONGEST typelength;
1693 struct value *val;
1694 struct type *arraytype;
1695
1696 /* Validate that the bounds are reasonable and that each of the
1697 elements have the same size. */
1698
1699 typelength = type_length_units (elemvec[0]->enclosing_type ());
1700 for (struct value *other : elemvec.slice (1))
1701 {
1702 if (type_length_units (other->enclosing_type ()) != typelength)
1703 {
1704 error (_("array elements must all be the same size"));
1705 }
1706 }
1707
1708 arraytype = lookup_array_range_type (elemvec[0]->enclosing_type (),
1709 lowbound,
1710 lowbound + elemvec.size () - 1);
1711
1712 if (!current_language->c_style_arrays_p ())
1713 {
1714 val = value::allocate (arraytype);
1715 for (idx = 0; idx < elemvec.size (); idx++)
1716 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1717 return val;
1718 }
1719
1720 /* Allocate space to store the array, and then initialize it by
1721 copying in each element. */
1722
1723 val = value::allocate (arraytype);
1724 for (idx = 0; idx < elemvec.size (); idx++)
1725 elemvec[idx]->contents_copy (val, idx * typelength, 0, typelength);
1726 return val;
1727 }
1728
1729 /* See value.h. */
1730
1731 struct value *
1732 value_cstring (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1733 {
1734 struct value *val;
1735 int lowbound = current_language->string_lower_bound ();
1736 ssize_t highbound = count + 1;
1737 struct type *stringtype
1738 = lookup_array_range_type (char_type, lowbound, highbound + lowbound - 1);
1739
1740 val = value::allocate (stringtype);
1741 ssize_t len = count * char_type->length ();
1742 memcpy (val->contents_raw ().data (), ptr, len);
1743 /* Write the terminating null-character. */
1744 memset (val->contents_raw ().data () + len, 0, char_type->length ());
1745 return val;
1746 }
1747
1748 /* See value.h. */
1749
1750 struct value *
1751 value_string (const gdb_byte *ptr, ssize_t count, struct type *char_type)
1752 {
1753 struct value *val;
1754 int lowbound = current_language->string_lower_bound ();
1755 ssize_t highbound = count;
1756 struct type *stringtype
1757 = lookup_string_range_type (char_type, lowbound, highbound + lowbound - 1);
1758
1759 val = value::allocate (stringtype);
1760 ssize_t len = count * char_type->length ();
1761 memcpy (val->contents_raw ().data (), ptr, len);
1762 return val;
1763 }
1764
1765
1766 /* See if we can pass arguments in T2 to a function which takes arguments
1768 of types T1. T1 is a list of NARGS arguments, and T2 is an array_view
1769 of the values we're trying to pass. If some arguments need coercion of
1770 some sort, then the coerced values are written into T2. Return value is
1771 0 if the arguments could be matched, or the position at which they
1772 differ if not.
1773
1774 STATICP is nonzero if the T1 argument list came from a static
1775 member function. T2 must still include the ``this'' pointer, but
1776 it will be skipped.
1777
1778 For non-static member functions, we ignore the first argument,
1779 which is the type of the instance variable. This is because we
1780 want to handle calls with objects from derived classes. This is
1781 not entirely correct: we should actually check to make sure that a
1782 requested operation is type secure, shouldn't we? FIXME. */
1783
1784 static int
1785 typecmp (bool staticp, bool varargs, int nargs,
1786 struct field t1[], gdb::array_view<value *> t2)
1787 {
1788 int i;
1789
1790 /* Skip ``this'' argument if applicable. T2 will always include
1791 THIS. */
1792 if (staticp)
1793 t2 = t2.slice (1);
1794
1795 for (i = 0;
1796 (i < nargs) && t1[i].type ()->code () != TYPE_CODE_VOID;
1797 i++)
1798 {
1799 struct type *tt1, *tt2;
1800
1801 if (i == t2.size ())
1802 return i + 1;
1803
1804 tt1 = check_typedef (t1[i].type ());
1805 tt2 = check_typedef (t2[i]->type ());
1806
1807 if (TYPE_IS_REFERENCE (tt1)
1808 /* We should be doing hairy argument matching, as below. */
1809 && (check_typedef (tt1->target_type ())->code ()
1810 == tt2->code ()))
1811 {
1812 if (tt2->code () == TYPE_CODE_ARRAY)
1813 t2[i] = value_coerce_array (t2[i]);
1814 else
1815 t2[i] = value_ref (t2[i], tt1->code ());
1816 continue;
1817 }
1818
1819 /* djb - 20000715 - Until the new type structure is in the
1820 place, and we can attempt things like implicit conversions,
1821 we need to do this so you can take something like a map<const
1822 char *>, and properly access map["hello"], because the
1823 argument to [] will be a reference to a pointer to a char,
1824 and the argument will be a pointer to a char. */
1825 while (TYPE_IS_REFERENCE (tt1) || tt1->code () == TYPE_CODE_PTR)
1826 {
1827 tt1 = check_typedef ( tt1->target_type () );
1828 }
1829 while (tt2->code () == TYPE_CODE_ARRAY
1830 || tt2->code () == TYPE_CODE_PTR
1831 || TYPE_IS_REFERENCE (tt2))
1832 {
1833 tt2 = check_typedef (tt2->target_type ());
1834 }
1835 if (tt1->code () == tt2->code ())
1836 continue;
1837 /* Array to pointer is a `trivial conversion' according to the
1838 ARM. */
1839
1840 /* We should be doing much hairier argument matching (see
1841 section 13.2 of the ARM), but as a quick kludge, just check
1842 for the same type code. */
1843 if (t1[i].type ()->code () != t2[i]->type ()->code ())
1844 return i + 1;
1845 }
1846 if (varargs || i == t2.size ())
1847 return 0;
1848 return i + 1;
1849 }
1850
1851 /* Helper class for search_struct_field that keeps track of found
1852 results and possibly throws an exception if the search yields
1853 ambiguous results. See search_struct_field for description of
1854 LOOKING_FOR_BASECLASS. */
1855
1856 struct struct_field_searcher
1857 {
1858 /* A found field. */
1859 struct found_field
1860 {
1861 /* Path to the structure where the field was found. */
1862 std::vector<struct type *> path;
1863
1864 /* The field found. */
1865 struct value *field_value;
1866 };
1867
1868 /* See corresponding fields for description of parameters. */
1869 struct_field_searcher (const char *name,
1870 struct type *outermost_type,
1871 bool looking_for_baseclass)
1872 : m_name (name),
1873 m_looking_for_baseclass (looking_for_baseclass),
1874 m_outermost_type (outermost_type)
1875 {
1876 }
1877
1878 /* The search entry point. If LOOKING_FOR_BASECLASS is true and the
1879 base class search yields ambiguous results, this throws an
1880 exception. If LOOKING_FOR_BASECLASS is false, the found fields
1881 are accumulated and the caller (search_struct_field) takes care
1882 of throwing an error if the field search yields ambiguous
1883 results. The latter is done that way so that the error message
1884 can include a list of all the found candidates. */
1885 void search (struct value *arg, LONGEST offset, struct type *type);
1886
1887 const std::vector<found_field> &fields ()
1888 {
1889 return m_fields;
1890 }
1891
1892 struct value *baseclass ()
1893 {
1894 return m_baseclass;
1895 }
1896
1897 private:
1898 /* Update results to include V, a found field/baseclass. */
1899 void update_result (struct value *v, LONGEST boffset);
1900
1901 /* The name of the field/baseclass we're searching for. */
1902 const char *m_name;
1903
1904 /* Whether we're looking for a baseclass, or a field. */
1905 const bool m_looking_for_baseclass;
1906
1907 /* The offset of the baseclass containing the field/baseclass we
1908 last recorded. */
1909 LONGEST m_last_boffset = 0;
1910
1911 /* If looking for a baseclass, then the result is stored here. */
1912 struct value *m_baseclass = nullptr;
1913
1914 /* When looking for fields, the found candidates are stored
1915 here. */
1916 std::vector<found_field> m_fields;
1917
1918 /* The type of the initial type passed to search_struct_field; this
1919 is used for error reporting when the lookup is ambiguous. */
1920 struct type *m_outermost_type;
1921
1922 /* The full path to the struct being inspected. E.g. for field 'x'
1923 defined in class B inherited by class A, we have A and B pushed
1924 on the path. */
1925 std::vector <struct type *> m_struct_path;
1926 };
1927
1928 void
1929 struct_field_searcher::update_result (struct value *v, LONGEST boffset)
1930 {
1931 if (v != NULL)
1932 {
1933 if (m_looking_for_baseclass)
1934 {
1935 if (m_baseclass != nullptr
1936 /* The result is not ambiguous if all the classes that are
1937 found occupy the same space. */
1938 && m_last_boffset != boffset)
1939 error (_("base class '%s' is ambiguous in type '%s'"),
1940 m_name, TYPE_SAFE_NAME (m_outermost_type));
1941
1942 m_baseclass = v;
1943 m_last_boffset = boffset;
1944 }
1945 else
1946 {
1947 /* The field is not ambiguous if it occupies the same
1948 space. */
1949 if (m_fields.empty () || m_last_boffset != boffset)
1950 m_fields.push_back ({m_struct_path, v});
1951 else
1952 {
1953 /*Fields can occupy the same space and have the same name (be
1954 ambiguous). This can happen when fields in two different base
1955 classes are marked [[no_unique_address]] and have the same name.
1956 The C++ standard says that such fields can only occupy the same
1957 space if they are of different type, but we don't rely on that in
1958 the following code. */
1959 bool ambiguous = false, insert = true;
1960 for (const found_field &field: m_fields)
1961 {
1962 if(field.path.back () != m_struct_path.back ())
1963 {
1964 /* Same boffset points to members of different classes.
1965 We have found an ambiguity and should record it. */
1966 ambiguous = true;
1967 }
1968 else
1969 {
1970 /* We don't need to insert this value again, because a
1971 non-ambiguous path already leads to it. */
1972 insert = false;
1973 break;
1974 }
1975 }
1976 if (ambiguous && insert)
1977 m_fields.push_back ({m_struct_path, v});
1978 }
1979 }
1980 }
1981 }
1982
1983 /* A helper for search_struct_field. This does all the work; most
1984 arguments are as passed to search_struct_field. */
1985
1986 void
1987 struct_field_searcher::search (struct value *arg1, LONGEST offset,
1988 struct type *type)
1989 {
1990 int i;
1991 int nbases;
1992
1993 m_struct_path.push_back (type);
1994 SCOPE_EXIT { m_struct_path.pop_back (); };
1995
1996 type = check_typedef (type);
1997 nbases = TYPE_N_BASECLASSES (type);
1998
1999 if (!m_looking_for_baseclass)
2000 for (i = type->num_fields () - 1; i >= nbases; i--)
2001 {
2002 const char *t_field_name = type->field (i).name ();
2003
2004 if (t_field_name && (strcmp_iw (t_field_name, m_name) == 0))
2005 {
2006 struct value *v;
2007
2008 if (type->field (i).is_static ())
2009 v = value_static_field (type, i);
2010 else
2011 v = arg1->primitive_field (offset, i, type);
2012
2013 update_result (v, offset);
2014 return;
2015 }
2016
2017 if (t_field_name
2018 && t_field_name[0] == '\0')
2019 {
2020 struct type *field_type = type->field (i).type ();
2021
2022 if (field_type->code () == TYPE_CODE_UNION
2023 || field_type->code () == TYPE_CODE_STRUCT)
2024 {
2025 /* Look for a match through the fields of an anonymous
2026 union, or anonymous struct. C++ provides anonymous
2027 unions.
2028
2029 In the GNU Chill (now deleted from GDB)
2030 implementation of variant record types, each
2031 <alternative field> has an (anonymous) union type,
2032 each member of the union represents a <variant
2033 alternative>. Each <variant alternative> is
2034 represented as a struct, with a member for each
2035 <variant field>. */
2036
2037 LONGEST new_offset = offset;
2038
2039 /* This is pretty gross. In G++, the offset in an
2040 anonymous union is relative to the beginning of the
2041 enclosing struct. In the GNU Chill (now deleted
2042 from GDB) implementation of variant records, the
2043 bitpos is zero in an anonymous union field, so we
2044 have to add the offset of the union here. */
2045 if (field_type->code () == TYPE_CODE_STRUCT
2046 || (field_type->num_fields () > 0
2047 && field_type->field (0).loc_bitpos () == 0))
2048 new_offset += type->field (i).loc_bitpos () / 8;
2049
2050 search (arg1, new_offset, field_type);
2051 }
2052 }
2053 }
2054
2055 for (i = 0; i < nbases; i++)
2056 {
2057 struct value *v = NULL;
2058 struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
2059 /* If we are looking for baseclasses, this is what we get when
2060 we hit them. But it could happen that the base part's member
2061 name is not yet filled in. */
2062 int found_baseclass = (m_looking_for_baseclass
2063 && TYPE_BASECLASS_NAME (type, i) != NULL
2064 && (strcmp_iw (m_name, basetype->name ()) == 0));
2065 LONGEST boffset = arg1->embedded_offset () + offset;
2066
2067 if (BASETYPE_VIA_VIRTUAL (type, i))
2068 {
2069 struct value *v2;
2070
2071 boffset = baseclass_offset (type, i,
2072 arg1->contents_for_printing ().data (),
2073 arg1->embedded_offset () + offset,
2074 arg1->address (),
2075 arg1);
2076
2077 /* The virtual base class pointer might have been clobbered
2078 by the user program. Make sure that it still points to a
2079 valid memory location. */
2080
2081 boffset += arg1->embedded_offset () + offset;
2082 if (boffset < 0
2083 || boffset >= arg1->enclosing_type ()->length ())
2084 {
2085 CORE_ADDR base_addr;
2086
2087 base_addr = arg1->address () + boffset;
2088 v2 = value_at_lazy (basetype, base_addr);
2089 if (target_read_memory (base_addr,
2090 v2->contents_raw ().data (),
2091 v2->type ()->length ()) != 0)
2092 error (_("virtual baseclass botch"));
2093 }
2094 else
2095 {
2096 v2 = arg1->copy ();
2097 v2->deprecated_set_type (basetype);
2098 v2->set_embedded_offset (boffset);
2099 }
2100
2101 if (found_baseclass)
2102 v = v2;
2103 else
2104 search (v2, 0, TYPE_BASECLASS (type, i));
2105 }
2106 else if (found_baseclass)
2107 v = arg1->primitive_field (offset, i, type);
2108 else
2109 {
2110 search (arg1, offset + TYPE_BASECLASS_BITPOS (type, i) / 8,
2111 basetype);
2112 }
2113
2114 update_result (v, boffset);
2115 }
2116 }
2117
2118 /* Helper function used by value_struct_elt to recurse through
2119 baseclasses. Look for a field NAME in ARG1. Search in it assuming
2120 it has (class) type TYPE. If found, return value, else return NULL.
2121
2122 If LOOKING_FOR_BASECLASS, then instead of looking for struct
2123 fields, look for a baseclass named NAME. */
2124
2125 static struct value *
2126 search_struct_field (const char *name, struct value *arg1,
2127 struct type *type, int looking_for_baseclass)
2128 {
2129 struct_field_searcher searcher (name, type, looking_for_baseclass);
2130
2131 searcher.search (arg1, 0, type);
2132
2133 if (!looking_for_baseclass)
2134 {
2135 const auto &fields = searcher.fields ();
2136
2137 if (fields.empty ())
2138 return nullptr;
2139 else if (fields.size () == 1)
2140 return fields[0].field_value;
2141 else
2142 {
2143 std::string candidates;
2144
2145 for (auto &&candidate : fields)
2146 {
2147 gdb_assert (!candidate.path.empty ());
2148
2149 struct type *field_type = candidate.field_value->type ();
2150 struct type *struct_type = candidate.path.back ();
2151
2152 std::string path;
2153 bool first = true;
2154 for (struct type *t : candidate.path)
2155 {
2156 if (first)
2157 first = false;
2158 else
2159 path += " -> ";
2160 path += t->name ();
2161 }
2162
2163 candidates += string_printf ("\n '%s %s::%s' (%s)",
2164 TYPE_SAFE_NAME (field_type),
2165 TYPE_SAFE_NAME (struct_type),
2166 name,
2167 path.c_str ());
2168 }
2169
2170 error (_("Request for member '%s' is ambiguous in type '%s'."
2171 " Candidates are:%s"),
2172 name, TYPE_SAFE_NAME (type),
2173 candidates.c_str ());
2174 }
2175 }
2176 else
2177 return searcher.baseclass ();
2178 }
2179
2180 /* Helper function used by value_struct_elt to recurse through
2181 baseclasses. Look for a field NAME in ARG1. Adjust the address of
2182 ARG1 by OFFSET bytes, and search in it assuming it has (class) type
2183 TYPE.
2184
2185 ARGS is an optional array of argument values used to help finding NAME.
2186 The contents of ARGS can be adjusted if type coercion is required in
2187 order to find a matching NAME.
2188
2189 If found, return value, else if name matched and args not return
2190 (value) -1, else return NULL. */
2191
2192 static struct value *
2193 search_struct_method (const char *name, struct value **arg1p,
2194 std::optional<gdb::array_view<value *>> args,
2195 LONGEST offset, int *static_memfuncp,
2196 struct type *type)
2197 {
2198 int i;
2199 struct value *v;
2200 int name_matched = 0;
2201
2202 type = check_typedef (type);
2203 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2204 {
2205 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2206
2207 if (t_field_name && (strcmp_iw (t_field_name, name) == 0))
2208 {
2209 int j = TYPE_FN_FIELDLIST_LENGTH (type, i) - 1;
2210 struct fn_field *f = TYPE_FN_FIELDLIST1 (type, i);
2211
2212 name_matched = 1;
2213 check_stub_method_group (type, i);
2214 if (j > 0 && !args.has_value ())
2215 error (_("cannot resolve overloaded method "
2216 "`%s': no arguments supplied"), name);
2217 else if (j == 0 && !args.has_value ())
2218 {
2219 v = value_fn_field (arg1p, f, j, type, offset);
2220 if (v != NULL)
2221 return v;
2222 }
2223 else
2224 while (j >= 0)
2225 {
2226 gdb_assert (args.has_value ());
2227 if (!typecmp (TYPE_FN_FIELD_STATIC_P (f, j),
2228 TYPE_FN_FIELD_TYPE (f, j)->has_varargs (),
2229 TYPE_FN_FIELD_TYPE (f, j)->num_fields (),
2230 TYPE_FN_FIELD_ARGS (f, j), *args))
2231 {
2232 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
2233 return value_virtual_fn_field (arg1p, f, j,
2234 type, offset);
2235 if (TYPE_FN_FIELD_STATIC_P (f, j)
2236 && static_memfuncp)
2237 *static_memfuncp = 1;
2238 v = value_fn_field (arg1p, f, j, type, offset);
2239 if (v != NULL)
2240 return v;
2241 }
2242 j--;
2243 }
2244 }
2245 }
2246
2247 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2248 {
2249 LONGEST base_offset;
2250 LONGEST this_offset;
2251
2252 if (BASETYPE_VIA_VIRTUAL (type, i))
2253 {
2254 struct type *baseclass = check_typedef (TYPE_BASECLASS (type, i));
2255 struct value *base_val;
2256 const gdb_byte *base_valaddr;
2257
2258 /* The virtual base class pointer might have been
2259 clobbered by the user program. Make sure that it
2260 still points to a valid memory location. */
2261
2262 if (offset < 0 || offset >= type->length ())
2263 {
2264 CORE_ADDR address;
2265
2266 gdb::byte_vector tmp (baseclass->length ());
2267 address = (*arg1p)->address ();
2268
2269 if (target_read_memory (address + offset,
2270 tmp.data (), baseclass->length ()) != 0)
2271 error (_("virtual baseclass botch"));
2272
2273 base_val = value_from_contents_and_address (baseclass,
2274 tmp.data (),
2275 address + offset);
2276 base_valaddr = base_val->contents_for_printing ().data ();
2277 this_offset = 0;
2278 }
2279 else
2280 {
2281 base_val = *arg1p;
2282 base_valaddr = (*arg1p)->contents_for_printing ().data ();
2283 this_offset = offset;
2284 }
2285
2286 base_offset = baseclass_offset (type, i, base_valaddr,
2287 this_offset, base_val->address (),
2288 base_val);
2289 }
2290 else
2291 {
2292 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2293 }
2294 v = search_struct_method (name, arg1p, args, base_offset + offset,
2295 static_memfuncp, TYPE_BASECLASS (type, i));
2296 if (v == (struct value *) - 1)
2297 {
2298 name_matched = 1;
2299 }
2300 else if (v)
2301 {
2302 /* FIXME-bothner: Why is this commented out? Why is it here? */
2303 /* *arg1p = arg1_tmp; */
2304 return v;
2305 }
2306 }
2307 if (name_matched)
2308 return (struct value *) - 1;
2309 else
2310 return NULL;
2311 }
2312
2313 /* Given *ARGP, a value of type (pointer to a)* structure/union,
2314 extract the component named NAME from the ultimate target
2315 structure/union and return it as a value with its appropriate type.
2316 ERR is used in the error message if *ARGP's type is wrong.
2317
2318 C++: ARGS is a list of argument types to aid in the selection of
2319 an appropriate method. Also, handle derived types.
2320
2321 STATIC_MEMFUNCP, if non-NULL, points to a caller-supplied location
2322 where the truthvalue of whether the function that was resolved was
2323 a static member function or not is stored.
2324
2325 ERR is an error message to be printed in case the field is not
2326 found. */
2327
2328 struct value *
2329 value_struct_elt (struct value **argp,
2330 std::optional<gdb::array_view<value *>> args,
2331 const char *name, int *static_memfuncp, const char *err)
2332 {
2333 struct type *t;
2334 struct value *v;
2335
2336 *argp = coerce_array (*argp);
2337
2338 t = check_typedef ((*argp)->type ());
2339
2340 /* Follow pointers until we get to a non-pointer. */
2341
2342 while (t->is_pointer_or_reference ())
2343 {
2344 *argp = value_ind (*argp);
2345 /* Don't coerce fn pointer to fn and then back again! */
2346 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2347 *argp = coerce_array (*argp);
2348 t = check_typedef ((*argp)->type ());
2349 }
2350
2351 if (t->code () != TYPE_CODE_STRUCT
2352 && t->code () != TYPE_CODE_UNION)
2353 error (_("Attempt to extract a component of a value that is not a %s."),
2354 err);
2355
2356 /* Assume it's not, unless we see that it is. */
2357 if (static_memfuncp)
2358 *static_memfuncp = 0;
2359
2360 if (!args.has_value ())
2361 {
2362 /* if there are no arguments ...do this... */
2363
2364 /* Try as a field first, because if we succeed, there is less
2365 work to be done. */
2366 v = search_struct_field (name, *argp, t, 0);
2367 if (v)
2368 return v;
2369
2370 if (current_language->la_language == language_fortran)
2371 {
2372 /* If it is not a field it is the type name of an inherited
2373 structure. */
2374 v = search_struct_field (name, *argp, t, 1);
2375 if (v)
2376 return v;
2377 }
2378
2379 /* C++: If it was not found as a data field, then try to
2380 return it as a pointer to a method. */
2381 v = search_struct_method (name, argp, args, 0,
2382 static_memfuncp, t);
2383
2384 if (v == (struct value *) - 1)
2385 error (_("Cannot take address of method %s."), name);
2386 else if (v == 0)
2387 {
2388 if (TYPE_NFN_FIELDS (t))
2389 error (_("There is no member or method named %s."), name);
2390 else
2391 error (_("There is no member named %s."), name);
2392 }
2393 return v;
2394 }
2395
2396 v = search_struct_method (name, argp, args, 0,
2397 static_memfuncp, t);
2398
2399 if (v == (struct value *) - 1)
2400 {
2401 error (_("One of the arguments you tried to pass to %s could not "
2402 "be converted to what the function wants."), name);
2403 }
2404 else if (v == 0)
2405 {
2406 /* See if user tried to invoke data as function. If so, hand it
2407 back. If it's not callable (i.e., a pointer to function),
2408 gdb should give an error. */
2409 v = search_struct_field (name, *argp, t, 0);
2410 /* If we found an ordinary field, then it is not a method call.
2411 So, treat it as if it were a static member function. */
2412 if (v && static_memfuncp)
2413 *static_memfuncp = 1;
2414 }
2415
2416 if (!v)
2417 throw_error (NOT_FOUND_ERROR,
2418 _("Structure has no component named %s."), name);
2419 return v;
2420 }
2421
2422 /* Given *ARGP, a value of type structure or union, or a pointer/reference
2423 to a structure or union, extract and return its component (field) of
2424 type FTYPE at the specified BITPOS.
2425 Throw an exception on error. */
2426
2427 struct value *
2428 value_struct_elt_bitpos (struct value **argp, int bitpos, struct type *ftype,
2429 const char *err)
2430 {
2431 struct type *t;
2432 int i;
2433
2434 *argp = coerce_array (*argp);
2435
2436 t = check_typedef ((*argp)->type ());
2437
2438 while (t->is_pointer_or_reference ())
2439 {
2440 *argp = value_ind (*argp);
2441 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2442 *argp = coerce_array (*argp);
2443 t = check_typedef ((*argp)->type ());
2444 }
2445
2446 if (t->code () != TYPE_CODE_STRUCT
2447 && t->code () != TYPE_CODE_UNION)
2448 error (_("Attempt to extract a component of a value that is not a %s."),
2449 err);
2450
2451 for (i = TYPE_N_BASECLASSES (t); i < t->num_fields (); i++)
2452 {
2453 if (!t->field (i).is_static ()
2454 && bitpos == t->field (i).loc_bitpos ()
2455 && types_equal (ftype, t->field (i).type ()))
2456 return (*argp)->primitive_field (0, i, t);
2457 }
2458
2459 error (_("No field with matching bitpos and type."));
2460
2461 /* Never hit. */
2462 return NULL;
2463 }
2464
2465 /* Search through the methods of an object (and its bases) to find a
2466 specified method. Return a reference to the fn_field list METHODS of
2467 overloaded instances defined in the source language. If available
2468 and matching, a vector of matching xmethods defined in extension
2469 languages are also returned in XMETHODS.
2470
2471 Helper function for value_find_oload_list.
2472 ARGP is a pointer to a pointer to a value (the object).
2473 METHOD is a string containing the method name.
2474 OFFSET is the offset within the value.
2475 TYPE is the assumed type of the object.
2476 METHODS is a pointer to the matching overloaded instances defined
2477 in the source language. Since this is a recursive function,
2478 *METHODS should be set to NULL when calling this function.
2479 NUM_FNS is the number of overloaded instances. *NUM_FNS should be set to
2480 0 when calling this function.
2481 XMETHODS is the vector of matching xmethod workers. *XMETHODS
2482 should also be set to NULL when calling this function.
2483 BASETYPE is set to the actual type of the subobject where the
2484 method is found.
2485 BOFFSET is the offset of the base subobject where the method is found. */
2486
2487 static void
2488 find_method_list (struct value **argp, const char *method,
2489 LONGEST offset, struct type *type,
2490 gdb::array_view<fn_field> *methods,
2491 std::vector<xmethod_worker_up> *xmethods,
2492 struct type **basetype, LONGEST *boffset)
2493 {
2494 int i;
2495 struct fn_field *f = NULL;
2496
2497 gdb_assert (methods != NULL && xmethods != NULL);
2498 type = check_typedef (type);
2499
2500 /* First check in object itself.
2501 This function is called recursively to search through base classes.
2502 If there is a source method match found at some stage, then we need not
2503 look for source methods in consequent recursive calls. */
2504 if (methods->empty ())
2505 {
2506 for (i = TYPE_NFN_FIELDS (type) - 1; i >= 0; i--)
2507 {
2508 /* pai: FIXME What about operators and type conversions? */
2509 const char *fn_field_name = TYPE_FN_FIELDLIST_NAME (type, i);
2510
2511 if (fn_field_name && (strcmp_iw (fn_field_name, method) == 0))
2512 {
2513 int len = TYPE_FN_FIELDLIST_LENGTH (type, i);
2514 f = TYPE_FN_FIELDLIST1 (type, i);
2515 *methods = gdb::make_array_view (f, len);
2516
2517 *basetype = type;
2518 *boffset = offset;
2519
2520 /* Resolve any stub methods. */
2521 check_stub_method_group (type, i);
2522
2523 break;
2524 }
2525 }
2526 }
2527
2528 /* Unlike source methods, xmethods can be accumulated over successive
2529 recursive calls. In other words, an xmethod named 'm' in a class
2530 will not hide an xmethod named 'm' in its base class(es). We want
2531 it to be this way because xmethods are after all convenience functions
2532 and hence there is no point restricting them with something like method
2533 hiding. Moreover, if hiding is done for xmethods as well, then we will
2534 have to provide a mechanism to un-hide (like the 'using' construct). */
2535 get_matching_xmethod_workers (type, method, xmethods);
2536
2537 /* If source methods are not found in current class, look for them in the
2538 base classes. We also have to go through the base classes to gather
2539 extension methods. */
2540 for (i = TYPE_N_BASECLASSES (type) - 1; i >= 0; i--)
2541 {
2542 LONGEST base_offset;
2543
2544 if (BASETYPE_VIA_VIRTUAL (type, i))
2545 {
2546 base_offset = baseclass_offset (type, i,
2547 (*argp)->contents_for_printing ().data (),
2548 (*argp)->offset () + offset,
2549 (*argp)->address (), *argp);
2550 }
2551 else /* Non-virtual base, simply use bit position from debug
2552 info. */
2553 {
2554 base_offset = TYPE_BASECLASS_BITPOS (type, i) / 8;
2555 }
2556
2557 find_method_list (argp, method, base_offset + offset,
2558 TYPE_BASECLASS (type, i), methods,
2559 xmethods, basetype, boffset);
2560 }
2561 }
2562
2563 /* Return the list of overloaded methods of a specified name. The methods
2564 could be those GDB finds in the binary, or xmethod. Methods found in
2565 the binary are returned in METHODS, and xmethods are returned in
2566 XMETHODS.
2567
2568 ARGP is a pointer to a pointer to a value (the object).
2569 METHOD is the method name.
2570 OFFSET is the offset within the value contents.
2571 METHODS is the list of matching overloaded instances defined in
2572 the source language.
2573 XMETHODS is the vector of matching xmethod workers defined in
2574 extension languages.
2575 BASETYPE is set to the type of the base subobject that defines the
2576 method.
2577 BOFFSET is the offset of the base subobject which defines the method. */
2578
2579 static void
2580 value_find_oload_method_list (struct value **argp, const char *method,
2581 LONGEST offset,
2582 gdb::array_view<fn_field> *methods,
2583 std::vector<xmethod_worker_up> *xmethods,
2584 struct type **basetype, LONGEST *boffset)
2585 {
2586 struct type *t;
2587
2588 t = check_typedef ((*argp)->type ());
2589
2590 /* Code snarfed from value_struct_elt. */
2591 while (t->is_pointer_or_reference ())
2592 {
2593 *argp = value_ind (*argp);
2594 /* Don't coerce fn pointer to fn and then back again! */
2595 if (check_typedef ((*argp)->type ())->code () != TYPE_CODE_FUNC)
2596 *argp = coerce_array (*argp);
2597 t = check_typedef ((*argp)->type ());
2598 }
2599
2600 if (t->code () != TYPE_CODE_STRUCT
2601 && t->code () != TYPE_CODE_UNION)
2602 error (_("Attempt to extract a component of a "
2603 "value that is not a struct or union"));
2604
2605 gdb_assert (methods != NULL && xmethods != NULL);
2606
2607 /* Clear the lists. */
2608 *methods = {};
2609 xmethods->clear ();
2610
2611 find_method_list (argp, method, 0, t, methods, xmethods,
2612 basetype, boffset);
2613 }
2614
2615 /* Helper function for find_overload_match. If no matches were
2616 found, this function may generate a hint for the user that some
2617 of the relevant types are incomplete, so GDB can't evaluate
2618 type relationships to properly evaluate overloads.
2619
2620 If no incomplete types are present, an empty string is returned. */
2621 static std::string
2622 incomplete_type_hint (gdb::array_view<value *> args)
2623 {
2624 int incomplete_types = 0;
2625 std::string incomplete_arg_names;
2626 for (const struct value *arg : args)
2627 {
2628 struct type *t = arg->type ();
2629 while (t->code () == TYPE_CODE_PTR)
2630 t = t->target_type ();
2631 if (t->is_stub ())
2632 {
2633 string_file buffer;
2634 if (incomplete_types > 0)
2635 incomplete_arg_names += ", ";
2636
2637 current_language->print_type (arg->type (), "", &buffer,
2638 -1, 0, &type_print_raw_options);
2639
2640 incomplete_types++;
2641 incomplete_arg_names += buffer.string ();
2642 }
2643 }
2644 std::string hint;
2645 if (incomplete_types > 1)
2646 hint = string_printf (_("\nThe types: '%s' aren't fully known to GDB."
2647 " Please cast them directly to the desired"
2648 " typed in the function call."),
2649 incomplete_arg_names.c_str ());
2650 else if (incomplete_types == 1)
2651 hint = string_printf (_("\nThe type: '%s' isn't fully known to GDB."
2652 " Please cast it directly to the desired"
2653 " typed in the function call."),
2654 incomplete_arg_names.c_str ());
2655 return hint;
2656 }
2657
2658 /* Given an array of arguments (ARGS) (which includes an entry for
2659 "this" in the case of C++ methods), the NAME of a function, and
2660 whether it's a method or not (METHOD), find the best function that
2661 matches on the argument types according to the overload resolution
2662 rules.
2663
2664 METHOD can be one of three values:
2665 NON_METHOD for non-member functions.
2666 METHOD: for member functions.
2667 BOTH: used for overload resolution of operators where the
2668 candidates are expected to be either member or non member
2669 functions. In this case the first argument ARGTYPES
2670 (representing 'this') is expected to be a reference to the
2671 target object, and will be dereferenced when attempting the
2672 non-member search.
2673
2674 In the case of class methods, the parameter OBJ is an object value
2675 in which to search for overloaded methods.
2676
2677 In the case of non-method functions, the parameter FSYM is a symbol
2678 corresponding to one of the overloaded functions.
2679
2680 Return value is an integer: 0 -> good match, 10 -> debugger applied
2681 non-standard coercions, 100 -> incompatible.
2682
2683 If a method is being searched for, VALP will hold the value.
2684 If a non-method is being searched for, SYMP will hold the symbol
2685 for it.
2686
2687 If a method is being searched for, and it is a static method,
2688 then STATICP will point to a non-zero value.
2689
2690 If NO_ADL argument dependent lookup is disabled. This is used to prevent
2691 ADL overload candidates when performing overload resolution for a fully
2692 qualified name.
2693
2694 If NOSIDE is EVAL_AVOID_SIDE_EFFECTS, then OBJP's memory cannot be
2695 read while picking the best overload match (it may be all zeroes and thus
2696 not have a vtable pointer), in which case skip virtual function lookup.
2697 This is ok as typically EVAL_AVOID_SIDE_EFFECTS is only used to determine
2698 the result type.
2699
2700 Note: This function does *not* check the value of
2701 overload_resolution. Caller must check it to see whether overload
2702 resolution is permitted. */
2703
2704 int
2705 find_overload_match (gdb::array_view<value *> args,
2706 const char *name, enum oload_search_type method,
2707 struct value **objp, struct symbol *fsym,
2708 struct value **valp, struct symbol **symp,
2709 int *staticp, const int no_adl,
2710 const enum noside noside)
2711 {
2712 struct value *obj = (objp ? *objp : NULL);
2713 struct type *obj_type = obj ? obj->type () : NULL;
2714 /* Index of best overloaded function. */
2715 int func_oload_champ = -1;
2716 int method_oload_champ = -1;
2717 int src_method_oload_champ = -1;
2718 int ext_method_oload_champ = -1;
2719
2720 /* The measure for the current best match. */
2721 badness_vector method_badness;
2722 badness_vector func_badness;
2723 badness_vector ext_method_badness;
2724 badness_vector src_method_badness;
2725
2726 struct value *temp = obj;
2727 /* For methods, the list of overloaded methods. */
2728 gdb::array_view<fn_field> methods;
2729 /* For non-methods, the list of overloaded function symbols. */
2730 std::vector<symbol *> functions;
2731 /* For xmethods, the vector of xmethod workers. */
2732 std::vector<xmethod_worker_up> xmethods;
2733 struct type *basetype = NULL;
2734 LONGEST boffset;
2735
2736 const char *obj_type_name = NULL;
2737 const char *func_name = NULL;
2738 gdb::unique_xmalloc_ptr<char> temp_func;
2739 enum oload_classification match_quality;
2740 enum oload_classification method_match_quality = INCOMPATIBLE;
2741 enum oload_classification src_method_match_quality = INCOMPATIBLE;
2742 enum oload_classification ext_method_match_quality = INCOMPATIBLE;
2743 enum oload_classification func_match_quality = INCOMPATIBLE;
2744
2745 /* Get the list of overloaded methods or functions. */
2746 if (method == METHOD || method == BOTH)
2747 {
2748 gdb_assert (obj);
2749
2750 /* OBJ may be a pointer value rather than the object itself. */
2751 obj = coerce_ref (obj);
2752 while (check_typedef (obj->type ())->code () == TYPE_CODE_PTR)
2753 obj = coerce_ref (value_ind (obj));
2754 obj_type_name = obj->type ()->name ();
2755
2756 /* First check whether this is a data member, e.g. a pointer to
2757 a function. */
2758 if (check_typedef (obj->type ())->code () == TYPE_CODE_STRUCT)
2759 {
2760 *valp = search_struct_field (name, obj,
2761 check_typedef (obj->type ()), 0);
2762 if (*valp)
2763 {
2764 *staticp = 1;
2765 return 0;
2766 }
2767 }
2768
2769 /* Retrieve the list of methods with the name NAME. */
2770 value_find_oload_method_list (&temp, name, 0, &methods,
2771 &xmethods, &basetype, &boffset);
2772 /* If this is a method only search, and no methods were found
2773 the search has failed. */
2774 if (method == METHOD && methods.empty () && xmethods.empty ())
2775 error (_("Couldn't find method %s%s%s"),
2776 obj_type_name,
2777 (obj_type_name && *obj_type_name) ? "::" : "",
2778 name);
2779 /* If we are dealing with stub method types, they should have
2780 been resolved by find_method_list via
2781 value_find_oload_method_list above. */
2782 if (!methods.empty ())
2783 {
2784 gdb_assert (TYPE_SELF_TYPE (methods[0].type) != NULL);
2785
2786 src_method_oload_champ
2787 = find_oload_champ (args,
2788 methods.size (),
2789 methods.data (), NULL, NULL,
2790 &src_method_badness);
2791
2792 src_method_match_quality = classify_oload_match
2793 (src_method_badness, args.size (),
2794 oload_method_static_p (methods.data (), src_method_oload_champ));
2795 }
2796
2797 if (!xmethods.empty ())
2798 {
2799 ext_method_oload_champ
2800 = find_oload_champ (args,
2801 xmethods.size (),
2802 NULL, xmethods.data (), NULL,
2803 &ext_method_badness);
2804 ext_method_match_quality = classify_oload_match (ext_method_badness,
2805 args.size (), 0);
2806 }
2807
2808 if (src_method_oload_champ >= 0 && ext_method_oload_champ >= 0)
2809 {
2810 switch (compare_badness (ext_method_badness, src_method_badness))
2811 {
2812 case 0: /* Src method and xmethod are equally good. */
2813 /* If src method and xmethod are equally good, then
2814 xmethod should be the winner. Hence, fall through to the
2815 case where a xmethod is better than the source
2816 method, except when the xmethod match quality is
2817 non-standard. */
2818 [[fallthrough]];
2819 case 1: /* Src method and ext method are incompatible. */
2820 /* If ext method match is not standard, then let source method
2821 win. Otherwise, fallthrough to let xmethod win. */
2822 if (ext_method_match_quality != STANDARD)
2823 {
2824 method_oload_champ = src_method_oload_champ;
2825 method_badness = src_method_badness;
2826 ext_method_oload_champ = -1;
2827 method_match_quality = src_method_match_quality;
2828 break;
2829 }
2830 [[fallthrough]];
2831 case 2: /* Ext method is champion. */
2832 method_oload_champ = ext_method_oload_champ;
2833 method_badness = ext_method_badness;
2834 src_method_oload_champ = -1;
2835 method_match_quality = ext_method_match_quality;
2836 break;
2837 case 3: /* Src method is champion. */
2838 method_oload_champ = src_method_oload_champ;
2839 method_badness = src_method_badness;
2840 ext_method_oload_champ = -1;
2841 method_match_quality = src_method_match_quality;
2842 break;
2843 default:
2844 gdb_assert_not_reached ("Unexpected overload comparison "
2845 "result");
2846 break;
2847 }
2848 }
2849 else if (src_method_oload_champ >= 0)
2850 {
2851 method_oload_champ = src_method_oload_champ;
2852 method_badness = src_method_badness;
2853 method_match_quality = src_method_match_quality;
2854 }
2855 else if (ext_method_oload_champ >= 0)
2856 {
2857 method_oload_champ = ext_method_oload_champ;
2858 method_badness = ext_method_badness;
2859 method_match_quality = ext_method_match_quality;
2860 }
2861 }
2862
2863 if (method == NON_METHOD || method == BOTH)
2864 {
2865 const char *qualified_name = NULL;
2866
2867 /* If the overload match is being search for both as a method
2868 and non member function, the first argument must now be
2869 dereferenced. */
2870 if (method == BOTH)
2871 args[0] = value_ind (args[0]);
2872
2873 if (fsym)
2874 {
2875 qualified_name = fsym->natural_name ();
2876
2877 /* If we have a function with a C++ name, try to extract just
2878 the function part. Do not try this for non-functions (e.g.
2879 function pointers). */
2880 if (qualified_name
2881 && (check_typedef (fsym->type ())->code ()
2882 == TYPE_CODE_FUNC))
2883 {
2884 temp_func = cp_func_name (qualified_name);
2885
2886 /* If cp_func_name did not remove anything, the name of the
2887 symbol did not include scope or argument types - it was
2888 probably a C-style function. */
2889 if (temp_func != nullptr)
2890 {
2891 if (strcmp (temp_func.get (), qualified_name) == 0)
2892 func_name = NULL;
2893 else
2894 func_name = temp_func.get ();
2895 }
2896 }
2897 }
2898 else
2899 {
2900 func_name = name;
2901 qualified_name = name;
2902 }
2903
2904 /* If there was no C++ name, this must be a C-style function or
2905 not a function at all. Just return the same symbol. Do the
2906 same if cp_func_name fails for some reason. */
2907 if (func_name == NULL)
2908 {
2909 *symp = fsym;
2910 return 0;
2911 }
2912
2913 func_oload_champ = find_oload_champ_namespace (args,
2914 func_name,
2915 qualified_name,
2916 &functions,
2917 &func_badness,
2918 no_adl);
2919
2920 if (func_oload_champ >= 0)
2921 func_match_quality = classify_oload_match (func_badness,
2922 args.size (), 0);
2923 }
2924
2925 /* Did we find a match ? */
2926 if (method_oload_champ == -1 && func_oload_champ == -1)
2927 throw_error (NOT_FOUND_ERROR,
2928 _("No symbol \"%s\" in current context."),
2929 name);
2930
2931 /* If we have found both a method match and a function
2932 match, find out which one is better, and calculate match
2933 quality. */
2934 if (method_oload_champ >= 0 && func_oload_champ >= 0)
2935 {
2936 switch (compare_badness (func_badness, method_badness))
2937 {
2938 case 0: /* Top two contenders are equally good. */
2939 /* FIXME: GDB does not support the general ambiguous case.
2940 All candidates should be collected and presented the
2941 user. */
2942 error (_("Ambiguous overload resolution"));
2943 break;
2944 case 1: /* Incomparable top contenders. */
2945 /* This is an error incompatible candidates
2946 should not have been proposed. */
2947 error (_("Internal error: incompatible "
2948 "overload candidates proposed"));
2949 break;
2950 case 2: /* Function champion. */
2951 method_oload_champ = -1;
2952 match_quality = func_match_quality;
2953 break;
2954 case 3: /* Method champion. */
2955 func_oload_champ = -1;
2956 match_quality = method_match_quality;
2957 break;
2958 default:
2959 error (_("Internal error: unexpected overload comparison result"));
2960 break;
2961 }
2962 }
2963 else
2964 {
2965 /* We have either a method match or a function match. */
2966 if (method_oload_champ >= 0)
2967 match_quality = method_match_quality;
2968 else
2969 match_quality = func_match_quality;
2970 }
2971
2972 if (match_quality == INCOMPATIBLE)
2973 {
2974 std::string hint = incomplete_type_hint (args);
2975 if (method == METHOD)
2976 error (_("Cannot resolve method %s%s%s to any overloaded instance%s"),
2977 obj_type_name,
2978 (obj_type_name && *obj_type_name) ? "::" : "",
2979 name, hint.c_str ());
2980 else
2981 error (_("Cannot resolve function %s to any overloaded instance%s"),
2982 func_name, hint.c_str ());
2983 }
2984 else if (match_quality == NON_STANDARD)
2985 {
2986 if (method == METHOD)
2987 warning (_("Using non-standard conversion to match "
2988 "method %s%s%s to supplied arguments"),
2989 obj_type_name,
2990 (obj_type_name && *obj_type_name) ? "::" : "",
2991 name);
2992 else
2993 warning (_("Using non-standard conversion to match "
2994 "function %s to supplied arguments"),
2995 func_name);
2996 }
2997
2998 if (staticp != NULL)
2999 *staticp = oload_method_static_p (methods.data (), method_oload_champ);
3000
3001 if (method_oload_champ >= 0)
3002 {
3003 if (src_method_oload_champ >= 0)
3004 {
3005 if (TYPE_FN_FIELD_VIRTUAL_P (methods, method_oload_champ)
3006 && noside != EVAL_AVOID_SIDE_EFFECTS)
3007 {
3008 *valp = value_virtual_fn_field (&temp, methods.data (),
3009 method_oload_champ, basetype,
3010 boffset);
3011 }
3012 else
3013 *valp = value_fn_field (&temp, methods.data (),
3014 method_oload_champ, basetype, boffset);
3015 }
3016 else
3017 *valp = value::from_xmethod
3018 (std::move (xmethods[ext_method_oload_champ]));
3019 }
3020 else
3021 *symp = functions[func_oload_champ];
3022
3023 if (objp)
3024 {
3025 struct type *temp_type = check_typedef (temp->type ());
3026 struct type *objtype = check_typedef (obj_type);
3027
3028 if (temp_type->code () != TYPE_CODE_PTR
3029 && objtype->is_pointer_or_reference ())
3030 {
3031 temp = value_addr (temp);
3032 }
3033 *objp = temp;
3034 }
3035
3036 switch (match_quality)
3037 {
3038 case INCOMPATIBLE:
3039 return 100;
3040 case NON_STANDARD:
3041 return 10;
3042 default: /* STANDARD */
3043 return 0;
3044 }
3045 }
3046
3047 /* Find the best overload match, searching for FUNC_NAME in namespaces
3048 contained in QUALIFIED_NAME until it either finds a good match or
3049 runs out of namespaces. It stores the overloaded functions in
3050 *OLOAD_SYMS, and the badness vector in *OLOAD_CHAMP_BV. If NO_ADL,
3051 argument dependent lookup is not performed. */
3052
3053 static int
3054 find_oload_champ_namespace (gdb::array_view<value *> args,
3055 const char *func_name,
3056 const char *qualified_name,
3057 std::vector<symbol *> *oload_syms,
3058 badness_vector *oload_champ_bv,
3059 const int no_adl)
3060 {
3061 int oload_champ;
3062
3063 find_oload_champ_namespace_loop (args,
3064 func_name,
3065 qualified_name, 0,
3066 oload_syms, oload_champ_bv,
3067 &oload_champ,
3068 no_adl);
3069
3070 return oload_champ;
3071 }
3072
3073 /* Helper function for find_oload_champ_namespace; NAMESPACE_LEN is
3074 how deep we've looked for namespaces, and the champ is stored in
3075 OLOAD_CHAMP. The return value is 1 if the champ is a good one, 0
3076 if it isn't. Other arguments are the same as in
3077 find_oload_champ_namespace. */
3078
3079 static int
3080 find_oload_champ_namespace_loop (gdb::array_view<value *> args,
3081 const char *func_name,
3082 const char *qualified_name,
3083 int namespace_len,
3084 std::vector<symbol *> *oload_syms,
3085 badness_vector *oload_champ_bv,
3086 int *oload_champ,
3087 const int no_adl)
3088 {
3089 int next_namespace_len = namespace_len;
3090 int searched_deeper = 0;
3091 int new_oload_champ;
3092 char *new_namespace;
3093
3094 if (next_namespace_len != 0)
3095 {
3096 gdb_assert (qualified_name[next_namespace_len] == ':');
3097 next_namespace_len += 2;
3098 }
3099 next_namespace_len +=
3100 cp_find_first_component (qualified_name + next_namespace_len);
3101
3102 /* First, see if we have a deeper namespace we can search in.
3103 If we get a good match there, use it. */
3104
3105 if (qualified_name[next_namespace_len] == ':')
3106 {
3107 searched_deeper = 1;
3108
3109 if (find_oload_champ_namespace_loop (args,
3110 func_name, qualified_name,
3111 next_namespace_len,
3112 oload_syms, oload_champ_bv,
3113 oload_champ, no_adl))
3114 {
3115 return 1;
3116 }
3117 };
3118
3119 /* If we reach here, either we're in the deepest namespace or we
3120 didn't find a good match in a deeper namespace. But, in the
3121 latter case, we still have a bad match in a deeper namespace;
3122 note that we might not find any match at all in the current
3123 namespace. (There's always a match in the deepest namespace,
3124 because this overload mechanism only gets called if there's a
3125 function symbol to start off with.) */
3126
3127 new_namespace = (char *) alloca (namespace_len + 1);
3128 strncpy (new_namespace, qualified_name, namespace_len);
3129 new_namespace[namespace_len] = '\0';
3130
3131 std::vector<symbol *> new_oload_syms
3132 = make_symbol_overload_list (func_name, new_namespace);
3133
3134 /* If we have reached the deepest level perform argument
3135 determined lookup. */
3136 if (!searched_deeper && !no_adl)
3137 {
3138 int ix;
3139 struct type **arg_types;
3140
3141 /* Prepare list of argument types for overload resolution. */
3142 arg_types = (struct type **)
3143 alloca (args.size () * (sizeof (struct type *)));
3144 for (ix = 0; ix < args.size (); ix++)
3145 arg_types[ix] = args[ix]->type ();
3146 add_symbol_overload_list_adl ({arg_types, args.size ()}, func_name,
3147 &new_oload_syms);
3148 }
3149
3150 badness_vector new_oload_champ_bv;
3151 new_oload_champ = find_oload_champ (args,
3152 new_oload_syms.size (),
3153 NULL, NULL, new_oload_syms.data (),
3154 &new_oload_champ_bv);
3155
3156 /* Case 1: We found a good match. Free earlier matches (if any),
3157 and return it. Case 2: We didn't find a good match, but we're
3158 not the deepest function. Then go with the bad match that the
3159 deeper function found. Case 3: We found a bad match, and we're
3160 the deepest function. Then return what we found, even though
3161 it's a bad match. */
3162
3163 if (new_oload_champ != -1
3164 && classify_oload_match (new_oload_champ_bv, args.size (), 0) == STANDARD)
3165 {
3166 *oload_syms = std::move (new_oload_syms);
3167 *oload_champ = new_oload_champ;
3168 *oload_champ_bv = std::move (new_oload_champ_bv);
3169 return 1;
3170 }
3171 else if (searched_deeper)
3172 {
3173 return 0;
3174 }
3175 else
3176 {
3177 *oload_syms = std::move (new_oload_syms);
3178 *oload_champ = new_oload_champ;
3179 *oload_champ_bv = std::move (new_oload_champ_bv);
3180 return 0;
3181 }
3182 }
3183
3184 /* Look for a function to take ARGS. Find the best match from among
3185 the overloaded methods or functions given by METHODS or FUNCTIONS
3186 or XMETHODS, respectively. One, and only one of METHODS, FUNCTIONS
3187 and XMETHODS can be non-NULL.
3188
3189 NUM_FNS is the length of the array pointed at by METHODS, FUNCTIONS
3190 or XMETHODS, whichever is non-NULL.
3191
3192 Return the index of the best match; store an indication of the
3193 quality of the match in OLOAD_CHAMP_BV. */
3194
3195 static int
3196 find_oload_champ (gdb::array_view<value *> args,
3197 size_t num_fns,
3198 fn_field *methods,
3199 xmethod_worker_up *xmethods,
3200 symbol **functions,
3201 badness_vector *oload_champ_bv)
3202 {
3203 /* A measure of how good an overloaded instance is. */
3204 badness_vector bv;
3205 /* Index of best overloaded function. */
3206 int oload_champ = -1;
3207 /* Current ambiguity state for overload resolution. */
3208 int oload_ambiguous = 0;
3209 /* 0 => no ambiguity, 1 => two good funcs, 2 => incomparable funcs. */
3210
3211 /* A champion can be found among methods alone, or among functions
3212 alone, or in xmethods alone, but not in more than one of these
3213 groups. */
3214 gdb_assert ((methods != NULL) + (functions != NULL) + (xmethods != NULL)
3215 == 1);
3216
3217 /* Consider each candidate in turn. */
3218 for (size_t ix = 0; ix < num_fns; ix++)
3219 {
3220 int jj;
3221 int static_offset = 0;
3222 bool varargs = false;
3223 std::vector<type *> parm_types;
3224
3225 if (xmethods != NULL)
3226 parm_types = xmethods[ix]->get_arg_types ();
3227 else
3228 {
3229 size_t nparms;
3230
3231 if (methods != NULL)
3232 {
3233 nparms = TYPE_FN_FIELD_TYPE (methods, ix)->num_fields ();
3234 static_offset = oload_method_static_p (methods, ix);
3235 varargs = TYPE_FN_FIELD_TYPE (methods, ix)->has_varargs ();
3236 }
3237 else
3238 {
3239 nparms = functions[ix]->type ()->num_fields ();
3240 varargs = functions[ix]->type ()->has_varargs ();
3241 }
3242
3243 parm_types.reserve (nparms);
3244 for (jj = 0; jj < nparms; jj++)
3245 {
3246 type *t = (methods != NULL
3247 ? (TYPE_FN_FIELD_ARGS (methods, ix)[jj].type ())
3248 : functions[ix]->type ()->field (jj).type ());
3249 parm_types.push_back (t);
3250 }
3251 }
3252
3253 /* Compare parameter types to supplied argument types. Skip
3254 THIS for static methods. */
3255 bv = rank_function (parm_types,
3256 args.slice (static_offset),
3257 varargs);
3258
3259 if (overload_debug)
3260 {
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 ());
3275
3276 gdb_printf (gdb_stderr,
3277 "...Badness of length : {%d, %d}\n",
3278 bv[0].rank, bv[0].subrank);
3279
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);
3284 }
3285
3286 if (oload_champ_bv->empty ())
3287 {
3288 *oload_champ_bv = std::move (bv);
3289 oload_champ = 0;
3290 }
3291 else /* See whether current candidate is better or worse than
3292 previous best. */
3293 switch (compare_badness (bv, *oload_champ_bv))
3294 {
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;
3309 }
3310 if (overload_debug)
3311 gdb_printf (gdb_stderr, "Overload resolution "
3312 "champion is %d, ambiguous? %d\n",
3313 oload_champ, oload_ambiguous);
3314 }
3315
3316 return oload_champ;
3317 }
3318
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. */
3321
3322 static int
3323 oload_method_static_p (struct fn_field *fns_ptr, int index)
3324 {
3325 if (fns_ptr && index >= 0 && TYPE_FN_FIELD_STATIC_P (fns_ptr, index))
3326 return 1;
3327 else
3328 return 0;
3329 }
3330
3331 /* Check how good an overload match OLOAD_CHAMP_BV represents. */
3332
3333 static enum oload_classification
3334 classify_oload_match (const badness_vector &oload_champ_bv,
3335 int nargs,
3336 int static_offset)
3337 {
3338 int ix;
3339 enum oload_classification worst = STANDARD;
3340
3341 for (ix = 1; ix <= nargs - static_offset; ix++)
3342 {
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. */
3354 }
3355
3356 /* If no INCOMPATIBLE classification was found, return the worst one
3357 that was found (if any). */
3358 return worst;
3359 }
3360
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. */
3365
3366 int
3367 destructor_name_p (const char *name, struct type *type)
3368 {
3369 if (name[0] == '~')
3370 {
3371 const char *dname = type_name_or_error (type);
3372 const char *cp = strchr (dname, '<');
3373 unsigned int len;
3374
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;
3384 }
3385 return 0;
3386 }
3387
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. */
3391
3392 static struct value *
3393 enum_constant_from_type (struct type *type, const char *name)
3394 {
3395 int i;
3396 int name_len = strlen (name);
3397
3398 gdb_assert (type->code () == TYPE_CODE_ENUM
3399 && type->is_declared_class ());
3400
3401 for (i = TYPE_N_BASECLASSES (type); i < type->num_fields (); ++i)
3402 {
3403 const char *fname = type->field (i).name ();
3404 int len;
3405
3406 if (type->field (i).loc_kind () != FIELD_LOC_KIND_ENUMVAL
3407 || fname == NULL)
3408 continue;
3409
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 ());
3418 }
3419
3420 error (_("no constant named \"%s\" in enum \"%s\""),
3421 name, type->name ());
3422 }
3423
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. */
3429
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)
3434 {
3435 switch (curtype->code ())
3436 {
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);
3445
3446 case TYPE_CODE_ENUM:
3447 return enum_constant_from_type (curtype, name);
3448
3449 default:
3450 internal_error (_("non-aggregate type in value_aggregate_elt"));
3451 }
3452 }
3453
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.
3460
3461 The type T2 is expected to have come from make_params (in eval.c). */
3462
3463 static int
3464 compare_parameters (struct type *t1, struct type *t2, int skip_artificial)
3465 {
3466 int start = 0;
3467
3468 if (t1->num_fields () > 0 && t1->field (0).is_artificial ())
3469 ++start;
3470
3471 /* If skipping artificial fields, find the first real field
3472 in T1. */
3473 if (skip_artificial)
3474 {
3475 while (start < t1->num_fields ()
3476 && t1->field (start).is_artificial ())
3477 ++start;
3478 }
3479
3480 /* Now compare parameters. */
3481
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;
3487
3488 if ((t1->num_fields () - start) == t2->num_fields ())
3489 {
3490 int i;
3491
3492 for (i = 0; i < t2->num_fields (); ++i)
3493 {
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;
3498 }
3499
3500 return 1;
3501 }
3502
3503 return 0;
3504 }
3505
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. */
3512
3513 static bool
3514 get_baseclass_offset (struct type *vt, struct type *cls,
3515 struct value *v, int *boffs, bool *isvirt)
3516 {
3517 for (int i = 0; i < TYPE_N_BASECLASSES (vt); i++)
3518 {
3519 struct type *t = vt->field (i).type ();
3520 if (types_equal (t, cls))
3521 {
3522 if (BASETYPE_VIA_VIRTUAL (vt, i))
3523 {
3524 const gdb_byte *adr = v->contents_for_printing ().data ();
3525 *boffs = baseclass_offset (vt, i, adr, v->offset (),
3526 value_as_long (v), v);
3527 *isvirt = true;
3528 }
3529 else
3530 *isvirt = false;
3531 return true;
3532 }
3533
3534 if (get_baseclass_offset (check_typedef (t), cls, v, boffs, isvirt))
3535 {
3536 if (*isvirt == false) /* Add non-virtual base offset. */
3537 {
3538 const gdb_byte *adr = v->contents_for_printing ().data ();
3539 *boffs += baseclass_offset (vt, i, adr, v->offset (),
3540 value_as_long (v), v);
3541 }
3542 return true;
3543 }
3544 }
3545
3546 return false;
3547 }
3548
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". */
3555
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)
3562 {
3563 struct type *t = check_typedef (curtype);
3564 int i;
3565 struct value *result;
3566
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"));
3571
3572 for (i = t->num_fields () - 1; i >= TYPE_N_BASECLASSES (t); i--)
3573 {
3574 const char *t_field_name = t->field (i).name ();
3575
3576 if (t_field_name && strcmp (t_field_name, name) == 0)
3577 {
3578 if (t->field (i).is_static ())
3579 {
3580 struct value *v = value_static_field (t, i);
3581 if (want_address)
3582 v = value_addr (v);
3583 return v;
3584 }
3585 if (t->field (i).is_packed ())
3586 error (_("pointers to bitfield members not allowed"));
3587
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 value::allocate (t->field (i).type ());
3594 else
3595 {
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)
3601 {
3602 struct value *ptr, *this_v = v;
3603 long mem_offset;
3604 struct type *type, *tmp;
3605
3606 ptr = value_aggregate_elt (domain, name, NULL, 1, noside);
3607 type = check_typedef (ptr->type ());
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)
3614 {
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
3623 {
3624 struct type *p = check_typedef (this_v->type ());
3625 p = check_typedef (p->target_type ());
3626 if (get_baseclass_offset (p, curtype, this_v,
3627 &boff, &isvirt))
3628 mem_offset += boff;
3629 }
3630 }
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);
3635 }
3636
3637 error (_("Cannot reference non-static field \"%s\""), name);
3638 }
3639 }
3640 }
3641
3642 /* C++: If it was not found as a data field, then try to return it
3643 as a pointer to a method. */
3644
3645 /* Perform all necessary dereferencing. */
3646 while (intype && intype->code () == TYPE_CODE_PTR)
3647 intype = intype->target_type ();
3648
3649 for (i = TYPE_NFN_FIELDS (t) - 1; i >= 0; --i)
3650 {
3651 const char *t_field_name = TYPE_FN_FIELDLIST_NAME (t, i);
3652
3653 if (t_field_name && strcmp (t_field_name, name) == 0)
3654 {
3655 int j;
3656 int len = TYPE_FN_FIELDLIST_LENGTH (t, i);
3657 struct fn_field *f = TYPE_FN_FIELDLIST1 (t, i);
3658
3659 check_stub_method_group (t, i);
3660
3661 if (intype)
3662 {
3663 for (j = 0; j < len; ++j)
3664 {
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;
3669
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;
3674 }
3675
3676 if (j == len)
3677 error (_("no member function matches "
3678 "that type instantiation"));
3679 }
3680 else
3681 {
3682 int ii;
3683
3684 j = -1;
3685 for (ii = 0; ii < len; ++ii)
3686 {
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))
3694 {
3695 if (j == -1)
3696 j = ii;
3697 continue;
3698 }
3699
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);
3705
3706 j = ii;
3707 }
3708
3709 if (j == -1)
3710 error (_("no matching member function"));
3711 }
3712
3713 if (TYPE_FN_FIELD_STATIC_P (f, j))
3714 {
3715 struct symbol *s =
3716 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3717 0, SEARCH_FUNCTION_DOMAIN, 0).symbol;
3718
3719 if (s == NULL)
3720 return NULL;
3721
3722 if (want_address)
3723 return value_addr (read_var_value (s, 0, 0));
3724 else
3725 return read_var_value (s, 0, 0);
3726 }
3727
3728 if (TYPE_FN_FIELD_VIRTUAL_P (f, j))
3729 {
3730 if (want_address)
3731 {
3732 result = value::allocate
3733 (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3734 cplus_make_method_ptr (result->type (),
3735 result->contents_writeable ().data (),
3736 TYPE_FN_FIELD_VOFFSET (f, j), 1);
3737 }
3738 else if (noside == EVAL_AVOID_SIDE_EFFECTS)
3739 return value::allocate (TYPE_FN_FIELD_TYPE (f, j));
3740 else
3741 error (_("Cannot reference virtual member function \"%s\""),
3742 name);
3743 }
3744 else
3745 {
3746 struct symbol *s =
3747 lookup_symbol (TYPE_FN_FIELD_PHYSNAME (f, j),
3748 0, SEARCH_FUNCTION_DOMAIN, 0).symbol;
3749
3750 if (s == NULL)
3751 return NULL;
3752
3753 struct value *v = read_var_value (s, 0, 0);
3754 if (!want_address)
3755 result = v;
3756 else
3757 {
3758 result = value::allocate (lookup_methodptr_type (TYPE_FN_FIELD_TYPE (f, j)));
3759 cplus_make_method_ptr (result->type (),
3760 result->contents_writeable ().data (),
3761 v->address (), 0);
3762 }
3763 }
3764 return result;
3765 }
3766 }
3767 for (i = TYPE_N_BASECLASSES (t) - 1; i >= 0; i--)
3768 {
3769 struct value *v;
3770 int base_offset;
3771
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;
3783 }
3784
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. */
3788
3789 return value_maybe_namespace_elt (curtype, name,
3790 want_address, noside);
3791 }
3792
3793 /* C++: Return the member NAME of the namespace given by the type
3794 CURTYPE. */
3795
3796 static struct value *
3797 value_namespace_elt (const struct type *curtype,
3798 const char *name, int want_address,
3799 enum noside noside)
3800 {
3801 struct value *retval = value_maybe_namespace_elt (curtype, name,
3802 want_address,
3803 noside);
3804
3805 if (retval == NULL)
3806 error (_("No symbol \"%s\" in namespace \"%s\"."),
3807 name, curtype->name ());
3808
3809 return retval;
3810 }
3811
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). */
3817
3818 static struct value *
3819 value_maybe_namespace_elt (const struct type *curtype,
3820 const char *name, int want_address,
3821 enum noside noside)
3822 {
3823 const char *namespace_name = curtype->name ();
3824 struct block_symbol sym;
3825 struct value *result;
3826
3827 sym = cp_lookup_symbol_namespace (namespace_name, name,
3828 get_selected_block (0), SEARCH_VFT);
3829
3830 if (sym.symbol == NULL)
3831 return NULL;
3832 else if ((noside == EVAL_AVOID_SIDE_EFFECTS)
3833 && (sym.symbol->aclass () == LOC_TYPEDEF))
3834 result = value::allocate (sym.symbol->type ());
3835 else
3836 result = value_of_variable (sym.symbol, sym.block);
3837
3838 if (want_address)
3839 result = value_addr (result);
3840
3841 return result;
3842 }
3843
3844 /* Given a pointer or a reference value V, find its real (RTTI) type.
3845
3846 Other parameters FULL, TOP, USING_ENC as with value_rtti_type()
3847 and refer to the values computed for the object pointed to. */
3848
3849 struct type *
3850 value_rtti_indirect_type (struct value *v, int *full,
3851 LONGEST *top, int *using_enc)
3852 {
3853 struct value *target = NULL;
3854 struct type *type, *real_type, *target_type;
3855
3856 type = v->type ();
3857 type = check_typedef (type);
3858 if (TYPE_IS_REFERENCE (type))
3859 target = coerce_ref (v);
3860 else if (type->code () == TYPE_CODE_PTR)
3861 {
3862
3863 try
3864 {
3865 target = value_ind (v);
3866 }
3867 catch (const gdb_exception_error &except)
3868 {
3869 if (except.error == MEMORY_ERROR)
3870 {
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;
3875 }
3876 throw;
3877 }
3878 }
3879 else
3880 return NULL;
3881
3882 real_type = value_rtti_type (target, full, top, using_enc);
3883
3884 if (real_type)
3885 {
3886 /* Copy qualifiers to the referenced object. */
3887 target_type = target->type ();
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."));
3896
3897 /* Copy qualifiers to the pointer/reference. */
3898 real_type = make_cv_type (TYPE_CONST (type), TYPE_VOLATILE (type),
3899 real_type, NULL);
3900 }
3901
3902 return real_type;
3903 }
3904
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. */
3914
3915 struct value *
3916 value_full_object (struct value *argp,
3917 struct type *rtype,
3918 int xfull, int xtop,
3919 int xusing_enc)
3920 {
3921 struct type *real_type;
3922 int full = 0;
3923 LONGEST top = -1;
3924 int using_enc = 0;
3925 struct value *new_val;
3926
3927 if (rtype)
3928 {
3929 real_type = rtype;
3930 full = xfull;
3931 top = xtop;
3932 using_enc = xusing_enc;
3933 }
3934 else
3935 real_type = value_rtti_type (argp, &full, &top, &using_enc);
3936
3937 /* If no RTTI data, or if object is already complete, do nothing. */
3938 if (!real_type || real_type == argp->enclosing_type ())
3939 return argp;
3940
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 () < argp->enclosing_type ()->length ())
3946 return argp;
3947
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)
3952 {
3953 argp = argp->copy ();
3954 argp->set_enclosing_type (real_type);
3955 return argp;
3956 }
3957
3958 /* Check if object is in memory. */
3959 if (argp->lval () != lval_memory)
3960 {
3961 warning (_("Couldn't retrieve complete object of RTTI "
3962 "type %s; object may be in register(s)."),
3963 real_type->name ());
3964
3965 return argp;
3966 }
3967
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, argp->address () - top +
3973 (using_enc ? 0 : argp->embedded_offset ()));
3974 new_val->deprecated_set_type (argp->type ());
3975 new_val->set_embedded_offset ((using_enc
3976 ? top + argp->embedded_offset ()
3977 : top));
3978 return new_val;
3979 }
3980
3981
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. */
3984
3985 struct value *
3986 value_of_this (const struct language_defn *lang)
3987 {
3988 struct block_symbol sym;
3989 const struct block *b;
3990 frame_info_ptr frame;
3991
3992 if (lang->name_of_this () == NULL)
3993 error (_("no `this' in current language"));
3994
3995 frame = get_selected_frame (_("no frame selected"));
3996
3997 b = get_frame_block (frame, NULL);
3998
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 ());
4003
4004 return read_var_value (sym.symbol, sym.block, frame);
4005 }
4006
4007 /* Return the value of the local variable, if one exists. Return NULL
4008 otherwise. Never throw error. */
4009
4010 struct value *
4011 value_of_this_silent (const struct language_defn *lang)
4012 {
4013 struct value *ret = NULL;
4014
4015 try
4016 {
4017 ret = value_of_this (lang);
4018 }
4019 catch (const gdb_exception_error &except)
4020 {
4021 }
4022
4023 return ret;
4024 }
4025
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. */
4029
4030 struct value *
4031 value_slice (struct value *array, int lowbound, int length)
4032 {
4033 struct type *slice_range_type, *slice_type, *range_type;
4034 LONGEST lowerbound, upperbound;
4035 struct value *slice;
4036 struct type *array_type;
4037
4038 array_type = check_typedef (array->type ());
4039 if (array_type->code () != TYPE_CODE_ARRAY
4040 && array_type->code () != TYPE_CODE_STRING)
4041 error (_("cannot take slice of non-array"));
4042
4043 if (type_not_allocated (array_type))
4044 error (_("array not allocated"));
4045 if (type_not_associated (array_type))
4046 error (_("array not associated"));
4047
4048 range_type = array_type->index_type ();
4049 if (!get_discrete_bounds (range_type, &lowerbound, &upperbound))
4050 error (_("slice from bad array or bitstring"));
4051
4052 if (lowbound < lowerbound || length < 0
4053 || lowbound + length - 1 > upperbound)
4054 error (_("slice out of range"));
4055
4056 /* FIXME-type-allocation: need a way to free this type when we are
4057 done with it. */
4058 type_allocator alloc (range_type->target_type ());
4059 slice_range_type = create_static_range_type (alloc,
4060 range_type->target_type (),
4061 lowbound,
4062 lowbound + length - 1);
4063
4064 {
4065 struct type *element_type = array_type->target_type ();
4066 LONGEST offset
4067 = (lowbound - lowerbound) * check_typedef (element_type)->length ();
4068
4069 slice_type = create_array_type (alloc,
4070 element_type,
4071 slice_range_type);
4072 slice_type->set_code (array_type->code ());
4073
4074 if (array->lval () == lval_memory && array->lazy ())
4075 slice = value::allocate_lazy (slice_type);
4076 else
4077 {
4078 slice = value::allocate (slice_type);
4079 array->contents_copy (slice, 0, offset,
4080 type_length_units (slice_type));
4081 }
4082
4083 slice->set_component_location (array);
4084 slice->set_offset (array->offset () + offset);
4085 }
4086
4087 return slice;
4088 }
4089
4090 /* See value.h. */
4091
4092 struct value *
4093 value_literal_complex (struct value *arg1,
4094 struct value *arg2,
4095 struct type *type)
4096 {
4097 struct value *val;
4098 struct type *real_type = type->target_type ();
4099
4100 val = value::allocate (type);
4101 arg1 = value_cast (real_type, arg1);
4102 arg2 = value_cast (real_type, arg2);
4103
4104 int len = real_type->length ();
4105
4106 copy (arg1->contents (),
4107 val->contents_raw ().slice (0, len));
4108 copy (arg2->contents (),
4109 val->contents_raw ().slice (len, len));
4110
4111 return val;
4112 }
4113
4114 /* See value.h. */
4115
4116 struct value *
4117 value_real_part (struct value *value)
4118 {
4119 struct type *type = check_typedef (value->type ());
4120 struct type *ttype = type->target_type ();
4121
4122 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4123 return value_from_component (value, ttype, 0);
4124 }
4125
4126 /* See value.h. */
4127
4128 struct value *
4129 value_imaginary_part (struct value *value)
4130 {
4131 struct type *type = check_typedef (value->type ());
4132 struct type *ttype = type->target_type ();
4133
4134 gdb_assert (type->code () == TYPE_CODE_COMPLEX);
4135 return value_from_component (value, ttype,
4136 check_typedef (ttype)->length ());
4137 }
4138
4139 /* Cast a value into the appropriate complex data type. */
4140
4141 static struct value *
4142 cast_into_complex (struct type *type, struct value *val)
4143 {
4144 struct type *real_type = type->target_type ();
4145
4146 if (val->type ()->code () == TYPE_CODE_COMPLEX)
4147 {
4148 struct type *val_real_type = val->type ()->target_type ();
4149 struct value *re_val = value::allocate (val_real_type);
4150 struct value *im_val = value::allocate (val_real_type);
4151 int len = val_real_type->length ();
4152
4153 copy (val->contents ().slice (0, len),
4154 re_val->contents_raw ());
4155 copy (val->contents ().slice (len, len),
4156 im_val->contents_raw ());
4157
4158 return value_literal_complex (re_val, im_val, type);
4159 }
4160 else if (val->type ()->code () == TYPE_CODE_FLT
4161 || val->type ()->code () == TYPE_CODE_INT)
4162 return value_literal_complex (val,
4163 value::zero (real_type, not_lval),
4164 type);
4165 else
4166 error (_("cannot cast non-number to complex"));
4167 }
4168
4169 void _initialize_valops ();
4170 void
4171 _initialize_valops ()
4172 {
4173 add_setshow_boolean_cmd ("overload-resolution", class_support,
4174 &overload_resolution, _("\
4175 Set overload resolution in evaluating C++ functions."), _("\
4176 Show overload resolution in evaluating C++ functions."),
4177 NULL, NULL,
4178 show_overload_resolution,
4179 &setlist, &showlist);
4180 overload_resolution = 1;
4181 }
4182