1 //===-- ThreadPlan.h --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_ThreadPlan_h_
11 #define liblldb_ThreadPlan_h_
18 // Other libraries and framework includes
20 #include "lldb/Target/Process.h"
21 #include "lldb/Target/StopInfo.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Target/Thread.h"
24 #include "lldb/Target/ThreadPlanTracer.h"
25 #include "lldb/Utility/UserID.h"
26 #include "lldb/lldb-private.h"
28 namespace lldb_private {
30 //------------------------------------------------------------------
32 // This is the pure virtual base class for thread plans.
34 // The thread plans provide the "atoms" of behavior that
35 // all the logical process control, either directly from commands or through
36 // more complex composite plans will rely on.
40 // The thread maintaining a thread plan stack, and you program the actions of a
42 // by pushing plans onto the plan stack.
43 // There is always a "Current" plan, which is the top of the plan stack,
44 // though in some cases
45 // a plan may defer to plans higher in the stack for some piece of information
46 // (let us define that the plan stack grows downwards).
48 // The plan stack is never empty, there is always a Base Plan which persists
50 // of the running process.
55 // The thread plan is generally created and added to the plan stack through the
56 // QueueThreadPlanFor... API
57 // in lldb::Thread. Those API's will return the plan that performs the named
58 // operation in a manner
59 // appropriate for the current process. The plans in lldb/source/Target are
61 // implementations, but a Process plugin can override them.
63 // ValidatePlan is then called. If it returns false, the plan is unshipped.
65 // convenience which keeps us from having to error out of the constructor.
67 // Then the plan is added to the plan stack. When the plan is added to the
68 // plan stack its DidPush
69 // will get called. This is useful if a plan wants to push any additional
70 // plans as it is constructed,
71 // since you need to make sure you're already on the stack before you push
76 // When the target process stops the plans are queried, among other things, for
77 // whether their job is done.
78 // If it is they are moved from the plan stack to the Completed Plan stack in
79 // reverse order from their position
80 // on the plan stack (since multiple plans may be done at a given stop.) This
81 // is used primarily so that
82 // the lldb::Thread::StopInfo for the thread can be set properly. If one plan
83 // pushes another to achieve part of
84 // its job, but it doesn't want that sub-plan to be the one that sets the
85 // StopInfo, then call SetPrivate on the
86 // sub-plan when you create it, and the Thread will pass over that plan in
87 // reporting the reason for the stop.
91 // Your plan may also get discarded, i.e. moved from the plan stack to the
92 // "discarded plan stack". This can
93 // happen, for instance, if the plan is calling a function and the function
94 // call crashes and you want
95 // to unwind the attempt to call. So don't assume that your plan will always
96 // successfully stop. Which leads to:
98 // Cleaning up after your plans:
100 // When the plan is moved from the plan stack its WillPop method is always
101 // called, no matter why. Once it is
102 // moved off the plan stack it is done, and won't get a chance to run again.
104 // undo anything that affects target state in this method. But be sure to
105 // leave the plan able to correctly
106 // fill the StopInfo, however.
107 // N.B. Don't wait to do clean up target state till the destructor, since that
108 // will usually get called when
109 // the target resumes, and you want to leave the target state correct for new
110 // plans in the time between when
111 // your plan gets unshipped and the next resume.
113 // Thread State Checkpoint:
115 // Note that calling functions on target process (ThreadPlanCallFunction) changes
116 // current thread state. The function can be called either by direct user demand or
117 // internally, for example lldb allocates memory on device to calculate breakpoint
118 // condition expression - on Linux it is performed by calling mmap on device.
119 // ThreadStateCheckpoint saves Thread state (stop info and completed
120 // plan stack) to restore it after completing function call.
122 // Over the lifetime of the plan, various methods of the ThreadPlan are then
123 // called in response to changes of state in
124 // the process we are debugging as follows:
128 // When the target process is about to be restarted, the plan's WillResume
130 // giving the plan a chance to prepare for the run. If WillResume returns
132 // process is not restarted. Be sure to set an appropriate error value in the
134 // you have to do this. Note, ThreadPlans actually implement DoWillResume,
135 // WillResume wraps that call.
137 // Next the "StopOthers" method of all the threads are polled, and if one
138 // thread's Current plan
139 // returns "true" then only that thread gets to run. If more than one returns
140 // "true" the threads that want to run solo
141 // get run one by one round robin fashion. Otherwise all are let to run.
143 // Note, the way StopOthers is implemented, the base class implementation just
144 // asks the previous plan. So if your plan
145 // has no opinion about whether it should run stopping others or not, just
146 // don't implement StopOthers, and the parent
149 // Finally, for each thread that is running, it run state is set to the return
150 // of RunState from the
151 // thread's Current plan.
153 // Responding to a stop:
155 // When the target process stops, the plan is called in the following stages:
157 // First the thread asks the Current Plan if it can handle this stop by calling
159 // If the Current plan answers "true" then it is asked if the stop should
160 // percolate all the way to the
161 // user by calling the ShouldStop method. If the current plan doesn't explain
162 // the stop, then we query up
163 // the plan stack for a plan that does explain the stop. The plan that does
164 // explain the stop then needs to
165 // figure out what to do about the plans below it in the stack. If the stop is
166 // recoverable, then the plan that
167 // understands it can just do what it needs to set up to restart, and then
169 // Otherwise, the plan that understood the stop should call DiscardPlanStack to
170 // clean up the stack below it.
171 // Note, plans actually implement DoPlanExplainsStop, the result is cached in
172 // PlanExplainsStop so the DoPlanExplainsStop
173 // itself will only get called once per stop.
177 // In the normal case, when we decide to stop, we will collapse the plan stack
178 // up to the point of the plan that understood
179 // the stop reason. However, if a plan wishes to stay on the stack after an
180 // event it didn't directly handle
181 // it can designate itself a "Master" plan by responding true to IsMasterPlan,
182 // and then if it wants not to be
183 // discarded, it can return false to OkayToDiscard, and it and all its dependent
184 // plans will be preserved when
185 // we resume execution.
187 // The other effect of being a master plan is that when the Master plan is done
188 // , if it has set "OkayToDiscard" to false,
189 // then it will be popped & execution will stop and return to the user.
190 // Remember that if OkayToDiscard is false, the
191 // plan will be popped and control will be given to the next plan above it on
192 // the stack So setting OkayToDiscard to
193 // false means the user will regain control when the MasterPlan is completed.
195 // Between these two controls this allows things like: a MasterPlan/DontDiscard
196 // Step Over to hit a breakpoint, stop and
197 // return control to the user, but then when the user continues, the step out
199 // Even more tricky, when the breakpoint is hit, the user can continue to step
200 // in/step over/etc, and finally when they
201 // continue, they will finish up the Step Over.
203 // FIXME: MasterPlan & OkayToDiscard aren't really orthogonal. MasterPlan
204 // designation means that this plan controls
205 // it's fate and the fate of plans below it. OkayToDiscard tells whether the
206 // MasterPlan wants to stay on the stack. I
207 // originally thought "MasterPlan-ness" would need to be a fixed characteristic
208 // of a ThreadPlan, in which case you needed
209 // the extra control. But that doesn't seem to be true. So we should be able
210 // to convert to only MasterPlan status to mean
211 // the current "MasterPlan/DontDiscard". Then no plans would be MasterPlans by
212 // default, and you would set the ones you
213 // wanted to be "user level" in this way.
216 // Actually Stopping:
218 // If a plan says responds "true" to ShouldStop, then it is asked if it's job
219 // is complete by calling
220 // MischiefManaged. If that returns true, the plan is popped from the plan
221 // stack and added to the
222 // Completed Plan Stack. Then the next plan in the stack is asked if it
223 // ShouldStop, and it returns "true",
224 // it is asked if it is done, and if yes popped, and so on till we reach a plan
227 // Since you often know in the ShouldStop method whether your plan is complete,
228 // as a convenience you can call
229 // SetPlanComplete and the ThreadPlan implementation of MischiefManaged will
230 // return "true", without your having
231 // to redo the calculation when your sub-classes MischiefManaged is called. If
232 // you call SetPlanComplete, you can
233 // later use IsPlanComplete to determine whether the plan is complete. This is
234 // only a convenience for sub-classes,
235 // the logic in lldb::Thread will only call MischiefManaged.
237 // One slightly tricky point is you have to be careful using SetPlanComplete in
238 // PlanExplainsStop because you
239 // are not guaranteed that PlanExplainsStop for a plan will get called before
240 // ShouldStop gets called. If your sub-plan
241 // explained the stop and then popped itself, only your ShouldStop will get
244 // If ShouldStop for any thread returns "true", then the WillStop method of the
246 // all threads will be called, the stop event is placed on the Process's public
248 // control returns to the upper layers of the debugger.
250 // Reporting the stop:
252 // When the process stops, the thread is given a StopReason, in the form of a
253 // StopInfo object. If there is a completed
254 // plan corresponding to the stop, then the "actual" stop reason can be
255 // suppressed, and instead a StopInfoThreadPlan
256 // object will be cons'ed up from the top completed plan in the stack.
257 // However, if the plan doesn't want to be
258 // the stop reason, then it can call SetPlanComplete and pass in "false" for
259 // the "success" parameter. In that case,
260 // the real stop reason will be used instead. One exapmle of this is the
261 // "StepRangeStepIn" thread plan. If it stops
262 // because of a crash or breakpoint hit, it wants to unship itself, because it
263 // isn't so useful to have step in keep going
264 // after a breakpoint hit. But it can't be the reason for the stop or no-one
265 // would see that they had hit a breakpoint.
267 // Cleaning up the plan stack:
269 // One of the complications of MasterPlans is that you may get past the limits
270 // of a plan without triggering it to clean
271 // itself up. For instance, if you are doing a MasterPlan StepOver, and hit a
272 // breakpoint in a called function, then
273 // step over enough times to step out of the initial StepOver range, each of
274 // the step overs will explain the stop &
275 // take themselves off the stack, but control would never be returned to the
276 // original StepOver. Eventually, the user
277 // will continue, and when that continue stops, the old stale StepOver plan
278 // that was left on the stack will get woken
279 // up and notice it is done. But that can leave junk on the stack for a while.
280 // To avoid that, the plans implement a
281 // "IsPlanStale" method, that can check whether it is relevant anymore. On
282 // stop, after the regular plan negotiation,
283 // the remaining plan stack is consulted and if any plan says it is stale, it
284 // and the plans below it are discarded from
287 // Automatically Resuming:
289 // If ShouldStop for all threads returns "false", then the target process will
290 // resume. This then cycles back to
293 // Reporting eStateStopped events when the target is restarted:
295 // If a plan decides to auto-continue the target by returning "false" from
296 // ShouldStop, then it will be asked
297 // whether the Stopped event should still be reported. For instance, if you
298 // hit a breakpoint that is a User set
299 // breakpoint, but the breakpoint callback said to continue the target process,
300 // you might still want to inform
301 // the upper layers of lldb that the stop had happened.
302 // The way this works is every thread gets to vote on whether to report the
303 // stop. If all votes are eVoteNoOpinion,
304 // then the thread list will decide what to do (at present it will pretty much
305 // always suppress these stopped events.)
306 // If there is an eVoteYes, then the event will be reported regardless of the
307 // other votes. If there is an eVoteNo
308 // and no eVoteYes's, then the event won't be reported.
310 // One other little detail here, sometimes a plan will push another plan onto
311 // the plan stack to do some part of
312 // the first plan's job, and it would be convenient to tell that plan how it
313 // should respond to ShouldReportStop.
314 // You can do that by setting the stop_vote in the child plan when you create
317 // Suppressing the initial eStateRunning event:
319 // The private process running thread will take care of ensuring that only one
320 // "eStateRunning" event will be
321 // delivered to the public Process broadcaster per public eStateStopped event.
322 // However there are some cases
323 // where the public state of this process is eStateStopped, but a thread plan
324 // needs to restart the target, but
325 // doesn't want the running event to be publicly broadcast. The obvious
326 // example of this is running functions
327 // by hand as part of expression evaluation. To suppress the running event
328 // return eVoteNo from ShouldReportStop,
329 // to force a running event to be reported return eVoteYes, in general though
330 // you should return eVoteNoOpinion
331 // which will allow the ThreadList to figure out the right thing to do.
332 // The run_vote argument to the constructor works like stop_vote, and is a way
333 // for a plan to instruct a sub-plan
334 // on how to respond to ShouldReportStop.
336 //------------------------------------------------------------------
338 class ThreadPlan : public std::enable_shared_from_this<ThreadPlan>,
341 typedef enum { eAllThreads, eSomeThreads, eThisThread } ThreadScope;
343 // We use these enums so that we can cast a base thread plan to it's real type
344 // without having to resort
345 // to dynamic casting.
352 eKindStepInstruction,
354 eKindStepOverBreakpoint,
364 //------------------------------------------------------------------
365 // Constructors and Destructors
366 //------------------------------------------------------------------
367 ThreadPlan(ThreadPlanKind kind, const char *name, Thread &thread,
368 Vote stop_vote, Vote run_vote);
370 virtual ~ThreadPlan();
372 //------------------------------------------------------------------
373 /// Returns the name of this thread plan.
376 /// A const char * pointer to the thread plan's name.
377 //------------------------------------------------------------------
378 const char *GetName() const { return m_name.c_str(); }
380 //------------------------------------------------------------------
381 /// Returns the Thread that is using this thread plan.
384 /// A pointer to the thread plan's owning thread.
385 //------------------------------------------------------------------
386 Thread &GetThread() { return m_thread; }
388 const Thread &GetThread() const { return m_thread; }
390 Target &GetTarget() { return m_thread.GetProcess()->GetTarget(); }
392 const Target &GetTarget() const { return m_thread.GetProcess()->GetTarget(); }
394 //------------------------------------------------------------------
395 /// Print a description of this thread to the stream \a s.
399 /// The stream to which to print the description.
402 /// The level of description desired. Note that eDescriptionLevelBrief
403 /// will be used in the stop message printed when the plan is complete.
404 //------------------------------------------------------------------
405 virtual void GetDescription(Stream *s, lldb::DescriptionLevel level) = 0;
407 //------------------------------------------------------------------
408 /// Returns whether this plan could be successfully created.
411 /// A stream to which to print some reason why the plan could not be
416 /// \b true if the plan should be queued, \b false otherwise.
417 //------------------------------------------------------------------
418 virtual bool ValidatePlan(Stream *error) = 0;
420 bool TracerExplainsStop() {
424 return m_tracer_sp->TracerExplainsStop();
427 lldb::StateType RunState();
429 bool PlanExplainsStop(Event *event_ptr);
431 virtual bool ShouldStop(Event *event_ptr) = 0;
433 virtual bool ShouldAutoContinue(Event *event_ptr) { return false; }
435 // Whether a "stop class" event should be reported to the "outside world". In
437 // if a thread plan is active, events should not be reported.
439 virtual Vote ShouldReportStop(Event *event_ptr);
441 virtual Vote ShouldReportRun(Event *event_ptr);
443 virtual void SetStopOthers(bool new_value);
445 virtual bool StopOthers();
447 // This is the wrapper for DoWillResume that does generic ThreadPlan logic,
449 // calls DoWillResume.
450 bool WillResume(lldb::StateType resume_state, bool current_plan);
452 virtual bool WillStop() = 0;
454 bool IsMasterPlan() { return m_is_master_plan; }
456 bool SetIsMasterPlan(bool value) {
457 bool old_value = m_is_master_plan;
458 m_is_master_plan = value;
462 virtual bool OkayToDiscard();
464 void SetOkayToDiscard(bool value) { m_okay_to_discard = value; }
466 // The base class MischiefManaged does some cleanup - so you have to call it
467 // in your MischiefManaged derived class.
468 virtual bool MischiefManaged();
470 virtual void ThreadDestroyed() {
471 // Any cleanup that a plan might want to do in case the thread goes away
472 // in the middle of the plan being queued on a thread can be done here.
475 bool GetPrivate() { return m_plan_private; }
477 void SetPrivate(bool input) { m_plan_private = input; }
479 virtual void DidPush();
481 virtual void WillPop();
483 // This pushes a plan onto the plan stack of the current plan's thread.
484 void PushPlan(lldb::ThreadPlanSP &thread_plan_sp) {
485 m_thread.PushPlan(thread_plan_sp);
488 ThreadPlanKind GetKind() const { return m_kind; }
490 bool IsPlanComplete();
492 void SetPlanComplete(bool success = true);
494 virtual bool IsPlanStale() { return false; }
496 bool PlanSucceeded() { return m_plan_succeeded; }
498 virtual bool IsBasePlan() { return false; }
500 lldb::ThreadPlanTracerSP &GetThreadPlanTracer() { return m_tracer_sp; }
502 void SetThreadPlanTracer(lldb::ThreadPlanTracerSP new_tracer_sp) {
503 m_tracer_sp = new_tracer_sp;
507 if (m_tracer_sp && m_tracer_sp->TracingEnabled())
511 // Some thread plans hide away the actual stop info which caused any
512 // particular stop. For
513 // instance the ThreadPlanCallFunction restores the original stop reason so
515 // calling a few functions won't lose the history of the run.
516 // This call can be implemented to get you back to the real stop info.
517 virtual lldb::StopInfoSP GetRealStopInfo() { return m_thread.GetStopInfo(); }
519 // If the completion of the thread plan stepped out of a function, the return
520 // value of the function
521 // might have been captured by the thread plan (currently only
522 // ThreadPlanStepOut does this.)
523 // If so, the ReturnValueObject can be retrieved from here.
525 virtual lldb::ValueObjectSP GetReturnValueObject() {
526 return lldb::ValueObjectSP();
529 // If the thread plan managing the evaluation of a user expression lives
530 // longer than the command
531 // that instigated the expression (generally because the expression evaluation
532 // hit a breakpoint, and
533 // the user regained control at that point) a subsequent process control
534 // command step/continue/etc. might
535 // complete the expression evaluations. If so, the result of the expression
536 // evaluation will show up here.
538 virtual lldb::ExpressionVariableSP GetExpressionVariable() {
539 return lldb::ExpressionVariableSP();
542 // If a thread plan stores the state before it was run, then you might
543 // want to restore the state when it is done. This will do that job.
544 // This is mostly useful for artificial plans like CallFunction plans.
546 virtual bool RestoreThreadState() {
547 // Nothing to do in general.
551 virtual bool IsVirtualStep() { return false; }
553 virtual bool SetIterationCount(size_t count) {
554 if (m_takes_iteration_count) {
555 // Don't tell me to do something 0 times...
558 m_iteration_count = count;
560 return m_takes_iteration_count;
563 virtual size_t GetIterationCount() {
564 if (!m_takes_iteration_count)
567 return m_iteration_count;
571 //------------------------------------------------------------------
572 // Classes that inherit from ThreadPlan can see and modify these
573 //------------------------------------------------------------------
575 virtual bool DoWillResume(lldb::StateType resume_state, bool current_plan) {
579 virtual bool DoPlanExplainsStop(Event *event_ptr) = 0;
581 // This gets the previous plan to the current plan (for forwarding requests).
582 // This is mostly a formal requirement, it allows us to make the Thread's
583 // GetPreviousPlan protected, but only friend ThreadPlan to thread.
585 ThreadPlan *GetPreviousPlan() { return m_thread.GetPreviousPlan(this); }
587 // This forwards the private Thread::GetPrivateStopInfo which is generally
589 // ThreadPlan's need to know.
591 lldb::StopInfoSP GetPrivateStopInfo() {
592 return m_thread.GetPrivateStopInfo();
595 void SetStopInfo(lldb::StopInfoSP stop_reason_sp) {
596 m_thread.SetStopInfo(stop_reason_sp);
599 void CachePlanExplainsStop(bool does_explain) {
600 m_cached_plan_explains_stop = does_explain ? eLazyBoolYes : eLazyBoolNo;
603 LazyBool GetCachedPlanExplainsStop() const {
604 return m_cached_plan_explains_stop;
607 virtual lldb::StateType GetPlanRunState() = 0;
609 bool IsUsuallyUnexplainedStopReason(lldb::StopReason);
614 bool m_takes_iteration_count = false;
615 int32_t m_iteration_count = 1;
618 //------------------------------------------------------------------
619 // For ThreadPlan only
620 //------------------------------------------------------------------
621 static lldb::user_id_t GetNextID();
623 ThreadPlanKind m_kind;
625 std::recursive_mutex m_plan_complete_mutex;
626 LazyBool m_cached_plan_explains_stop;
627 bool m_plan_complete;
629 bool m_okay_to_discard;
630 bool m_is_master_plan;
631 bool m_plan_succeeded;
633 lldb::ThreadPlanTracerSP m_tracer_sp;
636 DISALLOW_COPY_AND_ASSIGN(ThreadPlan);
639 //----------------------------------------------------------------------
641 // Threads are assumed to always have at least one plan on the plan stack.
642 // This is put on the plan stack when a thread is destroyed so that if you
643 // accidentally access a thread after it is destroyed you won't crash.
644 // But asking questions of the ThreadPlanNull is definitely an error.
645 //----------------------------------------------------------------------
647 class ThreadPlanNull : public ThreadPlan {
649 ThreadPlanNull(Thread &thread);
650 ~ThreadPlanNull() override;
652 void GetDescription(Stream *s, lldb::DescriptionLevel level) override;
654 bool ValidatePlan(Stream *error) override;
656 bool ShouldStop(Event *event_ptr) override;
658 bool MischiefManaged() override;
660 bool WillStop() override;
662 bool IsBasePlan() override { return true; }
664 bool OkayToDiscard() override { return false; }
667 bool DoPlanExplainsStop(Event *event_ptr) override;
669 lldb::StateType GetPlanRunState() override;
671 DISALLOW_COPY_AND_ASSIGN(ThreadPlanNull);
674 } // namespace lldb_private
676 #endif // liblldb_ThreadPlan_h_