xref: /freebsd/contrib/llvm-project/lldb/include/lldb/Target/Thread.h (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===-- Thread.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_THREAD_H
10 #define LLDB_TARGET_THREAD_H
11 
12 #include <memory>
13 #include <mutex>
14 #include <optional>
15 #include <string>
16 #include <vector>
17 
18 #include "lldb/Core/UserSettingsController.h"
19 #include "lldb/Target/ExecutionContextScope.h"
20 #include "lldb/Target/RegisterCheckpoint.h"
21 #include "lldb/Target/StackFrameList.h"
22 #include "lldb/Utility/Broadcaster.h"
23 #include "lldb/Utility/CompletionRequest.h"
24 #include "lldb/Utility/Event.h"
25 #include "lldb/Utility/StructuredData.h"
26 #include "lldb/Utility/UnimplementedError.h"
27 #include "lldb/Utility/UserID.h"
28 #include "lldb/lldb-private.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 
31 #define LLDB_THREAD_MAX_STOP_EXC_DATA 8
32 
33 namespace lldb_private {
34 
35 class ThreadPlanStack;
36 
37 class ThreadProperties : public Properties {
38 public:
39   ThreadProperties(bool is_global);
40 
41   ~ThreadProperties() override;
42 
43   /// The regular expression returned determines symbols that this
44   /// thread won't stop in during "step-in" operations.
45   ///
46   /// \return
47   ///    A pointer to a regular expression to compare against symbols,
48   ///    or nullptr if all symbols are allowed.
49   ///
50   const RegularExpression *GetSymbolsToAvoidRegexp();
51 
52   FileSpecList GetLibrariesToAvoid() const;
53 
54   bool GetTraceEnabledState() const;
55 
56   bool GetStepInAvoidsNoDebug() const;
57 
58   bool GetStepOutAvoidsNoDebug() const;
59 
60   uint64_t GetMaxBacktraceDepth() const;
61 
62   uint64_t GetSingleThreadPlanTimeout() const;
63 };
64 
65 class Thread : public std::enable_shared_from_this<Thread>,
66                public ThreadProperties,
67                public UserID,
68                public ExecutionContextScope,
69                public Broadcaster {
70 public:
71   /// Broadcaster event bits definitions.
72   enum {
73     eBroadcastBitStackChanged = (1 << 0),
74     eBroadcastBitThreadSuspended = (1 << 1),
75     eBroadcastBitThreadResumed = (1 << 2),
76     eBroadcastBitSelectedFrameChanged = (1 << 3),
77     eBroadcastBitThreadSelected = (1 << 4)
78   };
79 
80   static llvm::StringRef GetStaticBroadcasterClass();
81 
GetBroadcasterClass()82   llvm::StringRef GetBroadcasterClass() const override {
83     return GetStaticBroadcasterClass();
84   }
85 
86   class ThreadEventData : public EventData {
87   public:
88     ThreadEventData(const lldb::ThreadSP thread_sp);
89 
90     ThreadEventData(const lldb::ThreadSP thread_sp, const StackID &stack_id);
91 
92     ThreadEventData();
93 
94     ~ThreadEventData() override;
95 
96     static llvm::StringRef GetFlavorString();
97 
GetFlavor()98     llvm::StringRef GetFlavor() const override {
99       return ThreadEventData::GetFlavorString();
100     }
101 
102     void Dump(Stream *s) const override;
103 
104     static const ThreadEventData *GetEventDataFromEvent(const Event *event_ptr);
105 
106     static lldb::ThreadSP GetThreadFromEvent(const Event *event_ptr);
107 
108     static StackID GetStackIDFromEvent(const Event *event_ptr);
109 
110     static lldb::StackFrameSP GetStackFrameFromEvent(const Event *event_ptr);
111 
GetThread()112     lldb::ThreadSP GetThread() const { return m_thread_sp; }
113 
GetStackID()114     StackID GetStackID() const { return m_stack_id; }
115 
116   private:
117     lldb::ThreadSP m_thread_sp;
118     StackID m_stack_id;
119 
120     ThreadEventData(const ThreadEventData &) = delete;
121     const ThreadEventData &operator=(const ThreadEventData &) = delete;
122   };
123 
124   struct ThreadStateCheckpoint {
125     uint32_t orig_stop_id; // Dunno if I need this yet but it is an interesting
126                            // bit of data.
127     lldb::StopInfoSP stop_info_sp; // You have to restore the stop info or you
128                                    // might continue with the wrong signals.
129     size_t m_completed_plan_checkpoint;
130     lldb::RegisterCheckpointSP
131         register_backup_sp; // You need to restore the registers, of course...
132     uint32_t current_inlined_depth;
133     lldb::addr_t current_inlined_pc;
134     lldb::addr_t stopped_at_unexecuted_bp;
135   };
136 
137   /// Constructor
138   ///
139   /// \param [in] use_invalid_index_id
140   ///     Optional parameter, defaults to false.  The only subclass that
141   ///     is likely to set use_invalid_index_id == true is the HistoryThread
142   ///     class.  In that case, the Thread we are constructing represents
143   ///     a thread from earlier in the program execution.  We may have the
144   ///     tid of the original thread that they represent but we don't want
145   ///     to reuse the IndexID of that thread, or create a new one.  If a
146   ///     client wants to know the original thread's IndexID, they should use
147   ///     Thread::GetExtendedBacktraceOriginatingIndexID().
148   Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id = false);
149 
150   ~Thread() override;
151 
152   static void SettingsInitialize();
153 
154   static void SettingsTerminate();
155 
156   static ThreadProperties &GetGlobalProperties();
157 
GetProcess()158   lldb::ProcessSP GetProcess() const { return m_process_wp.lock(); }
159 
GetResumeSignal()160   int GetResumeSignal() const { return m_resume_signal; }
161 
SetResumeSignal(int signal)162   void SetResumeSignal(int signal) { m_resume_signal = signal; }
163 
164   lldb::StateType GetState() const;
165 
166   void SetState(lldb::StateType state);
167 
168   /// Sets the USER resume state for this thread.  If you set a thread to
169   /// suspended with
170   /// this API, it won't take part in any of the arbitration for ShouldResume,
171   /// and will stay
172   /// suspended even when other threads do get to run.
173   ///
174   /// N.B. This is not the state that is used internally by thread plans to
175   /// implement
176   /// staying on one thread while stepping over a breakpoint, etc.  The is the
177   /// TemporaryResume state, and if you are implementing some bit of strategy in
178   /// the stepping
179   /// machinery you should be using that state and not the user resume state.
180   ///
181   /// If you are just preparing all threads to run, you should not override the
182   /// threads that are
183   /// marked as suspended by the debugger.  In that case, pass override_suspend
184   /// = false.  If you want
185   /// to force the thread to run (e.g. the "thread continue" command, or are
186   /// resetting the state
187   /// (e.g. in SBThread::Resume()), then pass true to override_suspend.
188   void SetResumeState(lldb::StateType state, bool override_suspend = false) {
189     if (m_resume_state == lldb::eStateSuspended && !override_suspend)
190       return;
191     m_resume_state = state;
192   }
193 
194   /// Gets the USER resume state for this thread.  This is not the same as what
195   /// this thread is going to do for any particular step, however if this thread
196   /// returns eStateSuspended, then the process control logic will never allow
197   /// this
198   /// thread to run.
199   ///
200   /// \return
201   ///    The User resume state for this thread.
GetResumeState()202   lldb::StateType GetResumeState() const { return m_resume_state; }
203 
204   // This function is called to determine whether the thread needs to
205   // step over a breakpoint and if so, push a step-over-breakpoint thread
206   // plan.
207   ///
208   /// \return
209   ///    True if we pushed a ThreadPlanStepOverBreakpoint
210   bool SetupToStepOverBreakpointIfNeeded(lldb::RunDirection direction);
211 
212   // Do not override this function, it is for thread plan logic only
213   bool ShouldResume(lldb::StateType resume_state);
214 
215   // Override this to do platform specific tasks before resume.
WillResume(lldb::StateType resume_state)216   virtual void WillResume(lldb::StateType resume_state) {}
217 
218   // This clears generic thread state after a resume.  If you subclass this, be
219   // sure to call it.
220   virtual void DidResume();
221 
222   // This notifies the thread when a private stop occurs.
223   virtual void DidStop();
224 
225   virtual void RefreshStateAfterStop() = 0;
226 
227   std::string GetStopDescription();
228 
229   std::string GetStopDescriptionRaw();
230 
231   void WillStop();
232 
233   bool ShouldStop(Event *event_ptr);
234 
235   Vote ShouldReportStop(Event *event_ptr);
236 
237   Vote ShouldReportRun(Event *event_ptr);
238 
239   void Flush();
240 
241   // Return whether this thread matches the specification in ThreadSpec.  This
242   // is a virtual method because at some point we may extend the thread spec
243   // with a platform specific dictionary of attributes, which then only the
244   // platform specific Thread implementation would know how to match.  For now,
245   // this just calls through to the ThreadSpec's ThreadPassesBasicTests method.
246   virtual bool MatchesSpec(const ThreadSpec *spec);
247 
248   // Get the current public stop info, calculating it if necessary.
249   lldb::StopInfoSP GetStopInfo();
250 
251   lldb::StopReason GetStopReason();
252 
253   bool StopInfoIsUpToDate() const;
254 
255   // This sets the stop reason to a "blank" stop reason, so you can call
256   // functions on the thread without having the called function run with
257   // whatever stop reason you stopped with.
258   void SetStopInfoToNothing();
259 
260   bool ThreadStoppedForAReason();
261 
262   static std::string RunModeAsString(lldb::RunMode mode);
263 
264   static std::string StopReasonAsString(lldb::StopReason reason);
265 
GetInfo()266   virtual const char *GetInfo() { return nullptr; }
267 
268   /// Retrieve a dictionary of information about this thread
269   ///
270   /// On Mac OS X systems there may be voucher information.
271   /// The top level dictionary returned will have an "activity" key and the
272   /// value of the activity is a dictionary.  Keys in that dictionary will
273   /// be "name" and "id", among others.
274   /// There may also be "trace_messages" (an array) with each entry in that
275   /// array
276   /// being a dictionary (keys include "message" with the text of the trace
277   /// message).
GetExtendedInfo()278   StructuredData::ObjectSP GetExtendedInfo() {
279     if (!m_extended_info_fetched) {
280       m_extended_info = FetchThreadExtendedInfo();
281       m_extended_info_fetched = true;
282     }
283     return m_extended_info;
284   }
285 
GetName()286   virtual const char *GetName() { return nullptr; }
287 
SetName(const char * name)288   virtual void SetName(const char *name) {}
289 
290   /// Whether this thread can be associated with a libdispatch queue
291   ///
292   /// The Thread may know if it is associated with a libdispatch queue,
293   /// it may know definitively that it is NOT associated with a libdispatch
294   /// queue, or it may be unknown whether it is associated with a libdispatch
295   /// queue.
296   ///
297   /// \return
298   ///     eLazyBoolNo if this thread is definitely not associated with a
299   ///     libdispatch queue (e.g. on a non-Darwin system where GCD aka
300   ///     libdispatch is not available).
301   ///
302   ///     eLazyBoolYes this thread is associated with a libdispatch queue.
303   ///
304   ///     eLazyBoolCalculate this thread may be associated with a libdispatch
305   ///     queue but the thread doesn't know one way or the other.
GetAssociatedWithLibdispatchQueue()306   virtual lldb_private::LazyBool GetAssociatedWithLibdispatchQueue() {
307     return eLazyBoolNo;
308   }
309 
SetAssociatedWithLibdispatchQueue(lldb_private::LazyBool associated_with_libdispatch_queue)310   virtual void SetAssociatedWithLibdispatchQueue(
311       lldb_private::LazyBool associated_with_libdispatch_queue) {}
312 
313   /// Retrieve the Queue ID for the queue currently using this Thread
314   ///
315   /// If this Thread is doing work on behalf of a libdispatch/GCD queue,
316   /// retrieve the QueueID.
317   ///
318   /// This is a unique identifier for the libdispatch/GCD queue in a
319   /// process.  Often starting at 1 for the initial system-created
320   /// queues and incrementing, a QueueID will not be reused for a
321   /// different queue during the lifetime of a process.
322   ///
323   /// \return
324   ///     A QueueID if the Thread subclass implements this, else
325   ///     LLDB_INVALID_QUEUE_ID.
GetQueueID()326   virtual lldb::queue_id_t GetQueueID() { return LLDB_INVALID_QUEUE_ID; }
327 
SetQueueID(lldb::queue_id_t new_val)328   virtual void SetQueueID(lldb::queue_id_t new_val) {}
329 
330   /// Retrieve the Queue name for the queue currently using this Thread
331   ///
332   /// If this Thread is doing work on behalf of a libdispatch/GCD queue,
333   /// retrieve the Queue name.
334   ///
335   /// \return
336   ///     The Queue name, if the Thread subclass implements this, else
337   ///     nullptr.
GetQueueName()338   virtual const char *GetQueueName() { return nullptr; }
339 
SetQueueName(const char * name)340   virtual void SetQueueName(const char *name) {}
341 
342   /// Retrieve the Queue kind for the queue currently using this Thread
343   ///
344   /// If this Thread is doing work on behalf of a libdispatch/GCD queue,
345   /// retrieve the Queue kind - either eQueueKindSerial or
346   /// eQueueKindConcurrent, indicating that this queue processes work
347   /// items serially or concurrently.
348   ///
349   /// \return
350   ///     The Queue kind, if the Thread subclass implements this, else
351   ///     eQueueKindUnknown.
GetQueueKind()352   virtual lldb::QueueKind GetQueueKind() { return lldb::eQueueKindUnknown; }
353 
SetQueueKind(lldb::QueueKind kind)354   virtual void SetQueueKind(lldb::QueueKind kind) {}
355 
356   /// Retrieve the Queue for this thread, if any.
357   ///
358   /// \return
359   ///     A QueueSP for the queue that is currently associated with this
360   ///     thread.
361   ///     An empty shared pointer indicates that this thread is not
362   ///     associated with a queue, or libdispatch queues are not
363   ///     supported on this target.
GetQueue()364   virtual lldb::QueueSP GetQueue() { return lldb::QueueSP(); }
365 
366   /// Retrieve the address of the libdispatch_queue_t struct for queue
367   /// currently using this Thread
368   ///
369   /// If this Thread is doing work on behalf of a libdispatch/GCD queue,
370   /// retrieve the address of the libdispatch_queue_t structure describing
371   /// the queue.
372   ///
373   /// This address may be reused for different queues later in the Process
374   /// lifetime and should not be used to identify a queue uniquely.  Use
375   /// the GetQueueID() call for that.
376   ///
377   /// \return
378   ///     The Queue's libdispatch_queue_t address if the Thread subclass
379   ///     implements this, else LLDB_INVALID_ADDRESS.
GetQueueLibdispatchQueueAddress()380   virtual lldb::addr_t GetQueueLibdispatchQueueAddress() {
381     return LLDB_INVALID_ADDRESS;
382   }
383 
SetQueueLibdispatchQueueAddress(lldb::addr_t dispatch_queue_t)384   virtual void SetQueueLibdispatchQueueAddress(lldb::addr_t dispatch_queue_t) {}
385 
386   /// When a thread stops at an enabled BreakpointSite that has not executed,
387   /// the Process plugin should call SetThreadStoppedAtUnexecutedBP(pc).
388   /// If that BreakpointSite was actually triggered (the instruction was
389   /// executed, for a software breakpoint), regardless of whether the
390   /// breakpoint is valid for this thread, SetThreadHitBreakpointSite()
391   /// should be called to record that fact.
392   ///
393   /// Depending on the structure of the Process plugin, it may be easiest
394   /// to call SetThreadStoppedAtUnexecutedBP(pc) unconditionally when at
395   /// a BreakpointSite, and later when it is known that it was triggered,
396   /// SetThreadHitBreakpointSite() can be called.  These two methods
397   /// overwrite the same piece of state in the Thread, the last one
398   /// called on a Thread wins.
SetThreadStoppedAtUnexecutedBP(lldb::addr_t pc)399   void SetThreadStoppedAtUnexecutedBP(lldb::addr_t pc) {
400     m_stopped_at_unexecuted_bp = pc;
401   }
SetThreadHitBreakpointSite()402   void SetThreadHitBreakpointSite() {
403     m_stopped_at_unexecuted_bp = LLDB_INVALID_ADDRESS;
404   }
405 
406   /// Whether this Thread already has all the Queue information cached or not
407   ///
408   /// A Thread may be associated with a libdispatch work Queue at a given
409   /// public stop event.  If so, the thread can satisify requests like
410   /// GetQueueLibdispatchQueueAddress, GetQueueKind, GetQueueName, and
411   /// GetQueueID
412   /// either from information from the remote debug stub when it is initially
413   /// created, or it can query the SystemRuntime for that information.
414   ///
415   /// This method allows the SystemRuntime to discover if a thread has this
416   /// information already, instead of calling the thread to get the information
417   /// and having the thread call the SystemRuntime again.
ThreadHasQueueInformation()418   virtual bool ThreadHasQueueInformation() const { return false; }
419 
420   /// GetStackFrameCount can be expensive.  Stacks can get very deep, and they
421   /// require memory reads for each frame.  So only use GetStackFrameCount when
422   /// you need to know the depth of the stack.  When iterating over frames, its
423   /// better to generate the frames one by one with GetFrameAtIndex, and when
424   /// that returns NULL, you are at the end of the stack.  That way your loop
425   /// will only do the work it needs to, without forcing lldb to realize
426   /// StackFrames you weren't going to look at.
GetStackFrameCount()427   virtual uint32_t GetStackFrameCount() {
428     return GetStackFrameList()->GetNumFrames();
429   }
430 
GetStackFrameAtIndex(uint32_t idx)431   virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx) {
432     return GetStackFrameList()->GetFrameAtIndex(idx);
433   }
434 
435   virtual lldb::StackFrameSP
436   GetFrameWithConcreteFrameIndex(uint32_t unwind_idx);
437 
DecrementCurrentInlinedDepth()438   bool DecrementCurrentInlinedDepth() {
439     return GetStackFrameList()->DecrementCurrentInlinedDepth();
440   }
441 
GetCurrentInlinedDepth()442   uint32_t GetCurrentInlinedDepth() {
443     return GetStackFrameList()->GetCurrentInlinedDepth();
444   }
445 
446   Status ReturnFromFrameWithIndex(uint32_t frame_idx,
447                                   lldb::ValueObjectSP return_value_sp,
448                                   bool broadcast = false);
449 
450   Status ReturnFromFrame(lldb::StackFrameSP frame_sp,
451                          lldb::ValueObjectSP return_value_sp,
452                          bool broadcast = false);
453 
454   Status JumpToLine(const FileSpec &file, uint32_t line,
455                     bool can_leave_function, std::string *warnings = nullptr);
456 
GetFrameWithStackID(const StackID & stack_id)457   virtual lldb::StackFrameSP GetFrameWithStackID(const StackID &stack_id) {
458     if (stack_id.IsValid())
459       return GetStackFrameList()->GetFrameWithStackID(stack_id);
460     return lldb::StackFrameSP();
461   }
462 
463   // Only pass true to select_most_relevant if you are fulfilling an explicit
464   // user request for GetSelectedFrameIndex.  The most relevant frame is only
465   // for showing to the user, and can do arbitrary work, so we don't want to
466   // call it internally.
GetSelectedFrameIndex(SelectMostRelevant select_most_relevant)467   uint32_t GetSelectedFrameIndex(SelectMostRelevant select_most_relevant) {
468     return GetStackFrameList()->GetSelectedFrameIndex(select_most_relevant);
469   }
470 
471   lldb::StackFrameSP
472   GetSelectedFrame(SelectMostRelevant select_most_relevant);
473 
474   uint32_t SetSelectedFrame(lldb_private::StackFrame *frame,
475                             bool broadcast = false);
476 
477   bool SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast = false);
478 
479   bool SetSelectedFrameByIndexNoisily(uint32_t frame_idx,
480                                       Stream &output_stream);
481 
482   /// Resets the selected frame index of this object.
ClearSelectedFrameIndex()483   void ClearSelectedFrameIndex() {
484     return GetStackFrameList()->ClearSelectedFrameIndex();
485   }
486 
SetDefaultFileAndLineToSelectedFrame()487   void SetDefaultFileAndLineToSelectedFrame() {
488     GetStackFrameList()->SetDefaultFileAndLineToSelectedFrame();
489   }
490 
491   virtual lldb::RegisterContextSP GetRegisterContext() = 0;
492 
493   virtual lldb::RegisterContextSP
494   CreateRegisterContextForFrame(StackFrame *frame) = 0;
495 
496   virtual void ClearStackFrames();
497 
498   /// Sets the thread that is backed by this thread.
499   /// If backed_thread.GetBackedThread() is null, this method also calls
500   /// backed_thread.SetBackingThread(this).
501   /// If backed_thread.GetBackedThread() is non-null, asserts that it is equal
502   /// to `this`.
SetBackedThread(Thread & backed_thread)503   void SetBackedThread(Thread &backed_thread) {
504     m_backed_thread = backed_thread.shared_from_this();
505 
506     // Ensure the bidrectional relationship is preserved.
507     Thread *backing_thread = backed_thread.GetBackingThread().get();
508     assert(backing_thread == nullptr || backing_thread == this);
509     if (backing_thread == nullptr)
510       backed_thread.SetBackingThread(shared_from_this());
511   }
512 
ClearBackedThread()513   void ClearBackedThread() { m_backed_thread.reset(); }
514 
515   /// Returns the thread that is backed by this thread, if any.
GetBackedThread()516   lldb::ThreadSP GetBackedThread() const { return m_backed_thread.lock(); }
517 
SetBackingThread(const lldb::ThreadSP & thread_sp)518   virtual bool SetBackingThread(const lldb::ThreadSP &thread_sp) {
519     return false;
520   }
521 
GetBackingThread()522   virtual lldb::ThreadSP GetBackingThread() const { return lldb::ThreadSP(); }
523 
ClearBackingThread()524   virtual void ClearBackingThread() {
525     // Subclasses can use this function if a thread is actually backed by
526     // another thread. This is currently used for the OperatingSystem plug-ins
527     // where they might have a thread that is in memory, yet its registers are
528     // available through the lldb_private::Thread subclass for the current
529     // lldb_private::Process class. Since each time the process stops the
530     // backing threads for memory threads can change, we need a way to clear
531     // the backing thread for all memory threads each time we stop.
532   }
533 
534   /// Dump \a count instructions of the thread's \a Trace starting at the \a
535   /// start_position position in reverse order.
536   ///
537   /// The instructions are indexed in reverse order, which means that the \a
538   /// start_position 0 represents the last instruction of the trace
539   /// chronologically.
540   ///
541   /// \param[in] s
542   ///   The stream object where the instructions are printed.
543   ///
544   /// \param[in] count
545   ///     The number of instructions to print.
546   ///
547   /// \param[in] start_position
548   ///     The position of the first instruction to print.
549   void DumpTraceInstructions(Stream &s, size_t count,
550                              size_t start_position = 0) const;
551 
552   /// Print a description of this thread using the provided thread format.
553   ///
554   /// \param[out] strm
555   ///   The Stream to print the description to.
556   ///
557   /// \param[in] frame_idx
558   ///   If not \b LLDB_INVALID_FRAME_ID, then use this frame index as context to
559   ///   generate the description.
560   ///
561   /// \param[in] format
562   ///   The input format.
563   ///
564   /// \return
565   ///   \b true if and only if dumping with the given \p format worked.
566   bool DumpUsingFormat(Stream &strm, uint32_t frame_idx,
567                        const FormatEntity::Entry *format);
568 
569   // If stop_format is true, this will be the form used when we print stop
570   // info. If false, it will be the form we use for thread list and co.
571   void DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
572                                bool stop_format);
573 
574   bool GetDescription(Stream &s, lldb::DescriptionLevel level,
575                       bool print_json_thread, bool print_json_stopinfo);
576 
577   /// Default implementation for stepping into.
578   ///
579   /// This function is designed to be used by commands where the
580   /// process is publicly stopped.
581   ///
582   /// \param[in] source_step
583   ///     If true and the frame has debug info, then do a source level
584   ///     step in, else do a single instruction step in.
585   ///
586   /// \param[in] step_in_avoids_code_without_debug_info
587   ///     If \a true, then avoid stepping into code that doesn't have
588   ///     debug info, else step into any code regardless of whether it
589   ///     has debug info.
590   ///
591   /// \param[in] step_out_avoids_code_without_debug_info
592   ///     If \a true, then if you step out to code with no debug info, keep
593   ///     stepping out till you get to code with debug info.
594   ///
595   /// \return
596   ///     An error that describes anything that went wrong
597   virtual Status
598   StepIn(bool source_step,
599          LazyBool step_in_avoids_code_without_debug_info = eLazyBoolCalculate,
600          LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate);
601 
602   /// Default implementation for stepping over.
603   ///
604   /// This function is designed to be used by commands where the
605   /// process is publicly stopped.
606   ///
607   /// \param[in] source_step
608   ///     If true and the frame has debug info, then do a source level
609   ///     step over, else do a single instruction step over.
610   ///
611   /// \return
612   ///     An error that describes anything that went wrong
613   virtual Status StepOver(
614       bool source_step,
615       LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate);
616 
617   /// Default implementation for stepping out.
618   ///
619   /// This function is designed to be used by commands where the
620   /// process is publicly stopped.
621   ///
622   /// \param[in] frame_idx
623   ///     The frame index to step out of.
624   ///
625   /// \return
626   ///     An error that describes anything that went wrong
627   virtual Status StepOut(uint32_t frame_idx = 0);
628 
629   /// Retrieves the per-thread data area.
630   /// Most OSs maintain a per-thread pointer (e.g. the FS register on
631   /// x64), which we return the value of here.
632   ///
633   /// \return
634   ///     LLDB_INVALID_ADDRESS if not supported, otherwise the thread
635   ///     pointer value.
636   virtual lldb::addr_t GetThreadPointer();
637 
638   /// Retrieves the per-module TLS block for a thread.
639   ///
640   /// \param[in] module
641   ///     The module to query TLS data for.
642   ///
643   /// \param[in] tls_file_addr
644   ///     The thread local address in module
645   /// \return
646   ///     If the thread has TLS data allocated for the
647   ///     module, the address of the TLS block. Otherwise
648   ///     LLDB_INVALID_ADDRESS is returned.
649   virtual lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module,
650                                           lldb::addr_t tls_file_addr);
651 
652   /// Check whether this thread is safe to run functions
653   ///
654   /// The SystemRuntime may know of certain thread states (functions in
655   /// process of execution, for instance) which can make it unsafe for
656   /// functions to be called.
657   ///
658   /// \return
659   ///     True if it is safe to call functions on this thread.
660   ///     False if function calls should be avoided on this thread.
661   virtual bool SafeToCallFunctions();
662 
663   // Thread Plan Providers:
664   // This section provides the basic thread plans that the Process control
665   // machinery uses to run the target.  ThreadPlan.h provides more details on
666   // how this mechanism works. The thread provides accessors to a set of plans
667   // that perform basic operations. The idea is that particular Platform
668   // plugins can override these methods to provide the implementation of these
669   // basic operations appropriate to their environment.
670   //
671   // NB: All the QueueThreadPlanXXX providers return Shared Pointers to
672   // Thread plans.  This is useful so that you can modify the plans after
673   // creation in ways specific to that plan type.  Also, it is often necessary
674   // for ThreadPlans that utilize other ThreadPlans to implement their task to
675   // keep a shared pointer to the sub-plan. But besides that, the shared
676   // pointers should only be held onto by entities who live no longer than the
677   // thread containing the ThreadPlan.
678   // FIXME: If this becomes a problem, we can make a version that just returns a
679   // pointer,
680   // which it is clearly unsafe to hold onto, and a shared pointer version, and
681   // only allow ThreadPlan and Co. to use the latter.  That is made more
682   // annoying to do because there's no elegant way to friend a method to all
683   // sub-classes of a given class.
684   //
685 
686   /// Queues the base plan for a thread.
687   /// The version returned by Process does some things that are useful,
688   /// like handle breakpoints and signals, so if you return a plugin specific
689   /// one you probably want to call through to the Process one for anything
690   /// your plugin doesn't explicitly handle.
691   ///
692   /// \param[in] abort_other_plans
693   ///    \b true if we discard the currently queued plans and replace them with
694   ///    this one.
695   ///    Otherwise this plan will go on the end of the plan stack.
696   ///
697   /// \return
698   ///     A shared pointer to the newly queued thread plan, or nullptr if the
699   ///     plan could not be queued.
700   lldb::ThreadPlanSP QueueBasePlan(bool abort_other_plans);
701 
702   /// Queues the plan used to step one instruction from the current PC of \a
703   /// thread.
704   ///
705   /// \param[in] step_over
706   ///    \b true if we step over calls to functions, false if we step in.
707   ///
708   /// \param[in] abort_other_plans
709   ///    \b true if we discard the currently queued plans and replace them with
710   ///    this one.
711   ///    Otherwise this plan will go on the end of the plan stack.
712   ///
713   /// \param[in] stop_other_threads
714   ///    \b true if we will stop other threads while we single step this one.
715   ///
716   /// \param[out] status
717   ///     A status with an error if queuing failed.
718   ///
719   /// \return
720   ///     A shared pointer to the newly queued thread plan, or nullptr if the
721   ///     plan could not be queued.
722   virtual lldb::ThreadPlanSP QueueThreadPlanForStepSingleInstruction(
723       bool step_over, bool abort_other_plans, bool stop_other_threads,
724       Status &status);
725 
726   /// Queues the plan used to step through an address range, stepping  over
727   /// function calls.
728   ///
729   /// \param[in] abort_other_plans
730   ///    \b true if we discard the currently queued plans and replace them with
731   ///    this one.
732   ///    Otherwise this plan will go on the end of the plan stack.
733   ///
734   /// \param[in] type
735   ///    Type of step to do, only eStepTypeInto and eStepTypeOver are supported
736   ///    by this plan.
737   ///
738   /// \param[in] range
739   ///    The address range to step through.
740   ///
741   /// \param[in] addr_context
742   ///    When dealing with stepping through inlined functions the current PC is
743   ///    not enough information to know
744   ///    what "step" means.  For instance a series of nested inline functions
745   ///    might start at the same address.
746   //     The \a addr_context provides the current symbol context the step
747   ///    is supposed to be out of.
748   //   FIXME: Currently unused.
749   ///
750   /// \param[in] stop_other_threads
751   ///    \b true if we will stop other threads while we single step this one.
752   ///
753   /// \param[out] status
754   ///     A status with an error if queuing failed.
755   ///
756   /// \param[in] step_out_avoids_code_without_debug_info
757   ///    If eLazyBoolYes, if the step over steps out it will continue to step
758   ///    out till it comes to a frame with debug info.
759   ///    If eLazyBoolCalculate, we will consult the default set in the thread.
760   ///
761   /// \return
762   ///     A shared pointer to the newly queued thread plan, or nullptr if the
763   ///     plan could not be queued.
764   virtual lldb::ThreadPlanSP QueueThreadPlanForStepOverRange(
765       bool abort_other_plans, const AddressRange &range,
766       const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
767       Status &status,
768       LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate);
769 
770   // Helper function that takes a LineEntry to step, insted of an AddressRange.
771   // This may combine multiple LineEntries of the same source line number to
772   // step over a longer address range in a single operation.
773   virtual lldb::ThreadPlanSP QueueThreadPlanForStepOverRange(
774       bool abort_other_plans, const LineEntry &line_entry,
775       const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
776       Status &status,
777       LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate);
778 
779   /// Queues the plan used to step through an address range, stepping into
780   /// functions.
781   ///
782   /// \param[in] abort_other_plans
783   ///    \b true if we discard the currently queued plans and replace them with
784   ///    this one.
785   ///    Otherwise this plan will go on the end of the plan stack.
786   ///
787   /// \param[in] type
788   ///    Type of step to do, only eStepTypeInto and eStepTypeOver are supported
789   ///    by this plan.
790   ///
791   /// \param[in] range
792   ///    The address range to step through.
793   ///
794   /// \param[in] addr_context
795   ///    When dealing with stepping through inlined functions the current PC is
796   ///    not enough information to know
797   ///    what "step" means.  For instance a series of nested inline functions
798   ///    might start at the same address.
799   //     The \a addr_context provides the current symbol context the step
800   ///    is supposed to be out of.
801   //   FIXME: Currently unused.
802   ///
803   /// \param[in] step_in_target
804   ///    Name if function we are trying to step into.  We will step out if we
805   ///    don't land in that function.
806   ///
807   /// \param[in] stop_other_threads
808   ///    \b true if we will stop other threads while we single step this one.
809   ///
810   /// \param[out] status
811   ///     A status with an error if queuing failed.
812   ///
813   /// \param[in] step_in_avoids_code_without_debug_info
814   ///    If eLazyBoolYes we will step out if we step into code with no debug
815   ///    info.
816   ///    If eLazyBoolCalculate we will consult the default set in the thread.
817   ///
818   /// \param[in] step_out_avoids_code_without_debug_info
819   ///    If eLazyBoolYes, if the step over steps out it will continue to step
820   ///    out till it comes to a frame with debug info.
821   ///    If eLazyBoolCalculate, it will consult the default set in the thread.
822   ///
823   /// \return
824   ///     A shared pointer to the newly queued thread plan, or nullptr if the
825   ///     plan could not be queued.
826   virtual lldb::ThreadPlanSP QueueThreadPlanForStepInRange(
827       bool abort_other_plans, const AddressRange &range,
828       const SymbolContext &addr_context, const char *step_in_target,
829       lldb::RunMode stop_other_threads, Status &status,
830       LazyBool step_in_avoids_code_without_debug_info = eLazyBoolCalculate,
831       LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate);
832 
833   // Helper function that takes a LineEntry to step, insted of an AddressRange.
834   // This may combine multiple LineEntries of the same source line number to
835   // step over a longer address range in a single operation.
836   virtual lldb::ThreadPlanSP QueueThreadPlanForStepInRange(
837       bool abort_other_plans, const LineEntry &line_entry,
838       const SymbolContext &addr_context, const char *step_in_target,
839       lldb::RunMode stop_other_threads, Status &status,
840       LazyBool step_in_avoids_code_without_debug_info = eLazyBoolCalculate,
841       LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate);
842 
843   /// Queue the plan used to step out of the function at the current PC of
844   /// \a thread.
845   ///
846   /// \param[in] abort_other_plans
847   ///    \b true if we discard the currently queued plans and replace them with
848   ///    this one.
849   ///    Otherwise this plan will go on the end of the plan stack.
850   ///
851   /// \param[in] addr_context
852   ///    When dealing with stepping through inlined functions the current PC is
853   ///    not enough information to know
854   ///    what "step" means.  For instance a series of nested inline functions
855   ///    might start at the same address.
856   //     The \a addr_context provides the current symbol context the step
857   ///    is supposed to be out of.
858   //   FIXME: Currently unused.
859   ///
860   /// \param[in] first_insn
861   ///     \b true if this is the first instruction of a function.
862   ///
863   /// \param[in] stop_other_threads
864   ///    \b true if we will stop other threads while we single step this one.
865   ///
866   /// \param[in] report_stop_vote
867   ///    See standard meanings for the stop & run votes in ThreadPlan.h.
868   ///
869   /// \param[in] report_run_vote
870   ///    See standard meanings for the stop & run votes in ThreadPlan.h.
871   ///
872   /// \param[out] status
873   ///     A status with an error if queuing failed.
874   ///
875   /// \param[in] step_out_avoids_code_without_debug_info
876   ///    If eLazyBoolYes, if the step over steps out it will continue to step
877   ///    out till it comes to a frame with debug info.
878   ///    If eLazyBoolCalculate, it will consult the default set in the thread.
879   ///
880   /// \return
881   ///     A shared pointer to the newly queued thread plan, or nullptr if the
882   ///     plan could not be queued.
883   virtual lldb::ThreadPlanSP QueueThreadPlanForStepOut(
884       bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
885       bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
886       uint32_t frame_idx, Status &status,
887       LazyBool step_out_avoids_code_without_debug_info = eLazyBoolCalculate);
888 
889   /// Queue the plan used to step out of the function at the current PC of
890   /// a thread.  This version does not consult the should stop here callback,
891   /// and should only
892   /// be used by other thread plans when they need to retain control of the step
893   /// out.
894   ///
895   /// \param[in] abort_other_plans
896   ///    \b true if we discard the currently queued plans and replace them with
897   ///    this one.
898   ///    Otherwise this plan will go on the end of the plan stack.
899   ///
900   /// \param[in] addr_context
901   ///    When dealing with stepping through inlined functions the current PC is
902   ///    not enough information to know
903   ///    what "step" means.  For instance a series of nested inline functions
904   ///    might start at the same address.
905   //     The \a addr_context provides the current symbol context the step
906   ///    is supposed to be out of.
907   //   FIXME: Currently unused.
908   ///
909   /// \param[in] first_insn
910   ///     \b true if this is the first instruction of a function.
911   ///
912   /// \param[in] stop_other_threads
913   ///    \b true if we will stop other threads while we single step this one.
914   ///
915   /// \param[in] report_stop_vote
916   ///    See standard meanings for the stop & run votes in ThreadPlan.h.
917   ///
918   /// \param[in] report_run_vote
919   ///    See standard meanings for the stop & run votes in ThreadPlan.h.
920   ///
921   /// \param[in] frame_idx
922   ///     The frame index.
923   ///
924   /// \param[out] status
925   ///     A status with an error if queuing failed.
926   ///
927   /// \param[in] continue_to_next_branch
928   ///    Normally this will enqueue a plan that will put a breakpoint on the
929   ///    return address and continue
930   ///    to there.  If continue_to_next_branch is true, this is an operation not
931   ///    involving the user --
932   ///    e.g. stepping "next" in a source line and we instruction stepped into
933   ///    another function --
934   ///    so instead of putting a breakpoint on the return address, advance the
935   ///    breakpoint to the
936   ///    end of the source line that is doing the call, or until the next flow
937   ///    control instruction.
938   ///    If the return value from the function call is to be retrieved /
939   ///    displayed to the user, you must stop
940   ///    on the return address.  The return value may be stored in volatile
941   ///    registers which are overwritten
942   ///    before the next branch instruction.
943   ///
944   /// \return
945   ///     A shared pointer to the newly queued thread plan, or nullptr if the
946   ///     plan could not be queued.
947   virtual lldb::ThreadPlanSP QueueThreadPlanForStepOutNoShouldStop(
948       bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
949       bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
950       uint32_t frame_idx, Status &status, bool continue_to_next_branch = false);
951 
952   /// Gets the plan used to step through the code that steps from a function
953   /// call site at the current PC into the actual function call.
954   ///
955   /// \param[in] return_stack_id
956   ///    The stack id that we will return to (by setting backstop breakpoints on
957   ///    the return
958   ///    address to that frame) if we fail to step through.
959   ///
960   /// \param[in] abort_other_plans
961   ///    \b true if we discard the currently queued plans and replace them with
962   ///    this one.
963   ///    Otherwise this plan will go on the end of the plan stack.
964   ///
965   /// \param[in] stop_other_threads
966   ///    \b true if we will stop other threads while we single step this one.
967   ///
968   /// \param[out] status
969   ///     A status with an error if queuing failed.
970   ///
971   /// \return
972   ///     A shared pointer to the newly queued thread plan, or nullptr if the
973   ///     plan could not be queued.
974   virtual lldb::ThreadPlanSP
975   QueueThreadPlanForStepThrough(StackID &return_stack_id,
976                                 bool abort_other_plans, bool stop_other_threads,
977                                 Status &status);
978 
979   /// Gets the plan used to continue from the current PC.
980   /// This is a simple plan, mostly useful as a backstop when you are continuing
981   /// for some particular purpose.
982   ///
983   /// \param[in] abort_other_plans
984   ///    \b true if we discard the currently queued plans and replace them with
985   ///    this one.
986   ///    Otherwise this plan will go on the end of the plan stack.
987   ///
988   /// \param[in] target_addr
989   ///    The address to which we're running.
990   ///
991   /// \param[in] stop_other_threads
992   ///    \b true if we will stop other threads while we single step this one.
993   ///
994   /// \param[out] status
995   ///     A status with an error if queuing failed.
996   ///
997   /// \return
998   ///     A shared pointer to the newly queued thread plan, or nullptr if the
999   ///     plan could not be queued.
1000   virtual lldb::ThreadPlanSP
1001   QueueThreadPlanForRunToAddress(bool abort_other_plans, Address &target_addr,
1002                                  bool stop_other_threads, Status &status);
1003 
1004   virtual lldb::ThreadPlanSP QueueThreadPlanForStepUntil(
1005       bool abort_other_plans, lldb::addr_t *address_list, size_t num_addresses,
1006       bool stop_others, uint32_t frame_idx, Status &status);
1007 
1008   virtual lldb::ThreadPlanSP
1009   QueueThreadPlanForStepScripted(bool abort_other_plans, const char *class_name,
1010                                  StructuredData::ObjectSP extra_args_sp,
1011                                  bool stop_other_threads, Status &status);
1012 
1013   // Thread Plan accessors:
1014 
1015   /// Format the thread plan information for auto completion.
1016   ///
1017   /// \param[in] request
1018   ///     The reference to the completion handler.
1019   void AutoCompleteThreadPlans(CompletionRequest &request) const;
1020 
1021   /// Gets the plan which will execute next on the plan stack.
1022   ///
1023   /// \return
1024   ///     A pointer to the next executed plan.
1025   ThreadPlan *GetCurrentPlan() const;
1026 
1027   /// Unwinds the thread stack for the innermost expression plan currently
1028   /// on the thread plan stack.
1029   ///
1030   /// \return
1031   ///     An error if the thread plan could not be unwound.
1032 
1033   Status UnwindInnermostExpression();
1034 
1035   /// Gets the outer-most plan that was popped off the plan stack in the
1036   /// most recent stop.  Useful for printing the stop reason accurately.
1037   ///
1038   /// \return
1039   ///     A pointer to the last completed plan.
1040   lldb::ThreadPlanSP GetCompletedPlan() const;
1041 
1042   /// Gets the outer-most return value from the completed plans
1043   ///
1044   /// \return
1045   ///     A ValueObjectSP, either empty if there is no return value,
1046   ///     or containing the return value.
1047   lldb::ValueObjectSP GetReturnValueObject() const;
1048 
1049   /// Gets the outer-most expression variable from the completed plans
1050   ///
1051   /// \return
1052   ///     A ExpressionVariableSP, either empty if there is no
1053   ///     plan completed an expression during the current stop
1054   ///     or the expression variable that was made for the completed expression.
1055   lldb::ExpressionVariableSP GetExpressionVariable() const;
1056 
1057   ///  Checks whether the given plan is in the completed plans for this
1058   ///  stop.
1059   ///
1060   /// \param[in] plan
1061   ///     Pointer to the plan you're checking.
1062   ///
1063   /// \return
1064   ///     Returns true if the input plan is in the completed plan stack,
1065   ///     false otherwise.
1066   bool IsThreadPlanDone(ThreadPlan *plan) const;
1067 
1068   ///  Checks whether the given plan is in the discarded plans for this
1069   ///  stop.
1070   ///
1071   /// \param[in] plan
1072   ///     Pointer to the plan you're checking.
1073   ///
1074   /// \return
1075   ///     Returns true if the input plan is in the discarded plan stack,
1076   ///     false otherwise.
1077   bool WasThreadPlanDiscarded(ThreadPlan *plan) const;
1078 
1079   /// Check if we have completed plan to override breakpoint stop reason
1080   ///
1081   /// \return
1082   ///     Returns true if completed plan stack is not empty
1083   ///     false otherwise.
1084   bool CompletedPlanOverridesBreakpoint() const;
1085 
1086   /// Queues a generic thread plan.
1087   ///
1088   /// \param[in] plan_sp
1089   ///    The plan to queue.
1090   ///
1091   /// \param[in] abort_other_plans
1092   ///    \b true if we discard the currently queued plans and replace them with
1093   ///    this one.
1094   ///    Otherwise this plan will go on the end of the plan stack.
1095   ///
1096   /// \return
1097   ///     A pointer to the last completed plan.
1098   Status QueueThreadPlan(lldb::ThreadPlanSP &plan_sp, bool abort_other_plans);
1099 
1100   /// Discards the plans queued on the plan stack of the current thread.  This
1101   /// is
1102   /// arbitrated by the "Controlling" ThreadPlans, using the "OkayToDiscard"
1103   /// call.
1104   //  But if \a force is true, all thread plans are discarded.
1105   void DiscardThreadPlans(bool force);
1106 
1107   /// Discards the plans queued on the plan stack of the current thread up to
1108   /// and
1109   /// including up_to_plan_sp.
1110   //
1111   // \param[in] up_to_plan_sp
1112   //   Discard all plans up to and including this one.
1113   void DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp);
1114 
1115   void DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr);
1116 
1117   /// Discards the plans queued on the plan stack of the current thread up to
1118   /// and
1119   /// including the plan in that matches \a thread_index counting only
1120   /// the non-Private plans.
1121   ///
1122   /// \param[in] thread_index
1123   ///   Discard all plans up to and including this user plan given by this
1124   ///   index.
1125   ///
1126   /// \return
1127   ///    \b true if there was a thread plan with that user index, \b false
1128   ///    otherwise.
1129   bool DiscardUserThreadPlansUpToIndex(uint32_t thread_index);
1130 
1131   virtual bool CheckpointThreadState(ThreadStateCheckpoint &saved_state);
1132 
1133   virtual bool
1134   RestoreRegisterStateFromCheckpoint(ThreadStateCheckpoint &saved_state);
1135 
1136   void RestoreThreadStateFromCheckpoint(ThreadStateCheckpoint &saved_state);
1137 
1138   // Get the thread index ID. The index ID that is guaranteed to not be re-used
1139   // by a process. They start at 1 and increase with each new thread. This
1140   // allows easy command line access by a unique ID that is easier to type than
1141   // the actual system thread ID.
1142   uint32_t GetIndexID() const;
1143 
1144   // Get the originating thread's index ID.
1145   // In the case of an "extended" thread -- a thread which represents the stack
1146   // that enqueued/spawned work that is currently executing -- we need to
1147   // provide the IndexID of the thread that actually did this work.  We don't
1148   // want to just masquerade as that thread's IndexID by using it in our own
1149   // IndexID because that way leads to madness - but the driver program which
1150   // is iterating over extended threads may ask for the OriginatingThreadID to
1151   // display that information to the user.
1152   // Normal threads will return the same thing as GetIndexID();
GetExtendedBacktraceOriginatingIndexID()1153   virtual uint32_t GetExtendedBacktraceOriginatingIndexID() {
1154     return GetIndexID();
1155   }
1156 
1157   // The API ID is often the same as the Thread::GetID(), but not in all cases.
1158   // Thread::GetID() is the user visible thread ID that clients would want to
1159   // see. The API thread ID is the thread ID that is used when sending data
1160   // to/from the debugging protocol.
GetProtocolID()1161   virtual lldb::user_id_t GetProtocolID() const { return GetID(); }
1162 
1163   // lldb::ExecutionContextScope pure virtual functions
1164   lldb::TargetSP CalculateTarget() override;
1165 
1166   lldb::ProcessSP CalculateProcess() override;
1167 
1168   lldb::ThreadSP CalculateThread() override;
1169 
1170   lldb::StackFrameSP CalculateStackFrame() override;
1171 
1172   void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
1173 
1174   lldb::StackFrameSP
1175   GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr);
1176 
1177   size_t GetStatus(Stream &strm, uint32_t start_frame, uint32_t num_frames,
1178                    uint32_t num_frames_with_source, bool stop_format,
1179                    bool show_hidden, bool only_stacks = false);
1180 
1181   size_t GetStackFrameStatus(Stream &strm, uint32_t first_frame,
1182                              uint32_t num_frames, bool show_frame_info,
1183                              uint32_t num_frames_with_source, bool show_hidden);
1184 
1185   // We need a way to verify that even though we have a thread in a shared
1186   // pointer that the object itself is still valid. Currently this won't be the
1187   // case if DestroyThread() was called. DestroyThread is called when a thread
1188   // has been removed from the Process' thread list.
IsValid()1189   bool IsValid() const { return !m_destroy_called; }
1190 
1191   // Sets and returns a valid stop info based on the process stop ID and the
1192   // current thread plan. If the thread stop ID does not match the process'
1193   // stop ID, the private stop reason is not set and an invalid StopInfoSP may
1194   // be returned.
1195   //
1196   // NOTE: This function must be called before the current thread plan is
1197   // moved to the completed plan stack (in Thread::ShouldStop()).
1198   //
1199   // NOTE: If subclasses override this function, ensure they do not overwrite
1200   // the m_actual_stop_info if it is valid.  The stop info may be a
1201   // "checkpointed and restored" stop info, so if it is still around it is
1202   // right even if you have not calculated this yourself, or if it disagrees
1203   // with what you might have calculated.
1204   virtual lldb::StopInfoSP GetPrivateStopInfo(bool calculate = true);
1205 
1206   // Calculate the stop info that will be shown to lldb clients.  For instance,
1207   // a "step out" is implemented by running to a breakpoint on the function
1208   // return PC, so the process plugin initially sets the stop info to a
1209   // StopInfoBreakpoint. But once we've run the ShouldStop machinery, we
1210   // discover that there's a completed ThreadPlanStepOut, and that's really
1211   // the StopInfo we want to show.  That will happen naturally the next
1212   // time GetStopInfo is called, but if you want to force the replacement,
1213   // you can call this.
1214 
1215   void CalculatePublicStopInfo();
1216 
1217   /// Ask the thread subclass to set its stop info.
1218   ///
1219   /// Thread subclasses should call Thread::SetStopInfo(...) with the reason the
1220   /// thread stopped.
1221   ///
1222   /// A thread that is sitting at a breakpoint site, but has not yet executed
1223   /// the breakpoint instruction, should have a breakpoint-hit StopInfo set.
1224   /// When execution is resumed, any thread sitting at a breakpoint site will
1225   /// instruction-step over the breakpoint instruction silently, and we will
1226   /// never record this breakpoint as being hit, updating the hit count,
1227   /// possibly executing breakpoint commands or conditions.
1228   ///
1229   /// \return
1230   ///      True if Thread::SetStopInfo(...) was called, false otherwise.
1231   virtual bool CalculateStopInfo() = 0;
1232 
1233   // Gets the temporary resume state for a thread.
1234   //
1235   // This value gets set in each thread by complex debugger logic in
1236   // Thread::ShouldResume() and an appropriate thread resume state will get set
1237   // in each thread every time the process is resumed prior to calling
1238   // Process::DoResume(). The lldb_private::Process subclass should adhere to
1239   // the thread resume state request which will be one of:
1240   //
1241   //  eStateRunning   - thread will resume when process is resumed
1242   //  eStateStepping  - thread should step 1 instruction and stop when process
1243   //                    is resumed
1244   //  eStateSuspended - thread should not execute any instructions when
1245   //                    process is resumed
GetTemporaryResumeState()1246   lldb::StateType GetTemporaryResumeState() const {
1247     return m_temporary_resume_state;
1248   }
1249 
1250   void SetStopInfo(const lldb::StopInfoSP &stop_info_sp);
1251 
1252   void ResetStopInfo();
1253 
1254   void SetShouldReportStop(Vote vote);
1255 
SetShouldRunBeforePublicStop(bool newval)1256   void SetShouldRunBeforePublicStop(bool newval) {
1257       m_should_run_before_public_stop = newval;
1258   }
1259 
ShouldRunBeforePublicStop()1260   bool ShouldRunBeforePublicStop() {
1261       return m_should_run_before_public_stop;
1262   }
1263 
1264   /// Sets the extended backtrace token for this thread
1265   ///
1266   /// Some Thread subclasses may maintain a token to help with providing
1267   /// an extended backtrace.  The SystemRuntime plugin will set/request this.
1268   ///
1269   /// \param [in] token The extended backtrace token.
SetExtendedBacktraceToken(uint64_t token)1270   virtual void SetExtendedBacktraceToken(uint64_t token) {}
1271 
1272   /// Gets the extended backtrace token for this thread
1273   ///
1274   /// Some Thread subclasses may maintain a token to help with providing
1275   /// an extended backtrace.  The SystemRuntime plugin will set/request this.
1276   ///
1277   /// \return
1278   ///     The token needed by the SystemRuntime to create an extended backtrace.
1279   ///     LLDB_INVALID_ADDRESS is returned if no token is available.
GetExtendedBacktraceToken()1280   virtual uint64_t GetExtendedBacktraceToken() { return LLDB_INVALID_ADDRESS; }
1281 
1282   lldb::ValueObjectSP GetCurrentException();
1283 
1284   lldb::ThreadSP GetCurrentExceptionBacktrace();
1285 
1286   lldb::ValueObjectSP GetSiginfoValue();
1287 
1288   /// Request the pc value the thread had when previously stopped.
1289   ///
1290   /// When the thread performs execution, it copies the current RegisterContext
1291   /// GetPC() value.  This method returns that value, if it is available.
1292   ///
1293   /// \return
1294   ///     The PC value before execution was resumed.  May not be available;
1295   ///     an empty std::optional is returned in that case.
1296   std::optional<lldb::addr_t> GetPreviousFrameZeroPC();
1297 
1298 protected:
1299   friend class ThreadPlan;
1300   friend class ThreadList;
1301   friend class ThreadEventData;
1302   friend class StackFrameList;
1303   friend class StackFrame;
1304   friend class OperatingSystem;
1305 
1306   // This is necessary to make sure thread assets get destroyed while the
1307   // thread is still in good shape to call virtual thread methods.  This must
1308   // be called by classes that derive from Thread in their destructor.
1309   virtual void DestroyThread();
1310 
1311   ThreadPlanStack &GetPlans() const;
1312 
1313   void PushPlan(lldb::ThreadPlanSP plan_sp);
1314 
1315   void PopPlan();
1316 
1317   void DiscardPlan();
1318 
1319   ThreadPlan *GetPreviousPlan(ThreadPlan *plan) const;
1320 
1321   virtual Unwind &GetUnwinder();
1322 
1323   // Check to see whether the thread is still at the last breakpoint hit that
1324   // stopped it.
1325   virtual bool IsStillAtLastBreakpointHit();
1326 
1327   // Some threads are threads that are made up by OperatingSystem plugins that
1328   // are threads that exist and are context switched out into memory. The
1329   // OperatingSystem plug-in need a ways to know if a thread is "real" or made
1330   // up.
IsOperatingSystemPluginThread()1331   virtual bool IsOperatingSystemPluginThread() const { return false; }
1332 
1333   // Subclasses that have a way to get an extended info dictionary for this
1334   // thread should fill
FetchThreadExtendedInfo()1335   virtual lldb_private::StructuredData::ObjectSP FetchThreadExtendedInfo() {
1336     return StructuredData::ObjectSP();
1337   }
1338 
1339   lldb::StackFrameListSP GetStackFrameList();
1340 
SetTemporaryResumeState(lldb::StateType new_state)1341   void SetTemporaryResumeState(lldb::StateType new_state) {
1342     m_temporary_resume_state = new_state;
1343   }
1344 
1345   void FrameSelectedCallback(lldb_private::StackFrame *frame);
1346 
1347   virtual llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
GetSiginfo(size_t max_size)1348   GetSiginfo(size_t max_size) const {
1349     return llvm::make_error<UnimplementedError>();
1350   }
1351 
1352   // Classes that inherit from Process can see and modify these
1353   lldb::ProcessWP m_process_wp;    ///< The process that owns this thread.
1354   lldb::StopInfoSP m_stop_info_sp; ///< The private stop reason for this thread
1355   uint32_t m_stop_info_stop_id; // This is the stop id for which the StopInfo is
1356                                 // valid.  Can use this so you know that
1357   // the thread's m_stop_info_sp is current and you don't have to fetch it
1358   // again
1359   uint32_t m_stop_info_override_stop_id; // The stop ID containing the last time
1360                                          // the stop info was checked against
1361                                          // the stop info override
1362   bool m_should_run_before_public_stop;  // If this thread has "stop others"
1363                                          // private work to do, then it will
1364                                          // set this.
1365   lldb::addr_t m_stopped_at_unexecuted_bp; // Set to the address of a breakpoint
1366                                            // instruction that we have not yet
1367                                            // hit, but will hit when we resume.
1368   const uint32_t m_index_id; ///< A unique 1 based index assigned to each thread
1369                              /// for easy UI/command line access.
1370   lldb::RegisterContextSP m_reg_context_sp; ///< The register context for this
1371                                             ///thread's current register state.
1372   lldb::StateType m_state;                  ///< The state of our process.
1373   mutable std::recursive_mutex
1374       m_state_mutex;       ///< Multithreaded protection for m_state.
1375   mutable std::recursive_mutex
1376       m_frame_mutex; ///< Multithreaded protection for m_state.
1377   lldb::StackFrameListSP m_curr_frames_sp; ///< The stack frames that get lazily
1378                                            ///populated after a thread stops.
1379   lldb::StackFrameListSP m_prev_frames_sp; ///< The previous stack frames from
1380                                            ///the last time this thread stopped.
1381   std::optional<lldb::addr_t>
1382       m_prev_framezero_pc; ///< Frame 0's PC the last
1383                            /// time this thread was stopped.
1384   int m_resume_signal; ///< The signal that should be used when continuing this
1385                        ///thread.
1386   lldb::StateType m_resume_state; ///< This state is used to force a thread to
1387                                   ///be suspended from outside the ThreadPlan
1388                                   ///logic.
1389   lldb::StateType m_temporary_resume_state; ///< This state records what the
1390                                             ///thread was told to do by the
1391                                             ///thread plan logic for the current
1392                                             ///resume.
1393   /// It gets set in Thread::ShouldResume.
1394   std::unique_ptr<lldb_private::Unwind> m_unwinder_up;
1395   bool m_destroy_called; // This is used internally to make sure derived Thread
1396                          // classes call DestroyThread.
1397   LazyBool m_override_should_notify;
1398   mutable std::unique_ptr<ThreadPlanStack> m_null_plan_stack_up;
1399 
1400   /// The Thread backed by this thread, if any.
1401   lldb::ThreadWP m_backed_thread;
1402 
1403 private:
1404   bool m_extended_info_fetched; // Have we tried to retrieve the m_extended_info
1405                                 // for this thread?
1406   StructuredData::ObjectSP m_extended_info; // The extended info for this thread
1407 
1408   void BroadcastSelectedFrameChange(StackID &new_frame_id);
1409 
1410   Thread(const Thread &) = delete;
1411   const Thread &operator=(const Thread &) = delete;
1412 };
1413 
1414 } // namespace lldb_private
1415 
1416 #endif // LLDB_TARGET_THREAD_H
1417