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/>. */
21 #include "arch-utils.h"
33 #include "target-float.h"
36 #include "cli/cli-decode.h"
37 #include "extension.h"
39 #include "tracepoint.h"
41 #include "user-regs.h"
43 #include "completer.h"
44 #include "gdbsupport/selftest.h"
45 #include "gdbsupport/array-view.h"
46 #include "cli/cli-style.h"
50 /* Definition of a user function. */
51 struct internal_function
53 /* The name of the function. It is a bit odd to have this in the
54 function itself -- the user might use a differently-named
55 convenience variable to hold the function. */
59 internal_function_fn handler;
61 /* User data for the handler. */
65 /* Defines an [OFFSET, OFFSET + LENGTH) range. */
69 /* Lowest offset in the range. */
72 /* Length of the range. */
75 /* Returns true if THIS is strictly less than OTHER, useful for
76 searching. We keep ranges sorted by offset and coalesce
77 overlapping and contiguous ranges, so this just compares the
80 bool operator< (const range &other) const
82 return offset < other.offset;
85 /* Returns true if THIS is equal to OTHER. */
86 bool operator== (const range &other) const
88 return offset == other.offset && length == other.length;
92 /* Returns true if the ranges defined by [offset1, offset1+len1) and
93 [offset2, offset2+len2) overlap. */
96 ranges_overlap (LONGEST offset1, LONGEST len1,
97 LONGEST offset2, LONGEST len2)
101 l = std::max (offset1, offset2);
102 h = std::min (offset1 + len1, offset2 + len2);
106 /* Returns true if RANGES contains any range that overlaps [OFFSET,
110 ranges_contain (const std::vector<range> &ranges, LONGEST offset,
115 what.offset = offset;
116 what.length = length;
118 /* We keep ranges sorted by offset and coalesce overlapping and
119 contiguous ranges, so to check if a range list contains a given
120 range, we can do a binary search for the position the given range
121 would be inserted if we only considered the starting OFFSET of
122 ranges. We call that position I. Since we also have LENGTH to
123 care for (this is a range afterall), we need to check if the
124 _previous_ range overlaps the I range. E.g.,
128 |---| |---| |------| ... |--|
133 In the case above, the binary search would return `I=1', meaning,
134 this OFFSET should be inserted at position 1, and the current
135 position 1 should be pushed further (and before 2). But, `0'
138 Then we need to check if the I range overlaps the I range itself.
143 |---| |---| |-------| ... |--|
150 auto i = std::lower_bound (ranges.begin (), ranges.end (), what);
152 if (i > ranges.begin ())
154 const struct range &bef = *(i - 1);
156 if (ranges_overlap (bef.offset, bef.length, offset, length))
160 if (i < ranges.end ())
162 const struct range &r = *i;
164 if (ranges_overlap (r.offset, r.length, offset, length))
171 static struct cmd_list_element *functionlist;
173 /* Note that the fields in this structure are arranged to save a bit
178 explicit value (struct type *type_)
185 enclosing_type (type_)
191 if (VALUE_LVAL (this) == lval_computed)
193 const struct lval_funcs *funcs = location.computed.funcs;
195 if (funcs->free_closure)
196 funcs->free_closure (this);
198 else if (VALUE_LVAL (this) == lval_xcallable)
199 delete location.xm_worker;
202 DISABLE_COPY_AND_ASSIGN (value);
204 /* Type of value; either not an lval, or one of the various
205 different possible kinds of lval. */
206 enum lval_type lval = not_lval;
208 /* Is it modifiable? Only relevant if lval != not_lval. */
209 unsigned int modifiable : 1;
211 /* If zero, contents of this value are in the contents field. If
212 nonzero, contents are in inferior. If the lval field is lval_memory,
213 the contents are in inferior memory at location.address plus offset.
214 The lval field may also be lval_register.
216 WARNING: This field is used by the code which handles watchpoints
217 (see breakpoint.c) to decide whether a particular value can be
218 watched by hardware watchpoints. If the lazy flag is set for
219 some member of a value chain, it is assumed that this member of
220 the chain doesn't need to be watched as part of watching the
221 value itself. This is how GDB avoids watching the entire struct
222 or array when the user wants to watch a single struct member or
223 array element. If you ever change the way lazy flag is set and
224 reset, be sure to consider this use as well! */
225 unsigned int lazy : 1;
227 /* If value is a variable, is it initialized or not. */
228 unsigned int initialized : 1;
230 /* If value is from the stack. If this is set, read_stack will be
231 used instead of read_memory to enable extra caching. */
232 unsigned int stack : 1;
234 /* True if this is a zero value, created by 'value_zero'; false
238 /* Location of value (if lval). */
241 /* If lval == lval_memory, this is the address in the inferior */
244 /*If lval == lval_register, the value is from a register. */
247 /* Register number. */
249 /* Frame ID of "next" frame to which a register value is relative.
250 If the register value is found relative to frame F, then the
251 frame id of F->next will be stored in next_frame_id. */
252 struct frame_id next_frame_id;
255 /* Pointer to internal variable. */
256 struct internalvar *internalvar;
258 /* Pointer to xmethod worker. */
259 struct xmethod_worker *xm_worker;
261 /* If lval == lval_computed, this is a set of function pointers
262 to use to access and describe the value, and a closure pointer
266 /* Functions to call. */
267 const struct lval_funcs *funcs;
269 /* Closure for those functions to use. */
274 /* Describes offset of a value within lval of a structure in target
275 addressable memory units. Note also the member embedded_offset
279 /* Only used for bitfields; number of bits contained in them. */
282 /* Only used for bitfields; position of start of field. For
283 little-endian targets, it is the position of the LSB. For
284 big-endian targets, it is the position of the MSB. */
287 /* The number of references to this value. When a value is created,
288 the value chain holds a reference, so REFERENCE_COUNT is 1. If
289 release_value is called, this value is removed from the chain but
290 the caller of release_value now has a reference to this value.
291 The caller must arrange for a call to value_free later. */
292 int reference_count = 1;
294 /* Only used for bitfields; the containing value. This allows a
295 single read from the target when displaying multiple
297 value_ref_ptr parent;
299 /* Type of the value. */
302 /* If a value represents a C++ object, then the `type' field gives
303 the object's compile-time type. If the object actually belongs
304 to some class derived from `type', perhaps with other base
305 classes and additional members, then `type' is just a subobject
306 of the real thing, and the full object is probably larger than
307 `type' would suggest.
309 If `type' is a dynamic class (i.e. one with a vtable), then GDB
310 can actually determine the object's run-time type by looking at
311 the run-time type information in the vtable. When this
312 information is available, we may elect to read in the entire
313 object, for several reasons:
315 - When printing the value, the user would probably rather see the
316 full object, not just the limited portion apparent from the
319 - If `type' has virtual base classes, then even printing `type'
320 alone may require reaching outside the `type' portion of the
321 object to wherever the virtual base class has been stored.
323 When we store the entire object, `enclosing_type' is the run-time
324 type -- the complete object -- and `embedded_offset' is the
325 offset of `type' within that larger type, in target addressable memory
326 units. The value_contents() macro takes `embedded_offset' into account,
327 so most GDB code continues to see the `type' portion of the value, just
328 as the inferior would.
330 If `type' is a pointer to an object, then `enclosing_type' is a
331 pointer to the object's run-time type, and `pointed_to_offset' is
332 the offset in target addressable memory units from the full object
333 to the pointed-to object -- that is, the value `embedded_offset' would
334 have if we followed the pointer and fetched the complete object.
335 (I don't really see the point. Why not just determine the
336 run-time type when you indirect, and avoid the special case? The
337 contents don't matter until you indirect anyway.)
339 If we're not doing anything fancy, `enclosing_type' is equal to
340 `type', and `embedded_offset' is zero, so everything works
342 struct type *enclosing_type;
343 LONGEST embedded_offset = 0;
344 LONGEST pointed_to_offset = 0;
346 /* Actual contents of the value. Target byte-order. NULL or not
347 valid if lazy is nonzero. */
348 gdb::unique_xmalloc_ptr<gdb_byte> contents;
350 /* Unavailable ranges in CONTENTS. We mark unavailable ranges,
351 rather than available, since the common and default case is for a
352 value to be available. This is filled in at value read time.
353 The unavailable ranges are tracked in bits. Note that a contents
354 bit that has been optimized out doesn't really exist in the
355 program, so it can't be marked unavailable either. */
356 std::vector<range> unavailable;
358 /* Likewise, but for optimized out contents (a chunk of the value of
359 a variable that does not actually exist in the program). If LVAL
360 is lval_register, this is a register ($pc, $sp, etc., never a
361 program variable) that has not been saved in the frame. Not
362 saved registers and optimized-out program variables values are
363 treated pretty much the same, except not-saved registers have a
364 different string representation and related error strings. */
365 std::vector<range> optimized_out;
371 get_value_arch (const struct value *value)
373 return value_type (value)->arch ();
377 value_bits_available (const struct value *value, LONGEST offset, LONGEST length)
379 gdb_assert (!value->lazy);
381 return !ranges_contain (value->unavailable, offset, length);
385 value_bytes_available (const struct value *value,
386 LONGEST offset, LONGEST length)
388 return value_bits_available (value,
389 offset * TARGET_CHAR_BIT,
390 length * TARGET_CHAR_BIT);
394 value_bits_any_optimized_out (const struct value *value, int bit_offset, int bit_length)
396 gdb_assert (!value->lazy);
398 return ranges_contain (value->optimized_out, bit_offset, bit_length);
402 value_entirely_available (struct value *value)
404 /* We can only tell whether the whole value is available when we try
407 value_fetch_lazy (value);
409 if (value->unavailable.empty ())
414 /* Returns true if VALUE is entirely covered by RANGES. If the value
415 is lazy, it'll be read now. Note that RANGE is a pointer to
416 pointer because reading the value might change *RANGE. */
419 value_entirely_covered_by_range_vector (struct value *value,
420 const std::vector<range> &ranges)
422 /* We can only tell whether the whole value is optimized out /
423 unavailable when we try to read it. */
425 value_fetch_lazy (value);
427 if (ranges.size () == 1)
429 const struct range &t = ranges[0];
432 && t.length == (TARGET_CHAR_BIT
433 * TYPE_LENGTH (value_enclosing_type (value))))
441 value_entirely_unavailable (struct value *value)
443 return value_entirely_covered_by_range_vector (value, value->unavailable);
447 value_entirely_optimized_out (struct value *value)
449 return value_entirely_covered_by_range_vector (value, value->optimized_out);
452 /* Insert into the vector pointed to by VECTORP the bit range starting of
453 OFFSET bits, and extending for the next LENGTH bits. */
456 insert_into_bit_range_vector (std::vector<range> *vectorp,
457 LONGEST offset, LONGEST length)
461 /* Insert the range sorted. If there's overlap or the new range
462 would be contiguous with an existing range, merge. */
464 newr.offset = offset;
465 newr.length = length;
467 /* Do a binary search for the position the given range would be
468 inserted if we only considered the starting OFFSET of ranges.
469 Call that position I. Since we also have LENGTH to care for
470 (this is a range afterall), we need to check if the _previous_
471 range overlaps the I range. E.g., calling R the new range:
473 #1 - overlaps with previous
477 |---| |---| |------| ... |--|
482 In the case #1 above, the binary search would return `I=1',
483 meaning, this OFFSET should be inserted at position 1, and the
484 current position 1 should be pushed further (and become 2). But,
485 note that `0' overlaps with R, so we want to merge them.
487 A similar consideration needs to be taken if the new range would
488 be contiguous with the previous range:
490 #2 - contiguous with previous
494 |--| |---| |------| ... |--|
499 If there's no overlap with the previous range, as in:
501 #3 - not overlapping and not contiguous
505 |--| |---| |------| ... |--|
512 #4 - R is the range with lowest offset
516 |--| |---| |------| ... |--|
521 ... we just push the new range to I.
523 All the 4 cases above need to consider that the new range may
524 also overlap several of the ranges that follow, or that R may be
525 contiguous with the following range, and merge. E.g.,
527 #5 - overlapping following ranges
530 |------------------------|
531 |--| |---| |------| ... |--|
540 |--| |---| |------| ... |--|
547 auto i = std::lower_bound (vectorp->begin (), vectorp->end (), newr);
548 if (i > vectorp->begin ())
550 struct range &bef = *(i - 1);
552 if (ranges_overlap (bef.offset, bef.length, offset, length))
555 ULONGEST l = std::min (bef.offset, offset);
556 ULONGEST h = std::max (bef.offset + bef.length, offset + length);
562 else if (offset == bef.offset + bef.length)
565 bef.length += length;
571 i = vectorp->insert (i, newr);
577 i = vectorp->insert (i, newr);
580 /* Check whether the ranges following the one we've just added or
581 touched can be folded in (#5 above). */
582 if (i != vectorp->end () && i + 1 < vectorp->end ())
587 /* Get the range we just touched. */
588 struct range &t = *i;
592 for (; i < vectorp->end (); i++)
594 struct range &r = *i;
595 if (r.offset <= t.offset + t.length)
599 l = std::min (t.offset, r.offset);
600 h = std::max (t.offset + t.length, r.offset + r.length);
609 /* If we couldn't merge this one, we won't be able to
610 merge following ones either, since the ranges are
611 always sorted by OFFSET. */
617 vectorp->erase (next, next + removed);
622 mark_value_bits_unavailable (struct value *value,
623 LONGEST offset, LONGEST length)
625 insert_into_bit_range_vector (&value->unavailable, offset, length);
629 mark_value_bytes_unavailable (struct value *value,
630 LONGEST offset, LONGEST length)
632 mark_value_bits_unavailable (value,
633 offset * TARGET_CHAR_BIT,
634 length * TARGET_CHAR_BIT);
637 /* Find the first range in RANGES that overlaps the range defined by
638 OFFSET and LENGTH, starting at element POS in the RANGES vector,
639 Returns the index into RANGES where such overlapping range was
640 found, or -1 if none was found. */
643 find_first_range_overlap (const std::vector<range> *ranges, int pos,
644 LONGEST offset, LONGEST length)
648 for (i = pos; i < ranges->size (); i++)
650 const range &r = (*ranges)[i];
651 if (ranges_overlap (r.offset, r.length, offset, length))
658 /* Compare LENGTH_BITS of memory at PTR1 + OFFSET1_BITS with the memory at
659 PTR2 + OFFSET2_BITS. Return 0 if the memory is the same, otherwise
662 It must always be the case that:
663 OFFSET1_BITS % TARGET_CHAR_BIT == OFFSET2_BITS % TARGET_CHAR_BIT
665 It is assumed that memory can be accessed from:
666 PTR + (OFFSET_BITS / TARGET_CHAR_BIT)
668 PTR + ((OFFSET_BITS + LENGTH_BITS + TARGET_CHAR_BIT - 1)
669 / TARGET_CHAR_BIT) */
671 memcmp_with_bit_offsets (const gdb_byte *ptr1, size_t offset1_bits,
672 const gdb_byte *ptr2, size_t offset2_bits,
675 gdb_assert (offset1_bits % TARGET_CHAR_BIT
676 == offset2_bits % TARGET_CHAR_BIT);
678 if (offset1_bits % TARGET_CHAR_BIT != 0)
681 gdb_byte mask, b1, b2;
683 /* The offset from the base pointers PTR1 and PTR2 is not a complete
684 number of bytes. A number of bits up to either the next exact
685 byte boundary, or LENGTH_BITS (which ever is sooner) will be
687 bits = TARGET_CHAR_BIT - offset1_bits % TARGET_CHAR_BIT;
688 gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
689 mask = (1 << bits) - 1;
691 if (length_bits < bits)
693 mask &= ~(gdb_byte) ((1 << (bits - length_bits)) - 1);
697 /* Now load the two bytes and mask off the bits we care about. */
698 b1 = *(ptr1 + offset1_bits / TARGET_CHAR_BIT) & mask;
699 b2 = *(ptr2 + offset2_bits / TARGET_CHAR_BIT) & mask;
704 /* Now update the length and offsets to take account of the bits
705 we've just compared. */
707 offset1_bits += bits;
708 offset2_bits += bits;
711 if (length_bits % TARGET_CHAR_BIT != 0)
715 gdb_byte mask, b1, b2;
717 /* The length is not an exact number of bytes. After the previous
718 IF.. block then the offsets are byte aligned, or the
719 length is zero (in which case this code is not reached). Compare
720 a number of bits at the end of the region, starting from an exact
722 bits = length_bits % TARGET_CHAR_BIT;
723 o1 = offset1_bits + length_bits - bits;
724 o2 = offset2_bits + length_bits - bits;
726 gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
727 mask = ((1 << bits) - 1) << (TARGET_CHAR_BIT - bits);
729 gdb_assert (o1 % TARGET_CHAR_BIT == 0);
730 gdb_assert (o2 % TARGET_CHAR_BIT == 0);
732 b1 = *(ptr1 + o1 / TARGET_CHAR_BIT) & mask;
733 b2 = *(ptr2 + o2 / TARGET_CHAR_BIT) & mask;
743 /* We've now taken care of any stray "bits" at the start, or end of
744 the region to compare, the remainder can be covered with a simple
746 gdb_assert (offset1_bits % TARGET_CHAR_BIT == 0);
747 gdb_assert (offset2_bits % TARGET_CHAR_BIT == 0);
748 gdb_assert (length_bits % TARGET_CHAR_BIT == 0);
750 return memcmp (ptr1 + offset1_bits / TARGET_CHAR_BIT,
751 ptr2 + offset2_bits / TARGET_CHAR_BIT,
752 length_bits / TARGET_CHAR_BIT);
755 /* Length is zero, regions match. */
759 /* Helper struct for find_first_range_overlap_and_match and
760 value_contents_bits_eq. Keep track of which slot of a given ranges
761 vector have we last looked at. */
763 struct ranges_and_idx
766 const std::vector<range> *ranges;
768 /* The range we've last found in RANGES. Given ranges are sorted,
769 we can start the next lookup here. */
773 /* Helper function for value_contents_bits_eq. Compare LENGTH bits of
774 RP1's ranges starting at OFFSET1 bits with LENGTH bits of RP2's
775 ranges starting at OFFSET2 bits. Return true if the ranges match
776 and fill in *L and *H with the overlapping window relative to
777 (both) OFFSET1 or OFFSET2. */
780 find_first_range_overlap_and_match (struct ranges_and_idx *rp1,
781 struct ranges_and_idx *rp2,
782 LONGEST offset1, LONGEST offset2,
783 LONGEST length, ULONGEST *l, ULONGEST *h)
785 rp1->idx = find_first_range_overlap (rp1->ranges, rp1->idx,
787 rp2->idx = find_first_range_overlap (rp2->ranges, rp2->idx,
790 if (rp1->idx == -1 && rp2->idx == -1)
796 else if (rp1->idx == -1 || rp2->idx == -1)
800 const range *r1, *r2;
804 r1 = &(*rp1->ranges)[rp1->idx];
805 r2 = &(*rp2->ranges)[rp2->idx];
807 /* Get the unavailable windows intersected by the incoming
808 ranges. The first and last ranges that overlap the argument
809 range may be wider than said incoming arguments ranges. */
810 l1 = std::max (offset1, r1->offset);
811 h1 = std::min (offset1 + length, r1->offset + r1->length);
813 l2 = std::max (offset2, r2->offset);
814 h2 = std::min (offset2 + length, offset2 + r2->length);
816 /* Make them relative to the respective start offsets, so we can
817 compare them for equality. */
824 /* Different ranges, no match. */
825 if (l1 != l2 || h1 != h2)
834 /* Helper function for value_contents_eq. The only difference is that
835 this function is bit rather than byte based.
837 Compare LENGTH bits of VAL1's contents starting at OFFSET1 bits
838 with LENGTH bits of VAL2's contents starting at OFFSET2 bits.
839 Return true if the available bits match. */
842 value_contents_bits_eq (const struct value *val1, int offset1,
843 const struct value *val2, int offset2,
846 /* Each array element corresponds to a ranges source (unavailable,
847 optimized out). '1' is for VAL1, '2' for VAL2. */
848 struct ranges_and_idx rp1[2], rp2[2];
850 /* See function description in value.h. */
851 gdb_assert (!val1->lazy && !val2->lazy);
853 /* We shouldn't be trying to compare past the end of the values. */
854 gdb_assert (offset1 + length
855 <= TYPE_LENGTH (val1->enclosing_type) * TARGET_CHAR_BIT);
856 gdb_assert (offset2 + length
857 <= TYPE_LENGTH (val2->enclosing_type) * TARGET_CHAR_BIT);
859 memset (&rp1, 0, sizeof (rp1));
860 memset (&rp2, 0, sizeof (rp2));
861 rp1[0].ranges = &val1->unavailable;
862 rp2[0].ranges = &val2->unavailable;
863 rp1[1].ranges = &val1->optimized_out;
864 rp2[1].ranges = &val2->optimized_out;
868 ULONGEST l = 0, h = 0; /* init for gcc -Wall */
871 for (i = 0; i < 2; i++)
873 ULONGEST l_tmp, h_tmp;
875 /* The contents only match equal if the invalid/unavailable
876 contents ranges match as well. */
877 if (!find_first_range_overlap_and_match (&rp1[i], &rp2[i],
878 offset1, offset2, length,
882 /* We're interested in the lowest/first range found. */
883 if (i == 0 || l_tmp < l)
890 /* Compare the available/valid contents. */
891 if (memcmp_with_bit_offsets (val1->contents.get (), offset1,
892 val2->contents.get (), offset2, l) != 0)
904 value_contents_eq (const struct value *val1, LONGEST offset1,
905 const struct value *val2, LONGEST offset2,
908 return value_contents_bits_eq (val1, offset1 * TARGET_CHAR_BIT,
909 val2, offset2 * TARGET_CHAR_BIT,
910 length * TARGET_CHAR_BIT);
914 /* The value-history records all the values printed by print commands
915 during this session. */
917 static std::vector<value_ref_ptr> value_history;
920 /* List of all value objects currently allocated
921 (except for those released by calls to release_value)
922 This is so they can be freed after each command. */
924 static std::vector<value_ref_ptr> all_values;
926 /* Allocate a lazy value for type TYPE. Its actual content is
927 "lazily" allocated too: the content field of the return value is
928 NULL; it will be allocated when it is fetched from the target. */
931 allocate_value_lazy (struct type *type)
935 /* Call check_typedef on our type to make sure that, if TYPE
936 is a TYPE_CODE_TYPEDEF, its length is set to the length
937 of the target type instead of zero. However, we do not
938 replace the typedef type by the target type, because we want
939 to keep the typedef in order to be able to set the VAL's type
940 description correctly. */
941 check_typedef (type);
943 val = new struct value (type);
945 /* Values start out on the all_values chain. */
946 all_values.emplace_back (val);
951 /* The maximum size, in bytes, that GDB will try to allocate for a value.
952 The initial value of 64k was not selected for any specific reason, it is
953 just a reasonable starting point. */
955 static int max_value_size = 65536; /* 64k bytes */
957 /* It is critical that the MAX_VALUE_SIZE is at least as big as the size of
958 LONGEST, otherwise GDB will not be able to parse integer values from the
959 CLI; for example if the MAX_VALUE_SIZE could be set to 1 then GDB would
960 be unable to parse "set max-value-size 2".
962 As we want a consistent GDB experience across hosts with different sizes
963 of LONGEST, this arbitrary minimum value was selected, so long as this
964 is bigger than LONGEST on all GDB supported hosts we're fine. */
966 #define MIN_VALUE_FOR_MAX_VALUE_SIZE 16
967 gdb_static_assert (sizeof (LONGEST) <= MIN_VALUE_FOR_MAX_VALUE_SIZE);
969 /* Implement the "set max-value-size" command. */
972 set_max_value_size (const char *args, int from_tty,
973 struct cmd_list_element *c)
975 gdb_assert (max_value_size == -1 || max_value_size >= 0);
977 if (max_value_size > -1 && max_value_size < MIN_VALUE_FOR_MAX_VALUE_SIZE)
979 max_value_size = MIN_VALUE_FOR_MAX_VALUE_SIZE;
980 error (_("max-value-size set too low, increasing to %d bytes"),
985 /* Implement the "show max-value-size" command. */
988 show_max_value_size (struct ui_file *file, int from_tty,
989 struct cmd_list_element *c, const char *value)
991 if (max_value_size == -1)
992 fprintf_filtered (file, _("Maximum value size is unlimited.\n"));
994 fprintf_filtered (file, _("Maximum value size is %d bytes.\n"),
998 /* Called before we attempt to allocate or reallocate a buffer for the
999 contents of a value. TYPE is the type of the value for which we are
1000 allocating the buffer. If the buffer is too large (based on the user
1001 controllable setting) then throw an error. If this function returns
1002 then we should attempt to allocate the buffer. */
1005 check_type_length_before_alloc (const struct type *type)
1007 ULONGEST length = TYPE_LENGTH (type);
1009 if (max_value_size > -1 && length > max_value_size)
1011 if (type->name () != NULL)
1012 error (_("value of type `%s' requires %s bytes, which is more "
1013 "than max-value-size"), type->name (), pulongest (length));
1015 error (_("value requires %s bytes, which is more than "
1016 "max-value-size"), pulongest (length));
1020 /* Allocate the contents of VAL if it has not been allocated yet. */
1023 allocate_value_contents (struct value *val)
1027 check_type_length_before_alloc (val->enclosing_type);
1029 ((gdb_byte *) xzalloc (TYPE_LENGTH (val->enclosing_type)));
1033 /* Allocate a value and its contents for type TYPE. */
1036 allocate_value (struct type *type)
1038 struct value *val = allocate_value_lazy (type);
1040 allocate_value_contents (val);
1045 /* Allocate a value that has the correct length
1046 for COUNT repetitions of type TYPE. */
1049 allocate_repeat_value (struct type *type, int count)
1051 /* Despite the fact that we are really creating an array of TYPE here, we
1052 use the string lower bound as the array lower bound. This seems to
1053 work fine for now. */
1054 int low_bound = current_language->string_lower_bound ();
1055 /* FIXME-type-allocation: need a way to free this type when we are
1057 struct type *array_type
1058 = lookup_array_range_type (type, low_bound, count + low_bound - 1);
1060 return allocate_value (array_type);
1064 allocate_computed_value (struct type *type,
1065 const struct lval_funcs *funcs,
1068 struct value *v = allocate_value_lazy (type);
1070 VALUE_LVAL (v) = lval_computed;
1071 v->location.computed.funcs = funcs;
1072 v->location.computed.closure = closure;
1077 /* Allocate NOT_LVAL value for type TYPE being OPTIMIZED_OUT. */
1080 allocate_optimized_out_value (struct type *type)
1082 struct value *retval = allocate_value_lazy (type);
1084 mark_value_bytes_optimized_out (retval, 0, TYPE_LENGTH (type));
1085 set_value_lazy (retval, 0);
1089 /* Accessor methods. */
1092 value_type (const struct value *value)
1097 deprecated_set_value_type (struct value *value, struct type *type)
1103 value_offset (const struct value *value)
1105 return value->offset;
1108 set_value_offset (struct value *value, LONGEST offset)
1110 value->offset = offset;
1114 value_bitpos (const struct value *value)
1116 return value->bitpos;
1119 set_value_bitpos (struct value *value, LONGEST bit)
1121 value->bitpos = bit;
1125 value_bitsize (const struct value *value)
1127 return value->bitsize;
1130 set_value_bitsize (struct value *value, LONGEST bit)
1132 value->bitsize = bit;
1136 value_parent (const struct value *value)
1138 return value->parent.get ();
1144 set_value_parent (struct value *value, struct value *parent)
1146 value->parent = value_ref_ptr::new_reference (parent);
1149 gdb::array_view<gdb_byte>
1150 value_contents_raw (struct value *value)
1152 struct gdbarch *arch = get_value_arch (value);
1153 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1155 allocate_value_contents (value);
1157 ULONGEST length = TYPE_LENGTH (value_type (value));
1158 return gdb::make_array_view
1159 (value->contents.get () + value->embedded_offset * unit_size, length);
1162 gdb::array_view<gdb_byte>
1163 value_contents_all_raw (struct value *value)
1165 allocate_value_contents (value);
1167 ULONGEST length = TYPE_LENGTH (value_enclosing_type (value));
1168 return gdb::make_array_view (value->contents.get (), length);
1172 value_enclosing_type (const struct value *value)
1174 return value->enclosing_type;
1177 /* Look at value.h for description. */
1180 value_actual_type (struct value *value, int resolve_simple_types,
1181 int *real_type_found)
1183 struct value_print_options opts;
1184 struct type *result;
1186 get_user_print_options (&opts);
1188 if (real_type_found)
1189 *real_type_found = 0;
1190 result = value_type (value);
1191 if (opts.objectprint)
1193 /* If result's target type is TYPE_CODE_STRUCT, proceed to
1194 fetch its rtti type. */
1195 if (result->is_pointer_or_reference ()
1196 && (check_typedef (TYPE_TARGET_TYPE (result))->code ()
1197 == TYPE_CODE_STRUCT)
1198 && !value_optimized_out (value))
1200 struct type *real_type;
1202 real_type = value_rtti_indirect_type (value, NULL, NULL, NULL);
1205 if (real_type_found)
1206 *real_type_found = 1;
1210 else if (resolve_simple_types)
1212 if (real_type_found)
1213 *real_type_found = 1;
1214 result = value_enclosing_type (value);
1222 error_value_optimized_out (void)
1224 throw_error (OPTIMIZED_OUT_ERROR, _("value has been optimized out"));
1228 require_not_optimized_out (const struct value *value)
1230 if (!value->optimized_out.empty ())
1232 if (value->lval == lval_register)
1233 throw_error (OPTIMIZED_OUT_ERROR,
1234 _("register has not been saved in frame"));
1236 error_value_optimized_out ();
1241 require_available (const struct value *value)
1243 if (!value->unavailable.empty ())
1244 throw_error (NOT_AVAILABLE_ERROR, _("value is not available"));
1247 gdb::array_view<const gdb_byte>
1248 value_contents_for_printing (struct value *value)
1251 value_fetch_lazy (value);
1253 ULONGEST length = TYPE_LENGTH (value_enclosing_type (value));
1254 return gdb::make_array_view (value->contents.get (), length);
1257 gdb::array_view<const gdb_byte>
1258 value_contents_for_printing_const (const struct value *value)
1260 gdb_assert (!value->lazy);
1262 ULONGEST length = TYPE_LENGTH (value_enclosing_type (value));
1263 return gdb::make_array_view (value->contents.get (), length);
1266 gdb::array_view<const gdb_byte>
1267 value_contents_all (struct value *value)
1269 gdb::array_view<const gdb_byte> result = value_contents_for_printing (value);
1270 require_not_optimized_out (value);
1271 require_available (value);
1275 /* Copy ranges in SRC_RANGE that overlap [SRC_BIT_OFFSET,
1276 SRC_BIT_OFFSET+BIT_LENGTH) ranges into *DST_RANGE, adjusted. */
1279 ranges_copy_adjusted (std::vector<range> *dst_range, int dst_bit_offset,
1280 const std::vector<range> &src_range, int src_bit_offset,
1283 for (const range &r : src_range)
1287 l = std::max (r.offset, (LONGEST) src_bit_offset);
1288 h = std::min (r.offset + r.length,
1289 (LONGEST) src_bit_offset + bit_length);
1292 insert_into_bit_range_vector (dst_range,
1293 dst_bit_offset + (l - src_bit_offset),
1298 /* Copy the ranges metadata in SRC that overlaps [SRC_BIT_OFFSET,
1299 SRC_BIT_OFFSET+BIT_LENGTH) into DST, adjusted. */
1302 value_ranges_copy_adjusted (struct value *dst, int dst_bit_offset,
1303 const struct value *src, int src_bit_offset,
1306 ranges_copy_adjusted (&dst->unavailable, dst_bit_offset,
1307 src->unavailable, src_bit_offset,
1309 ranges_copy_adjusted (&dst->optimized_out, dst_bit_offset,
1310 src->optimized_out, src_bit_offset,
1314 /* Copy LENGTH target addressable memory units of SRC value's (all) contents
1315 (value_contents_all) starting at SRC_OFFSET, into DST value's (all)
1316 contents, starting at DST_OFFSET. If unavailable contents are
1317 being copied from SRC, the corresponding DST contents are marked
1318 unavailable accordingly. Neither DST nor SRC may be lazy
1321 It is assumed the contents of DST in the [DST_OFFSET,
1322 DST_OFFSET+LENGTH) range are wholly available. */
1325 value_contents_copy_raw (struct value *dst, LONGEST dst_offset,
1326 struct value *src, LONGEST src_offset, LONGEST length)
1328 LONGEST src_bit_offset, dst_bit_offset, bit_length;
1329 struct gdbarch *arch = get_value_arch (src);
1330 int unit_size = gdbarch_addressable_memory_unit_size (arch);
1332 /* A lazy DST would make that this copy operation useless, since as
1333 soon as DST's contents were un-lazied (by a later value_contents
1334 call, say), the contents would be overwritten. A lazy SRC would
1335 mean we'd be copying garbage. */
1336 gdb_assert (!dst->lazy && !src->lazy);
1338 /* The overwritten DST range gets unavailability ORed in, not
1339 replaced. Make sure to remember to implement replacing if it
1340 turns out actually necessary. */
1341 gdb_assert (value_bytes_available (dst, dst_offset, length));
1342 gdb_assert (!value_bits_any_optimized_out (dst,
1343 TARGET_CHAR_BIT * dst_offset,
1344 TARGET_CHAR_BIT * length));
1346 /* Copy the data. */
1347 gdb::array_view<gdb_byte> dst_contents
1348 = value_contents_all_raw (dst).slice (dst_offset * unit_size,
1349 length * unit_size);
1350 gdb::array_view<const gdb_byte> src_contents
1351 = value_contents_all_raw (src).slice (src_offset * unit_size,
1352 length * unit_size);
1353 copy (src_contents, dst_contents);
1355 /* Copy the meta-data, adjusted. */
1356 src_bit_offset = src_offset * unit_size * HOST_CHAR_BIT;
1357 dst_bit_offset = dst_offset * unit_size * HOST_CHAR_BIT;
1358 bit_length = length * unit_size * HOST_CHAR_BIT;
1360 value_ranges_copy_adjusted (dst, dst_bit_offset,
1361 src, src_bit_offset,
1365 /* Copy LENGTH bytes of SRC value's (all) contents
1366 (value_contents_all) starting at SRC_OFFSET byte, into DST value's
1367 (all) contents, starting at DST_OFFSET. If unavailable contents
1368 are being copied from SRC, the corresponding DST contents are
1369 marked unavailable accordingly. DST must not be lazy. If SRC is
1370 lazy, it will be fetched now.
1372 It is assumed the contents of DST in the [DST_OFFSET,
1373 DST_OFFSET+LENGTH) range are wholly available. */
1376 value_contents_copy (struct value *dst, LONGEST dst_offset,
1377 struct value *src, LONGEST src_offset, LONGEST length)
1380 value_fetch_lazy (src);
1382 value_contents_copy_raw (dst, dst_offset, src, src_offset, length);
1386 value_lazy (const struct value *value)
1392 set_value_lazy (struct value *value, int val)
1398 value_stack (const struct value *value)
1400 return value->stack;
1404 set_value_stack (struct value *value, int val)
1409 gdb::array_view<const gdb_byte>
1410 value_contents (struct value *value)
1412 gdb::array_view<const gdb_byte> result = value_contents_writeable (value);
1413 require_not_optimized_out (value);
1414 require_available (value);
1418 gdb::array_view<gdb_byte>
1419 value_contents_writeable (struct value *value)
1422 value_fetch_lazy (value);
1423 return value_contents_raw (value);
1427 value_optimized_out (struct value *value)
1431 /* See if we can compute the result without fetching the
1433 if (VALUE_LVAL (value) == lval_memory)
1435 else if (VALUE_LVAL (value) == lval_computed)
1437 const struct lval_funcs *funcs = value->location.computed.funcs;
1439 if (funcs->is_optimized_out != nullptr)
1440 return funcs->is_optimized_out (value);
1443 /* Fall back to fetching. */
1446 value_fetch_lazy (value);
1448 catch (const gdb_exception_error &ex)
1453 case OPTIMIZED_OUT_ERROR:
1454 case NOT_AVAILABLE_ERROR:
1455 /* These can normally happen when we try to access an
1456 optimized out or unavailable register, either in a
1457 physical register or spilled to memory. */
1465 return !value->optimized_out.empty ();
1468 /* Mark contents of VALUE as optimized out, starting at OFFSET bytes, and
1469 the following LENGTH bytes. */
1472 mark_value_bytes_optimized_out (struct value *value, int offset, int length)
1474 mark_value_bits_optimized_out (value,
1475 offset * TARGET_CHAR_BIT,
1476 length * TARGET_CHAR_BIT);
1482 mark_value_bits_optimized_out (struct value *value,
1483 LONGEST offset, LONGEST length)
1485 insert_into_bit_range_vector (&value->optimized_out, offset, length);
1489 value_bits_synthetic_pointer (const struct value *value,
1490 LONGEST offset, LONGEST length)
1492 if (value->lval != lval_computed
1493 || !value->location.computed.funcs->check_synthetic_pointer)
1495 return value->location.computed.funcs->check_synthetic_pointer (value,
1501 value_embedded_offset (const struct value *value)
1503 return value->embedded_offset;
1507 set_value_embedded_offset (struct value *value, LONGEST val)
1509 value->embedded_offset = val;
1513 value_pointed_to_offset (const struct value *value)
1515 return value->pointed_to_offset;
1519 set_value_pointed_to_offset (struct value *value, LONGEST val)
1521 value->pointed_to_offset = val;
1524 const struct lval_funcs *
1525 value_computed_funcs (const struct value *v)
1527 gdb_assert (value_lval_const (v) == lval_computed);
1529 return v->location.computed.funcs;
1533 value_computed_closure (const struct value *v)
1535 gdb_assert (v->lval == lval_computed);
1537 return v->location.computed.closure;
1541 deprecated_value_lval_hack (struct value *value)
1543 return &value->lval;
1547 value_lval_const (const struct value *value)
1553 value_address (const struct value *value)
1555 if (value->lval != lval_memory)
1557 if (value->parent != NULL)
1558 return value_address (value->parent.get ()) + value->offset;
1559 if (NULL != TYPE_DATA_LOCATION (value_type (value)))
1561 gdb_assert (PROP_CONST == TYPE_DATA_LOCATION_KIND (value_type (value)));
1562 return TYPE_DATA_LOCATION_ADDR (value_type (value));
1565 return value->location.address + value->offset;
1569 value_raw_address (const struct value *value)
1571 if (value->lval != lval_memory)
1573 return value->location.address;
1577 set_value_address (struct value *value, CORE_ADDR addr)
1579 gdb_assert (value->lval == lval_memory);
1580 value->location.address = addr;
1583 struct internalvar **
1584 deprecated_value_internalvar_hack (struct value *value)
1586 return &value->location.internalvar;
1590 deprecated_value_next_frame_id_hack (struct value *value)
1592 gdb_assert (value->lval == lval_register);
1593 return &value->location.reg.next_frame_id;
1597 deprecated_value_regnum_hack (struct value *value)
1599 gdb_assert (value->lval == lval_register);
1600 return &value->location.reg.regnum;
1604 deprecated_value_modifiable (const struct value *value)
1606 return value->modifiable;
1609 /* Return a mark in the value chain. All values allocated after the
1610 mark is obtained (except for those released) are subject to being freed
1611 if a subsequent value_free_to_mark is passed the mark. */
1615 if (all_values.empty ())
1617 return all_values.back ().get ();
1623 value_incref (struct value *val)
1625 val->reference_count++;
1628 /* Release a reference to VAL, which was acquired with value_incref.
1629 This function is also called to deallocate values from the value
1633 value_decref (struct value *val)
1637 gdb_assert (val->reference_count > 0);
1638 val->reference_count--;
1639 if (val->reference_count == 0)
1644 /* Free all values allocated since MARK was obtained by value_mark
1645 (except for those released). */
1647 value_free_to_mark (const struct value *mark)
1649 auto iter = std::find (all_values.begin (), all_values.end (), mark);
1650 if (iter == all_values.end ())
1651 all_values.clear ();
1653 all_values.erase (iter + 1, all_values.end ());
1656 /* Remove VAL from the chain all_values
1657 so it will not be freed automatically. */
1660 release_value (struct value *val)
1663 return value_ref_ptr ();
1665 std::vector<value_ref_ptr>::reverse_iterator iter;
1666 for (iter = all_values.rbegin (); iter != all_values.rend (); ++iter)
1670 value_ref_ptr result = *iter;
1671 all_values.erase (iter.base () - 1);
1676 /* We must always return an owned reference. Normally this happens
1677 because we transfer the reference from the value chain, but in
1678 this case the value was not on the chain. */
1679 return value_ref_ptr::new_reference (val);
1684 std::vector<value_ref_ptr>
1685 value_release_to_mark (const struct value *mark)
1687 std::vector<value_ref_ptr> result;
1689 auto iter = std::find (all_values.begin (), all_values.end (), mark);
1690 if (iter == all_values.end ())
1691 std::swap (result, all_values);
1694 std::move (iter + 1, all_values.end (), std::back_inserter (result));
1695 all_values.erase (iter + 1, all_values.end ());
1697 std::reverse (result.begin (), result.end ());
1701 /* Return a copy of the value ARG.
1702 It contains the same contents, for same memory address,
1703 but it's a different block of storage. */
1706 value_copy (struct value *arg)
1708 struct type *encl_type = value_enclosing_type (arg);
1711 if (value_lazy (arg))
1712 val = allocate_value_lazy (encl_type);
1714 val = allocate_value (encl_type);
1715 val->type = arg->type;
1716 VALUE_LVAL (val) = VALUE_LVAL (arg);
1717 val->location = arg->location;
1718 val->offset = arg->offset;
1719 val->bitpos = arg->bitpos;
1720 val->bitsize = arg->bitsize;
1721 val->lazy = arg->lazy;
1722 val->embedded_offset = value_embedded_offset (arg);
1723 val->pointed_to_offset = arg->pointed_to_offset;
1724 val->modifiable = arg->modifiable;
1725 val->stack = arg->stack;
1726 val->is_zero = arg->is_zero;
1727 val->initialized = arg->initialized;
1729 if (!value_lazy (val))
1730 copy (value_contents_all_raw (arg),
1731 value_contents_all_raw (val));
1733 val->unavailable = arg->unavailable;
1734 val->optimized_out = arg->optimized_out;
1735 val->parent = arg->parent;
1736 if (VALUE_LVAL (val) == lval_computed)
1738 const struct lval_funcs *funcs = val->location.computed.funcs;
1740 if (funcs->copy_closure)
1741 val->location.computed.closure = funcs->copy_closure (val);
1746 /* Return a "const" and/or "volatile" qualified version of the value V.
1747 If CNST is true, then the returned value will be qualified with
1749 if VOLTL is true, then the returned value will be qualified with
1753 make_cv_value (int cnst, int voltl, struct value *v)
1755 struct type *val_type = value_type (v);
1756 struct type *enclosing_type = value_enclosing_type (v);
1757 struct value *cv_val = value_copy (v);
1759 deprecated_set_value_type (cv_val,
1760 make_cv_type (cnst, voltl, val_type, NULL));
1761 set_value_enclosing_type (cv_val,
1762 make_cv_type (cnst, voltl, enclosing_type, NULL));
1767 /* Return a version of ARG that is non-lvalue. */
1770 value_non_lval (struct value *arg)
1772 if (VALUE_LVAL (arg) != not_lval)
1774 struct type *enc_type = value_enclosing_type (arg);
1775 struct value *val = allocate_value (enc_type);
1777 copy (value_contents_all (arg), value_contents_all_raw (val));
1778 val->type = arg->type;
1779 set_value_embedded_offset (val, value_embedded_offset (arg));
1780 set_value_pointed_to_offset (val, value_pointed_to_offset (arg));
1786 /* Write contents of V at ADDR and set its lval type to be LVAL_MEMORY. */
1789 value_force_lval (struct value *v, CORE_ADDR addr)
1791 gdb_assert (VALUE_LVAL (v) == not_lval);
1793 write_memory (addr, value_contents_raw (v).data (), TYPE_LENGTH (value_type (v)));
1794 v->lval = lval_memory;
1795 v->location.address = addr;
1799 set_value_component_location (struct value *component,
1800 const struct value *whole)
1804 gdb_assert (whole->lval != lval_xcallable);
1806 if (whole->lval == lval_internalvar)
1807 VALUE_LVAL (component) = lval_internalvar_component;
1809 VALUE_LVAL (component) = whole->lval;
1811 component->location = whole->location;
1812 if (whole->lval == lval_computed)
1814 const struct lval_funcs *funcs = whole->location.computed.funcs;
1816 if (funcs->copy_closure)
1817 component->location.computed.closure = funcs->copy_closure (whole);
1820 /* If the WHOLE value has a dynamically resolved location property then
1821 update the address of the COMPONENT. */
1822 type = value_type (whole);
1823 if (NULL != TYPE_DATA_LOCATION (type)
1824 && TYPE_DATA_LOCATION_KIND (type) == PROP_CONST)
1825 set_value_address (component, TYPE_DATA_LOCATION_ADDR (type));
1827 /* Similarly, if the COMPONENT value has a dynamically resolved location
1828 property then update its address. */
1829 type = value_type (component);
1830 if (NULL != TYPE_DATA_LOCATION (type)
1831 && TYPE_DATA_LOCATION_KIND (type) == PROP_CONST)
1833 /* If the COMPONENT has a dynamic location, and is an
1834 lval_internalvar_component, then we change it to a lval_memory.
1836 Usually a component of an internalvar is created non-lazy, and has
1837 its content immediately copied from the parent internalvar.
1838 However, for components with a dynamic location, the content of
1839 the component is not contained within the parent, but is instead
1840 accessed indirectly. Further, the component will be created as a
1843 By changing the type of the component to lval_memory we ensure
1844 that value_fetch_lazy can successfully load the component.
1846 This solution isn't ideal, but a real fix would require values to
1847 carry around both the parent value contents, and the contents of
1848 any dynamic fields within the parent. This is a substantial
1849 change to how values work in GDB. */
1850 if (VALUE_LVAL (component) == lval_internalvar_component)
1852 gdb_assert (value_lazy (component));
1853 VALUE_LVAL (component) = lval_memory;
1856 gdb_assert (VALUE_LVAL (component) == lval_memory);
1857 set_value_address (component, TYPE_DATA_LOCATION_ADDR (type));
1861 /* Access to the value history. */
1863 /* Record a new value in the value history.
1864 Returns the absolute history index of the entry. */
1867 record_latest_value (struct value *val)
1869 /* We don't want this value to have anything to do with the inferior anymore.
1870 In particular, "set $1 = 50" should not affect the variable from which
1871 the value was taken, and fast watchpoints should be able to assume that
1872 a value on the value history never changes. */
1873 if (value_lazy (val))
1874 value_fetch_lazy (val);
1875 /* We preserve VALUE_LVAL so that the user can find out where it was fetched
1876 from. This is a bit dubious, because then *&$1 does not just return $1
1877 but the current contents of that location. c'est la vie... */
1878 val->modifiable = 0;
1880 value_history.push_back (release_value (val));
1882 return value_history.size ();
1885 /* Return a copy of the value in the history with sequence number NUM. */
1888 access_value_history (int num)
1893 absnum += value_history.size ();
1898 error (_("The history is empty."));
1900 error (_("There is only one value in the history."));
1902 error (_("History does not go back to $$%d."), -num);
1904 if (absnum > value_history.size ())
1905 error (_("History has not yet reached $%d."), absnum);
1909 return value_copy (value_history[absnum].get ());
1915 value_history_count ()
1917 return value_history.size ();
1921 show_values (const char *num_exp, int from_tty)
1929 /* "show values +" should print from the stored position.
1930 "show values <exp>" should print around value number <exp>. */
1931 if (num_exp[0] != '+' || num_exp[1] != '\0')
1932 num = parse_and_eval_long (num_exp) - 5;
1936 /* "show values" means print the last 10 values. */
1937 num = value_history.size () - 9;
1943 for (i = num; i < num + 10 && i <= value_history.size (); i++)
1945 struct value_print_options opts;
1947 val = access_value_history (i);
1948 printf_filtered (("$%d = "), i);
1949 get_user_print_options (&opts);
1950 value_print (val, gdb_stdout, &opts);
1951 printf_filtered (("\n"));
1954 /* The next "show values +" should start after what we just printed. */
1957 /* Hitting just return after this command should do the same thing as
1958 "show values +". If num_exp is null, this is unnecessary, since
1959 "show values +" is not useful after "show values". */
1960 if (from_tty && num_exp)
1961 set_repeat_arguments ("+");
1964 enum internalvar_kind
1966 /* The internal variable is empty. */
1969 /* The value of the internal variable is provided directly as
1970 a GDB value object. */
1973 /* A fresh value is computed via a call-back routine on every
1974 access to the internal variable. */
1975 INTERNALVAR_MAKE_VALUE,
1977 /* The internal variable holds a GDB internal convenience function. */
1978 INTERNALVAR_FUNCTION,
1980 /* The variable holds an integer value. */
1981 INTERNALVAR_INTEGER,
1983 /* The variable holds a GDB-provided string. */
1987 union internalvar_data
1989 /* A value object used with INTERNALVAR_VALUE. */
1990 struct value *value;
1992 /* The call-back routine used with INTERNALVAR_MAKE_VALUE. */
1995 /* The functions to call. */
1996 const struct internalvar_funcs *functions;
1998 /* The function's user-data. */
2002 /* The internal function used with INTERNALVAR_FUNCTION. */
2005 struct internal_function *function;
2006 /* True if this is the canonical name for the function. */
2010 /* An integer value used with INTERNALVAR_INTEGER. */
2013 /* If type is non-NULL, it will be used as the type to generate
2014 a value for this internal variable. If type is NULL, a default
2015 integer type for the architecture is used. */
2020 /* A string value used with INTERNALVAR_STRING. */
2024 /* Internal variables. These are variables within the debugger
2025 that hold values assigned by debugger commands.
2026 The user refers to them with a '$' prefix
2027 that does not appear in the variable names stored internally. */
2031 struct internalvar *next;
2034 /* We support various different kinds of content of an internal variable.
2035 enum internalvar_kind specifies the kind, and union internalvar_data
2036 provides the data associated with this particular kind. */
2038 enum internalvar_kind kind;
2040 union internalvar_data u;
2043 static struct internalvar *internalvars;
2045 /* If the variable does not already exist create it and give it the
2046 value given. If no value is given then the default is zero. */
2048 init_if_undefined_command (const char* args, int from_tty)
2050 struct internalvar *intvar = nullptr;
2052 /* Parse the expression - this is taken from set_command(). */
2053 expression_up expr = parse_expression (args);
2055 /* Validate the expression.
2056 Was the expression an assignment?
2057 Or even an expression at all? */
2058 if (expr->first_opcode () != BINOP_ASSIGN)
2059 error (_("Init-if-undefined requires an assignment expression."));
2061 /* Extract the variable from the parsed expression. */
2062 expr::assign_operation *assign
2063 = dynamic_cast<expr::assign_operation *> (expr->op.get ());
2064 if (assign != nullptr)
2066 expr::operation *lhs = assign->get_lhs ();
2067 expr::internalvar_operation *ivarop
2068 = dynamic_cast<expr::internalvar_operation *> (lhs);
2069 if (ivarop != nullptr)
2070 intvar = ivarop->get_internalvar ();
2073 if (intvar == nullptr)
2074 error (_("The first parameter to init-if-undefined "
2075 "should be a GDB variable."));
2077 /* Only evaluate the expression if the lvalue is void.
2078 This may still fail if the expression is invalid. */
2079 if (intvar->kind == INTERNALVAR_VOID)
2080 evaluate_expression (expr.get ());
2084 /* Look up an internal variable with name NAME. NAME should not
2085 normally include a dollar sign.
2087 If the specified internal variable does not exist,
2088 the return value is NULL. */
2090 struct internalvar *
2091 lookup_only_internalvar (const char *name)
2093 struct internalvar *var;
2095 for (var = internalvars; var; var = var->next)
2096 if (strcmp (var->name, name) == 0)
2102 /* Complete NAME by comparing it to the names of internal
2106 complete_internalvar (completion_tracker &tracker, const char *name)
2108 struct internalvar *var;
2111 len = strlen (name);
2113 for (var = internalvars; var; var = var->next)
2114 if (strncmp (var->name, name, len) == 0)
2115 tracker.add_completion (make_unique_xstrdup (var->name));
2118 /* Create an internal variable with name NAME and with a void value.
2119 NAME should not normally include a dollar sign. */
2121 struct internalvar *
2122 create_internalvar (const char *name)
2124 struct internalvar *var = XNEW (struct internalvar);
2126 var->name = xstrdup (name);
2127 var->kind = INTERNALVAR_VOID;
2128 var->next = internalvars;
2133 /* Create an internal variable with name NAME and register FUN as the
2134 function that value_of_internalvar uses to create a value whenever
2135 this variable is referenced. NAME should not normally include a
2136 dollar sign. DATA is passed uninterpreted to FUN when it is
2137 called. CLEANUP, if not NULL, is called when the internal variable
2138 is destroyed. It is passed DATA as its only argument. */
2140 struct internalvar *
2141 create_internalvar_type_lazy (const char *name,
2142 const struct internalvar_funcs *funcs,
2145 struct internalvar *var = create_internalvar (name);
2147 var->kind = INTERNALVAR_MAKE_VALUE;
2148 var->u.make_value.functions = funcs;
2149 var->u.make_value.data = data;
2153 /* See documentation in value.h. */
2156 compile_internalvar_to_ax (struct internalvar *var,
2157 struct agent_expr *expr,
2158 struct axs_value *value)
2160 if (var->kind != INTERNALVAR_MAKE_VALUE
2161 || var->u.make_value.functions->compile_to_ax == NULL)
2164 var->u.make_value.functions->compile_to_ax (var, expr, value,
2165 var->u.make_value.data);
2169 /* Look up an internal variable with name NAME. NAME should not
2170 normally include a dollar sign.
2172 If the specified internal variable does not exist,
2173 one is created, with a void value. */
2175 struct internalvar *
2176 lookup_internalvar (const char *name)
2178 struct internalvar *var;
2180 var = lookup_only_internalvar (name);
2184 return create_internalvar (name);
2187 /* Return current value of internal variable VAR. For variables that
2188 are not inherently typed, use a value type appropriate for GDBARCH. */
2191 value_of_internalvar (struct gdbarch *gdbarch, struct internalvar *var)
2194 struct trace_state_variable *tsv;
2196 /* If there is a trace state variable of the same name, assume that
2197 is what we really want to see. */
2198 tsv = find_trace_state_variable (var->name);
2201 tsv->value_known = target_get_trace_state_variable_value (tsv->number,
2203 if (tsv->value_known)
2204 val = value_from_longest (builtin_type (gdbarch)->builtin_int64,
2207 val = allocate_value (builtin_type (gdbarch)->builtin_void);
2213 case INTERNALVAR_VOID:
2214 val = allocate_value (builtin_type (gdbarch)->builtin_void);
2217 case INTERNALVAR_FUNCTION:
2218 val = allocate_value (builtin_type (gdbarch)->internal_fn);
2221 case INTERNALVAR_INTEGER:
2222 if (!var->u.integer.type)
2223 val = value_from_longest (builtin_type (gdbarch)->builtin_int,
2224 var->u.integer.val);
2226 val = value_from_longest (var->u.integer.type, var->u.integer.val);
2229 case INTERNALVAR_STRING:
2230 val = value_cstring (var->u.string, strlen (var->u.string),
2231 builtin_type (gdbarch)->builtin_char);
2234 case INTERNALVAR_VALUE:
2235 val = value_copy (var->u.value);
2236 if (value_lazy (val))
2237 value_fetch_lazy (val);
2240 case INTERNALVAR_MAKE_VALUE:
2241 val = (*var->u.make_value.functions->make_value) (gdbarch, var,
2242 var->u.make_value.data);
2246 internal_error (__FILE__, __LINE__, _("bad kind"));
2249 /* Change the VALUE_LVAL to lval_internalvar so that future operations
2250 on this value go back to affect the original internal variable.
2252 Do not do this for INTERNALVAR_MAKE_VALUE variables, as those have
2253 no underlying modifiable state in the internal variable.
2255 Likewise, if the variable's value is a computed lvalue, we want
2256 references to it to produce another computed lvalue, where
2257 references and assignments actually operate through the
2258 computed value's functions.
2260 This means that internal variables with computed values
2261 behave a little differently from other internal variables:
2262 assignments to them don't just replace the previous value
2263 altogether. At the moment, this seems like the behavior we
2266 if (var->kind != INTERNALVAR_MAKE_VALUE
2267 && val->lval != lval_computed)
2269 VALUE_LVAL (val) = lval_internalvar;
2270 VALUE_INTERNALVAR (val) = var;
2277 get_internalvar_integer (struct internalvar *var, LONGEST *result)
2279 if (var->kind == INTERNALVAR_INTEGER)
2281 *result = var->u.integer.val;
2285 if (var->kind == INTERNALVAR_VALUE)
2287 struct type *type = check_typedef (value_type (var->u.value));
2289 if (type->code () == TYPE_CODE_INT)
2291 *result = value_as_long (var->u.value);
2300 get_internalvar_function (struct internalvar *var,
2301 struct internal_function **result)
2305 case INTERNALVAR_FUNCTION:
2306 *result = var->u.fn.function;
2315 set_internalvar_component (struct internalvar *var,
2316 LONGEST offset, LONGEST bitpos,
2317 LONGEST bitsize, struct value *newval)
2320 struct gdbarch *arch;
2325 case INTERNALVAR_VALUE:
2326 addr = value_contents_writeable (var->u.value).data ();
2327 arch = get_value_arch (var->u.value);
2328 unit_size = gdbarch_addressable_memory_unit_size (arch);
2331 modify_field (value_type (var->u.value), addr + offset,
2332 value_as_long (newval), bitpos, bitsize);
2334 memcpy (addr + offset * unit_size, value_contents (newval).data (),
2335 TYPE_LENGTH (value_type (newval)));
2339 /* We can never get a component of any other kind. */
2340 internal_error (__FILE__, __LINE__, _("set_internalvar_component"));
2345 set_internalvar (struct internalvar *var, struct value *val)
2347 enum internalvar_kind new_kind;
2348 union internalvar_data new_data = { 0 };
2350 if (var->kind == INTERNALVAR_FUNCTION && var->u.fn.canonical)
2351 error (_("Cannot overwrite convenience function %s"), var->name);
2353 /* Prepare new contents. */
2354 switch (check_typedef (value_type (val))->code ())
2356 case TYPE_CODE_VOID:
2357 new_kind = INTERNALVAR_VOID;
2360 case TYPE_CODE_INTERNAL_FUNCTION:
2361 gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2362 new_kind = INTERNALVAR_FUNCTION;
2363 get_internalvar_function (VALUE_INTERNALVAR (val),
2364 &new_data.fn.function);
2365 /* Copies created here are never canonical. */
2369 new_kind = INTERNALVAR_VALUE;
2370 struct value *copy = value_copy (val);
2371 copy->modifiable = 1;
2373 /* Force the value to be fetched from the target now, to avoid problems
2374 later when this internalvar is referenced and the target is gone or
2376 if (value_lazy (copy))
2377 value_fetch_lazy (copy);
2379 /* Release the value from the value chain to prevent it from being
2380 deleted by free_all_values. From here on this function should not
2381 call error () until new_data is installed into the var->u to avoid
2383 new_data.value = release_value (copy).release ();
2385 /* Internal variables which are created from values with a dynamic
2386 location don't need the location property of the origin anymore.
2387 The resolved dynamic location is used prior then any other address
2388 when accessing the value.
2389 If we keep it, we would still refer to the origin value.
2390 Remove the location property in case it exist. */
2391 value_type (new_data.value)->remove_dyn_prop (DYN_PROP_DATA_LOCATION);
2396 /* Clean up old contents. */
2397 clear_internalvar (var);
2400 var->kind = new_kind;
2402 /* End code which must not call error(). */
2406 set_internalvar_integer (struct internalvar *var, LONGEST l)
2408 /* Clean up old contents. */
2409 clear_internalvar (var);
2411 var->kind = INTERNALVAR_INTEGER;
2412 var->u.integer.type = NULL;
2413 var->u.integer.val = l;
2417 set_internalvar_string (struct internalvar *var, const char *string)
2419 /* Clean up old contents. */
2420 clear_internalvar (var);
2422 var->kind = INTERNALVAR_STRING;
2423 var->u.string = xstrdup (string);
2427 set_internalvar_function (struct internalvar *var, struct internal_function *f)
2429 /* Clean up old contents. */
2430 clear_internalvar (var);
2432 var->kind = INTERNALVAR_FUNCTION;
2433 var->u.fn.function = f;
2434 var->u.fn.canonical = 1;
2435 /* Variables installed here are always the canonical version. */
2439 clear_internalvar (struct internalvar *var)
2441 /* Clean up old contents. */
2444 case INTERNALVAR_VALUE:
2445 value_decref (var->u.value);
2448 case INTERNALVAR_STRING:
2449 xfree (var->u.string);
2452 case INTERNALVAR_MAKE_VALUE:
2453 if (var->u.make_value.functions->destroy != NULL)
2454 var->u.make_value.functions->destroy (var->u.make_value.data);
2461 /* Reset to void kind. */
2462 var->kind = INTERNALVAR_VOID;
2466 internalvar_name (const struct internalvar *var)
2471 static struct internal_function *
2472 create_internal_function (const char *name,
2473 internal_function_fn handler, void *cookie)
2475 struct internal_function *ifn = XNEW (struct internal_function);
2477 ifn->name = xstrdup (name);
2478 ifn->handler = handler;
2479 ifn->cookie = cookie;
2484 value_internal_function_name (struct value *val)
2486 struct internal_function *ifn;
2489 gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2490 result = get_internalvar_function (VALUE_INTERNALVAR (val), &ifn);
2491 gdb_assert (result);
2497 call_internal_function (struct gdbarch *gdbarch,
2498 const struct language_defn *language,
2499 struct value *func, int argc, struct value **argv)
2501 struct internal_function *ifn;
2504 gdb_assert (VALUE_LVAL (func) == lval_internalvar);
2505 result = get_internalvar_function (VALUE_INTERNALVAR (func), &ifn);
2506 gdb_assert (result);
2508 return (*ifn->handler) (gdbarch, language, ifn->cookie, argc, argv);
2511 /* The 'function' command. This does nothing -- it is just a
2512 placeholder to let "help function NAME" work. This is also used as
2513 the implementation of the sub-command that is created when
2514 registering an internal function. */
2516 function_command (const char *command, int from_tty)
2521 /* Helper function that does the work for add_internal_function. */
2523 static struct cmd_list_element *
2524 do_add_internal_function (const char *name, const char *doc,
2525 internal_function_fn handler, void *cookie)
2527 struct internal_function *ifn;
2528 struct internalvar *var = lookup_internalvar (name);
2530 ifn = create_internal_function (name, handler, cookie);
2531 set_internalvar_function (var, ifn);
2533 return add_cmd (name, no_class, function_command, doc, &functionlist);
2539 add_internal_function (const char *name, const char *doc,
2540 internal_function_fn handler, void *cookie)
2542 do_add_internal_function (name, doc, handler, cookie);
2548 add_internal_function (gdb::unique_xmalloc_ptr<char> &&name,
2549 gdb::unique_xmalloc_ptr<char> &&doc,
2550 internal_function_fn handler, void *cookie)
2552 struct cmd_list_element *cmd
2553 = do_add_internal_function (name.get (), doc.get (), handler, cookie);
2555 cmd->doc_allocated = 1;
2557 cmd->name_allocated = 1;
2560 /* Update VALUE before discarding OBJFILE. COPIED_TYPES is used to
2561 prevent cycles / duplicates. */
2564 preserve_one_value (struct value *value, struct objfile *objfile,
2565 htab_t copied_types)
2567 if (value->type->objfile_owner () == objfile)
2568 value->type = copy_type_recursive (objfile, value->type, copied_types);
2570 if (value->enclosing_type->objfile_owner () == objfile)
2571 value->enclosing_type = copy_type_recursive (objfile,
2572 value->enclosing_type,
2576 /* Likewise for internal variable VAR. */
2579 preserve_one_internalvar (struct internalvar *var, struct objfile *objfile,
2580 htab_t copied_types)
2584 case INTERNALVAR_INTEGER:
2585 if (var->u.integer.type
2586 && var->u.integer.type->objfile_owner () == objfile)
2588 = copy_type_recursive (objfile, var->u.integer.type, copied_types);
2591 case INTERNALVAR_VALUE:
2592 preserve_one_value (var->u.value, objfile, copied_types);
2597 /* Update the internal variables and value history when OBJFILE is
2598 discarded; we must copy the types out of the objfile. New global types
2599 will be created for every convenience variable which currently points to
2600 this objfile's types, and the convenience variables will be adjusted to
2601 use the new global types. */
2604 preserve_values (struct objfile *objfile)
2606 struct internalvar *var;
2608 /* Create the hash table. We allocate on the objfile's obstack, since
2609 it is soon to be deleted. */
2610 htab_up copied_types = create_copied_types_hash (objfile);
2612 for (const value_ref_ptr &item : value_history)
2613 preserve_one_value (item.get (), objfile, copied_types.get ());
2615 for (var = internalvars; var; var = var->next)
2616 preserve_one_internalvar (var, objfile, copied_types.get ());
2618 preserve_ext_lang_values (objfile, copied_types.get ());
2622 show_convenience (const char *ignore, int from_tty)
2624 struct gdbarch *gdbarch = get_current_arch ();
2625 struct internalvar *var;
2627 struct value_print_options opts;
2629 get_user_print_options (&opts);
2630 for (var = internalvars; var; var = var->next)
2637 printf_filtered (("$%s = "), var->name);
2643 val = value_of_internalvar (gdbarch, var);
2644 value_print (val, gdb_stdout, &opts);
2646 catch (const gdb_exception_error &ex)
2648 fprintf_styled (gdb_stdout, metadata_style.style (),
2649 _("<error: %s>"), ex.what ());
2652 printf_filtered (("\n"));
2656 /* This text does not mention convenience functions on purpose.
2657 The user can't create them except via Python, and if Python support
2658 is installed this message will never be printed ($_streq will
2660 printf_filtered (_("No debugger convenience variables now defined.\n"
2661 "Convenience variables have "
2662 "names starting with \"$\";\n"
2663 "use \"set\" as in \"set "
2664 "$foo = 5\" to define them.\n"));
2672 value_from_xmethod (xmethod_worker_up &&worker)
2676 v = allocate_value (builtin_type (target_gdbarch ())->xmethod);
2677 v->lval = lval_xcallable;
2678 v->location.xm_worker = worker.release ();
2684 /* Return the type of the result of TYPE_CODE_XMETHOD value METHOD. */
2687 result_type_of_xmethod (struct value *method, gdb::array_view<value *> argv)
2689 gdb_assert (value_type (method)->code () == TYPE_CODE_XMETHOD
2690 && method->lval == lval_xcallable && !argv.empty ());
2692 return method->location.xm_worker->get_result_type (argv[0], argv.slice (1));
2695 /* Call the xmethod corresponding to the TYPE_CODE_XMETHOD value METHOD. */
2698 call_xmethod (struct value *method, gdb::array_view<value *> argv)
2700 gdb_assert (value_type (method)->code () == TYPE_CODE_XMETHOD
2701 && method->lval == lval_xcallable && !argv.empty ());
2703 return method->location.xm_worker->invoke (argv[0], argv.slice (1));
2706 /* Extract a value as a C number (either long or double).
2707 Knows how to convert fixed values to double, or
2708 floating values to long.
2709 Does not deallocate the value. */
2712 value_as_long (struct value *val)
2714 /* This coerces arrays and functions, which is necessary (e.g.
2715 in disassemble_command). It also dereferences references, which
2716 I suspect is the most logical thing to do. */
2717 val = coerce_array (val);
2718 return unpack_long (value_type (val), value_contents (val).data ());
2721 /* Extract a value as a C pointer. Does not deallocate the value.
2722 Note that val's type may not actually be a pointer; value_as_long
2723 handles all the cases. */
2725 value_as_address (struct value *val)
2727 struct gdbarch *gdbarch = value_type (val)->arch ();
2729 /* Assume a CORE_ADDR can fit in a LONGEST (for now). Not sure
2730 whether we want this to be true eventually. */
2732 /* gdbarch_addr_bits_remove is wrong if we are being called for a
2733 non-address (e.g. argument to "signal", "info break", etc.), or
2734 for pointers to char, in which the low bits *are* significant. */
2735 return gdbarch_addr_bits_remove (gdbarch, value_as_long (val));
2738 /* There are several targets (IA-64, PowerPC, and others) which
2739 don't represent pointers to functions as simply the address of
2740 the function's entry point. For example, on the IA-64, a
2741 function pointer points to a two-word descriptor, generated by
2742 the linker, which contains the function's entry point, and the
2743 value the IA-64 "global pointer" register should have --- to
2744 support position-independent code. The linker generates
2745 descriptors only for those functions whose addresses are taken.
2747 On such targets, it's difficult for GDB to convert an arbitrary
2748 function address into a function pointer; it has to either find
2749 an existing descriptor for that function, or call malloc and
2750 build its own. On some targets, it is impossible for GDB to
2751 build a descriptor at all: the descriptor must contain a jump
2752 instruction; data memory cannot be executed; and code memory
2755 Upon entry to this function, if VAL is a value of type `function'
2756 (that is, TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FUNC), then
2757 value_address (val) is the address of the function. This is what
2758 you'll get if you evaluate an expression like `main'. The call
2759 to COERCE_ARRAY below actually does all the usual unary
2760 conversions, which includes converting values of type `function'
2761 to `pointer to function'. This is the challenging conversion
2762 discussed above. Then, `unpack_long' will convert that pointer
2763 back into an address.
2765 So, suppose the user types `disassemble foo' on an architecture
2766 with a strange function pointer representation, on which GDB
2767 cannot build its own descriptors, and suppose further that `foo'
2768 has no linker-built descriptor. The address->pointer conversion
2769 will signal an error and prevent the command from running, even
2770 though the next step would have been to convert the pointer
2771 directly back into the same address.
2773 The following shortcut avoids this whole mess. If VAL is a
2774 function, just return its address directly. */
2775 if (value_type (val)->code () == TYPE_CODE_FUNC
2776 || value_type (val)->code () == TYPE_CODE_METHOD)
2777 return value_address (val);
2779 val = coerce_array (val);
2781 /* Some architectures (e.g. Harvard), map instruction and data
2782 addresses onto a single large unified address space. For
2783 instance: An architecture may consider a large integer in the
2784 range 0x10000000 .. 0x1000ffff to already represent a data
2785 addresses (hence not need a pointer to address conversion) while
2786 a small integer would still need to be converted integer to
2787 pointer to address. Just assume such architectures handle all
2788 integer conversions in a single function. */
2792 I think INTEGER_TO_ADDRESS is a good idea as proposed --- but we
2793 must admonish GDB hackers to make sure its behavior matches the
2794 compiler's, whenever possible.
2796 In general, I think GDB should evaluate expressions the same way
2797 the compiler does. When the user copies an expression out of
2798 their source code and hands it to a `print' command, they should
2799 get the same value the compiler would have computed. Any
2800 deviation from this rule can cause major confusion and annoyance,
2801 and needs to be justified carefully. In other words, GDB doesn't
2802 really have the freedom to do these conversions in clever and
2805 AndrewC pointed out that users aren't complaining about how GDB
2806 casts integers to pointers; they are complaining that they can't
2807 take an address from a disassembly listing and give it to `x/i'.
2808 This is certainly important.
2810 Adding an architecture method like integer_to_address() certainly
2811 makes it possible for GDB to "get it right" in all circumstances
2812 --- the target has complete control over how things get done, so
2813 people can Do The Right Thing for their target without breaking
2814 anyone else. The standard doesn't specify how integers get
2815 converted to pointers; usually, the ABI doesn't either, but
2816 ABI-specific code is a more reasonable place to handle it. */
2818 if (!value_type (val)->is_pointer_or_reference ()
2819 && gdbarch_integer_to_address_p (gdbarch))
2820 return gdbarch_integer_to_address (gdbarch, value_type (val),
2821 value_contents (val).data ());
2823 return unpack_long (value_type (val), value_contents (val).data ());
2827 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2828 as a long, or as a double, assuming the raw data is described
2829 by type TYPE. Knows how to convert different sizes of values
2830 and can convert between fixed and floating point. We don't assume
2831 any alignment for the raw data. Return value is in host byte order.
2833 If you want functions and arrays to be coerced to pointers, and
2834 references to be dereferenced, call value_as_long() instead.
2836 C++: It is assumed that the front-end has taken care of
2837 all matters concerning pointers to members. A pointer
2838 to member which reaches here is considered to be equivalent
2839 to an INT (or some size). After all, it is only an offset. */
2842 unpack_long (struct type *type, const gdb_byte *valaddr)
2844 if (is_fixed_point_type (type))
2845 type = type->fixed_point_type_base_type ();
2847 enum bfd_endian byte_order = type_byte_order (type);
2848 enum type_code code = type->code ();
2849 int len = TYPE_LENGTH (type);
2850 int nosign = type->is_unsigned ();
2854 case TYPE_CODE_TYPEDEF:
2855 return unpack_long (check_typedef (type), valaddr);
2856 case TYPE_CODE_ENUM:
2857 case TYPE_CODE_FLAGS:
2858 case TYPE_CODE_BOOL:
2860 case TYPE_CODE_CHAR:
2861 case TYPE_CODE_RANGE:
2862 case TYPE_CODE_MEMBERPTR:
2866 if (type->bit_size_differs_p ())
2868 unsigned bit_off = type->bit_offset ();
2869 unsigned bit_size = type->bit_size ();
2872 /* unpack_bits_as_long doesn't handle this case the
2873 way we'd like, so handle it here. */
2877 result = unpack_bits_as_long (type, valaddr, bit_off, bit_size);
2882 result = extract_unsigned_integer (valaddr, len, byte_order);
2884 result = extract_signed_integer (valaddr, len, byte_order);
2886 if (code == TYPE_CODE_RANGE)
2887 result += type->bounds ()->bias;
2892 case TYPE_CODE_DECFLOAT:
2893 return target_float_to_longest (valaddr, type);
2895 case TYPE_CODE_FIXED_POINT:
2898 vq.read_fixed_point (gdb::make_array_view (valaddr, len),
2900 type->fixed_point_scaling_factor ());
2903 mpz_tdiv_q (vz.val, mpq_numref (vq.val), mpq_denref (vq.val));
2904 return vz.as_integer<LONGEST> ();
2909 case TYPE_CODE_RVALUE_REF:
2910 /* Assume a CORE_ADDR can fit in a LONGEST (for now). Not sure
2911 whether we want this to be true eventually. */
2912 return extract_typed_address (valaddr, type);
2915 error (_("Value can't be converted to integer."));
2919 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2920 as a CORE_ADDR, assuming the raw data is described by type TYPE.
2921 We don't assume any alignment for the raw data. Return value is in
2924 If you want functions and arrays to be coerced to pointers, and
2925 references to be dereferenced, call value_as_address() instead.
2927 C++: It is assumed that the front-end has taken care of
2928 all matters concerning pointers to members. A pointer
2929 to member which reaches here is considered to be equivalent
2930 to an INT (or some size). After all, it is only an offset. */
2933 unpack_pointer (struct type *type, const gdb_byte *valaddr)
2935 /* Assume a CORE_ADDR can fit in a LONGEST (for now). Not sure
2936 whether we want this to be true eventually. */
2937 return unpack_long (type, valaddr);
2941 is_floating_value (struct value *val)
2943 struct type *type = check_typedef (value_type (val));
2945 if (is_floating_type (type))
2947 if (!target_float_is_valid (value_contents (val).data (), type))
2948 error (_("Invalid floating value found in program."));
2956 /* Get the value of the FIELDNO'th field (which must be static) of
2960 value_static_field (struct type *type, int fieldno)
2962 struct value *retval;
2964 switch (type->field (fieldno).loc_kind ())
2966 case FIELD_LOC_KIND_PHYSADDR:
2967 retval = value_at_lazy (type->field (fieldno).type (),
2968 type->field (fieldno).loc_physaddr ());
2970 case FIELD_LOC_KIND_PHYSNAME:
2972 const char *phys_name = type->field (fieldno).loc_physname ();
2973 /* type->field (fieldno).name (); */
2974 struct block_symbol sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0);
2976 if (sym.symbol == NULL)
2978 /* With some compilers, e.g. HP aCC, static data members are
2979 reported as non-debuggable symbols. */
2980 struct bound_minimal_symbol msym
2981 = lookup_minimal_symbol (phys_name, NULL, NULL);
2982 struct type *field_type = type->field (fieldno).type ();
2985 retval = allocate_optimized_out_value (field_type);
2987 retval = value_at_lazy (field_type, BMSYMBOL_VALUE_ADDRESS (msym));
2990 retval = value_of_variable (sym.symbol, sym.block);
2994 gdb_assert_not_reached ("unexpected field location kind");
3000 /* Change the enclosing type of a value object VAL to NEW_ENCL_TYPE.
3001 You have to be careful here, since the size of the data area for the value
3002 is set by the length of the enclosing type. So if NEW_ENCL_TYPE is bigger
3003 than the old enclosing type, you have to allocate more space for the
3007 set_value_enclosing_type (struct value *val, struct type *new_encl_type)
3009 if (TYPE_LENGTH (new_encl_type) > TYPE_LENGTH (value_enclosing_type (val)))
3011 check_type_length_before_alloc (new_encl_type);
3013 .reset ((gdb_byte *) xrealloc (val->contents.release (),
3014 TYPE_LENGTH (new_encl_type)));
3017 val->enclosing_type = new_encl_type;
3020 /* Given a value ARG1 (offset by OFFSET bytes)
3021 of a struct or union type ARG_TYPE,
3022 extract and return the value of one of its (non-static) fields.
3023 FIELDNO says which field. */
3026 value_primitive_field (struct value *arg1, LONGEST offset,
3027 int fieldno, struct type *arg_type)
3031 struct gdbarch *arch = get_value_arch (arg1);
3032 int unit_size = gdbarch_addressable_memory_unit_size (arch);
3034 arg_type = check_typedef (arg_type);
3035 type = arg_type->field (fieldno).type ();
3037 /* Call check_typedef on our type to make sure that, if TYPE
3038 is a TYPE_CODE_TYPEDEF, its length is set to the length
3039 of the target type instead of zero. However, we do not
3040 replace the typedef type by the target type, because we want
3041 to keep the typedef in order to be able to print the type
3042 description correctly. */
3043 check_typedef (type);
3045 if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
3047 /* Handle packed fields.
3049 Create a new value for the bitfield, with bitpos and bitsize
3050 set. If possible, arrange offset and bitpos so that we can
3051 do a single aligned read of the size of the containing type.
3052 Otherwise, adjust offset to the byte containing the first
3053 bit. Assume that the address, offset, and embedded offset
3054 are sufficiently aligned. */
3056 LONGEST bitpos = arg_type->field (fieldno).loc_bitpos ();
3057 LONGEST container_bitsize = TYPE_LENGTH (type) * 8;
3059 v = allocate_value_lazy (type);
3060 v->bitsize = TYPE_FIELD_BITSIZE (arg_type, fieldno);
3061 if ((bitpos % container_bitsize) + v->bitsize <= container_bitsize
3062 && TYPE_LENGTH (type) <= (int) sizeof (LONGEST))
3063 v->bitpos = bitpos % container_bitsize;
3065 v->bitpos = bitpos % 8;
3066 v->offset = (value_embedded_offset (arg1)
3068 + (bitpos - v->bitpos) / 8);
3069 set_value_parent (v, arg1);
3070 if (!value_lazy (arg1))
3071 value_fetch_lazy (v);
3073 else if (fieldno < TYPE_N_BASECLASSES (arg_type))
3075 /* This field is actually a base subobject, so preserve the
3076 entire object's contents for later references to virtual
3080 /* Lazy register values with offsets are not supported. */
3081 if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
3082 value_fetch_lazy (arg1);
3084 /* We special case virtual inheritance here because this
3085 requires access to the contents, which we would rather avoid
3086 for references to ordinary fields of unavailable values. */
3087 if (BASETYPE_VIA_VIRTUAL (arg_type, fieldno))
3088 boffset = baseclass_offset (arg_type, fieldno,
3089 value_contents (arg1).data (),
3090 value_embedded_offset (arg1),
3091 value_address (arg1),
3094 boffset = arg_type->field (fieldno).loc_bitpos () / 8;
3096 if (value_lazy (arg1))
3097 v = allocate_value_lazy (value_enclosing_type (arg1));
3100 v = allocate_value (value_enclosing_type (arg1));
3101 value_contents_copy_raw (v, 0, arg1, 0,
3102 TYPE_LENGTH (value_enclosing_type (arg1)));
3105 v->offset = value_offset (arg1);
3106 v->embedded_offset = offset + value_embedded_offset (arg1) + boffset;
3108 else if (NULL != TYPE_DATA_LOCATION (type))
3110 /* Field is a dynamic data member. */
3112 gdb_assert (0 == offset);
3113 /* We expect an already resolved data location. */
3114 gdb_assert (PROP_CONST == TYPE_DATA_LOCATION_KIND (type));
3115 /* For dynamic data types defer memory allocation
3116 until we actual access the value. */
3117 v = allocate_value_lazy (type);
3121 /* Plain old data member */
3122 offset += (arg_type->field (fieldno).loc_bitpos ()
3123 / (HOST_CHAR_BIT * unit_size));
3125 /* Lazy register values with offsets are not supported. */
3126 if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
3127 value_fetch_lazy (arg1);
3129 if (value_lazy (arg1))
3130 v = allocate_value_lazy (type);
3133 v = allocate_value (type);
3134 value_contents_copy_raw (v, value_embedded_offset (v),
3135 arg1, value_embedded_offset (arg1) + offset,
3136 type_length_units (type));
3138 v->offset = (value_offset (arg1) + offset
3139 + value_embedded_offset (arg1));
3141 set_value_component_location (v, arg1);
3145 /* Given a value ARG1 of a struct or union type,
3146 extract and return the value of one of its (non-static) fields.
3147 FIELDNO says which field. */
3150 value_field (struct value *arg1, int fieldno)
3152 return value_primitive_field (arg1, 0, fieldno, value_type (arg1));
3155 /* Return a non-virtual function as a value.
3156 F is the list of member functions which contains the desired method.
3157 J is an index into F which provides the desired method.
3159 We only use the symbol for its address, so be happy with either a
3160 full symbol or a minimal symbol. */
3163 value_fn_field (struct value **arg1p, struct fn_field *f,
3164 int j, struct type *type,
3168 struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
3169 const char *physname = TYPE_FN_FIELD_PHYSNAME (f, j);
3171 struct bound_minimal_symbol msym;
3173 sym = lookup_symbol (physname, 0, VAR_DOMAIN, 0).symbol;
3176 memset (&msym, 0, sizeof (msym));
3180 gdb_assert (sym == NULL);
3181 msym = lookup_bound_minimal_symbol (physname);
3182 if (msym.minsym == NULL)
3186 v = allocate_value (ftype);
3187 VALUE_LVAL (v) = lval_memory;
3190 set_value_address (v, BLOCK_ENTRY_PC (SYMBOL_BLOCK_VALUE (sym)));
3194 /* The minimal symbol might point to a function descriptor;
3195 resolve it to the actual code address instead. */
3196 struct objfile *objfile = msym.objfile;
3197 struct gdbarch *gdbarch = objfile->arch ();
3199 set_value_address (v,
3200 gdbarch_convert_from_func_ptr_addr
3201 (gdbarch, BMSYMBOL_VALUE_ADDRESS (msym),
3202 current_inferior ()->top_target ()));
3207 if (type != value_type (*arg1p))
3208 *arg1p = value_ind (value_cast (lookup_pointer_type (type),
3209 value_addr (*arg1p)));
3211 /* Move the `this' pointer according to the offset.
3212 VALUE_OFFSET (*arg1p) += offset; */
3223 unpack_bits_as_long (struct type *field_type, const gdb_byte *valaddr,
3224 LONGEST bitpos, LONGEST bitsize)
3226 enum bfd_endian byte_order = type_byte_order (field_type);
3231 LONGEST read_offset;
3233 /* Read the minimum number of bytes required; there may not be
3234 enough bytes to read an entire ULONGEST. */
3235 field_type = check_typedef (field_type);
3237 bytes_read = ((bitpos % 8) + bitsize + 7) / 8;
3240 bytes_read = TYPE_LENGTH (field_type);
3241 bitsize = 8 * bytes_read;
3244 read_offset = bitpos / 8;
3246 val = extract_unsigned_integer (valaddr + read_offset,
3247 bytes_read, byte_order);
3249 /* Extract bits. See comment above. */
3251 if (byte_order == BFD_ENDIAN_BIG)
3252 lsbcount = (bytes_read * 8 - bitpos % 8 - bitsize);
3254 lsbcount = (bitpos % 8);
3257 /* If the field does not entirely fill a LONGEST, then zero the sign bits.
3258 If the field is signed, and is negative, then sign extend. */
3260 if (bitsize < 8 * (int) sizeof (val))
3262 valmask = (((ULONGEST) 1) << bitsize) - 1;
3264 if (!field_type->is_unsigned ())
3266 if (val & (valmask ^ (valmask >> 1)))
3276 /* Unpack a field FIELDNO of the specified TYPE, from the object at
3277 VALADDR + EMBEDDED_OFFSET. VALADDR points to the contents of
3278 ORIGINAL_VALUE, which must not be NULL. See
3279 unpack_value_bits_as_long for more details. */
3282 unpack_value_field_as_long (struct type *type, const gdb_byte *valaddr,
3283 LONGEST embedded_offset, int fieldno,
3284 const struct value *val, LONGEST *result)
3286 int bitpos = type->field (fieldno).loc_bitpos ();
3287 int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3288 struct type *field_type = type->field (fieldno).type ();
3291 gdb_assert (val != NULL);
3293 bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
3294 if (value_bits_any_optimized_out (val, bit_offset, bitsize)
3295 || !value_bits_available (val, bit_offset, bitsize))
3298 *result = unpack_bits_as_long (field_type, valaddr + embedded_offset,
3303 /* Unpack a field FIELDNO of the specified TYPE, from the anonymous
3304 object at VALADDR. See unpack_bits_as_long for more details. */
3307 unpack_field_as_long (struct type *type, const gdb_byte *valaddr, int fieldno)
3309 int bitpos = type->field (fieldno).loc_bitpos ();
3310 int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3311 struct type *field_type = type->field (fieldno).type ();
3313 return unpack_bits_as_long (field_type, valaddr, bitpos, bitsize);
3316 /* Unpack a bitfield of BITSIZE bits found at BITPOS in the object at
3317 VALADDR + EMBEDDEDOFFSET that has the type of DEST_VAL and store
3318 the contents in DEST_VAL, zero or sign extending if the type of
3319 DEST_VAL is wider than BITSIZE. VALADDR points to the contents of
3320 VAL. If the VAL's contents required to extract the bitfield from
3321 are unavailable/optimized out, DEST_VAL is correspondingly
3322 marked unavailable/optimized out. */
3325 unpack_value_bitfield (struct value *dest_val,
3326 LONGEST bitpos, LONGEST bitsize,
3327 const gdb_byte *valaddr, LONGEST embedded_offset,
3328 const struct value *val)
3330 enum bfd_endian byte_order;
3333 struct type *field_type = value_type (dest_val);
3335 byte_order = type_byte_order (field_type);
3337 /* First, unpack and sign extend the bitfield as if it was wholly
3338 valid. Optimized out/unavailable bits are read as zero, but
3339 that's OK, as they'll end up marked below. If the VAL is
3340 wholly-invalid we may have skipped allocating its contents,
3341 though. See allocate_optimized_out_value. */
3342 if (valaddr != NULL)
3346 num = unpack_bits_as_long (field_type, valaddr + embedded_offset,
3348 store_signed_integer (value_contents_raw (dest_val).data (),
3349 TYPE_LENGTH (field_type), byte_order, num);
3352 /* Now copy the optimized out / unavailability ranges to the right
3354 src_bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
3355 if (byte_order == BFD_ENDIAN_BIG)
3356 dst_bit_offset = TYPE_LENGTH (field_type) * TARGET_CHAR_BIT - bitsize;
3359 value_ranges_copy_adjusted (dest_val, dst_bit_offset,
3360 val, src_bit_offset, bitsize);
3363 /* Return a new value with type TYPE, which is FIELDNO field of the
3364 object at VALADDR + EMBEDDEDOFFSET. VALADDR points to the contents
3365 of VAL. If the VAL's contents required to extract the bitfield
3366 from are unavailable/optimized out, the new value is
3367 correspondingly marked unavailable/optimized out. */
3370 value_field_bitfield (struct type *type, int fieldno,
3371 const gdb_byte *valaddr,
3372 LONGEST embedded_offset, const struct value *val)
3374 int bitpos = type->field (fieldno).loc_bitpos ();
3375 int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3376 struct value *res_val = allocate_value (type->field (fieldno).type ());
3378 unpack_value_bitfield (res_val, bitpos, bitsize,
3379 valaddr, embedded_offset, val);
3384 /* Modify the value of a bitfield. ADDR points to a block of memory in
3385 target byte order; the bitfield starts in the byte pointed to. FIELDVAL
3386 is the desired value of the field, in host byte order. BITPOS and BITSIZE
3387 indicate which bits (in target bit order) comprise the bitfield.
3388 Requires 0 < BITSIZE <= lbits, 0 <= BITPOS % 8 + BITSIZE <= lbits, and
3389 0 <= BITPOS, where lbits is the size of a LONGEST in bits. */
3392 modify_field (struct type *type, gdb_byte *addr,
3393 LONGEST fieldval, LONGEST bitpos, LONGEST bitsize)
3395 enum bfd_endian byte_order = type_byte_order (type);
3397 ULONGEST mask = (ULONGEST) -1 >> (8 * sizeof (ULONGEST) - bitsize);
3400 /* Normalize BITPOS. */
3404 /* If a negative fieldval fits in the field in question, chop
3405 off the sign extension bits. */
3406 if ((~fieldval & ~(mask >> 1)) == 0)
3409 /* Warn if value is too big to fit in the field in question. */
3410 if (0 != (fieldval & ~mask))
3412 /* FIXME: would like to include fieldval in the message, but
3413 we don't have a sprintf_longest. */
3414 warning (_("Value does not fit in %s bits."), plongest (bitsize));
3416 /* Truncate it, otherwise adjoining fields may be corrupted. */
3420 /* Ensure no bytes outside of the modified ones get accessed as it may cause
3421 false valgrind reports. */
3423 bytesize = (bitpos + bitsize + 7) / 8;
3424 oword = extract_unsigned_integer (addr, bytesize, byte_order);
3426 /* Shifting for bit field depends on endianness of the target machine. */
3427 if (byte_order == BFD_ENDIAN_BIG)
3428 bitpos = bytesize * 8 - bitpos - bitsize;
3430 oword &= ~(mask << bitpos);
3431 oword |= fieldval << bitpos;
3433 store_unsigned_integer (addr, bytesize, byte_order, oword);
3436 /* Pack NUM into BUF using a target format of TYPE. */
3439 pack_long (gdb_byte *buf, struct type *type, LONGEST num)
3441 enum bfd_endian byte_order = type_byte_order (type);
3444 type = check_typedef (type);
3445 len = TYPE_LENGTH (type);
3447 switch (type->code ())
3449 case TYPE_CODE_RANGE:
3450 num -= type->bounds ()->bias;
3453 case TYPE_CODE_CHAR:
3454 case TYPE_CODE_ENUM:
3455 case TYPE_CODE_FLAGS:
3456 case TYPE_CODE_BOOL:
3457 case TYPE_CODE_MEMBERPTR:
3458 if (type->bit_size_differs_p ())
3460 unsigned bit_off = type->bit_offset ();
3461 unsigned bit_size = type->bit_size ();
3462 num &= ((ULONGEST) 1 << bit_size) - 1;
3465 store_signed_integer (buf, len, byte_order, num);
3469 case TYPE_CODE_RVALUE_REF:
3471 store_typed_address (buf, type, (CORE_ADDR) num);
3475 case TYPE_CODE_DECFLOAT:
3476 target_float_from_longest (buf, type, num);
3480 error (_("Unexpected type (%d) encountered for integer constant."),
3486 /* Pack NUM into BUF using a target format of TYPE. */
3489 pack_unsigned_long (gdb_byte *buf, struct type *type, ULONGEST num)
3492 enum bfd_endian byte_order;
3494 type = check_typedef (type);
3495 len = TYPE_LENGTH (type);
3496 byte_order = type_byte_order (type);
3498 switch (type->code ())
3501 case TYPE_CODE_CHAR:
3502 case TYPE_CODE_ENUM:
3503 case TYPE_CODE_FLAGS:
3504 case TYPE_CODE_BOOL:
3505 case TYPE_CODE_RANGE:
3506 case TYPE_CODE_MEMBERPTR:
3507 if (type->bit_size_differs_p ())
3509 unsigned bit_off = type->bit_offset ();
3510 unsigned bit_size = type->bit_size ();
3511 num &= ((ULONGEST) 1 << bit_size) - 1;
3514 store_unsigned_integer (buf, len, byte_order, num);
3518 case TYPE_CODE_RVALUE_REF:
3520 store_typed_address (buf, type, (CORE_ADDR) num);
3524 case TYPE_CODE_DECFLOAT:
3525 target_float_from_ulongest (buf, type, num);
3529 error (_("Unexpected type (%d) encountered "
3530 "for unsigned integer constant."),
3536 /* Create a value of type TYPE that is zero, and return it. */
3539 value_zero (struct type *type, enum lval_type lv)
3541 struct value *val = allocate_value_lazy (type);
3543 VALUE_LVAL (val) = (lv == lval_computed ? not_lval : lv);
3544 val->is_zero = true;
3548 /* Convert C numbers into newly allocated values. */
3551 value_from_longest (struct type *type, LONGEST num)
3553 struct value *val = allocate_value (type);
3555 pack_long (value_contents_raw (val).data (), type, num);
3560 /* Convert C unsigned numbers into newly allocated values. */
3563 value_from_ulongest (struct type *type, ULONGEST num)
3565 struct value *val = allocate_value (type);
3567 pack_unsigned_long (value_contents_raw (val).data (), type, num);
3573 /* Create a value representing a pointer of type TYPE to the address
3577 value_from_pointer (struct type *type, CORE_ADDR addr)
3579 struct value *val = allocate_value (type);
3581 store_typed_address (value_contents_raw (val).data (),
3582 check_typedef (type), addr);
3586 /* Create and return a value object of TYPE containing the value D. The
3587 TYPE must be of TYPE_CODE_FLT, and must be large enough to hold D once
3588 it is converted to target format. */
3591 value_from_host_double (struct type *type, double d)
3593 struct value *value = allocate_value (type);
3594 gdb_assert (type->code () == TYPE_CODE_FLT);
3595 target_float_from_host_double (value_contents_raw (value).data (),
3596 value_type (value), d);
3600 /* Create a value of type TYPE whose contents come from VALADDR, if it
3601 is non-null, and whose memory address (in the inferior) is
3602 ADDRESS. The type of the created value may differ from the passed
3603 type TYPE. Make sure to retrieve values new type after this call.
3604 Note that TYPE is not passed through resolve_dynamic_type; this is
3605 a special API intended for use only by Ada. */
3608 value_from_contents_and_address_unresolved (struct type *type,
3609 const gdb_byte *valaddr,
3614 if (valaddr == NULL)
3615 v = allocate_value_lazy (type);
3617 v = value_from_contents (type, valaddr);
3618 VALUE_LVAL (v) = lval_memory;
3619 set_value_address (v, address);
3623 /* Create a value of type TYPE whose contents come from VALADDR, if it
3624 is non-null, and whose memory address (in the inferior) is
3625 ADDRESS. The type of the created value may differ from the passed
3626 type TYPE. Make sure to retrieve values new type after this call. */
3629 value_from_contents_and_address (struct type *type,
3630 const gdb_byte *valaddr,
3633 gdb::array_view<const gdb_byte> view;
3634 if (valaddr != nullptr)
3635 view = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
3636 struct type *resolved_type = resolve_dynamic_type (type, view, address);
3637 struct type *resolved_type_no_typedef = check_typedef (resolved_type);
3640 if (valaddr == NULL)
3641 v = allocate_value_lazy (resolved_type);
3643 v = value_from_contents (resolved_type, valaddr);
3644 if (TYPE_DATA_LOCATION (resolved_type_no_typedef) != NULL
3645 && TYPE_DATA_LOCATION_KIND (resolved_type_no_typedef) == PROP_CONST)
3646 address = TYPE_DATA_LOCATION_ADDR (resolved_type_no_typedef);
3647 VALUE_LVAL (v) = lval_memory;
3648 set_value_address (v, address);
3652 /* Create a value of type TYPE holding the contents CONTENTS.
3653 The new value is `not_lval'. */
3656 value_from_contents (struct type *type, const gdb_byte *contents)
3658 struct value *result;
3660 result = allocate_value (type);
3661 memcpy (value_contents_raw (result).data (), contents, TYPE_LENGTH (type));
3665 /* Extract a value from the history file. Input will be of the form
3666 $digits or $$digits. See block comment above 'write_dollar_variable'
3670 value_from_history_ref (const char *h, const char **endp)
3682 /* Find length of numeral string. */
3683 for (; isdigit (h[len]); len++)
3686 /* Make sure numeral string is not part of an identifier. */
3687 if (h[len] == '_' || isalpha (h[len]))
3690 /* Now collect the index value. */
3695 /* For some bizarre reason, "$$" is equivalent to "$$1",
3696 rather than to "$$0" as it ought to be! */
3704 index = -strtol (&h[2], &local_end, 10);
3712 /* "$" is equivalent to "$0". */
3720 index = strtol (&h[1], &local_end, 10);
3725 return access_value_history (index);
3728 /* Get the component value (offset by OFFSET bytes) of a struct or
3729 union WHOLE. Component's type is TYPE. */
3732 value_from_component (struct value *whole, struct type *type, LONGEST offset)
3736 if (VALUE_LVAL (whole) == lval_memory && value_lazy (whole))
3737 v = allocate_value_lazy (type);
3740 v = allocate_value (type);
3741 value_contents_copy (v, value_embedded_offset (v),
3742 whole, value_embedded_offset (whole) + offset,
3743 type_length_units (type));
3745 v->offset = value_offset (whole) + offset + value_embedded_offset (whole);
3746 set_value_component_location (v, whole);
3752 coerce_ref_if_computed (const struct value *arg)
3754 const struct lval_funcs *funcs;
3756 if (!TYPE_IS_REFERENCE (check_typedef (value_type (arg))))
3759 if (value_lval_const (arg) != lval_computed)
3762 funcs = value_computed_funcs (arg);
3763 if (funcs->coerce_ref == NULL)
3766 return funcs->coerce_ref (arg);
3769 /* Look at value.h for description. */
3772 readjust_indirect_value_type (struct value *value, struct type *enc_type,
3773 const struct type *original_type,
3774 struct value *original_value,
3775 CORE_ADDR original_value_address)
3777 gdb_assert (original_type->is_pointer_or_reference ());
3779 struct type *original_target_type = TYPE_TARGET_TYPE (original_type);
3780 gdb::array_view<const gdb_byte> view;
3781 struct type *resolved_original_target_type
3782 = resolve_dynamic_type (original_target_type, view,
3783 original_value_address);
3785 /* Re-adjust type. */
3786 deprecated_set_value_type (value, resolved_original_target_type);
3788 /* Add embedding info. */
3789 set_value_enclosing_type (value, enc_type);
3790 set_value_embedded_offset (value, value_pointed_to_offset (original_value));
3792 /* We may be pointing to an object of some derived type. */
3793 return value_full_object (value, NULL, 0, 0, 0);
3797 coerce_ref (struct value *arg)
3799 struct type *value_type_arg_tmp = check_typedef (value_type (arg));
3800 struct value *retval;
3801 struct type *enc_type;
3803 retval = coerce_ref_if_computed (arg);
3807 if (!TYPE_IS_REFERENCE (value_type_arg_tmp))
3810 enc_type = check_typedef (value_enclosing_type (arg));
3811 enc_type = TYPE_TARGET_TYPE (enc_type);
3813 CORE_ADDR addr = unpack_pointer (value_type (arg), value_contents (arg).data ());
3814 retval = value_at_lazy (enc_type, addr);
3815 enc_type = value_type (retval);
3816 return readjust_indirect_value_type (retval, enc_type, value_type_arg_tmp,
3821 coerce_array (struct value *arg)
3825 arg = coerce_ref (arg);
3826 type = check_typedef (value_type (arg));
3828 switch (type->code ())
3830 case TYPE_CODE_ARRAY:
3831 if (!type->is_vector () && current_language->c_style_arrays_p ())
3832 arg = value_coerce_array (arg);
3834 case TYPE_CODE_FUNC:
3835 arg = value_coerce_function (arg);
3842 /* Return the return value convention that will be used for the
3845 enum return_value_convention
3846 struct_return_convention (struct gdbarch *gdbarch,
3847 struct value *function, struct type *value_type)
3849 enum type_code code = value_type->code ();
3851 if (code == TYPE_CODE_ERROR)
3852 error (_("Function return type unknown."));
3854 /* Probe the architecture for the return-value convention. */
3855 return gdbarch_return_value (gdbarch, function, value_type,
3859 /* Return true if the function returning the specified type is using
3860 the convention of returning structures in memory (passing in the
3861 address as a hidden first parameter). */
3864 using_struct_return (struct gdbarch *gdbarch,
3865 struct value *function, struct type *value_type)
3867 if (value_type->code () == TYPE_CODE_VOID)
3868 /* A void return value is never in memory. See also corresponding
3869 code in "print_return_value". */
3872 return (struct_return_convention (gdbarch, function, value_type)
3873 != RETURN_VALUE_REGISTER_CONVENTION);
3876 /* Set the initialized field in a value struct. */
3879 set_value_initialized (struct value *val, int status)
3881 val->initialized = status;
3884 /* Return the initialized field in a value struct. */
3887 value_initialized (const struct value *val)
3889 return val->initialized;
3892 /* Helper for value_fetch_lazy when the value is a bitfield. */
3895 value_fetch_lazy_bitfield (struct value *val)
3897 gdb_assert (value_bitsize (val) != 0);
3899 /* To read a lazy bitfield, read the entire enclosing value. This
3900 prevents reading the same block of (possibly volatile) memory once
3901 per bitfield. It would be even better to read only the containing
3902 word, but we have no way to record that just specific bits of a
3903 value have been fetched. */
3904 struct value *parent = value_parent (val);
3906 if (value_lazy (parent))
3907 value_fetch_lazy (parent);
3909 unpack_value_bitfield (val, value_bitpos (val), value_bitsize (val),
3910 value_contents_for_printing (parent).data (),
3911 value_offset (val), parent);
3914 /* Helper for value_fetch_lazy when the value is in memory. */
3917 value_fetch_lazy_memory (struct value *val)
3919 gdb_assert (VALUE_LVAL (val) == lval_memory);
3921 CORE_ADDR addr = value_address (val);
3922 struct type *type = check_typedef (value_enclosing_type (val));
3924 if (TYPE_LENGTH (type))
3925 read_value_memory (val, 0, value_stack (val),
3926 addr, value_contents_all_raw (val).data (),
3927 type_length_units (type));
3930 /* Helper for value_fetch_lazy when the value is in a register. */
3933 value_fetch_lazy_register (struct value *val)
3935 struct frame_info *next_frame;
3937 struct type *type = check_typedef (value_type (val));
3938 struct value *new_val = val, *mark = value_mark ();
3940 /* Offsets are not supported here; lazy register values must
3941 refer to the entire register. */
3942 gdb_assert (value_offset (val) == 0);
3944 while (VALUE_LVAL (new_val) == lval_register && value_lazy (new_val))
3946 struct frame_id next_frame_id = VALUE_NEXT_FRAME_ID (new_val);
3948 next_frame = frame_find_by_id (next_frame_id);
3949 regnum = VALUE_REGNUM (new_val);
3951 gdb_assert (next_frame != NULL);
3953 /* Convertible register routines are used for multi-register
3954 values and for interpretation in different types
3955 (e.g. float or int from a double register). Lazy
3956 register values should have the register's natural type,
3957 so they do not apply. */
3958 gdb_assert (!gdbarch_convert_register_p (get_frame_arch (next_frame),
3961 /* FRAME was obtained, above, via VALUE_NEXT_FRAME_ID.
3962 Since a "->next" operation was performed when setting
3963 this field, we do not need to perform a "next" operation
3964 again when unwinding the register. That's why
3965 frame_unwind_register_value() is called here instead of
3966 get_frame_register_value(). */
3967 new_val = frame_unwind_register_value (next_frame, regnum);
3969 /* If we get another lazy lval_register value, it means the
3970 register is found by reading it from NEXT_FRAME's next frame.
3971 frame_unwind_register_value should never return a value with
3972 the frame id pointing to NEXT_FRAME. If it does, it means we
3973 either have two consecutive frames with the same frame id
3974 in the frame chain, or some code is trying to unwind
3975 behind get_prev_frame's back (e.g., a frame unwind
3976 sniffer trying to unwind), bypassing its validations. In
3977 any case, it should always be an internal error to end up
3978 in this situation. */
3979 if (VALUE_LVAL (new_val) == lval_register
3980 && value_lazy (new_val)
3981 && frame_id_eq (VALUE_NEXT_FRAME_ID (new_val), next_frame_id))
3982 internal_error (__FILE__, __LINE__,
3983 _("infinite loop while fetching a register"));
3986 /* If it's still lazy (for instance, a saved register on the
3987 stack), fetch it. */
3988 if (value_lazy (new_val))
3989 value_fetch_lazy (new_val);
3991 /* Copy the contents and the unavailability/optimized-out
3992 meta-data from NEW_VAL to VAL. */
3993 set_value_lazy (val, 0);
3994 value_contents_copy (val, value_embedded_offset (val),
3995 new_val, value_embedded_offset (new_val),
3996 type_length_units (type));
4000 struct gdbarch *gdbarch;
4001 struct frame_info *frame;
4002 frame = frame_find_by_id (VALUE_NEXT_FRAME_ID (val));
4003 frame = get_prev_frame_always (frame);
4004 regnum = VALUE_REGNUM (val);
4005 gdbarch = get_frame_arch (frame);
4007 string_file debug_file;
4008 fprintf_unfiltered (&debug_file,
4009 "(frame=%d, regnum=%d(%s), ...) ",
4010 frame_relative_level (frame), regnum,
4011 user_reg_map_regnum_to_name (gdbarch, regnum));
4013 fprintf_unfiltered (&debug_file, "->");
4014 if (value_optimized_out (new_val))
4016 fprintf_unfiltered (&debug_file, " ");
4017 val_print_optimized_out (new_val, &debug_file);
4022 gdb::array_view<const gdb_byte> buf = value_contents (new_val);
4024 if (VALUE_LVAL (new_val) == lval_register)
4025 fprintf_unfiltered (&debug_file, " register=%d",
4026 VALUE_REGNUM (new_val));
4027 else if (VALUE_LVAL (new_val) == lval_memory)
4028 fprintf_unfiltered (&debug_file, " address=%s",
4030 value_address (new_val)));
4032 fprintf_unfiltered (&debug_file, " computed");
4034 fprintf_unfiltered (&debug_file, " bytes=");
4035 fprintf_unfiltered (&debug_file, "[");
4036 for (i = 0; i < register_size (gdbarch, regnum); i++)
4037 fprintf_unfiltered (&debug_file, "%02x", buf[i]);
4038 fprintf_unfiltered (&debug_file, "]");
4041 frame_debug_printf ("%s", debug_file.c_str ());
4044 /* Dispose of the intermediate values. This prevents
4045 watchpoints from trying to watch the saved frame pointer. */
4046 value_free_to_mark (mark);
4049 /* Load the actual content of a lazy value. Fetch the data from the
4050 user's process and clear the lazy flag to indicate that the data in
4051 the buffer is valid.
4053 If the value is zero-length, we avoid calling read_memory, which
4054 would abort. We mark the value as fetched anyway -- all 0 bytes of
4058 value_fetch_lazy (struct value *val)
4060 gdb_assert (value_lazy (val));
4061 allocate_value_contents (val);
4062 /* A value is either lazy, or fully fetched. The
4063 availability/validity is only established as we try to fetch a
4065 gdb_assert (val->optimized_out.empty ());
4066 gdb_assert (val->unavailable.empty ());
4071 else if (value_bitsize (val))
4072 value_fetch_lazy_bitfield (val);
4073 else if (VALUE_LVAL (val) == lval_memory)
4074 value_fetch_lazy_memory (val);
4075 else if (VALUE_LVAL (val) == lval_register)
4076 value_fetch_lazy_register (val);
4077 else if (VALUE_LVAL (val) == lval_computed
4078 && value_computed_funcs (val)->read != NULL)
4079 value_computed_funcs (val)->read (val);
4081 internal_error (__FILE__, __LINE__, _("Unexpected lazy value type."));
4083 set_value_lazy (val, 0);
4086 /* Implementation of the convenience function $_isvoid. */
4088 static struct value *
4089 isvoid_internal_fn (struct gdbarch *gdbarch,
4090 const struct language_defn *language,
4091 void *cookie, int argc, struct value **argv)
4096 error (_("You must provide one argument for $_isvoid."));
4098 ret = value_type (argv[0])->code () == TYPE_CODE_VOID;
4100 return value_from_longest (builtin_type (gdbarch)->builtin_int, ret);
4103 /* Implementation of the convenience function $_creal. Extracts the
4104 real part from a complex number. */
4106 static struct value *
4107 creal_internal_fn (struct gdbarch *gdbarch,
4108 const struct language_defn *language,
4109 void *cookie, int argc, struct value **argv)
4112 error (_("You must provide one argument for $_creal."));
4114 value *cval = argv[0];
4115 type *ctype = check_typedef (value_type (cval));
4116 if (ctype->code () != TYPE_CODE_COMPLEX)
4117 error (_("expected a complex number"));
4118 return value_real_part (cval);
4121 /* Implementation of the convenience function $_cimag. Extracts the
4122 imaginary part from a complex number. */
4124 static struct value *
4125 cimag_internal_fn (struct gdbarch *gdbarch,
4126 const struct language_defn *language,
4127 void *cookie, int argc,
4128 struct value **argv)
4131 error (_("You must provide one argument for $_cimag."));
4133 value *cval = argv[0];
4134 type *ctype = check_typedef (value_type (cval));
4135 if (ctype->code () != TYPE_CODE_COMPLEX)
4136 error (_("expected a complex number"));
4137 return value_imaginary_part (cval);
4144 /* Test the ranges_contain function. */
4147 test_ranges_contain ()
4149 std::vector<range> ranges;
4155 ranges.push_back (r);
4160 ranges.push_back (r);
4163 SELF_CHECK (!ranges_contain (ranges, 2, 5));
4165 SELF_CHECK (ranges_contain (ranges, 9, 5));
4167 SELF_CHECK (ranges_contain (ranges, 10, 2));
4169 SELF_CHECK (ranges_contain (ranges, 10, 5));
4171 SELF_CHECK (ranges_contain (ranges, 13, 6));
4173 SELF_CHECK (ranges_contain (ranges, 14, 5));
4175 SELF_CHECK (!ranges_contain (ranges, 15, 4));
4177 SELF_CHECK (!ranges_contain (ranges, 16, 4));
4179 SELF_CHECK (ranges_contain (ranges, 16, 6));
4181 SELF_CHECK (ranges_contain (ranges, 21, 1));
4183 SELF_CHECK (ranges_contain (ranges, 21, 5));
4185 SELF_CHECK (!ranges_contain (ranges, 26, 3));
4188 /* Check that RANGES contains the same ranges as EXPECTED. */
4191 check_ranges_vector (gdb::array_view<const range> ranges,
4192 gdb::array_view<const range> expected)
4194 return ranges == expected;
4197 /* Test the insert_into_bit_range_vector function. */
4200 test_insert_into_bit_range_vector ()
4202 std::vector<range> ranges;
4206 insert_into_bit_range_vector (&ranges, 10, 5);
4207 static const range expected[] = {
4210 SELF_CHECK (check_ranges_vector (ranges, expected));
4215 insert_into_bit_range_vector (&ranges, 11, 4);
4216 static const range expected = {10, 5};
4217 SELF_CHECK (check_ranges_vector (ranges, expected));
4220 /* [10, 14] [20, 24] */
4222 insert_into_bit_range_vector (&ranges, 20, 5);
4223 static const range expected[] = {
4227 SELF_CHECK (check_ranges_vector (ranges, expected));
4230 /* [10, 14] [17, 24] */
4232 insert_into_bit_range_vector (&ranges, 17, 5);
4233 static const range expected[] = {
4237 SELF_CHECK (check_ranges_vector (ranges, expected));
4240 /* [2, 8] [10, 14] [17, 24] */
4242 insert_into_bit_range_vector (&ranges, 2, 7);
4243 static const range expected[] = {
4248 SELF_CHECK (check_ranges_vector (ranges, expected));
4251 /* [2, 14] [17, 24] */
4253 insert_into_bit_range_vector (&ranges, 9, 1);
4254 static const range expected[] = {
4258 SELF_CHECK (check_ranges_vector (ranges, expected));
4261 /* [2, 14] [17, 24] */
4263 insert_into_bit_range_vector (&ranges, 9, 1);
4264 static const range expected[] = {
4268 SELF_CHECK (check_ranges_vector (ranges, expected));
4273 insert_into_bit_range_vector (&ranges, 4, 30);
4274 static const range expected = {2, 32};
4275 SELF_CHECK (check_ranges_vector (ranges, expected));
4279 } /* namespace selftests */
4280 #endif /* GDB_SELF_TEST */
4282 void _initialize_values ();
4284 _initialize_values ()
4286 cmd_list_element *show_convenience_cmd
4287 = add_cmd ("convenience", no_class, show_convenience, _("\
4288 Debugger convenience (\"$foo\") variables and functions.\n\
4289 Convenience variables are created when you assign them values;\n\
4290 thus, \"set $foo=1\" gives \"$foo\" the value 1. Values may be any type.\n\
4292 A few convenience variables are given values automatically:\n\
4293 \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
4294 \"$__\" holds the contents of the last address examined with \"x\"."
4297 Convenience functions are defined via the Python API."
4300 add_alias_cmd ("conv", show_convenience_cmd, no_class, 1, &showlist);
4302 add_cmd ("values", no_set_class, show_values, _("\
4303 Elements of value history around item number IDX (or last ten)."),
4306 add_com ("init-if-undefined", class_vars, init_if_undefined_command, _("\
4307 Initialize a convenience variable if necessary.\n\
4308 init-if-undefined VARIABLE = EXPRESSION\n\
4309 Set an internal VARIABLE to the result of the EXPRESSION if it does not\n\
4310 exist or does not contain a value. The EXPRESSION is not evaluated if the\n\
4311 VARIABLE is already initialized."));
4313 add_prefix_cmd ("function", no_class, function_command, _("\
4314 Placeholder command for showing help on convenience functions."),
4315 &functionlist, 0, &cmdlist);
4317 add_internal_function ("_isvoid", _("\
4318 Check whether an expression is void.\n\
4319 Usage: $_isvoid (expression)\n\
4320 Return 1 if the expression is void, zero otherwise."),
4321 isvoid_internal_fn, NULL);
4323 add_internal_function ("_creal", _("\
4324 Extract the real part of a complex number.\n\
4325 Usage: $_creal (expression)\n\
4326 Return the real part of a complex number, the type depends on the\n\
4327 type of a complex number."),
4328 creal_internal_fn, NULL);
4330 add_internal_function ("_cimag", _("\
4331 Extract the imaginary part of a complex number.\n\
4332 Usage: $_cimag (expression)\n\
4333 Return the imaginary part of a complex number, the type depends on the\n\
4334 type of a complex number."),
4335 cimag_internal_fn, NULL);
4337 add_setshow_zuinteger_unlimited_cmd ("max-value-size",
4338 class_support, &max_value_size, _("\
4339 Set maximum sized value gdb will load from the inferior."), _("\
4340 Show maximum sized value gdb will load from the inferior."), _("\
4341 Use this to control the maximum size, in bytes, of a value that gdb\n\
4342 will load from the inferior. Setting this value to 'unlimited'\n\
4343 disables checking.\n\
4344 Setting this does not invalidate already allocated values, it only\n\
4345 prevents future values, larger than this size, from being allocated."),
4347 show_max_value_size,
4348 &setlist, &showlist);
4349 set_show_commands vsize_limit
4350 = add_setshow_zuinteger_unlimited_cmd ("varsize-limit", class_support,
4351 &max_value_size, _("\
4352 Set the maximum number of bytes allowed in a variable-size object."), _("\
4353 Show the maximum number of bytes allowed in a variable-size object."), _("\
4354 Attempts to access an object whose size is not a compile-time constant\n\
4355 and exceeds this limit will cause an error."),
4356 NULL, NULL, &setlist, &showlist);
4357 deprecate_cmd (vsize_limit.set, "set max-value-size");
4360 selftests::register_test ("ranges_contain", selftests::test_ranges_contain);
4361 selftests::register_test ("insert_into_bit_range_vector",
4362 selftests::test_insert_into_bit_range_vector);
4371 all_values.clear ();