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