ThreadPlan.h revision 2370a97fe5bea6fa9d82f40bb34d37d3d3bda317
1//===-- ThreadPlan.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_ThreadPlan_h_
11#define liblldb_ThreadPlan_h_
12
13// C Includes
14// C++ Includes
15#include <string>
16// Other libraries and framework includes
17// Project includes
18#include "lldb/lldb-private.h"
19#include "lldb/Core/UserID.h"
20#include "lldb/Host/Mutex.h"
21#include "lldb/Target/Thread.h"
22#include "lldb/Target/ThreadPlanTracer.h"
23#include "lldb/Target/StopInfo.h"
24
25namespace lldb_private {
26
27//------------------------------------------------------------------
28//  ThreadPlan:
29//  This is the pure virtual base class for thread plans.
30//
31//  The thread plans provide the "atoms" of behavior that
32//  all the logical process control, either directly from commands or through
33//  more complex composite plans will rely on.
34//
35//  Plan Stack:
36//
37//  The thread maintaining a thread plan stack, and you program the actions of a particular thread
38//  by pushing plans onto the plan stack.
39//  There is always a "Current" plan, which is the head of the plan stack, though in some cases
40//  a plan may defer to plans higher in the stack for some piece of information.
41//
42//  The plan stack is never empty, there is always a Base Plan which persists through the life
43//  of the running process.
44//
45//
46//  Creating Plans:
47//
48//  The thread plan is generally created and added to the plan stack through the QueueThreadPlanFor... API
49//  in lldb::Thread.  Those API's will return the plan that performs the named operation in a manner
50//  appropriate for the current process.  The plans in lldb/source/Target are generic
51//  implementations, but a Process plugin can override them.
52//
53//  ValidatePlan is then called.  If it returns false, the plan is unshipped.  This is a little
54//  convenience which keeps us from having to error out of the constructor.
55//
56//  Then the plan is added to the plan stack.  When the plan is added to the plan stack its DidPush
57//  will get called.  This is useful if a plan wants to push any additional plans as it is constructed,
58//  since you need to make sure you're already on the stack before you push additional plans.
59//
60//  Completed Plans:
61//
62//  When the target process stops the plans are queried, among other things, for whether their job is done.
63//  If it is they are moved from the plan stack to the Completed Plan stack in reverse order from their position
64//  on the plan stack (since multiple plans may be done at a given stop.)  This is used primarily so that
65//  the lldb::Thread::StopInfo for the thread can be set properly.  If one plan pushes another to achieve part of
66//  its job, but it doesn't want that sub-plan to be the one that sets the StopInfo, then call SetPrivate on the
67//  sub-plan when you create it, and the Thread will pass over that plan in reporting the reason for the stop.
68//
69//  Discarded plans:
70//
71//  Your plan may also get discarded, i.e. moved from the plan stack to the "discarded plan stack".  This can
72//  happen, for instance, if the plan is calling a function and the function call crashes and you want
73//  to unwind the attempt to call.  So don't assume that your plan will always successfully stop.  Which leads to:
74//
75//  Cleaning up after your plans:
76//
77//  When the plan is moved from the plan stack its WillPop method is always called, no matter why.  Once it is
78//  moved off the plan stack it is done, and won't get a chance to run again.  So you should
79//  undo anything that affects target state in this method.  But be sure to leave the plan able to correctly
80//  fill the StopInfo, however.
81//  N.B. Don't wait to do clean up target state till the destructor, since that will usually get called when
82//  the target resumes, and you want to leave the target state correct for new plans in the time between when
83//  your plan gets unshipped and the next resume.
84//
85//  Over the lifetime of the plan, various methods of the ThreadPlan are then called in response to changes of state in
86//  the process we are debugging as follows:
87//
88//  Resuming:
89//
90//  When the target process is about to be restarted, the plan's WillResume method is called,
91//  giving the plan a chance to prepare for the run.  If WillResume returns false, then the
92//  process is not restarted.  Be sure to set an appropriate error value in the Process if
93//  you have to do this.
94//  Next the "StopOthers" method of all the threads are polled, and if one thread's Current plan
95//  returns "true" then only that thread gets to run.  If more than one returns "true" the threads that want to run solo
96//  get run one by one round robin fashion.  Otherwise all are let to run.
97//
98//  Note, the way StopOthers is implemented, the base class implementation just asks the previous plan.  So if your plan
99//  has no opinion about whether it should run stopping others or not, just don't implement StopOthers, and the parent
100//  will be asked.
101//
102//  Finally, for each thread that is running, it run state is set to the return of RunState from the
103//  thread's Current plan.
104//
105//  Responding to a stop:
106//
107//  When the target process stops, the plan is called in the following stages:
108//
109//  First the thread asks the Current Plan if it can handle this stop by calling PlanExplainsStop.
110//  If the Current plan answers "true" then it is asked if the stop should percolate all the way to the
111//  user by calling the ShouldStop method.  If the current plan doesn't explain the stop, then we query down
112//  the plan stack for a plan that does explain the stop.  The plan that does explain the stop then needs to
113//  figure out what to do about the plans below it in the stack.  If the stop is recoverable, then the plan that
114//  understands it can just do what it needs to set up to restart, and then continue.
115//  Otherwise, the plan that understood the stop should call DiscardPlanStack to clean up the stack below it.
116//  In the normal case, this will just collapse the plan stack up to the point of the plan that understood
117//  the stop reason.  However, if a plan wishes to stay on the stack after an event it didn't directly handle
118//  it can designate itself a "Master" plan by responding true to IsMasterPlan, and then if it wants not to be
119//  discarded, it can return true to OkayToDiscard, and it and all its dependent plans will be preserved when
120//  we resume execution.
121//
122//  Actually Stopping:
123//
124//  If a plan says responds "true" to ShouldStop, then it is asked if it's job is complete by calling
125//  MischiefManaged.  If that returns true, the thread is popped from the plan stack and added to the
126//  Completed Plan Stack.  Then the next plan in the stack is asked if it ShouldStop, and  it returns "true",
127//  it is asked if it is done, and if yes popped, and so on till we reach a plan that is not done.
128//
129//  Since you often know in the ShouldStop method whether your plan is complete, as a convenience you can call
130//  SetPlanComplete and the ThreadPlan implementation of MischiefManaged will return "true", without your having
131//  to redo the calculation when your sub-classes MischiefManaged is called.  If you call SetPlanComplete, you can
132//  later use IsPlanComplete to determine whether the plan is complete.  This is only a convenience for sub-classes,
133//  the logic in lldb::Thread will only call MischiefManaged.
134//
135//  One slightly tricky point is you have to be careful using SetPlanComplete in PlanExplainsStop because you
136//  are not guaranteed that PlanExplainsStop for a plan will get called before ShouldStop gets called.  If your sub-plan
137//  explained the stop and then popped itself, only your ShouldStop will get called.
138//
139//  If ShouldStop for any thread returns "true", then the WillStop method of the Current plan of
140//  all threads will be called, the stop event is placed on the Process's public broadcaster, and
141//  control returns to the upper layers of the debugger.
142//
143//  Automatically Resuming:
144//
145//  If ShouldStop for all threads returns "false", then the target process will resume.  This then cycles back to
146//  Resuming above.
147//
148//  Reporting eStateStopped events when the target is restarted:
149//
150//  If a plan decides to auto-continue the target by returning "false" from ShouldStop, then it will be asked
151//  whether the Stopped event should still be reported.  For instance, if you hit a breakpoint that is a User set
152//  breakpoint, but the breakpoint callback said to continue the target process, you might still want to inform
153//  the upper layers of lldb that the stop had happened.
154//  The way this works is every thread gets to vote on whether to report the stop.  If all votes are eVoteNoOpinion,
155//  then the thread list will decide what to do (at present it will pretty much always suppress these stopped events.)
156//  If there is an eVoteYes, then the event will be reported regardless of the other votes.  If there is an eVoteNo
157//  and no eVoteYes's, then the event won't be reported.
158//
159//  One other little detail here, sometimes a plan will push another plan onto the plan stack to do some part of
160//  the first plan's job, and it would be convenient to tell that plan how it should respond to ShouldReportStop.
161//  You can do that by setting the stop_vote in the child plan when you create it.
162//
163//  Suppressing the initial eStateRunning event:
164//
165//  The private process running thread will take care of ensuring that only one "eStateRunning" event will be
166//  delivered to the public Process broadcaster per public eStateStopped event.  However there are some cases
167//  where the public state of this process is eStateStopped, but a thread plan needs to restart the target, but
168//  doesn't want the running event to be publically broadcast.  The obvious example of this is running functions
169//  by hand as part of expression evaluation.  To suppress the running event return eVoteNo from ShouldReportStop,
170//  to force a running event to be reported return eVoteYes, in general though you should return eVoteNoOpinion
171//  which will allow the ThreadList to figure out the right thing to do.
172//  The run_vote argument to the constructor works like stop_vote, and is a way for a plan to instruct a sub-plan
173//  on how to respond to ShouldReportStop.
174//
175//------------------------------------------------------------------
176
177class ThreadPlan :
178    public UserID
179{
180public:
181    typedef enum
182    {
183        eAllThreads,
184        eSomeThreads,
185        eThisThread
186    } ThreadScope;
187
188    // We use these enums so that we can cast a base thread plan to it's real type without having to resort
189    // to dynamic casting.
190    typedef enum
191    {
192        eKindGeneric,
193        eKindBase,
194        eKindCallFunction,
195        eKindStepInstruction,
196        eKindStepOut,
197        eKindStepOverBreakpoint,
198        eKindStepOverRange,
199        eKindStepInRange,
200        eKindRunToAddress,
201        eKindStepThrough,
202        eKindStepUntil,
203        eKindTestCondition
204
205    } ThreadPlanKind;
206
207    //------------------------------------------------------------------
208    // Constructors and Destructors
209    //------------------------------------------------------------------
210    ThreadPlan (ThreadPlanKind kind,
211                const char *name,
212                Thread &thread,
213                Vote stop_vote,
214                Vote run_vote);
215
216    virtual
217    ~ThreadPlan();
218
219    //------------------------------------------------------------------
220    /// Returns the name of this thread plan.
221    ///
222    /// @return
223    ///   A const char * pointer to the thread plan's name.
224    //------------------------------------------------------------------
225    const char *
226    GetName () const;
227
228    //------------------------------------------------------------------
229    /// Returns the Thread that is using this thread plan.
230    ///
231    /// @return
232    ///   A  pointer to the thread plan's owning thread.
233    //------------------------------------------------------------------
234    Thread &
235    GetThread();
236
237    const Thread &
238    GetThread() const;
239
240    //------------------------------------------------------------------
241    /// Print a description of this thread to the stream \a s.
242    /// \a thread.
243    ///
244    /// @param[in] s
245    ///    The stream to which to print the description.
246    ///
247    /// @param[in] level
248    ///    The level of description desired.  Note that eDescriptionLevelBrief
249    ///    will be used in the stop message printed when the plan is complete.
250    //------------------------------------------------------------------
251    virtual void
252    GetDescription (Stream *s,
253                    lldb::DescriptionLevel level) = 0;
254
255    //------------------------------------------------------------------
256    /// Returns whether this plan could be successfully created.
257    ///
258    /// @param[in] error
259    ///    A stream to which to print some reason why the plan could not be created.
260    ///    Can be NULL.
261    ///
262    /// @return
263    ///   \b true if the plan should be queued, \b false otherwise.
264    //------------------------------------------------------------------
265    virtual bool
266    ValidatePlan (Stream *error) = 0;
267
268    virtual bool
269    PlanExplainsStop () = 0;
270
271    bool
272    TracerExplainsStop ()
273    {
274        if (!m_tracer_sp)
275            return false;
276        else
277            return m_tracer_sp->TracerExplainsStop();
278    }
279
280
281    lldb::StateType
282    RunState ();
283
284    virtual bool
285    ShouldStop (Event *event_ptr) = 0;
286
287    virtual bool
288    ShouldAutoContinue (Event *event_ptr)
289    {
290        return false;
291    }
292
293    // Whether a "stop class" event should be reported to the "outside world".  In general
294    // if a thread plan is active, events should not be reported.
295
296    virtual Vote
297    ShouldReportStop (Event *event_ptr);
298
299    virtual Vote
300    ShouldReportRun (Event *event_ptr);
301
302    virtual void
303    SetStopOthers (bool new_value);
304
305    virtual bool
306    StopOthers ();
307
308    virtual bool
309    WillResume (lldb::StateType resume_state, bool current_plan);
310
311    virtual bool
312    WillStop () = 0;
313
314    virtual bool
315    IsMasterPlan()
316    {
317        return false;
318    }
319
320    virtual bool
321    OkayToDiscard();
322
323    void
324    SetOkayToDiscard (bool value)
325    {
326        m_okay_to_discard = value;
327    }
328
329    // The base class MischiefManaged does some cleanup - so you have to call it
330    // in your MischiefManaged derived class.
331    virtual bool
332    MischiefManaged ();
333
334    bool
335    GetPrivate ();
336
337    void
338    SetPrivate (bool input);
339
340    virtual void
341    DidPush();
342
343    virtual void
344    WillPop();
345
346    // This pushes \a plan onto the plan stack of the current plan's thread.
347    void
348    PushPlan (lldb::ThreadPlanSP &thread_plan_sp);
349
350    ThreadPlanKind GetKind() const
351    {
352        return m_kind;
353    }
354
355    bool
356    IsPlanComplete();
357
358    void
359    SetPlanComplete ();
360
361    lldb::ThreadPlanTracerSP &
362    GetThreadPlanTracer()
363    {
364        return m_tracer_sp;
365    }
366
367    void
368    SetThreadPlanTracer (lldb::ThreadPlanTracerSP new_tracer_sp)
369    {
370        m_tracer_sp = new_tracer_sp;
371    }
372
373    void
374    DoTraceLog ()
375    {
376        if (m_tracer_sp && m_tracer_sp->TracingEnabled())
377            m_tracer_sp->Log();
378    }
379
380    // Some thread plans hide away the actual stop info which caused any particular stop.  For
381    // instance the ThreadPlanCallFunction restores the original stop reason so that stopping and
382    // calling a few functions won't lose the history of the run.
383    // This call can be implemented to get you back to the real stop info.
384    virtual lldb::StopInfoSP
385    GetRealStopInfo ()
386    {
387        return m_thread.GetStopInfo ();
388    }
389
390protected:
391    //------------------------------------------------------------------
392    // Classes that inherit from ThreadPlan can see and modify these
393    //------------------------------------------------------------------
394
395    // This gets the previous plan to the current plan (for forwarding requests).
396    // This is mostly a formal requirement, it allows us to make the Thread's
397    // GetPreviousPlan protected, but only friend ThreadPlan to thread.
398
399    ThreadPlan *
400    GetPreviousPlan ();
401
402    // This forwards the private Thread::GetPrivateStopReason which is generally what
403    // ThreadPlan's need to know.
404
405    lldb::StopInfoSP
406    GetPrivateStopReason()
407    {
408        return m_thread.GetPrivateStopReason ();
409    }
410
411    void
412    SetStopInfo (lldb::StopInfoSP stop_reason_sp)
413    {
414        m_thread.SetStopInfo (stop_reason_sp);
415    }
416
417    virtual lldb::StateType
418    GetPlanRunState () = 0;
419
420
421    Thread &m_thread;
422    Vote m_stop_vote;
423    Vote m_run_vote;
424
425private:
426    //------------------------------------------------------------------
427    // For ThreadPlan only
428    //------------------------------------------------------------------
429    static lldb::user_id_t GetNextID ();
430
431    ThreadPlanKind m_kind;
432    std::string m_name;
433    Mutex m_plan_complete_mutex;
434    bool m_plan_complete;
435    bool m_plan_private;
436    bool m_okay_to_discard;
437
438    lldb::ThreadPlanTracerSP m_tracer_sp;
439
440private:
441    DISALLOW_COPY_AND_ASSIGN(ThreadPlan);
442};
443
444
445} // namespace lldb_private
446
447#endif  // liblldb_ThreadPlan_h_
448