Thread.h revision 263367
1//===-- Thread.h ------------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef liblldb_Thread_h_
11#define liblldb_Thread_h_
12
13#include "lldb/lldb-private.h"
14#include "lldb/Host/Mutex.h"
15#include "lldb/Core/Broadcaster.h"
16#include "lldb/Core/Event.h"
17#include "lldb/Core/UserID.h"
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
23#define LLDB_THREAD_MAX_STOP_EXC_DATA 8
24
25namespace lldb_private {
26
27class ThreadProperties : public Properties
28{
29public:
30    ThreadProperties(bool is_global);
31
32    virtual
33    ~ThreadProperties();
34
35    //------------------------------------------------------------------
36    /// The regular expression returned determines symbols that this
37    /// thread won't stop in during "step-in" operations.
38    ///
39    /// @return
40    ///    A pointer to a regular expression to compare against symbols,
41    ///    or NULL if all symbols are allowed.
42    ///
43    //------------------------------------------------------------------
44    const RegularExpression *
45    GetSymbolsToAvoidRegexp();
46
47    bool
48    GetTraceEnabledState() const;
49};
50
51typedef std::shared_ptr<ThreadProperties> ThreadPropertiesSP;
52
53class Thread :
54    public std::enable_shared_from_this<Thread>,
55    public ThreadProperties,
56    public UserID,
57    public ExecutionContextScope,
58    public Broadcaster
59{
60public:
61    //------------------------------------------------------------------
62    /// Broadcaster event bits definitions.
63    //------------------------------------------------------------------
64    enum
65    {
66        eBroadcastBitStackChanged           = (1 << 0),
67        eBroadcastBitThreadSuspended        = (1 << 1),
68        eBroadcastBitThreadResumed          = (1 << 2),
69        eBroadcastBitSelectedFrameChanged   = (1 << 3),
70        eBroadcastBitThreadSelected         = (1 << 4)
71    };
72
73    static ConstString &GetStaticBroadcasterClass ();
74
75    virtual ConstString &GetBroadcasterClass() const
76    {
77        return GetStaticBroadcasterClass();
78    }
79
80    class ThreadEventData :
81        public EventData
82    {
83    public:
84        ThreadEventData (const lldb::ThreadSP thread_sp);
85
86        ThreadEventData (const lldb::ThreadSP thread_sp, const StackID &stack_id);
87
88        ThreadEventData();
89
90        virtual ~ThreadEventData();
91
92        static const ConstString &
93        GetFlavorString ();
94
95        virtual const ConstString &
96        GetFlavor () const
97        {
98            return ThreadEventData::GetFlavorString ();
99        }
100
101        virtual void
102        Dump (Stream *s) const;
103
104        static const ThreadEventData *
105        GetEventDataFromEvent (const Event *event_ptr);
106
107        static lldb::ThreadSP
108        GetThreadFromEvent (const Event *event_ptr);
109
110        static StackID
111        GetStackIDFromEvent (const Event *event_ptr);
112
113        static lldb::StackFrameSP
114        GetStackFrameFromEvent (const Event *event_ptr);
115
116        lldb::ThreadSP
117        GetThread () const
118        {
119            return m_thread_sp;
120        }
121
122        StackID
123        GetStackID () const
124        {
125            return m_stack_id;
126        }
127
128    private:
129        lldb::ThreadSP m_thread_sp;
130        StackID        m_stack_id;
131    DISALLOW_COPY_AND_ASSIGN (ThreadEventData);
132    };
133
134
135    struct ThreadStateCheckpoint
136    {
137        uint32_t           orig_stop_id;  // Dunno if I need this yet but it is an interesting bit of data.
138        lldb::StopInfoSP   stop_info_sp;  // You have to restore the stop info or you might continue with the wrong signals.
139        lldb::RegisterCheckpointSP register_backup_sp;  // You need to restore the registers, of course...
140        uint32_t           current_inlined_depth;
141        lldb::addr_t       current_inlined_pc;
142    };
143
144    static void
145    SettingsInitialize ();
146
147    static void
148    SettingsTerminate ();
149
150    static const ThreadPropertiesSP &
151    GetGlobalProperties();
152
153    Thread (Process &process, lldb::tid_t tid);
154    virtual ~Thread();
155
156    lldb::ProcessSP
157    GetProcess() const
158    {
159        return m_process_wp.lock();
160    }
161
162    int
163    GetResumeSignal () const
164    {
165        return m_resume_signal;
166    }
167
168    void
169    SetResumeSignal (int signal)
170    {
171        m_resume_signal = signal;
172    }
173
174    lldb::StateType
175    GetState() const;
176
177    void
178    SetState (lldb::StateType state);
179
180    lldb::StateType
181    GetResumeState () const
182    {
183        return m_resume_state;
184    }
185
186    void
187    SetResumeState (lldb::StateType state)
188    {
189        m_resume_state = state;
190    }
191
192    // This function is called on all the threads before "ShouldResume" and
193    // "WillResume" in case a thread needs to change its state before the
194    // ThreadList polls all the threads to figure out which ones actually
195    // will get to run and how.
196    void
197    SetupForResume ();
198
199    // Do not override this function, it is for thread plan logic only
200    bool
201    ShouldResume (lldb::StateType resume_state);
202
203    // Override this to do platform specific tasks before resume.
204    virtual void
205    WillResume (lldb::StateType resume_state)
206    {
207    }
208
209    // This clears generic thread state after a resume.  If you subclass this,
210    // be sure to call it.
211    virtual void
212    DidResume ();
213
214    // This notifies the thread when a private stop occurs.
215    virtual void
216    DidStop ();
217
218    virtual void
219    RefreshStateAfterStop() = 0;
220
221    void
222    WillStop ();
223
224    bool
225    ShouldStop (Event *event_ptr);
226
227    Vote
228    ShouldReportStop (Event *event_ptr);
229
230    Vote
231    ShouldReportRun (Event *event_ptr);
232
233    void
234    Flush ();
235
236    // Return whether this thread matches the specification in ThreadSpec.  This is a virtual
237    // method because at some point we may extend the thread spec with a platform specific
238    // dictionary of attributes, which then only the platform specific Thread implementation
239    // would know how to match.  For now, this just calls through to the ThreadSpec's
240    // ThreadPassesBasicTests method.
241    virtual bool
242    MatchesSpec (const ThreadSpec *spec);
243
244    lldb::StopInfoSP
245    GetStopInfo ();
246
247    lldb::StopReason
248    GetStopReason();
249
250    // This sets the stop reason to a "blank" stop reason, so you can call functions on the thread
251    // without having the called function run with whatever stop reason you stopped with.
252    void
253    SetStopInfoToNothing();
254
255    bool
256    ThreadStoppedForAReason ();
257
258    static const char *
259    RunModeAsCString (lldb::RunMode mode);
260
261    static const char *
262    StopReasonAsCString (lldb::StopReason reason);
263
264    virtual const char *
265    GetInfo ()
266    {
267        return NULL;
268    }
269
270    virtual const char *
271    GetName ()
272    {
273        return NULL;
274    }
275
276    virtual void
277    SetName (const char *name)
278    {
279    }
280
281    virtual lldb::queue_id_t
282    GetQueueID ()
283    {
284        return LLDB_INVALID_QUEUE_ID;
285    }
286
287    virtual void
288    SetQueueID (lldb::queue_id_t new_val)
289    {
290    }
291
292    virtual const char *
293    GetQueueName ()
294    {
295        return NULL;
296    }
297
298    virtual void
299    SetQueueName (const char *name)
300    {
301    }
302
303    virtual uint32_t
304    GetStackFrameCount()
305    {
306        return GetStackFrameList()->GetNumFrames();
307    }
308
309    virtual lldb::StackFrameSP
310    GetStackFrameAtIndex (uint32_t idx)
311    {
312        return GetStackFrameList()->GetFrameAtIndex(idx);
313    }
314
315    virtual lldb::StackFrameSP
316    GetFrameWithConcreteFrameIndex (uint32_t unwind_idx);
317
318    bool
319    DecrementCurrentInlinedDepth()
320    {
321        return GetStackFrameList()->DecrementCurrentInlinedDepth();
322    }
323
324    uint32_t
325    GetCurrentInlinedDepth()
326    {
327        return GetStackFrameList()->GetCurrentInlinedDepth();
328    }
329
330    Error
331    ReturnFromFrameWithIndex (uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast = false);
332
333    Error
334    ReturnFromFrame (lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast = false);
335
336    Error
337    JumpToLine (const FileSpec &file, uint32_t line, bool can_leave_function, std::string *warnings = NULL);
338
339    virtual lldb::StackFrameSP
340    GetFrameWithStackID (const StackID &stack_id)
341    {
342        if (stack_id.IsValid())
343            return GetStackFrameList()->GetFrameWithStackID (stack_id);
344        return lldb::StackFrameSP();
345    }
346
347    uint32_t
348    GetSelectedFrameIndex ()
349    {
350        return GetStackFrameList()->GetSelectedFrameIndex();
351    }
352
353    lldb::StackFrameSP
354    GetSelectedFrame ()
355    {
356        lldb::StackFrameListSP stack_frame_list_sp(GetStackFrameList());
357        return stack_frame_list_sp->GetFrameAtIndex (stack_frame_list_sp->GetSelectedFrameIndex());
358    }
359
360    uint32_t
361    SetSelectedFrame (lldb_private::StackFrame *frame, bool broadcast = false);
362
363
364    bool
365    SetSelectedFrameByIndex (uint32_t frame_idx, bool broadcast = false);
366
367    bool
368    SetSelectedFrameByIndexNoisily (uint32_t frame_idx, Stream &output_stream);
369
370    void
371    SetDefaultFileAndLineToSelectedFrame()
372    {
373        GetStackFrameList()->SetDefaultFileAndLineToSelectedFrame();
374    }
375
376    virtual lldb::RegisterContextSP
377    GetRegisterContext () = 0;
378
379    virtual lldb::RegisterContextSP
380    CreateRegisterContextForFrame (StackFrame *frame) = 0;
381
382    virtual void
383    ClearStackFrames ();
384
385    virtual bool
386    SetBackingThread (const lldb::ThreadSP &thread_sp)
387    {
388        return false;
389    }
390
391    virtual lldb::ThreadSP
392    GetBackingThread () const
393    {
394        return lldb::ThreadSP();
395    }
396
397    virtual void
398    ClearBackingThread ()
399    {
400        // Subclasses can use this function if a thread is actually backed by
401        // another thread. This is currently used for the OperatingSystem plug-ins
402        // where they might have a thread that is in memory, yet its registers
403        // are available through the lldb_private::Thread subclass for the current
404        // lldb_private::Process class. Since each time the process stops the backing
405        // threads for memory threads can change, we need a way to clear the backing
406        // thread for all memory threads each time we stop.
407    }
408
409    void
410    DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx);
411
412    //------------------------------------------------------------------
413    /// Retrieves the per-thread data area.
414    /// Most OSs maintain a per-thread pointer (e.g. the FS register on
415    /// x64), which we return the value of here.
416    ///
417    /// @return
418    ///     LLDB_INVALID_ADDRESS if not supported, otherwise the thread
419    ///     pointer value.
420    //------------------------------------------------------------------
421    virtual lldb::addr_t
422    GetThreadPointer ();
423
424    //------------------------------------------------------------------
425    /// Retrieves the per-module TLS block for a thread.
426    ///
427    /// @param[in] module
428    ///     The module to query TLS data for.
429    ///
430    /// @return
431    ///     If the thread has TLS data allocated for the
432    ///     module, the address of the TLS block. Otherwise
433    ///     LLDB_INVALID_ADDRESS is returned.
434    //------------------------------------------------------------------
435    virtual lldb::addr_t
436    GetThreadLocalData (const lldb::ModuleSP module);
437
438
439    //------------------------------------------------------------------
440    // Thread Plan Providers:
441    // This section provides the basic thread plans that the Process control
442    // machinery uses to run the target.  ThreadPlan.h provides more details on
443    // how this mechanism works.
444    // The thread provides accessors to a set of plans that perform basic operations.
445    // The idea is that particular Platform plugins can override these methods to
446    // provide the implementation of these basic operations appropriate to their
447    // environment.
448    //
449    // NB: All the QueueThreadPlanXXX providers return Shared Pointers to
450    // Thread plans.  This is useful so that you can modify the plans after
451    // creation in ways specific to that plan type.  Also, it is often necessary for
452    // ThreadPlans that utilize other ThreadPlans to implement their task to keep a shared
453    // pointer to the sub-plan.
454    // But besides that, the shared pointers should only be held onto by entities who live no longer
455    // than the thread containing the ThreadPlan.
456    // FIXME: If this becomes a problem, we can make a version that just returns a pointer,
457    // which it is clearly unsafe to hold onto, and a shared pointer version, and only allow
458    // ThreadPlan and Co. to use the latter.  That is made more annoying to do because there's
459    // no elegant way to friend a method to all sub-classes of a given class.
460    //
461    //------------------------------------------------------------------
462
463    //------------------------------------------------------------------
464    /// Queues the base plan for a thread.
465    /// The version returned by Process does some things that are useful,
466    /// like handle breakpoints and signals, so if you return a plugin specific
467    /// one you probably want to call through to the Process one for anything
468    /// your plugin doesn't explicitly handle.
469    ///
470    /// @param[in] abort_other_plans
471    ///    \b true if we discard the currently queued plans and replace them with this one.
472    ///    Otherwise this plan will go on the end of the plan stack.
473    ///
474    /// @return
475    ///     A shared pointer to the newly queued thread plan, or NULL if the plan could not be queued.
476    //------------------------------------------------------------------
477    virtual lldb::ThreadPlanSP
478    QueueFundamentalPlan (bool abort_other_plans);
479
480    //------------------------------------------------------------------
481    /// Queues the plan used to step one instruction from the current PC of \a thread.
482    ///
483    /// @param[in] step_over
484    ///    \b true if we step over calls to functions, false if we step in.
485    ///
486    /// @param[in] abort_other_plans
487    ///    \b true if we discard the currently queued plans and replace them with this one.
488    ///    Otherwise this plan will go on the end of the plan stack.
489    ///
490    /// @param[in] stop_other_threads
491    ///    \b true if we will stop other threads while we single step this one.
492    ///
493    /// @return
494    ///     A shared pointer to the newly queued thread plan, or NULL if the plan could not be queued.
495    //------------------------------------------------------------------
496    virtual lldb::ThreadPlanSP
497    QueueThreadPlanForStepSingleInstruction (bool step_over,
498                                             bool abort_other_plans,
499                                             bool stop_other_threads);
500
501    //------------------------------------------------------------------
502    /// Queues the plan used to step through an address range, stepping  over
503    /// function calls.
504    ///
505    /// @param[in] abort_other_plans
506    ///    \b true if we discard the currently queued plans and replace them with this one.
507    ///    Otherwise this plan will go on the end of the plan stack.
508    ///
509    /// @param[in] type
510    ///    Type of step to do, only eStepTypeInto and eStepTypeOver are supported by this plan.
511    ///
512    /// @param[in] range
513    ///    The address range to step through.
514    ///
515    /// @param[in] addr_context
516    ///    When dealing with stepping through inlined functions the current PC is not enough information to know
517    ///    what "step" means.  For instance a series of nested inline functions might start at the same address.
518    //     The \a addr_context provides the current symbol context the step
519    ///    is supposed to be out of.
520    //   FIXME: Currently unused.
521    ///
522    /// @param[in] stop_other_threads
523    ///    \b true if we will stop other threads while we single step this one.
524    ///
525    /// @return
526    ///     A shared pointer to the newly queued thread plan, or NULL if the plan could not be queued.
527    //------------------------------------------------------------------
528    virtual lldb::ThreadPlanSP
529    QueueThreadPlanForStepOverRange (bool abort_other_plans,
530                                 const AddressRange &range,
531                                 const SymbolContext &addr_context,
532                                 lldb::RunMode stop_other_threads);
533
534    //------------------------------------------------------------------
535    /// Queues the plan used to step through an address range, stepping into functions.
536    ///
537    /// @param[in] abort_other_plans
538    ///    \b true if we discard the currently queued plans and replace them with this one.
539    ///    Otherwise this plan will go on the end of the plan stack.
540    ///
541    /// @param[in] type
542    ///    Type of step to do, only eStepTypeInto and eStepTypeOver are supported by this plan.
543    ///
544    /// @param[in] range
545    ///    The address range to step through.
546    ///
547    /// @param[in] addr_context
548    ///    When dealing with stepping through inlined functions the current PC is not enough information to know
549    ///    what "step" means.  For instance a series of nested inline functions might start at the same address.
550    //     The \a addr_context provides the current symbol context the step
551    ///    is supposed to be out of.
552    //   FIXME: Currently unused.
553    ///
554    /// @param[in] step_in_target
555    ///    Name if function we are trying to step into.  We will step out if we don't land in that function.
556    ///
557    /// @param[in] stop_other_threads
558    ///    \b true if we will stop other threads while we single step this one.
559    ///
560    /// @param[in] avoid_code_without_debug_info
561    ///    If \b true we will step out if we step into code with no debug info.
562    ///
563    /// @return
564    ///     A shared pointer to the newly queued thread plan, or NULL if the plan could not be queued.
565    //------------------------------------------------------------------
566    virtual lldb::ThreadPlanSP
567    QueueThreadPlanForStepInRange (bool abort_other_plans,
568                                 const AddressRange &range,
569                                 const SymbolContext &addr_context,
570                                 const char *step_in_target,
571                                 lldb::RunMode stop_other_threads,
572                                 bool avoid_code_without_debug_info);
573
574    //------------------------------------------------------------------
575    /// Queue the plan used to step out of the function at the current PC of
576    /// \a thread.
577    ///
578    /// @param[in] abort_other_plans
579    ///    \b true if we discard the currently queued plans and replace them with this one.
580    ///    Otherwise this plan will go on the end of the plan stack.
581    ///
582    /// @param[in] addr_context
583    ///    When dealing with stepping through inlined functions the current PC is not enough information to know
584    ///    what "step" means.  For instance a series of nested inline functions might start at the same address.
585    //     The \a addr_context provides the current symbol context the step
586    ///    is supposed to be out of.
587    //   FIXME: Currently unused.
588    ///
589    /// @param[in] first_insn
590    ///     \b true if this is the first instruction of a function.
591    ///
592    /// @param[in] stop_other_threads
593    ///    \b true if we will stop other threads while we single step this one.
594    ///
595    /// @param[in] stop_vote
596    /// @param[in] run_vote
597    ///    See standard meanings for the stop & run votes in ThreadPlan.h.
598    ///
599    /// @return
600    ///     A shared pointer to the newly queued thread plan, or NULL if the plan could not be queued.
601    //------------------------------------------------------------------
602    virtual lldb::ThreadPlanSP
603    QueueThreadPlanForStepOut (bool abort_other_plans,
604                               SymbolContext *addr_context,
605                               bool first_insn,
606                               bool stop_other_threads,
607                               Vote stop_vote, // = eVoteYes,
608                               Vote run_vote, // = eVoteNoOpinion);
609                               uint32_t frame_idx);
610
611    //------------------------------------------------------------------
612    /// Gets the plan used to step through the code that steps from a function
613    /// call site at the current PC into the actual function call.
614    ///
615    ///
616    /// @param[in] return_stack_id
617    ///    The stack id that we will return to (by setting backstop breakpoints on the return
618    ///    address to that frame) if we fail to step through.
619    ///
620    /// @param[in] abort_other_plans
621    ///    \b true if we discard the currently queued plans and replace them with this one.
622    ///    Otherwise this plan will go on the end of the plan stack.
623    ///
624    /// @param[in] stop_other_threads
625    ///    \b true if we will stop other threads while we single step this one.
626    ///
627    /// @return
628    ///     A shared pointer to the newly queued thread plan, or NULL if the plan could not be queued.
629    //------------------------------------------------------------------
630    virtual lldb::ThreadPlanSP
631    QueueThreadPlanForStepThrough (StackID &return_stack_id,
632                                   bool abort_other_plans,
633                                   bool stop_other_threads);
634
635    //------------------------------------------------------------------
636    /// Gets the plan used to continue from the current PC.
637    /// This is a simple plan, mostly useful as a backstop when you are continuing
638    /// for some particular purpose.
639    ///
640    /// @param[in] abort_other_plans
641    ///    \b true if we discard the currently queued plans and replace them with this one.
642    ///    Otherwise this plan will go on the end of the plan stack.
643    ///
644    /// @param[in] target_addr
645    ///    The address to which we're running.
646    ///
647    /// @param[in] stop_other_threads
648    ///    \b true if we will stop other threads while we single step this one.
649    ///
650    /// @return
651    ///     A shared pointer to the newly queued thread plan, or NULL if the plan could not be queued.
652    //------------------------------------------------------------------
653    virtual lldb::ThreadPlanSP
654    QueueThreadPlanForRunToAddress (bool abort_other_plans,
655                                    Address &target_addr,
656                                    bool stop_other_threads);
657
658    virtual lldb::ThreadPlanSP
659    QueueThreadPlanForStepUntil (bool abort_other_plans,
660                                 lldb::addr_t *address_list,
661                                 size_t num_addresses,
662                                 bool stop_others,
663                                 uint32_t frame_idx);
664
665    //------------------------------------------------------------------
666    // Thread Plan accessors:
667    //------------------------------------------------------------------
668
669    //------------------------------------------------------------------
670    /// Gets the plan which will execute next on the plan stack.
671    ///
672    /// @return
673    ///     A pointer to the next executed plan.
674    //------------------------------------------------------------------
675    ThreadPlan *
676    GetCurrentPlan ();
677
678    //------------------------------------------------------------------
679    /// Unwinds the thread stack for the innermost expression plan currently
680    /// on the thread plan stack.
681    ///
682    /// @return
683    ///     An error if the thread plan could not be unwound.
684    //------------------------------------------------------------------
685
686    Error
687    UnwindInnermostExpression();
688
689private:
690    bool
691    PlanIsBasePlan (ThreadPlan *plan_ptr);
692
693    void
694    BroadcastSelectedFrameChange(StackID &new_frame_id);
695
696public:
697
698    //------------------------------------------------------------------
699    /// Gets the outer-most plan that was popped off the plan stack in the
700    /// most recent stop.  Useful for printing the stop reason accurately.
701    ///
702    /// @return
703    ///     A pointer to the last completed plan.
704    //------------------------------------------------------------------
705    lldb::ThreadPlanSP
706    GetCompletedPlan ();
707
708    //------------------------------------------------------------------
709    /// Gets the outer-most return value from the completed plans
710    ///
711    /// @return
712    ///     A ValueObjectSP, either empty if there is no return value,
713    ///     or containing the return value.
714    //------------------------------------------------------------------
715    lldb::ValueObjectSP
716    GetReturnValueObject ();
717
718    //------------------------------------------------------------------
719    ///  Checks whether the given plan is in the completed plans for this
720    ///  stop.
721    ///
722    /// @param[in] plan
723    ///     Pointer to the plan you're checking.
724    ///
725    /// @return
726    ///     Returns true if the input plan is in the completed plan stack,
727    ///     false otherwise.
728    //------------------------------------------------------------------
729    bool
730    IsThreadPlanDone (ThreadPlan *plan);
731
732    //------------------------------------------------------------------
733    ///  Checks whether the given plan is in the discarded plans for this
734    ///  stop.
735    ///
736    /// @param[in] plan
737    ///     Pointer to the plan you're checking.
738    ///
739    /// @return
740    ///     Returns true if the input plan is in the discarded plan stack,
741    ///     false otherwise.
742    //------------------------------------------------------------------
743    bool
744    WasThreadPlanDiscarded (ThreadPlan *plan);
745
746    //------------------------------------------------------------------
747    /// Queues a generic thread plan.
748    ///
749    /// @param[in] plan_sp
750    ///    The plan to queue.
751    ///
752    /// @param[in] abort_other_plans
753    ///    \b true if we discard the currently queued plans and replace them with this one.
754    ///    Otherwise this plan will go on the end of the plan stack.
755    ///
756    /// @return
757    ///     A pointer to the last completed plan.
758    //------------------------------------------------------------------
759    void
760    QueueThreadPlan (lldb::ThreadPlanSP &plan_sp, bool abort_other_plans);
761
762
763    //------------------------------------------------------------------
764    /// Discards the plans queued on the plan stack of the current thread.  This is
765    /// arbitrated by the "Master" ThreadPlans, using the "OkayToDiscard" call.
766    //  But if \a force is true, all thread plans are discarded.
767    //------------------------------------------------------------------
768    void
769    DiscardThreadPlans (bool force);
770
771    //------------------------------------------------------------------
772    /// Discards the plans queued on the plan stack of the current thread up to and
773    /// including up_to_plan_sp.
774    //
775    // @param[in] up_to_plan_sp
776    //   Discard all plans up to and including this one.
777    //------------------------------------------------------------------
778    void
779    DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp);
780
781    void
782    DiscardThreadPlansUpToPlan (ThreadPlan *up_to_plan_ptr);
783
784    //------------------------------------------------------------------
785    /// Prints the current plan stack.
786    ///
787    /// @param[in] s
788    ///    The stream to which to dump the plan stack info.
789    ///
790    //------------------------------------------------------------------
791    void
792    DumpThreadPlans (Stream *s) const;
793
794    virtual bool
795    CheckpointThreadState (ThreadStateCheckpoint &saved_state);
796
797    virtual bool
798    RestoreRegisterStateFromCheckpoint (ThreadStateCheckpoint &saved_state);
799
800    virtual bool
801    RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state);
802
803    void
804    EnableTracer (bool value, bool single_step);
805
806    void
807    SetTracer (lldb::ThreadPlanTracerSP &tracer_sp);
808
809    //------------------------------------------------------------------
810    // Get the thread index ID. The index ID that is guaranteed to not
811    // be re-used by a process. They start at 1 and increase with each
812    // new thread. This allows easy command line access by a unique ID
813    // that is easier to type than the actual system thread ID.
814    //------------------------------------------------------------------
815    uint32_t
816    GetIndexID () const;
817
818    //------------------------------------------------------------------
819    // Get the originating thread's index ID.
820    // In the case of an "extended" thread -- a thread which represents
821    // the stack that enqueued/spawned work that is currently executing --
822    // we need to provide the IndexID of the thread that actually did
823    // this work.  We don't want to just masquerade as that thread's IndexID
824    // by using it in our own IndexID because that way leads to madness -
825    // but the driver program which is iterating over extended threads
826    // may ask for the OriginatingThreadID to display that information
827    // to the user.
828    // Normal threads will return the same thing as GetIndexID();
829    //------------------------------------------------------------------
830    virtual uint32_t
831    GetExtendedBacktraceOriginatingIndexID ()
832    {
833        return GetIndexID ();
834    }
835
836    //------------------------------------------------------------------
837    // The API ID is often the same as the Thread::GetID(), but not in
838    // all cases. Thread::GetID() is the user visible thread ID that
839    // clients would want to see. The API thread ID is the thread ID
840    // that is used when sending data to/from the debugging protocol.
841    //------------------------------------------------------------------
842    virtual lldb::user_id_t
843    GetProtocolID () const
844    {
845        return GetID();
846    }
847
848    //------------------------------------------------------------------
849    // lldb::ExecutionContextScope pure virtual functions
850    //------------------------------------------------------------------
851    virtual lldb::TargetSP
852    CalculateTarget ();
853
854    virtual lldb::ProcessSP
855    CalculateProcess ();
856
857    virtual lldb::ThreadSP
858    CalculateThread ();
859
860    virtual lldb::StackFrameSP
861    CalculateStackFrame ();
862
863    virtual void
864    CalculateExecutionContext (ExecutionContext &exe_ctx);
865
866    lldb::StackFrameSP
867    GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr);
868
869    size_t
870    GetStatus (Stream &strm,
871               uint32_t start_frame,
872               uint32_t num_frames,
873               uint32_t num_frames_with_source);
874
875    size_t
876    GetStackFrameStatus (Stream& strm,
877                         uint32_t first_frame,
878                         uint32_t num_frames,
879                         bool show_frame_info,
880                         uint32_t num_frames_with_source);
881
882    // We need a way to verify that even though we have a thread in a shared
883    // pointer that the object itself is still valid. Currently this won't be
884    // the case if DestroyThread() was called. DestroyThread is called when
885    // a thread has been removed from the Process' thread list.
886    bool
887    IsValid () const
888    {
889        return !m_destroy_called;
890    }
891
892    // Sets and returns a valid stop info based on the process stop ID and the
893    // current thread plan. If the thread stop ID does not match the process'
894    // stop ID, the private stop reason is not set and an invalid StopInfoSP may
895    // be returned.
896    //
897    // NOTE: This function must be called before the current thread plan is
898    // moved to the completed plan stack (in Thread::ShouldStop()).
899    //
900    // NOTE: If subclasses override this function, ensure they do not overwrite
901    // the m_actual_stop_info if it is valid.  The stop info may be a
902    // "checkpointed and restored" stop info, so if it is still around it is
903    // right even if you have not calculated this yourself, or if it disagrees
904    // with what you might have calculated.
905    virtual lldb::StopInfoSP
906    GetPrivateStopInfo ();
907
908    //----------------------------------------------------------------------
909    // Ask the thread subclass to set its stop info.
910    //
911    // Thread subclasses should call Thread::SetStopInfo(...) with the
912    // reason the thread stopped.
913    //
914    // @return
915    //      True if Thread::SetStopInfo(...) was called, false otherwise.
916    //----------------------------------------------------------------------
917    virtual bool
918    CalculateStopInfo () = 0;
919
920    //----------------------------------------------------------------------
921    // Gets the temporary resume state for a thread.
922    //
923    // This value gets set in each thread by complex debugger logic in
924    // Thread::ShouldResume() and an appropriate thread resume state will get
925    // set in each thread every time the process is resumed prior to calling
926    // Process::DoResume(). The lldb_private::Process subclass should adhere
927    // to the thread resume state request which will be one of:
928    //
929    //  eStateRunning   - thread will resume when process is resumed
930    //  eStateStepping  - thread should step 1 instruction and stop when process
931    //                    is resumed
932    //  eStateSuspended - thread should not execute any instructions when
933    //                    process is resumed
934    //----------------------------------------------------------------------
935    lldb::StateType
936    GetTemporaryResumeState() const
937    {
938        return m_temporary_resume_state;
939    }
940
941    void
942    SetStopInfo (const lldb::StopInfoSP &stop_info_sp);
943
944    void
945    SetShouldReportStop (Vote vote);
946
947    //----------------------------------------------------------------------
948    /// Sets the extended backtrace token for this thread
949    ///
950    /// Some Thread subclasses may maintain a token to help with providing
951    /// an extended backtrace.  The SystemRuntime plugin will set/request this.
952    ///
953    /// @param [in] token
954    //----------------------------------------------------------------------
955    virtual void
956    SetExtendedBacktraceToken (uint64_t token) { }
957
958    //----------------------------------------------------------------------
959    /// Gets the extended backtrace token for this thread
960    ///
961    /// Some Thread subclasses may maintain a token to help with providing
962    /// an extended backtrace.  The SystemRuntime plugin will set/request this.
963    ///
964    /// @return
965    ///     The token needed by the SystemRuntime to create an extended backtrace.
966    ///     LLDB_INVALID_ADDRESS is returned if no token is available.
967    //----------------------------------------------------------------------
968    virtual uint64_t
969    GetExtendedBacktraceToken ()
970    {
971        return LLDB_INVALID_ADDRESS;
972    }
973
974protected:
975
976    friend class ThreadPlan;
977    friend class ThreadList;
978    friend class ThreadEventData;
979    friend class StackFrameList;
980    friend class StackFrame;
981    friend class OperatingSystem;
982
983    // This is necessary to make sure thread assets get destroyed while the thread is still in good shape
984    // to call virtual thread methods.  This must be called by classes that derive from Thread in their destructor.
985    virtual void DestroyThread ();
986
987    void
988    PushPlan (lldb::ThreadPlanSP &plan_sp);
989
990    void
991    PopPlan ();
992
993    void
994    DiscardPlan ();
995
996    ThreadPlan *GetPreviousPlan (ThreadPlan *plan);
997
998    typedef std::vector<lldb::ThreadPlanSP> plan_stack;
999
1000    virtual lldb_private::Unwind *
1001    GetUnwinder ();
1002
1003    // Check to see whether the thread is still at the last breakpoint hit that stopped it.
1004    virtual bool
1005    IsStillAtLastBreakpointHit();
1006
1007    // Some threads are threads that are made up by OperatingSystem plugins that
1008    // are threads that exist and are context switched out into memory. The
1009    // OperatingSystem plug-in need a ways to know if a thread is "real" or made
1010    // up.
1011    virtual bool
1012    IsOperatingSystemPluginThread () const
1013    {
1014        return false;
1015    }
1016
1017
1018    lldb::StackFrameListSP
1019    GetStackFrameList ();
1020
1021
1022    //------------------------------------------------------------------
1023    // Classes that inherit from Process can see and modify these
1024    //------------------------------------------------------------------
1025    lldb::ProcessWP     m_process_wp;           ///< The process that owns this thread.
1026    lldb::StopInfoSP    m_stop_info_sp;         ///< The private stop reason for this thread
1027    uint32_t            m_stop_info_stop_id;    // This is the stop id for which the StopInfo is valid.  Can use this so you know that
1028    // the thread's m_stop_info_sp is current and you don't have to fetch it again
1029    const uint32_t      m_index_id;             ///< A unique 1 based index assigned to each thread for easy UI/command line access.
1030    lldb::RegisterContextSP m_reg_context_sp;   ///< The register context for this thread's current register state.
1031    lldb::StateType     m_state;                ///< The state of our process.
1032    mutable Mutex       m_state_mutex;          ///< Multithreaded protection for m_state.
1033    plan_stack          m_plan_stack;           ///< The stack of plans this thread is executing.
1034    plan_stack          m_completed_plan_stack; ///< Plans that have been completed by this stop.  They get deleted when the thread resumes.
1035    plan_stack          m_discarded_plan_stack; ///< Plans that have been discarded by this stop.  They get deleted when the thread resumes.
1036    mutable Mutex       m_frame_mutex;          ///< Multithreaded protection for m_state.
1037    lldb::StackFrameListSP m_curr_frames_sp;    ///< The stack frames that get lazily populated after a thread stops.
1038    lldb::StackFrameListSP m_prev_frames_sp;    ///< The previous stack frames from the last time this thread stopped.
1039    int                 m_resume_signal;        ///< The signal that should be used when continuing this thread.
1040    lldb::StateType     m_resume_state;         ///< This state is used to force a thread to be suspended from outside the ThreadPlan logic.
1041    lldb::StateType     m_temporary_resume_state; ///< This state records what the thread was told to do by the thread plan logic for the current resume.
1042                                                  /// It gets set in Thread::ShoudResume.
1043    std::unique_ptr<lldb_private::Unwind> m_unwinder_ap;
1044    bool                m_destroy_called;       // This is used internally to make sure derived Thread classes call DestroyThread.
1045    LazyBool            m_override_should_notify;
1046private:
1047    //------------------------------------------------------------------
1048    // For Thread only
1049    //------------------------------------------------------------------
1050
1051    DISALLOW_COPY_AND_ASSIGN (Thread);
1052
1053};
1054
1055} // namespace lldb_private
1056
1057#endif  // liblldb_Thread_h_
1058