Automatic date update in version.in
[binutils-gdb.git] / gdb / value.c
blob8ed941f3749b5ab7235a61125827bb7abbc93357
1 /* Low level packing and unpacking of values for GDB, the GNU Debugger.
3 Copyright (C) 1986-2022 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "value.h"
25 #include "gdbcore.h"
26 #include "command.h"
27 #include "gdbcmd.h"
28 #include "target.h"
29 #include "language.h"
30 #include "demangle.h"
31 #include "regcache.h"
32 #include "block.h"
33 #include "target-float.h"
34 #include "objfiles.h"
35 #include "valprint.h"
36 #include "cli/cli-decode.h"
37 #include "extension.h"
38 #include <ctype.h>
39 #include "tracepoint.h"
40 #include "cp-abi.h"
41 #include "user-regs.h"
42 #include <algorithm>
43 #include <iterator>
44 #include <utility>
45 #include <vector>
46 #include "completer.h"
47 #include "gdbsupport/selftest.h"
48 #include "gdbsupport/array-view.h"
49 #include "cli/cli-style.h"
50 #include "expop.h"
51 #include "inferior.h"
52 #include "varobj.h"
54 /* Definition of a user function. */
55 struct internal_function
57 /* The name of the function. It is a bit odd to have this in the
58 function itself -- the user might use a differently-named
59 convenience variable to hold the function. */
60 char *name;
62 /* The handler. */
63 internal_function_fn handler;
65 /* User data for the handler. */
66 void *cookie;
69 /* Defines an [OFFSET, OFFSET + LENGTH) range. */
71 struct range
73 /* Lowest offset in the range. */
74 LONGEST offset;
76 /* Length of the range. */
77 LONGEST length;
79 /* Returns true if THIS is strictly less than OTHER, useful for
80 searching. We keep ranges sorted by offset and coalesce
81 overlapping and contiguous ranges, so this just compares the
82 starting offset. */
84 bool operator< (const range &other) const
86 return offset < other.offset;
89 /* Returns true if THIS is equal to OTHER. */
90 bool operator== (const range &other) const
92 return offset == other.offset && length == other.length;
96 /* Returns true if the ranges defined by [offset1, offset1+len1) and
97 [offset2, offset2+len2) overlap. */
99 static int
100 ranges_overlap (LONGEST offset1, LONGEST len1,
101 LONGEST offset2, LONGEST len2)
103 ULONGEST h, l;
105 l = std::max (offset1, offset2);
106 h = std::min (offset1 + len1, offset2 + len2);
107 return (l < h);
110 /* Returns true if RANGES contains any range that overlaps [OFFSET,
111 OFFSET+LENGTH). */
113 static int
114 ranges_contain (const std::vector<range> &ranges, LONGEST offset,
115 LONGEST length)
117 range what;
119 what.offset = offset;
120 what.length = length;
122 /* We keep ranges sorted by offset and coalesce overlapping and
123 contiguous ranges, so to check if a range list contains a given
124 range, we can do a binary search for the position the given range
125 would be inserted if we only considered the starting OFFSET of
126 ranges. We call that position I. Since we also have LENGTH to
127 care for (this is a range afterall), we need to check if the
128 _previous_ range overlaps the I range. E.g.,
131 |---|
132 |---| |---| |------| ... |--|
133 0 1 2 N
137 In the case above, the binary search would return `I=1', meaning,
138 this OFFSET should be inserted at position 1, and the current
139 position 1 should be pushed further (and before 2). But, `0'
140 overlaps with R.
142 Then we need to check if the I range overlaps the I range itself.
143 E.g.,
146 |---|
147 |---| |---| |-------| ... |--|
148 0 1 2 N
154 auto i = std::lower_bound (ranges.begin (), ranges.end (), what);
156 if (i > ranges.begin ())
158 const struct range &bef = *(i - 1);
160 if (ranges_overlap (bef.offset, bef.length, offset, length))
161 return 1;
164 if (i < ranges.end ())
166 const struct range &r = *i;
168 if (ranges_overlap (r.offset, r.length, offset, length))
169 return 1;
172 return 0;
175 static struct cmd_list_element *functionlist;
177 /* Note that the fields in this structure are arranged to save a bit
178 of memory. */
180 struct value
182 explicit value (struct type *type_)
183 : modifiable (1),
184 lazy (1),
185 initialized (1),
186 stack (0),
187 is_zero (false),
188 type (type_),
189 enclosing_type (type_)
193 ~value ()
195 if (VALUE_LVAL (this) == lval_computed)
197 const struct lval_funcs *funcs = location.computed.funcs;
199 if (funcs->free_closure)
200 funcs->free_closure (this);
202 else if (VALUE_LVAL (this) == lval_xcallable)
203 delete location.xm_worker;
206 DISABLE_COPY_AND_ASSIGN (value);
208 /* Type of value; either not an lval, or one of the various
209 different possible kinds of lval. */
210 enum lval_type lval = not_lval;
212 /* Is it modifiable? Only relevant if lval != not_lval. */
213 unsigned int modifiable : 1;
215 /* If zero, contents of this value are in the contents field. If
216 nonzero, contents are in inferior. If the lval field is lval_memory,
217 the contents are in inferior memory at location.address plus offset.
218 The lval field may also be lval_register.
220 WARNING: This field is used by the code which handles watchpoints
221 (see breakpoint.c) to decide whether a particular value can be
222 watched by hardware watchpoints. If the lazy flag is set for
223 some member of a value chain, it is assumed that this member of
224 the chain doesn't need to be watched as part of watching the
225 value itself. This is how GDB avoids watching the entire struct
226 or array when the user wants to watch a single struct member or
227 array element. If you ever change the way lazy flag is set and
228 reset, be sure to consider this use as well! */
229 unsigned int lazy : 1;
231 /* If value is a variable, is it initialized or not. */
232 unsigned int initialized : 1;
234 /* If value is from the stack. If this is set, read_stack will be
235 used instead of read_memory to enable extra caching. */
236 unsigned int stack : 1;
238 /* True if this is a zero value, created by 'value_zero'; false
239 otherwise. */
240 bool is_zero : 1;
242 /* Location of value (if lval). */
243 union
245 /* If lval == lval_memory, this is the address in the inferior */
246 CORE_ADDR address;
248 /*If lval == lval_register, the value is from a register. */
249 struct
251 /* Register number. */
252 int regnum;
253 /* Frame ID of "next" frame to which a register value is relative.
254 If the register value is found relative to frame F, then the
255 frame id of F->next will be stored in next_frame_id. */
256 struct frame_id next_frame_id;
257 } reg;
259 /* Pointer to internal variable. */
260 struct internalvar *internalvar;
262 /* Pointer to xmethod worker. */
263 struct xmethod_worker *xm_worker;
265 /* If lval == lval_computed, this is a set of function pointers
266 to use to access and describe the value, and a closure pointer
267 for them to use. */
268 struct
270 /* Functions to call. */
271 const struct lval_funcs *funcs;
273 /* Closure for those functions to use. */
274 void *closure;
275 } computed;
276 } location {};
278 /* Describes offset of a value within lval of a structure in target
279 addressable memory units. Note also the member embedded_offset
280 below. */
281 LONGEST offset = 0;
283 /* Only used for bitfields; number of bits contained in them. */
284 LONGEST bitsize = 0;
286 /* Only used for bitfields; position of start of field. For
287 little-endian targets, it is the position of the LSB. For
288 big-endian targets, it is the position of the MSB. */
289 LONGEST bitpos = 0;
291 /* The number of references to this value. When a value is created,
292 the value chain holds a reference, so REFERENCE_COUNT is 1. If
293 release_value is called, this value is removed from the chain but
294 the caller of release_value now has a reference to this value.
295 The caller must arrange for a call to value_free later. */
296 int reference_count = 1;
298 /* Only used for bitfields; the containing value. This allows a
299 single read from the target when displaying multiple
300 bitfields. */
301 value_ref_ptr parent;
303 /* Type of the value. */
304 struct type *type;
306 /* If a value represents a C++ object, then the `type' field gives
307 the object's compile-time type. If the object actually belongs
308 to some class derived from `type', perhaps with other base
309 classes and additional members, then `type' is just a subobject
310 of the real thing, and the full object is probably larger than
311 `type' would suggest.
313 If `type' is a dynamic class (i.e. one with a vtable), then GDB
314 can actually determine the object's run-time type by looking at
315 the run-time type information in the vtable. When this
316 information is available, we may elect to read in the entire
317 object, for several reasons:
319 - When printing the value, the user would probably rather see the
320 full object, not just the limited portion apparent from the
321 compile-time type.
323 - If `type' has virtual base classes, then even printing `type'
324 alone may require reaching outside the `type' portion of the
325 object to wherever the virtual base class has been stored.
327 When we store the entire object, `enclosing_type' is the run-time
328 type -- the complete object -- and `embedded_offset' is the
329 offset of `type' within that larger type, in target addressable memory
330 units. The value_contents() macro takes `embedded_offset' into account,
331 so most GDB code continues to see the `type' portion of the value, just
332 as the inferior would.
334 If `type' is a pointer to an object, then `enclosing_type' is a
335 pointer to the object's run-time type, and `pointed_to_offset' is
336 the offset in target addressable memory units from the full object
337 to the pointed-to object -- that is, the value `embedded_offset' would
338 have if we followed the pointer and fetched the complete object.
339 (I don't really see the point. Why not just determine the
340 run-time type when you indirect, and avoid the special case? The
341 contents don't matter until you indirect anyway.)
343 If we're not doing anything fancy, `enclosing_type' is equal to
344 `type', and `embedded_offset' is zero, so everything works
345 normally. */
346 struct type *enclosing_type;
347 LONGEST embedded_offset = 0;
348 LONGEST pointed_to_offset = 0;
350 /* Actual contents of the value. Target byte-order.
352 May be nullptr if the value is lazy or is entirely optimized out.
353 Guaranteed to be non-nullptr otherwise. */
354 gdb::unique_xmalloc_ptr<gdb_byte> contents;
356 /* Unavailable ranges in CONTENTS. We mark unavailable ranges,
357 rather than available, since the common and default case is for a
358 value to be available. This is filled in at value read time.
359 The unavailable ranges are tracked in bits. Note that a contents
360 bit that has been optimized out doesn't really exist in the
361 program, so it can't be marked unavailable either. */
362 std::vector<range> unavailable;
364 /* Likewise, but for optimized out contents (a chunk of the value of
365 a variable that does not actually exist in the program). If LVAL
366 is lval_register, this is a register ($pc, $sp, etc., never a
367 program variable) that has not been saved in the frame. Not
368 saved registers and optimized-out program variables values are
369 treated pretty much the same, except not-saved registers have a
370 different string representation and related error strings. */
371 std::vector<range> optimized_out;
374 /* See value.h. */
376 struct gdbarch *
377 get_value_arch (const struct value *value)
379 return value_type (value)->arch ();
383 value_bits_available (const struct value *value, LONGEST offset, LONGEST length)
385 gdb_assert (!value->lazy);
387 return !ranges_contain (value->unavailable, offset, length);
391 value_bytes_available (const struct value *value,
392 LONGEST offset, LONGEST length)
394 return value_bits_available (value,
395 offset * TARGET_CHAR_BIT,
396 length * TARGET_CHAR_BIT);
400 value_bits_any_optimized_out (const struct value *value, int bit_offset, int bit_length)
402 gdb_assert (!value->lazy);
404 return ranges_contain (value->optimized_out, bit_offset, bit_length);
408 value_entirely_available (struct value *value)
410 /* We can only tell whether the whole value is available when we try
411 to read it. */
412 if (value->lazy)
413 value_fetch_lazy (value);
415 if (value->unavailable.empty ())
416 return 1;
417 return 0;
420 /* Returns true if VALUE is entirely covered by RANGES. If the value
421 is lazy, it'll be read now. Note that RANGE is a pointer to
422 pointer because reading the value might change *RANGE. */
424 static int
425 value_entirely_covered_by_range_vector (struct value *value,
426 const std::vector<range> &ranges)
428 /* We can only tell whether the whole value is optimized out /
429 unavailable when we try to read it. */
430 if (value->lazy)
431 value_fetch_lazy (value);
433 if (ranges.size () == 1)
435 const struct range &t = ranges[0];
437 if (t.offset == 0
438 && t.length == (TARGET_CHAR_BIT
439 * value_enclosing_type (value)->length ()))
440 return 1;
443 return 0;
447 value_entirely_unavailable (struct value *value)
449 return value_entirely_covered_by_range_vector (value, value->unavailable);
453 value_entirely_optimized_out (struct value *value)
455 return value_entirely_covered_by_range_vector (value, value->optimized_out);
458 /* Insert into the vector pointed to by VECTORP the bit range starting of
459 OFFSET bits, and extending for the next LENGTH bits. */
461 static void
462 insert_into_bit_range_vector (std::vector<range> *vectorp,
463 LONGEST offset, LONGEST length)
465 range newr;
467 /* Insert the range sorted. If there's overlap or the new range
468 would be contiguous with an existing range, merge. */
470 newr.offset = offset;
471 newr.length = length;
473 /* Do a binary search for the position the given range would be
474 inserted if we only considered the starting OFFSET of ranges.
475 Call that position I. Since we also have LENGTH to care for
476 (this is a range afterall), we need to check if the _previous_
477 range overlaps the I range. E.g., calling R the new range:
479 #1 - overlaps with previous
482 |-...-|
483 |---| |---| |------| ... |--|
484 0 1 2 N
488 In the case #1 above, the binary search would return `I=1',
489 meaning, this OFFSET should be inserted at position 1, and the
490 current position 1 should be pushed further (and become 2). But,
491 note that `0' overlaps with R, so we want to merge them.
493 A similar consideration needs to be taken if the new range would
494 be contiguous with the previous range:
496 #2 - contiguous with previous
499 |-...-|
500 |--| |---| |------| ... |--|
501 0 1 2 N
505 If there's no overlap with the previous range, as in:
507 #3 - not overlapping and not contiguous
510 |-...-|
511 |--| |---| |------| ... |--|
512 0 1 2 N
516 or if I is 0:
518 #4 - R is the range with lowest offset
521 |-...-|
522 |--| |---| |------| ... |--|
523 0 1 2 N
527 ... we just push the new range to I.
529 All the 4 cases above need to consider that the new range may
530 also overlap several of the ranges that follow, or that R may be
531 contiguous with the following range, and merge. E.g.,
533 #5 - overlapping following ranges
536 |------------------------|
537 |--| |---| |------| ... |--|
538 0 1 2 N
545 |-------|
546 |--| |---| |------| ... |--|
547 0 1 2 N
553 auto i = std::lower_bound (vectorp->begin (), vectorp->end (), newr);
554 if (i > vectorp->begin ())
556 struct range &bef = *(i - 1);
558 if (ranges_overlap (bef.offset, bef.length, offset, length))
560 /* #1 */
561 ULONGEST l = std::min (bef.offset, offset);
562 ULONGEST h = std::max (bef.offset + bef.length, offset + length);
564 bef.offset = l;
565 bef.length = h - l;
566 i--;
568 else if (offset == bef.offset + bef.length)
570 /* #2 */
571 bef.length += length;
572 i--;
574 else
576 /* #3 */
577 i = vectorp->insert (i, newr);
580 else
582 /* #4 */
583 i = vectorp->insert (i, newr);
586 /* Check whether the ranges following the one we've just added or
587 touched can be folded in (#5 above). */
588 if (i != vectorp->end () && i + 1 < vectorp->end ())
590 int removed = 0;
591 auto next = i + 1;
593 /* Get the range we just touched. */
594 struct range &t = *i;
595 removed = 0;
597 i = next;
598 for (; i < vectorp->end (); i++)
600 struct range &r = *i;
601 if (r.offset <= t.offset + t.length)
603 ULONGEST l, h;
605 l = std::min (t.offset, r.offset);
606 h = std::max (t.offset + t.length, r.offset + r.length);
608 t.offset = l;
609 t.length = h - l;
611 removed++;
613 else
615 /* If we couldn't merge this one, we won't be able to
616 merge following ones either, since the ranges are
617 always sorted by OFFSET. */
618 break;
622 if (removed != 0)
623 vectorp->erase (next, next + removed);
627 void
628 mark_value_bits_unavailable (struct value *value,
629 LONGEST offset, LONGEST length)
631 insert_into_bit_range_vector (&value->unavailable, offset, length);
634 void
635 mark_value_bytes_unavailable (struct value *value,
636 LONGEST offset, LONGEST length)
638 mark_value_bits_unavailable (value,
639 offset * TARGET_CHAR_BIT,
640 length * TARGET_CHAR_BIT);
643 /* Find the first range in RANGES that overlaps the range defined by
644 OFFSET and LENGTH, starting at element POS in the RANGES vector,
645 Returns the index into RANGES where such overlapping range was
646 found, or -1 if none was found. */
648 static int
649 find_first_range_overlap (const std::vector<range> *ranges, int pos,
650 LONGEST offset, LONGEST length)
652 int i;
654 for (i = pos; i < ranges->size (); i++)
656 const range &r = (*ranges)[i];
657 if (ranges_overlap (r.offset, r.length, offset, length))
658 return i;
661 return -1;
664 /* Compare LENGTH_BITS of memory at PTR1 + OFFSET1_BITS with the memory at
665 PTR2 + OFFSET2_BITS. Return 0 if the memory is the same, otherwise
666 return non-zero.
668 It must always be the case that:
669 OFFSET1_BITS % TARGET_CHAR_BIT == OFFSET2_BITS % TARGET_CHAR_BIT
671 It is assumed that memory can be accessed from:
672 PTR + (OFFSET_BITS / TARGET_CHAR_BIT)
674 PTR + ((OFFSET_BITS + LENGTH_BITS + TARGET_CHAR_BIT - 1)
675 / TARGET_CHAR_BIT) */
676 static int
677 memcmp_with_bit_offsets (const gdb_byte *ptr1, size_t offset1_bits,
678 const gdb_byte *ptr2, size_t offset2_bits,
679 size_t length_bits)
681 gdb_assert (offset1_bits % TARGET_CHAR_BIT
682 == offset2_bits % TARGET_CHAR_BIT);
684 if (offset1_bits % TARGET_CHAR_BIT != 0)
686 size_t bits;
687 gdb_byte mask, b1, b2;
689 /* The offset from the base pointers PTR1 and PTR2 is not a complete
690 number of bytes. A number of bits up to either the next exact
691 byte boundary, or LENGTH_BITS (which ever is sooner) will be
692 compared. */
693 bits = TARGET_CHAR_BIT - offset1_bits % TARGET_CHAR_BIT;
694 gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
695 mask = (1 << bits) - 1;
697 if (length_bits < bits)
699 mask &= ~(gdb_byte) ((1 << (bits - length_bits)) - 1);
700 bits = length_bits;
703 /* Now load the two bytes and mask off the bits we care about. */
704 b1 = *(ptr1 + offset1_bits / TARGET_CHAR_BIT) & mask;
705 b2 = *(ptr2 + offset2_bits / TARGET_CHAR_BIT) & mask;
707 if (b1 != b2)
708 return 1;
710 /* Now update the length and offsets to take account of the bits
711 we've just compared. */
712 length_bits -= bits;
713 offset1_bits += bits;
714 offset2_bits += bits;
717 if (length_bits % TARGET_CHAR_BIT != 0)
719 size_t bits;
720 size_t o1, o2;
721 gdb_byte mask, b1, b2;
723 /* The length is not an exact number of bytes. After the previous
724 IF.. block then the offsets are byte aligned, or the
725 length is zero (in which case this code is not reached). Compare
726 a number of bits at the end of the region, starting from an exact
727 byte boundary. */
728 bits = length_bits % TARGET_CHAR_BIT;
729 o1 = offset1_bits + length_bits - bits;
730 o2 = offset2_bits + length_bits - bits;
732 gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
733 mask = ((1 << bits) - 1) << (TARGET_CHAR_BIT - bits);
735 gdb_assert (o1 % TARGET_CHAR_BIT == 0);
736 gdb_assert (o2 % TARGET_CHAR_BIT == 0);
738 b1 = *(ptr1 + o1 / TARGET_CHAR_BIT) & mask;
739 b2 = *(ptr2 + o2 / TARGET_CHAR_BIT) & mask;
741 if (b1 != b2)
742 return 1;
744 length_bits -= bits;
747 if (length_bits > 0)
749 /* We've now taken care of any stray "bits" at the start, or end of
750 the region to compare, the remainder can be covered with a simple
751 memcmp. */
752 gdb_assert (offset1_bits % TARGET_CHAR_BIT == 0);
753 gdb_assert (offset2_bits % TARGET_CHAR_BIT == 0);
754 gdb_assert (length_bits % TARGET_CHAR_BIT == 0);
756 return memcmp (ptr1 + offset1_bits / TARGET_CHAR_BIT,
757 ptr2 + offset2_bits / TARGET_CHAR_BIT,
758 length_bits / TARGET_CHAR_BIT);
761 /* Length is zero, regions match. */
762 return 0;
765 /* Helper struct for find_first_range_overlap_and_match and
766 value_contents_bits_eq. Keep track of which slot of a given ranges
767 vector have we last looked at. */
769 struct ranges_and_idx
771 /* The ranges. */
772 const std::vector<range> *ranges;
774 /* The range we've last found in RANGES. Given ranges are sorted,
775 we can start the next lookup here. */
776 int idx;
779 /* Helper function for value_contents_bits_eq. Compare LENGTH bits of
780 RP1's ranges starting at OFFSET1 bits with LENGTH bits of RP2's
781 ranges starting at OFFSET2 bits. Return true if the ranges match
782 and fill in *L and *H with the overlapping window relative to
783 (both) OFFSET1 or OFFSET2. */
785 static int
786 find_first_range_overlap_and_match (struct ranges_and_idx *rp1,
787 struct ranges_and_idx *rp2,
788 LONGEST offset1, LONGEST offset2,
789 LONGEST length, ULONGEST *l, ULONGEST *h)
791 rp1->idx = find_first_range_overlap (rp1->ranges, rp1->idx,
792 offset1, length);
793 rp2->idx = find_first_range_overlap (rp2->ranges, rp2->idx,
794 offset2, length);
796 if (rp1->idx == -1 && rp2->idx == -1)
798 *l = length;
799 *h = length;
800 return 1;
802 else if (rp1->idx == -1 || rp2->idx == -1)
803 return 0;
804 else
806 const range *r1, *r2;
807 ULONGEST l1, h1;
808 ULONGEST l2, h2;
810 r1 = &(*rp1->ranges)[rp1->idx];
811 r2 = &(*rp2->ranges)[rp2->idx];
813 /* Get the unavailable windows intersected by the incoming
814 ranges. The first and last ranges that overlap the argument
815 range may be wider than said incoming arguments ranges. */
816 l1 = std::max (offset1, r1->offset);
817 h1 = std::min (offset1 + length, r1->offset + r1->length);
819 l2 = std::max (offset2, r2->offset);
820 h2 = std::min (offset2 + length, offset2 + r2->length);
822 /* Make them relative to the respective start offsets, so we can
823 compare them for equality. */
824 l1 -= offset1;
825 h1 -= offset1;
827 l2 -= offset2;
828 h2 -= offset2;
830 /* Different ranges, no match. */
831 if (l1 != l2 || h1 != h2)
832 return 0;
834 *h = h1;
835 *l = l1;
836 return 1;
840 /* Helper function for value_contents_eq. The only difference is that
841 this function is bit rather than byte based.
843 Compare LENGTH bits of VAL1's contents starting at OFFSET1 bits
844 with LENGTH bits of VAL2's contents starting at OFFSET2 bits.
845 Return true if the available bits match. */
847 static bool
848 value_contents_bits_eq (const struct value *val1, int offset1,
849 const struct value *val2, int offset2,
850 int length)
852 /* Each array element corresponds to a ranges source (unavailable,
853 optimized out). '1' is for VAL1, '2' for VAL2. */
854 struct ranges_and_idx rp1[2], rp2[2];
856 /* See function description in value.h. */
857 gdb_assert (!val1->lazy && !val2->lazy);
859 /* We shouldn't be trying to compare past the end of the values. */
860 gdb_assert (offset1 + length
861 <= val1->enclosing_type->length () * TARGET_CHAR_BIT);
862 gdb_assert (offset2 + length
863 <= val2->enclosing_type->length () * TARGET_CHAR_BIT);
865 memset (&rp1, 0, sizeof (rp1));
866 memset (&rp2, 0, sizeof (rp2));
867 rp1[0].ranges = &val1->unavailable;
868 rp2[0].ranges = &val2->unavailable;
869 rp1[1].ranges = &val1->optimized_out;
870 rp2[1].ranges = &val2->optimized_out;
872 while (length > 0)
874 ULONGEST l = 0, h = 0; /* init for gcc -Wall */
875 int i;
877 for (i = 0; i < 2; i++)
879 ULONGEST l_tmp, h_tmp;
881 /* The contents only match equal if the invalid/unavailable
882 contents ranges match as well. */
883 if (!find_first_range_overlap_and_match (&rp1[i], &rp2[i],
884 offset1, offset2, length,
885 &l_tmp, &h_tmp))
886 return false;
888 /* We're interested in the lowest/first range found. */
889 if (i == 0 || l_tmp < l)
891 l = l_tmp;
892 h = h_tmp;
896 /* Compare the available/valid contents. */
897 if (memcmp_with_bit_offsets (val1->contents.get (), offset1,
898 val2->contents.get (), offset2, l) != 0)
899 return false;
901 length -= h;
902 offset1 += h;
903 offset2 += h;
906 return true;
909 bool
910 value_contents_eq (const struct value *val1, LONGEST offset1,
911 const struct value *val2, LONGEST offset2,
912 LONGEST length)
914 return value_contents_bits_eq (val1, offset1 * TARGET_CHAR_BIT,
915 val2, offset2 * TARGET_CHAR_BIT,
916 length * TARGET_CHAR_BIT);
920 /* The value-history records all the values printed by print commands
921 during this session. */
923 static std::vector<value_ref_ptr> value_history;
926 /* List of all value objects currently allocated
927 (except for those released by calls to release_value)
928 This is so they can be freed after each command. */
930 static std::vector<value_ref_ptr> all_values;
932 /* Allocate a lazy value for type TYPE. Its actual content is
933 "lazily" allocated too: the content field of the return value is
934 NULL; it will be allocated when it is fetched from the target. */
936 struct value *
937 allocate_value_lazy (struct type *type)
939 struct value *val;
941 /* Call check_typedef on our type to make sure that, if TYPE
942 is a TYPE_CODE_TYPEDEF, its length is set to the length
943 of the target type instead of zero. However, we do not
944 replace the typedef type by the target type, because we want
945 to keep the typedef in order to be able to set the VAL's type
946 description correctly. */
947 check_typedef (type);
949 val = new struct value (type);
951 /* Values start out on the all_values chain. */
952 all_values.emplace_back (val);
954 return val;
957 /* The maximum size, in bytes, that GDB will try to allocate for a value.
958 The initial value of 64k was not selected for any specific reason, it is
959 just a reasonable starting point. */
961 static int max_value_size = 65536; /* 64k bytes */
963 /* It is critical that the MAX_VALUE_SIZE is at least as big as the size of
964 LONGEST, otherwise GDB will not be able to parse integer values from the
965 CLI; for example if the MAX_VALUE_SIZE could be set to 1 then GDB would
966 be unable to parse "set max-value-size 2".
968 As we want a consistent GDB experience across hosts with different sizes
969 of LONGEST, this arbitrary minimum value was selected, so long as this
970 is bigger than LONGEST on all GDB supported hosts we're fine. */
972 #define MIN_VALUE_FOR_MAX_VALUE_SIZE 16
973 gdb_static_assert (sizeof (LONGEST) <= MIN_VALUE_FOR_MAX_VALUE_SIZE);
975 /* Implement the "set max-value-size" command. */
977 static void
978 set_max_value_size (const char *args, int from_tty,
979 struct cmd_list_element *c)
981 gdb_assert (max_value_size == -1 || max_value_size >= 0);
983 if (max_value_size > -1 && max_value_size < MIN_VALUE_FOR_MAX_VALUE_SIZE)
985 max_value_size = MIN_VALUE_FOR_MAX_VALUE_SIZE;
986 error (_("max-value-size set too low, increasing to %d bytes"),
987 max_value_size);
991 /* Implement the "show max-value-size" command. */
993 static void
994 show_max_value_size (struct ui_file *file, int from_tty,
995 struct cmd_list_element *c, const char *value)
997 if (max_value_size == -1)
998 gdb_printf (file, _("Maximum value size is unlimited.\n"));
999 else
1000 gdb_printf (file, _("Maximum value size is %d bytes.\n"),
1001 max_value_size);
1004 /* Called before we attempt to allocate or reallocate a buffer for the
1005 contents of a value. TYPE is the type of the value for which we are
1006 allocating the buffer. If the buffer is too large (based on the user
1007 controllable setting) then throw an error. If this function returns
1008 then we should attempt to allocate the buffer. */
1010 static void
1011 check_type_length_before_alloc (const struct type *type)
1013 ULONGEST length = type->length ();
1015 if (max_value_size > -1 && length > max_value_size)
1017 if (type->name () != NULL)
1018 error (_("value of type `%s' requires %s bytes, which is more "
1019 "than max-value-size"), type->name (), pulongest (length));
1020 else
1021 error (_("value requires %s bytes, which is more than "
1022 "max-value-size"), pulongest (length));
1026 /* Allocate the contents of VAL if it has not been allocated yet. */
1028 static void
1029 allocate_value_contents (struct value *val)
1031 if (!val->contents)
1033 check_type_length_before_alloc (val->enclosing_type);
1034 val->contents.reset
1035 ((gdb_byte *) xzalloc (val->enclosing_type->length ()));
1039 /* Allocate a value and its contents for type TYPE. */
1041 struct value *
1042 allocate_value (struct type *type)
1044 struct value *val = allocate_value_lazy (type);
1046 allocate_value_contents (val);
1047 val->lazy = 0;
1048 return val;
1051 /* Allocate a value that has the correct length
1052 for COUNT repetitions of type TYPE. */
1054 struct value *
1055 allocate_repeat_value (struct type *type, int count)
1057 /* Despite the fact that we are really creating an array of TYPE here, we
1058 use the string lower bound as the array lower bound. This seems to
1059 work fine for now. */
1060 int low_bound = current_language->string_lower_bound ();
1061 /* FIXME-type-allocation: need a way to free this type when we are
1062 done with it. */
1063 struct type *array_type
1064 = lookup_array_range_type (type, low_bound, count + low_bound - 1);
1066 return allocate_value (array_type);
1069 struct value *
1070 allocate_computed_value (struct type *type,
1071 const struct lval_funcs *funcs,
1072 void *closure)
1074 struct value *v = allocate_value_lazy (type);
1076 VALUE_LVAL (v) = lval_computed;
1077 v->location.computed.funcs = funcs;
1078 v->location.computed.closure = closure;
1080 return v;
1083 /* Allocate NOT_LVAL value for type TYPE being OPTIMIZED_OUT. */
1085 struct value *
1086 allocate_optimized_out_value (struct type *type)
1088 struct value *retval = allocate_value_lazy (type);
1090 mark_value_bytes_optimized_out (retval, 0, type->length ());
1091 set_value_lazy (retval, 0);
1092 return retval;
1095 /* Accessor methods. */
1097 struct type *
1098 value_type (const struct value *value)
1100 return value->type;
1102 void
1103 deprecated_set_value_type (struct value *value, struct type *type)
1105 value->type = type;
1108 LONGEST
1109 value_offset (const struct value *value)
1111 return value->offset;
1113 void
1114 set_value_offset (struct value *value, LONGEST offset)
1116 value->offset = offset;
1119 LONGEST
1120 value_bitpos (const struct value *value)
1122 return value->bitpos;
1124 void
1125 set_value_bitpos (struct value *value, LONGEST bit)
1127 value->bitpos = bit;
1130 LONGEST
1131 value_bitsize (const struct value *value)
1133 return value->bitsize;
1135 void
1136 set_value_bitsize (struct value *value, LONGEST bit)
1138 value->bitsize = bit;
1141 struct value *
1142 value_parent (const struct value *value)
1144 return value->parent.get ();
1147 /* See value.h. */
1149 void
1150 set_value_parent (struct value *value, struct value *parent)
1152 value->parent = value_ref_ptr::new_reference (parent);
1155 gdb::array_view<gdb_byte>
1156 value_contents_raw (struct value *value)
1158 struct gdbarch *arch = get_value_arch (value);
1159 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1161 allocate_value_contents (value);
1163 ULONGEST length = value_type (value)->length ();
1164 return gdb::make_array_view
1165 (value->contents.get () + value->embedded_offset * unit_size, length);
1168 gdb::array_view<gdb_byte>
1169 value_contents_all_raw (struct value *value)
1171 allocate_value_contents (value);
1173 ULONGEST length = value_enclosing_type (value)->length ();
1174 return gdb::make_array_view (value->contents.get (), length);
1177 struct type *
1178 value_enclosing_type (const struct value *value)
1180 return value->enclosing_type;
1183 /* Look at value.h for description. */
1185 struct type *
1186 value_actual_type (struct value *value, int resolve_simple_types,
1187 int *real_type_found)
1189 struct value_print_options opts;
1190 struct type *result;
1192 get_user_print_options (&opts);
1194 if (real_type_found)
1195 *real_type_found = 0;
1196 result = value_type (value);
1197 if (opts.objectprint)
1199 /* If result's target type is TYPE_CODE_STRUCT, proceed to
1200 fetch its rtti type. */
1201 if (result->is_pointer_or_reference ()
1202 && (check_typedef (result->target_type ())->code ()
1203 == TYPE_CODE_STRUCT)
1204 && !value_optimized_out (value))
1206 struct type *real_type;
1208 real_type = value_rtti_indirect_type (value, NULL, NULL, NULL);
1209 if (real_type)
1211 if (real_type_found)
1212 *real_type_found = 1;
1213 result = real_type;
1216 else if (resolve_simple_types)
1218 if (real_type_found)
1219 *real_type_found = 1;
1220 result = value_enclosing_type (value);
1224 return result;
1227 void
1228 error_value_optimized_out (void)
1230 throw_error (OPTIMIZED_OUT_ERROR, _("value has been optimized out"));
1233 static void
1234 require_not_optimized_out (const struct value *value)
1236 if (!value->optimized_out.empty ())
1238 if (value->lval == lval_register)
1239 throw_error (OPTIMIZED_OUT_ERROR,
1240 _("register has not been saved in frame"));
1241 else
1242 error_value_optimized_out ();
1246 static void
1247 require_available (const struct value *value)
1249 if (!value->unavailable.empty ())
1250 throw_error (NOT_AVAILABLE_ERROR, _("value is not available"));
1253 gdb::array_view<const gdb_byte>
1254 value_contents_for_printing (struct value *value)
1256 if (value->lazy)
1257 value_fetch_lazy (value);
1259 ULONGEST length = value_enclosing_type (value)->length ();
1260 return gdb::make_array_view (value->contents.get (), length);
1263 gdb::array_view<const gdb_byte>
1264 value_contents_for_printing_const (const struct value *value)
1266 gdb_assert (!value->lazy);
1268 ULONGEST length = value_enclosing_type (value)->length ();
1269 return gdb::make_array_view (value->contents.get (), length);
1272 gdb::array_view<const gdb_byte>
1273 value_contents_all (struct value *value)
1275 gdb::array_view<const gdb_byte> result = value_contents_for_printing (value);
1276 require_not_optimized_out (value);
1277 require_available (value);
1278 return result;
1281 /* Copy ranges in SRC_RANGE that overlap [SRC_BIT_OFFSET,
1282 SRC_BIT_OFFSET+BIT_LENGTH) ranges into *DST_RANGE, adjusted. */
1284 static void
1285 ranges_copy_adjusted (std::vector<range> *dst_range, int dst_bit_offset,
1286 const std::vector<range> &src_range, int src_bit_offset,
1287 int bit_length)
1289 for (const range &r : src_range)
1291 ULONGEST h, l;
1293 l = std::max (r.offset, (LONGEST) src_bit_offset);
1294 h = std::min (r.offset + r.length,
1295 (LONGEST) src_bit_offset + bit_length);
1297 if (l < h)
1298 insert_into_bit_range_vector (dst_range,
1299 dst_bit_offset + (l - src_bit_offset),
1300 h - l);
1304 /* Copy the ranges metadata in SRC that overlaps [SRC_BIT_OFFSET,
1305 SRC_BIT_OFFSET+BIT_LENGTH) into DST, adjusted. */
1307 static void
1308 value_ranges_copy_adjusted (struct value *dst, int dst_bit_offset,
1309 const struct value *src, int src_bit_offset,
1310 int bit_length)
1312 ranges_copy_adjusted (&dst->unavailable, dst_bit_offset,
1313 src->unavailable, src_bit_offset,
1314 bit_length);
1315 ranges_copy_adjusted (&dst->optimized_out, dst_bit_offset,
1316 src->optimized_out, src_bit_offset,
1317 bit_length);
1320 /* Copy LENGTH target addressable memory units of SRC value's (all) contents
1321 (value_contents_all) starting at SRC_OFFSET, into DST value's (all)
1322 contents, starting at DST_OFFSET. If unavailable contents are
1323 being copied from SRC, the corresponding DST contents are marked
1324 unavailable accordingly. Neither DST nor SRC may be lazy
1325 values.
1327 It is assumed the contents of DST in the [DST_OFFSET,
1328 DST_OFFSET+LENGTH) range are wholly available. */
1330 static void
1331 value_contents_copy_raw (struct value *dst, LONGEST dst_offset,
1332 struct value *src, LONGEST src_offset, LONGEST length)
1334 LONGEST src_bit_offset, dst_bit_offset, bit_length;
1335 struct gdbarch *arch = get_value_arch (src);
1336 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1338 /* A lazy DST would make that this copy operation useless, since as
1339 soon as DST's contents were un-lazied (by a later value_contents
1340 call, say), the contents would be overwritten. A lazy SRC would
1341 mean we'd be copying garbage. */
1342 gdb_assert (!dst->lazy && !src->lazy);
1344 /* The overwritten DST range gets unavailability ORed in, not
1345 replaced. Make sure to remember to implement replacing if it
1346 turns out actually necessary. */
1347 gdb_assert (value_bytes_available (dst, dst_offset, length));
1348 gdb_assert (!value_bits_any_optimized_out (dst,
1349 TARGET_CHAR_BIT * dst_offset,
1350 TARGET_CHAR_BIT * length));
1352 /* Copy the data. */
1353 gdb::array_view<gdb_byte> dst_contents
1354 = value_contents_all_raw (dst).slice (dst_offset * unit_size,
1355 length * unit_size);
1356 gdb::array_view<const gdb_byte> src_contents
1357 = value_contents_all_raw (src).slice (src_offset * unit_size,
1358 length * unit_size);
1359 copy (src_contents, dst_contents);
1361 /* Copy the meta-data, adjusted. */
1362 src_bit_offset = src_offset * unit_size * HOST_CHAR_BIT;
1363 dst_bit_offset = dst_offset * unit_size * HOST_CHAR_BIT;
1364 bit_length = length * unit_size * HOST_CHAR_BIT;
1366 value_ranges_copy_adjusted (dst, dst_bit_offset,
1367 src, src_bit_offset,
1368 bit_length);
1371 /* Copy LENGTH bytes of SRC value's (all) contents
1372 (value_contents_all) starting at SRC_OFFSET byte, into DST value's
1373 (all) contents, starting at DST_OFFSET. If unavailable contents
1374 are being copied from SRC, the corresponding DST contents are
1375 marked unavailable accordingly. DST must not be lazy. If SRC is
1376 lazy, it will be fetched now.
1378 It is assumed the contents of DST in the [DST_OFFSET,
1379 DST_OFFSET+LENGTH) range are wholly available. */
1381 void
1382 value_contents_copy (struct value *dst, LONGEST dst_offset,
1383 struct value *src, LONGEST src_offset, LONGEST length)
1385 if (src->lazy)
1386 value_fetch_lazy (src);
1388 value_contents_copy_raw (dst, dst_offset, src, src_offset, length);
1392 value_lazy (const struct value *value)
1394 return value->lazy;
1397 void
1398 set_value_lazy (struct value *value, int val)
1400 value->lazy = val;
1404 value_stack (const struct value *value)
1406 return value->stack;
1409 void
1410 set_value_stack (struct value *value, int val)
1412 value->stack = val;
1415 gdb::array_view<const gdb_byte>
1416 value_contents (struct value *value)
1418 gdb::array_view<const gdb_byte> result = value_contents_writeable (value);
1419 require_not_optimized_out (value);
1420 require_available (value);
1421 return result;
1424 gdb::array_view<gdb_byte>
1425 value_contents_writeable (struct value *value)
1427 if (value->lazy)
1428 value_fetch_lazy (value);
1429 return value_contents_raw (value);
1433 value_optimized_out (struct value *value)
1435 if (value->lazy)
1437 /* See if we can compute the result without fetching the
1438 value. */
1439 if (VALUE_LVAL (value) == lval_memory)
1440 return false;
1441 else if (VALUE_LVAL (value) == lval_computed)
1443 const struct lval_funcs *funcs = value->location.computed.funcs;
1445 if (funcs->is_optimized_out != nullptr)
1446 return funcs->is_optimized_out (value);
1449 /* Fall back to fetching. */
1452 value_fetch_lazy (value);
1454 catch (const gdb_exception_error &ex)
1456 switch (ex.error)
1458 case MEMORY_ERROR:
1459 case OPTIMIZED_OUT_ERROR:
1460 case NOT_AVAILABLE_ERROR:
1461 /* These can normally happen when we try to access an
1462 optimized out or unavailable register, either in a
1463 physical register or spilled to memory. */
1464 break;
1465 default:
1466 throw;
1471 return !value->optimized_out.empty ();
1474 /* Mark contents of VALUE as optimized out, starting at OFFSET bytes, and
1475 the following LENGTH bytes. */
1477 void
1478 mark_value_bytes_optimized_out (struct value *value, int offset, int length)
1480 mark_value_bits_optimized_out (value,
1481 offset * TARGET_CHAR_BIT,
1482 length * TARGET_CHAR_BIT);
1485 /* See value.h. */
1487 void
1488 mark_value_bits_optimized_out (struct value *value,
1489 LONGEST offset, LONGEST length)
1491 insert_into_bit_range_vector (&value->optimized_out, offset, length);
1495 value_bits_synthetic_pointer (const struct value *value,
1496 LONGEST offset, LONGEST length)
1498 if (value->lval != lval_computed
1499 || !value->location.computed.funcs->check_synthetic_pointer)
1500 return 0;
1501 return value->location.computed.funcs->check_synthetic_pointer (value,
1502 offset,
1503 length);
1506 LONGEST
1507 value_embedded_offset (const struct value *value)
1509 return value->embedded_offset;
1512 void
1513 set_value_embedded_offset (struct value *value, LONGEST val)
1515 value->embedded_offset = val;
1518 LONGEST
1519 value_pointed_to_offset (const struct value *value)
1521 return value->pointed_to_offset;
1524 void
1525 set_value_pointed_to_offset (struct value *value, LONGEST val)
1527 value->pointed_to_offset = val;
1530 const struct lval_funcs *
1531 value_computed_funcs (const struct value *v)
1533 gdb_assert (value_lval_const (v) == lval_computed);
1535 return v->location.computed.funcs;
1538 void *
1539 value_computed_closure (const struct value *v)
1541 gdb_assert (v->lval == lval_computed);
1543 return v->location.computed.closure;
1546 enum lval_type *
1547 deprecated_value_lval_hack (struct value *value)
1549 return &value->lval;
1552 enum lval_type
1553 value_lval_const (const struct value *value)
1555 return value->lval;
1558 CORE_ADDR
1559 value_address (const struct value *value)
1561 if (value->lval != lval_memory)
1562 return 0;
1563 if (value->parent != NULL)
1564 return value_address (value->parent.get ()) + value->offset;
1565 if (NULL != TYPE_DATA_LOCATION (value_type (value)))
1567 gdb_assert (PROP_CONST == TYPE_DATA_LOCATION_KIND (value_type (value)));
1568 return TYPE_DATA_LOCATION_ADDR (value_type (value));
1571 return value->location.address + value->offset;
1574 CORE_ADDR
1575 value_raw_address (const struct value *value)
1577 if (value->lval != lval_memory)
1578 return 0;
1579 return value->location.address;
1582 void
1583 set_value_address (struct value *value, CORE_ADDR addr)
1585 gdb_assert (value->lval == lval_memory);
1586 value->location.address = addr;
1589 struct internalvar **
1590 deprecated_value_internalvar_hack (struct value *value)
1592 return &value->location.internalvar;
1595 struct frame_id *
1596 deprecated_value_next_frame_id_hack (struct value *value)
1598 gdb_assert (value->lval == lval_register);
1599 return &value->location.reg.next_frame_id;
1602 int *
1603 deprecated_value_regnum_hack (struct value *value)
1605 gdb_assert (value->lval == lval_register);
1606 return &value->location.reg.regnum;
1610 deprecated_value_modifiable (const struct value *value)
1612 return value->modifiable;
1615 /* Return a mark in the value chain. All values allocated after the
1616 mark is obtained (except for those released) are subject to being freed
1617 if a subsequent value_free_to_mark is passed the mark. */
1618 struct value *
1619 value_mark (void)
1621 if (all_values.empty ())
1622 return nullptr;
1623 return all_values.back ().get ();
1626 /* See value.h. */
1628 void
1629 value_incref (struct value *val)
1631 val->reference_count++;
1634 /* Release a reference to VAL, which was acquired with value_incref.
1635 This function is also called to deallocate values from the value
1636 chain. */
1638 void
1639 value_decref (struct value *val)
1641 if (val != nullptr)
1643 gdb_assert (val->reference_count > 0);
1644 val->reference_count--;
1645 if (val->reference_count == 0)
1646 delete val;
1650 /* Free all values allocated since MARK was obtained by value_mark
1651 (except for those released). */
1652 void
1653 value_free_to_mark (const struct value *mark)
1655 auto iter = std::find (all_values.begin (), all_values.end (), mark);
1656 if (iter == all_values.end ())
1657 all_values.clear ();
1658 else
1659 all_values.erase (iter + 1, all_values.end ());
1662 /* Remove VAL from the chain all_values
1663 so it will not be freed automatically. */
1665 value_ref_ptr
1666 release_value (struct value *val)
1668 if (val == nullptr)
1669 return value_ref_ptr ();
1671 std::vector<value_ref_ptr>::reverse_iterator iter;
1672 for (iter = all_values.rbegin (); iter != all_values.rend (); ++iter)
1674 if (*iter == val)
1676 value_ref_ptr result = *iter;
1677 all_values.erase (iter.base () - 1);
1678 return result;
1682 /* We must always return an owned reference. Normally this happens
1683 because we transfer the reference from the value chain, but in
1684 this case the value was not on the chain. */
1685 return value_ref_ptr::new_reference (val);
1688 /* See value.h. */
1690 std::vector<value_ref_ptr>
1691 value_release_to_mark (const struct value *mark)
1693 std::vector<value_ref_ptr> result;
1695 auto iter = std::find (all_values.begin (), all_values.end (), mark);
1696 if (iter == all_values.end ())
1697 std::swap (result, all_values);
1698 else
1700 std::move (iter + 1, all_values.end (), std::back_inserter (result));
1701 all_values.erase (iter + 1, all_values.end ());
1703 std::reverse (result.begin (), result.end ());
1704 return result;
1707 /* Return a copy of the value ARG.
1708 It contains the same contents, for same memory address,
1709 but it's a different block of storage. */
1711 struct value *
1712 value_copy (const value *arg)
1714 struct type *encl_type = value_enclosing_type (arg);
1715 struct value *val;
1717 if (value_lazy (arg))
1718 val = allocate_value_lazy (encl_type);
1719 else
1720 val = allocate_value (encl_type);
1721 val->type = arg->type;
1722 VALUE_LVAL (val) = arg->lval;
1723 val->location = arg->location;
1724 val->offset = arg->offset;
1725 val->bitpos = arg->bitpos;
1726 val->bitsize = arg->bitsize;
1727 val->lazy = arg->lazy;
1728 val->embedded_offset = value_embedded_offset (arg);
1729 val->pointed_to_offset = arg->pointed_to_offset;
1730 val->modifiable = arg->modifiable;
1731 val->stack = arg->stack;
1732 val->is_zero = arg->is_zero;
1733 val->initialized = arg->initialized;
1734 val->unavailable = arg->unavailable;
1735 val->optimized_out = arg->optimized_out;
1737 if (!value_lazy (val) && !value_entirely_optimized_out (val))
1739 gdb_assert (arg->contents != nullptr);
1740 ULONGEST length = value_enclosing_type (arg)->length ();
1741 const auto &arg_view
1742 = gdb::make_array_view (arg->contents.get (), length);
1743 copy (arg_view, value_contents_all_raw (val));
1746 val->parent = arg->parent;
1747 if (VALUE_LVAL (val) == lval_computed)
1749 const struct lval_funcs *funcs = val->location.computed.funcs;
1751 if (funcs->copy_closure)
1752 val->location.computed.closure = funcs->copy_closure (val);
1754 return val;
1757 /* Return a "const" and/or "volatile" qualified version of the value V.
1758 If CNST is true, then the returned value will be qualified with
1759 "const".
1760 if VOLTL is true, then the returned value will be qualified with
1761 "volatile". */
1763 struct value *
1764 make_cv_value (int cnst, int voltl, struct value *v)
1766 struct type *val_type = value_type (v);
1767 struct type *enclosing_type = value_enclosing_type (v);
1768 struct value *cv_val = value_copy (v);
1770 deprecated_set_value_type (cv_val,
1771 make_cv_type (cnst, voltl, val_type, NULL));
1772 set_value_enclosing_type (cv_val,
1773 make_cv_type (cnst, voltl, enclosing_type, NULL));
1775 return cv_val;
1778 /* Return a version of ARG that is non-lvalue. */
1780 struct value *
1781 value_non_lval (struct value *arg)
1783 if (VALUE_LVAL (arg) != not_lval)
1785 struct type *enc_type = value_enclosing_type (arg);
1786 struct value *val = allocate_value (enc_type);
1788 copy (value_contents_all (arg), value_contents_all_raw (val));
1789 val->type = arg->type;
1790 set_value_embedded_offset (val, value_embedded_offset (arg));
1791 set_value_pointed_to_offset (val, value_pointed_to_offset (arg));
1792 return val;
1794 return arg;
1797 /* Write contents of V at ADDR and set its lval type to be LVAL_MEMORY. */
1799 void
1800 value_force_lval (struct value *v, CORE_ADDR addr)
1802 gdb_assert (VALUE_LVAL (v) == not_lval);
1804 write_memory (addr, value_contents_raw (v).data (), value_type (v)->length ());
1805 v->lval = lval_memory;
1806 v->location.address = addr;
1809 void
1810 set_value_component_location (struct value *component,
1811 const struct value *whole)
1813 struct type *type;
1815 gdb_assert (whole->lval != lval_xcallable);
1817 if (whole->lval == lval_internalvar)
1818 VALUE_LVAL (component) = lval_internalvar_component;
1819 else
1820 VALUE_LVAL (component) = whole->lval;
1822 component->location = whole->location;
1823 if (whole->lval == lval_computed)
1825 const struct lval_funcs *funcs = whole->location.computed.funcs;
1827 if (funcs->copy_closure)
1828 component->location.computed.closure = funcs->copy_closure (whole);
1831 /* If the WHOLE value has a dynamically resolved location property then
1832 update the address of the COMPONENT. */
1833 type = value_type (whole);
1834 if (NULL != TYPE_DATA_LOCATION (type)
1835 && TYPE_DATA_LOCATION_KIND (type) == PROP_CONST)
1836 set_value_address (component, TYPE_DATA_LOCATION_ADDR (type));
1838 /* Similarly, if the COMPONENT value has a dynamically resolved location
1839 property then update its address. */
1840 type = value_type (component);
1841 if (NULL != TYPE_DATA_LOCATION (type)
1842 && TYPE_DATA_LOCATION_KIND (type) == PROP_CONST)
1844 /* If the COMPONENT has a dynamic location, and is an
1845 lval_internalvar_component, then we change it to a lval_memory.
1847 Usually a component of an internalvar is created non-lazy, and has
1848 its content immediately copied from the parent internalvar.
1849 However, for components with a dynamic location, the content of
1850 the component is not contained within the parent, but is instead
1851 accessed indirectly. Further, the component will be created as a
1852 lazy value.
1854 By changing the type of the component to lval_memory we ensure
1855 that value_fetch_lazy can successfully load the component.
1857 This solution isn't ideal, but a real fix would require values to
1858 carry around both the parent value contents, and the contents of
1859 any dynamic fields within the parent. This is a substantial
1860 change to how values work in GDB. */
1861 if (VALUE_LVAL (component) == lval_internalvar_component)
1863 gdb_assert (value_lazy (component));
1864 VALUE_LVAL (component) = lval_memory;
1866 else
1867 gdb_assert (VALUE_LVAL (component) == lval_memory);
1868 set_value_address (component, TYPE_DATA_LOCATION_ADDR (type));
1872 /* Access to the value history. */
1874 /* Record a new value in the value history.
1875 Returns the absolute history index of the entry. */
1878 record_latest_value (struct value *val)
1880 /* We don't want this value to have anything to do with the inferior anymore.
1881 In particular, "set $1 = 50" should not affect the variable from which
1882 the value was taken, and fast watchpoints should be able to assume that
1883 a value on the value history never changes. */
1884 if (value_lazy (val))
1885 value_fetch_lazy (val);
1886 /* We preserve VALUE_LVAL so that the user can find out where it was fetched
1887 from. This is a bit dubious, because then *&$1 does not just return $1
1888 but the current contents of that location. c'est la vie... */
1889 val->modifiable = 0;
1891 value_history.push_back (release_value (val));
1893 return value_history.size ();
1896 /* Return a copy of the value in the history with sequence number NUM. */
1898 struct value *
1899 access_value_history (int num)
1901 int absnum = num;
1903 if (absnum <= 0)
1904 absnum += value_history.size ();
1906 if (absnum <= 0)
1908 if (num == 0)
1909 error (_("The history is empty."));
1910 else if (num == 1)
1911 error (_("There is only one value in the history."));
1912 else
1913 error (_("History does not go back to $$%d."), -num);
1915 if (absnum > value_history.size ())
1916 error (_("History has not yet reached $%d."), absnum);
1918 absnum--;
1920 return value_copy (value_history[absnum].get ());
1923 /* See value.h. */
1925 ULONGEST
1926 value_history_count ()
1928 return value_history.size ();
1931 static void
1932 show_values (const char *num_exp, int from_tty)
1934 int i;
1935 struct value *val;
1936 static int num = 1;
1938 if (num_exp)
1940 /* "show values +" should print from the stored position.
1941 "show values <exp>" should print around value number <exp>. */
1942 if (num_exp[0] != '+' || num_exp[1] != '\0')
1943 num = parse_and_eval_long (num_exp) - 5;
1945 else
1947 /* "show values" means print the last 10 values. */
1948 num = value_history.size () - 9;
1951 if (num <= 0)
1952 num = 1;
1954 for (i = num; i < num + 10 && i <= value_history.size (); i++)
1956 struct value_print_options opts;
1958 val = access_value_history (i);
1959 gdb_printf (("$%d = "), i);
1960 get_user_print_options (&opts);
1961 value_print (val, gdb_stdout, &opts);
1962 gdb_printf (("\n"));
1965 /* The next "show values +" should start after what we just printed. */
1966 num += 10;
1968 /* Hitting just return after this command should do the same thing as
1969 "show values +". If num_exp is null, this is unnecessary, since
1970 "show values +" is not useful after "show values". */
1971 if (from_tty && num_exp)
1972 set_repeat_arguments ("+");
1975 enum internalvar_kind
1977 /* The internal variable is empty. */
1978 INTERNALVAR_VOID,
1980 /* The value of the internal variable is provided directly as
1981 a GDB value object. */
1982 INTERNALVAR_VALUE,
1984 /* A fresh value is computed via a call-back routine on every
1985 access to the internal variable. */
1986 INTERNALVAR_MAKE_VALUE,
1988 /* The internal variable holds a GDB internal convenience function. */
1989 INTERNALVAR_FUNCTION,
1991 /* The variable holds an integer value. */
1992 INTERNALVAR_INTEGER,
1994 /* The variable holds a GDB-provided string. */
1995 INTERNALVAR_STRING,
1998 union internalvar_data
2000 /* A value object used with INTERNALVAR_VALUE. */
2001 struct value *value;
2003 /* The call-back routine used with INTERNALVAR_MAKE_VALUE. */
2004 struct
2006 /* The functions to call. */
2007 const struct internalvar_funcs *functions;
2009 /* The function's user-data. */
2010 void *data;
2011 } make_value;
2013 /* The internal function used with INTERNALVAR_FUNCTION. */
2014 struct
2016 struct internal_function *function;
2017 /* True if this is the canonical name for the function. */
2018 int canonical;
2019 } fn;
2021 /* An integer value used with INTERNALVAR_INTEGER. */
2022 struct
2024 /* If type is non-NULL, it will be used as the type to generate
2025 a value for this internal variable. If type is NULL, a default
2026 integer type for the architecture is used. */
2027 struct type *type;
2028 LONGEST val;
2029 } integer;
2031 /* A string value used with INTERNALVAR_STRING. */
2032 char *string;
2035 /* Internal variables. These are variables within the debugger
2036 that hold values assigned by debugger commands.
2037 The user refers to them with a '$' prefix
2038 that does not appear in the variable names stored internally. */
2040 struct internalvar
2042 struct internalvar *next;
2043 char *name;
2045 /* We support various different kinds of content of an internal variable.
2046 enum internalvar_kind specifies the kind, and union internalvar_data
2047 provides the data associated with this particular kind. */
2049 enum internalvar_kind kind;
2051 union internalvar_data u;
2054 static struct internalvar *internalvars;
2056 /* If the variable does not already exist create it and give it the
2057 value given. If no value is given then the default is zero. */
2058 static void
2059 init_if_undefined_command (const char* args, int from_tty)
2061 struct internalvar *intvar = nullptr;
2063 /* Parse the expression - this is taken from set_command(). */
2064 expression_up expr = parse_expression (args);
2066 /* Validate the expression.
2067 Was the expression an assignment?
2068 Or even an expression at all? */
2069 if (expr->first_opcode () != BINOP_ASSIGN)
2070 error (_("Init-if-undefined requires an assignment expression."));
2072 /* Extract the variable from the parsed expression. */
2073 expr::assign_operation *assign
2074 = dynamic_cast<expr::assign_operation *> (expr->op.get ());
2075 if (assign != nullptr)
2077 expr::operation *lhs = assign->get_lhs ();
2078 expr::internalvar_operation *ivarop
2079 = dynamic_cast<expr::internalvar_operation *> (lhs);
2080 if (ivarop != nullptr)
2081 intvar = ivarop->get_internalvar ();
2084 if (intvar == nullptr)
2085 error (_("The first parameter to init-if-undefined "
2086 "should be a GDB variable."));
2088 /* Only evaluate the expression if the lvalue is void.
2089 This may still fail if the expression is invalid. */
2090 if (intvar->kind == INTERNALVAR_VOID)
2091 evaluate_expression (expr.get ());
2095 /* Look up an internal variable with name NAME. NAME should not
2096 normally include a dollar sign.
2098 If the specified internal variable does not exist,
2099 the return value is NULL. */
2101 struct internalvar *
2102 lookup_only_internalvar (const char *name)
2104 struct internalvar *var;
2106 for (var = internalvars; var; var = var->next)
2107 if (strcmp (var->name, name) == 0)
2108 return var;
2110 return NULL;
2113 /* Complete NAME by comparing it to the names of internal
2114 variables. */
2116 void
2117 complete_internalvar (completion_tracker &tracker, const char *name)
2119 struct internalvar *var;
2120 int len;
2122 len = strlen (name);
2124 for (var = internalvars; var; var = var->next)
2125 if (strncmp (var->name, name, len) == 0)
2126 tracker.add_completion (make_unique_xstrdup (var->name));
2129 /* Create an internal variable with name NAME and with a void value.
2130 NAME should not normally include a dollar sign. */
2132 struct internalvar *
2133 create_internalvar (const char *name)
2135 struct internalvar *var = XNEW (struct internalvar);
2137 var->name = xstrdup (name);
2138 var->kind = INTERNALVAR_VOID;
2139 var->next = internalvars;
2140 internalvars = var;
2141 return var;
2144 /* Create an internal variable with name NAME and register FUN as the
2145 function that value_of_internalvar uses to create a value whenever
2146 this variable is referenced. NAME should not normally include a
2147 dollar sign. DATA is passed uninterpreted to FUN when it is
2148 called. CLEANUP, if not NULL, is called when the internal variable
2149 is destroyed. It is passed DATA as its only argument. */
2151 struct internalvar *
2152 create_internalvar_type_lazy (const char *name,
2153 const struct internalvar_funcs *funcs,
2154 void *data)
2156 struct internalvar *var = create_internalvar (name);
2158 var->kind = INTERNALVAR_MAKE_VALUE;
2159 var->u.make_value.functions = funcs;
2160 var->u.make_value.data = data;
2161 return var;
2164 /* See documentation in value.h. */
2167 compile_internalvar_to_ax (struct internalvar *var,
2168 struct agent_expr *expr,
2169 struct axs_value *value)
2171 if (var->kind != INTERNALVAR_MAKE_VALUE
2172 || var->u.make_value.functions->compile_to_ax == NULL)
2173 return 0;
2175 var->u.make_value.functions->compile_to_ax (var, expr, value,
2176 var->u.make_value.data);
2177 return 1;
2180 /* Look up an internal variable with name NAME. NAME should not
2181 normally include a dollar sign.
2183 If the specified internal variable does not exist,
2184 one is created, with a void value. */
2186 struct internalvar *
2187 lookup_internalvar (const char *name)
2189 struct internalvar *var;
2191 var = lookup_only_internalvar (name);
2192 if (var)
2193 return var;
2195 return create_internalvar (name);
2198 /* Return current value of internal variable VAR. For variables that
2199 are not inherently typed, use a value type appropriate for GDBARCH. */
2201 struct value *
2202 value_of_internalvar (struct gdbarch *gdbarch, struct internalvar *var)
2204 struct value *val;
2205 struct trace_state_variable *tsv;
2207 /* If there is a trace state variable of the same name, assume that
2208 is what we really want to see. */
2209 tsv = find_trace_state_variable (var->name);
2210 if (tsv)
2212 tsv->value_known = target_get_trace_state_variable_value (tsv->number,
2213 &(tsv->value));
2214 if (tsv->value_known)
2215 val = value_from_longest (builtin_type (gdbarch)->builtin_int64,
2216 tsv->value);
2217 else
2218 val = allocate_value (builtin_type (gdbarch)->builtin_void);
2219 return val;
2222 switch (var->kind)
2224 case INTERNALVAR_VOID:
2225 val = allocate_value (builtin_type (gdbarch)->builtin_void);
2226 break;
2228 case INTERNALVAR_FUNCTION:
2229 val = allocate_value (builtin_type (gdbarch)->internal_fn);
2230 break;
2232 case INTERNALVAR_INTEGER:
2233 if (!var->u.integer.type)
2234 val = value_from_longest (builtin_type (gdbarch)->builtin_int,
2235 var->u.integer.val);
2236 else
2237 val = value_from_longest (var->u.integer.type, var->u.integer.val);
2238 break;
2240 case INTERNALVAR_STRING:
2241 val = value_cstring (var->u.string, strlen (var->u.string),
2242 builtin_type (gdbarch)->builtin_char);
2243 break;
2245 case INTERNALVAR_VALUE:
2246 val = value_copy (var->u.value);
2247 if (value_lazy (val))
2248 value_fetch_lazy (val);
2249 break;
2251 case INTERNALVAR_MAKE_VALUE:
2252 val = (*var->u.make_value.functions->make_value) (gdbarch, var,
2253 var->u.make_value.data);
2254 break;
2256 default:
2257 internal_error (__FILE__, __LINE__, _("bad kind"));
2260 /* Change the VALUE_LVAL to lval_internalvar so that future operations
2261 on this value go back to affect the original internal variable.
2263 Do not do this for INTERNALVAR_MAKE_VALUE variables, as those have
2264 no underlying modifiable state in the internal variable.
2266 Likewise, if the variable's value is a computed lvalue, we want
2267 references to it to produce another computed lvalue, where
2268 references and assignments actually operate through the
2269 computed value's functions.
2271 This means that internal variables with computed values
2272 behave a little differently from other internal variables:
2273 assignments to them don't just replace the previous value
2274 altogether. At the moment, this seems like the behavior we
2275 want. */
2277 if (var->kind != INTERNALVAR_MAKE_VALUE
2278 && val->lval != lval_computed)
2280 VALUE_LVAL (val) = lval_internalvar;
2281 VALUE_INTERNALVAR (val) = var;
2284 return val;
2288 get_internalvar_integer (struct internalvar *var, LONGEST *result)
2290 if (var->kind == INTERNALVAR_INTEGER)
2292 *result = var->u.integer.val;
2293 return 1;
2296 if (var->kind == INTERNALVAR_VALUE)
2298 struct type *type = check_typedef (value_type (var->u.value));
2300 if (type->code () == TYPE_CODE_INT)
2302 *result = value_as_long (var->u.value);
2303 return 1;
2307 return 0;
2310 static int
2311 get_internalvar_function (struct internalvar *var,
2312 struct internal_function **result)
2314 switch (var->kind)
2316 case INTERNALVAR_FUNCTION:
2317 *result = var->u.fn.function;
2318 return 1;
2320 default:
2321 return 0;
2325 void
2326 set_internalvar_component (struct internalvar *var,
2327 LONGEST offset, LONGEST bitpos,
2328 LONGEST bitsize, struct value *newval)
2330 gdb_byte *addr;
2331 struct gdbarch *arch;
2332 int unit_size;
2334 switch (var->kind)
2336 case INTERNALVAR_VALUE:
2337 addr = value_contents_writeable (var->u.value).data ();
2338 arch = get_value_arch (var->u.value);
2339 unit_size = gdbarch_addressable_memory_unit_size (arch);
2341 if (bitsize)
2342 modify_field (value_type (var->u.value), addr + offset,
2343 value_as_long (newval), bitpos, bitsize);
2344 else
2345 memcpy (addr + offset * unit_size, value_contents (newval).data (),
2346 value_type (newval)->length ());
2347 break;
2349 default:
2350 /* We can never get a component of any other kind. */
2351 internal_error (__FILE__, __LINE__, _("set_internalvar_component"));
2355 void
2356 set_internalvar (struct internalvar *var, struct value *val)
2358 enum internalvar_kind new_kind;
2359 union internalvar_data new_data = { 0 };
2361 if (var->kind == INTERNALVAR_FUNCTION && var->u.fn.canonical)
2362 error (_("Cannot overwrite convenience function %s"), var->name);
2364 /* Prepare new contents. */
2365 switch (check_typedef (value_type (val))->code ())
2367 case TYPE_CODE_VOID:
2368 new_kind = INTERNALVAR_VOID;
2369 break;
2371 case TYPE_CODE_INTERNAL_FUNCTION:
2372 gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2373 new_kind = INTERNALVAR_FUNCTION;
2374 get_internalvar_function (VALUE_INTERNALVAR (val),
2375 &new_data.fn.function);
2376 /* Copies created here are never canonical. */
2377 break;
2379 default:
2380 new_kind = INTERNALVAR_VALUE;
2381 struct value *copy = value_copy (val);
2382 copy->modifiable = 1;
2384 /* Force the value to be fetched from the target now, to avoid problems
2385 later when this internalvar is referenced and the target is gone or
2386 has changed. */
2387 if (value_lazy (copy))
2388 value_fetch_lazy (copy);
2390 /* Release the value from the value chain to prevent it from being
2391 deleted by free_all_values. From here on this function should not
2392 call error () until new_data is installed into the var->u to avoid
2393 leaking memory. */
2394 new_data.value = release_value (copy).release ();
2396 /* Internal variables which are created from values with a dynamic
2397 location don't need the location property of the origin anymore.
2398 The resolved dynamic location is used prior then any other address
2399 when accessing the value.
2400 If we keep it, we would still refer to the origin value.
2401 Remove the location property in case it exist. */
2402 value_type (new_data.value)->remove_dyn_prop (DYN_PROP_DATA_LOCATION);
2404 break;
2407 /* Clean up old contents. */
2408 clear_internalvar (var);
2410 /* Switch over. */
2411 var->kind = new_kind;
2412 var->u = new_data;
2413 /* End code which must not call error(). */
2416 void
2417 set_internalvar_integer (struct internalvar *var, LONGEST l)
2419 /* Clean up old contents. */
2420 clear_internalvar (var);
2422 var->kind = INTERNALVAR_INTEGER;
2423 var->u.integer.type = NULL;
2424 var->u.integer.val = l;
2427 void
2428 set_internalvar_string (struct internalvar *var, const char *string)
2430 /* Clean up old contents. */
2431 clear_internalvar (var);
2433 var->kind = INTERNALVAR_STRING;
2434 var->u.string = xstrdup (string);
2437 static void
2438 set_internalvar_function (struct internalvar *var, struct internal_function *f)
2440 /* Clean up old contents. */
2441 clear_internalvar (var);
2443 var->kind = INTERNALVAR_FUNCTION;
2444 var->u.fn.function = f;
2445 var->u.fn.canonical = 1;
2446 /* Variables installed here are always the canonical version. */
2449 void
2450 clear_internalvar (struct internalvar *var)
2452 /* Clean up old contents. */
2453 switch (var->kind)
2455 case INTERNALVAR_VALUE:
2456 value_decref (var->u.value);
2457 break;
2459 case INTERNALVAR_STRING:
2460 xfree (var->u.string);
2461 break;
2463 default:
2464 break;
2467 /* Reset to void kind. */
2468 var->kind = INTERNALVAR_VOID;
2471 const char *
2472 internalvar_name (const struct internalvar *var)
2474 return var->name;
2477 static struct internal_function *
2478 create_internal_function (const char *name,
2479 internal_function_fn handler, void *cookie)
2481 struct internal_function *ifn = XNEW (struct internal_function);
2483 ifn->name = xstrdup (name);
2484 ifn->handler = handler;
2485 ifn->cookie = cookie;
2486 return ifn;
2489 const char *
2490 value_internal_function_name (struct value *val)
2492 struct internal_function *ifn;
2493 int result;
2495 gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2496 result = get_internalvar_function (VALUE_INTERNALVAR (val), &ifn);
2497 gdb_assert (result);
2499 return ifn->name;
2502 struct value *
2503 call_internal_function (struct gdbarch *gdbarch,
2504 const struct language_defn *language,
2505 struct value *func, int argc, struct value **argv)
2507 struct internal_function *ifn;
2508 int result;
2510 gdb_assert (VALUE_LVAL (func) == lval_internalvar);
2511 result = get_internalvar_function (VALUE_INTERNALVAR (func), &ifn);
2512 gdb_assert (result);
2514 return (*ifn->handler) (gdbarch, language, ifn->cookie, argc, argv);
2517 /* The 'function' command. This does nothing -- it is just a
2518 placeholder to let "help function NAME" work. This is also used as
2519 the implementation of the sub-command that is created when
2520 registering an internal function. */
2521 static void
2522 function_command (const char *command, int from_tty)
2524 /* Do nothing. */
2527 /* Helper function that does the work for add_internal_function. */
2529 static struct cmd_list_element *
2530 do_add_internal_function (const char *name, const char *doc,
2531 internal_function_fn handler, void *cookie)
2533 struct internal_function *ifn;
2534 struct internalvar *var = lookup_internalvar (name);
2536 ifn = create_internal_function (name, handler, cookie);
2537 set_internalvar_function (var, ifn);
2539 return add_cmd (name, no_class, function_command, doc, &functionlist);
2542 /* See value.h. */
2544 void
2545 add_internal_function (const char *name, const char *doc,
2546 internal_function_fn handler, void *cookie)
2548 do_add_internal_function (name, doc, handler, cookie);
2551 /* See value.h. */
2553 void
2554 add_internal_function (gdb::unique_xmalloc_ptr<char> &&name,
2555 gdb::unique_xmalloc_ptr<char> &&doc,
2556 internal_function_fn handler, void *cookie)
2558 struct cmd_list_element *cmd
2559 = do_add_internal_function (name.get (), doc.get (), handler, cookie);
2560 doc.release ();
2561 cmd->doc_allocated = 1;
2562 name.release ();
2563 cmd->name_allocated = 1;
2566 /* Update VALUE before discarding OBJFILE. COPIED_TYPES is used to
2567 prevent cycles / duplicates. */
2569 void
2570 preserve_one_value (struct value *value, struct objfile *objfile,
2571 htab_t copied_types)
2573 if (value->type->objfile_owner () == objfile)
2574 value->type = copy_type_recursive (value->type, copied_types);
2576 if (value->enclosing_type->objfile_owner () == objfile)
2577 value->enclosing_type = copy_type_recursive (value->enclosing_type,
2578 copied_types);
2581 /* Likewise for internal variable VAR. */
2583 static void
2584 preserve_one_internalvar (struct internalvar *var, struct objfile *objfile,
2585 htab_t copied_types)
2587 switch (var->kind)
2589 case INTERNALVAR_INTEGER:
2590 if (var->u.integer.type
2591 && var->u.integer.type->objfile_owner () == objfile)
2592 var->u.integer.type
2593 = copy_type_recursive (var->u.integer.type, copied_types);
2594 break;
2596 case INTERNALVAR_VALUE:
2597 preserve_one_value (var->u.value, objfile, copied_types);
2598 break;
2602 /* Make sure that all types and values referenced by VAROBJ are updated before
2603 OBJFILE is discarded. COPIED_TYPES is used to prevent cycles and
2604 duplicates. */
2606 static void
2607 preserve_one_varobj (struct varobj *varobj, struct objfile *objfile,
2608 htab_t copied_types)
2610 if (varobj->type->is_objfile_owned ()
2611 && varobj->type->objfile_owner () == objfile)
2613 varobj->type
2614 = copy_type_recursive (varobj->type, copied_types);
2617 if (varobj->value != nullptr)
2618 preserve_one_value (varobj->value.get (), objfile, copied_types);
2621 /* Update the internal variables and value history when OBJFILE is
2622 discarded; we must copy the types out of the objfile. New global types
2623 will be created for every convenience variable which currently points to
2624 this objfile's types, and the convenience variables will be adjusted to
2625 use the new global types. */
2627 void
2628 preserve_values (struct objfile *objfile)
2630 struct internalvar *var;
2632 /* Create the hash table. We allocate on the objfile's obstack, since
2633 it is soon to be deleted. */
2634 htab_up copied_types = create_copied_types_hash ();
2636 for (const value_ref_ptr &item : value_history)
2637 preserve_one_value (item.get (), objfile, copied_types.get ());
2639 for (var = internalvars; var; var = var->next)
2640 preserve_one_internalvar (var, objfile, copied_types.get ());
2642 /* For the remaining varobj, check that none has type owned by OBJFILE. */
2643 all_root_varobjs ([&copied_types, objfile] (struct varobj *varobj)
2645 preserve_one_varobj (varobj, objfile,
2646 copied_types.get ());
2649 preserve_ext_lang_values (objfile, copied_types.get ());
2652 static void
2653 show_convenience (const char *ignore, int from_tty)
2655 struct gdbarch *gdbarch = get_current_arch ();
2656 struct internalvar *var;
2657 int varseen = 0;
2658 struct value_print_options opts;
2660 get_user_print_options (&opts);
2661 for (var = internalvars; var; var = var->next)
2664 if (!varseen)
2666 varseen = 1;
2668 gdb_printf (("$%s = "), var->name);
2672 struct value *val;
2674 val = value_of_internalvar (gdbarch, var);
2675 value_print (val, gdb_stdout, &opts);
2677 catch (const gdb_exception_error &ex)
2679 fprintf_styled (gdb_stdout, metadata_style.style (),
2680 _("<error: %s>"), ex.what ());
2683 gdb_printf (("\n"));
2685 if (!varseen)
2687 /* This text does not mention convenience functions on purpose.
2688 The user can't create them except via Python, and if Python support
2689 is installed this message will never be printed ($_streq will
2690 exist). */
2691 gdb_printf (_("No debugger convenience variables now defined.\n"
2692 "Convenience variables have "
2693 "names starting with \"$\";\n"
2694 "use \"set\" as in \"set "
2695 "$foo = 5\" to define them.\n"));
2700 /* See value.h. */
2702 struct value *
2703 value_from_xmethod (xmethod_worker_up &&worker)
2705 struct value *v;
2707 v = allocate_value (builtin_type (target_gdbarch ())->xmethod);
2708 v->lval = lval_xcallable;
2709 v->location.xm_worker = worker.release ();
2710 v->modifiable = 0;
2712 return v;
2715 /* Return the type of the result of TYPE_CODE_XMETHOD value METHOD. */
2717 struct type *
2718 result_type_of_xmethod (struct value *method, gdb::array_view<value *> argv)
2720 gdb_assert (value_type (method)->code () == TYPE_CODE_XMETHOD
2721 && method->lval == lval_xcallable && !argv.empty ());
2723 return method->location.xm_worker->get_result_type (argv[0], argv.slice (1));
2726 /* Call the xmethod corresponding to the TYPE_CODE_XMETHOD value METHOD. */
2728 struct value *
2729 call_xmethod (struct value *method, gdb::array_view<value *> argv)
2731 gdb_assert (value_type (method)->code () == TYPE_CODE_XMETHOD
2732 && method->lval == lval_xcallable && !argv.empty ());
2734 return method->location.xm_worker->invoke (argv[0], argv.slice (1));
2737 /* Extract a value as a C number (either long or double).
2738 Knows how to convert fixed values to double, or
2739 floating values to long.
2740 Does not deallocate the value. */
2742 LONGEST
2743 value_as_long (struct value *val)
2745 /* This coerces arrays and functions, which is necessary (e.g.
2746 in disassemble_command). It also dereferences references, which
2747 I suspect is the most logical thing to do. */
2748 val = coerce_array (val);
2749 return unpack_long (value_type (val), value_contents (val).data ());
2752 /* Extract a value as a C pointer. Does not deallocate the value.
2753 Note that val's type may not actually be a pointer; value_as_long
2754 handles all the cases. */
2755 CORE_ADDR
2756 value_as_address (struct value *val)
2758 struct gdbarch *gdbarch = value_type (val)->arch ();
2760 /* Assume a CORE_ADDR can fit in a LONGEST (for now). Not sure
2761 whether we want this to be true eventually. */
2762 #if 0
2763 /* gdbarch_addr_bits_remove is wrong if we are being called for a
2764 non-address (e.g. argument to "signal", "info break", etc.), or
2765 for pointers to char, in which the low bits *are* significant. */
2766 return gdbarch_addr_bits_remove (gdbarch, value_as_long (val));
2767 #else
2769 /* There are several targets (IA-64, PowerPC, and others) which
2770 don't represent pointers to functions as simply the address of
2771 the function's entry point. For example, on the IA-64, a
2772 function pointer points to a two-word descriptor, generated by
2773 the linker, which contains the function's entry point, and the
2774 value the IA-64 "global pointer" register should have --- to
2775 support position-independent code. The linker generates
2776 descriptors only for those functions whose addresses are taken.
2778 On such targets, it's difficult for GDB to convert an arbitrary
2779 function address into a function pointer; it has to either find
2780 an existing descriptor for that function, or call malloc and
2781 build its own. On some targets, it is impossible for GDB to
2782 build a descriptor at all: the descriptor must contain a jump
2783 instruction; data memory cannot be executed; and code memory
2784 cannot be modified.
2786 Upon entry to this function, if VAL is a value of type `function'
2787 (that is, TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FUNC), then
2788 value_address (val) is the address of the function. This is what
2789 you'll get if you evaluate an expression like `main'. The call
2790 to COERCE_ARRAY below actually does all the usual unary
2791 conversions, which includes converting values of type `function'
2792 to `pointer to function'. This is the challenging conversion
2793 discussed above. Then, `unpack_long' will convert that pointer
2794 back into an address.
2796 So, suppose the user types `disassemble foo' on an architecture
2797 with a strange function pointer representation, on which GDB
2798 cannot build its own descriptors, and suppose further that `foo'
2799 has no linker-built descriptor. The address->pointer conversion
2800 will signal an error and prevent the command from running, even
2801 though the next step would have been to convert the pointer
2802 directly back into the same address.
2804 The following shortcut avoids this whole mess. If VAL is a
2805 function, just return its address directly. */
2806 if (value_type (val)->code () == TYPE_CODE_FUNC
2807 || value_type (val)->code () == TYPE_CODE_METHOD)
2808 return value_address (val);
2810 val = coerce_array (val);
2812 /* Some architectures (e.g. Harvard), map instruction and data
2813 addresses onto a single large unified address space. For
2814 instance: An architecture may consider a large integer in the
2815 range 0x10000000 .. 0x1000ffff to already represent a data
2816 addresses (hence not need a pointer to address conversion) while
2817 a small integer would still need to be converted integer to
2818 pointer to address. Just assume such architectures handle all
2819 integer conversions in a single function. */
2821 /* JimB writes:
2823 I think INTEGER_TO_ADDRESS is a good idea as proposed --- but we
2824 must admonish GDB hackers to make sure its behavior matches the
2825 compiler's, whenever possible.
2827 In general, I think GDB should evaluate expressions the same way
2828 the compiler does. When the user copies an expression out of
2829 their source code and hands it to a `print' command, they should
2830 get the same value the compiler would have computed. Any
2831 deviation from this rule can cause major confusion and annoyance,
2832 and needs to be justified carefully. In other words, GDB doesn't
2833 really have the freedom to do these conversions in clever and
2834 useful ways.
2836 AndrewC pointed out that users aren't complaining about how GDB
2837 casts integers to pointers; they are complaining that they can't
2838 take an address from a disassembly listing and give it to `x/i'.
2839 This is certainly important.
2841 Adding an architecture method like integer_to_address() certainly
2842 makes it possible for GDB to "get it right" in all circumstances
2843 --- the target has complete control over how things get done, so
2844 people can Do The Right Thing for their target without breaking
2845 anyone else. The standard doesn't specify how integers get
2846 converted to pointers; usually, the ABI doesn't either, but
2847 ABI-specific code is a more reasonable place to handle it. */
2849 if (!value_type (val)->is_pointer_or_reference ()
2850 && gdbarch_integer_to_address_p (gdbarch))
2851 return gdbarch_integer_to_address (gdbarch, value_type (val),
2852 value_contents (val).data ());
2854 return unpack_long (value_type (val), value_contents (val).data ());
2855 #endif
2858 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2859 as a long, or as a double, assuming the raw data is described
2860 by type TYPE. Knows how to convert different sizes of values
2861 and can convert between fixed and floating point. We don't assume
2862 any alignment for the raw data. Return value is in host byte order.
2864 If you want functions and arrays to be coerced to pointers, and
2865 references to be dereferenced, call value_as_long() instead.
2867 C++: It is assumed that the front-end has taken care of
2868 all matters concerning pointers to members. A pointer
2869 to member which reaches here is considered to be equivalent
2870 to an INT (or some size). After all, it is only an offset. */
2872 LONGEST
2873 unpack_long (struct type *type, const gdb_byte *valaddr)
2875 if (is_fixed_point_type (type))
2876 type = type->fixed_point_type_base_type ();
2878 enum bfd_endian byte_order = type_byte_order (type);
2879 enum type_code code = type->code ();
2880 int len = type->length ();
2881 int nosign = type->is_unsigned ();
2883 switch (code)
2885 case TYPE_CODE_TYPEDEF:
2886 return unpack_long (check_typedef (type), valaddr);
2887 case TYPE_CODE_ENUM:
2888 case TYPE_CODE_FLAGS:
2889 case TYPE_CODE_BOOL:
2890 case TYPE_CODE_INT:
2891 case TYPE_CODE_CHAR:
2892 case TYPE_CODE_RANGE:
2893 case TYPE_CODE_MEMBERPTR:
2895 LONGEST result;
2897 if (type->bit_size_differs_p ())
2899 unsigned bit_off = type->bit_offset ();
2900 unsigned bit_size = type->bit_size ();
2901 if (bit_size == 0)
2903 /* unpack_bits_as_long doesn't handle this case the
2904 way we'd like, so handle it here. */
2905 result = 0;
2907 else
2908 result = unpack_bits_as_long (type, valaddr, bit_off, bit_size);
2910 else
2912 if (nosign)
2913 result = extract_unsigned_integer (valaddr, len, byte_order);
2914 else
2915 result = extract_signed_integer (valaddr, len, byte_order);
2917 if (code == TYPE_CODE_RANGE)
2918 result += type->bounds ()->bias;
2919 return result;
2922 case TYPE_CODE_FLT:
2923 case TYPE_CODE_DECFLOAT:
2924 return target_float_to_longest (valaddr, type);
2926 case TYPE_CODE_FIXED_POINT:
2928 gdb_mpq vq;
2929 vq.read_fixed_point (gdb::make_array_view (valaddr, len),
2930 byte_order, nosign,
2931 type->fixed_point_scaling_factor ());
2933 gdb_mpz vz;
2934 mpz_tdiv_q (vz.val, mpq_numref (vq.val), mpq_denref (vq.val));
2935 return vz.as_integer<LONGEST> ();
2938 case TYPE_CODE_PTR:
2939 case TYPE_CODE_REF:
2940 case TYPE_CODE_RVALUE_REF:
2941 /* Assume a CORE_ADDR can fit in a LONGEST (for now). Not sure
2942 whether we want this to be true eventually. */
2943 return extract_typed_address (valaddr, type);
2945 default:
2946 error (_("Value can't be converted to integer."));
2950 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2951 as a CORE_ADDR, assuming the raw data is described by type TYPE.
2952 We don't assume any alignment for the raw data. Return value is in
2953 host byte order.
2955 If you want functions and arrays to be coerced to pointers, and
2956 references to be dereferenced, call value_as_address() instead.
2958 C++: It is assumed that the front-end has taken care of
2959 all matters concerning pointers to members. A pointer
2960 to member which reaches here is considered to be equivalent
2961 to an INT (or some size). After all, it is only an offset. */
2963 CORE_ADDR
2964 unpack_pointer (struct type *type, const gdb_byte *valaddr)
2966 /* Assume a CORE_ADDR can fit in a LONGEST (for now). Not sure
2967 whether we want this to be true eventually. */
2968 return unpack_long (type, valaddr);
2971 bool
2972 is_floating_value (struct value *val)
2974 struct type *type = check_typedef (value_type (val));
2976 if (is_floating_type (type))
2978 if (!target_float_is_valid (value_contents (val).data (), type))
2979 error (_("Invalid floating value found in program."));
2980 return true;
2983 return false;
2987 /* Get the value of the FIELDNO'th field (which must be static) of
2988 TYPE. */
2990 struct value *
2991 value_static_field (struct type *type, int fieldno)
2993 struct value *retval;
2995 switch (type->field (fieldno).loc_kind ())
2997 case FIELD_LOC_KIND_PHYSADDR:
2998 retval = value_at_lazy (type->field (fieldno).type (),
2999 type->field (fieldno).loc_physaddr ());
3000 break;
3001 case FIELD_LOC_KIND_PHYSNAME:
3003 const char *phys_name = type->field (fieldno).loc_physname ();
3004 /* type->field (fieldno).name (); */
3005 struct block_symbol sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0);
3007 if (sym.symbol == NULL)
3009 /* With some compilers, e.g. HP aCC, static data members are
3010 reported as non-debuggable symbols. */
3011 struct bound_minimal_symbol msym
3012 = lookup_minimal_symbol (phys_name, NULL, NULL);
3013 struct type *field_type = type->field (fieldno).type ();
3015 if (!msym.minsym)
3016 retval = allocate_optimized_out_value (field_type);
3017 else
3018 retval = value_at_lazy (field_type, msym.value_address ());
3020 else
3021 retval = value_of_variable (sym.symbol, sym.block);
3022 break;
3024 default:
3025 gdb_assert_not_reached ("unexpected field location kind");
3028 return retval;
3031 /* Change the enclosing type of a value object VAL to NEW_ENCL_TYPE.
3032 You have to be careful here, since the size of the data area for the value
3033 is set by the length of the enclosing type. So if NEW_ENCL_TYPE is bigger
3034 than the old enclosing type, you have to allocate more space for the
3035 data. */
3037 void
3038 set_value_enclosing_type (struct value *val, struct type *new_encl_type)
3040 if (new_encl_type->length () > value_enclosing_type (val)->length ())
3042 check_type_length_before_alloc (new_encl_type);
3043 val->contents
3044 .reset ((gdb_byte *) xrealloc (val->contents.release (),
3045 new_encl_type->length ()));
3048 val->enclosing_type = new_encl_type;
3051 /* Given a value ARG1 (offset by OFFSET bytes)
3052 of a struct or union type ARG_TYPE,
3053 extract and return the value of one of its (non-static) fields.
3054 FIELDNO says which field. */
3056 struct value *
3057 value_primitive_field (struct value *arg1, LONGEST offset,
3058 int fieldno, struct type *arg_type)
3060 struct value *v;
3061 struct type *type;
3062 struct gdbarch *arch = get_value_arch (arg1);
3063 int unit_size = gdbarch_addressable_memory_unit_size (arch);
3065 arg_type = check_typedef (arg_type);
3066 type = arg_type->field (fieldno).type ();
3068 /* Call check_typedef on our type to make sure that, if TYPE
3069 is a TYPE_CODE_TYPEDEF, its length is set to the length
3070 of the target type instead of zero. However, we do not
3071 replace the typedef type by the target type, because we want
3072 to keep the typedef in order to be able to print the type
3073 description correctly. */
3074 check_typedef (type);
3076 if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
3078 /* Handle packed fields.
3080 Create a new value for the bitfield, with bitpos and bitsize
3081 set. If possible, arrange offset and bitpos so that we can
3082 do a single aligned read of the size of the containing type.
3083 Otherwise, adjust offset to the byte containing the first
3084 bit. Assume that the address, offset, and embedded offset
3085 are sufficiently aligned. */
3087 LONGEST bitpos = arg_type->field (fieldno).loc_bitpos ();
3088 LONGEST container_bitsize = type->length () * 8;
3090 v = allocate_value_lazy (type);
3091 v->bitsize = TYPE_FIELD_BITSIZE (arg_type, fieldno);
3092 if ((bitpos % container_bitsize) + v->bitsize <= container_bitsize
3093 && type->length () <= (int) sizeof (LONGEST))
3094 v->bitpos = bitpos % container_bitsize;
3095 else
3096 v->bitpos = bitpos % 8;
3097 v->offset = (value_embedded_offset (arg1)
3098 + offset
3099 + (bitpos - v->bitpos) / 8);
3100 set_value_parent (v, arg1);
3101 if (!value_lazy (arg1))
3102 value_fetch_lazy (v);
3104 else if (fieldno < TYPE_N_BASECLASSES (arg_type))
3106 /* This field is actually a base subobject, so preserve the
3107 entire object's contents for later references to virtual
3108 bases, etc. */
3109 LONGEST boffset;
3111 /* Lazy register values with offsets are not supported. */
3112 if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
3113 value_fetch_lazy (arg1);
3115 /* We special case virtual inheritance here because this
3116 requires access to the contents, which we would rather avoid
3117 for references to ordinary fields of unavailable values. */
3118 if (BASETYPE_VIA_VIRTUAL (arg_type, fieldno))
3119 boffset = baseclass_offset (arg_type, fieldno,
3120 value_contents (arg1).data (),
3121 value_embedded_offset (arg1),
3122 value_address (arg1),
3123 arg1);
3124 else
3125 boffset = arg_type->field (fieldno).loc_bitpos () / 8;
3127 if (value_lazy (arg1))
3128 v = allocate_value_lazy (value_enclosing_type (arg1));
3129 else
3131 v = allocate_value (value_enclosing_type (arg1));
3132 value_contents_copy_raw (v, 0, arg1, 0,
3133 value_enclosing_type (arg1)->length ());
3135 v->type = type;
3136 v->offset = value_offset (arg1);
3137 v->embedded_offset = offset + value_embedded_offset (arg1) + boffset;
3139 else if (NULL != TYPE_DATA_LOCATION (type))
3141 /* Field is a dynamic data member. */
3143 gdb_assert (0 == offset);
3144 /* We expect an already resolved data location. */
3145 gdb_assert (PROP_CONST == TYPE_DATA_LOCATION_KIND (type));
3146 /* For dynamic data types defer memory allocation
3147 until we actual access the value. */
3148 v = allocate_value_lazy (type);
3150 else
3152 /* Plain old data member */
3153 offset += (arg_type->field (fieldno).loc_bitpos ()
3154 / (HOST_CHAR_BIT * unit_size));
3156 /* Lazy register values with offsets are not supported. */
3157 if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
3158 value_fetch_lazy (arg1);
3160 if (value_lazy (arg1))
3161 v = allocate_value_lazy (type);
3162 else
3164 v = allocate_value (type);
3165 value_contents_copy_raw (v, value_embedded_offset (v),
3166 arg1, value_embedded_offset (arg1) + offset,
3167 type_length_units (type));
3169 v->offset = (value_offset (arg1) + offset
3170 + value_embedded_offset (arg1));
3172 set_value_component_location (v, arg1);
3173 return v;
3176 /* Given a value ARG1 of a struct or union type,
3177 extract and return the value of one of its (non-static) fields.
3178 FIELDNO says which field. */
3180 struct value *
3181 value_field (struct value *arg1, int fieldno)
3183 return value_primitive_field (arg1, 0, fieldno, value_type (arg1));
3186 /* Return a non-virtual function as a value.
3187 F is the list of member functions which contains the desired method.
3188 J is an index into F which provides the desired method.
3190 We only use the symbol for its address, so be happy with either a
3191 full symbol or a minimal symbol. */
3193 struct value *
3194 value_fn_field (struct value **arg1p, struct fn_field *f,
3195 int j, struct type *type,
3196 LONGEST offset)
3198 struct value *v;
3199 struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
3200 const char *physname = TYPE_FN_FIELD_PHYSNAME (f, j);
3201 struct symbol *sym;
3202 struct bound_minimal_symbol msym;
3204 sym = lookup_symbol (physname, 0, VAR_DOMAIN, 0).symbol;
3205 if (sym == nullptr)
3207 msym = lookup_bound_minimal_symbol (physname);
3208 if (msym.minsym == NULL)
3209 return NULL;
3212 v = allocate_value (ftype);
3213 VALUE_LVAL (v) = lval_memory;
3214 if (sym)
3216 set_value_address (v, sym->value_block ()->entry_pc ());
3218 else
3220 /* The minimal symbol might point to a function descriptor;
3221 resolve it to the actual code address instead. */
3222 struct objfile *objfile = msym.objfile;
3223 struct gdbarch *gdbarch = objfile->arch ();
3225 set_value_address (v,
3226 gdbarch_convert_from_func_ptr_addr
3227 (gdbarch, msym.value_address (),
3228 current_inferior ()->top_target ()));
3231 if (arg1p)
3233 if (type != value_type (*arg1p))
3234 *arg1p = value_ind (value_cast (lookup_pointer_type (type),
3235 value_addr (*arg1p)));
3237 /* Move the `this' pointer according to the offset.
3238 VALUE_OFFSET (*arg1p) += offset; */
3241 return v;
3246 /* See value.h. */
3248 LONGEST
3249 unpack_bits_as_long (struct type *field_type, const gdb_byte *valaddr,
3250 LONGEST bitpos, LONGEST bitsize)
3252 enum bfd_endian byte_order = type_byte_order (field_type);
3253 ULONGEST val;
3254 ULONGEST valmask;
3255 int lsbcount;
3256 LONGEST bytes_read;
3257 LONGEST read_offset;
3259 /* Read the minimum number of bytes required; there may not be
3260 enough bytes to read an entire ULONGEST. */
3261 field_type = check_typedef (field_type);
3262 if (bitsize)
3263 bytes_read = ((bitpos % 8) + bitsize + 7) / 8;
3264 else
3266 bytes_read = field_type->length ();
3267 bitsize = 8 * bytes_read;
3270 read_offset = bitpos / 8;
3272 val = extract_unsigned_integer (valaddr + read_offset,
3273 bytes_read, byte_order);
3275 /* Extract bits. See comment above. */
3277 if (byte_order == BFD_ENDIAN_BIG)
3278 lsbcount = (bytes_read * 8 - bitpos % 8 - bitsize);
3279 else
3280 lsbcount = (bitpos % 8);
3281 val >>= lsbcount;
3283 /* If the field does not entirely fill a LONGEST, then zero the sign bits.
3284 If the field is signed, and is negative, then sign extend. */
3286 if (bitsize < 8 * (int) sizeof (val))
3288 valmask = (((ULONGEST) 1) << bitsize) - 1;
3289 val &= valmask;
3290 if (!field_type->is_unsigned ())
3292 if (val & (valmask ^ (valmask >> 1)))
3294 val |= ~valmask;
3299 return val;
3302 /* Unpack a field FIELDNO of the specified TYPE, from the object at
3303 VALADDR + EMBEDDED_OFFSET. VALADDR points to the contents of
3304 ORIGINAL_VALUE, which must not be NULL. See
3305 unpack_value_bits_as_long for more details. */
3308 unpack_value_field_as_long (struct type *type, const gdb_byte *valaddr,
3309 LONGEST embedded_offset, int fieldno,
3310 const struct value *val, LONGEST *result)
3312 int bitpos = type->field (fieldno).loc_bitpos ();
3313 int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3314 struct type *field_type = type->field (fieldno).type ();
3315 int bit_offset;
3317 gdb_assert (val != NULL);
3319 bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
3320 if (value_bits_any_optimized_out (val, bit_offset, bitsize)
3321 || !value_bits_available (val, bit_offset, bitsize))
3322 return 0;
3324 *result = unpack_bits_as_long (field_type, valaddr + embedded_offset,
3325 bitpos, bitsize);
3326 return 1;
3329 /* Unpack a field FIELDNO of the specified TYPE, from the anonymous
3330 object at VALADDR. See unpack_bits_as_long for more details. */
3332 LONGEST
3333 unpack_field_as_long (struct type *type, const gdb_byte *valaddr, int fieldno)
3335 int bitpos = type->field (fieldno).loc_bitpos ();
3336 int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3337 struct type *field_type = type->field (fieldno).type ();
3339 return unpack_bits_as_long (field_type, valaddr, bitpos, bitsize);
3342 /* Unpack a bitfield of BITSIZE bits found at BITPOS in the object at
3343 VALADDR + EMBEDDEDOFFSET that has the type of DEST_VAL and store
3344 the contents in DEST_VAL, zero or sign extending if the type of
3345 DEST_VAL is wider than BITSIZE. VALADDR points to the contents of
3346 VAL. If the VAL's contents required to extract the bitfield from
3347 are unavailable/optimized out, DEST_VAL is correspondingly
3348 marked unavailable/optimized out. */
3350 void
3351 unpack_value_bitfield (struct value *dest_val,
3352 LONGEST bitpos, LONGEST bitsize,
3353 const gdb_byte *valaddr, LONGEST embedded_offset,
3354 const struct value *val)
3356 enum bfd_endian byte_order;
3357 int src_bit_offset;
3358 int dst_bit_offset;
3359 struct type *field_type = value_type (dest_val);
3361 byte_order = type_byte_order (field_type);
3363 /* First, unpack and sign extend the bitfield as if it was wholly
3364 valid. Optimized out/unavailable bits are read as zero, but
3365 that's OK, as they'll end up marked below. If the VAL is
3366 wholly-invalid we may have skipped allocating its contents,
3367 though. See allocate_optimized_out_value. */
3368 if (valaddr != NULL)
3370 LONGEST num;
3372 num = unpack_bits_as_long (field_type, valaddr + embedded_offset,
3373 bitpos, bitsize);
3374 store_signed_integer (value_contents_raw (dest_val).data (),
3375 field_type->length (), byte_order, num);
3378 /* Now copy the optimized out / unavailability ranges to the right
3379 bits. */
3380 src_bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
3381 if (byte_order == BFD_ENDIAN_BIG)
3382 dst_bit_offset = field_type->length () * TARGET_CHAR_BIT - bitsize;
3383 else
3384 dst_bit_offset = 0;
3385 value_ranges_copy_adjusted (dest_val, dst_bit_offset,
3386 val, src_bit_offset, bitsize);
3389 /* Return a new value with type TYPE, which is FIELDNO field of the
3390 object at VALADDR + EMBEDDEDOFFSET. VALADDR points to the contents
3391 of VAL. If the VAL's contents required to extract the bitfield
3392 from are unavailable/optimized out, the new value is
3393 correspondingly marked unavailable/optimized out. */
3395 struct value *
3396 value_field_bitfield (struct type *type, int fieldno,
3397 const gdb_byte *valaddr,
3398 LONGEST embedded_offset, const struct value *val)
3400 int bitpos = type->field (fieldno).loc_bitpos ();
3401 int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3402 struct value *res_val = allocate_value (type->field (fieldno).type ());
3404 unpack_value_bitfield (res_val, bitpos, bitsize,
3405 valaddr, embedded_offset, val);
3407 return res_val;
3410 /* Modify the value of a bitfield. ADDR points to a block of memory in
3411 target byte order; the bitfield starts in the byte pointed to. FIELDVAL
3412 is the desired value of the field, in host byte order. BITPOS and BITSIZE
3413 indicate which bits (in target bit order) comprise the bitfield.
3414 Requires 0 < BITSIZE <= lbits, 0 <= BITPOS % 8 + BITSIZE <= lbits, and
3415 0 <= BITPOS, where lbits is the size of a LONGEST in bits. */
3417 void
3418 modify_field (struct type *type, gdb_byte *addr,
3419 LONGEST fieldval, LONGEST bitpos, LONGEST bitsize)
3421 enum bfd_endian byte_order = type_byte_order (type);
3422 ULONGEST oword;
3423 ULONGEST mask = (ULONGEST) -1 >> (8 * sizeof (ULONGEST) - bitsize);
3424 LONGEST bytesize;
3426 /* Normalize BITPOS. */
3427 addr += bitpos / 8;
3428 bitpos %= 8;
3430 /* If a negative fieldval fits in the field in question, chop
3431 off the sign extension bits. */
3432 if ((~fieldval & ~(mask >> 1)) == 0)
3433 fieldval &= mask;
3435 /* Warn if value is too big to fit in the field in question. */
3436 if (0 != (fieldval & ~mask))
3438 /* FIXME: would like to include fieldval in the message, but
3439 we don't have a sprintf_longest. */
3440 warning (_("Value does not fit in %s bits."), plongest (bitsize));
3442 /* Truncate it, otherwise adjoining fields may be corrupted. */
3443 fieldval &= mask;
3446 /* Ensure no bytes outside of the modified ones get accessed as it may cause
3447 false valgrind reports. */
3449 bytesize = (bitpos + bitsize + 7) / 8;
3450 oword = extract_unsigned_integer (addr, bytesize, byte_order);
3452 /* Shifting for bit field depends on endianness of the target machine. */
3453 if (byte_order == BFD_ENDIAN_BIG)
3454 bitpos = bytesize * 8 - bitpos - bitsize;
3456 oword &= ~(mask << bitpos);
3457 oword |= fieldval << bitpos;
3459 store_unsigned_integer (addr, bytesize, byte_order, oword);
3462 /* Pack NUM into BUF using a target format of TYPE. */
3464 void
3465 pack_long (gdb_byte *buf, struct type *type, LONGEST num)
3467 enum bfd_endian byte_order = type_byte_order (type);
3468 LONGEST len;
3470 type = check_typedef (type);
3471 len = type->length ();
3473 switch (type->code ())
3475 case TYPE_CODE_RANGE:
3476 num -= type->bounds ()->bias;
3477 /* Fall through. */
3478 case TYPE_CODE_INT:
3479 case TYPE_CODE_CHAR:
3480 case TYPE_CODE_ENUM:
3481 case TYPE_CODE_FLAGS:
3482 case TYPE_CODE_BOOL:
3483 case TYPE_CODE_MEMBERPTR:
3484 if (type->bit_size_differs_p ())
3486 unsigned bit_off = type->bit_offset ();
3487 unsigned bit_size = type->bit_size ();
3488 num &= ((ULONGEST) 1 << bit_size) - 1;
3489 num <<= bit_off;
3491 store_signed_integer (buf, len, byte_order, num);
3492 break;
3494 case TYPE_CODE_REF:
3495 case TYPE_CODE_RVALUE_REF:
3496 case TYPE_CODE_PTR:
3497 store_typed_address (buf, type, (CORE_ADDR) num);
3498 break;
3500 case TYPE_CODE_FLT:
3501 case TYPE_CODE_DECFLOAT:
3502 target_float_from_longest (buf, type, num);
3503 break;
3505 default:
3506 error (_("Unexpected type (%d) encountered for integer constant."),
3507 type->code ());
3512 /* Pack NUM into BUF using a target format of TYPE. */
3514 static void
3515 pack_unsigned_long (gdb_byte *buf, struct type *type, ULONGEST num)
3517 LONGEST len;
3518 enum bfd_endian byte_order;
3520 type = check_typedef (type);
3521 len = type->length ();
3522 byte_order = type_byte_order (type);
3524 switch (type->code ())
3526 case TYPE_CODE_INT:
3527 case TYPE_CODE_CHAR:
3528 case TYPE_CODE_ENUM:
3529 case TYPE_CODE_FLAGS:
3530 case TYPE_CODE_BOOL:
3531 case TYPE_CODE_RANGE:
3532 case TYPE_CODE_MEMBERPTR:
3533 if (type->bit_size_differs_p ())
3535 unsigned bit_off = type->bit_offset ();
3536 unsigned bit_size = type->bit_size ();
3537 num &= ((ULONGEST) 1 << bit_size) - 1;
3538 num <<= bit_off;
3540 store_unsigned_integer (buf, len, byte_order, num);
3541 break;
3543 case TYPE_CODE_REF:
3544 case TYPE_CODE_RVALUE_REF:
3545 case TYPE_CODE_PTR:
3546 store_typed_address (buf, type, (CORE_ADDR) num);
3547 break;
3549 case TYPE_CODE_FLT:
3550 case TYPE_CODE_DECFLOAT:
3551 target_float_from_ulongest (buf, type, num);
3552 break;
3554 default:
3555 error (_("Unexpected type (%d) encountered "
3556 "for unsigned integer constant."),
3557 type->code ());
3562 /* Create a value of type TYPE that is zero, and return it. */
3564 struct value *
3565 value_zero (struct type *type, enum lval_type lv)
3567 struct value *val = allocate_value_lazy (type);
3569 VALUE_LVAL (val) = (lv == lval_computed ? not_lval : lv);
3570 val->is_zero = true;
3571 return val;
3574 /* Convert C numbers into newly allocated values. */
3576 struct value *
3577 value_from_longest (struct type *type, LONGEST num)
3579 struct value *val = allocate_value (type);
3581 pack_long (value_contents_raw (val).data (), type, num);
3582 return val;
3586 /* Convert C unsigned numbers into newly allocated values. */
3588 struct value *
3589 value_from_ulongest (struct type *type, ULONGEST num)
3591 struct value *val = allocate_value (type);
3593 pack_unsigned_long (value_contents_raw (val).data (), type, num);
3595 return val;
3599 /* Create a value representing a pointer of type TYPE to the address
3600 ADDR. */
3602 struct value *
3603 value_from_pointer (struct type *type, CORE_ADDR addr)
3605 struct value *val = allocate_value (type);
3607 store_typed_address (value_contents_raw (val).data (),
3608 check_typedef (type), addr);
3609 return val;
3612 /* Create and return a value object of TYPE containing the value D. The
3613 TYPE must be of TYPE_CODE_FLT, and must be large enough to hold D once
3614 it is converted to target format. */
3616 struct value *
3617 value_from_host_double (struct type *type, double d)
3619 struct value *value = allocate_value (type);
3620 gdb_assert (type->code () == TYPE_CODE_FLT);
3621 target_float_from_host_double (value_contents_raw (value).data (),
3622 value_type (value), d);
3623 return value;
3626 /* Create a value of type TYPE whose contents come from VALADDR, if it
3627 is non-null, and whose memory address (in the inferior) is
3628 ADDRESS. The type of the created value may differ from the passed
3629 type TYPE. Make sure to retrieve values new type after this call.
3630 Note that TYPE is not passed through resolve_dynamic_type; this is
3631 a special API intended for use only by Ada. */
3633 struct value *
3634 value_from_contents_and_address_unresolved (struct type *type,
3635 const gdb_byte *valaddr,
3636 CORE_ADDR address)
3638 struct value *v;
3640 if (valaddr == NULL)
3641 v = allocate_value_lazy (type);
3642 else
3643 v = value_from_contents (type, valaddr);
3644 VALUE_LVAL (v) = lval_memory;
3645 set_value_address (v, address);
3646 return v;
3649 /* Create a value of type TYPE whose contents come from VALADDR, if it
3650 is non-null, and whose memory address (in the inferior) is
3651 ADDRESS. The type of the created value may differ from the passed
3652 type TYPE. Make sure to retrieve values new type after this call. */
3654 struct value *
3655 value_from_contents_and_address (struct type *type,
3656 const gdb_byte *valaddr,
3657 CORE_ADDR address)
3659 gdb::array_view<const gdb_byte> view;
3660 if (valaddr != nullptr)
3661 view = gdb::make_array_view (valaddr, type->length ());
3662 struct type *resolved_type = resolve_dynamic_type (type, view, address);
3663 struct type *resolved_type_no_typedef = check_typedef (resolved_type);
3664 struct value *v;
3666 if (valaddr == NULL)
3667 v = allocate_value_lazy (resolved_type);
3668 else
3669 v = value_from_contents (resolved_type, valaddr);
3670 if (TYPE_DATA_LOCATION (resolved_type_no_typedef) != NULL
3671 && TYPE_DATA_LOCATION_KIND (resolved_type_no_typedef) == PROP_CONST)
3672 address = TYPE_DATA_LOCATION_ADDR (resolved_type_no_typedef);
3673 VALUE_LVAL (v) = lval_memory;
3674 set_value_address (v, address);
3675 return v;
3678 /* Create a value of type TYPE holding the contents CONTENTS.
3679 The new value is `not_lval'. */
3681 struct value *
3682 value_from_contents (struct type *type, const gdb_byte *contents)
3684 struct value *result;
3686 result = allocate_value (type);
3687 memcpy (value_contents_raw (result).data (), contents, type->length ());
3688 return result;
3691 /* Extract a value from the history file. Input will be of the form
3692 $digits or $$digits. See block comment above 'write_dollar_variable'
3693 for details. */
3695 struct value *
3696 value_from_history_ref (const char *h, const char **endp)
3698 int index, len;
3700 if (h[0] == '$')
3701 len = 1;
3702 else
3703 return NULL;
3705 if (h[1] == '$')
3706 len = 2;
3708 /* Find length of numeral string. */
3709 for (; isdigit (h[len]); len++)
3712 /* Make sure numeral string is not part of an identifier. */
3713 if (h[len] == '_' || isalpha (h[len]))
3714 return NULL;
3716 /* Now collect the index value. */
3717 if (h[1] == '$')
3719 if (len == 2)
3721 /* For some bizarre reason, "$$" is equivalent to "$$1",
3722 rather than to "$$0" as it ought to be! */
3723 index = -1;
3724 *endp += len;
3726 else
3728 char *local_end;
3730 index = -strtol (&h[2], &local_end, 10);
3731 *endp = local_end;
3734 else
3736 if (len == 1)
3738 /* "$" is equivalent to "$0". */
3739 index = 0;
3740 *endp += len;
3742 else
3744 char *local_end;
3746 index = strtol (&h[1], &local_end, 10);
3747 *endp = local_end;
3751 return access_value_history (index);
3754 /* Get the component value (offset by OFFSET bytes) of a struct or
3755 union WHOLE. Component's type is TYPE. */
3757 struct value *
3758 value_from_component (struct value *whole, struct type *type, LONGEST offset)
3760 struct value *v;
3762 if (VALUE_LVAL (whole) == lval_memory && value_lazy (whole))
3763 v = allocate_value_lazy (type);
3764 else
3766 v = allocate_value (type);
3767 value_contents_copy (v, value_embedded_offset (v),
3768 whole, value_embedded_offset (whole) + offset,
3769 type_length_units (type));
3771 v->offset = value_offset (whole) + offset + value_embedded_offset (whole);
3772 set_value_component_location (v, whole);
3774 return v;
3777 struct value *
3778 coerce_ref_if_computed (const struct value *arg)
3780 const struct lval_funcs *funcs;
3782 if (!TYPE_IS_REFERENCE (check_typedef (value_type (arg))))
3783 return NULL;
3785 if (value_lval_const (arg) != lval_computed)
3786 return NULL;
3788 funcs = value_computed_funcs (arg);
3789 if (funcs->coerce_ref == NULL)
3790 return NULL;
3792 return funcs->coerce_ref (arg);
3795 /* Look at value.h for description. */
3797 struct value *
3798 readjust_indirect_value_type (struct value *value, struct type *enc_type,
3799 const struct type *original_type,
3800 struct value *original_value,
3801 CORE_ADDR original_value_address)
3803 gdb_assert (original_type->is_pointer_or_reference ());
3805 struct type *original_target_type = original_type->target_type ();
3806 gdb::array_view<const gdb_byte> view;
3807 struct type *resolved_original_target_type
3808 = resolve_dynamic_type (original_target_type, view,
3809 original_value_address);
3811 /* Re-adjust type. */
3812 deprecated_set_value_type (value, resolved_original_target_type);
3814 /* Add embedding info. */
3815 set_value_enclosing_type (value, enc_type);
3816 set_value_embedded_offset (value, value_pointed_to_offset (original_value));
3818 /* We may be pointing to an object of some derived type. */
3819 return value_full_object (value, NULL, 0, 0, 0);
3822 struct value *
3823 coerce_ref (struct value *arg)
3825 struct type *value_type_arg_tmp = check_typedef (value_type (arg));
3826 struct value *retval;
3827 struct type *enc_type;
3829 retval = coerce_ref_if_computed (arg);
3830 if (retval)
3831 return retval;
3833 if (!TYPE_IS_REFERENCE (value_type_arg_tmp))
3834 return arg;
3836 enc_type = check_typedef (value_enclosing_type (arg));
3837 enc_type = enc_type->target_type ();
3839 CORE_ADDR addr = unpack_pointer (value_type (arg), value_contents (arg).data ());
3840 retval = value_at_lazy (enc_type, addr);
3841 enc_type = value_type (retval);
3842 return readjust_indirect_value_type (retval, enc_type, value_type_arg_tmp,
3843 arg, addr);
3846 struct value *
3847 coerce_array (struct value *arg)
3849 struct type *type;
3851 arg = coerce_ref (arg);
3852 type = check_typedef (value_type (arg));
3854 switch (type->code ())
3856 case TYPE_CODE_ARRAY:
3857 if (!type->is_vector () && current_language->c_style_arrays_p ())
3858 arg = value_coerce_array (arg);
3859 break;
3860 case TYPE_CODE_FUNC:
3861 arg = value_coerce_function (arg);
3862 break;
3864 return arg;
3868 /* Return the return value convention that will be used for the
3869 specified type. */
3871 enum return_value_convention
3872 struct_return_convention (struct gdbarch *gdbarch,
3873 struct value *function, struct type *value_type)
3875 enum type_code code = value_type->code ();
3877 if (code == TYPE_CODE_ERROR)
3878 error (_("Function return type unknown."));
3880 /* Probe the architecture for the return-value convention. */
3881 return gdbarch_return_value (gdbarch, function, value_type,
3882 NULL, NULL, NULL);
3885 /* Return true if the function returning the specified type is using
3886 the convention of returning structures in memory (passing in the
3887 address as a hidden first parameter). */
3890 using_struct_return (struct gdbarch *gdbarch,
3891 struct value *function, struct type *value_type)
3893 if (value_type->code () == TYPE_CODE_VOID)
3894 /* A void return value is never in memory. See also corresponding
3895 code in "print_return_value". */
3896 return 0;
3898 return (struct_return_convention (gdbarch, function, value_type)
3899 != RETURN_VALUE_REGISTER_CONVENTION);
3902 /* Set the initialized field in a value struct. */
3904 void
3905 set_value_initialized (struct value *val, int status)
3907 val->initialized = status;
3910 /* Return the initialized field in a value struct. */
3913 value_initialized (const struct value *val)
3915 return val->initialized;
3918 /* Helper for value_fetch_lazy when the value is a bitfield. */
3920 static void
3921 value_fetch_lazy_bitfield (struct value *val)
3923 gdb_assert (value_bitsize (val) != 0);
3925 /* To read a lazy bitfield, read the entire enclosing value. This
3926 prevents reading the same block of (possibly volatile) memory once
3927 per bitfield. It would be even better to read only the containing
3928 word, but we have no way to record that just specific bits of a
3929 value have been fetched. */
3930 struct value *parent = value_parent (val);
3932 if (value_lazy (parent))
3933 value_fetch_lazy (parent);
3935 unpack_value_bitfield (val, value_bitpos (val), value_bitsize (val),
3936 value_contents_for_printing (parent).data (),
3937 value_offset (val), parent);
3940 /* Helper for value_fetch_lazy when the value is in memory. */
3942 static void
3943 value_fetch_lazy_memory (struct value *val)
3945 gdb_assert (VALUE_LVAL (val) == lval_memory);
3947 CORE_ADDR addr = value_address (val);
3948 struct type *type = check_typedef (value_enclosing_type (val));
3950 if (type->length ())
3951 read_value_memory (val, 0, value_stack (val),
3952 addr, value_contents_all_raw (val).data (),
3953 type_length_units (type));
3956 /* Helper for value_fetch_lazy when the value is in a register. */
3958 static void
3959 value_fetch_lazy_register (struct value *val)
3961 struct frame_info *next_frame;
3962 int regnum;
3963 struct type *type = check_typedef (value_type (val));
3964 struct value *new_val = val, *mark = value_mark ();
3966 /* Offsets are not supported here; lazy register values must
3967 refer to the entire register. */
3968 gdb_assert (value_offset (val) == 0);
3970 while (VALUE_LVAL (new_val) == lval_register && value_lazy (new_val))
3972 struct frame_id next_frame_id = VALUE_NEXT_FRAME_ID (new_val);
3974 next_frame = frame_find_by_id (next_frame_id);
3975 regnum = VALUE_REGNUM (new_val);
3977 gdb_assert (next_frame != NULL);
3979 /* Convertible register routines are used for multi-register
3980 values and for interpretation in different types
3981 (e.g. float or int from a double register). Lazy
3982 register values should have the register's natural type,
3983 so they do not apply. */
3984 gdb_assert (!gdbarch_convert_register_p (get_frame_arch (next_frame),
3985 regnum, type));
3987 /* FRAME was obtained, above, via VALUE_NEXT_FRAME_ID.
3988 Since a "->next" operation was performed when setting
3989 this field, we do not need to perform a "next" operation
3990 again when unwinding the register. That's why
3991 frame_unwind_register_value() is called here instead of
3992 get_frame_register_value(). */
3993 new_val = frame_unwind_register_value (next_frame, regnum);
3995 /* If we get another lazy lval_register value, it means the
3996 register is found by reading it from NEXT_FRAME's next frame.
3997 frame_unwind_register_value should never return a value with
3998 the frame id pointing to NEXT_FRAME. If it does, it means we
3999 either have two consecutive frames with the same frame id
4000 in the frame chain, or some code is trying to unwind
4001 behind get_prev_frame's back (e.g., a frame unwind
4002 sniffer trying to unwind), bypassing its validations. In
4003 any case, it should always be an internal error to end up
4004 in this situation. */
4005 if (VALUE_LVAL (new_val) == lval_register
4006 && value_lazy (new_val)
4007 && frame_id_eq (VALUE_NEXT_FRAME_ID (new_val), next_frame_id))
4008 internal_error (__FILE__, __LINE__,
4009 _("infinite loop while fetching a register"));
4012 /* If it's still lazy (for instance, a saved register on the
4013 stack), fetch it. */
4014 if (value_lazy (new_val))
4015 value_fetch_lazy (new_val);
4017 /* Copy the contents and the unavailability/optimized-out
4018 meta-data from NEW_VAL to VAL. */
4019 set_value_lazy (val, 0);
4020 value_contents_copy (val, value_embedded_offset (val),
4021 new_val, value_embedded_offset (new_val),
4022 type_length_units (type));
4024 if (frame_debug)
4026 struct gdbarch *gdbarch;
4027 struct frame_info *frame;
4028 frame = frame_find_by_id (VALUE_NEXT_FRAME_ID (val));
4029 frame = get_prev_frame_always (frame);
4030 regnum = VALUE_REGNUM (val);
4031 gdbarch = get_frame_arch (frame);
4033 string_file debug_file;
4034 gdb_printf (&debug_file,
4035 "(frame=%d, regnum=%d(%s), ...) ",
4036 frame_relative_level (frame), regnum,
4037 user_reg_map_regnum_to_name (gdbarch, regnum));
4039 gdb_printf (&debug_file, "->");
4040 if (value_optimized_out (new_val))
4042 gdb_printf (&debug_file, " ");
4043 val_print_optimized_out (new_val, &debug_file);
4045 else
4047 int i;
4048 gdb::array_view<const gdb_byte> buf = value_contents (new_val);
4050 if (VALUE_LVAL (new_val) == lval_register)
4051 gdb_printf (&debug_file, " register=%d",
4052 VALUE_REGNUM (new_val));
4053 else if (VALUE_LVAL (new_val) == lval_memory)
4054 gdb_printf (&debug_file, " address=%s",
4055 paddress (gdbarch,
4056 value_address (new_val)));
4057 else
4058 gdb_printf (&debug_file, " computed");
4060 gdb_printf (&debug_file, " bytes=");
4061 gdb_printf (&debug_file, "[");
4062 for (i = 0; i < register_size (gdbarch, regnum); i++)
4063 gdb_printf (&debug_file, "%02x", buf[i]);
4064 gdb_printf (&debug_file, "]");
4067 frame_debug_printf ("%s", debug_file.c_str ());
4070 /* Dispose of the intermediate values. This prevents
4071 watchpoints from trying to watch the saved frame pointer. */
4072 value_free_to_mark (mark);
4075 /* Load the actual content of a lazy value. Fetch the data from the
4076 user's process and clear the lazy flag to indicate that the data in
4077 the buffer is valid.
4079 If the value is zero-length, we avoid calling read_memory, which
4080 would abort. We mark the value as fetched anyway -- all 0 bytes of
4081 it. */
4083 void
4084 value_fetch_lazy (struct value *val)
4086 gdb_assert (value_lazy (val));
4087 allocate_value_contents (val);
4088 /* A value is either lazy, or fully fetched. The
4089 availability/validity is only established as we try to fetch a
4090 value. */
4091 gdb_assert (val->optimized_out.empty ());
4092 gdb_assert (val->unavailable.empty ());
4093 if (val->is_zero)
4095 /* Nothing. */
4097 else if (value_bitsize (val))
4098 value_fetch_lazy_bitfield (val);
4099 else if (VALUE_LVAL (val) == lval_memory)
4100 value_fetch_lazy_memory (val);
4101 else if (VALUE_LVAL (val) == lval_register)
4102 value_fetch_lazy_register (val);
4103 else if (VALUE_LVAL (val) == lval_computed
4104 && value_computed_funcs (val)->read != NULL)
4105 value_computed_funcs (val)->read (val);
4106 else
4107 internal_error (__FILE__, __LINE__, _("Unexpected lazy value type."));
4109 set_value_lazy (val, 0);
4112 /* Implementation of the convenience function $_isvoid. */
4114 static struct value *
4115 isvoid_internal_fn (struct gdbarch *gdbarch,
4116 const struct language_defn *language,
4117 void *cookie, int argc, struct value **argv)
4119 int ret;
4121 if (argc != 1)
4122 error (_("You must provide one argument for $_isvoid."));
4124 ret = value_type (argv[0])->code () == TYPE_CODE_VOID;
4126 return value_from_longest (builtin_type (gdbarch)->builtin_int, ret);
4129 /* Implementation of the convenience function $_creal. Extracts the
4130 real part from a complex number. */
4132 static struct value *
4133 creal_internal_fn (struct gdbarch *gdbarch,
4134 const struct language_defn *language,
4135 void *cookie, int argc, struct value **argv)
4137 if (argc != 1)
4138 error (_("You must provide one argument for $_creal."));
4140 value *cval = argv[0];
4141 type *ctype = check_typedef (value_type (cval));
4142 if (ctype->code () != TYPE_CODE_COMPLEX)
4143 error (_("expected a complex number"));
4144 return value_real_part (cval);
4147 /* Implementation of the convenience function $_cimag. Extracts the
4148 imaginary part from a complex number. */
4150 static struct value *
4151 cimag_internal_fn (struct gdbarch *gdbarch,
4152 const struct language_defn *language,
4153 void *cookie, int argc,
4154 struct value **argv)
4156 if (argc != 1)
4157 error (_("You must provide one argument for $_cimag."));
4159 value *cval = argv[0];
4160 type *ctype = check_typedef (value_type (cval));
4161 if (ctype->code () != TYPE_CODE_COMPLEX)
4162 error (_("expected a complex number"));
4163 return value_imaginary_part (cval);
4166 #if GDB_SELF_TEST
4167 namespace selftests
4170 /* Test the ranges_contain function. */
4172 static void
4173 test_ranges_contain ()
4175 std::vector<range> ranges;
4176 range r;
4178 /* [10, 14] */
4179 r.offset = 10;
4180 r.length = 5;
4181 ranges.push_back (r);
4183 /* [20, 24] */
4184 r.offset = 20;
4185 r.length = 5;
4186 ranges.push_back (r);
4188 /* [2, 6] */
4189 SELF_CHECK (!ranges_contain (ranges, 2, 5));
4190 /* [9, 13] */
4191 SELF_CHECK (ranges_contain (ranges, 9, 5));
4192 /* [10, 11] */
4193 SELF_CHECK (ranges_contain (ranges, 10, 2));
4194 /* [10, 14] */
4195 SELF_CHECK (ranges_contain (ranges, 10, 5));
4196 /* [13, 18] */
4197 SELF_CHECK (ranges_contain (ranges, 13, 6));
4198 /* [14, 18] */
4199 SELF_CHECK (ranges_contain (ranges, 14, 5));
4200 /* [15, 18] */
4201 SELF_CHECK (!ranges_contain (ranges, 15, 4));
4202 /* [16, 19] */
4203 SELF_CHECK (!ranges_contain (ranges, 16, 4));
4204 /* [16, 21] */
4205 SELF_CHECK (ranges_contain (ranges, 16, 6));
4206 /* [21, 21] */
4207 SELF_CHECK (ranges_contain (ranges, 21, 1));
4208 /* [21, 25] */
4209 SELF_CHECK (ranges_contain (ranges, 21, 5));
4210 /* [26, 28] */
4211 SELF_CHECK (!ranges_contain (ranges, 26, 3));
4214 /* Check that RANGES contains the same ranges as EXPECTED. */
4216 static bool
4217 check_ranges_vector (gdb::array_view<const range> ranges,
4218 gdb::array_view<const range> expected)
4220 return ranges == expected;
4223 /* Test the insert_into_bit_range_vector function. */
4225 static void
4226 test_insert_into_bit_range_vector ()
4228 std::vector<range> ranges;
4230 /* [10, 14] */
4232 insert_into_bit_range_vector (&ranges, 10, 5);
4233 static const range expected[] = {
4234 {10, 5}
4236 SELF_CHECK (check_ranges_vector (ranges, expected));
4239 /* [10, 14] */
4241 insert_into_bit_range_vector (&ranges, 11, 4);
4242 static const range expected = {10, 5};
4243 SELF_CHECK (check_ranges_vector (ranges, expected));
4246 /* [10, 14] [20, 24] */
4248 insert_into_bit_range_vector (&ranges, 20, 5);
4249 static const range expected[] = {
4250 {10, 5},
4251 {20, 5},
4253 SELF_CHECK (check_ranges_vector (ranges, expected));
4256 /* [10, 14] [17, 24] */
4258 insert_into_bit_range_vector (&ranges, 17, 5);
4259 static const range expected[] = {
4260 {10, 5},
4261 {17, 8},
4263 SELF_CHECK (check_ranges_vector (ranges, expected));
4266 /* [2, 8] [10, 14] [17, 24] */
4268 insert_into_bit_range_vector (&ranges, 2, 7);
4269 static const range expected[] = {
4270 {2, 7},
4271 {10, 5},
4272 {17, 8},
4274 SELF_CHECK (check_ranges_vector (ranges, expected));
4277 /* [2, 14] [17, 24] */
4279 insert_into_bit_range_vector (&ranges, 9, 1);
4280 static const range expected[] = {
4281 {2, 13},
4282 {17, 8},
4284 SELF_CHECK (check_ranges_vector (ranges, expected));
4287 /* [2, 14] [17, 24] */
4289 insert_into_bit_range_vector (&ranges, 9, 1);
4290 static const range expected[] = {
4291 {2, 13},
4292 {17, 8},
4294 SELF_CHECK (check_ranges_vector (ranges, expected));
4297 /* [2, 33] */
4299 insert_into_bit_range_vector (&ranges, 4, 30);
4300 static const range expected = {2, 32};
4301 SELF_CHECK (check_ranges_vector (ranges, expected));
4305 static void
4306 test_value_copy ()
4308 type *type = builtin_type (current_inferior ()->gdbarch)->builtin_int;
4310 /* Verify that we can copy an entirely optimized out value, that may not have
4311 its contents allocated. */
4312 value_ref_ptr val = release_value (allocate_optimized_out_value (type));
4313 value_ref_ptr copy = release_value (value_copy (val.get ()));
4315 SELF_CHECK (value_entirely_optimized_out (val.get ()));
4316 SELF_CHECK (value_entirely_optimized_out (copy.get ()));
4319 } /* namespace selftests */
4320 #endif /* GDB_SELF_TEST */
4322 void _initialize_values ();
4323 void
4324 _initialize_values ()
4326 cmd_list_element *show_convenience_cmd
4327 = add_cmd ("convenience", no_class, show_convenience, _("\
4328 Debugger convenience (\"$foo\") variables and functions.\n\
4329 Convenience variables are created when you assign them values;\n\
4330 thus, \"set $foo=1\" gives \"$foo\" the value 1. Values may be any type.\n\
4332 A few convenience variables are given values automatically:\n\
4333 \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
4334 \"$__\" holds the contents of the last address examined with \"x\"."
4335 #ifdef HAVE_PYTHON
4336 "\n\n\
4337 Convenience functions are defined via the Python API."
4338 #endif
4339 ), &showlist);
4340 add_alias_cmd ("conv", show_convenience_cmd, no_class, 1, &showlist);
4342 add_cmd ("values", no_set_class, show_values, _("\
4343 Elements of value history around item number IDX (or last ten)."),
4344 &showlist);
4346 add_com ("init-if-undefined", class_vars, init_if_undefined_command, _("\
4347 Initialize a convenience variable if necessary.\n\
4348 init-if-undefined VARIABLE = EXPRESSION\n\
4349 Set an internal VARIABLE to the result of the EXPRESSION if it does not\n\
4350 exist or does not contain a value. The EXPRESSION is not evaluated if the\n\
4351 VARIABLE is already initialized."));
4353 add_prefix_cmd ("function", no_class, function_command, _("\
4354 Placeholder command for showing help on convenience functions."),
4355 &functionlist, 0, &cmdlist);
4357 add_internal_function ("_isvoid", _("\
4358 Check whether an expression is void.\n\
4359 Usage: $_isvoid (expression)\n\
4360 Return 1 if the expression is void, zero otherwise."),
4361 isvoid_internal_fn, NULL);
4363 add_internal_function ("_creal", _("\
4364 Extract the real part of a complex number.\n\
4365 Usage: $_creal (expression)\n\
4366 Return the real part of a complex number, the type depends on the\n\
4367 type of a complex number."),
4368 creal_internal_fn, NULL);
4370 add_internal_function ("_cimag", _("\
4371 Extract the imaginary part of a complex number.\n\
4372 Usage: $_cimag (expression)\n\
4373 Return the imaginary part of a complex number, the type depends on the\n\
4374 type of a complex number."),
4375 cimag_internal_fn, NULL);
4377 add_setshow_zuinteger_unlimited_cmd ("max-value-size",
4378 class_support, &max_value_size, _("\
4379 Set maximum sized value gdb will load from the inferior."), _("\
4380 Show maximum sized value gdb will load from the inferior."), _("\
4381 Use this to control the maximum size, in bytes, of a value that gdb\n\
4382 will load from the inferior. Setting this value to 'unlimited'\n\
4383 disables checking.\n\
4384 Setting this does not invalidate already allocated values, it only\n\
4385 prevents future values, larger than this size, from being allocated."),
4386 set_max_value_size,
4387 show_max_value_size,
4388 &setlist, &showlist);
4389 set_show_commands vsize_limit
4390 = add_setshow_zuinteger_unlimited_cmd ("varsize-limit", class_support,
4391 &max_value_size, _("\
4392 Set the maximum number of bytes allowed in a variable-size object."), _("\
4393 Show the maximum number of bytes allowed in a variable-size object."), _("\
4394 Attempts to access an object whose size is not a compile-time constant\n\
4395 and exceeds this limit will cause an error."),
4396 NULL, NULL, &setlist, &showlist);
4397 deprecate_cmd (vsize_limit.set, "set max-value-size");
4399 #if GDB_SELF_TEST
4400 selftests::register_test ("ranges_contain", selftests::test_ranges_contain);
4401 selftests::register_test ("insert_into_bit_range_vector",
4402 selftests::test_insert_into_bit_range_vector);
4403 selftests::register_test ("value_copy", selftests::test_value_copy);
4404 #endif
4407 /* See value.h. */
4409 void
4410 finalize_values ()
4412 all_values.clear ();