]> Git Repo - binutils.git/blob - gdb/value.c
gdb: remove TYPE_FIELD_NAME and FIELD_NAME macros
[binutils.git] / gdb / value.c
1 /* Low level packing and unpacking of values for GDB, the GNU Debugger.
2
3    Copyright (C) 1986-2021 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "value.h"
25 #include "gdbcore.h"
26 #include "command.h"
27 #include "gdbcmd.h"
28 #include "target.h"
29 #include "language.h"
30 #include "demangle.h"
31 #include "regcache.h"
32 #include "block.h"
33 #include "target-float.h"
34 #include "objfiles.h"
35 #include "valprint.h"
36 #include "cli/cli-decode.h"
37 #include "extension.h"
38 #include <ctype.h>
39 #include "tracepoint.h"
40 #include "cp-abi.h"
41 #include "user-regs.h"
42 #include <algorithm>
43 #include "completer.h"
44 #include "gdbsupport/selftest.h"
45 #include "gdbsupport/array-view.h"
46 #include "cli/cli-style.h"
47 #include "expop.h"
48 #include "inferior.h"
49
50 /* Definition of a user function.  */
51 struct internal_function
52 {
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.  */
56   char *name;
57
58   /* The handler.  */
59   internal_function_fn handler;
60
61   /* User data for the handler.  */
62   void *cookie;
63 };
64
65 /* Defines an [OFFSET, OFFSET + LENGTH) range.  */
66
67 struct range
68 {
69   /* Lowest offset in the range.  */
70   LONGEST offset;
71
72   /* Length of the range.  */
73   LONGEST length;
74
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
78      starting offset.  */
79
80   bool operator< (const range &other) const
81   {
82     return offset < other.offset;
83   }
84
85   /* Returns true if THIS is equal to OTHER.  */
86   bool operator== (const range &other) const
87   {
88     return offset == other.offset && length == other.length;
89   }
90 };
91
92 /* Returns true if the ranges defined by [offset1, offset1+len1) and
93    [offset2, offset2+len2) overlap.  */
94
95 static int
96 ranges_overlap (LONGEST offset1, LONGEST len1,
97                 LONGEST offset2, LONGEST len2)
98 {
99   ULONGEST h, l;
100
101   l = std::max (offset1, offset2);
102   h = std::min (offset1 + len1, offset2 + len2);
103   return (l < h);
104 }
105
106 /* Returns true if RANGES contains any range that overlaps [OFFSET,
107    OFFSET+LENGTH).  */
108
109 static int
110 ranges_contain (const std::vector<range> &ranges, LONGEST offset,
111                 LONGEST length)
112 {
113   range what;
114
115   what.offset = offset;
116   what.length = length;
117
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.,
125
126          R
127          |---|
128        |---|    |---|  |------| ... |--|
129        0        1      2            N
130
131        I=1
132
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'
136      overlaps with R.
137
138      Then we need to check if the I range overlaps the I range itself.
139      E.g.,
140
141               R
142               |---|
143        |---|    |---|  |-------| ... |--|
144        0        1      2             N
145
146        I=1
147   */
148
149
150   auto i = std::lower_bound (ranges.begin (), ranges.end (), what);
151
152   if (i > ranges.begin ())
153     {
154       const struct range &bef = *(i - 1);
155
156       if (ranges_overlap (bef.offset, bef.length, offset, length))
157         return 1;
158     }
159
160   if (i < ranges.end ())
161     {
162       const struct range &r = *i;
163
164       if (ranges_overlap (r.offset, r.length, offset, length))
165         return 1;
166     }
167
168   return 0;
169 }
170
171 static struct cmd_list_element *functionlist;
172
173 /* Note that the fields in this structure are arranged to save a bit
174    of memory.  */
175
176 struct value
177 {
178   explicit value (struct type *type_)
179     : modifiable (1),
180       lazy (1),
181       initialized (1),
182       stack (0),
183       type (type_),
184       enclosing_type (type_)
185   {
186   }
187
188   ~value ()
189   {
190     if (VALUE_LVAL (this) == lval_computed)
191       {
192         const struct lval_funcs *funcs = location.computed.funcs;
193
194         if (funcs->free_closure)
195           funcs->free_closure (this);
196       }
197     else if (VALUE_LVAL (this) == lval_xcallable)
198       delete location.xm_worker;
199   }
200
201   DISABLE_COPY_AND_ASSIGN (value);
202
203   /* Type of value; either not an lval, or one of the various
204      different possible kinds of lval.  */
205   enum lval_type lval = not_lval;
206
207   /* Is it modifiable?  Only relevant if lval != not_lval.  */
208   unsigned int modifiable : 1;
209
210   /* If zero, contents of this value are in the contents field.  If
211      nonzero, contents are in inferior.  If the lval field is lval_memory,
212      the contents are in inferior memory at location.address plus offset.
213      The lval field may also be lval_register.
214
215      WARNING: This field is used by the code which handles watchpoints
216      (see breakpoint.c) to decide whether a particular value can be
217      watched by hardware watchpoints.  If the lazy flag is set for
218      some member of a value chain, it is assumed that this member of
219      the chain doesn't need to be watched as part of watching the
220      value itself.  This is how GDB avoids watching the entire struct
221      or array when the user wants to watch a single struct member or
222      array element.  If you ever change the way lazy flag is set and
223      reset, be sure to consider this use as well!  */
224   unsigned int lazy : 1;
225
226   /* If value is a variable, is it initialized or not.  */
227   unsigned int initialized : 1;
228
229   /* If value is from the stack.  If this is set, read_stack will be
230      used instead of read_memory to enable extra caching.  */
231   unsigned int stack : 1;
232
233   /* Location of value (if lval).  */
234   union
235   {
236     /* If lval == lval_memory, this is the address in the inferior  */
237     CORE_ADDR address;
238
239     /*If lval == lval_register, the value is from a register.  */
240     struct
241     {
242       /* Register number.  */
243       int regnum;
244       /* Frame ID of "next" frame to which a register value is relative.
245          If the register value is found relative to frame F, then the
246          frame id of F->next will be stored in next_frame_id.  */
247       struct frame_id next_frame_id;
248     } reg;
249
250     /* Pointer to internal variable.  */
251     struct internalvar *internalvar;
252
253     /* Pointer to xmethod worker.  */
254     struct xmethod_worker *xm_worker;
255
256     /* If lval == lval_computed, this is a set of function pointers
257        to use to access and describe the value, and a closure pointer
258        for them to use.  */
259     struct
260     {
261       /* Functions to call.  */
262       const struct lval_funcs *funcs;
263
264       /* Closure for those functions to use.  */
265       void *closure;
266     } computed;
267   } location {};
268
269   /* Describes offset of a value within lval of a structure in target
270      addressable memory units.  Note also the member embedded_offset
271      below.  */
272   LONGEST offset = 0;
273
274   /* Only used for bitfields; number of bits contained in them.  */
275   LONGEST bitsize = 0;
276
277   /* Only used for bitfields; position of start of field.  For
278      little-endian targets, it is the position of the LSB.  For
279      big-endian targets, it is the position of the MSB.  */
280   LONGEST bitpos = 0;
281
282   /* The number of references to this value.  When a value is created,
283      the value chain holds a reference, so REFERENCE_COUNT is 1.  If
284      release_value is called, this value is removed from the chain but
285      the caller of release_value now has a reference to this value.
286      The caller must arrange for a call to value_free later.  */
287   int reference_count = 1;
288
289   /* Only used for bitfields; the containing value.  This allows a
290      single read from the target when displaying multiple
291      bitfields.  */
292   value_ref_ptr parent;
293
294   /* Type of the value.  */
295   struct type *type;
296
297   /* If a value represents a C++ object, then the `type' field gives
298      the object's compile-time type.  If the object actually belongs
299      to some class derived from `type', perhaps with other base
300      classes and additional members, then `type' is just a subobject
301      of the real thing, and the full object is probably larger than
302      `type' would suggest.
303
304      If `type' is a dynamic class (i.e. one with a vtable), then GDB
305      can actually determine the object's run-time type by looking at
306      the run-time type information in the vtable.  When this
307      information is available, we may elect to read in the entire
308      object, for several reasons:
309
310      - When printing the value, the user would probably rather see the
311      full object, not just the limited portion apparent from the
312      compile-time type.
313
314      - If `type' has virtual base classes, then even printing `type'
315      alone may require reaching outside the `type' portion of the
316      object to wherever the virtual base class has been stored.
317
318      When we store the entire object, `enclosing_type' is the run-time
319      type -- the complete object -- and `embedded_offset' is the
320      offset of `type' within that larger type, in target addressable memory
321      units.  The value_contents() macro takes `embedded_offset' into account,
322      so most GDB code continues to see the `type' portion of the value, just
323      as the inferior would.
324
325      If `type' is a pointer to an object, then `enclosing_type' is a
326      pointer to the object's run-time type, and `pointed_to_offset' is
327      the offset in target addressable memory units from the full object
328      to the pointed-to object -- that is, the value `embedded_offset' would
329      have if we followed the pointer and fetched the complete object.
330      (I don't really see the point.  Why not just determine the
331      run-time type when you indirect, and avoid the special case?  The
332      contents don't matter until you indirect anyway.)
333
334      If we're not doing anything fancy, `enclosing_type' is equal to
335      `type', and `embedded_offset' is zero, so everything works
336      normally.  */
337   struct type *enclosing_type;
338   LONGEST embedded_offset = 0;
339   LONGEST pointed_to_offset = 0;
340
341   /* Actual contents of the value.  Target byte-order.  NULL or not
342      valid if lazy is nonzero.  */
343   gdb::unique_xmalloc_ptr<gdb_byte> contents;
344
345   /* Unavailable ranges in CONTENTS.  We mark unavailable ranges,
346      rather than available, since the common and default case is for a
347      value to be available.  This is filled in at value read time.
348      The unavailable ranges are tracked in bits.  Note that a contents
349      bit that has been optimized out doesn't really exist in the
350      program, so it can't be marked unavailable either.  */
351   std::vector<range> unavailable;
352
353   /* Likewise, but for optimized out contents (a chunk of the value of
354      a variable that does not actually exist in the program).  If LVAL
355      is lval_register, this is a register ($pc, $sp, etc., never a
356      program variable) that has not been saved in the frame.  Not
357      saved registers and optimized-out program variables values are
358      treated pretty much the same, except not-saved registers have a
359      different string representation and related error strings.  */
360   std::vector<range> optimized_out;
361 };
362
363 /* See value.h.  */
364
365 struct gdbarch *
366 get_value_arch (const struct value *value)
367 {
368   return value_type (value)->arch ();
369 }
370
371 int
372 value_bits_available (const struct value *value, LONGEST offset, LONGEST length)
373 {
374   gdb_assert (!value->lazy);
375
376   return !ranges_contain (value->unavailable, offset, length);
377 }
378
379 int
380 value_bytes_available (const struct value *value,
381                        LONGEST offset, LONGEST length)
382 {
383   return value_bits_available (value,
384                                offset * TARGET_CHAR_BIT,
385                                length * TARGET_CHAR_BIT);
386 }
387
388 int
389 value_bits_any_optimized_out (const struct value *value, int bit_offset, int bit_length)
390 {
391   gdb_assert (!value->lazy);
392
393   return ranges_contain (value->optimized_out, bit_offset, bit_length);
394 }
395
396 int
397 value_entirely_available (struct value *value)
398 {
399   /* We can only tell whether the whole value is available when we try
400      to read it.  */
401   if (value->lazy)
402     value_fetch_lazy (value);
403
404   if (value->unavailable.empty ())
405     return 1;
406   return 0;
407 }
408
409 /* Returns true if VALUE is entirely covered by RANGES.  If the value
410    is lazy, it'll be read now.  Note that RANGE is a pointer to
411    pointer because reading the value might change *RANGE.  */
412
413 static int
414 value_entirely_covered_by_range_vector (struct value *value,
415                                         const std::vector<range> &ranges)
416 {
417   /* We can only tell whether the whole value is optimized out /
418      unavailable when we try to read it.  */
419   if (value->lazy)
420     value_fetch_lazy (value);
421
422   if (ranges.size () == 1)
423     {
424       const struct range &t = ranges[0];
425
426       if (t.offset == 0
427           && t.length == (TARGET_CHAR_BIT
428                           * TYPE_LENGTH (value_enclosing_type (value))))
429         return 1;
430     }
431
432   return 0;
433 }
434
435 int
436 value_entirely_unavailable (struct value *value)
437 {
438   return value_entirely_covered_by_range_vector (value, value->unavailable);
439 }
440
441 int
442 value_entirely_optimized_out (struct value *value)
443 {
444   return value_entirely_covered_by_range_vector (value, value->optimized_out);
445 }
446
447 /* Insert into the vector pointed to by VECTORP the bit range starting of
448    OFFSET bits, and extending for the next LENGTH bits.  */
449
450 static void
451 insert_into_bit_range_vector (std::vector<range> *vectorp,
452                               LONGEST offset, LONGEST length)
453 {
454   range newr;
455
456   /* Insert the range sorted.  If there's overlap or the new range
457      would be contiguous with an existing range, merge.  */
458
459   newr.offset = offset;
460   newr.length = length;
461
462   /* Do a binary search for the position the given range would be
463      inserted if we only considered the starting OFFSET of ranges.
464      Call that position I.  Since we also have LENGTH to care for
465      (this is a range afterall), we need to check if the _previous_
466      range overlaps the I range.  E.g., calling R the new range:
467
468        #1 - overlaps with previous
469
470            R
471            |-...-|
472          |---|     |---|  |------| ... |--|
473          0         1      2            N
474
475          I=1
476
477      In the case #1 above, the binary search would return `I=1',
478      meaning, this OFFSET should be inserted at position 1, and the
479      current position 1 should be pushed further (and become 2).  But,
480      note that `0' overlaps with R, so we want to merge them.
481
482      A similar consideration needs to be taken if the new range would
483      be contiguous with the previous range:
484
485        #2 - contiguous with previous
486
487             R
488             |-...-|
489          |--|       |---|  |------| ... |--|
490          0          1      2            N
491
492          I=1
493
494      If there's no overlap with the previous range, as in:
495
496        #3 - not overlapping and not contiguous
497
498                R
499                |-...-|
500           |--|         |---|  |------| ... |--|
501           0            1      2            N
502
503          I=1
504
505      or if I is 0:
506
507        #4 - R is the range with lowest offset
508
509           R
510          |-...-|
511                  |--|       |---|  |------| ... |--|
512                  0          1      2            N
513
514          I=0
515
516      ... we just push the new range to I.
517
518      All the 4 cases above need to consider that the new range may
519      also overlap several of the ranges that follow, or that R may be
520      contiguous with the following range, and merge.  E.g.,
521
522        #5 - overlapping following ranges
523
524           R
525          |------------------------|
526                  |--|       |---|  |------| ... |--|
527                  0          1      2            N
528
529          I=0
530
531        or:
532
533             R
534             |-------|
535          |--|       |---|  |------| ... |--|
536          0          1      2            N
537
538          I=1
539
540   */
541
542   auto i = std::lower_bound (vectorp->begin (), vectorp->end (), newr);
543   if (i > vectorp->begin ())
544     {
545       struct range &bef = *(i - 1);
546
547       if (ranges_overlap (bef.offset, bef.length, offset, length))
548         {
549           /* #1 */
550           ULONGEST l = std::min (bef.offset, offset);
551           ULONGEST h = std::max (bef.offset + bef.length, offset + length);
552
553           bef.offset = l;
554           bef.length = h - l;
555           i--;
556         }
557       else if (offset == bef.offset + bef.length)
558         {
559           /* #2 */
560           bef.length += length;
561           i--;
562         }
563       else
564         {
565           /* #3 */
566           i = vectorp->insert (i, newr);
567         }
568     }
569   else
570     {
571       /* #4 */
572       i = vectorp->insert (i, newr);
573     }
574
575   /* Check whether the ranges following the one we've just added or
576      touched can be folded in (#5 above).  */
577   if (i != vectorp->end () && i + 1 < vectorp->end ())
578     {
579       int removed = 0;
580       auto next = i + 1;
581
582       /* Get the range we just touched.  */
583       struct range &t = *i;
584       removed = 0;
585
586       i = next;
587       for (; i < vectorp->end (); i++)
588         {
589           struct range &r = *i;
590           if (r.offset <= t.offset + t.length)
591             {
592               ULONGEST l, h;
593
594               l = std::min (t.offset, r.offset);
595               h = std::max (t.offset + t.length, r.offset + r.length);
596
597               t.offset = l;
598               t.length = h - l;
599
600               removed++;
601             }
602           else
603             {
604               /* If we couldn't merge this one, we won't be able to
605                  merge following ones either, since the ranges are
606                  always sorted by OFFSET.  */
607               break;
608             }
609         }
610
611       if (removed != 0)
612         vectorp->erase (next, next + removed);
613     }
614 }
615
616 void
617 mark_value_bits_unavailable (struct value *value,
618                              LONGEST offset, LONGEST length)
619 {
620   insert_into_bit_range_vector (&value->unavailable, offset, length);
621 }
622
623 void
624 mark_value_bytes_unavailable (struct value *value,
625                               LONGEST offset, LONGEST length)
626 {
627   mark_value_bits_unavailable (value,
628                                offset * TARGET_CHAR_BIT,
629                                length * TARGET_CHAR_BIT);
630 }
631
632 /* Find the first range in RANGES that overlaps the range defined by
633    OFFSET and LENGTH, starting at element POS in the RANGES vector,
634    Returns the index into RANGES where such overlapping range was
635    found, or -1 if none was found.  */
636
637 static int
638 find_first_range_overlap (const std::vector<range> *ranges, int pos,
639                           LONGEST offset, LONGEST length)
640 {
641   int i;
642
643   for (i = pos; i < ranges->size (); i++)
644     {
645       const range &r = (*ranges)[i];
646       if (ranges_overlap (r.offset, r.length, offset, length))
647         return i;
648     }
649
650   return -1;
651 }
652
653 /* Compare LENGTH_BITS of memory at PTR1 + OFFSET1_BITS with the memory at
654    PTR2 + OFFSET2_BITS.  Return 0 if the memory is the same, otherwise
655    return non-zero.
656
657    It must always be the case that:
658      OFFSET1_BITS % TARGET_CHAR_BIT == OFFSET2_BITS % TARGET_CHAR_BIT
659
660    It is assumed that memory can be accessed from:
661      PTR + (OFFSET_BITS / TARGET_CHAR_BIT)
662    to:
663      PTR + ((OFFSET_BITS + LENGTH_BITS + TARGET_CHAR_BIT - 1)
664             / TARGET_CHAR_BIT)  */
665 static int
666 memcmp_with_bit_offsets (const gdb_byte *ptr1, size_t offset1_bits,
667                          const gdb_byte *ptr2, size_t offset2_bits,
668                          size_t length_bits)
669 {
670   gdb_assert (offset1_bits % TARGET_CHAR_BIT
671               == offset2_bits % TARGET_CHAR_BIT);
672
673   if (offset1_bits % TARGET_CHAR_BIT != 0)
674     {
675       size_t bits;
676       gdb_byte mask, b1, b2;
677
678       /* The offset from the base pointers PTR1 and PTR2 is not a complete
679          number of bytes.  A number of bits up to either the next exact
680          byte boundary, or LENGTH_BITS (which ever is sooner) will be
681          compared.  */
682       bits = TARGET_CHAR_BIT - offset1_bits % TARGET_CHAR_BIT;
683       gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
684       mask = (1 << bits) - 1;
685
686       if (length_bits < bits)
687         {
688           mask &= ~(gdb_byte) ((1 << (bits - length_bits)) - 1);
689           bits = length_bits;
690         }
691
692       /* Now load the two bytes and mask off the bits we care about.  */
693       b1 = *(ptr1 + offset1_bits / TARGET_CHAR_BIT) & mask;
694       b2 = *(ptr2 + offset2_bits / TARGET_CHAR_BIT) & mask;
695
696       if (b1 != b2)
697         return 1;
698
699       /* Now update the length and offsets to take account of the bits
700          we've just compared.  */
701       length_bits -= bits;
702       offset1_bits += bits;
703       offset2_bits += bits;
704     }
705
706   if (length_bits % TARGET_CHAR_BIT != 0)
707     {
708       size_t bits;
709       size_t o1, o2;
710       gdb_byte mask, b1, b2;
711
712       /* The length is not an exact number of bytes.  After the previous
713          IF.. block then the offsets are byte aligned, or the
714          length is zero (in which case this code is not reached).  Compare
715          a number of bits at the end of the region, starting from an exact
716          byte boundary.  */
717       bits = length_bits % TARGET_CHAR_BIT;
718       o1 = offset1_bits + length_bits - bits;
719       o2 = offset2_bits + length_bits - bits;
720
721       gdb_assert (bits < sizeof (mask) * TARGET_CHAR_BIT);
722       mask = ((1 << bits) - 1) << (TARGET_CHAR_BIT - bits);
723
724       gdb_assert (o1 % TARGET_CHAR_BIT == 0);
725       gdb_assert (o2 % TARGET_CHAR_BIT == 0);
726
727       b1 = *(ptr1 + o1 / TARGET_CHAR_BIT) & mask;
728       b2 = *(ptr2 + o2 / TARGET_CHAR_BIT) & mask;
729
730       if (b1 != b2)
731         return 1;
732
733       length_bits -= bits;
734     }
735
736   if (length_bits > 0)
737     {
738       /* We've now taken care of any stray "bits" at the start, or end of
739          the region to compare, the remainder can be covered with a simple
740          memcmp.  */
741       gdb_assert (offset1_bits % TARGET_CHAR_BIT == 0);
742       gdb_assert (offset2_bits % TARGET_CHAR_BIT == 0);
743       gdb_assert (length_bits % TARGET_CHAR_BIT == 0);
744
745       return memcmp (ptr1 + offset1_bits / TARGET_CHAR_BIT,
746                      ptr2 + offset2_bits / TARGET_CHAR_BIT,
747                      length_bits / TARGET_CHAR_BIT);
748     }
749
750   /* Length is zero, regions match.  */
751   return 0;
752 }
753
754 /* Helper struct for find_first_range_overlap_and_match and
755    value_contents_bits_eq.  Keep track of which slot of a given ranges
756    vector have we last looked at.  */
757
758 struct ranges_and_idx
759 {
760   /* The ranges.  */
761   const std::vector<range> *ranges;
762
763   /* The range we've last found in RANGES.  Given ranges are sorted,
764      we can start the next lookup here.  */
765   int idx;
766 };
767
768 /* Helper function for value_contents_bits_eq.  Compare LENGTH bits of
769    RP1's ranges starting at OFFSET1 bits with LENGTH bits of RP2's
770    ranges starting at OFFSET2 bits.  Return true if the ranges match
771    and fill in *L and *H with the overlapping window relative to
772    (both) OFFSET1 or OFFSET2.  */
773
774 static int
775 find_first_range_overlap_and_match (struct ranges_and_idx *rp1,
776                                     struct ranges_and_idx *rp2,
777                                     LONGEST offset1, LONGEST offset2,
778                                     LONGEST length, ULONGEST *l, ULONGEST *h)
779 {
780   rp1->idx = find_first_range_overlap (rp1->ranges, rp1->idx,
781                                        offset1, length);
782   rp2->idx = find_first_range_overlap (rp2->ranges, rp2->idx,
783                                        offset2, length);
784
785   if (rp1->idx == -1 && rp2->idx == -1)
786     {
787       *l = length;
788       *h = length;
789       return 1;
790     }
791   else if (rp1->idx == -1 || rp2->idx == -1)
792     return 0;
793   else
794     {
795       const range *r1, *r2;
796       ULONGEST l1, h1;
797       ULONGEST l2, h2;
798
799       r1 = &(*rp1->ranges)[rp1->idx];
800       r2 = &(*rp2->ranges)[rp2->idx];
801
802       /* Get the unavailable windows intersected by the incoming
803          ranges.  The first and last ranges that overlap the argument
804          range may be wider than said incoming arguments ranges.  */
805       l1 = std::max (offset1, r1->offset);
806       h1 = std::min (offset1 + length, r1->offset + r1->length);
807
808       l2 = std::max (offset2, r2->offset);
809       h2 = std::min (offset2 + length, offset2 + r2->length);
810
811       /* Make them relative to the respective start offsets, so we can
812          compare them for equality.  */
813       l1 -= offset1;
814       h1 -= offset1;
815
816       l2 -= offset2;
817       h2 -= offset2;
818
819       /* Different ranges, no match.  */
820       if (l1 != l2 || h1 != h2)
821         return 0;
822
823       *h = h1;
824       *l = l1;
825       return 1;
826     }
827 }
828
829 /* Helper function for value_contents_eq.  The only difference is that
830    this function is bit rather than byte based.
831
832    Compare LENGTH bits of VAL1's contents starting at OFFSET1 bits
833    with LENGTH bits of VAL2's contents starting at OFFSET2 bits.
834    Return true if the available bits match.  */
835
836 static bool
837 value_contents_bits_eq (const struct value *val1, int offset1,
838                         const struct value *val2, int offset2,
839                         int length)
840 {
841   /* Each array element corresponds to a ranges source (unavailable,
842      optimized out).  '1' is for VAL1, '2' for VAL2.  */
843   struct ranges_and_idx rp1[2], rp2[2];
844
845   /* See function description in value.h.  */
846   gdb_assert (!val1->lazy && !val2->lazy);
847
848   /* We shouldn't be trying to compare past the end of the values.  */
849   gdb_assert (offset1 + length
850               <= TYPE_LENGTH (val1->enclosing_type) * TARGET_CHAR_BIT);
851   gdb_assert (offset2 + length
852               <= TYPE_LENGTH (val2->enclosing_type) * TARGET_CHAR_BIT);
853
854   memset (&rp1, 0, sizeof (rp1));
855   memset (&rp2, 0, sizeof (rp2));
856   rp1[0].ranges = &val1->unavailable;
857   rp2[0].ranges = &val2->unavailable;
858   rp1[1].ranges = &val1->optimized_out;
859   rp2[1].ranges = &val2->optimized_out;
860
861   while (length > 0)
862     {
863       ULONGEST l = 0, h = 0; /* init for gcc -Wall */
864       int i;
865
866       for (i = 0; i < 2; i++)
867         {
868           ULONGEST l_tmp, h_tmp;
869
870           /* The contents only match equal if the invalid/unavailable
871              contents ranges match as well.  */
872           if (!find_first_range_overlap_and_match (&rp1[i], &rp2[i],
873                                                    offset1, offset2, length,
874                                                    &l_tmp, &h_tmp))
875             return false;
876
877           /* We're interested in the lowest/first range found.  */
878           if (i == 0 || l_tmp < l)
879             {
880               l = l_tmp;
881               h = h_tmp;
882             }
883         }
884
885       /* Compare the available/valid contents.  */
886       if (memcmp_with_bit_offsets (val1->contents.get (), offset1,
887                                    val2->contents.get (), offset2, l) != 0)
888         return false;
889
890       length -= h;
891       offset1 += h;
892       offset2 += h;
893     }
894
895   return true;
896 }
897
898 bool
899 value_contents_eq (const struct value *val1, LONGEST offset1,
900                    const struct value *val2, LONGEST offset2,
901                    LONGEST length)
902 {
903   return value_contents_bits_eq (val1, offset1 * TARGET_CHAR_BIT,
904                                  val2, offset2 * TARGET_CHAR_BIT,
905                                  length * TARGET_CHAR_BIT);
906 }
907
908
909 /* The value-history records all the values printed by print commands
910    during this session.  */
911
912 static std::vector<value_ref_ptr> value_history;
913
914 \f
915 /* List of all value objects currently allocated
916    (except for those released by calls to release_value)
917    This is so they can be freed after each command.  */
918
919 static std::vector<value_ref_ptr> all_values;
920
921 /* Allocate a lazy value for type TYPE.  Its actual content is
922    "lazily" allocated too: the content field of the return value is
923    NULL; it will be allocated when it is fetched from the target.  */
924
925 struct value *
926 allocate_value_lazy (struct type *type)
927 {
928   struct value *val;
929
930   /* Call check_typedef on our type to make sure that, if TYPE
931      is a TYPE_CODE_TYPEDEF, its length is set to the length
932      of the target type instead of zero.  However, we do not
933      replace the typedef type by the target type, because we want
934      to keep the typedef in order to be able to set the VAL's type
935      description correctly.  */
936   check_typedef (type);
937
938   val = new struct value (type);
939
940   /* Values start out on the all_values chain.  */
941   all_values.emplace_back (val);
942
943   return val;
944 }
945
946 /* The maximum size, in bytes, that GDB will try to allocate for a value.
947    The initial value of 64k was not selected for any specific reason, it is
948    just a reasonable starting point.  */
949
950 static int max_value_size = 65536; /* 64k bytes */
951
952 /* It is critical that the MAX_VALUE_SIZE is at least as big as the size of
953    LONGEST, otherwise GDB will not be able to parse integer values from the
954    CLI; for example if the MAX_VALUE_SIZE could be set to 1 then GDB would
955    be unable to parse "set max-value-size 2".
956
957    As we want a consistent GDB experience across hosts with different sizes
958    of LONGEST, this arbitrary minimum value was selected, so long as this
959    is bigger than LONGEST on all GDB supported hosts we're fine.  */
960
961 #define MIN_VALUE_FOR_MAX_VALUE_SIZE 16
962 gdb_static_assert (sizeof (LONGEST) <= MIN_VALUE_FOR_MAX_VALUE_SIZE);
963
964 /* Implement the "set max-value-size" command.  */
965
966 static void
967 set_max_value_size (const char *args, int from_tty,
968                     struct cmd_list_element *c)
969 {
970   gdb_assert (max_value_size == -1 || max_value_size >= 0);
971
972   if (max_value_size > -1 && max_value_size < MIN_VALUE_FOR_MAX_VALUE_SIZE)
973     {
974       max_value_size = MIN_VALUE_FOR_MAX_VALUE_SIZE;
975       error (_("max-value-size set too low, increasing to %d bytes"),
976              max_value_size);
977     }
978 }
979
980 /* Implement the "show max-value-size" command.  */
981
982 static void
983 show_max_value_size (struct ui_file *file, int from_tty,
984                      struct cmd_list_element *c, const char *value)
985 {
986   if (max_value_size == -1)
987     fprintf_filtered (file, _("Maximum value size is unlimited.\n"));
988   else
989     fprintf_filtered (file, _("Maximum value size is %d bytes.\n"),
990                       max_value_size);
991 }
992
993 /* Called before we attempt to allocate or reallocate a buffer for the
994    contents of a value.  TYPE is the type of the value for which we are
995    allocating the buffer.  If the buffer is too large (based on the user
996    controllable setting) then throw an error.  If this function returns
997    then we should attempt to allocate the buffer.  */
998
999 static void
1000 check_type_length_before_alloc (const struct type *type)
1001 {
1002   ULONGEST length = TYPE_LENGTH (type);
1003
1004   if (max_value_size > -1 && length > max_value_size)
1005     {
1006       if (type->name () != NULL)
1007         error (_("value of type `%s' requires %s bytes, which is more "
1008                  "than max-value-size"), type->name (), pulongest (length));
1009       else
1010         error (_("value requires %s bytes, which is more than "
1011                  "max-value-size"), pulongest (length));
1012     }
1013 }
1014
1015 /* Allocate the contents of VAL if it has not been allocated yet.  */
1016
1017 static void
1018 allocate_value_contents (struct value *val)
1019 {
1020   if (!val->contents)
1021     {
1022       check_type_length_before_alloc (val->enclosing_type);
1023       val->contents.reset
1024         ((gdb_byte *) xzalloc (TYPE_LENGTH (val->enclosing_type)));
1025     }
1026 }
1027
1028 /* Allocate a  value  and its contents for type TYPE.  */
1029
1030 struct value *
1031 allocate_value (struct type *type)
1032 {
1033   struct value *val = allocate_value_lazy (type);
1034
1035   allocate_value_contents (val);
1036   val->lazy = 0;
1037   return val;
1038 }
1039
1040 /* Allocate a  value  that has the correct length
1041    for COUNT repetitions of type TYPE.  */
1042
1043 struct value *
1044 allocate_repeat_value (struct type *type, int count)
1045 {
1046   /* Despite the fact that we are really creating an array of TYPE here, we
1047      use the string lower bound as the array lower bound.  This seems to
1048      work fine for now.  */
1049   int low_bound = current_language->string_lower_bound ();
1050   /* FIXME-type-allocation: need a way to free this type when we are
1051      done with it.  */
1052   struct type *array_type
1053     = lookup_array_range_type (type, low_bound, count + low_bound - 1);
1054
1055   return allocate_value (array_type);
1056 }
1057
1058 struct value *
1059 allocate_computed_value (struct type *type,
1060                          const struct lval_funcs *funcs,
1061                          void *closure)
1062 {
1063   struct value *v = allocate_value_lazy (type);
1064
1065   VALUE_LVAL (v) = lval_computed;
1066   v->location.computed.funcs = funcs;
1067   v->location.computed.closure = closure;
1068
1069   return v;
1070 }
1071
1072 /* Allocate NOT_LVAL value for type TYPE being OPTIMIZED_OUT.  */
1073
1074 struct value *
1075 allocate_optimized_out_value (struct type *type)
1076 {
1077   struct value *retval = allocate_value_lazy (type);
1078
1079   mark_value_bytes_optimized_out (retval, 0, TYPE_LENGTH (type));
1080   set_value_lazy (retval, 0);
1081   return retval;
1082 }
1083
1084 /* Accessor methods.  */
1085
1086 struct type *
1087 value_type (const struct value *value)
1088 {
1089   return value->type;
1090 }
1091 void
1092 deprecated_set_value_type (struct value *value, struct type *type)
1093 {
1094   value->type = type;
1095 }
1096
1097 LONGEST
1098 value_offset (const struct value *value)
1099 {
1100   return value->offset;
1101 }
1102 void
1103 set_value_offset (struct value *value, LONGEST offset)
1104 {
1105   value->offset = offset;
1106 }
1107
1108 LONGEST
1109 value_bitpos (const struct value *value)
1110 {
1111   return value->bitpos;
1112 }
1113 void
1114 set_value_bitpos (struct value *value, LONGEST bit)
1115 {
1116   value->bitpos = bit;
1117 }
1118
1119 LONGEST
1120 value_bitsize (const struct value *value)
1121 {
1122   return value->bitsize;
1123 }
1124 void
1125 set_value_bitsize (struct value *value, LONGEST bit)
1126 {
1127   value->bitsize = bit;
1128 }
1129
1130 struct value *
1131 value_parent (const struct value *value)
1132 {
1133   return value->parent.get ();
1134 }
1135
1136 /* See value.h.  */
1137
1138 void
1139 set_value_parent (struct value *value, struct value *parent)
1140 {
1141   value->parent = value_ref_ptr::new_reference (parent);
1142 }
1143
1144 gdb_byte *
1145 value_contents_raw (struct value *value)
1146 {
1147   struct gdbarch *arch = get_value_arch (value);
1148   int unit_size = gdbarch_addressable_memory_unit_size (arch);
1149
1150   allocate_value_contents (value);
1151   return value->contents.get () + value->embedded_offset * unit_size;
1152 }
1153
1154 gdb_byte *
1155 value_contents_all_raw (struct value *value)
1156 {
1157   allocate_value_contents (value);
1158   return value->contents.get ();
1159 }
1160
1161 struct type *
1162 value_enclosing_type (const struct value *value)
1163 {
1164   return value->enclosing_type;
1165 }
1166
1167 /* Look at value.h for description.  */
1168
1169 struct type *
1170 value_actual_type (struct value *value, int resolve_simple_types,
1171                    int *real_type_found)
1172 {
1173   struct value_print_options opts;
1174   struct type *result;
1175
1176   get_user_print_options (&opts);
1177
1178   if (real_type_found)
1179     *real_type_found = 0;
1180   result = value_type (value);
1181   if (opts.objectprint)
1182     {
1183       /* If result's target type is TYPE_CODE_STRUCT, proceed to
1184          fetch its rtti type.  */
1185       if (result->is_pointer_or_reference ()
1186           && (check_typedef (TYPE_TARGET_TYPE (result))->code ()
1187               == TYPE_CODE_STRUCT)
1188           && !value_optimized_out (value))
1189         {
1190           struct type *real_type;
1191
1192           real_type = value_rtti_indirect_type (value, NULL, NULL, NULL);
1193           if (real_type)
1194             {
1195               if (real_type_found)
1196                 *real_type_found = 1;
1197               result = real_type;
1198             }
1199         }
1200       else if (resolve_simple_types)
1201         {
1202           if (real_type_found)
1203             *real_type_found = 1;
1204           result = value_enclosing_type (value);
1205         }
1206     }
1207
1208   return result;
1209 }
1210
1211 void
1212 error_value_optimized_out (void)
1213 {
1214   error (_("value has been optimized out"));
1215 }
1216
1217 static void
1218 require_not_optimized_out (const struct value *value)
1219 {
1220   if (!value->optimized_out.empty ())
1221     {
1222       if (value->lval == lval_register)
1223         error (_("register has not been saved in frame"));
1224       else
1225         error_value_optimized_out ();
1226     }
1227 }
1228
1229 static void
1230 require_available (const struct value *value)
1231 {
1232   if (!value->unavailable.empty ())
1233     throw_error (NOT_AVAILABLE_ERROR, _("value is not available"));
1234 }
1235
1236 const gdb_byte *
1237 value_contents_for_printing (struct value *value)
1238 {
1239   if (value->lazy)
1240     value_fetch_lazy (value);
1241   return value->contents.get ();
1242 }
1243
1244 const gdb_byte *
1245 value_contents_for_printing_const (const struct value *value)
1246 {
1247   gdb_assert (!value->lazy);
1248   return value->contents.get ();
1249 }
1250
1251 const gdb_byte *
1252 value_contents_all (struct value *value)
1253 {
1254   const gdb_byte *result = value_contents_for_printing (value);
1255   require_not_optimized_out (value);
1256   require_available (value);
1257   return result;
1258 }
1259
1260 /* Copy ranges in SRC_RANGE that overlap [SRC_BIT_OFFSET,
1261    SRC_BIT_OFFSET+BIT_LENGTH) ranges into *DST_RANGE, adjusted.  */
1262
1263 static void
1264 ranges_copy_adjusted (std::vector<range> *dst_range, int dst_bit_offset,
1265                       const std::vector<range> &src_range, int src_bit_offset,
1266                       int bit_length)
1267 {
1268   for (const range &r : src_range)
1269     {
1270       ULONGEST h, l;
1271
1272       l = std::max (r.offset, (LONGEST) src_bit_offset);
1273       h = std::min (r.offset + r.length,
1274                     (LONGEST) src_bit_offset + bit_length);
1275
1276       if (l < h)
1277         insert_into_bit_range_vector (dst_range,
1278                                       dst_bit_offset + (l - src_bit_offset),
1279                                       h - l);
1280     }
1281 }
1282
1283 /* Copy the ranges metadata in SRC that overlaps [SRC_BIT_OFFSET,
1284    SRC_BIT_OFFSET+BIT_LENGTH) into DST, adjusted.  */
1285
1286 static void
1287 value_ranges_copy_adjusted (struct value *dst, int dst_bit_offset,
1288                             const struct value *src, int src_bit_offset,
1289                             int bit_length)
1290 {
1291   ranges_copy_adjusted (&dst->unavailable, dst_bit_offset,
1292                         src->unavailable, src_bit_offset,
1293                         bit_length);
1294   ranges_copy_adjusted (&dst->optimized_out, dst_bit_offset,
1295                         src->optimized_out, src_bit_offset,
1296                         bit_length);
1297 }
1298
1299 /* Copy LENGTH target addressable memory units of SRC value's (all) contents
1300    (value_contents_all) starting at SRC_OFFSET, into DST value's (all)
1301    contents, starting at DST_OFFSET.  If unavailable contents are
1302    being copied from SRC, the corresponding DST contents are marked
1303    unavailable accordingly.  Neither DST nor SRC may be lazy
1304    values.
1305
1306    It is assumed the contents of DST in the [DST_OFFSET,
1307    DST_OFFSET+LENGTH) range are wholly available.  */
1308
1309 static void
1310 value_contents_copy_raw (struct value *dst, LONGEST dst_offset,
1311                          struct value *src, LONGEST src_offset, LONGEST length)
1312 {
1313   LONGEST src_bit_offset, dst_bit_offset, bit_length;
1314   struct gdbarch *arch = get_value_arch (src);
1315   int unit_size = gdbarch_addressable_memory_unit_size (arch);
1316
1317   /* A lazy DST would make that this copy operation useless, since as
1318      soon as DST's contents were un-lazied (by a later value_contents
1319      call, say), the contents would be overwritten.  A lazy SRC would
1320      mean we'd be copying garbage.  */
1321   gdb_assert (!dst->lazy && !src->lazy);
1322
1323   /* The overwritten DST range gets unavailability ORed in, not
1324      replaced.  Make sure to remember to implement replacing if it
1325      turns out actually necessary.  */
1326   gdb_assert (value_bytes_available (dst, dst_offset, length));
1327   gdb_assert (!value_bits_any_optimized_out (dst,
1328                                              TARGET_CHAR_BIT * dst_offset,
1329                                              TARGET_CHAR_BIT * length));
1330
1331   /* Copy the data.  */
1332   memcpy (value_contents_all_raw (dst) + dst_offset * unit_size,
1333           value_contents_all_raw (src) + src_offset * unit_size,
1334           length * unit_size);
1335
1336   /* Copy the meta-data, adjusted.  */
1337   src_bit_offset = src_offset * unit_size * HOST_CHAR_BIT;
1338   dst_bit_offset = dst_offset * unit_size * HOST_CHAR_BIT;
1339   bit_length = length * unit_size * HOST_CHAR_BIT;
1340
1341   value_ranges_copy_adjusted (dst, dst_bit_offset,
1342                               src, src_bit_offset,
1343                               bit_length);
1344 }
1345
1346 /* Copy LENGTH bytes of SRC value's (all) contents
1347    (value_contents_all) starting at SRC_OFFSET byte, into DST value's
1348    (all) contents, starting at DST_OFFSET.  If unavailable contents
1349    are being copied from SRC, the corresponding DST contents are
1350    marked unavailable accordingly.  DST must not be lazy.  If SRC is
1351    lazy, it will be fetched now.
1352
1353    It is assumed the contents of DST in the [DST_OFFSET,
1354    DST_OFFSET+LENGTH) range are wholly available.  */
1355
1356 void
1357 value_contents_copy (struct value *dst, LONGEST dst_offset,
1358                      struct value *src, LONGEST src_offset, LONGEST length)
1359 {
1360   if (src->lazy)
1361     value_fetch_lazy (src);
1362
1363   value_contents_copy_raw (dst, dst_offset, src, src_offset, length);
1364 }
1365
1366 int
1367 value_lazy (const struct value *value)
1368 {
1369   return value->lazy;
1370 }
1371
1372 void
1373 set_value_lazy (struct value *value, int val)
1374 {
1375   value->lazy = val;
1376 }
1377
1378 int
1379 value_stack (const struct value *value)
1380 {
1381   return value->stack;
1382 }
1383
1384 void
1385 set_value_stack (struct value *value, int val)
1386 {
1387   value->stack = val;
1388 }
1389
1390 const gdb_byte *
1391 value_contents (struct value *value)
1392 {
1393   const gdb_byte *result = value_contents_writeable (value);
1394   require_not_optimized_out (value);
1395   require_available (value);
1396   return result;
1397 }
1398
1399 gdb_byte *
1400 value_contents_writeable (struct value *value)
1401 {
1402   if (value->lazy)
1403     value_fetch_lazy (value);
1404   return value_contents_raw (value);
1405 }
1406
1407 int
1408 value_optimized_out (struct value *value)
1409 {
1410   /* We can only know if a value is optimized out once we have tried to
1411      fetch it.  */
1412   if (value->optimized_out.empty () && value->lazy)
1413     {
1414       try
1415         {
1416           value_fetch_lazy (value);
1417         }
1418       catch (const gdb_exception_error &ex)
1419         {
1420           switch (ex.error)
1421             {
1422             case MEMORY_ERROR:
1423             case OPTIMIZED_OUT_ERROR:
1424             case NOT_AVAILABLE_ERROR:
1425               /* These can normally happen when we try to access an
1426                  optimized out or unavailable register, either in a
1427                  physical register or spilled to memory.  */
1428               break;
1429             default:
1430               throw;
1431             }
1432         }
1433     }
1434
1435   return !value->optimized_out.empty ();
1436 }
1437
1438 /* Mark contents of VALUE as optimized out, starting at OFFSET bytes, and
1439    the following LENGTH bytes.  */
1440
1441 void
1442 mark_value_bytes_optimized_out (struct value *value, int offset, int length)
1443 {
1444   mark_value_bits_optimized_out (value,
1445                                  offset * TARGET_CHAR_BIT,
1446                                  length * TARGET_CHAR_BIT);
1447 }
1448
1449 /* See value.h.  */
1450
1451 void
1452 mark_value_bits_optimized_out (struct value *value,
1453                                LONGEST offset, LONGEST length)
1454 {
1455   insert_into_bit_range_vector (&value->optimized_out, offset, length);
1456 }
1457
1458 int
1459 value_bits_synthetic_pointer (const struct value *value,
1460                               LONGEST offset, LONGEST length)
1461 {
1462   if (value->lval != lval_computed
1463       || !value->location.computed.funcs->check_synthetic_pointer)
1464     return 0;
1465   return value->location.computed.funcs->check_synthetic_pointer (value,
1466                                                                   offset,
1467                                                                   length);
1468 }
1469
1470 LONGEST
1471 value_embedded_offset (const struct value *value)
1472 {
1473   return value->embedded_offset;
1474 }
1475
1476 void
1477 set_value_embedded_offset (struct value *value, LONGEST val)
1478 {
1479   value->embedded_offset = val;
1480 }
1481
1482 LONGEST
1483 value_pointed_to_offset (const struct value *value)
1484 {
1485   return value->pointed_to_offset;
1486 }
1487
1488 void
1489 set_value_pointed_to_offset (struct value *value, LONGEST val)
1490 {
1491   value->pointed_to_offset = val;
1492 }
1493
1494 const struct lval_funcs *
1495 value_computed_funcs (const struct value *v)
1496 {
1497   gdb_assert (value_lval_const (v) == lval_computed);
1498
1499   return v->location.computed.funcs;
1500 }
1501
1502 void *
1503 value_computed_closure (const struct value *v)
1504 {
1505   gdb_assert (v->lval == lval_computed);
1506
1507   return v->location.computed.closure;
1508 }
1509
1510 enum lval_type *
1511 deprecated_value_lval_hack (struct value *value)
1512 {
1513   return &value->lval;
1514 }
1515
1516 enum lval_type
1517 value_lval_const (const struct value *value)
1518 {
1519   return value->lval;
1520 }
1521
1522 CORE_ADDR
1523 value_address (const struct value *value)
1524 {
1525   if (value->lval != lval_memory)
1526     return 0;
1527   if (value->parent != NULL)
1528     return value_address (value->parent.get ()) + value->offset;
1529   if (NULL != TYPE_DATA_LOCATION (value_type (value)))
1530     {
1531       gdb_assert (PROP_CONST == TYPE_DATA_LOCATION_KIND (value_type (value)));
1532       return TYPE_DATA_LOCATION_ADDR (value_type (value));
1533     }
1534
1535   return value->location.address + value->offset;
1536 }
1537
1538 CORE_ADDR
1539 value_raw_address (const struct value *value)
1540 {
1541   if (value->lval != lval_memory)
1542     return 0;
1543   return value->location.address;
1544 }
1545
1546 void
1547 set_value_address (struct value *value, CORE_ADDR addr)
1548 {
1549   gdb_assert (value->lval == lval_memory);
1550   value->location.address = addr;
1551 }
1552
1553 struct internalvar **
1554 deprecated_value_internalvar_hack (struct value *value)
1555 {
1556   return &value->location.internalvar;
1557 }
1558
1559 struct frame_id *
1560 deprecated_value_next_frame_id_hack (struct value *value)
1561 {
1562   gdb_assert (value->lval == lval_register);
1563   return &value->location.reg.next_frame_id;
1564 }
1565
1566 int *
1567 deprecated_value_regnum_hack (struct value *value)
1568 {
1569   gdb_assert (value->lval == lval_register);
1570   return &value->location.reg.regnum;
1571 }
1572
1573 int
1574 deprecated_value_modifiable (const struct value *value)
1575 {
1576   return value->modifiable;
1577 }
1578 \f
1579 /* Return a mark in the value chain.  All values allocated after the
1580    mark is obtained (except for those released) are subject to being freed
1581    if a subsequent value_free_to_mark is passed the mark.  */
1582 struct value *
1583 value_mark (void)
1584 {
1585   if (all_values.empty ())
1586     return nullptr;
1587   return all_values.back ().get ();
1588 }
1589
1590 /* See value.h.  */
1591
1592 void
1593 value_incref (struct value *val)
1594 {
1595   val->reference_count++;
1596 }
1597
1598 /* Release a reference to VAL, which was acquired with value_incref.
1599    This function is also called to deallocate values from the value
1600    chain.  */
1601
1602 void
1603 value_decref (struct value *val)
1604 {
1605   if (val != nullptr)
1606     {
1607       gdb_assert (val->reference_count > 0);
1608       val->reference_count--;
1609       if (val->reference_count == 0)
1610         delete val;
1611     }
1612 }
1613
1614 /* Free all values allocated since MARK was obtained by value_mark
1615    (except for those released).  */
1616 void
1617 value_free_to_mark (const struct value *mark)
1618 {
1619   auto iter = std::find (all_values.begin (), all_values.end (), mark);
1620   if (iter == all_values.end ())
1621     all_values.clear ();
1622   else
1623     all_values.erase (iter + 1, all_values.end ());
1624 }
1625
1626 /* Remove VAL from the chain all_values
1627    so it will not be freed automatically.  */
1628
1629 value_ref_ptr
1630 release_value (struct value *val)
1631 {
1632   if (val == nullptr)
1633     return value_ref_ptr ();
1634
1635   std::vector<value_ref_ptr>::reverse_iterator iter;
1636   for (iter = all_values.rbegin (); iter != all_values.rend (); ++iter)
1637     {
1638       if (*iter == val)
1639         {
1640           value_ref_ptr result = *iter;
1641           all_values.erase (iter.base () - 1);
1642           return result;
1643         }
1644     }
1645
1646   /* We must always return an owned reference.  Normally this happens
1647      because we transfer the reference from the value chain, but in
1648      this case the value was not on the chain.  */
1649   return value_ref_ptr::new_reference (val);
1650 }
1651
1652 /* See value.h.  */
1653
1654 std::vector<value_ref_ptr>
1655 value_release_to_mark (const struct value *mark)
1656 {
1657   std::vector<value_ref_ptr> result;
1658
1659   auto iter = std::find (all_values.begin (), all_values.end (), mark);
1660   if (iter == all_values.end ())
1661     std::swap (result, all_values);
1662   else
1663     {
1664       std::move (iter + 1, all_values.end (), std::back_inserter (result));
1665       all_values.erase (iter + 1, all_values.end ());
1666     }
1667   std::reverse (result.begin (), result.end ());
1668   return result;
1669 }
1670
1671 /* Return a copy of the value ARG.
1672    It contains the same contents, for same memory address,
1673    but it's a different block of storage.  */
1674
1675 struct value *
1676 value_copy (struct value *arg)
1677 {
1678   struct type *encl_type = value_enclosing_type (arg);
1679   struct value *val;
1680
1681   if (value_lazy (arg))
1682     val = allocate_value_lazy (encl_type);
1683   else
1684     val = allocate_value (encl_type);
1685   val->type = arg->type;
1686   VALUE_LVAL (val) = VALUE_LVAL (arg);
1687   val->location = arg->location;
1688   val->offset = arg->offset;
1689   val->bitpos = arg->bitpos;
1690   val->bitsize = arg->bitsize;
1691   val->lazy = arg->lazy;
1692   val->embedded_offset = value_embedded_offset (arg);
1693   val->pointed_to_offset = arg->pointed_to_offset;
1694   val->modifiable = arg->modifiable;
1695   val->stack = arg->stack;
1696   val->initialized = arg->initialized;
1697   if (!value_lazy (val))
1698     {
1699       memcpy (value_contents_all_raw (val), value_contents_all_raw (arg),
1700               TYPE_LENGTH (value_enclosing_type (arg)));
1701
1702     }
1703   val->unavailable = arg->unavailable;
1704   val->optimized_out = arg->optimized_out;
1705   val->parent = arg->parent;
1706   if (VALUE_LVAL (val) == lval_computed)
1707     {
1708       const struct lval_funcs *funcs = val->location.computed.funcs;
1709
1710       if (funcs->copy_closure)
1711         val->location.computed.closure = funcs->copy_closure (val);
1712     }
1713   return val;
1714 }
1715
1716 /* Return a "const" and/or "volatile" qualified version of the value V.
1717    If CNST is true, then the returned value will be qualified with
1718    "const".
1719    if VOLTL is true, then the returned value will be qualified with
1720    "volatile".  */
1721
1722 struct value *
1723 make_cv_value (int cnst, int voltl, struct value *v)
1724 {
1725   struct type *val_type = value_type (v);
1726   struct type *enclosing_type = value_enclosing_type (v);
1727   struct value *cv_val = value_copy (v);
1728
1729   deprecated_set_value_type (cv_val,
1730                              make_cv_type (cnst, voltl, val_type, NULL));
1731   set_value_enclosing_type (cv_val,
1732                             make_cv_type (cnst, voltl, enclosing_type, NULL));
1733
1734   return cv_val;
1735 }
1736
1737 /* Return a version of ARG that is non-lvalue.  */
1738
1739 struct value *
1740 value_non_lval (struct value *arg)
1741 {
1742   if (VALUE_LVAL (arg) != not_lval)
1743     {
1744       struct type *enc_type = value_enclosing_type (arg);
1745       struct value *val = allocate_value (enc_type);
1746
1747       memcpy (value_contents_all_raw (val), value_contents_all (arg),
1748               TYPE_LENGTH (enc_type));
1749       val->type = arg->type;
1750       set_value_embedded_offset (val, value_embedded_offset (arg));
1751       set_value_pointed_to_offset (val, value_pointed_to_offset (arg));
1752       return val;
1753     }
1754    return arg;
1755 }
1756
1757 /* Write contents of V at ADDR and set its lval type to be LVAL_MEMORY.  */
1758
1759 void
1760 value_force_lval (struct value *v, CORE_ADDR addr)
1761 {
1762   gdb_assert (VALUE_LVAL (v) == not_lval);
1763
1764   write_memory (addr, value_contents_raw (v), TYPE_LENGTH (value_type (v)));
1765   v->lval = lval_memory;
1766   v->location.address = addr;
1767 }
1768
1769 void
1770 set_value_component_location (struct value *component,
1771                               const struct value *whole)
1772 {
1773   struct type *type;
1774
1775   gdb_assert (whole->lval != lval_xcallable);
1776
1777   if (whole->lval == lval_internalvar)
1778     VALUE_LVAL (component) = lval_internalvar_component;
1779   else
1780     VALUE_LVAL (component) = whole->lval;
1781
1782   component->location = whole->location;
1783   if (whole->lval == lval_computed)
1784     {
1785       const struct lval_funcs *funcs = whole->location.computed.funcs;
1786
1787       if (funcs->copy_closure)
1788         component->location.computed.closure = funcs->copy_closure (whole);
1789     }
1790
1791   /* If the WHOLE value has a dynamically resolved location property then
1792      update the address of the COMPONENT.  */
1793   type = value_type (whole);
1794   if (NULL != TYPE_DATA_LOCATION (type)
1795       && TYPE_DATA_LOCATION_KIND (type) == PROP_CONST)
1796     set_value_address (component, TYPE_DATA_LOCATION_ADDR (type));
1797
1798   /* Similarly, if the COMPONENT value has a dynamically resolved location
1799      property then update its address.  */
1800   type = value_type (component);
1801   if (NULL != TYPE_DATA_LOCATION (type)
1802       && TYPE_DATA_LOCATION_KIND (type) == PROP_CONST)
1803     {
1804       /* If the COMPONENT has a dynamic location, and is an
1805          lval_internalvar_component, then we change it to a lval_memory.
1806
1807          Usually a component of an internalvar is created non-lazy, and has
1808          its content immediately copied from the parent internalvar.
1809          However, for components with a dynamic location, the content of
1810          the component is not contained within the parent, but is instead
1811          accessed indirectly.  Further, the component will be created as a
1812          lazy value.
1813
1814          By changing the type of the component to lval_memory we ensure
1815          that value_fetch_lazy can successfully load the component.
1816
1817          This solution isn't ideal, but a real fix would require values to
1818          carry around both the parent value contents, and the contents of
1819          any dynamic fields within the parent.  This is a substantial
1820          change to how values work in GDB.  */
1821       if (VALUE_LVAL (component) == lval_internalvar_component)
1822         {
1823           gdb_assert (value_lazy (component));
1824           VALUE_LVAL (component) = lval_memory;
1825         }
1826       else
1827         gdb_assert (VALUE_LVAL (component) == lval_memory);
1828       set_value_address (component, TYPE_DATA_LOCATION_ADDR (type));
1829     }
1830 }
1831
1832 /* Access to the value history.  */
1833
1834 /* Record a new value in the value history.
1835    Returns the absolute history index of the entry.  */
1836
1837 int
1838 record_latest_value (struct value *val)
1839 {
1840   /* We don't want this value to have anything to do with the inferior anymore.
1841      In particular, "set $1 = 50" should not affect the variable from which
1842      the value was taken, and fast watchpoints should be able to assume that
1843      a value on the value history never changes.  */
1844   if (value_lazy (val))
1845     value_fetch_lazy (val);
1846   /* We preserve VALUE_LVAL so that the user can find out where it was fetched
1847      from.  This is a bit dubious, because then *&$1 does not just return $1
1848      but the current contents of that location.  c'est la vie...  */
1849   val->modifiable = 0;
1850
1851   value_history.push_back (release_value (val));
1852
1853   return value_history.size ();
1854 }
1855
1856 /* Return a copy of the value in the history with sequence number NUM.  */
1857
1858 struct value *
1859 access_value_history (int num)
1860 {
1861   int absnum = num;
1862
1863   if (absnum <= 0)
1864     absnum += value_history.size ();
1865
1866   if (absnum <= 0)
1867     {
1868       if (num == 0)
1869         error (_("The history is empty."));
1870       else if (num == 1)
1871         error (_("There is only one value in the history."));
1872       else
1873         error (_("History does not go back to $$%d."), -num);
1874     }
1875   if (absnum > value_history.size ())
1876     error (_("History has not yet reached $%d."), absnum);
1877
1878   absnum--;
1879
1880   return value_copy (value_history[absnum].get ());
1881 }
1882
1883 static void
1884 show_values (const char *num_exp, int from_tty)
1885 {
1886   int i;
1887   struct value *val;
1888   static int num = 1;
1889
1890   if (num_exp)
1891     {
1892       /* "show values +" should print from the stored position.
1893          "show values <exp>" should print around value number <exp>.  */
1894       if (num_exp[0] != '+' || num_exp[1] != '\0')
1895         num = parse_and_eval_long (num_exp) - 5;
1896     }
1897   else
1898     {
1899       /* "show values" means print the last 10 values.  */
1900       num = value_history.size () - 9;
1901     }
1902
1903   if (num <= 0)
1904     num = 1;
1905
1906   for (i = num; i < num + 10 && i <= value_history.size (); i++)
1907     {
1908       struct value_print_options opts;
1909
1910       val = access_value_history (i);
1911       printf_filtered (("$%d = "), i);
1912       get_user_print_options (&opts);
1913       value_print (val, gdb_stdout, &opts);
1914       printf_filtered (("\n"));
1915     }
1916
1917   /* The next "show values +" should start after what we just printed.  */
1918   num += 10;
1919
1920   /* Hitting just return after this command should do the same thing as
1921      "show values +".  If num_exp is null, this is unnecessary, since
1922      "show values +" is not useful after "show values".  */
1923   if (from_tty && num_exp)
1924     set_repeat_arguments ("+");
1925 }
1926 \f
1927 enum internalvar_kind
1928 {
1929   /* The internal variable is empty.  */
1930   INTERNALVAR_VOID,
1931
1932   /* The value of the internal variable is provided directly as
1933      a GDB value object.  */
1934   INTERNALVAR_VALUE,
1935
1936   /* A fresh value is computed via a call-back routine on every
1937      access to the internal variable.  */
1938   INTERNALVAR_MAKE_VALUE,
1939
1940   /* The internal variable holds a GDB internal convenience function.  */
1941   INTERNALVAR_FUNCTION,
1942
1943   /* The variable holds an integer value.  */
1944   INTERNALVAR_INTEGER,
1945
1946   /* The variable holds a GDB-provided string.  */
1947   INTERNALVAR_STRING,
1948 };
1949
1950 union internalvar_data
1951 {
1952   /* A value object used with INTERNALVAR_VALUE.  */
1953   struct value *value;
1954
1955   /* The call-back routine used with INTERNALVAR_MAKE_VALUE.  */
1956   struct
1957   {
1958     /* The functions to call.  */
1959     const struct internalvar_funcs *functions;
1960
1961     /* The function's user-data.  */
1962     void *data;
1963   } make_value;
1964
1965   /* The internal function used with INTERNALVAR_FUNCTION.  */
1966   struct
1967   {
1968     struct internal_function *function;
1969     /* True if this is the canonical name for the function.  */
1970     int canonical;
1971   } fn;
1972
1973   /* An integer value used with INTERNALVAR_INTEGER.  */
1974   struct
1975   {
1976     /* If type is non-NULL, it will be used as the type to generate
1977        a value for this internal variable.  If type is NULL, a default
1978        integer type for the architecture is used.  */
1979     struct type *type;
1980     LONGEST val;
1981   } integer;
1982
1983   /* A string value used with INTERNALVAR_STRING.  */
1984   char *string;
1985 };
1986
1987 /* Internal variables.  These are variables within the debugger
1988    that hold values assigned by debugger commands.
1989    The user refers to them with a '$' prefix
1990    that does not appear in the variable names stored internally.  */
1991
1992 struct internalvar
1993 {
1994   struct internalvar *next;
1995   char *name;
1996
1997   /* We support various different kinds of content of an internal variable.
1998      enum internalvar_kind specifies the kind, and union internalvar_data
1999      provides the data associated with this particular kind.  */
2000
2001   enum internalvar_kind kind;
2002
2003   union internalvar_data u;
2004 };
2005
2006 static struct internalvar *internalvars;
2007
2008 /* If the variable does not already exist create it and give it the
2009    value given.  If no value is given then the default is zero.  */
2010 static void
2011 init_if_undefined_command (const char* args, int from_tty)
2012 {
2013   struct internalvar *intvar = nullptr;
2014
2015   /* Parse the expression - this is taken from set_command().  */
2016   expression_up expr = parse_expression (args);
2017
2018   /* Validate the expression.
2019      Was the expression an assignment?
2020      Or even an expression at all?  */
2021   if (expr->first_opcode () != BINOP_ASSIGN)
2022     error (_("Init-if-undefined requires an assignment expression."));
2023
2024   /* Extract the variable from the parsed expression.  */
2025   expr::assign_operation *assign
2026     = dynamic_cast<expr::assign_operation *> (expr->op.get ());
2027   if (assign != nullptr)
2028     {
2029       expr::operation *lhs = assign->get_lhs ();
2030       expr::internalvar_operation *ivarop
2031         = dynamic_cast<expr::internalvar_operation *> (lhs);
2032       if (ivarop != nullptr)
2033         intvar = ivarop->get_internalvar ();
2034     }
2035
2036   if (intvar == nullptr)
2037     error (_("The first parameter to init-if-undefined "
2038              "should be a GDB variable."));
2039
2040   /* Only evaluate the expression if the lvalue is void.
2041      This may still fail if the expression is invalid.  */
2042   if (intvar->kind == INTERNALVAR_VOID)
2043     evaluate_expression (expr.get ());
2044 }
2045
2046
2047 /* Look up an internal variable with name NAME.  NAME should not
2048    normally include a dollar sign.
2049
2050    If the specified internal variable does not exist,
2051    the return value is NULL.  */
2052
2053 struct internalvar *
2054 lookup_only_internalvar (const char *name)
2055 {
2056   struct internalvar *var;
2057
2058   for (var = internalvars; var; var = var->next)
2059     if (strcmp (var->name, name) == 0)
2060       return var;
2061
2062   return NULL;
2063 }
2064
2065 /* Complete NAME by comparing it to the names of internal
2066    variables.  */
2067
2068 void
2069 complete_internalvar (completion_tracker &tracker, const char *name)
2070 {
2071   struct internalvar *var;
2072   int len;
2073
2074   len = strlen (name);
2075
2076   for (var = internalvars; var; var = var->next)
2077     if (strncmp (var->name, name, len) == 0)
2078       tracker.add_completion (make_unique_xstrdup (var->name));
2079 }
2080
2081 /* Create an internal variable with name NAME and with a void value.
2082    NAME should not normally include a dollar sign.  */
2083
2084 struct internalvar *
2085 create_internalvar (const char *name)
2086 {
2087   struct internalvar *var = XNEW (struct internalvar);
2088
2089   var->name = xstrdup (name);
2090   var->kind = INTERNALVAR_VOID;
2091   var->next = internalvars;
2092   internalvars = var;
2093   return var;
2094 }
2095
2096 /* Create an internal variable with name NAME and register FUN as the
2097    function that value_of_internalvar uses to create a value whenever
2098    this variable is referenced.  NAME should not normally include a
2099    dollar sign.  DATA is passed uninterpreted to FUN when it is
2100    called.  CLEANUP, if not NULL, is called when the internal variable
2101    is destroyed.  It is passed DATA as its only argument.  */
2102
2103 struct internalvar *
2104 create_internalvar_type_lazy (const char *name,
2105                               const struct internalvar_funcs *funcs,
2106                               void *data)
2107 {
2108   struct internalvar *var = create_internalvar (name);
2109
2110   var->kind = INTERNALVAR_MAKE_VALUE;
2111   var->u.make_value.functions = funcs;
2112   var->u.make_value.data = data;
2113   return var;
2114 }
2115
2116 /* See documentation in value.h.  */
2117
2118 int
2119 compile_internalvar_to_ax (struct internalvar *var,
2120                            struct agent_expr *expr,
2121                            struct axs_value *value)
2122 {
2123   if (var->kind != INTERNALVAR_MAKE_VALUE
2124       || var->u.make_value.functions->compile_to_ax == NULL)
2125     return 0;
2126
2127   var->u.make_value.functions->compile_to_ax (var, expr, value,
2128                                               var->u.make_value.data);
2129   return 1;
2130 }
2131
2132 /* Look up an internal variable with name NAME.  NAME should not
2133    normally include a dollar sign.
2134
2135    If the specified internal variable does not exist,
2136    one is created, with a void value.  */
2137
2138 struct internalvar *
2139 lookup_internalvar (const char *name)
2140 {
2141   struct internalvar *var;
2142
2143   var = lookup_only_internalvar (name);
2144   if (var)
2145     return var;
2146
2147   return create_internalvar (name);
2148 }
2149
2150 /* Return current value of internal variable VAR.  For variables that
2151    are not inherently typed, use a value type appropriate for GDBARCH.  */
2152
2153 struct value *
2154 value_of_internalvar (struct gdbarch *gdbarch, struct internalvar *var)
2155 {
2156   struct value *val;
2157   struct trace_state_variable *tsv;
2158
2159   /* If there is a trace state variable of the same name, assume that
2160      is what we really want to see.  */
2161   tsv = find_trace_state_variable (var->name);
2162   if (tsv)
2163     {
2164       tsv->value_known = target_get_trace_state_variable_value (tsv->number,
2165                                                                 &(tsv->value));
2166       if (tsv->value_known)
2167         val = value_from_longest (builtin_type (gdbarch)->builtin_int64,
2168                                   tsv->value);
2169       else
2170         val = allocate_value (builtin_type (gdbarch)->builtin_void);
2171       return val;
2172     }
2173
2174   switch (var->kind)
2175     {
2176     case INTERNALVAR_VOID:
2177       val = allocate_value (builtin_type (gdbarch)->builtin_void);
2178       break;
2179
2180     case INTERNALVAR_FUNCTION:
2181       val = allocate_value (builtin_type (gdbarch)->internal_fn);
2182       break;
2183
2184     case INTERNALVAR_INTEGER:
2185       if (!var->u.integer.type)
2186         val = value_from_longest (builtin_type (gdbarch)->builtin_int,
2187                                   var->u.integer.val);
2188       else
2189         val = value_from_longest (var->u.integer.type, var->u.integer.val);
2190       break;
2191
2192     case INTERNALVAR_STRING:
2193       val = value_cstring (var->u.string, strlen (var->u.string),
2194                            builtin_type (gdbarch)->builtin_char);
2195       break;
2196
2197     case INTERNALVAR_VALUE:
2198       val = value_copy (var->u.value);
2199       if (value_lazy (val))
2200         value_fetch_lazy (val);
2201       break;
2202
2203     case INTERNALVAR_MAKE_VALUE:
2204       val = (*var->u.make_value.functions->make_value) (gdbarch, var,
2205                                                         var->u.make_value.data);
2206       break;
2207
2208     default:
2209       internal_error (__FILE__, __LINE__, _("bad kind"));
2210     }
2211
2212   /* Change the VALUE_LVAL to lval_internalvar so that future operations
2213      on this value go back to affect the original internal variable.
2214
2215      Do not do this for INTERNALVAR_MAKE_VALUE variables, as those have
2216      no underlying modifiable state in the internal variable.
2217
2218      Likewise, if the variable's value is a computed lvalue, we want
2219      references to it to produce another computed lvalue, where
2220      references and assignments actually operate through the
2221      computed value's functions.
2222
2223      This means that internal variables with computed values
2224      behave a little differently from other internal variables:
2225      assignments to them don't just replace the previous value
2226      altogether.  At the moment, this seems like the behavior we
2227      want.  */
2228
2229   if (var->kind != INTERNALVAR_MAKE_VALUE
2230       && val->lval != lval_computed)
2231     {
2232       VALUE_LVAL (val) = lval_internalvar;
2233       VALUE_INTERNALVAR (val) = var;
2234     }
2235
2236   return val;
2237 }
2238
2239 int
2240 get_internalvar_integer (struct internalvar *var, LONGEST *result)
2241 {
2242   if (var->kind == INTERNALVAR_INTEGER)
2243     {
2244       *result = var->u.integer.val;
2245       return 1;
2246     }
2247
2248   if (var->kind == INTERNALVAR_VALUE)
2249     {
2250       struct type *type = check_typedef (value_type (var->u.value));
2251
2252       if (type->code () == TYPE_CODE_INT)
2253         {
2254           *result = value_as_long (var->u.value);
2255           return 1;
2256         }
2257     }
2258
2259   return 0;
2260 }
2261
2262 static int
2263 get_internalvar_function (struct internalvar *var,
2264                           struct internal_function **result)
2265 {
2266   switch (var->kind)
2267     {
2268     case INTERNALVAR_FUNCTION:
2269       *result = var->u.fn.function;
2270       return 1;
2271
2272     default:
2273       return 0;
2274     }
2275 }
2276
2277 void
2278 set_internalvar_component (struct internalvar *var,
2279                            LONGEST offset, LONGEST bitpos,
2280                            LONGEST bitsize, struct value *newval)
2281 {
2282   gdb_byte *addr;
2283   struct gdbarch *arch;
2284   int unit_size;
2285
2286   switch (var->kind)
2287     {
2288     case INTERNALVAR_VALUE:
2289       addr = value_contents_writeable (var->u.value);
2290       arch = get_value_arch (var->u.value);
2291       unit_size = gdbarch_addressable_memory_unit_size (arch);
2292
2293       if (bitsize)
2294         modify_field (value_type (var->u.value), addr + offset,
2295                       value_as_long (newval), bitpos, bitsize);
2296       else
2297         memcpy (addr + offset * unit_size, value_contents (newval),
2298                 TYPE_LENGTH (value_type (newval)));
2299       break;
2300
2301     default:
2302       /* We can never get a component of any other kind.  */
2303       internal_error (__FILE__, __LINE__, _("set_internalvar_component"));
2304     }
2305 }
2306
2307 void
2308 set_internalvar (struct internalvar *var, struct value *val)
2309 {
2310   enum internalvar_kind new_kind;
2311   union internalvar_data new_data = { 0 };
2312
2313   if (var->kind == INTERNALVAR_FUNCTION && var->u.fn.canonical)
2314     error (_("Cannot overwrite convenience function %s"), var->name);
2315
2316   /* Prepare new contents.  */
2317   switch (check_typedef (value_type (val))->code ())
2318     {
2319     case TYPE_CODE_VOID:
2320       new_kind = INTERNALVAR_VOID;
2321       break;
2322
2323     case TYPE_CODE_INTERNAL_FUNCTION:
2324       gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2325       new_kind = INTERNALVAR_FUNCTION;
2326       get_internalvar_function (VALUE_INTERNALVAR (val),
2327                                 &new_data.fn.function);
2328       /* Copies created here are never canonical.  */
2329       break;
2330
2331     default:
2332       new_kind = INTERNALVAR_VALUE;
2333       struct value *copy = value_copy (val);
2334       copy->modifiable = 1;
2335
2336       /* Force the value to be fetched from the target now, to avoid problems
2337          later when this internalvar is referenced and the target is gone or
2338          has changed.  */
2339       if (value_lazy (copy))
2340         value_fetch_lazy (copy);
2341
2342       /* Release the value from the value chain to prevent it from being
2343          deleted by free_all_values.  From here on this function should not
2344          call error () until new_data is installed into the var->u to avoid
2345          leaking memory.  */
2346       new_data.value = release_value (copy).release ();
2347
2348       /* Internal variables which are created from values with a dynamic
2349          location don't need the location property of the origin anymore.
2350          The resolved dynamic location is used prior then any other address
2351          when accessing the value.
2352          If we keep it, we would still refer to the origin value.
2353          Remove the location property in case it exist.  */
2354       value_type (new_data.value)->remove_dyn_prop (DYN_PROP_DATA_LOCATION);
2355
2356       break;
2357     }
2358
2359   /* Clean up old contents.  */
2360   clear_internalvar (var);
2361
2362   /* Switch over.  */
2363   var->kind = new_kind;
2364   var->u = new_data;
2365   /* End code which must not call error().  */
2366 }
2367
2368 void
2369 set_internalvar_integer (struct internalvar *var, LONGEST l)
2370 {
2371   /* Clean up old contents.  */
2372   clear_internalvar (var);
2373
2374   var->kind = INTERNALVAR_INTEGER;
2375   var->u.integer.type = NULL;
2376   var->u.integer.val = l;
2377 }
2378
2379 void
2380 set_internalvar_string (struct internalvar *var, const char *string)
2381 {
2382   /* Clean up old contents.  */
2383   clear_internalvar (var);
2384
2385   var->kind = INTERNALVAR_STRING;
2386   var->u.string = xstrdup (string);
2387 }
2388
2389 static void
2390 set_internalvar_function (struct internalvar *var, struct internal_function *f)
2391 {
2392   /* Clean up old contents.  */
2393   clear_internalvar (var);
2394
2395   var->kind = INTERNALVAR_FUNCTION;
2396   var->u.fn.function = f;
2397   var->u.fn.canonical = 1;
2398   /* Variables installed here are always the canonical version.  */
2399 }
2400
2401 void
2402 clear_internalvar (struct internalvar *var)
2403 {
2404   /* Clean up old contents.  */
2405   switch (var->kind)
2406     {
2407     case INTERNALVAR_VALUE:
2408       value_decref (var->u.value);
2409       break;
2410
2411     case INTERNALVAR_STRING:
2412       xfree (var->u.string);
2413       break;
2414
2415     case INTERNALVAR_MAKE_VALUE:
2416       if (var->u.make_value.functions->destroy != NULL)
2417         var->u.make_value.functions->destroy (var->u.make_value.data);
2418       break;
2419
2420     default:
2421       break;
2422     }
2423
2424   /* Reset to void kind.  */
2425   var->kind = INTERNALVAR_VOID;
2426 }
2427
2428 const char *
2429 internalvar_name (const struct internalvar *var)
2430 {
2431   return var->name;
2432 }
2433
2434 static struct internal_function *
2435 create_internal_function (const char *name,
2436                           internal_function_fn handler, void *cookie)
2437 {
2438   struct internal_function *ifn = XNEW (struct internal_function);
2439
2440   ifn->name = xstrdup (name);
2441   ifn->handler = handler;
2442   ifn->cookie = cookie;
2443   return ifn;
2444 }
2445
2446 const char *
2447 value_internal_function_name (struct value *val)
2448 {
2449   struct internal_function *ifn;
2450   int result;
2451
2452   gdb_assert (VALUE_LVAL (val) == lval_internalvar);
2453   result = get_internalvar_function (VALUE_INTERNALVAR (val), &ifn);
2454   gdb_assert (result);
2455
2456   return ifn->name;
2457 }
2458
2459 struct value *
2460 call_internal_function (struct gdbarch *gdbarch,
2461                         const struct language_defn *language,
2462                         struct value *func, int argc, struct value **argv)
2463 {
2464   struct internal_function *ifn;
2465   int result;
2466
2467   gdb_assert (VALUE_LVAL (func) == lval_internalvar);
2468   result = get_internalvar_function (VALUE_INTERNALVAR (func), &ifn);
2469   gdb_assert (result);
2470
2471   return (*ifn->handler) (gdbarch, language, ifn->cookie, argc, argv);
2472 }
2473
2474 /* The 'function' command.  This does nothing -- it is just a
2475    placeholder to let "help function NAME" work.  This is also used as
2476    the implementation of the sub-command that is created when
2477    registering an internal function.  */
2478 static void
2479 function_command (const char *command, int from_tty)
2480 {
2481   /* Do nothing.  */
2482 }
2483
2484 /* Helper function that does the work for add_internal_function.  */
2485
2486 static struct cmd_list_element *
2487 do_add_internal_function (const char *name, const char *doc,
2488                           internal_function_fn handler, void *cookie)
2489 {
2490   struct internal_function *ifn;
2491   struct internalvar *var = lookup_internalvar (name);
2492
2493   ifn = create_internal_function (name, handler, cookie);
2494   set_internalvar_function (var, ifn);
2495
2496   return add_cmd (name, no_class, function_command, doc, &functionlist);
2497 }
2498
2499 /* See value.h.  */
2500
2501 void
2502 add_internal_function (const char *name, const char *doc,
2503                        internal_function_fn handler, void *cookie)
2504 {
2505   do_add_internal_function (name, doc, handler, cookie);
2506 }
2507
2508 /* See value.h.  */
2509
2510 void
2511 add_internal_function (gdb::unique_xmalloc_ptr<char> &&name,
2512                        gdb::unique_xmalloc_ptr<char> &&doc,
2513                        internal_function_fn handler, void *cookie)
2514 {
2515   struct cmd_list_element *cmd
2516     = do_add_internal_function (name.get (), doc.get (), handler, cookie);
2517   doc.release ();
2518   cmd->doc_allocated = 1;
2519   name.release ();
2520   cmd->name_allocated = 1;
2521 }
2522
2523 /* Update VALUE before discarding OBJFILE.  COPIED_TYPES is used to
2524    prevent cycles / duplicates.  */
2525
2526 void
2527 preserve_one_value (struct value *value, struct objfile *objfile,
2528                     htab_t copied_types)
2529 {
2530   if (value->type->objfile_owner () == objfile)
2531     value->type = copy_type_recursive (objfile, value->type, copied_types);
2532
2533   if (value->enclosing_type->objfile_owner () == objfile)
2534     value->enclosing_type = copy_type_recursive (objfile,
2535                                                  value->enclosing_type,
2536                                                  copied_types);
2537 }
2538
2539 /* Likewise for internal variable VAR.  */
2540
2541 static void
2542 preserve_one_internalvar (struct internalvar *var, struct objfile *objfile,
2543                           htab_t copied_types)
2544 {
2545   switch (var->kind)
2546     {
2547     case INTERNALVAR_INTEGER:
2548       if (var->u.integer.type
2549           && var->u.integer.type->objfile_owner () == objfile)
2550         var->u.integer.type
2551           = copy_type_recursive (objfile, var->u.integer.type, copied_types);
2552       break;
2553
2554     case INTERNALVAR_VALUE:
2555       preserve_one_value (var->u.value, objfile, copied_types);
2556       break;
2557     }
2558 }
2559
2560 /* Update the internal variables and value history when OBJFILE is
2561    discarded; we must copy the types out of the objfile.  New global types
2562    will be created for every convenience variable which currently points to
2563    this objfile's types, and the convenience variables will be adjusted to
2564    use the new global types.  */
2565
2566 void
2567 preserve_values (struct objfile *objfile)
2568 {
2569   struct internalvar *var;
2570
2571   /* Create the hash table.  We allocate on the objfile's obstack, since
2572      it is soon to be deleted.  */
2573   htab_up copied_types = create_copied_types_hash (objfile);
2574
2575   for (const value_ref_ptr &item : value_history)
2576     preserve_one_value (item.get (), objfile, copied_types.get ());
2577
2578   for (var = internalvars; var; var = var->next)
2579     preserve_one_internalvar (var, objfile, copied_types.get ());
2580
2581   preserve_ext_lang_values (objfile, copied_types.get ());
2582 }
2583
2584 static void
2585 show_convenience (const char *ignore, int from_tty)
2586 {
2587   struct gdbarch *gdbarch = get_current_arch ();
2588   struct internalvar *var;
2589   int varseen = 0;
2590   struct value_print_options opts;
2591
2592   get_user_print_options (&opts);
2593   for (var = internalvars; var; var = var->next)
2594     {
2595
2596       if (!varseen)
2597         {
2598           varseen = 1;
2599         }
2600       printf_filtered (("$%s = "), var->name);
2601
2602       try
2603         {
2604           struct value *val;
2605
2606           val = value_of_internalvar (gdbarch, var);
2607           value_print (val, gdb_stdout, &opts);
2608         }
2609       catch (const gdb_exception_error &ex)
2610         {
2611           fprintf_styled (gdb_stdout, metadata_style.style (),
2612                           _("<error: %s>"), ex.what ());
2613         }
2614
2615       printf_filtered (("\n"));
2616     }
2617   if (!varseen)
2618     {
2619       /* This text does not mention convenience functions on purpose.
2620          The user can't create them except via Python, and if Python support
2621          is installed this message will never be printed ($_streq will
2622          exist).  */
2623       printf_unfiltered (_("No debugger convenience variables now defined.\n"
2624                            "Convenience variables have "
2625                            "names starting with \"$\";\n"
2626                            "use \"set\" as in \"set "
2627                            "$foo = 5\" to define them.\n"));
2628     }
2629 }
2630 \f
2631
2632 /* See value.h.  */
2633
2634 struct value *
2635 value_from_xmethod (xmethod_worker_up &&worker)
2636 {
2637   struct value *v;
2638
2639   v = allocate_value (builtin_type (target_gdbarch ())->xmethod);
2640   v->lval = lval_xcallable;
2641   v->location.xm_worker = worker.release ();
2642   v->modifiable = 0;
2643
2644   return v;
2645 }
2646
2647 /* Return the type of the result of TYPE_CODE_XMETHOD value METHOD.  */
2648
2649 struct type *
2650 result_type_of_xmethod (struct value *method, gdb::array_view<value *> argv)
2651 {
2652   gdb_assert (value_type (method)->code () == TYPE_CODE_XMETHOD
2653               && method->lval == lval_xcallable && !argv.empty ());
2654
2655   return method->location.xm_worker->get_result_type (argv[0], argv.slice (1));
2656 }
2657
2658 /* Call the xmethod corresponding to the TYPE_CODE_XMETHOD value METHOD.  */
2659
2660 struct value *
2661 call_xmethod (struct value *method, gdb::array_view<value *> argv)
2662 {
2663   gdb_assert (value_type (method)->code () == TYPE_CODE_XMETHOD
2664               && method->lval == lval_xcallable && !argv.empty ());
2665
2666   return method->location.xm_worker->invoke (argv[0], argv.slice (1));
2667 }
2668 \f
2669 /* Extract a value as a C number (either long or double).
2670    Knows how to convert fixed values to double, or
2671    floating values to long.
2672    Does not deallocate the value.  */
2673
2674 LONGEST
2675 value_as_long (struct value *val)
2676 {
2677   /* This coerces arrays and functions, which is necessary (e.g.
2678      in disassemble_command).  It also dereferences references, which
2679      I suspect is the most logical thing to do.  */
2680   val = coerce_array (val);
2681   return unpack_long (value_type (val), value_contents (val));
2682 }
2683
2684 /* Extract a value as a C pointer.  Does not deallocate the value.
2685    Note that val's type may not actually be a pointer; value_as_long
2686    handles all the cases.  */
2687 CORE_ADDR
2688 value_as_address (struct value *val)
2689 {
2690   struct gdbarch *gdbarch = value_type (val)->arch ();
2691
2692   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
2693      whether we want this to be true eventually.  */
2694 #if 0
2695   /* gdbarch_addr_bits_remove is wrong if we are being called for a
2696      non-address (e.g. argument to "signal", "info break", etc.), or
2697      for pointers to char, in which the low bits *are* significant.  */
2698   return gdbarch_addr_bits_remove (gdbarch, value_as_long (val));
2699 #else
2700
2701   /* There are several targets (IA-64, PowerPC, and others) which
2702      don't represent pointers to functions as simply the address of
2703      the function's entry point.  For example, on the IA-64, a
2704      function pointer points to a two-word descriptor, generated by
2705      the linker, which contains the function's entry point, and the
2706      value the IA-64 "global pointer" register should have --- to
2707      support position-independent code.  The linker generates
2708      descriptors only for those functions whose addresses are taken.
2709
2710      On such targets, it's difficult for GDB to convert an arbitrary
2711      function address into a function pointer; it has to either find
2712      an existing descriptor for that function, or call malloc and
2713      build its own.  On some targets, it is impossible for GDB to
2714      build a descriptor at all: the descriptor must contain a jump
2715      instruction; data memory cannot be executed; and code memory
2716      cannot be modified.
2717
2718      Upon entry to this function, if VAL is a value of type `function'
2719      (that is, TYPE_CODE (VALUE_TYPE (val)) == TYPE_CODE_FUNC), then
2720      value_address (val) is the address of the function.  This is what
2721      you'll get if you evaluate an expression like `main'.  The call
2722      to COERCE_ARRAY below actually does all the usual unary
2723      conversions, which includes converting values of type `function'
2724      to `pointer to function'.  This is the challenging conversion
2725      discussed above.  Then, `unpack_long' will convert that pointer
2726      back into an address.
2727
2728      So, suppose the user types `disassemble foo' on an architecture
2729      with a strange function pointer representation, on which GDB
2730      cannot build its own descriptors, and suppose further that `foo'
2731      has no linker-built descriptor.  The address->pointer conversion
2732      will signal an error and prevent the command from running, even
2733      though the next step would have been to convert the pointer
2734      directly back into the same address.
2735
2736      The following shortcut avoids this whole mess.  If VAL is a
2737      function, just return its address directly.  */
2738   if (value_type (val)->code () == TYPE_CODE_FUNC
2739       || value_type (val)->code () == TYPE_CODE_METHOD)
2740     return value_address (val);
2741
2742   val = coerce_array (val);
2743
2744   /* Some architectures (e.g. Harvard), map instruction and data
2745      addresses onto a single large unified address space.  For
2746      instance: An architecture may consider a large integer in the
2747      range 0x10000000 .. 0x1000ffff to already represent a data
2748      addresses (hence not need a pointer to address conversion) while
2749      a small integer would still need to be converted integer to
2750      pointer to address.  Just assume such architectures handle all
2751      integer conversions in a single function.  */
2752
2753   /* JimB writes:
2754
2755      I think INTEGER_TO_ADDRESS is a good idea as proposed --- but we
2756      must admonish GDB hackers to make sure its behavior matches the
2757      compiler's, whenever possible.
2758
2759      In general, I think GDB should evaluate expressions the same way
2760      the compiler does.  When the user copies an expression out of
2761      their source code and hands it to a `print' command, they should
2762      get the same value the compiler would have computed.  Any
2763      deviation from this rule can cause major confusion and annoyance,
2764      and needs to be justified carefully.  In other words, GDB doesn't
2765      really have the freedom to do these conversions in clever and
2766      useful ways.
2767
2768      AndrewC pointed out that users aren't complaining about how GDB
2769      casts integers to pointers; they are complaining that they can't
2770      take an address from a disassembly listing and give it to `x/i'.
2771      This is certainly important.
2772
2773      Adding an architecture method like integer_to_address() certainly
2774      makes it possible for GDB to "get it right" in all circumstances
2775      --- the target has complete control over how things get done, so
2776      people can Do The Right Thing for their target without breaking
2777      anyone else.  The standard doesn't specify how integers get
2778      converted to pointers; usually, the ABI doesn't either, but
2779      ABI-specific code is a more reasonable place to handle it.  */
2780
2781   if (!value_type (val)->is_pointer_or_reference ()
2782       && gdbarch_integer_to_address_p (gdbarch))
2783     return gdbarch_integer_to_address (gdbarch, value_type (val),
2784                                        value_contents (val));
2785
2786   return unpack_long (value_type (val), value_contents (val));
2787 #endif
2788 }
2789 \f
2790 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2791    as a long, or as a double, assuming the raw data is described
2792    by type TYPE.  Knows how to convert different sizes of values
2793    and can convert between fixed and floating point.  We don't assume
2794    any alignment for the raw data.  Return value is in host byte order.
2795
2796    If you want functions and arrays to be coerced to pointers, and
2797    references to be dereferenced, call value_as_long() instead.
2798
2799    C++: It is assumed that the front-end has taken care of
2800    all matters concerning pointers to members.  A pointer
2801    to member which reaches here is considered to be equivalent
2802    to an INT (or some size).  After all, it is only an offset.  */
2803
2804 LONGEST
2805 unpack_long (struct type *type, const gdb_byte *valaddr)
2806 {
2807   if (is_fixed_point_type (type))
2808     type = type->fixed_point_type_base_type ();
2809
2810   enum bfd_endian byte_order = type_byte_order (type);
2811   enum type_code code = type->code ();
2812   int len = TYPE_LENGTH (type);
2813   int nosign = type->is_unsigned ();
2814
2815   switch (code)
2816     {
2817     case TYPE_CODE_TYPEDEF:
2818       return unpack_long (check_typedef (type), valaddr);
2819     case TYPE_CODE_ENUM:
2820     case TYPE_CODE_FLAGS:
2821     case TYPE_CODE_BOOL:
2822     case TYPE_CODE_INT:
2823     case TYPE_CODE_CHAR:
2824     case TYPE_CODE_RANGE:
2825     case TYPE_CODE_MEMBERPTR:
2826       {
2827         LONGEST result;
2828
2829         if (type->bit_size_differs_p ())
2830           {
2831             unsigned bit_off = type->bit_offset ();
2832             unsigned bit_size = type->bit_size ();
2833             if (bit_size == 0)
2834               {
2835                 /* unpack_bits_as_long doesn't handle this case the
2836                    way we'd like, so handle it here.  */
2837                 result = 0;
2838               }
2839             else
2840               result = unpack_bits_as_long (type, valaddr, bit_off, bit_size);
2841           }
2842         else
2843           {
2844             if (nosign)
2845               result = extract_unsigned_integer (valaddr, len, byte_order);
2846             else
2847               result = extract_signed_integer (valaddr, len, byte_order);
2848           }
2849         if (code == TYPE_CODE_RANGE)
2850           result += type->bounds ()->bias;
2851         return result;
2852       }
2853
2854     case TYPE_CODE_FLT:
2855     case TYPE_CODE_DECFLOAT:
2856       return target_float_to_longest (valaddr, type);
2857
2858     case TYPE_CODE_FIXED_POINT:
2859       {
2860         gdb_mpq vq;
2861         vq.read_fixed_point (gdb::make_array_view (valaddr, len),
2862                              byte_order, nosign,
2863                              type->fixed_point_scaling_factor ());
2864
2865         gdb_mpz vz;
2866         mpz_tdiv_q (vz.val, mpq_numref (vq.val), mpq_denref (vq.val));
2867         return vz.as_integer<LONGEST> ();
2868       }
2869
2870     case TYPE_CODE_PTR:
2871     case TYPE_CODE_REF:
2872     case TYPE_CODE_RVALUE_REF:
2873       /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
2874          whether we want this to be true eventually.  */
2875       return extract_typed_address (valaddr, type);
2876
2877     default:
2878       error (_("Value can't be converted to integer."));
2879     }
2880 }
2881
2882 /* Unpack raw data (copied from debugee, target byte order) at VALADDR
2883    as a CORE_ADDR, assuming the raw data is described by type TYPE.
2884    We don't assume any alignment for the raw data.  Return value is in
2885    host byte order.
2886
2887    If you want functions and arrays to be coerced to pointers, and
2888    references to be dereferenced, call value_as_address() instead.
2889
2890    C++: It is assumed that the front-end has taken care of
2891    all matters concerning pointers to members.  A pointer
2892    to member which reaches here is considered to be equivalent
2893    to an INT (or some size).  After all, it is only an offset.  */
2894
2895 CORE_ADDR
2896 unpack_pointer (struct type *type, const gdb_byte *valaddr)
2897 {
2898   /* Assume a CORE_ADDR can fit in a LONGEST (for now).  Not sure
2899      whether we want this to be true eventually.  */
2900   return unpack_long (type, valaddr);
2901 }
2902
2903 bool
2904 is_floating_value (struct value *val)
2905 {
2906   struct type *type = check_typedef (value_type (val));
2907
2908   if (is_floating_type (type))
2909     {
2910       if (!target_float_is_valid (value_contents (val), type))
2911         error (_("Invalid floating value found in program."));
2912       return true;
2913     }
2914
2915   return false;
2916 }
2917
2918 \f
2919 /* Get the value of the FIELDNO'th field (which must be static) of
2920    TYPE.  */
2921
2922 struct value *
2923 value_static_field (struct type *type, int fieldno)
2924 {
2925   struct value *retval;
2926
2927   switch (TYPE_FIELD_LOC_KIND (type, fieldno))
2928     {
2929     case FIELD_LOC_KIND_PHYSADDR:
2930       retval = value_at_lazy (type->field (fieldno).type (),
2931                               TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
2932       break;
2933     case FIELD_LOC_KIND_PHYSNAME:
2934     {
2935       const char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
2936       /* type->field (fieldno).name (); */
2937       struct block_symbol sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0);
2938
2939       if (sym.symbol == NULL)
2940         {
2941           /* With some compilers, e.g. HP aCC, static data members are
2942              reported as non-debuggable symbols.  */
2943           struct bound_minimal_symbol msym
2944             = lookup_minimal_symbol (phys_name, NULL, NULL);
2945           struct type *field_type = type->field (fieldno).type ();
2946
2947           if (!msym.minsym)
2948             retval = allocate_optimized_out_value (field_type);
2949           else
2950             retval = value_at_lazy (field_type, BMSYMBOL_VALUE_ADDRESS (msym));
2951         }
2952       else
2953         retval = value_of_variable (sym.symbol, sym.block);
2954       break;
2955     }
2956     default:
2957       gdb_assert_not_reached ("unexpected field location kind");
2958     }
2959
2960   return retval;
2961 }
2962
2963 /* Change the enclosing type of a value object VAL to NEW_ENCL_TYPE.
2964    You have to be careful here, since the size of the data area for the value
2965    is set by the length of the enclosing type.  So if NEW_ENCL_TYPE is bigger
2966    than the old enclosing type, you have to allocate more space for the
2967    data.  */
2968
2969 void
2970 set_value_enclosing_type (struct value *val, struct type *new_encl_type)
2971 {
2972   if (TYPE_LENGTH (new_encl_type) > TYPE_LENGTH (value_enclosing_type (val)))
2973     {
2974       check_type_length_before_alloc (new_encl_type);
2975       val->contents
2976         .reset ((gdb_byte *) xrealloc (val->contents.release (),
2977                                        TYPE_LENGTH (new_encl_type)));
2978     }
2979
2980   val->enclosing_type = new_encl_type;
2981 }
2982
2983 /* Given a value ARG1 (offset by OFFSET bytes)
2984    of a struct or union type ARG_TYPE,
2985    extract and return the value of one of its (non-static) fields.
2986    FIELDNO says which field.  */
2987
2988 struct value *
2989 value_primitive_field (struct value *arg1, LONGEST offset,
2990                        int fieldno, struct type *arg_type)
2991 {
2992   struct value *v;
2993   struct type *type;
2994   struct gdbarch *arch = get_value_arch (arg1);
2995   int unit_size = gdbarch_addressable_memory_unit_size (arch);
2996
2997   arg_type = check_typedef (arg_type);
2998   type = arg_type->field (fieldno).type ();
2999
3000   /* Call check_typedef on our type to make sure that, if TYPE
3001      is a TYPE_CODE_TYPEDEF, its length is set to the length
3002      of the target type instead of zero.  However, we do not
3003      replace the typedef type by the target type, because we want
3004      to keep the typedef in order to be able to print the type
3005      description correctly.  */
3006   check_typedef (type);
3007
3008   if (TYPE_FIELD_BITSIZE (arg_type, fieldno))
3009     {
3010       /* Handle packed fields.
3011
3012          Create a new value for the bitfield, with bitpos and bitsize
3013          set.  If possible, arrange offset and bitpos so that we can
3014          do a single aligned read of the size of the containing type.
3015          Otherwise, adjust offset to the byte containing the first
3016          bit.  Assume that the address, offset, and embedded offset
3017          are sufficiently aligned.  */
3018
3019       LONGEST bitpos = TYPE_FIELD_BITPOS (arg_type, fieldno);
3020       LONGEST container_bitsize = TYPE_LENGTH (type) * 8;
3021
3022       v = allocate_value_lazy (type);
3023       v->bitsize = TYPE_FIELD_BITSIZE (arg_type, fieldno);
3024       if ((bitpos % container_bitsize) + v->bitsize <= container_bitsize
3025           && TYPE_LENGTH (type) <= (int) sizeof (LONGEST))
3026         v->bitpos = bitpos % container_bitsize;
3027       else
3028         v->bitpos = bitpos % 8;
3029       v->offset = (value_embedded_offset (arg1)
3030                    + offset
3031                    + (bitpos - v->bitpos) / 8);
3032       set_value_parent (v, arg1);
3033       if (!value_lazy (arg1))
3034         value_fetch_lazy (v);
3035     }
3036   else if (fieldno < TYPE_N_BASECLASSES (arg_type))
3037     {
3038       /* This field is actually a base subobject, so preserve the
3039          entire object's contents for later references to virtual
3040          bases, etc.  */
3041       LONGEST boffset;
3042
3043       /* Lazy register values with offsets are not supported.  */
3044       if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
3045         value_fetch_lazy (arg1);
3046
3047       /* We special case virtual inheritance here because this
3048          requires access to the contents, which we would rather avoid
3049          for references to ordinary fields of unavailable values.  */
3050       if (BASETYPE_VIA_VIRTUAL (arg_type, fieldno))
3051         boffset = baseclass_offset (arg_type, fieldno,
3052                                     value_contents (arg1),
3053                                     value_embedded_offset (arg1),
3054                                     value_address (arg1),
3055                                     arg1);
3056       else
3057         boffset = TYPE_FIELD_BITPOS (arg_type, fieldno) / 8;
3058
3059       if (value_lazy (arg1))
3060         v = allocate_value_lazy (value_enclosing_type (arg1));
3061       else
3062         {
3063           v = allocate_value (value_enclosing_type (arg1));
3064           value_contents_copy_raw (v, 0, arg1, 0,
3065                                    TYPE_LENGTH (value_enclosing_type (arg1)));
3066         }
3067       v->type = type;
3068       v->offset = value_offset (arg1);
3069       v->embedded_offset = offset + value_embedded_offset (arg1) + boffset;
3070     }
3071   else if (NULL != TYPE_DATA_LOCATION (type))
3072     {
3073       /* Field is a dynamic data member.  */
3074
3075       gdb_assert (0 == offset);
3076       /* We expect an already resolved data location.  */
3077       gdb_assert (PROP_CONST == TYPE_DATA_LOCATION_KIND (type));
3078       /* For dynamic data types defer memory allocation
3079          until we actual access the value.  */
3080       v = allocate_value_lazy (type);
3081     }
3082   else
3083     {
3084       /* Plain old data member */
3085       offset += (TYPE_FIELD_BITPOS (arg_type, fieldno)
3086                  / (HOST_CHAR_BIT * unit_size));
3087
3088       /* Lazy register values with offsets are not supported.  */
3089       if (VALUE_LVAL (arg1) == lval_register && value_lazy (arg1))
3090         value_fetch_lazy (arg1);
3091
3092       if (value_lazy (arg1))
3093         v = allocate_value_lazy (type);
3094       else
3095         {
3096           v = allocate_value (type);
3097           value_contents_copy_raw (v, value_embedded_offset (v),
3098                                    arg1, value_embedded_offset (arg1) + offset,
3099                                    type_length_units (type));
3100         }
3101       v->offset = (value_offset (arg1) + offset
3102                    + value_embedded_offset (arg1));
3103     }
3104   set_value_component_location (v, arg1);
3105   return v;
3106 }
3107
3108 /* Given a value ARG1 of a struct or union type,
3109    extract and return the value of one of its (non-static) fields.
3110    FIELDNO says which field.  */
3111
3112 struct value *
3113 value_field (struct value *arg1, int fieldno)
3114 {
3115   return value_primitive_field (arg1, 0, fieldno, value_type (arg1));
3116 }
3117
3118 /* Return a non-virtual function as a value.
3119    F is the list of member functions which contains the desired method.
3120    J is an index into F which provides the desired method.
3121
3122    We only use the symbol for its address, so be happy with either a
3123    full symbol or a minimal symbol.  */
3124
3125 struct value *
3126 value_fn_field (struct value **arg1p, struct fn_field *f,
3127                 int j, struct type *type,
3128                 LONGEST offset)
3129 {
3130   struct value *v;
3131   struct type *ftype = TYPE_FN_FIELD_TYPE (f, j);
3132   const char *physname = TYPE_FN_FIELD_PHYSNAME (f, j);
3133   struct symbol *sym;
3134   struct bound_minimal_symbol msym;
3135
3136   sym = lookup_symbol (physname, 0, VAR_DOMAIN, 0).symbol;
3137   if (sym != NULL)
3138     {
3139       memset (&msym, 0, sizeof (msym));
3140     }
3141   else
3142     {
3143       gdb_assert (sym == NULL);
3144       msym = lookup_bound_minimal_symbol (physname);
3145       if (msym.minsym == NULL)
3146         return NULL;
3147     }
3148
3149   v = allocate_value (ftype);
3150   VALUE_LVAL (v) = lval_memory;
3151   if (sym)
3152     {
3153       set_value_address (v, BLOCK_ENTRY_PC (SYMBOL_BLOCK_VALUE (sym)));
3154     }
3155   else
3156     {
3157       /* The minimal symbol might point to a function descriptor;
3158          resolve it to the actual code address instead.  */
3159       struct objfile *objfile = msym.objfile;
3160       struct gdbarch *gdbarch = objfile->arch ();
3161
3162       set_value_address (v,
3163         gdbarch_convert_from_func_ptr_addr
3164            (gdbarch, BMSYMBOL_VALUE_ADDRESS (msym),
3165             current_inferior ()->top_target ()));
3166     }
3167
3168   if (arg1p)
3169     {
3170       if (type != value_type (*arg1p))
3171         *arg1p = value_ind (value_cast (lookup_pointer_type (type),
3172                                         value_addr (*arg1p)));
3173
3174       /* Move the `this' pointer according to the offset.
3175          VALUE_OFFSET (*arg1p) += offset; */
3176     }
3177
3178   return v;
3179 }
3180
3181 \f
3182
3183 /* See value.h.  */
3184
3185 LONGEST
3186 unpack_bits_as_long (struct type *field_type, const gdb_byte *valaddr,
3187                      LONGEST bitpos, LONGEST bitsize)
3188 {
3189   enum bfd_endian byte_order = type_byte_order (field_type);
3190   ULONGEST val;
3191   ULONGEST valmask;
3192   int lsbcount;
3193   LONGEST bytes_read;
3194   LONGEST read_offset;
3195
3196   /* Read the minimum number of bytes required; there may not be
3197      enough bytes to read an entire ULONGEST.  */
3198   field_type = check_typedef (field_type);
3199   if (bitsize)
3200     bytes_read = ((bitpos % 8) + bitsize + 7) / 8;
3201   else
3202     {
3203       bytes_read = TYPE_LENGTH (field_type);
3204       bitsize = 8 * bytes_read;
3205     }
3206
3207   read_offset = bitpos / 8;
3208
3209   val = extract_unsigned_integer (valaddr + read_offset,
3210                                   bytes_read, byte_order);
3211
3212   /* Extract bits.  See comment above.  */
3213
3214   if (byte_order == BFD_ENDIAN_BIG)
3215     lsbcount = (bytes_read * 8 - bitpos % 8 - bitsize);
3216   else
3217     lsbcount = (bitpos % 8);
3218   val >>= lsbcount;
3219
3220   /* If the field does not entirely fill a LONGEST, then zero the sign bits.
3221      If the field is signed, and is negative, then sign extend.  */
3222
3223   if (bitsize < 8 * (int) sizeof (val))
3224     {
3225       valmask = (((ULONGEST) 1) << bitsize) - 1;
3226       val &= valmask;
3227       if (!field_type->is_unsigned ())
3228         {
3229           if (val & (valmask ^ (valmask >> 1)))
3230             {
3231               val |= ~valmask;
3232             }
3233         }
3234     }
3235
3236   return val;
3237 }
3238
3239 /* Unpack a field FIELDNO of the specified TYPE, from the object at
3240    VALADDR + EMBEDDED_OFFSET.  VALADDR points to the contents of
3241    ORIGINAL_VALUE, which must not be NULL.  See
3242    unpack_value_bits_as_long for more details.  */
3243
3244 int
3245 unpack_value_field_as_long (struct type *type, const gdb_byte *valaddr,
3246                             LONGEST embedded_offset, int fieldno,
3247                             const struct value *val, LONGEST *result)
3248 {
3249   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
3250   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3251   struct type *field_type = type->field (fieldno).type ();
3252   int bit_offset;
3253
3254   gdb_assert (val != NULL);
3255
3256   bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
3257   if (value_bits_any_optimized_out (val, bit_offset, bitsize)
3258       || !value_bits_available (val, bit_offset, bitsize))
3259     return 0;
3260
3261   *result = unpack_bits_as_long (field_type, valaddr + embedded_offset,
3262                                  bitpos, bitsize);
3263   return 1;
3264 }
3265
3266 /* Unpack a field FIELDNO of the specified TYPE, from the anonymous
3267    object at VALADDR.  See unpack_bits_as_long for more details.  */
3268
3269 LONGEST
3270 unpack_field_as_long (struct type *type, const gdb_byte *valaddr, int fieldno)
3271 {
3272   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
3273   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3274   struct type *field_type = type->field (fieldno).type ();
3275
3276   return unpack_bits_as_long (field_type, valaddr, bitpos, bitsize);
3277 }
3278
3279 /* Unpack a bitfield of BITSIZE bits found at BITPOS in the object at
3280    VALADDR + EMBEDDEDOFFSET that has the type of DEST_VAL and store
3281    the contents in DEST_VAL, zero or sign extending if the type of
3282    DEST_VAL is wider than BITSIZE.  VALADDR points to the contents of
3283    VAL.  If the VAL's contents required to extract the bitfield from
3284    are unavailable/optimized out, DEST_VAL is correspondingly
3285    marked unavailable/optimized out.  */
3286
3287 void
3288 unpack_value_bitfield (struct value *dest_val,
3289                        LONGEST bitpos, LONGEST bitsize,
3290                        const gdb_byte *valaddr, LONGEST embedded_offset,
3291                        const struct value *val)
3292 {
3293   enum bfd_endian byte_order;
3294   int src_bit_offset;
3295   int dst_bit_offset;
3296   struct type *field_type = value_type (dest_val);
3297
3298   byte_order = type_byte_order (field_type);
3299
3300   /* First, unpack and sign extend the bitfield as if it was wholly
3301      valid.  Optimized out/unavailable bits are read as zero, but
3302      that's OK, as they'll end up marked below.  If the VAL is
3303      wholly-invalid we may have skipped allocating its contents,
3304      though.  See allocate_optimized_out_value.  */
3305   if (valaddr != NULL)
3306     {
3307       LONGEST num;
3308
3309       num = unpack_bits_as_long (field_type, valaddr + embedded_offset,
3310                                  bitpos, bitsize);
3311       store_signed_integer (value_contents_raw (dest_val),
3312                             TYPE_LENGTH (field_type), byte_order, num);
3313     }
3314
3315   /* Now copy the optimized out / unavailability ranges to the right
3316      bits.  */
3317   src_bit_offset = embedded_offset * TARGET_CHAR_BIT + bitpos;
3318   if (byte_order == BFD_ENDIAN_BIG)
3319     dst_bit_offset = TYPE_LENGTH (field_type) * TARGET_CHAR_BIT - bitsize;
3320   else
3321     dst_bit_offset = 0;
3322   value_ranges_copy_adjusted (dest_val, dst_bit_offset,
3323                               val, src_bit_offset, bitsize);
3324 }
3325
3326 /* Return a new value with type TYPE, which is FIELDNO field of the
3327    object at VALADDR + EMBEDDEDOFFSET.  VALADDR points to the contents
3328    of VAL.  If the VAL's contents required to extract the bitfield
3329    from are unavailable/optimized out, the new value is
3330    correspondingly marked unavailable/optimized out.  */
3331
3332 struct value *
3333 value_field_bitfield (struct type *type, int fieldno,
3334                       const gdb_byte *valaddr,
3335                       LONGEST embedded_offset, const struct value *val)
3336 {
3337   int bitpos = TYPE_FIELD_BITPOS (type, fieldno);
3338   int bitsize = TYPE_FIELD_BITSIZE (type, fieldno);
3339   struct value *res_val = allocate_value (type->field (fieldno).type ());
3340
3341   unpack_value_bitfield (res_val, bitpos, bitsize,
3342                          valaddr, embedded_offset, val);
3343
3344   return res_val;
3345 }
3346
3347 /* Modify the value of a bitfield.  ADDR points to a block of memory in
3348    target byte order; the bitfield starts in the byte pointed to.  FIELDVAL
3349    is the desired value of the field, in host byte order.  BITPOS and BITSIZE
3350    indicate which bits (in target bit order) comprise the bitfield.
3351    Requires 0 < BITSIZE <= lbits, 0 <= BITPOS % 8 + BITSIZE <= lbits, and
3352    0 <= BITPOS, where lbits is the size of a LONGEST in bits.  */
3353
3354 void
3355 modify_field (struct type *type, gdb_byte *addr,
3356               LONGEST fieldval, LONGEST bitpos, LONGEST bitsize)
3357 {
3358   enum bfd_endian byte_order = type_byte_order (type);
3359   ULONGEST oword;
3360   ULONGEST mask = (ULONGEST) -1 >> (8 * sizeof (ULONGEST) - bitsize);
3361   LONGEST bytesize;
3362
3363   /* Normalize BITPOS.  */
3364   addr += bitpos / 8;
3365   bitpos %= 8;
3366
3367   /* If a negative fieldval fits in the field in question, chop
3368      off the sign extension bits.  */
3369   if ((~fieldval & ~(mask >> 1)) == 0)
3370     fieldval &= mask;
3371
3372   /* Warn if value is too big to fit in the field in question.  */
3373   if (0 != (fieldval & ~mask))
3374     {
3375       /* FIXME: would like to include fieldval in the message, but
3376          we don't have a sprintf_longest.  */
3377       warning (_("Value does not fit in %s bits."), plongest (bitsize));
3378
3379       /* Truncate it, otherwise adjoining fields may be corrupted.  */
3380       fieldval &= mask;
3381     }
3382
3383   /* Ensure no bytes outside of the modified ones get accessed as it may cause
3384      false valgrind reports.  */
3385
3386   bytesize = (bitpos + bitsize + 7) / 8;
3387   oword = extract_unsigned_integer (addr, bytesize, byte_order);
3388
3389   /* Shifting for bit field depends on endianness of the target machine.  */
3390   if (byte_order == BFD_ENDIAN_BIG)
3391     bitpos = bytesize * 8 - bitpos - bitsize;
3392
3393   oword &= ~(mask << bitpos);
3394   oword |= fieldval << bitpos;
3395
3396   store_unsigned_integer (addr, bytesize, byte_order, oword);
3397 }
3398 \f
3399 /* Pack NUM into BUF using a target format of TYPE.  */
3400
3401 void
3402 pack_long (gdb_byte *buf, struct type *type, LONGEST num)
3403 {
3404   enum bfd_endian byte_order = type_byte_order (type);
3405   LONGEST len;
3406
3407   type = check_typedef (type);
3408   len = TYPE_LENGTH (type);
3409
3410   switch (type->code ())
3411     {
3412     case TYPE_CODE_RANGE:
3413       num -= type->bounds ()->bias;
3414       /* Fall through.  */
3415     case TYPE_CODE_INT:
3416     case TYPE_CODE_CHAR:
3417     case TYPE_CODE_ENUM:
3418     case TYPE_CODE_FLAGS:
3419     case TYPE_CODE_BOOL:
3420     case TYPE_CODE_MEMBERPTR:
3421       if (type->bit_size_differs_p ())
3422         {
3423           unsigned bit_off = type->bit_offset ();
3424           unsigned bit_size = type->bit_size ();
3425           num &= ((ULONGEST) 1 << bit_size) - 1;
3426           num <<= bit_off;
3427         }
3428       store_signed_integer (buf, len, byte_order, num);
3429       break;
3430
3431     case TYPE_CODE_REF:
3432     case TYPE_CODE_RVALUE_REF:
3433     case TYPE_CODE_PTR:
3434       store_typed_address (buf, type, (CORE_ADDR) num);
3435       break;
3436
3437     case TYPE_CODE_FLT:
3438     case TYPE_CODE_DECFLOAT:
3439       target_float_from_longest (buf, type, num);
3440       break;
3441
3442     default:
3443       error (_("Unexpected type (%d) encountered for integer constant."),
3444              type->code ());
3445     }
3446 }
3447
3448
3449 /* Pack NUM into BUF using a target format of TYPE.  */
3450
3451 static void
3452 pack_unsigned_long (gdb_byte *buf, struct type *type, ULONGEST num)
3453 {
3454   LONGEST len;
3455   enum bfd_endian byte_order;
3456
3457   type = check_typedef (type);
3458   len = TYPE_LENGTH (type);
3459   byte_order = type_byte_order (type);
3460
3461   switch (type->code ())
3462     {
3463     case TYPE_CODE_INT:
3464     case TYPE_CODE_CHAR:
3465     case TYPE_CODE_ENUM:
3466     case TYPE_CODE_FLAGS:
3467     case TYPE_CODE_BOOL:
3468     case TYPE_CODE_RANGE:
3469     case TYPE_CODE_MEMBERPTR:
3470       if (type->bit_size_differs_p ())
3471         {
3472           unsigned bit_off = type->bit_offset ();
3473           unsigned bit_size = type->bit_size ();
3474           num &= ((ULONGEST) 1 << bit_size) - 1;
3475           num <<= bit_off;
3476         }
3477       store_unsigned_integer (buf, len, byte_order, num);
3478       break;
3479
3480     case TYPE_CODE_REF:
3481     case TYPE_CODE_RVALUE_REF:
3482     case TYPE_CODE_PTR:
3483       store_typed_address (buf, type, (CORE_ADDR) num);
3484       break;
3485
3486     case TYPE_CODE_FLT:
3487     case TYPE_CODE_DECFLOAT:
3488       target_float_from_ulongest (buf, type, num);
3489       break;
3490
3491     default:
3492       error (_("Unexpected type (%d) encountered "
3493                "for unsigned integer constant."),
3494              type->code ());
3495     }
3496 }
3497
3498
3499 /* Convert C numbers into newly allocated values.  */
3500
3501 struct value *
3502 value_from_longest (struct type *type, LONGEST num)
3503 {
3504   struct value *val = allocate_value (type);
3505
3506   pack_long (value_contents_raw (val), type, num);
3507   return val;
3508 }
3509
3510
3511 /* Convert C unsigned numbers into newly allocated values.  */
3512
3513 struct value *
3514 value_from_ulongest (struct type *type, ULONGEST num)
3515 {
3516   struct value *val = allocate_value (type);
3517
3518   pack_unsigned_long (value_contents_raw (val), type, num);
3519
3520   return val;
3521 }
3522
3523
3524 /* Create a value representing a pointer of type TYPE to the address
3525    ADDR.  */
3526
3527 struct value *
3528 value_from_pointer (struct type *type, CORE_ADDR addr)
3529 {
3530   struct value *val = allocate_value (type);
3531
3532   store_typed_address (value_contents_raw (val),
3533                        check_typedef (type), addr);
3534   return val;
3535 }
3536
3537 /* Create and return a value object of TYPE containing the value D.  The
3538    TYPE must be of TYPE_CODE_FLT, and must be large enough to hold D once
3539    it is converted to target format.  */
3540
3541 struct value *
3542 value_from_host_double (struct type *type, double d)
3543 {
3544   struct value *value = allocate_value (type);
3545   gdb_assert (type->code () == TYPE_CODE_FLT);
3546   target_float_from_host_double (value_contents_raw (value),
3547                                  value_type (value), d);
3548   return value;
3549 }
3550
3551 /* Create a value of type TYPE whose contents come from VALADDR, if it
3552    is non-null, and whose memory address (in the inferior) is
3553    ADDRESS.  The type of the created value may differ from the passed
3554    type TYPE.  Make sure to retrieve values new type after this call.
3555    Note that TYPE is not passed through resolve_dynamic_type; this is
3556    a special API intended for use only by Ada.  */
3557
3558 struct value *
3559 value_from_contents_and_address_unresolved (struct type *type,
3560                                             const gdb_byte *valaddr,
3561                                             CORE_ADDR address)
3562 {
3563   struct value *v;
3564
3565   if (valaddr == NULL)
3566     v = allocate_value_lazy (type);
3567   else
3568     v = value_from_contents (type, valaddr);
3569   VALUE_LVAL (v) = lval_memory;
3570   set_value_address (v, address);
3571   return v;
3572 }
3573
3574 /* Create a value of type TYPE whose contents come from VALADDR, if it
3575    is non-null, and whose memory address (in the inferior) is
3576    ADDRESS.  The type of the created value may differ from the passed
3577    type TYPE.  Make sure to retrieve values new type after this call.  */
3578
3579 struct value *
3580 value_from_contents_and_address (struct type *type,
3581                                  const gdb_byte *valaddr,
3582                                  CORE_ADDR address)
3583 {
3584   gdb::array_view<const gdb_byte> view;
3585   if (valaddr != nullptr)
3586     view = gdb::make_array_view (valaddr, TYPE_LENGTH (type));
3587   struct type *resolved_type = resolve_dynamic_type (type, view, address);
3588   struct type *resolved_type_no_typedef = check_typedef (resolved_type);
3589   struct value *v;
3590
3591   if (valaddr == NULL)
3592     v = allocate_value_lazy (resolved_type);
3593   else
3594     v = value_from_contents (resolved_type, valaddr);
3595   if (TYPE_DATA_LOCATION (resolved_type_no_typedef) != NULL
3596       && TYPE_DATA_LOCATION_KIND (resolved_type_no_typedef) == PROP_CONST)
3597     address = TYPE_DATA_LOCATION_ADDR (resolved_type_no_typedef);
3598   VALUE_LVAL (v) = lval_memory;
3599   set_value_address (v, address);
3600   return v;
3601 }
3602
3603 /* Create a value of type TYPE holding the contents CONTENTS.
3604    The new value is `not_lval'.  */
3605
3606 struct value *
3607 value_from_contents (struct type *type, const gdb_byte *contents)
3608 {
3609   struct value *result;
3610
3611   result = allocate_value (type);
3612   memcpy (value_contents_raw (result), contents, TYPE_LENGTH (type));
3613   return result;
3614 }
3615
3616 /* Extract a value from the history file.  Input will be of the form
3617    $digits or $$digits.  See block comment above 'write_dollar_variable'
3618    for details.  */
3619
3620 struct value *
3621 value_from_history_ref (const char *h, const char **endp)
3622 {
3623   int index, len;
3624
3625   if (h[0] == '$')
3626     len = 1;
3627   else
3628     return NULL;
3629
3630   if (h[1] == '$')
3631     len = 2;
3632
3633   /* Find length of numeral string.  */
3634   for (; isdigit (h[len]); len++)
3635     ;
3636
3637   /* Make sure numeral string is not part of an identifier.  */
3638   if (h[len] == '_' || isalpha (h[len]))
3639     return NULL;
3640
3641   /* Now collect the index value.  */
3642   if (h[1] == '$')
3643     {
3644       if (len == 2)
3645         {
3646           /* For some bizarre reason, "$$" is equivalent to "$$1", 
3647              rather than to "$$0" as it ought to be!  */
3648           index = -1;
3649           *endp += len;
3650         }
3651       else
3652         {
3653           char *local_end;
3654
3655           index = -strtol (&h[2], &local_end, 10);
3656           *endp = local_end;
3657         }
3658     }
3659   else
3660     {
3661       if (len == 1)
3662         {
3663           /* "$" is equivalent to "$0".  */
3664           index = 0;
3665           *endp += len;
3666         }
3667       else
3668         {
3669           char *local_end;
3670
3671           index = strtol (&h[1], &local_end, 10);
3672           *endp = local_end;
3673         }
3674     }
3675
3676   return access_value_history (index);
3677 }
3678
3679 /* Get the component value (offset by OFFSET bytes) of a struct or
3680    union WHOLE.  Component's type is TYPE.  */
3681
3682 struct value *
3683 value_from_component (struct value *whole, struct type *type, LONGEST offset)
3684 {
3685   struct value *v;
3686
3687   if (VALUE_LVAL (whole) == lval_memory && value_lazy (whole))
3688     v = allocate_value_lazy (type);
3689   else
3690     {
3691       v = allocate_value (type);
3692       value_contents_copy (v, value_embedded_offset (v),
3693                            whole, value_embedded_offset (whole) + offset,
3694                            type_length_units (type));
3695     }
3696   v->offset = value_offset (whole) + offset + value_embedded_offset (whole);
3697   set_value_component_location (v, whole);
3698
3699   return v;
3700 }
3701
3702 struct value *
3703 coerce_ref_if_computed (const struct value *arg)
3704 {
3705   const struct lval_funcs *funcs;
3706
3707   if (!TYPE_IS_REFERENCE (check_typedef (value_type (arg))))
3708     return NULL;
3709
3710   if (value_lval_const (arg) != lval_computed)
3711     return NULL;
3712
3713   funcs = value_computed_funcs (arg);
3714   if (funcs->coerce_ref == NULL)
3715     return NULL;
3716
3717   return funcs->coerce_ref (arg);
3718 }
3719
3720 /* Look at value.h for description.  */
3721
3722 struct value *
3723 readjust_indirect_value_type (struct value *value, struct type *enc_type,
3724                               const struct type *original_type,
3725                               struct value *original_value,
3726                               CORE_ADDR original_value_address)
3727 {
3728   gdb_assert (original_type->is_pointer_or_reference ());
3729
3730   struct type *original_target_type = TYPE_TARGET_TYPE (original_type);
3731   gdb::array_view<const gdb_byte> view;
3732   struct type *resolved_original_target_type
3733     = resolve_dynamic_type (original_target_type, view,
3734                             original_value_address);
3735
3736   /* Re-adjust type.  */
3737   deprecated_set_value_type (value, resolved_original_target_type);
3738
3739   /* Add embedding info.  */
3740   set_value_enclosing_type (value, enc_type);
3741   set_value_embedded_offset (value, value_pointed_to_offset (original_value));
3742
3743   /* We may be pointing to an object of some derived type.  */
3744   return value_full_object (value, NULL, 0, 0, 0);
3745 }
3746
3747 struct value *
3748 coerce_ref (struct value *arg)
3749 {
3750   struct type *value_type_arg_tmp = check_typedef (value_type (arg));
3751   struct value *retval;
3752   struct type *enc_type;
3753
3754   retval = coerce_ref_if_computed (arg);
3755   if (retval)
3756     return retval;
3757
3758   if (!TYPE_IS_REFERENCE (value_type_arg_tmp))
3759     return arg;
3760
3761   enc_type = check_typedef (value_enclosing_type (arg));
3762   enc_type = TYPE_TARGET_TYPE (enc_type);
3763
3764   CORE_ADDR addr = unpack_pointer (value_type (arg), value_contents (arg));
3765   retval = value_at_lazy (enc_type, addr);
3766   enc_type = value_type (retval);
3767   return readjust_indirect_value_type (retval, enc_type, value_type_arg_tmp,
3768                                        arg, addr);
3769 }
3770
3771 struct value *
3772 coerce_array (struct value *arg)
3773 {
3774   struct type *type;
3775
3776   arg = coerce_ref (arg);
3777   type = check_typedef (value_type (arg));
3778
3779   switch (type->code ())
3780     {
3781     case TYPE_CODE_ARRAY:
3782       if (!type->is_vector () && current_language->c_style_arrays_p ())
3783         arg = value_coerce_array (arg);
3784       break;
3785     case TYPE_CODE_FUNC:
3786       arg = value_coerce_function (arg);
3787       break;
3788     }
3789   return arg;
3790 }
3791 \f
3792
3793 /* Return the return value convention that will be used for the
3794    specified type.  */
3795
3796 enum return_value_convention
3797 struct_return_convention (struct gdbarch *gdbarch,
3798                           struct value *function, struct type *value_type)
3799 {
3800   enum type_code code = value_type->code ();
3801
3802   if (code == TYPE_CODE_ERROR)
3803     error (_("Function return type unknown."));
3804
3805   /* Probe the architecture for the return-value convention.  */
3806   return gdbarch_return_value (gdbarch, function, value_type,
3807                                NULL, NULL, NULL);
3808 }
3809
3810 /* Return true if the function returning the specified type is using
3811    the convention of returning structures in memory (passing in the
3812    address as a hidden first parameter).  */
3813
3814 int
3815 using_struct_return (struct gdbarch *gdbarch,
3816                      struct value *function, struct type *value_type)
3817 {
3818   if (value_type->code () == TYPE_CODE_VOID)
3819     /* A void return value is never in memory.  See also corresponding
3820        code in "print_return_value".  */
3821     return 0;
3822
3823   return (struct_return_convention (gdbarch, function, value_type)
3824           != RETURN_VALUE_REGISTER_CONVENTION);
3825 }
3826
3827 /* Set the initialized field in a value struct.  */
3828
3829 void
3830 set_value_initialized (struct value *val, int status)
3831 {
3832   val->initialized = status;
3833 }
3834
3835 /* Return the initialized field in a value struct.  */
3836
3837 int
3838 value_initialized (const struct value *val)
3839 {
3840   return val->initialized;
3841 }
3842
3843 /* Helper for value_fetch_lazy when the value is a bitfield.  */
3844
3845 static void
3846 value_fetch_lazy_bitfield (struct value *val)
3847 {
3848   gdb_assert (value_bitsize (val) != 0);
3849
3850   /* To read a lazy bitfield, read the entire enclosing value.  This
3851      prevents reading the same block of (possibly volatile) memory once
3852      per bitfield.  It would be even better to read only the containing
3853      word, but we have no way to record that just specific bits of a
3854      value have been fetched.  */
3855   struct value *parent = value_parent (val);
3856
3857   if (value_lazy (parent))
3858     value_fetch_lazy (parent);
3859
3860   unpack_value_bitfield (val, value_bitpos (val), value_bitsize (val),
3861                          value_contents_for_printing (parent),
3862                          value_offset (val), parent);
3863 }
3864
3865 /* Helper for value_fetch_lazy when the value is in memory.  */
3866
3867 static void
3868 value_fetch_lazy_memory (struct value *val)
3869 {
3870   gdb_assert (VALUE_LVAL (val) == lval_memory);
3871
3872   CORE_ADDR addr = value_address (val);
3873   struct type *type = check_typedef (value_enclosing_type (val));
3874
3875   if (TYPE_LENGTH (type))
3876       read_value_memory (val, 0, value_stack (val),
3877                          addr, value_contents_all_raw (val),
3878                          type_length_units (type));
3879 }
3880
3881 /* Helper for value_fetch_lazy when the value is in a register.  */
3882
3883 static void
3884 value_fetch_lazy_register (struct value *val)
3885 {
3886   struct frame_info *next_frame;
3887   int regnum;
3888   struct type *type = check_typedef (value_type (val));
3889   struct value *new_val = val, *mark = value_mark ();
3890
3891   /* Offsets are not supported here; lazy register values must
3892      refer to the entire register.  */
3893   gdb_assert (value_offset (val) == 0);
3894
3895   while (VALUE_LVAL (new_val) == lval_register && value_lazy (new_val))
3896     {
3897       struct frame_id next_frame_id = VALUE_NEXT_FRAME_ID (new_val);
3898
3899       next_frame = frame_find_by_id (next_frame_id);
3900       regnum = VALUE_REGNUM (new_val);
3901
3902       gdb_assert (next_frame != NULL);
3903
3904       /* Convertible register routines are used for multi-register
3905          values and for interpretation in different types
3906          (e.g. float or int from a double register).  Lazy
3907          register values should have the register's natural type,
3908          so they do not apply.  */
3909       gdb_assert (!gdbarch_convert_register_p (get_frame_arch (next_frame),
3910                                                regnum, type));
3911
3912       /* FRAME was obtained, above, via VALUE_NEXT_FRAME_ID.
3913          Since a "->next" operation was performed when setting
3914          this field, we do not need to perform a "next" operation
3915          again when unwinding the register.  That's why
3916          frame_unwind_register_value() is called here instead of
3917          get_frame_register_value().  */
3918       new_val = frame_unwind_register_value (next_frame, regnum);
3919
3920       /* If we get another lazy lval_register value, it means the
3921          register is found by reading it from NEXT_FRAME's next frame.
3922          frame_unwind_register_value should never return a value with
3923          the frame id pointing to NEXT_FRAME.  If it does, it means we
3924          either have two consecutive frames with the same frame id
3925          in the frame chain, or some code is trying to unwind
3926          behind get_prev_frame's back (e.g., a frame unwind
3927          sniffer trying to unwind), bypassing its validations.  In
3928          any case, it should always be an internal error to end up
3929          in this situation.  */
3930       if (VALUE_LVAL (new_val) == lval_register
3931           && value_lazy (new_val)
3932           && frame_id_eq (VALUE_NEXT_FRAME_ID (new_val), next_frame_id))
3933         internal_error (__FILE__, __LINE__,
3934                         _("infinite loop while fetching a register"));
3935     }
3936
3937   /* If it's still lazy (for instance, a saved register on the
3938      stack), fetch it.  */
3939   if (value_lazy (new_val))
3940     value_fetch_lazy (new_val);
3941
3942   /* Copy the contents and the unavailability/optimized-out
3943      meta-data from NEW_VAL to VAL.  */
3944   set_value_lazy (val, 0);
3945   value_contents_copy (val, value_embedded_offset (val),
3946                        new_val, value_embedded_offset (new_val),
3947                        type_length_units (type));
3948
3949   if (frame_debug)
3950     {
3951       struct gdbarch *gdbarch;
3952       struct frame_info *frame;
3953       frame = frame_find_by_id (VALUE_NEXT_FRAME_ID (val));
3954       frame = get_prev_frame_always (frame);
3955       regnum = VALUE_REGNUM (val);
3956       gdbarch = get_frame_arch (frame);
3957
3958       string_file debug_file;
3959       fprintf_unfiltered (&debug_file,
3960                           "(frame=%d, regnum=%d(%s), ...) ",
3961                           frame_relative_level (frame), regnum,
3962                           user_reg_map_regnum_to_name (gdbarch, regnum));
3963
3964       fprintf_unfiltered (&debug_file, "->");
3965       if (value_optimized_out (new_val))
3966         {
3967           fprintf_unfiltered (&debug_file, " ");
3968           val_print_optimized_out (new_val, &debug_file);
3969         }
3970       else
3971         {
3972           int i;
3973           const gdb_byte *buf = value_contents (new_val);
3974
3975           if (VALUE_LVAL (new_val) == lval_register)
3976             fprintf_unfiltered (&debug_file, " register=%d",
3977                                 VALUE_REGNUM (new_val));
3978           else if (VALUE_LVAL (new_val) == lval_memory)
3979             fprintf_unfiltered (&debug_file, " address=%s",
3980                                 paddress (gdbarch,
3981                                           value_address (new_val)));
3982           else
3983             fprintf_unfiltered (&debug_file, " computed");
3984
3985           fprintf_unfiltered (&debug_file, " bytes=");
3986           fprintf_unfiltered (&debug_file, "[");
3987           for (i = 0; i < register_size (gdbarch, regnum); i++)
3988             fprintf_unfiltered (&debug_file, "%02x", buf[i]);
3989           fprintf_unfiltered (&debug_file, "]");
3990         }
3991
3992       frame_debug_printf ("%s", debug_file.c_str ());
3993     }
3994
3995   /* Dispose of the intermediate values.  This prevents
3996      watchpoints from trying to watch the saved frame pointer.  */
3997   value_free_to_mark (mark);
3998 }
3999
4000 /* Load the actual content of a lazy value.  Fetch the data from the
4001    user's process and clear the lazy flag to indicate that the data in
4002    the buffer is valid.
4003
4004    If the value is zero-length, we avoid calling read_memory, which
4005    would abort.  We mark the value as fetched anyway -- all 0 bytes of
4006    it.  */
4007
4008 void
4009 value_fetch_lazy (struct value *val)
4010 {
4011   gdb_assert (value_lazy (val));
4012   allocate_value_contents (val);
4013   /* A value is either lazy, or fully fetched.  The
4014      availability/validity is only established as we try to fetch a
4015      value.  */
4016   gdb_assert (val->optimized_out.empty ());
4017   gdb_assert (val->unavailable.empty ());
4018   if (value_bitsize (val))
4019     value_fetch_lazy_bitfield (val);
4020   else if (VALUE_LVAL (val) == lval_memory)
4021     value_fetch_lazy_memory (val);
4022   else if (VALUE_LVAL (val) == lval_register)
4023     value_fetch_lazy_register (val);
4024   else if (VALUE_LVAL (val) == lval_computed
4025            && value_computed_funcs (val)->read != NULL)
4026     value_computed_funcs (val)->read (val);
4027   else
4028     internal_error (__FILE__, __LINE__, _("Unexpected lazy value type."));
4029
4030   set_value_lazy (val, 0);
4031 }
4032
4033 /* Implementation of the convenience function $_isvoid.  */
4034
4035 static struct value *
4036 isvoid_internal_fn (struct gdbarch *gdbarch,
4037                     const struct language_defn *language,
4038                     void *cookie, int argc, struct value **argv)
4039 {
4040   int ret;
4041
4042   if (argc != 1)
4043     error (_("You must provide one argument for $_isvoid."));
4044
4045   ret = value_type (argv[0])->code () == TYPE_CODE_VOID;
4046
4047   return value_from_longest (builtin_type (gdbarch)->builtin_int, ret);
4048 }
4049
4050 /* Implementation of the convenience function $_creal.  Extracts the
4051    real part from a complex number.  */
4052
4053 static struct value *
4054 creal_internal_fn (struct gdbarch *gdbarch,
4055                    const struct language_defn *language,
4056                    void *cookie, int argc, struct value **argv)
4057 {
4058   if (argc != 1)
4059     error (_("You must provide one argument for $_creal."));
4060
4061   value *cval = argv[0];
4062   type *ctype = check_typedef (value_type (cval));
4063   if (ctype->code () != TYPE_CODE_COMPLEX)
4064     error (_("expected a complex number"));
4065   return value_real_part (cval);
4066 }
4067
4068 /* Implementation of the convenience function $_cimag.  Extracts the
4069    imaginary part from a complex number.  */
4070
4071 static struct value *
4072 cimag_internal_fn (struct gdbarch *gdbarch,
4073                    const struct language_defn *language,
4074                    void *cookie, int argc,
4075                    struct value **argv)
4076 {
4077   if (argc != 1)
4078     error (_("You must provide one argument for $_cimag."));
4079
4080   value *cval = argv[0];
4081   type *ctype = check_typedef (value_type (cval));
4082   if (ctype->code () != TYPE_CODE_COMPLEX)
4083     error (_("expected a complex number"));
4084   return value_imaginary_part (cval);
4085 }
4086
4087 #if GDB_SELF_TEST
4088 namespace selftests
4089 {
4090
4091 /* Test the ranges_contain function.  */
4092
4093 static void
4094 test_ranges_contain ()
4095 {
4096   std::vector<range> ranges;
4097   range r;
4098
4099   /* [10, 14] */
4100   r.offset = 10;
4101   r.length = 5;
4102   ranges.push_back (r);
4103
4104   /* [20, 24] */
4105   r.offset = 20;
4106   r.length = 5;
4107   ranges.push_back (r);
4108
4109   /* [2, 6] */
4110   SELF_CHECK (!ranges_contain (ranges, 2, 5));
4111   /* [9, 13] */
4112   SELF_CHECK (ranges_contain (ranges, 9, 5));
4113   /* [10, 11] */
4114   SELF_CHECK (ranges_contain (ranges, 10, 2));
4115   /* [10, 14] */
4116   SELF_CHECK (ranges_contain (ranges, 10, 5));
4117   /* [13, 18] */
4118   SELF_CHECK (ranges_contain (ranges, 13, 6));
4119   /* [14, 18] */
4120   SELF_CHECK (ranges_contain (ranges, 14, 5));
4121   /* [15, 18] */
4122   SELF_CHECK (!ranges_contain (ranges, 15, 4));
4123   /* [16, 19] */
4124   SELF_CHECK (!ranges_contain (ranges, 16, 4));
4125   /* [16, 21] */
4126   SELF_CHECK (ranges_contain (ranges, 16, 6));
4127   /* [21, 21] */
4128   SELF_CHECK (ranges_contain (ranges, 21, 1));
4129   /* [21, 25] */
4130   SELF_CHECK (ranges_contain (ranges, 21, 5));
4131   /* [26, 28] */
4132   SELF_CHECK (!ranges_contain (ranges, 26, 3));
4133 }
4134
4135 /* Check that RANGES contains the same ranges as EXPECTED.  */
4136
4137 static bool
4138 check_ranges_vector (gdb::array_view<const range> ranges,
4139                      gdb::array_view<const range> expected)
4140 {
4141   return ranges == expected;
4142 }
4143
4144 /* Test the insert_into_bit_range_vector function.  */
4145
4146 static void
4147 test_insert_into_bit_range_vector ()
4148 {
4149   std::vector<range> ranges;
4150
4151   /* [10, 14] */
4152   {
4153     insert_into_bit_range_vector (&ranges, 10, 5);
4154     static const range expected[] = {
4155       {10, 5}
4156     };
4157     SELF_CHECK (check_ranges_vector (ranges, expected));
4158   }
4159
4160   /* [10, 14] */
4161   {
4162     insert_into_bit_range_vector (&ranges, 11, 4);
4163     static const range expected = {10, 5};
4164     SELF_CHECK (check_ranges_vector (ranges, expected));
4165   }
4166
4167   /* [10, 14] [20, 24] */
4168   {
4169     insert_into_bit_range_vector (&ranges, 20, 5);
4170     static const range expected[] = {
4171       {10, 5},
4172       {20, 5},
4173     };
4174     SELF_CHECK (check_ranges_vector (ranges, expected));
4175   }
4176
4177   /* [10, 14] [17, 24] */
4178   {
4179     insert_into_bit_range_vector (&ranges, 17, 5);
4180     static const range expected[] = {
4181       {10, 5},
4182       {17, 8},
4183     };
4184     SELF_CHECK (check_ranges_vector (ranges, expected));
4185   }
4186
4187   /* [2, 8] [10, 14] [17, 24] */
4188   {
4189     insert_into_bit_range_vector (&ranges, 2, 7);
4190     static const range expected[] = {
4191       {2, 7},
4192       {10, 5},
4193       {17, 8},
4194     };
4195     SELF_CHECK (check_ranges_vector (ranges, expected));
4196   }
4197
4198   /* [2, 14] [17, 24] */
4199   {
4200     insert_into_bit_range_vector (&ranges, 9, 1);
4201     static const range expected[] = {
4202       {2, 13},
4203       {17, 8},
4204     };
4205     SELF_CHECK (check_ranges_vector (ranges, expected));
4206   }
4207
4208   /* [2, 14] [17, 24] */
4209   {
4210     insert_into_bit_range_vector (&ranges, 9, 1);
4211     static const range expected[] = {
4212       {2, 13},
4213       {17, 8},
4214     };
4215     SELF_CHECK (check_ranges_vector (ranges, expected));
4216   }
4217
4218   /* [2, 33] */
4219   {
4220     insert_into_bit_range_vector (&ranges, 4, 30);
4221     static const range expected = {2, 32};
4222     SELF_CHECK (check_ranges_vector (ranges, expected));
4223   }
4224 }
4225
4226 } /* namespace selftests */
4227 #endif /* GDB_SELF_TEST */
4228
4229 void _initialize_values ();
4230 void
4231 _initialize_values ()
4232 {
4233   cmd_list_element *show_convenience_cmd
4234     = add_cmd ("convenience", no_class, show_convenience, _("\
4235 Debugger convenience (\"$foo\") variables and functions.\n\
4236 Convenience variables are created when you assign them values;\n\
4237 thus, \"set $foo=1\" gives \"$foo\" the value 1.  Values may be any type.\n\
4238 \n\
4239 A few convenience variables are given values automatically:\n\
4240 \"$_\"holds the last address examined with \"x\" or \"info lines\",\n\
4241 \"$__\" holds the contents of the last address examined with \"x\"."
4242 #ifdef HAVE_PYTHON
4243 "\n\n\
4244 Convenience functions are defined via the Python API."
4245 #endif
4246            ), &showlist);
4247   add_alias_cmd ("conv", show_convenience_cmd, no_class, 1, &showlist);
4248
4249   add_cmd ("values", no_set_class, show_values, _("\
4250 Elements of value history around item number IDX (or last ten)."),
4251            &showlist);
4252
4253   add_com ("init-if-undefined", class_vars, init_if_undefined_command, _("\
4254 Initialize a convenience variable if necessary.\n\
4255 init-if-undefined VARIABLE = EXPRESSION\n\
4256 Set an internal VARIABLE to the result of the EXPRESSION if it does not\n\
4257 exist or does not contain a value.  The EXPRESSION is not evaluated if the\n\
4258 VARIABLE is already initialized."));
4259
4260   add_prefix_cmd ("function", no_class, function_command, _("\
4261 Placeholder command for showing help on convenience functions."),
4262                   &functionlist, 0, &cmdlist);
4263
4264   add_internal_function ("_isvoid", _("\
4265 Check whether an expression is void.\n\
4266 Usage: $_isvoid (expression)\n\
4267 Return 1 if the expression is void, zero otherwise."),
4268                          isvoid_internal_fn, NULL);
4269
4270   add_internal_function ("_creal", _("\
4271 Extract the real part of a complex number.\n\
4272 Usage: $_creal (expression)\n\
4273 Return the real part of a complex number, the type depends on the\n\
4274 type of a complex number."),
4275                          creal_internal_fn, NULL);
4276
4277   add_internal_function ("_cimag", _("\
4278 Extract the imaginary part of a complex number.\n\
4279 Usage: $_cimag (expression)\n\
4280 Return the imaginary part of a complex number, the type depends on the\n\
4281 type of a complex number."),
4282                          cimag_internal_fn, NULL);
4283
4284   add_setshow_zuinteger_unlimited_cmd ("max-value-size",
4285                                        class_support, &max_value_size, _("\
4286 Set maximum sized value gdb will load from the inferior."), _("\
4287 Show maximum sized value gdb will load from the inferior."), _("\
4288 Use this to control the maximum size, in bytes, of a value that gdb\n\
4289 will load from the inferior.  Setting this value to 'unlimited'\n\
4290 disables checking.\n\
4291 Setting this does not invalidate already allocated values, it only\n\
4292 prevents future values, larger than this size, from being allocated."),
4293                             set_max_value_size,
4294                             show_max_value_size,
4295                             &setlist, &showlist);
4296 #if GDB_SELF_TEST
4297   selftests::register_test ("ranges_contain", selftests::test_ranges_contain);
4298   selftests::register_test ("insert_into_bit_range_vector",
4299                             selftests::test_insert_into_bit_range_vector);
4300 #endif
4301 }
4302
4303 /* See value.h.  */
4304
4305 void
4306 finalize_values ()
4307 {
4308   all_values.clear ();
4309 }
This page took 0.272949 seconds and 4 git commands to generate.