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