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