1 //===-- StackFrame.h --------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_TARGET_STACKFRAME_H
10 #define LLDB_TARGET_STACKFRAME_H
11 
12 #include <memory>
13 #include <mutex>
14 
15 #include "lldb/Utility/Flags.h"
16 
17 #include "lldb/Core/FormatEntity.h"
18 #include "lldb/Core/ValueObjectList.h"
19 #include "lldb/Symbol/SymbolContext.h"
20 #include "lldb/Target/ExecutionContextScope.h"
21 #include "lldb/Target/StackID.h"
22 #include "lldb/Utility/Scalar.h"
23 #include "lldb/Utility/Status.h"
24 #include "lldb/Utility/StreamString.h"
25 #include "lldb/Utility/UserID.h"
26 
27 namespace lldb_private {
28 
29 /// \class StackFrame StackFrame.h "lldb/Target/StackFrame.h"
30 ///
31 /// This base class provides an interface to stack frames.
32 ///
33 /// StackFrames may have a Canonical Frame Address (CFA) or not.
34 /// A frame may have a plain pc value or it may  indicate a specific point in
35 /// the debug session so the correct section load list is used for
36 /// symbolication.
37 ///
38 /// Local variables may be available, or not.  A register context may be
39 /// available, or not.
40 
41 class StackFrame : public ExecutionContextScope,
42                    public std::enable_shared_from_this<StackFrame> {
43 public:
44   enum ExpressionPathOption {
45     eExpressionPathOptionCheckPtrVsMember = (1u << 0),
46     eExpressionPathOptionsNoFragileObjcIvar = (1u << 1),
47     eExpressionPathOptionsNoSyntheticChildren = (1u << 2),
48     eExpressionPathOptionsNoSyntheticArrayRange = (1u << 3),
49     eExpressionPathOptionsAllowDirectIVarAccess = (1u << 4),
50     eExpressionPathOptionsInspectAnonymousUnions = (1u << 5)
51   };
52 
53   enum class Kind {
54     /// A regular stack frame with access to registers and local variables.
55     Regular,
56 
57     /// A historical stack frame -- possibly without CFA or registers or
58     /// local variables.
59     History,
60 
61     /// An artificial stack frame (e.g. a synthesized result of inferring
62     /// missing tail call frames from a backtrace) with limited support for
63     /// local variables.
64     Artificial
65   };
66 
67   /// Construct a StackFrame object without supplying a RegisterContextSP.
68   ///
69   /// This is the one constructor that doesn't take a RegisterContext
70   /// parameter.  This ctor may be called when creating a history StackFrame;
71   /// these are used if we've collected a stack trace of pc addresses at some
72   /// point in the past.  We may only have pc values. We may have a CFA,
73   /// or more likely, we won't.
74   ///
75   /// \param [in] thread_sp
76   ///   The Thread that this frame belongs to.
77   ///
78   /// \param [in] frame_idx
79   ///   This StackFrame's frame index number in the Thread.  If inlined stack
80   ///   frames are being created, this may differ from the concrete_frame_idx
81   ///   which is the frame index without any inlined stack frames.
82   ///
83   /// \param [in] concrete_frame_idx
84   ///   The StackFrame's frame index number in the Thread without any inlined
85   ///   stack frames being included in the index.
86   ///
87   /// \param [in] cfa
88   ///   The Canonical Frame Address (this terminology from DWARF) for this
89   ///   stack frame.  The CFA for a stack frame does not change over the
90   ///   span of the stack frame's existence.  It is often the value of the
91   ///   caller's stack pointer before the call instruction into this frame's
92   ///   function.  It is usually not the same as the frame pointer register's
93   ///   value.
94   ///
95   /// \param [in] cfa_is_valid
96   ///   A history stack frame may not have a CFA value collected.  We want to
97   ///   distinguish between "no CFA available" and a CFA of
98   ///   LLDB_INVALID_ADDRESS.
99   ///
100   /// \param [in] pc
101   ///   The current pc value of this stack frame.
102   ///
103   /// \param [in] sc_ptr
104   ///   Optionally seed the StackFrame with the SymbolContext information that
105   ///   has
106   ///   already been discovered.
107   StackFrame(const lldb::ThreadSP &thread_sp, lldb::user_id_t frame_idx,
108              lldb::user_id_t concrete_frame_idx, lldb::addr_t cfa,
109              bool cfa_is_valid, lldb::addr_t pc, Kind frame_kind,
110              bool behaves_like_zeroth_frame, const SymbolContext *sc_ptr);
111 
112   StackFrame(const lldb::ThreadSP &thread_sp, lldb::user_id_t frame_idx,
113              lldb::user_id_t concrete_frame_idx,
114              const lldb::RegisterContextSP &reg_context_sp, lldb::addr_t cfa,
115              lldb::addr_t pc, bool behaves_like_zeroth_frame,
116              const SymbolContext *sc_ptr);
117 
118   StackFrame(const lldb::ThreadSP &thread_sp, lldb::user_id_t frame_idx,
119              lldb::user_id_t concrete_frame_idx,
120              const lldb::RegisterContextSP &reg_context_sp, lldb::addr_t cfa,
121              const Address &pc, bool behaves_like_zeroth_frame,
122              const SymbolContext *sc_ptr);
123 
124   ~StackFrame() override;
125 
GetThread()126   lldb::ThreadSP GetThread() const { return m_thread_wp.lock(); }
127 
128   StackID &GetStackID();
129 
130   /// Get an Address for the current pc value in this StackFrame.
131   ///
132   /// May not be the same as the actual PC value for inlined stack frames.
133   ///
134   /// \return
135   ///   The Address object set to the current PC value.
136   const Address &GetFrameCodeAddress();
137 
138   /// Get the current code Address suitable for symbolication,
139   /// may not be the same as GetFrameCodeAddress().
140   ///
141   /// For a frame in the middle of the stack, the return-pc is the
142   /// current code address, but for symbolication purposes the
143   /// return address after a noreturn call may point to the next
144   /// function, a DWARF location list entry that is a completely
145   /// different code path, or the wrong source line.
146   ///
147   /// The address returned should be used for symbolication (source line,
148   /// block, function, DWARF location entry selection) but should NOT
149   /// be shown to the user.  It may not point to an actual instruction
150   /// boundary.
151   ///
152   /// \return
153   ///   The Address object set to the current PC value.
154   Address GetFrameCodeAddressForSymbolication();
155 
156   /// Change the pc value for a given thread.
157   ///
158   /// Change the current pc value for the frame on this thread.
159   ///
160   /// \param[in] pc
161   ///     The load address that the pc will be set to.
162   ///
163   /// \return
164   ///     true if the pc was changed.  false if this failed -- possibly
165   ///     because this frame is not a live StackFrame.
166   bool ChangePC(lldb::addr_t pc);
167 
168   /// Provide a SymbolContext for this StackFrame's current pc value.
169   ///
170   /// The StackFrame maintains this SymbolContext and adds additional
171   /// information to it on an as-needed basis.  This helps to avoid different
172   /// functions looking up symbolic information for a given pc value multiple
173   /// times.
174   ///
175   /// \param [in] resolve_scope
176   ///   Flags from the SymbolContextItem enumerated type which specify what
177   ///   type of symbol context is needed by this caller.
178   ///
179   /// \return
180   ///   A SymbolContext reference which includes the types of information
181   ///   requested by resolve_scope, if they are available.
182   const SymbolContext &GetSymbolContext(lldb::SymbolContextItem resolve_scope);
183 
184   /// Return the Canonical Frame Address (DWARF term) for this frame.
185   ///
186   /// The CFA is typically the value of the stack pointer register before the
187   /// call invocation is made.  It will not change during the lifetime of a
188   /// stack frame.  It is often not the same thing as the frame pointer
189   /// register value.
190   ///
191   /// Live StackFrames will always have a CFA but other types of frames may
192   /// not be able to supply one.
193   ///
194   /// \param [out] value
195   ///   The address of the CFA for this frame, if available.
196   ///
197   /// \param [out] error_ptr
198   ///   If there is an error determining the CFA address, this may contain a
199   ///   string explaining the failure.
200   ///
201   /// \return
202   ///   Returns true if the CFA value was successfully set in value.  Some
203   ///   frames may be unable to provide this value; they will return false.
204   bool GetFrameBaseValue(Scalar &value, Status *error_ptr);
205 
206   /// Get the DWARFExpressionList corresponding to the Canonical Frame Address.
207   ///
208   /// Often a register (bp), but sometimes a register + offset.
209   ///
210   /// \param [out] error_ptr
211   ///   If there is an error determining the CFA address, this may contain a
212   ///   string explaining the failure.
213   ///
214   /// \return
215   ///   Returns the corresponding DWARF expression, or NULL.
216   DWARFExpressionList *GetFrameBaseExpression(Status *error_ptr);
217 
218   /// Get the current lexical scope block for this StackFrame, if possible.
219   ///
220   /// If debug information is available for this stack frame, return a pointer
221   /// to the innermost lexical Block that the frame is currently executing.
222   ///
223   /// \return
224   ///   A pointer to the current Block.  nullptr is returned if this can
225   ///   not be provided.
226   Block *GetFrameBlock();
227 
228   /// Get the RegisterContext for this frame, if possible.
229   ///
230   /// Returns a shared pointer to the RegisterContext for this stack frame.
231   /// Only a live StackFrame object will be able to return a RegisterContext -
232   /// callers must be prepared for an empty shared pointer being returned.
233   ///
234   /// Even a live StackFrame RegisterContext may not be able to provide all
235   /// registers.  Only the currently executing frame (frame 0) can reliably
236   /// provide every register in the register context.
237   ///
238   /// \return
239   ///   The RegisterContext shared point for this frame.
240   lldb::RegisterContextSP GetRegisterContext();
241 
GetRegisterContextSP()242   const lldb::RegisterContextSP &GetRegisterContextSP() const {
243     return m_reg_context_sp;
244   }
245 
246   /// Retrieve the list of variables that are in scope at this StackFrame's
247   /// pc.
248   ///
249   /// A frame that is not live may return an empty VariableList for a given
250   /// pc value even though variables would be available at this point if it
251   /// were a live stack frame.
252   ///
253   /// \param[in] get_file_globals
254   ///     Whether to also retrieve compilation-unit scoped variables
255   ///     that are visible to the entire compilation unit (e.g. file
256   ///     static in C, globals that are homed in this CU).
257   ///
258   /// \param [out] error_ptr
259   ///   If there is an error in the debug information that prevents variables
260   ///   from being fetched. \see SymbolFile::GetFrameVariableError() for full
261   ///   details.
262   ///
263   /// \return
264   ///     A pointer to a list of variables.
265   VariableList *GetVariableList(bool get_file_globals, Status *error_ptr);
266 
267   /// Retrieve the list of variables that are in scope at this StackFrame's
268   /// pc.
269   ///
270   /// A frame that is not live may return an empty VariableListSP for a
271   /// given pc value even though variables would be available at this point if
272   /// it were a live stack frame.
273   ///
274   /// \param[in] get_file_globals
275   ///     Whether to also retrieve compilation-unit scoped variables
276   ///     that are visible to the entire compilation unit (e.g. file
277   ///     static in C, globals that are homed in this CU).
278   ///
279   /// \return
280   ///     A pointer to a list of variables.
281   lldb::VariableListSP
282   GetInScopeVariableList(bool get_file_globals,
283                          bool must_have_valid_location = false);
284 
285   /// Create a ValueObject for a variable name / pathname, possibly including
286   /// simple dereference/child selection syntax.
287   ///
288   /// \param[in] var_expr
289   ///     The string specifying a variable to base the VariableObject off
290   ///     of.
291   ///
292   /// \param[in] use_dynamic
293   ///     Whether the correct dynamic type of an object pointer should be
294   ///     determined before creating the object, or if the static type is
295   ///     sufficient.  One of the DynamicValueType enumerated values.
296   ///
297   /// \param[in] options
298   ///     An unsigned integer of flags, values from
299   ///     StackFrame::ExpressionPathOption
300   ///     enum.
301   /// \param[in] var_sp
302   ///     A VariableSP that will be set to the variable described in the
303   ///     var_expr path.
304   ///
305   /// \param[in] error
306   ///     Record any errors encountered while evaluating var_expr.
307   ///
308   /// \return
309   ///     A shared pointer to the ValueObject described by var_expr.
310   lldb::ValueObjectSP GetValueForVariableExpressionPath(
311       llvm::StringRef var_expr, lldb::DynamicValueType use_dynamic,
312       uint32_t options, lldb::VariableSP &var_sp, Status &error);
313 
314   /// Determine whether this StackFrame has debug information available or not.
315   ///
316   /// \return
317   ///    true if debug information is available for this frame (function,
318   ///    compilation unit, block, etc.)
319   bool HasDebugInformation();
320 
321   /// Return the disassembly for the instructions of this StackFrame's
322   /// function as a single C string.
323   ///
324   /// \return
325   ///    C string with the assembly instructions for this function.
326   const char *Disassemble();
327 
328   /// Print a description of this frame using the provided frame format.
329   ///
330   /// \param[out] strm
331   ///   The Stream to print the description to.
332   ///
333   /// \param[in] frame_marker
334   ///   Optional string that will be prepended to the frame output description.
335   ///
336   /// \return
337   ///   \b true if and only if dumping with the given \p format worked.
338   bool DumpUsingFormat(Stream &strm,
339                        const lldb_private::FormatEntity::Entry *format,
340                        llvm::StringRef frame_marker = {});
341 
342   /// Print a description for this frame using the frame-format formatter
343   /// settings. If the current frame-format settings are invalid, then the
344   /// default formatter will be used (see \a StackFrame::Dump()).
345   ///
346   /// \param [in] strm
347   ///   The Stream to print the description to.
348   ///
349   /// \param [in] show_unique
350   ///   Whether to print the function arguments or not for backtrace unique.
351   ///
352   /// \param [in] frame_marker
353   ///   Optional string that will be prepended to the frame output description.
354   void DumpUsingSettingsFormat(Stream *strm, bool show_unique = false,
355                                const char *frame_marker = nullptr);
356 
357   /// Print a description for this frame using a default format.
358   ///
359   /// \param [in] strm
360   ///   The Stream to print the description to.
361   ///
362   /// \param [in] show_frame_index
363   ///   Whether to print the frame number or not.
364   ///
365   /// \param [in] show_fullpaths
366   ///   Whether to print the full source paths or just the file base name.
367   void Dump(Stream *strm, bool show_frame_index, bool show_fullpaths);
368 
369   /// Print a description of this stack frame and/or the source
370   /// context/assembly for this stack frame.
371   ///
372   /// \param[in] strm
373   ///   The Stream to send the output to.
374   ///
375   /// \param[in] show_frame_info
376   ///   If true, print the frame info by calling DumpUsingSettingsFormat().
377   ///
378   /// \param[in] show_source
379   ///   If true, print source or disassembly as per the user's settings.
380   ///
381   /// \param[in] show_unique
382   ///   If true, print using backtrace unique style, without function
383   ///            arguments as per the user's settings.
384   ///
385   /// \param[in] frame_marker
386   ///   Passed to DumpUsingSettingsFormat() for the frame info printing.
387   ///
388   /// \return
389   ///   Returns true if successful.
390   bool GetStatus(Stream &strm, bool show_frame_info, bool show_source,
391                  bool show_unique = false, const char *frame_marker = nullptr);
392 
393   /// Query whether this frame is a concrete frame on the call stack, or if it
394   /// is an inlined frame derived from the debug information and presented by
395   /// the debugger.
396   ///
397   /// \return
398   ///   true if this is an inlined frame.
399   bool IsInlined();
400 
401   /// Query whether this frame is part of a historical backtrace.
402   bool IsHistorical() const;
403 
404   /// Query whether this frame is artificial (e.g a synthesized result of
405   /// inferring missing tail call frames from a backtrace). Artificial frames
406   /// may have limited support for inspecting variables.
407   bool IsArtificial() const;
408 
409   /// Query this frame to find what frame it is in this Thread's
410   /// StackFrameList.
411   ///
412   /// \return
413   ///   StackFrame index 0 indicates the currently-executing function.  Inline
414   ///   frames are included in this frame index count.
415   uint32_t GetFrameIndex() const;
416 
417   /// Set this frame's synthetic frame index.
SetFrameIndex(uint32_t index)418   void SetFrameIndex(uint32_t index) { m_frame_index = index; }
419 
420   /// Query this frame to find what frame it is in this Thread's
421   /// StackFrameList, not counting inlined frames.
422   ///
423   /// \return
424   ///   StackFrame index 0 indicates the currently-executing function.  Inline
425   ///   frames are not included in this frame index count; their concrete
426   ///   frame index will be the same as the concrete frame that they are
427   ///   derived from.
GetConcreteFrameIndex()428   uint32_t GetConcreteFrameIndex() const { return m_concrete_frame_index; }
429 
430   /// Create a ValueObject for a given Variable in this StackFrame.
431   ///
432   /// \param [in] variable_sp
433   ///   The Variable to base this ValueObject on
434   ///
435   /// \param [in] use_dynamic
436   ///     Whether the correct dynamic type of the variable should be
437   ///     determined before creating the ValueObject, or if the static type
438   ///     is sufficient.  One of the DynamicValueType enumerated values.
439   ///
440   /// \return
441   ///     A ValueObject for this variable.
442   lldb::ValueObjectSP
443   GetValueObjectForFrameVariable(const lldb::VariableSP &variable_sp,
444                                  lldb::DynamicValueType use_dynamic);
445 
446   /// Query this frame to determine what the default language should be when
447   /// parsing expressions given the execution context.
448   ///
449   /// \return
450   ///   The language of the frame if known, else lldb::eLanguageTypeUnknown.
451   lldb::LanguageType GetLanguage();
452 
453   // similar to GetLanguage(), but is allowed to take a potentially incorrect
454   // guess if exact information is not available
455   lldb::LanguageType GuessLanguage();
456 
457   /// Attempt to econstruct the ValueObject for a given raw address touched by
458   /// the current instruction.  The ExpressionPath should indicate how to get
459   /// to this value using "frame variable."
460   ///
461   /// \param [in] addr
462   ///   The raw address.
463   ///
464   /// \return
465   ///   The ValueObject if found.  If valid, it has a valid ExpressionPath.
466   lldb::ValueObjectSP GuessValueForAddress(lldb::addr_t addr);
467 
468   /// Attempt to reconstruct the ValueObject for the address contained in a
469   /// given register plus an offset.  The ExpressionPath should indicate how
470   /// to get to this value using "frame variable."
471   ///
472   /// \param [in] reg
473   ///   The name of the register.
474   ///
475   /// \param [in] offset
476   ///   The offset from the register.  Particularly important for sp...
477   ///
478   /// \return
479   ///   The ValueObject if found.  If valid, it has a valid ExpressionPath.
480   lldb::ValueObjectSP GuessValueForRegisterAndOffset(ConstString reg,
481                                                      int64_t offset);
482 
483   /// Attempt to reconstruct the ValueObject for a variable with a given \a name
484   /// from within the current StackFrame, within the current block. The search
485   /// for the variable starts in the deepest block corresponding to the current
486   /// PC in the stack frame and traverse through all parent blocks stopping at
487   /// inlined function boundaries.
488   ///
489   /// \param [in] name
490   ///   The name of the variable.
491   ///
492   /// \return
493   ///   The ValueObject if found.
494   lldb::ValueObjectSP FindVariable(ConstString name);
495 
496   // lldb::ExecutionContextScope pure virtual functions
497   lldb::TargetSP CalculateTarget() override;
498 
499   lldb::ProcessSP CalculateProcess() override;
500 
501   lldb::ThreadSP CalculateThread() override;
502 
503   lldb::StackFrameSP CalculateStackFrame() override;
504 
505   void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
506 
507   lldb::RecognizedStackFrameSP GetRecognizedFrame();
508 
509 protected:
510   friend class StackFrameList;
511 
512   void SetSymbolContextScope(SymbolContextScope *symbol_scope);
513 
514   void UpdateCurrentFrameFromPreviousFrame(StackFrame &prev_frame);
515 
516   void UpdatePreviousFrameFromCurrentFrame(StackFrame &curr_frame);
517 
518   bool HasCachedData() const;
519 
520 private:
521   // For StackFrame only
522   lldb::ThreadWP m_thread_wp;
523   uint32_t m_frame_index;
524   uint32_t m_concrete_frame_index;
525   lldb::RegisterContextSP m_reg_context_sp;
526   StackID m_id;
527   Address m_frame_code_addr; // The frame code address (might not be the same as
528                              // the actual PC for inlined frames) as a
529                              // section/offset address
530   SymbolContext m_sc;
531   Flags m_flags;
532   Scalar m_frame_base;
533   Status m_frame_base_error;
534   bool m_cfa_is_valid; // Does this frame have a CFA?  Different from CFA ==
535                        // LLDB_INVALID_ADDRESS
536   Kind m_stack_frame_kind;
537 
538   // Whether this frame behaves like the zeroth frame, in the sense
539   // that its pc value might not immediately follow a call (and thus might
540   // be the first address of its function). True for actual frame zero as
541   // well as any other frame with the same trait.
542   bool m_behaves_like_zeroth_frame;
543   lldb::VariableListSP m_variable_list_sp;
544   ValueObjectList m_variable_list_value_objects; // Value objects for each
545                                                  // variable in
546                                                  // m_variable_list_sp
547   lldb::RecognizedStackFrameSP m_recognized_frame_sp;
548   StreamString m_disassembly;
549   std::recursive_mutex m_mutex;
550 
551   StackFrame(const StackFrame &) = delete;
552   const StackFrame &operator=(const StackFrame &) = delete;
553 };
554 
555 } // namespace lldb_private
556 
557 #endif // LLDB_TARGET_STACKFRAME_H
558