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