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