1 /* Find a variable's value in memory, for GDB, the GNU debugger.
2 
3    Copyright (C) 1986-2024 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "event-top.h"
21 #include "extract-store-integer.h"
22 #include "symtab.h"
23 #include "gdbtypes.h"
24 #include "frame.h"
25 #include "value.h"
26 #include "gdbcore.h"
27 #include "inferior.h"
28 #include "target.h"
29 #include "symfile.h"
30 #include "regcache.h"
31 #include "user-regs.h"
32 #include "block.h"
33 #include "objfiles.h"
34 #include "language.h"
35 
36 /* Basic byte-swapping routines.  All 'extract' functions return a
37    host-format integer from a target-format integer at ADDR which is
38    LEN bytes long.  */
39 
40 #if TARGET_CHAR_BIT != 8 || HOST_CHAR_BIT != 8
41   /* 8 bit characters are a pretty safe assumption these days, so we
42      assume it throughout all these swapping routines.  If we had to deal with
43      9 bit characters, we would need to make len be in bits and would have
44      to re-write these routines...  */
45 you lose
46 #endif
47 
48 /* See value.h.  */
49 
50 value *
value_of_register(int regnum,const frame_info_ptr & next_frame)51 value_of_register (int regnum, const frame_info_ptr &next_frame)
52 {
53   gdbarch *gdbarch = frame_unwind_arch (next_frame);
54 
55   /* User registers lie completely outside of the range of normal
56      registers.  Catch them early so that the target never sees them.  */
57   if (regnum >= gdbarch_num_cooked_regs (gdbarch))
58     return value_of_user_reg (regnum, get_prev_frame_always (next_frame));
59 
60   value *reg_val = value_of_register_lazy (next_frame, regnum);
61   reg_val->fetch_lazy ();
62   return reg_val;
63 }
64 
65 /* See value.h.  */
66 
67 value *
value_of_register_lazy(const frame_info_ptr & next_frame,int regnum)68 value_of_register_lazy (const frame_info_ptr &next_frame, int regnum)
69 {
70   gdbarch *gdbarch = frame_unwind_arch (next_frame);
71 
72   gdb_assert (regnum < gdbarch_num_cooked_regs (gdbarch));
73   gdb_assert (next_frame != nullptr);
74 
75   return value::allocate_register_lazy (next_frame, regnum);
76 }
77 
78 /* Given a pointer of type TYPE in target form in BUF, return the
79    address it represents.  */
80 CORE_ADDR
unsigned_pointer_to_address(struct gdbarch * gdbarch,struct type * type,const gdb_byte * buf)81 unsigned_pointer_to_address (struct gdbarch *gdbarch,
82                                    struct type *type, const gdb_byte *buf)
83 {
84   enum bfd_endian byte_order = type_byte_order (type);
85 
86   return extract_unsigned_integer (buf, type->length (), byte_order);
87 }
88 
89 CORE_ADDR
signed_pointer_to_address(struct gdbarch * gdbarch,struct type * type,const gdb_byte * buf)90 signed_pointer_to_address (struct gdbarch *gdbarch,
91                                  struct type *type, const gdb_byte *buf)
92 {
93   enum bfd_endian byte_order = type_byte_order (type);
94 
95   return extract_signed_integer (buf, type->length (), byte_order);
96 }
97 
98 /* Given an address, store it as a pointer of type TYPE in target
99    format in BUF.  */
100 void
unsigned_address_to_pointer(struct gdbarch * gdbarch,struct type * type,gdb_byte * buf,CORE_ADDR addr)101 unsigned_address_to_pointer (struct gdbarch *gdbarch, struct type *type,
102                                    gdb_byte *buf, CORE_ADDR addr)
103 {
104   enum bfd_endian byte_order = type_byte_order (type);
105 
106   store_unsigned_integer (buf, type->length (), byte_order, addr);
107 }
108 
109 void
address_to_signed_pointer(struct gdbarch * gdbarch,struct type * type,gdb_byte * buf,CORE_ADDR addr)110 address_to_signed_pointer (struct gdbarch *gdbarch, struct type *type,
111                                  gdb_byte *buf, CORE_ADDR addr)
112 {
113   enum bfd_endian byte_order = type_byte_order (type);
114 
115   store_signed_integer (buf, type->length (), byte_order, addr);
116 }
117 
118 /* See value.h.  */
119 
120 enum symbol_needs_kind
symbol_read_needs(struct symbol * sym)121 symbol_read_needs (struct symbol *sym)
122 {
123   if (const symbol_computed_ops *computed_ops = sym->computed_ops ();
124       computed_ops != nullptr)
125     return computed_ops->get_symbol_read_needs (sym);
126 
127   switch (sym->aclass ())
128     {
129       /* All cases listed explicitly so that gcc -Wall will detect it if
130            we failed to consider one.  */
131     case LOC_COMPUTED:
132       gdb_assert_not_reached ("LOC_COMPUTED variable missing a method");
133 
134     case LOC_REGISTER:
135     case LOC_ARG:
136     case LOC_REF_ARG:
137     case LOC_REGPARM_ADDR:
138     case LOC_LOCAL:
139       return SYMBOL_NEEDS_FRAME;
140 
141     case LOC_UNDEF:
142     case LOC_CONST:
143     case LOC_STATIC:
144     case LOC_TYPEDEF:
145 
146     case LOC_LABEL:
147       /* Getting the address of a label can be done independently of the block,
148            even if some *uses* of that address wouldn't work so well without
149            the right frame.  */
150 
151     case LOC_BLOCK:
152     case LOC_CONST_BYTES:
153     case LOC_UNRESOLVED:
154     case LOC_OPTIMIZED_OUT:
155       return SYMBOL_NEEDS_NONE;
156     }
157   return SYMBOL_NEEDS_FRAME;
158 }
159 
160 /* See value.h.  */
161 
162 int
symbol_read_needs_frame(struct symbol * sym)163 symbol_read_needs_frame (struct symbol *sym)
164 {
165   return symbol_read_needs (sym) == SYMBOL_NEEDS_FRAME;
166 }
167 
168 /* Assuming VAR is a symbol that can be reached from FRAME thanks to lexical
169    rules, look for the frame that is actually hosting VAR and return it.  If,
170    for some reason, we found no such frame, return NULL.
171 
172    This kind of computation is necessary to correctly handle lexically nested
173    functions.
174 
175    Note that in some cases, we know what scope VAR comes from but we cannot
176    reach the specific frame that hosts the instance of VAR we are looking for.
177    For backward compatibility purposes (with old compilers), we then look for
178    the first frame that can host it.  */
179 
180 static frame_info_ptr
get_hosting_frame(struct symbol * var,const struct block * var_block,const frame_info_ptr & initial_frame)181 get_hosting_frame (struct symbol *var, const struct block *var_block,
182                        const frame_info_ptr &initial_frame)
183 {
184   const struct block *frame_block = NULL;
185 
186   if (!symbol_read_needs_frame (var))
187     return NULL;
188 
189   /* Some symbols for local variables have no block: this happens when they are
190      not produced by a debug information reader, for instance when GDB creates
191      synthetic symbols.  Without block information, we must assume they are
192      local to FRAME. In this case, there is nothing to do.  */
193   else if (var_block == NULL)
194     return initial_frame;
195 
196   /* We currently assume that all symbols with a location list need a frame.
197      This is true in practice because selecting the location description
198      requires to compute the CFA, hence requires a frame.  However we have
199      tests that embed global/static symbols with null location lists.
200      We want to get <optimized out> instead of <frame required> when evaluating
201      them so return a frame instead of raising an error.  */
202   else if (var_block->is_global_block () || var_block->is_static_block ())
203     return initial_frame;
204 
205   /* We have to handle the "my_func::my_local_var" notation.  This requires us
206      to look for upper frames when we find no block for the current frame: here
207      and below, handle when frame_block == NULL.  */
208   if (initial_frame != nullptr)
209     frame_block = get_frame_block (initial_frame, NULL);
210 
211   /* Climb up the call stack until reaching the frame we are looking for.  */
212   frame_info_ptr frame = initial_frame;
213   while (frame != NULL && frame_block != var_block)
214     {
215       /* Stacks can be quite deep: give the user a chance to stop this.  */
216       QUIT;
217 
218       if (frame_block == NULL)
219           {
220             frame = get_prev_frame (frame);
221             if (frame == NULL)
222               break;
223             frame_block = get_frame_block (frame, NULL);
224           }
225 
226       /* If we failed to find the proper frame, fallback to the heuristic
227            method below.  */
228       else if (frame_block->is_global_block ())
229           {
230             frame = NULL;
231             break;
232           }
233 
234       /* Assuming we have a block for this frame: if we are at the function
235            level, the immediate upper lexical block is in an outer function:
236            follow the static link.  */
237       else if (frame_block->function () != nullptr)
238           {
239             frame = frame_follow_static_link (frame);
240             if (frame != nullptr)
241               {
242                 frame_block = get_frame_block (frame, nullptr);
243                 if (frame_block == nullptr)
244                     frame = nullptr;
245               }
246           }
247 
248       else
249           /* We must be in some function nested lexical block.  Just get the
250              outer block: both must share the same frame.  */
251           frame_block = frame_block->superblock ();
252     }
253 
254   /* Old compilers may not provide a static link, or they may provide an
255      invalid one.  For such cases, fallback on the old way to evaluate
256      non-local references: just climb up the call stack and pick the first
257      frame that contains the variable we are looking for.  */
258   if (frame == NULL)
259     {
260       frame = block_innermost_frame (var_block);
261       if (frame == NULL)
262           {
263             if (var_block->function ()
264                 && !var_block->inlined_p ()
265                 && var_block->function ()->print_name ())
266               error (_("No frame is currently executing in block %s."),
267                        var_block->function ()->print_name ());
268             else
269               error (_("No frame is currently executing in specified"
270                          " block"));
271           }
272     }
273 
274   return frame;
275 }
276 
277 /* See language.h.  */
278 
279 struct value *
read_var_value(struct symbol * var,const struct block * var_block,const frame_info_ptr & frame_param)280 language_defn::read_var_value (struct symbol *var,
281                                      const struct block *var_block,
282                                      const frame_info_ptr &frame_param) const
283 {
284   struct value *v;
285   struct type *type = var->type ();
286   CORE_ADDR addr;
287   enum symbol_needs_kind sym_need;
288   frame_info_ptr frame = frame_param;
289 
290   /* Call check_typedef on our type to make sure that, if TYPE is
291      a TYPE_CODE_TYPEDEF, its length is set to the length of the target type
292      instead of zero.  However, we do not replace the typedef type by the
293      target type, because we want to keep the typedef in order to be able to
294      set the returned value type description correctly.  */
295   check_typedef (type);
296 
297   sym_need = symbol_read_needs (var);
298   if (sym_need == SYMBOL_NEEDS_FRAME)
299     gdb_assert (frame != NULL);
300   else if (sym_need == SYMBOL_NEEDS_REGISTERS && !target_has_registers ())
301     error (_("Cannot read `%s' without registers"), var->print_name ());
302 
303   if (frame != NULL)
304     frame = get_hosting_frame (var, var_block, frame);
305 
306   if (const symbol_computed_ops *computed_ops = var->computed_ops ())
307     return computed_ops->read_variable (var, frame);
308 
309   switch (var->aclass ())
310     {
311     case LOC_CONST:
312       if (is_dynamic_type (type))
313           {
314             gdb_byte bytes[sizeof (LONGEST)];
315 
316             size_t len = std::min (sizeof (LONGEST), (size_t) type->length ());
317             store_unsigned_integer (bytes, len,
318                                           type_byte_order (type),
319                                           var->value_longest ());
320             gdb::array_view<const gdb_byte> view (bytes, len);
321 
322             /* Value is a constant byte-sequence.  */
323             type = resolve_dynamic_type (type, view, /* Unused address.  */ 0);
324           }
325       /* Put the constant back in target format. */
326       v = value::allocate (type);
327       store_signed_integer (v->contents_raw ().data (), type->length (),
328                                   type_byte_order (type), var->value_longest ());
329       v->set_lval (not_lval);
330       return v;
331 
332     case LOC_LABEL:
333       {
334           /* Put the constant back in target format.  */
335           if (overlay_debugging)
336             {
337               struct objfile *var_objfile = var->objfile ();
338               addr = symbol_overlayed_address (var->value_address (),
339                                                        var->obj_section (var_objfile));
340             }
341           else
342             addr = var->value_address ();
343 
344           /* First convert the CORE_ADDR to a function pointer type, this
345              ensures the gdbarch knows what type of pointer we are
346              manipulating when value_from_pointer is called.  */
347           type = builtin_type (var->arch ())->builtin_func_ptr;
348           v = value_from_pointer (type, addr);
349 
350           /* But we want to present the value as 'void *', so cast it to the
351              required type now, this will not change the values bit
352              representation.  */
353           struct type *void_ptr_type
354             = builtin_type (var->arch ())->builtin_data_ptr;
355           v = value_cast_pointers (void_ptr_type, v, 0);
356           v->set_lval (not_lval);
357           return v;
358       }
359 
360     case LOC_CONST_BYTES:
361       if (is_dynamic_type (type))
362           {
363             gdb::array_view<const gdb_byte> view (var->value_bytes (),
364                                                             type->length ());
365 
366             /* Value is a constant byte-sequence.  */
367             type = resolve_dynamic_type (type, view, /* Unused address.  */ 0);
368           }
369       v = value::allocate (type);
370       memcpy (v->contents_raw ().data (), var->value_bytes (),
371                 type->length ());
372       v->set_lval (not_lval);
373       return v;
374 
375     case LOC_STATIC:
376       if (overlay_debugging)
377           addr
378             = symbol_overlayed_address (var->value_address (),
379                                               var->obj_section (var->objfile ()));
380       else
381           addr = var->value_address ();
382       break;
383 
384     case LOC_ARG:
385       addr = get_frame_args_address (frame);
386       if (!addr)
387           error (_("Unknown argument list address for `%s'."),
388                  var->print_name ());
389       addr += var->value_longest ();
390       break;
391 
392     case LOC_REF_ARG:
393       {
394           struct value *ref;
395           CORE_ADDR argref;
396 
397           argref = get_frame_args_address (frame);
398           if (!argref)
399             error (_("Unknown argument list address for `%s'."),
400                      var->print_name ());
401           argref += var->value_longest ();
402           ref = value_at (lookup_pointer_type (type), argref);
403           addr = value_as_address (ref);
404           break;
405       }
406 
407     case LOC_LOCAL:
408       addr = get_frame_locals_address (frame);
409       addr += var->value_longest ();
410       break;
411 
412     case LOC_TYPEDEF:
413       error (_("Cannot look up value of a typedef `%s'."),
414                var->print_name ());
415       break;
416 
417     case LOC_BLOCK:
418       if (overlay_debugging)
419           addr = symbol_overlayed_address
420             (var->value_block ()->entry_pc (),
421              var->obj_section (var->objfile ()));
422       else
423           addr = var->value_block ()->entry_pc ();
424       break;
425 
426     case LOC_REGISTER:
427     case LOC_REGPARM_ADDR:
428       {
429           const symbol_register_ops *reg_ops = var->register_ops ();
430           int regno = reg_ops->register_number (var, get_frame_arch (frame));
431 
432           if (var->aclass () == LOC_REGPARM_ADDR)
433             addr = value_as_address
434              (value_from_register (lookup_pointer_type (type), regno, frame));
435           else
436             return value_from_register (type, regno, frame);
437       }
438       break;
439 
440     case LOC_COMPUTED:
441       gdb_assert_not_reached ("LOC_COMPUTED variable missing a method");
442 
443     case LOC_UNRESOLVED:
444       {
445           struct obj_section *obj_section;
446           bound_minimal_symbol bmsym;
447 
448           gdbarch_iterate_over_objfiles_in_search_order
449             (var->arch (),
450              [var, &bmsym] (objfile *objfile)
451                {
452                     bmsym = lookup_minimal_symbol (var->linkage_name (), nullptr,
453                                                          objfile);
454 
455                     /* Stop if a match is found.  */
456                     return bmsym.minsym != nullptr;
457                },
458              var->objfile ());
459 
460           /* If we can't find the minsym there's a problem in the symbol info.
461              The symbol exists in the debug info, but it's missing in the minsym
462              table.  */
463           if (bmsym.minsym == nullptr)
464             {
465               const char *flavour_name
466                 = objfile_flavour_name (var->objfile ());
467 
468               /* We can't get here unless we've opened the file, so flavour_name
469                  can't be NULL.  */
470               gdb_assert (flavour_name != NULL);
471               error (_("Missing %s symbol \"%s\"."),
472                        flavour_name, var->linkage_name ());
473             }
474 
475           obj_section = bmsym.minsym->obj_section (bmsym.objfile);
476           /* Relocate address, unless there is no section or the variable is
477              a TLS variable. */
478           if (obj_section == NULL
479               || (obj_section->the_bfd_section->flags & SEC_THREAD_LOCAL) != 0)
480             addr = CORE_ADDR (bmsym.minsym->unrelocated_address ());
481           else
482             addr = bmsym.value_address ();
483           if (overlay_debugging)
484             addr = symbol_overlayed_address (addr, obj_section);
485           /* Determine address of TLS variable. */
486           if (obj_section
487               && (obj_section->the_bfd_section->flags & SEC_THREAD_LOCAL) != 0)
488             addr = target_translate_tls_address (obj_section->objfile, addr);
489       }
490       break;
491 
492     case LOC_OPTIMIZED_OUT:
493       if (is_dynamic_type (type))
494           type = resolve_dynamic_type (type, {}, /* Unused address.  */ 0);
495       return value::allocate_optimized_out (type);
496 
497     default:
498       error (_("Cannot look up value of a botched symbol `%s'."),
499                var->print_name ());
500       break;
501     }
502 
503   v = value_at_lazy (type, addr);
504   return v;
505 }
506 
507 /* Calls VAR's language read_var_value hook with the given arguments.  */
508 
509 struct value *
read_var_value(struct symbol * var,const struct block * var_block,const frame_info_ptr & frame)510 read_var_value (struct symbol *var, const struct block *var_block,
511                     const frame_info_ptr &frame)
512 {
513   const struct language_defn *lang = language_def (var->language ());
514 
515   gdb_assert (lang != NULL);
516 
517   return lang->read_var_value (var, var_block, frame);
518 }
519 
520 /* Install default attributes for register values.  */
521 
522 value *
default_value_from_register(gdbarch * gdbarch,type * type,int regnum,const frame_info_ptr & this_frame)523 default_value_from_register (gdbarch *gdbarch, type *type, int regnum,
524                                    const frame_info_ptr &this_frame)
525 {
526   value *value
527     = value::allocate_register (get_next_frame_sentinel_okay (this_frame),
528                                         regnum, type);
529 
530   /* Any structure stored in more than one register will always be
531      an integral number of registers.  Otherwise, you need to do
532      some fiddling with the last register copied here for little
533      endian machines.  */
534   if (type_byte_order (type) == BFD_ENDIAN_BIG
535       && type->length () < register_size (gdbarch, regnum))
536     /* Big-endian, and we want less than full size.  */
537     value->set_offset (register_size (gdbarch, regnum) - type->length ());
538   else
539     value->set_offset (0);
540 
541   return value;
542 }
543 
544 /* VALUE must be an lval_register value.  If regnum is the value's
545    associated register number, and len the length of the value's type,
546    read one or more registers in VALUE's frame, starting with register REGNUM,
547    until we've read LEN bytes.
548 
549    If any of the registers we try to read are optimized out, then mark the
550    complete resulting value as optimized out.  */
551 
552 static void
read_frame_register_value(value * value)553 read_frame_register_value (value *value)
554 {
555   gdb_assert (value->lval () == lval_register);
556 
557   frame_info_ptr next_frame = frame_find_by_id (value->next_frame_id ());
558   gdb_assert (next_frame != nullptr);
559 
560   gdbarch *gdbarch = frame_unwind_arch (next_frame);
561   LONGEST offset = 0;
562   LONGEST reg_offset = value->offset ();
563   int regnum = value->regnum ();
564   int len = type_length_units (check_typedef (value->type ()));
565 
566   /* Skip registers wholly inside of REG_OFFSET.  */
567   while (reg_offset >= register_size (gdbarch, regnum))
568     {
569       reg_offset -= register_size (gdbarch, regnum);
570       regnum++;
571     }
572 
573   /* Copy the data.  */
574   while (len > 0)
575     {
576       struct value *regval = frame_unwind_register_value (next_frame, regnum);
577       int reg_len = type_length_units (regval->type ()) - reg_offset;
578 
579       /* If the register length is larger than the number of bytes
580            remaining to copy, then only copy the appropriate bytes.  */
581       if (reg_len > len)
582           reg_len = len;
583 
584       regval->contents_copy (value, offset, reg_offset, reg_len);
585 
586       offset += reg_len;
587       len -= reg_len;
588       reg_offset = 0;
589       regnum++;
590     }
591 }
592 
593 /* Return a value of type TYPE, stored in register REGNUM, in frame FRAME.  */
594 
595 struct value *
value_from_register(struct type * type,int regnum,const frame_info_ptr & frame)596 value_from_register (struct type *type, int regnum, const frame_info_ptr &frame)
597 {
598   struct gdbarch *gdbarch = get_frame_arch (frame);
599   struct type *type1 = check_typedef (type);
600   struct value *v;
601 
602   if (gdbarch_convert_register_p (gdbarch, regnum, type1))
603     {
604       int optim, unavail, ok;
605 
606       /* The ISA/ABI need to something weird when obtaining the
607            specified value from this register.  It might need to
608            re-order non-adjacent, starting with REGNUM (see MIPS and
609            i386).  It might need to convert the [float] register into
610            the corresponding [integer] type (see Alpha).  The assumption
611            is that gdbarch_register_to_value populates the entire value
612            including the location.  */
613       v = value::allocate_register (get_next_frame_sentinel_okay (frame),
614                                             regnum, type);
615       ok = gdbarch_register_to_value (gdbarch, frame, regnum, type1,
616                                               v->contents_raw ().data (), &optim,
617                                               &unavail);
618 
619       if (!ok)
620           {
621             if (optim)
622               v->mark_bytes_optimized_out (0, type->length ());
623             if (unavail)
624               v->mark_bytes_unavailable (0, type->length ());
625           }
626     }
627   else
628     {
629       /* Construct the value.  */
630       v = gdbarch_value_from_register (gdbarch, type, regnum, frame);
631 
632       /* Get the data.  */
633       read_frame_register_value (v);
634     }
635 
636   return v;
637 }
638 
639 /* Return contents of register REGNUM in frame FRAME as address.
640    Will abort if register value is not available.  */
641 
642 CORE_ADDR
address_from_register(int regnum,const frame_info_ptr & frame)643 address_from_register (int regnum, const frame_info_ptr &frame)
644 {
645   type *type = builtin_type (get_frame_arch (frame))->builtin_data_ptr;
646   value_ref_ptr v = release_value (value_from_register (type, regnum, frame));
647 
648   if (v->optimized_out ())
649     {
650       /* This function is used while computing a location expression.
651            Complain about the value being optimized out, rather than
652            letting value_as_address complain about some random register
653            the expression depends on not being saved.  */
654       error_value_optimized_out ();
655     }
656 
657   return value_as_address (v.get ());
658 }
659