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