ThreadPlan.h revision 04cc48eb5cff32268a822b57f87590c9dc2643f8
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/Process.h"
22#include "lldb/Target/Target.h"
23#include "lldb/Target/Thread.h"
24#include "lldb/Target/ThreadPlanTracer.h"
25#include "lldb/Target/StopInfo.h"
26
27namespace lldb_private {
28
29//------------------------------------------------------------------
30//  ThreadPlan:
31//  This is the pure virtual base class for thread plans.
32//
33//  The thread plans provide the "atoms" of behavior that
34//  all the logical process control, either directly from commands or through
35//  more complex composite plans will rely on.
36//
37//  Plan Stack:
38//
39//  The thread maintaining a thread plan stack, and you program the actions of a particular thread
40//  by pushing plans onto the plan stack.
41//  There is always a "Current" plan, which is the head of the plan stack, though in some cases
42//  a plan may defer to plans higher in the stack for some piece of information.
43//
44//  The plan stack is never empty, there is always a Base Plan which persists through the life
45//  of the running process.
46//
47//
48//  Creating Plans:
49//
50//  The thread plan is generally created and added to the plan stack through the QueueThreadPlanFor... API
51//  in lldb::Thread.  Those API's will return the plan that performs the named operation in a manner
52//  appropriate for the current process.  The plans in lldb/source/Target are generic
53//  implementations, but a Process plugin can override them.
54//
55//  ValidatePlan is then called.  If it returns false, the plan is unshipped.  This is a little
56//  convenience which keeps us from having to error out of the constructor.
57//
58//  Then the plan is added to the plan stack.  When the plan is added to the plan stack its DidPush
59//  will get called.  This is useful if a plan wants to push any additional plans as it is constructed,
60//  since you need to make sure you're already on the stack before you push additional plans.
61//
62//  Completed Plans:
63//
64//  When the target process stops the plans are queried, among other things, for whether their job is done.
65//  If it is they are moved from the plan stack to the Completed Plan stack in reverse order from their position
66//  on the plan stack (since multiple plans may be done at a given stop.)  This is used primarily so that
67//  the lldb::Thread::StopInfo for the thread can be set properly.  If one plan pushes another to achieve part of
68//  its job, but it doesn't want that sub-plan to be the one that sets the StopInfo, then call SetPrivate on the
69//  sub-plan when you create it, and the Thread will pass over that plan in reporting the reason for the stop.
70//
71//  Discarded plans:
72//
73//  Your plan may also get discarded, i.e. moved from the plan stack to the "discarded plan stack".  This can
74//  happen, for instance, if the plan is calling a function and the function call crashes and you want
75//  to unwind the attempt to call.  So don't assume that your plan will always successfully stop.  Which leads to:
76//
77//  Cleaning up after your plans:
78//
79//  When the plan is moved from the plan stack its WillPop method is always called, no matter why.  Once it is
80//  moved off the plan stack it is done, and won't get a chance to run again.  So you should
81//  undo anything that affects target state in this method.  But be sure to leave the plan able to correctly
82//  fill the StopInfo, however.
83//  N.B. Don't wait to do clean up target state till the destructor, since that will usually get called when
84//  the target resumes, and you want to leave the target state correct for new plans in the time between when
85//  your plan gets unshipped and the next resume.
86//
87//  Over the lifetime of the plan, various methods of the ThreadPlan are then called in response to changes of state in
88//  the process we are debugging as follows:
89//
90//  Resuming:
91//
92//  When the target process is about to be restarted, the plan's WillResume method is called,
93//  giving the plan a chance to prepare for the run.  If WillResume returns false, then the
94//  process is not restarted.  Be sure to set an appropriate error value in the Process if
95//  you have to do this.  Note, ThreadPlans actually implement DoWillResume, WillResume wraps that call.
96//
97//  Next the "StopOthers" method of all the threads are polled, and if one thread's Current plan
98//  returns "true" then only that thread gets to run.  If more than one returns "true" the threads that want to run solo
99//  get run one by one round robin fashion.  Otherwise all are let to run.
100//
101//  Note, the way StopOthers is implemented, the base class implementation just asks the previous plan.  So if your plan
102//  has no opinion about whether it should run stopping others or not, just don't implement StopOthers, and the parent
103//  will be asked.
104//
105//  Finally, for each thread that is running, it run state is set to the return of RunState from the
106//  thread's Current plan.
107//
108//  Responding to a stop:
109//
110//  When the target process stops, the plan is called in the following stages:
111//
112//  First the thread asks the Current Plan if it can handle this stop by calling PlanExplainsStop.
113//  If the Current plan answers "true" then it is asked if the stop should percolate all the way to the
114//  user by calling the ShouldStop method.  If the current plan doesn't explain the stop, then we query down
115//  the plan stack for a plan that does explain the stop.  The plan that does explain the stop then needs to
116//  figure out what to do about the plans below it in the stack.  If the stop is recoverable, then the plan that
117//  understands it can just do what it needs to set up to restart, and then continue.
118//  Otherwise, the plan that understood the stop should call DiscardPlanStack to clean up the stack below it.
119//  Note, plans actually implement DoPlanExplainsStop, the result is cached in PlanExplainsStop so the DoPlanExplainsStop
120//  itself will only get called once per stop.
121//
122//  Master plans:
123//
124//  In the normal case, when we decide to stop, we will  collapse the plan stack up to the point of the plan that understood
125//  the stop reason.  However, if a plan wishes to stay on the stack after an event it didn't directly handle
126//  it can designate itself a "Master" plan by responding true to IsMasterPlan, and then if it wants not to be
127//  discarded, it can return true to OkayToDiscard, and it and all its dependent plans will be preserved when
128//  we resume execution.
129//
130//  The other effect of being a master plan is that when the Master plan is done , if it has set "OkayToDiscard" to false,
131//  then it will be popped & execution will stop and return to the user.  Remember that if OkayToDiscard is false, the
132//  plan will be popped and control will be given to the next plan above it on the stack  So setting OkayToDiscard to
133//  false means the user will regain control when the MasterPlan is completed.
134//
135//  Between these two controls this allows things like: a MasterPlan/DontDiscard Step Over to hit a breakpoint, stop and
136//  return control to the user, but then when the user continues, the step out succeeds.
137//  Even more tricky, when the breakpoint is hit, the user can continue to step in/step over/etc, and finally when they
138//  continue, they will finish up the Step Over.
139//
140//  FIXME: MasterPlan & OkayToDiscard aren't really orthogonal.  MasterPlan designation means that this plan controls
141//  it's fate and the fate of plans below it.  OkayToDiscard tells whether the MasterPlan wants to stay on the stack.  I
142//  originally thought "MasterPlan-ness" would need to be a fixed characteristic of a ThreadPlan, in which case you needed
143//  the extra control.  But that doesn't seem to be true.  So we should be able to convert to only MasterPlan status to mean
144//  the current "MasterPlan/DontDiscard".  Then no plans would be MasterPlans by default, and you would set the ones you
145//  wanted to be "user level" in this way.
146//
147//
148//  Actually Stopping:
149//
150//  If a plan says responds "true" to ShouldStop, then it is asked if it's job is complete by calling
151//  MischiefManaged.  If that returns true, the thread is popped from the plan stack and added to the
152//  Completed Plan Stack.  Then the next plan in the stack is asked if it ShouldStop, and  it returns "true",
153//  it is asked if it is done, and if yes popped, and so on till we reach a plan that is not done.
154//
155//  Since you often know in the ShouldStop method whether your plan is complete, as a convenience you can call
156//  SetPlanComplete and the ThreadPlan implementation of MischiefManaged will return "true", without your having
157//  to redo the calculation when your sub-classes MischiefManaged is called.  If you call SetPlanComplete, you can
158//  later use IsPlanComplete to determine whether the plan is complete.  This is only a convenience for sub-classes,
159//  the logic in lldb::Thread will only call MischiefManaged.
160//
161//  One slightly tricky point is you have to be careful using SetPlanComplete in PlanExplainsStop because you
162//  are not guaranteed that PlanExplainsStop for a plan will get called before ShouldStop gets called.  If your sub-plan
163//  explained the stop and then popped itself, only your ShouldStop will get called.
164//
165//  If ShouldStop for any thread returns "true", then the WillStop method of the Current plan of
166//  all threads will be called, the stop event is placed on the Process's public broadcaster, and
167//  control returns to the upper layers of the debugger.
168//
169//  Reporting the stop:
170//
171//  When the process stops, the thread is given a StopReason, in the form of a StopInfo object.  If there is a completed
172//  plan corresponding to the stop, then the "actual" stop reason will be suppressed, and instead a StopInfoThreadPlan
173//  object will be cons'ed up from the highest completed plan in the stack.  However, if the plan doesn't want to be
174//  the stop reason, then it can call SetPlanComplete and pass in "false" for the "success" parameter.  In that case,
175//  the real stop reason will be used instead.  One exapmle of this is the "StepRangeStepIn" thread plan.  If it stops
176//  because of a crash or breakpoint hit, it wants to unship itself, because it isn't so useful to have step in keep going
177//  after a breakpoint hit.  But it can't be the reason for the stop or no-one would see that they had hit a breakpoint.
178//
179//  Cleaning up the plan stack:
180//
181//  One of the complications of MasterPlans is that you may get past the limits of a plan without triggering it to clean
182//  itself up.  For instance, if you are doing a MasterPlan StepOver, and hit a breakpoint in a called function, then
183//  step over enough times to step out of the initial StepOver range, each of the step overs will explain the stop &
184//  take themselves off the stack, but control would never be returned to the original StepOver.  Eventually, the user
185//  will continue, and when that continue stops, the old stale StepOver plan that was left on the stack will get woken
186//  up and notice it is done. But that can leave junk on the stack for a while.  To avoid that, the plans implement a
187//  "IsPlanStale" method, that can check whether it is relevant anymore.  On stop, after the regular plan negotiation,
188//  the remaining plan stack is consulted and if any plan says it is stale, it and the plans below it are discarded from
189//  the stack.
190//
191//  Automatically Resuming:
192//
193//  If ShouldStop for all threads returns "false", then the target process will resume.  This then cycles back to
194//  Resuming above.
195//
196//  Reporting eStateStopped events when the target is restarted:
197//
198//  If a plan decides to auto-continue the target by returning "false" from ShouldStop, then it will be asked
199//  whether the Stopped event should still be reported.  For instance, if you hit a breakpoint that is a User set
200//  breakpoint, but the breakpoint callback said to continue the target process, you might still want to inform
201//  the upper layers of lldb that the stop had happened.
202//  The way this works is every thread gets to vote on whether to report the stop.  If all votes are eVoteNoOpinion,
203//  then the thread list will decide what to do (at present it will pretty much always suppress these stopped events.)
204//  If there is an eVoteYes, then the event will be reported regardless of the other votes.  If there is an eVoteNo
205//  and no eVoteYes's, then the event won't be reported.
206//
207//  One other little detail here, sometimes a plan will push another plan onto the plan stack to do some part of
208//  the first plan's job, and it would be convenient to tell that plan how it should respond to ShouldReportStop.
209//  You can do that by setting the stop_vote in the child plan when you create it.
210//
211//  Suppressing the initial eStateRunning event:
212//
213//  The private process running thread will take care of ensuring that only one "eStateRunning" event will be
214//  delivered to the public Process broadcaster per public eStateStopped event.  However there are some cases
215//  where the public state of this process is eStateStopped, but a thread plan needs to restart the target, but
216//  doesn't want the running event to be publically broadcast.  The obvious example of this is running functions
217//  by hand as part of expression evaluation.  To suppress the running event return eVoteNo from ShouldReportStop,
218//  to force a running event to be reported return eVoteYes, in general though you should return eVoteNoOpinion
219//  which will allow the ThreadList to figure out the right thing to do.
220//  The run_vote argument to the constructor works like stop_vote, and is a way for a plan to instruct a sub-plan
221//  on how to respond to ShouldReportStop.
222//
223//------------------------------------------------------------------
224
225class ThreadPlan :
226    public UserID
227{
228public:
229    typedef enum
230    {
231        eAllThreads,
232        eSomeThreads,
233        eThisThread
234    } ThreadScope;
235
236    // We use these enums so that we can cast a base thread plan to it's real type without having to resort
237    // to dynamic casting.
238    typedef enum
239    {
240        eKindGeneric,
241        eKindBase,
242        eKindCallFunction,
243        eKindStepInstruction,
244        eKindStepOut,
245        eKindStepOverBreakpoint,
246        eKindStepOverRange,
247        eKindStepInRange,
248        eKindRunToAddress,
249        eKindStepThrough,
250        eKindStepUntil,
251        eKindTestCondition
252
253    } ThreadPlanKind;
254
255    //------------------------------------------------------------------
256    // Constructors and Destructors
257    //------------------------------------------------------------------
258    ThreadPlan (ThreadPlanKind kind,
259                const char *name,
260                Thread &thread,
261                Vote stop_vote,
262                Vote run_vote);
263
264    virtual
265    ~ThreadPlan();
266
267    //------------------------------------------------------------------
268    /// Returns the name of this thread plan.
269    ///
270    /// @return
271    ///   A const char * pointer to the thread plan's name.
272    //------------------------------------------------------------------
273    const char *
274    GetName () const
275    {
276        return m_name.c_str();
277    }
278
279    //------------------------------------------------------------------
280    /// Returns the Thread that is using this thread plan.
281    ///
282    /// @return
283    ///   A  pointer to the thread plan's owning thread.
284    //------------------------------------------------------------------
285    Thread &
286    GetThread()
287    {
288        return m_thread;
289    }
290
291    const Thread &
292    GetThread() const
293    {
294        return m_thread;
295    }
296
297    Target &
298    GetTarget()
299    {
300        return m_thread.GetProcess()->GetTarget();
301    }
302
303    const Target &
304    GetTarget() const
305    {
306        return m_thread.GetProcess()->GetTarget();
307    }
308
309    //------------------------------------------------------------------
310    /// Print a description of this thread to the stream \a s.
311    /// \a thread.
312    ///
313    /// @param[in] s
314    ///    The stream to which to print the description.
315    ///
316    /// @param[in] level
317    ///    The level of description desired.  Note that eDescriptionLevelBrief
318    ///    will be used in the stop message printed when the plan is complete.
319    //------------------------------------------------------------------
320    virtual void
321    GetDescription (Stream *s,
322                    lldb::DescriptionLevel level) = 0;
323
324    //------------------------------------------------------------------
325    /// Returns whether this plan could be successfully created.
326    ///
327    /// @param[in] error
328    ///    A stream to which to print some reason why the plan could not be created.
329    ///    Can be NULL.
330    ///
331    /// @return
332    ///   \b true if the plan should be queued, \b false otherwise.
333    //------------------------------------------------------------------
334    virtual bool
335    ValidatePlan (Stream *error) = 0;
336
337    bool
338    TracerExplainsStop ()
339    {
340        if (!m_tracer_sp)
341            return false;
342        else
343            return m_tracer_sp->TracerExplainsStop();
344    }
345
346
347    lldb::StateType
348    RunState ();
349
350    bool
351    PlanExplainsStop (Event *event_ptr);
352
353    virtual bool
354    ShouldStop (Event *event_ptr) = 0;
355
356    virtual bool
357    ShouldAutoContinue (Event *event_ptr)
358    {
359        return false;
360    }
361
362    // Whether a "stop class" event should be reported to the "outside world".  In general
363    // if a thread plan is active, events should not be reported.
364
365    virtual Vote
366    ShouldReportStop (Event *event_ptr);
367
368    virtual Vote
369    ShouldReportRun (Event *event_ptr);
370
371    virtual void
372    SetStopOthers (bool new_value);
373
374    virtual bool
375    StopOthers ();
376
377    // This is the wrapper for DoWillResume that does generic ThreadPlan logic, then
378    // calls DoWillResume.
379    bool
380    WillResume (lldb::StateType resume_state, bool current_plan);
381
382    virtual bool
383    WillStop () = 0;
384
385    bool
386    IsMasterPlan()
387    {
388        return m_is_master_plan;
389    }
390
391    bool
392    SetIsMasterPlan (bool value)
393    {
394        bool old_value = m_is_master_plan;
395        m_is_master_plan = value;
396        return old_value;
397    }
398
399    virtual bool
400    OkayToDiscard();
401
402    void
403    SetOkayToDiscard (bool value)
404    {
405        m_okay_to_discard = value;
406    }
407
408    // The base class MischiefManaged does some cleanup - so you have to call it
409    // in your MischiefManaged derived class.
410    virtual bool
411    MischiefManaged ();
412
413    virtual void
414    ThreadDestroyed ()
415    {
416        // Any cleanup that a plan might want to do in case the thread goes away
417        // in the middle of the plan being queued on a thread can be done here.
418    }
419
420    bool
421    GetPrivate ()
422    {
423        return m_plan_private;
424    }
425
426    void
427    SetPrivate (bool input)
428    {
429        m_plan_private = input;
430    }
431
432    virtual void
433    DidPush();
434
435    virtual void
436    WillPop();
437
438    // This pushes \a plan onto the plan stack of the current plan's thread.
439    void
440    PushPlan (lldb::ThreadPlanSP &thread_plan_sp)
441    {
442        m_thread.PushPlan (thread_plan_sp);
443    }
444
445    ThreadPlanKind GetKind() const
446    {
447        return m_kind;
448    }
449
450    bool
451    IsPlanComplete();
452
453    void
454    SetPlanComplete (bool success = true);
455
456    virtual bool
457    IsPlanStale ()
458    {
459        return false;
460    }
461
462    bool
463    PlanSucceeded ()
464    {
465        return m_plan_succeeded;
466    }
467
468    virtual bool
469    IsBasePlan()
470    {
471        return false;
472    }
473
474    lldb::ThreadPlanTracerSP &
475    GetThreadPlanTracer()
476    {
477        return m_tracer_sp;
478    }
479
480    void
481    SetThreadPlanTracer (lldb::ThreadPlanTracerSP new_tracer_sp)
482    {
483        m_tracer_sp = new_tracer_sp;
484    }
485
486    void
487    DoTraceLog ()
488    {
489        if (m_tracer_sp && m_tracer_sp->TracingEnabled())
490            m_tracer_sp->Log();
491    }
492
493    // Some thread plans hide away the actual stop info which caused any particular stop.  For
494    // instance the ThreadPlanCallFunction restores the original stop reason so that stopping and
495    // calling a few functions won't lose the history of the run.
496    // This call can be implemented to get you back to the real stop info.
497    virtual lldb::StopInfoSP
498    GetRealStopInfo ()
499    {
500        return m_thread.GetStopInfo ();
501    }
502
503    virtual lldb::ValueObjectSP
504    GetReturnValueObject ()
505    {
506        return lldb::ValueObjectSP();
507    }
508
509    // If a thread plan stores the state before it was run, then you might
510    // want to restore the state when it is done.  This will do that job.
511    // This is mostly useful for artificial plans like CallFunction plans.
512
513    virtual bool
514    RestoreThreadState()
515    {
516        // Nothing to do in general.
517        return true;
518    }
519
520    virtual bool
521    IsVirtualStep()
522    {
523        return false;
524    }
525
526protected:
527    //------------------------------------------------------------------
528    // Classes that inherit from ThreadPlan can see and modify these
529    //------------------------------------------------------------------
530
531    virtual bool
532    DoWillResume (lldb::StateType resume_state, bool current_plan) { return true; };
533
534    virtual bool
535    DoPlanExplainsStop (Event *event_ptr) = 0;
536
537    // This gets the previous plan to the current plan (for forwarding requests).
538    // This is mostly a formal requirement, it allows us to make the Thread's
539    // GetPreviousPlan protected, but only friend ThreadPlan to thread.
540
541    ThreadPlan *
542    GetPreviousPlan ()
543    {
544        return m_thread.GetPreviousPlan (this);
545    }
546
547    // This forwards the private Thread::GetPrivateStopInfo which is generally what
548    // ThreadPlan's need to know.
549
550    lldb::StopInfoSP
551    GetPrivateStopInfo()
552    {
553        return m_thread.GetPrivateStopInfo ();
554    }
555
556    void
557    SetStopInfo (lldb::StopInfoSP stop_reason_sp)
558    {
559        m_thread.SetStopInfo (stop_reason_sp);
560    }
561
562    void
563    CachePlanExplainsStop (bool does_explain)
564    {
565        m_cached_plan_explains_stop = does_explain ? eLazyBoolYes : eLazyBoolNo;
566    }
567
568    LazyBool
569    GetCachedPlanExplainsStop () const
570    {
571        return m_cached_plan_explains_stop;
572    }
573
574    virtual lldb::StateType
575    GetPlanRunState () = 0;
576
577    Thread &m_thread;
578    Vote m_stop_vote;
579    Vote m_run_vote;
580
581private:
582    //------------------------------------------------------------------
583    // For ThreadPlan only
584    //------------------------------------------------------------------
585    static lldb::user_id_t GetNextID ();
586
587    ThreadPlanKind m_kind;
588    std::string m_name;
589    Mutex m_plan_complete_mutex;
590    LazyBool m_cached_plan_explains_stop;
591    bool m_plan_complete;
592    bool m_plan_private;
593    bool m_okay_to_discard;
594    bool m_is_master_plan;
595    bool m_plan_succeeded;
596
597    lldb::ThreadPlanTracerSP m_tracer_sp;
598
599private:
600    DISALLOW_COPY_AND_ASSIGN(ThreadPlan);
601};
602
603
604} // namespace lldb_private
605
606#endif  // liblldb_ThreadPlan_h_
607