1 //===-- Thread.cpp ----------------------------------------------*- 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 // C Includes 11 // C++ Includes 12 #include <mutex> 13 // Other libraries and framework includes 14 // Project includes 15 #include "lldb/Breakpoint/BreakpointLocation.h" 16 #include "lldb/Core/Debugger.h" 17 #include "lldb/Core/Log.h" 18 #include "lldb/Core/FormatEntity.h" 19 #include "lldb/Core/Module.h" 20 #include "lldb/Core/State.h" 21 #include "lldb/Core/Stream.h" 22 #include "lldb/Core/StreamString.h" 23 #include "lldb/Core/RegularExpression.h" 24 #include "lldb/Core/ValueObject.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Interpreter/OptionValueFileSpecList.h" 27 #include "lldb/Interpreter/OptionValueProperties.h" 28 #include "lldb/Interpreter/Property.h" 29 #include "lldb/Symbol/Function.h" 30 #include "lldb/Target/ABI.h" 31 #include "lldb/Target/DynamicLoader.h" 32 #include "lldb/Target/ExecutionContext.h" 33 #include "lldb/Target/Process.h" 34 #include "lldb/Target/RegisterContext.h" 35 #include "lldb/Target/StopInfo.h" 36 #include "lldb/Target/SystemRuntime.h" 37 #include "lldb/Target/Target.h" 38 #include "lldb/Target/Thread.h" 39 #include "lldb/Target/ThreadPlan.h" 40 #include "lldb/Target/ThreadPlanCallFunction.h" 41 #include "lldb/Target/ThreadPlanBase.h" 42 #include "lldb/Target/ThreadPlanPython.h" 43 #include "lldb/Target/ThreadPlanStepInstruction.h" 44 #include "lldb/Target/ThreadPlanStepOut.h" 45 #include "lldb/Target/ThreadPlanStepOverBreakpoint.h" 46 #include "lldb/Target/ThreadPlanStepThrough.h" 47 #include "lldb/Target/ThreadPlanStepInRange.h" 48 #include "lldb/Target/ThreadPlanStepOverRange.h" 49 #include "lldb/Target/ThreadPlanRunToAddress.h" 50 #include "lldb/Target/ThreadPlanStepUntil.h" 51 #include "lldb/Target/ThreadSpec.h" 52 #include "lldb/Target/Unwind.h" 53 #include "Plugins/Process/Utility/UnwindLLDB.h" 54 #include "Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h" 55 56 using namespace lldb; 57 using namespace lldb_private; 58 59 const ThreadPropertiesSP & 60 Thread::GetGlobalProperties() 61 { 62 // NOTE: intentional leak so we don't crash if global destructor chain gets 63 // called as other threads still use the result of this function 64 static ThreadPropertiesSP *g_settings_sp_ptr = nullptr; 65 static std::once_flag g_once_flag; 66 std::call_once(g_once_flag, []() { 67 g_settings_sp_ptr = new ThreadPropertiesSP(new ThreadProperties (true)); 68 }); 69 return *g_settings_sp_ptr; 70 } 71 72 static PropertyDefinition 73 g_properties[] = 74 { 75 { "step-in-avoid-nodebug", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, step-in will not stop in functions with no debug information." }, 76 { "step-out-avoid-nodebug", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, when step-in/step-out/step-over leave the current frame, they will continue to step out till they come to a function with " 77 "debug information. Passing a frame argument to step-out will override this option." }, 78 { "step-avoid-regexp", OptionValue::eTypeRegex , true , 0, "^std::", nullptr, "A regular expression defining functions step-in won't stop in." }, 79 { "step-avoid-libraries", OptionValue::eTypeFileSpecList , true , 0, nullptr, nullptr, "A list of libraries that source stepping won't stop in." }, 80 { "trace-thread", OptionValue::eTypeBoolean, false, false, nullptr, nullptr, "If true, this thread will single-step and log execution." }, 81 { nullptr , OptionValue::eTypeInvalid, false, 0 , nullptr, nullptr, nullptr } 82 }; 83 84 enum { 85 ePropertyStepInAvoidsNoDebug, 86 ePropertyStepOutAvoidsNoDebug, 87 ePropertyStepAvoidRegex, 88 ePropertyStepAvoidLibraries, 89 ePropertyEnableThreadTrace 90 }; 91 92 class ThreadOptionValueProperties : public OptionValueProperties 93 { 94 public: 95 ThreadOptionValueProperties (const ConstString &name) : 96 OptionValueProperties (name) 97 { 98 } 99 100 // This constructor is used when creating ThreadOptionValueProperties when it 101 // is part of a new lldb_private::Thread instance. It will copy all current 102 // global property values as needed 103 ThreadOptionValueProperties (ThreadProperties *global_properties) : 104 OptionValueProperties(*global_properties->GetValueProperties()) 105 { 106 } 107 108 const Property * 109 GetPropertyAtIndex(const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const override 110 { 111 // When getting the value for a key from the thread options, we will always 112 // try and grab the setting from the current thread if there is one. Else we just 113 // use the one from this instance. 114 if (exe_ctx) 115 { 116 Thread *thread = exe_ctx->GetThreadPtr(); 117 if (thread) 118 { 119 ThreadOptionValueProperties *instance_properties = static_cast<ThreadOptionValueProperties *>(thread->GetValueProperties().get()); 120 if (this != instance_properties) 121 return instance_properties->ProtectedGetPropertyAtIndex (idx); 122 } 123 } 124 return ProtectedGetPropertyAtIndex (idx); 125 } 126 }; 127 128 ThreadProperties::ThreadProperties (bool is_global) : 129 Properties () 130 { 131 if (is_global) 132 { 133 m_collection_sp.reset (new ThreadOptionValueProperties(ConstString("thread"))); 134 m_collection_sp->Initialize(g_properties); 135 } 136 else 137 m_collection_sp.reset (new ThreadOptionValueProperties(Thread::GetGlobalProperties().get())); 138 } 139 140 ThreadProperties::~ThreadProperties() = default; 141 142 const RegularExpression * 143 ThreadProperties::GetSymbolsToAvoidRegexp() 144 { 145 const uint32_t idx = ePropertyStepAvoidRegex; 146 return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex(nullptr, idx); 147 } 148 149 FileSpecList & 150 ThreadProperties::GetLibrariesToAvoid() const 151 { 152 const uint32_t idx = ePropertyStepAvoidLibraries; 153 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx); 154 assert(option_value); 155 return option_value->GetCurrentValue(); 156 } 157 158 bool 159 ThreadProperties::GetTraceEnabledState() const 160 { 161 const uint32_t idx = ePropertyEnableThreadTrace; 162 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0); 163 } 164 165 bool 166 ThreadProperties::GetStepInAvoidsNoDebug() const 167 { 168 const uint32_t idx = ePropertyStepInAvoidsNoDebug; 169 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0); 170 } 171 172 bool 173 ThreadProperties::GetStepOutAvoidsNoDebug() const 174 { 175 const uint32_t idx = ePropertyStepOutAvoidsNoDebug; 176 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0); 177 } 178 179 //------------------------------------------------------------------ 180 // Thread Event Data 181 //------------------------------------------------------------------ 182 183 const ConstString & 184 Thread::ThreadEventData::GetFlavorString () 185 { 186 static ConstString g_flavor ("Thread::ThreadEventData"); 187 return g_flavor; 188 } 189 190 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp) : 191 m_thread_sp (thread_sp), 192 m_stack_id () 193 { 194 } 195 196 Thread::ThreadEventData::ThreadEventData (const lldb::ThreadSP thread_sp, const StackID &stack_id) : 197 m_thread_sp (thread_sp), 198 m_stack_id (stack_id) 199 { 200 } 201 202 Thread::ThreadEventData::ThreadEventData () : 203 m_thread_sp (), 204 m_stack_id () 205 { 206 } 207 208 Thread::ThreadEventData::~ThreadEventData() = default; 209 210 void 211 Thread::ThreadEventData::Dump (Stream *s) const 212 { 213 } 214 215 const Thread::ThreadEventData * 216 Thread::ThreadEventData::GetEventDataFromEvent (const Event *event_ptr) 217 { 218 if (event_ptr) 219 { 220 const EventData *event_data = event_ptr->GetData(); 221 if (event_data && event_data->GetFlavor() == ThreadEventData::GetFlavorString()) 222 return static_cast <const ThreadEventData *> (event_ptr->GetData()); 223 } 224 return nullptr; 225 } 226 227 ThreadSP 228 Thread::ThreadEventData::GetThreadFromEvent (const Event *event_ptr) 229 { 230 ThreadSP thread_sp; 231 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr); 232 if (event_data) 233 thread_sp = event_data->GetThread(); 234 return thread_sp; 235 } 236 237 StackID 238 Thread::ThreadEventData::GetStackIDFromEvent (const Event *event_ptr) 239 { 240 StackID stack_id; 241 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr); 242 if (event_data) 243 stack_id = event_data->GetStackID(); 244 return stack_id; 245 } 246 247 StackFrameSP 248 Thread::ThreadEventData::GetStackFrameFromEvent (const Event *event_ptr) 249 { 250 const ThreadEventData *event_data = GetEventDataFromEvent (event_ptr); 251 StackFrameSP frame_sp; 252 if (event_data) 253 { 254 ThreadSP thread_sp = event_data->GetThread(); 255 if (thread_sp) 256 { 257 frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID (event_data->GetStackID()); 258 } 259 } 260 return frame_sp; 261 } 262 263 //------------------------------------------------------------------ 264 // Thread class 265 //------------------------------------------------------------------ 266 267 ConstString & 268 Thread::GetStaticBroadcasterClass () 269 { 270 static ConstString class_name ("lldb.thread"); 271 return class_name; 272 } 273 274 Thread::Thread (Process &process, lldb::tid_t tid, bool use_invalid_index_id) : 275 ThreadProperties (false), 276 UserID (tid), 277 Broadcaster(process.GetTarget().GetDebugger().GetBroadcasterManager(), Thread::GetStaticBroadcasterClass().AsCString()), 278 m_process_wp (process.shared_from_this()), 279 m_stop_info_sp (), 280 m_stop_info_stop_id (0), 281 m_stop_info_override_stop_id (0), 282 m_index_id (use_invalid_index_id ? LLDB_INVALID_INDEX32 : process.GetNextThreadIndexID(tid)), 283 m_reg_context_sp (), 284 m_state (eStateUnloaded), 285 m_state_mutex (Mutex::eMutexTypeRecursive), 286 m_plan_stack (), 287 m_completed_plan_stack(), 288 m_frame_mutex (Mutex::eMutexTypeRecursive), 289 m_curr_frames_sp (), 290 m_prev_frames_sp (), 291 m_resume_signal (LLDB_INVALID_SIGNAL_NUMBER), 292 m_resume_state (eStateRunning), 293 m_temporary_resume_state (eStateRunning), 294 m_unwinder_ap (), 295 m_destroy_called (false), 296 m_override_should_notify (eLazyBoolCalculate), 297 m_extended_info_fetched (false), 298 m_extended_info () 299 { 300 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 301 if (log) 302 log->Printf ("%p Thread::Thread(tid = 0x%4.4" PRIx64 ")", 303 static_cast<void*>(this), GetID()); 304 305 CheckInWithManager(); 306 QueueFundamentalPlan(true); 307 } 308 309 Thread::~Thread() 310 { 311 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT)); 312 if (log) 313 log->Printf ("%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")", 314 static_cast<void*>(this), GetID()); 315 /// If you hit this assert, it means your derived class forgot to call DoDestroy in its destructor. 316 assert (m_destroy_called); 317 } 318 319 void 320 Thread::DestroyThread () 321 { 322 // Tell any plans on the plan stacks that the thread is being destroyed since 323 // any plans that have a thread go away in the middle of might need 324 // to do cleanup, or in some cases NOT do cleanup... 325 for (auto plan : m_plan_stack) 326 plan->ThreadDestroyed(); 327 328 for (auto plan : m_discarded_plan_stack) 329 plan->ThreadDestroyed(); 330 331 for (auto plan : m_completed_plan_stack) 332 plan->ThreadDestroyed(); 333 334 m_destroy_called = true; 335 m_plan_stack.clear(); 336 m_discarded_plan_stack.clear(); 337 m_completed_plan_stack.clear(); 338 339 // Push a ThreadPlanNull on the plan stack. That way we can continue assuming that the 340 // plan stack is never empty, but if somebody errantly asks questions of a destroyed thread 341 // without checking first whether it is destroyed, they won't crash. 342 ThreadPlanSP null_plan_sp(new ThreadPlanNull (*this)); 343 m_plan_stack.push_back (null_plan_sp); 344 345 m_stop_info_sp.reset(); 346 m_reg_context_sp.reset(); 347 m_unwinder_ap.reset(); 348 Mutex::Locker locker(m_frame_mutex); 349 m_curr_frames_sp.reset(); 350 m_prev_frames_sp.reset(); 351 } 352 353 void 354 Thread::BroadcastSelectedFrameChange(StackID &new_frame_id) 355 { 356 if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged)) 357 BroadcastEvent(eBroadcastBitSelectedFrameChanged, new ThreadEventData (this->shared_from_this(), new_frame_id)); 358 } 359 360 lldb::StackFrameSP 361 Thread::GetSelectedFrame() 362 { 363 StackFrameListSP stack_frame_list_sp(GetStackFrameList()); 364 StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex (stack_frame_list_sp->GetSelectedFrameIndex()); 365 FunctionOptimizationWarning (frame_sp.get()); 366 return frame_sp; 367 } 368 369 uint32_t 370 Thread::SetSelectedFrame (lldb_private::StackFrame *frame, bool broadcast) 371 { 372 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame); 373 if (broadcast) 374 BroadcastSelectedFrameChange(frame->GetStackID()); 375 FunctionOptimizationWarning (frame); 376 return ret_value; 377 } 378 379 bool 380 Thread::SetSelectedFrameByIndex (uint32_t frame_idx, bool broadcast) 381 { 382 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex (frame_idx)); 383 if (frame_sp) 384 { 385 GetStackFrameList()->SetSelectedFrame(frame_sp.get()); 386 if (broadcast) 387 BroadcastSelectedFrameChange(frame_sp->GetStackID()); 388 FunctionOptimizationWarning (frame_sp.get()); 389 return true; 390 } 391 else 392 return false; 393 } 394 395 bool 396 Thread::SetSelectedFrameByIndexNoisily (uint32_t frame_idx, Stream &output_stream) 397 { 398 const bool broadcast = true; 399 bool success = SetSelectedFrameByIndex (frame_idx, broadcast); 400 if (success) 401 { 402 StackFrameSP frame_sp = GetSelectedFrame(); 403 if (frame_sp) 404 { 405 bool already_shown = false; 406 SymbolContext frame_sc(frame_sp->GetSymbolContext(eSymbolContextLineEntry)); 407 if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() && frame_sc.line_entry.file && frame_sc.line_entry.line != 0) 408 { 409 already_shown = Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line); 410 } 411 412 bool show_frame_info = true; 413 bool show_source = !already_shown; 414 FunctionOptimizationWarning (frame_sp.get()); 415 return frame_sp->GetStatus (output_stream, show_frame_info, show_source); 416 } 417 return false; 418 } 419 else 420 return false; 421 } 422 423 void 424 Thread::FunctionOptimizationWarning (StackFrame *frame) 425 { 426 if (frame && frame->HasDebugInformation() && GetProcess()->GetWarningsOptimization()) 427 { 428 SymbolContext sc = frame->GetSymbolContext (eSymbolContextFunction | eSymbolContextModule); 429 GetProcess()->PrintWarningOptimization (sc); 430 } 431 } 432 433 lldb::StopInfoSP 434 Thread::GetStopInfo () 435 { 436 if (m_destroy_called) 437 return m_stop_info_sp; 438 439 ThreadPlanSP plan_sp (GetCompletedPlan()); 440 ProcessSP process_sp (GetProcess()); 441 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX; 442 if (plan_sp && plan_sp->PlanSucceeded()) 443 { 444 return StopInfo::CreateStopReasonWithPlan (plan_sp, GetReturnValueObject(), GetExpressionVariable()); 445 } 446 else 447 { 448 if ((m_stop_info_stop_id == stop_id) || // Stop info is valid, just return what we have (even if empty) 449 (m_stop_info_sp && m_stop_info_sp->IsValid())) // Stop info is valid, just return what we have 450 { 451 return m_stop_info_sp; 452 } 453 else 454 { 455 GetPrivateStopInfo (); 456 return m_stop_info_sp; 457 } 458 } 459 } 460 461 lldb::StopInfoSP 462 Thread::GetPrivateStopInfo () 463 { 464 if (m_destroy_called) 465 return m_stop_info_sp; 466 467 ProcessSP process_sp (GetProcess()); 468 if (process_sp) 469 { 470 const uint32_t process_stop_id = process_sp->GetStopID(); 471 if (m_stop_info_stop_id != process_stop_id) 472 { 473 if (m_stop_info_sp) 474 { 475 if (m_stop_info_sp->IsValid() 476 || IsStillAtLastBreakpointHit() 477 || GetCurrentPlan()->IsVirtualStep()) 478 SetStopInfo (m_stop_info_sp); 479 else 480 m_stop_info_sp.reset(); 481 } 482 483 if (!m_stop_info_sp) 484 { 485 if (!CalculateStopInfo()) 486 SetStopInfo (StopInfoSP()); 487 } 488 } 489 490 // The stop info can be manually set by calling Thread::SetStopInfo() 491 // prior to this function ever getting called, so we can't rely on 492 // "m_stop_info_stop_id != process_stop_id" as the condition for 493 // the if statement below, we must also check the stop info to see 494 // if we need to override it. See the header documentation in 495 // Process::GetStopInfoOverrideCallback() for more information on 496 // the stop info override callback. 497 if (m_stop_info_override_stop_id != process_stop_id) 498 { 499 m_stop_info_override_stop_id = process_stop_id; 500 if (m_stop_info_sp) 501 { 502 ArchSpec::StopInfoOverrideCallbackType callback = GetProcess()->GetStopInfoOverrideCallback(); 503 if (callback) 504 callback(*this); 505 } 506 } 507 } 508 return m_stop_info_sp; 509 } 510 511 lldb::StopReason 512 Thread::GetStopReason() 513 { 514 lldb::StopInfoSP stop_info_sp (GetStopInfo ()); 515 if (stop_info_sp) 516 return stop_info_sp->GetStopReason(); 517 return eStopReasonNone; 518 } 519 520 bool 521 Thread::StopInfoIsUpToDate() const 522 { 523 ProcessSP process_sp (GetProcess()); 524 if (process_sp) 525 return m_stop_info_stop_id == process_sp->GetStopID(); 526 else 527 return true; // Process is no longer around so stop info is always up to date... 528 } 529 530 void 531 Thread::SetStopInfo (const lldb::StopInfoSP &stop_info_sp) 532 { 533 m_stop_info_sp = stop_info_sp; 534 if (m_stop_info_sp) 535 { 536 m_stop_info_sp->MakeStopInfoValid(); 537 // If we are overriding the ShouldReportStop, do that here: 538 if (m_override_should_notify != eLazyBoolCalculate) 539 m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes); 540 } 541 542 ProcessSP process_sp (GetProcess()); 543 if (process_sp) 544 m_stop_info_stop_id = process_sp->GetStopID(); 545 else 546 m_stop_info_stop_id = UINT32_MAX; 547 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 548 if (log) 549 log->Printf("%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)", 550 static_cast<void*>(this), GetID(), 551 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>", 552 m_stop_info_stop_id); 553 } 554 555 void 556 Thread::SetShouldReportStop (Vote vote) 557 { 558 if (vote == eVoteNoOpinion) 559 return; 560 else 561 { 562 m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo); 563 if (m_stop_info_sp) 564 m_stop_info_sp->OverrideShouldNotify (m_override_should_notify == eLazyBoolYes); 565 } 566 } 567 568 void 569 Thread::SetStopInfoToNothing() 570 { 571 // Note, we can't just NULL out the private reason, or the native thread implementation will try to 572 // go calculate it again. For now, just set it to a Unix Signal with an invalid signal number. 573 SetStopInfo (StopInfo::CreateStopReasonWithSignal (*this, LLDB_INVALID_SIGNAL_NUMBER)); 574 } 575 576 bool 577 Thread::ThreadStoppedForAReason (void) 578 { 579 return (bool) GetPrivateStopInfo (); 580 } 581 582 bool 583 Thread::CheckpointThreadState (ThreadStateCheckpoint &saved_state) 584 { 585 saved_state.register_backup_sp.reset(); 586 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0)); 587 if (frame_sp) 588 { 589 lldb::RegisterCheckpointSP reg_checkpoint_sp(new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression)); 590 if (reg_checkpoint_sp) 591 { 592 lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext()); 593 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues (*reg_checkpoint_sp)) 594 saved_state.register_backup_sp = reg_checkpoint_sp; 595 } 596 } 597 if (!saved_state.register_backup_sp) 598 return false; 599 600 saved_state.stop_info_sp = GetStopInfo(); 601 ProcessSP process_sp (GetProcess()); 602 if (process_sp) 603 saved_state.orig_stop_id = process_sp->GetStopID(); 604 saved_state.current_inlined_depth = GetCurrentInlinedDepth(); 605 606 return true; 607 } 608 609 bool 610 Thread::RestoreRegisterStateFromCheckpoint (ThreadStateCheckpoint &saved_state) 611 { 612 if (saved_state.register_backup_sp) 613 { 614 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex (0)); 615 if (frame_sp) 616 { 617 lldb::RegisterContextSP reg_ctx_sp (frame_sp->GetRegisterContext()); 618 if (reg_ctx_sp) 619 { 620 bool ret = reg_ctx_sp->WriteAllRegisterValues (*saved_state.register_backup_sp); 621 622 // Clear out all stack frames as our world just changed. 623 ClearStackFrames(); 624 reg_ctx_sp->InvalidateIfNeeded(true); 625 if (m_unwinder_ap.get()) 626 m_unwinder_ap->Clear(); 627 return ret; 628 } 629 } 630 } 631 return false; 632 } 633 634 bool 635 Thread::RestoreThreadStateFromCheckpoint (ThreadStateCheckpoint &saved_state) 636 { 637 if (saved_state.stop_info_sp) 638 saved_state.stop_info_sp->MakeStopInfoValid(); 639 SetStopInfo(saved_state.stop_info_sp); 640 GetStackFrameList()->SetCurrentInlinedDepth (saved_state.current_inlined_depth); 641 return true; 642 } 643 644 StateType 645 Thread::GetState() const 646 { 647 // If any other threads access this we will need a mutex for it 648 Mutex::Locker locker(m_state_mutex); 649 return m_state; 650 } 651 652 void 653 Thread::SetState(StateType state) 654 { 655 Mutex::Locker locker(m_state_mutex); 656 m_state = state; 657 } 658 659 void 660 Thread::WillStop() 661 { 662 ThreadPlan *current_plan = GetCurrentPlan(); 663 664 // FIXME: I may decide to disallow threads with no plans. In which 665 // case this should go to an assert. 666 667 if (!current_plan) 668 return; 669 670 current_plan->WillStop(); 671 } 672 673 void 674 Thread::SetupForResume () 675 { 676 if (GetResumeState() != eStateSuspended) 677 { 678 // If we're at a breakpoint push the step-over breakpoint plan. Do this before 679 // telling the current plan it will resume, since we might change what the current 680 // plan is. 681 682 lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext()); 683 if (reg_ctx_sp) 684 { 685 const addr_t thread_pc = reg_ctx_sp->GetPC(); 686 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc); 687 if (bp_site_sp) 688 { 689 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything 690 // special to step over a breakpoint. 691 692 ThreadPlan *cur_plan = GetCurrentPlan(); 693 694 bool push_step_over_bp_plan = false; 695 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) 696 { 697 ThreadPlanStepOverBreakpoint *bp_plan = (ThreadPlanStepOverBreakpoint *)cur_plan; 698 if (bp_plan->GetBreakpointLoadAddress() != thread_pc) 699 push_step_over_bp_plan = true; 700 } 701 else 702 push_step_over_bp_plan = true; 703 704 if (push_step_over_bp_plan) 705 { 706 ThreadPlanSP step_bp_plan_sp (new ThreadPlanStepOverBreakpoint (*this)); 707 if (step_bp_plan_sp) 708 { 709 step_bp_plan_sp->SetPrivate (true); 710 711 if (GetCurrentPlan()->RunState() != eStateStepping) 712 { 713 ThreadPlanStepOverBreakpoint *step_bp_plan 714 = static_cast<ThreadPlanStepOverBreakpoint *>(step_bp_plan_sp.get()); 715 step_bp_plan->SetAutoContinue(true); 716 } 717 QueueThreadPlan (step_bp_plan_sp, false); 718 } 719 } 720 } 721 } 722 } 723 } 724 725 bool 726 Thread::ShouldResume (StateType resume_state) 727 { 728 // At this point clear the completed plan stack. 729 m_completed_plan_stack.clear(); 730 m_discarded_plan_stack.clear(); 731 m_override_should_notify = eLazyBoolCalculate; 732 733 StateType prev_resume_state = GetTemporaryResumeState(); 734 735 SetTemporaryResumeState(resume_state); 736 737 lldb::ThreadSP backing_thread_sp (GetBackingThread ()); 738 if (backing_thread_sp) 739 backing_thread_sp->SetTemporaryResumeState(resume_state); 740 741 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended in the previous run. 742 if (prev_resume_state != eStateSuspended) 743 GetPrivateStopInfo(); 744 745 // This is a little dubious, but we are trying to limit how often we actually fetch stop info from 746 // the target, 'cause that slows down single stepping. So assume that if we got to the point where 747 // we're about to resume, and we haven't yet had to fetch the stop reason, then it doesn't need to know 748 // about the fact that we are resuming... 749 const uint32_t process_stop_id = GetProcess()->GetStopID(); 750 if (m_stop_info_stop_id == process_stop_id && 751 (m_stop_info_sp && m_stop_info_sp->IsValid())) 752 { 753 StopInfo *stop_info = GetPrivateStopInfo().get(); 754 if (stop_info) 755 stop_info->WillResume (resume_state); 756 } 757 758 // Tell all the plans that we are about to resume in case they need to clear any state. 759 // We distinguish between the plan on the top of the stack and the lower 760 // plans in case a plan needs to do any special business before it runs. 761 762 bool need_to_resume = false; 763 ThreadPlan *plan_ptr = GetCurrentPlan(); 764 if (plan_ptr) 765 { 766 need_to_resume = plan_ptr->WillResume(resume_state, true); 767 768 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) 769 { 770 plan_ptr->WillResume (resume_state, false); 771 } 772 773 // If the WillResume for the plan says we are faking a resume, then it will have set an appropriate stop info. 774 // In that case, don't reset it here. 775 776 if (need_to_resume && resume_state != eStateSuspended) 777 { 778 m_stop_info_sp.reset(); 779 } 780 } 781 782 if (need_to_resume) 783 { 784 ClearStackFrames(); 785 // Let Thread subclasses do any special work they need to prior to resuming 786 WillResume (resume_state); 787 } 788 789 return need_to_resume; 790 } 791 792 void 793 Thread::DidResume () 794 { 795 SetResumeSignal (LLDB_INVALID_SIGNAL_NUMBER); 796 } 797 798 void 799 Thread::DidStop () 800 { 801 SetState (eStateStopped); 802 } 803 804 bool 805 Thread::ShouldStop (Event* event_ptr) 806 { 807 ThreadPlan *current_plan = GetCurrentPlan(); 808 809 bool should_stop = true; 810 811 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 812 813 if (GetResumeState () == eStateSuspended) 814 { 815 if (log) 816 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)", 817 __FUNCTION__, GetID (), GetProtocolID()); 818 return false; 819 } 820 821 if (GetTemporaryResumeState () == eStateSuspended) 822 { 823 if (log) 824 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", should_stop = 0 (ignore since thread was suspended)", 825 __FUNCTION__, GetID (), GetProtocolID()); 826 return false; 827 } 828 829 // Based on the current thread plan and process stop info, check if this 830 // thread caused the process to stop. NOTE: this must take place before 831 // the plan is moved from the current plan stack to the completed plan 832 // stack. 833 if (!ThreadStoppedForAReason()) 834 { 835 if (log) 836 log->Printf ("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", pc = 0x%16.16" PRIx64 ", should_stop = 0 (ignore since no stop reason)", 837 __FUNCTION__, GetID (), GetProtocolID(), 838 GetRegisterContext() ? GetRegisterContext()->GetPC() : LLDB_INVALID_ADDRESS); 839 return false; 840 } 841 842 if (log) 843 { 844 log->Printf ("Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 ", pc = 0x%16.16" PRIx64, 845 __FUNCTION__, static_cast<void*>(this), GetID (), 846 GetProtocolID (), 847 GetRegisterContext() 848 ? GetRegisterContext()->GetPC() 849 : LLDB_INVALID_ADDRESS); 850 log->Printf ("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^"); 851 StreamString s; 852 s.IndentMore(); 853 DumpThreadPlans(&s); 854 log->Printf ("Plan stack initial state:\n%s", s.GetData()); 855 } 856 857 // The top most plan always gets to do the trace log... 858 current_plan->DoTraceLog (); 859 860 // First query the stop info's ShouldStopSynchronous. This handles "synchronous" stop reasons, for example the breakpoint 861 // command on internal breakpoints. If a synchronous stop reason says we should not stop, then we don't have to 862 // do any more work on this stop. 863 StopInfoSP private_stop_info (GetPrivateStopInfo()); 864 if (private_stop_info && !private_stop_info->ShouldStopSynchronous(event_ptr)) 865 { 866 if (log) 867 log->Printf ("StopInfo::ShouldStop async callback says we should not stop, returning ShouldStop of false."); 868 return false; 869 } 870 871 // If we've already been restarted, don't query the plans since the state they would examine is not current. 872 if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr)) 873 return false; 874 875 // Before the plans see the state of the world, calculate the current inlined depth. 876 GetStackFrameList()->CalculateCurrentInlinedDepth(); 877 878 // If the base plan doesn't understand why we stopped, then we have to find a plan that does. 879 // If that plan is still working, then we don't need to do any more work. If the plan that explains 880 // the stop is done, then we should pop all the plans below it, and pop it, and then let the plans above it decide 881 // whether they still need to do more work. 882 883 bool done_processing_current_plan = false; 884 885 if (!current_plan->PlanExplainsStop(event_ptr)) 886 { 887 if (current_plan->TracerExplainsStop()) 888 { 889 done_processing_current_plan = true; 890 should_stop = false; 891 } 892 else 893 { 894 // If the current plan doesn't explain the stop, then find one that 895 // does and let it handle the situation. 896 ThreadPlan *plan_ptr = current_plan; 897 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) 898 { 899 if (plan_ptr->PlanExplainsStop(event_ptr)) 900 { 901 should_stop = plan_ptr->ShouldStop (event_ptr); 902 903 // plan_ptr explains the stop, next check whether plan_ptr is done, if so, then we should take it 904 // and all the plans below it off the stack. 905 906 if (plan_ptr->MischiefManaged()) 907 { 908 // We're going to pop the plans up to and including the plan that explains the stop. 909 ThreadPlan *prev_plan_ptr = GetPreviousPlan (plan_ptr); 910 911 do 912 { 913 if (should_stop) 914 current_plan->WillStop(); 915 PopPlan(); 916 } 917 while ((current_plan = GetCurrentPlan()) != prev_plan_ptr); 918 // Now, if the responsible plan was not "Okay to discard" then we're done, 919 // otherwise we forward this to the next plan in the stack below. 920 done_processing_current_plan = (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard()); 921 } 922 else 923 done_processing_current_plan = true; 924 925 break; 926 } 927 } 928 } 929 } 930 931 if (!done_processing_current_plan) 932 { 933 bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr); 934 935 if (log) 936 log->Printf("Plan %s explains stop, auto-continue %i.", 937 current_plan->GetName(), over_ride_stop); 938 939 // We're starting from the base plan, so just let it decide; 940 if (PlanIsBasePlan(current_plan)) 941 { 942 should_stop = current_plan->ShouldStop (event_ptr); 943 if (log) 944 log->Printf("Base plan says should stop: %i.", should_stop); 945 } 946 else 947 { 948 // Otherwise, don't let the base plan override what the other plans say to do, since 949 // presumably if there were other plans they would know what to do... 950 while (1) 951 { 952 if (PlanIsBasePlan(current_plan)) 953 break; 954 955 should_stop = current_plan->ShouldStop(event_ptr); 956 if (log) 957 log->Printf("Plan %s should stop: %d.", 958 current_plan->GetName(), should_stop); 959 if (current_plan->MischiefManaged()) 960 { 961 if (should_stop) 962 current_plan->WillStop(); 963 964 // If a Master Plan wants to stop, and wants to stick on the stack, we let it. 965 // Otherwise, see if the plan's parent wants to stop. 966 967 if (should_stop && current_plan->IsMasterPlan() && !current_plan->OkayToDiscard()) 968 { 969 PopPlan(); 970 break; 971 } 972 else 973 { 974 PopPlan(); 975 976 current_plan = GetCurrentPlan(); 977 if (current_plan == nullptr) 978 { 979 break; 980 } 981 } 982 } 983 else 984 { 985 break; 986 } 987 } 988 } 989 990 if (over_ride_stop) 991 should_stop = false; 992 } 993 994 // One other potential problem is that we set up a master plan, then stop in before it is complete - for instance 995 // by hitting a breakpoint during a step-over - then do some step/finish/etc operations that wind up 996 // past the end point condition of the initial plan. We don't want to strand the original plan on the stack, 997 // This code clears stale plans off the stack. 998 999 if (should_stop) 1000 { 1001 ThreadPlan *plan_ptr = GetCurrentPlan(); 1002 while (!PlanIsBasePlan(plan_ptr)) 1003 { 1004 bool stale = plan_ptr->IsPlanStale (); 1005 ThreadPlan *examined_plan = plan_ptr; 1006 plan_ptr = GetPreviousPlan (examined_plan); 1007 1008 if (stale) 1009 { 1010 if (log) 1011 log->Printf("Plan %s being discarded in cleanup, it says it is already done.", 1012 examined_plan->GetName()); 1013 DiscardThreadPlansUpToPlan(examined_plan); 1014 } 1015 } 1016 } 1017 1018 if (log) 1019 { 1020 StreamString s; 1021 s.IndentMore(); 1022 DumpThreadPlans(&s); 1023 log->Printf ("Plan stack final state:\n%s", s.GetData()); 1024 log->Printf ("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv", should_stop); 1025 } 1026 return should_stop; 1027 } 1028 1029 Vote 1030 Thread::ShouldReportStop (Event* event_ptr) 1031 { 1032 StateType thread_state = GetResumeState (); 1033 StateType temp_thread_state = GetTemporaryResumeState(); 1034 1035 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1036 1037 if (thread_state == eStateSuspended || thread_state == eStateInvalid) 1038 { 1039 if (log) 1040 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (state was suspended or invalid)", GetID(), eVoteNoOpinion); 1041 return eVoteNoOpinion; 1042 } 1043 1044 if (temp_thread_state == eStateSuspended || temp_thread_state == eStateInvalid) 1045 { 1046 if (log) 1047 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (temporary state was suspended or invalid)", GetID(), eVoteNoOpinion); 1048 return eVoteNoOpinion; 1049 } 1050 1051 if (!ThreadStoppedForAReason()) 1052 { 1053 if (log) 1054 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i (thread didn't stop for a reason.)", GetID(), eVoteNoOpinion); 1055 return eVoteNoOpinion; 1056 } 1057 1058 if (m_completed_plan_stack.size() > 0) 1059 { 1060 // Don't use GetCompletedPlan here, since that suppresses private plans. 1061 if (log) 1062 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote for complete stack's back plan", GetID()); 1063 return m_completed_plan_stack.back()->ShouldReportStop (event_ptr); 1064 } 1065 else 1066 { 1067 Vote thread_vote = eVoteNoOpinion; 1068 ThreadPlan *plan_ptr = GetCurrentPlan(); 1069 while (1) 1070 { 1071 if (plan_ptr->PlanExplainsStop(event_ptr)) 1072 { 1073 thread_vote = plan_ptr->ShouldReportStop(event_ptr); 1074 break; 1075 } 1076 if (PlanIsBasePlan(plan_ptr)) 1077 break; 1078 else 1079 plan_ptr = GetPreviousPlan(plan_ptr); 1080 } 1081 if (log) 1082 log->Printf ("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 ": returning vote %i for current plan", GetID(), thread_vote); 1083 1084 return thread_vote; 1085 } 1086 } 1087 1088 Vote 1089 Thread::ShouldReportRun (Event* event_ptr) 1090 { 1091 StateType thread_state = GetResumeState (); 1092 1093 if (thread_state == eStateSuspended 1094 || thread_state == eStateInvalid) 1095 { 1096 return eVoteNoOpinion; 1097 } 1098 1099 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1100 if (m_completed_plan_stack.size() > 0) 1101 { 1102 // Don't use GetCompletedPlan here, since that suppresses private plans. 1103 if (log) 1104 log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.", 1105 GetIndexID(), static_cast<void*>(this), GetID(), 1106 StateAsCString(GetTemporaryResumeState()), 1107 m_completed_plan_stack.back()->GetName()); 1108 1109 return m_completed_plan_stack.back()->ShouldReportRun (event_ptr); 1110 } 1111 else 1112 { 1113 if (log) 1114 log->Printf ("Current Plan for thread %d(%p) (0x%4.4" PRIx64 ", %s): %s being asked whether we should report run.", 1115 GetIndexID(), static_cast<void*>(this), GetID(), 1116 StateAsCString(GetTemporaryResumeState()), 1117 GetCurrentPlan()->GetName()); 1118 1119 return GetCurrentPlan()->ShouldReportRun (event_ptr); 1120 } 1121 } 1122 1123 bool 1124 Thread::MatchesSpec (const ThreadSpec *spec) 1125 { 1126 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this); 1127 } 1128 1129 void 1130 Thread::PushPlan (ThreadPlanSP &thread_plan_sp) 1131 { 1132 if (thread_plan_sp) 1133 { 1134 // If the thread plan doesn't already have a tracer, give it its parent's tracer: 1135 if (!thread_plan_sp->GetThreadPlanTracer()) 1136 thread_plan_sp->SetThreadPlanTracer(m_plan_stack.back()->GetThreadPlanTracer()); 1137 m_plan_stack.push_back (thread_plan_sp); 1138 1139 thread_plan_sp->DidPush(); 1140 1141 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1142 if (log) 1143 { 1144 StreamString s; 1145 thread_plan_sp->GetDescription (&s, lldb::eDescriptionLevelFull); 1146 log->Printf("Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".", 1147 static_cast<void*>(this), s.GetData(), 1148 thread_plan_sp->GetThread().GetID()); 1149 } 1150 } 1151 } 1152 1153 void 1154 Thread::PopPlan () 1155 { 1156 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1157 1158 if (m_plan_stack.size() <= 1) 1159 return; 1160 else 1161 { 1162 ThreadPlanSP &plan = m_plan_stack.back(); 1163 if (log) 1164 { 1165 log->Printf("Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID()); 1166 } 1167 m_completed_plan_stack.push_back (plan); 1168 plan->WillPop(); 1169 m_plan_stack.pop_back(); 1170 } 1171 } 1172 1173 void 1174 Thread::DiscardPlan () 1175 { 1176 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1177 if (m_plan_stack.size() > 1) 1178 { 1179 ThreadPlanSP &plan = m_plan_stack.back(); 1180 if (log) 1181 log->Printf("Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".", plan->GetName(), plan->GetThread().GetID()); 1182 1183 m_discarded_plan_stack.push_back (plan); 1184 plan->WillPop(); 1185 m_plan_stack.pop_back(); 1186 } 1187 } 1188 1189 ThreadPlan * 1190 Thread::GetCurrentPlan () 1191 { 1192 // There will always be at least the base plan. If somebody is mucking with a 1193 // thread with an empty plan stack, we should assert right away. 1194 return m_plan_stack.empty() ? nullptr : m_plan_stack.back().get(); 1195 } 1196 1197 ThreadPlanSP 1198 Thread::GetCompletedPlan () 1199 { 1200 ThreadPlanSP empty_plan_sp; 1201 if (!m_completed_plan_stack.empty()) 1202 { 1203 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) 1204 { 1205 ThreadPlanSP completed_plan_sp; 1206 completed_plan_sp = m_completed_plan_stack[i]; 1207 if (!completed_plan_sp->GetPrivate ()) 1208 return completed_plan_sp; 1209 } 1210 } 1211 return empty_plan_sp; 1212 } 1213 1214 ValueObjectSP 1215 Thread::GetReturnValueObject () 1216 { 1217 if (!m_completed_plan_stack.empty()) 1218 { 1219 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) 1220 { 1221 ValueObjectSP return_valobj_sp; 1222 return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject(); 1223 if (return_valobj_sp) 1224 return return_valobj_sp; 1225 } 1226 } 1227 return ValueObjectSP(); 1228 } 1229 1230 ExpressionVariableSP 1231 Thread::GetExpressionVariable () 1232 { 1233 if (!m_completed_plan_stack.empty()) 1234 { 1235 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) 1236 { 1237 ExpressionVariableSP expression_variable_sp; 1238 expression_variable_sp = m_completed_plan_stack[i]->GetExpressionVariable(); 1239 if (expression_variable_sp) 1240 return expression_variable_sp; 1241 } 1242 } 1243 return ExpressionVariableSP(); 1244 } 1245 1246 bool 1247 Thread::IsThreadPlanDone (ThreadPlan *plan) 1248 { 1249 if (!m_completed_plan_stack.empty()) 1250 { 1251 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) 1252 { 1253 if (m_completed_plan_stack[i].get() == plan) 1254 return true; 1255 } 1256 } 1257 return false; 1258 } 1259 1260 bool 1261 Thread::WasThreadPlanDiscarded (ThreadPlan *plan) 1262 { 1263 if (!m_discarded_plan_stack.empty()) 1264 { 1265 for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--) 1266 { 1267 if (m_discarded_plan_stack[i].get() == plan) 1268 return true; 1269 } 1270 } 1271 return false; 1272 } 1273 1274 ThreadPlan * 1275 Thread::GetPreviousPlan (ThreadPlan *current_plan) 1276 { 1277 if (current_plan == nullptr) 1278 return nullptr; 1279 1280 int stack_size = m_completed_plan_stack.size(); 1281 for (int i = stack_size - 1; i > 0; i--) 1282 { 1283 if (current_plan == m_completed_plan_stack[i].get()) 1284 return m_completed_plan_stack[i-1].get(); 1285 } 1286 1287 if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan) 1288 { 1289 return GetCurrentPlan(); 1290 } 1291 1292 stack_size = m_plan_stack.size(); 1293 for (int i = stack_size - 1; i > 0; i--) 1294 { 1295 if (current_plan == m_plan_stack[i].get()) 1296 return m_plan_stack[i-1].get(); 1297 } 1298 return nullptr; 1299 } 1300 1301 void 1302 Thread::QueueThreadPlan (ThreadPlanSP &thread_plan_sp, bool abort_other_plans) 1303 { 1304 if (abort_other_plans) 1305 DiscardThreadPlans(true); 1306 1307 PushPlan (thread_plan_sp); 1308 } 1309 1310 void 1311 Thread::EnableTracer (bool value, bool single_stepping) 1312 { 1313 int stack_size = m_plan_stack.size(); 1314 for (int i = 0; i < stack_size; i++) 1315 { 1316 if (m_plan_stack[i]->GetThreadPlanTracer()) 1317 { 1318 m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value); 1319 m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping); 1320 } 1321 } 1322 } 1323 1324 void 1325 Thread::SetTracer (lldb::ThreadPlanTracerSP &tracer_sp) 1326 { 1327 int stack_size = m_plan_stack.size(); 1328 for (int i = 0; i < stack_size; i++) 1329 m_plan_stack[i]->SetThreadPlanTracer(tracer_sp); 1330 } 1331 1332 bool 1333 Thread::DiscardUserThreadPlansUpToIndex (uint32_t thread_index) 1334 { 1335 // Count the user thread plans from the back end to get the number of the one we want 1336 // to discard: 1337 1338 uint32_t idx = 0; 1339 ThreadPlan *up_to_plan_ptr = nullptr; 1340 1341 for (ThreadPlanSP plan_sp : m_plan_stack) 1342 { 1343 if (plan_sp->GetPrivate()) 1344 continue; 1345 if (idx == thread_index) 1346 { 1347 up_to_plan_ptr = plan_sp.get(); 1348 break; 1349 } 1350 else 1351 idx++; 1352 } 1353 1354 if (up_to_plan_ptr == nullptr) 1355 return false; 1356 1357 DiscardThreadPlansUpToPlan(up_to_plan_ptr); 1358 return true; 1359 } 1360 1361 void 1362 Thread::DiscardThreadPlansUpToPlan (lldb::ThreadPlanSP &up_to_plan_sp) 1363 { 1364 DiscardThreadPlansUpToPlan (up_to_plan_sp.get()); 1365 } 1366 1367 void 1368 Thread::DiscardThreadPlansUpToPlan (ThreadPlan *up_to_plan_ptr) 1369 { 1370 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1371 if (log) 1372 log->Printf("Discarding thread plans for thread tid = 0x%4.4" PRIx64 ", up to %p", 1373 GetID(), static_cast<void*>(up_to_plan_ptr)); 1374 1375 int stack_size = m_plan_stack.size(); 1376 1377 // If the input plan is nullptr, discard all plans. Otherwise make sure this plan is in the 1378 // stack, and if so discard up to and including it. 1379 1380 if (up_to_plan_ptr == nullptr) 1381 { 1382 for (int i = stack_size - 1; i > 0; i--) 1383 DiscardPlan(); 1384 } 1385 else 1386 { 1387 bool found_it = false; 1388 for (int i = stack_size - 1; i > 0; i--) 1389 { 1390 if (m_plan_stack[i].get() == up_to_plan_ptr) 1391 found_it = true; 1392 } 1393 if (found_it) 1394 { 1395 bool last_one = false; 1396 for (int i = stack_size - 1; i > 0 && !last_one ; i--) 1397 { 1398 if (GetCurrentPlan() == up_to_plan_ptr) 1399 last_one = true; 1400 DiscardPlan(); 1401 } 1402 } 1403 } 1404 } 1405 1406 void 1407 Thread::DiscardThreadPlans(bool force) 1408 { 1409 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1410 if (log) 1411 { 1412 log->Printf("Discarding thread plans for thread (tid = 0x%4.4" PRIx64 ", force %d)", GetID(), force); 1413 } 1414 1415 if (force) 1416 { 1417 int stack_size = m_plan_stack.size(); 1418 for (int i = stack_size - 1; i > 0; i--) 1419 { 1420 DiscardPlan(); 1421 } 1422 return; 1423 } 1424 1425 while (1) 1426 { 1427 int master_plan_idx; 1428 bool discard = true; 1429 1430 // Find the first master plan, see if it wants discarding, and if yes discard up to it. 1431 for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0; master_plan_idx--) 1432 { 1433 if (m_plan_stack[master_plan_idx]->IsMasterPlan()) 1434 { 1435 discard = m_plan_stack[master_plan_idx]->OkayToDiscard(); 1436 break; 1437 } 1438 } 1439 1440 if (discard) 1441 { 1442 // First pop all the dependent plans: 1443 for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--) 1444 { 1445 // FIXME: Do we need a finalize here, or is the rule that "PrepareForStop" 1446 // for the plan leaves it in a state that it is safe to pop the plan 1447 // with no more notice? 1448 DiscardPlan(); 1449 } 1450 1451 // Now discard the master plan itself. 1452 // The bottom-most plan never gets discarded. "OkayToDiscard" for it means 1453 // discard it's dependent plans, but not it... 1454 if (master_plan_idx > 0) 1455 { 1456 DiscardPlan(); 1457 } 1458 } 1459 else 1460 { 1461 // If the master plan doesn't want to get discarded, then we're done. 1462 break; 1463 } 1464 } 1465 } 1466 1467 bool 1468 Thread::PlanIsBasePlan (ThreadPlan *plan_ptr) 1469 { 1470 if (plan_ptr->IsBasePlan()) 1471 return true; 1472 else if (m_plan_stack.size() == 0) 1473 return false; 1474 else 1475 return m_plan_stack[0].get() == plan_ptr; 1476 } 1477 1478 Error 1479 Thread::UnwindInnermostExpression() 1480 { 1481 Error error; 1482 int stack_size = m_plan_stack.size(); 1483 1484 // If the input plan is nullptr, discard all plans. Otherwise make sure this plan is in the 1485 // stack, and if so discard up to and including it. 1486 1487 for (int i = stack_size - 1; i > 0; i--) 1488 { 1489 if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction) 1490 { 1491 DiscardThreadPlansUpToPlan(m_plan_stack[i].get()); 1492 return error; 1493 } 1494 } 1495 error.SetErrorString("No expressions currently active on this thread"); 1496 return error; 1497 } 1498 1499 ThreadPlanSP 1500 Thread::QueueFundamentalPlan (bool abort_other_plans) 1501 { 1502 ThreadPlanSP thread_plan_sp (new ThreadPlanBase(*this)); 1503 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1504 return thread_plan_sp; 1505 } 1506 1507 ThreadPlanSP 1508 Thread::QueueThreadPlanForStepSingleInstruction(bool step_over, 1509 bool abort_other_plans, 1510 bool stop_other_threads) 1511 { 1512 ThreadPlanSP thread_plan_sp (new ThreadPlanStepInstruction (*this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion)); 1513 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1514 return thread_plan_sp; 1515 } 1516 1517 ThreadPlanSP 1518 Thread::QueueThreadPlanForStepOverRange(bool abort_other_plans, 1519 const AddressRange &range, 1520 const SymbolContext &addr_context, 1521 lldb::RunMode stop_other_threads, 1522 LazyBool step_out_avoids_code_withoug_debug_info) 1523 { 1524 ThreadPlanSP thread_plan_sp; 1525 thread_plan_sp.reset (new ThreadPlanStepOverRange (*this, range, addr_context, stop_other_threads, step_out_avoids_code_withoug_debug_info)); 1526 1527 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1528 return thread_plan_sp; 1529 } 1530 1531 // Call the QueueThreadPlanForStepOverRange method which takes an address range. 1532 ThreadPlanSP 1533 Thread::QueueThreadPlanForStepOverRange(bool abort_other_plans, 1534 const LineEntry &line_entry, 1535 const SymbolContext &addr_context, 1536 lldb::RunMode stop_other_threads, 1537 LazyBool step_out_avoids_code_withoug_debug_info) 1538 { 1539 return QueueThreadPlanForStepOverRange (abort_other_plans, 1540 line_entry.GetSameLineContiguousAddressRange(), 1541 addr_context, 1542 stop_other_threads, 1543 step_out_avoids_code_withoug_debug_info); 1544 } 1545 1546 ThreadPlanSP 1547 Thread::QueueThreadPlanForStepInRange(bool abort_other_plans, 1548 const AddressRange &range, 1549 const SymbolContext &addr_context, 1550 const char *step_in_target, 1551 lldb::RunMode stop_other_threads, 1552 LazyBool step_in_avoids_code_without_debug_info, 1553 LazyBool step_out_avoids_code_without_debug_info) 1554 { 1555 ThreadPlanSP thread_plan_sp (new ThreadPlanStepInRange (*this, 1556 range, 1557 addr_context, 1558 stop_other_threads, 1559 step_in_avoids_code_without_debug_info, 1560 step_out_avoids_code_without_debug_info)); 1561 ThreadPlanStepInRange *plan = static_cast<ThreadPlanStepInRange *>(thread_plan_sp.get()); 1562 1563 if (step_in_target) 1564 plan->SetStepInTarget(step_in_target); 1565 1566 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1567 return thread_plan_sp; 1568 } 1569 1570 // Call the QueueThreadPlanForStepInRange method which takes an address range. 1571 ThreadPlanSP 1572 Thread::QueueThreadPlanForStepInRange(bool abort_other_plans, 1573 const LineEntry &line_entry, 1574 const SymbolContext &addr_context, 1575 const char *step_in_target, 1576 lldb::RunMode stop_other_threads, 1577 LazyBool step_in_avoids_code_without_debug_info, 1578 LazyBool step_out_avoids_code_without_debug_info) 1579 { 1580 return QueueThreadPlanForStepInRange (abort_other_plans, 1581 line_entry.GetSameLineContiguousAddressRange(), 1582 addr_context, 1583 step_in_target, 1584 stop_other_threads, 1585 step_in_avoids_code_without_debug_info, 1586 step_out_avoids_code_without_debug_info); 1587 } 1588 1589 1590 ThreadPlanSP 1591 Thread::QueueThreadPlanForStepOut(bool abort_other_plans, 1592 SymbolContext *addr_context, 1593 bool first_insn, 1594 bool stop_other_threads, 1595 Vote stop_vote, 1596 Vote run_vote, 1597 uint32_t frame_idx, 1598 LazyBool step_out_avoids_code_without_debug_info) 1599 { 1600 ThreadPlanSP thread_plan_sp (new ThreadPlanStepOut (*this, 1601 addr_context, 1602 first_insn, 1603 stop_other_threads, 1604 stop_vote, 1605 run_vote, 1606 frame_idx, 1607 step_out_avoids_code_without_debug_info)); 1608 1609 if (thread_plan_sp->ValidatePlan(nullptr)) 1610 { 1611 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1612 return thread_plan_sp; 1613 } 1614 else 1615 { 1616 return ThreadPlanSP(); 1617 } 1618 } 1619 1620 ThreadPlanSP 1621 Thread::QueueThreadPlanForStepOutNoShouldStop(bool abort_other_plans, 1622 SymbolContext *addr_context, 1623 bool first_insn, 1624 bool stop_other_threads, 1625 Vote stop_vote, 1626 Vote run_vote, 1627 uint32_t frame_idx, 1628 bool continue_to_next_branch) 1629 { 1630 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut (*this, 1631 addr_context, 1632 first_insn, 1633 stop_other_threads, 1634 stop_vote, 1635 run_vote, 1636 frame_idx, 1637 eLazyBoolNo, 1638 continue_to_next_branch)); 1639 1640 ThreadPlanStepOut *new_plan = static_cast<ThreadPlanStepOut *>(thread_plan_sp.get()); 1641 new_plan->ClearShouldStopHereCallbacks(); 1642 1643 if (thread_plan_sp->ValidatePlan(nullptr)) 1644 { 1645 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1646 return thread_plan_sp; 1647 } 1648 else 1649 { 1650 return ThreadPlanSP(); 1651 } 1652 } 1653 1654 ThreadPlanSP 1655 Thread::QueueThreadPlanForStepThrough (StackID &return_stack_id, bool abort_other_plans, bool stop_other_threads) 1656 { 1657 ThreadPlanSP thread_plan_sp(new ThreadPlanStepThrough (*this, return_stack_id, stop_other_threads)); 1658 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr)) 1659 return ThreadPlanSP(); 1660 1661 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1662 return thread_plan_sp; 1663 } 1664 1665 ThreadPlanSP 1666 Thread::QueueThreadPlanForRunToAddress (bool abort_other_plans, 1667 Address &target_addr, 1668 bool stop_other_threads) 1669 { 1670 ThreadPlanSP thread_plan_sp (new ThreadPlanRunToAddress (*this, target_addr, stop_other_threads)); 1671 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1672 return thread_plan_sp; 1673 } 1674 1675 ThreadPlanSP 1676 Thread::QueueThreadPlanForStepUntil (bool abort_other_plans, 1677 lldb::addr_t *address_list, 1678 size_t num_addresses, 1679 bool stop_other_threads, 1680 uint32_t frame_idx) 1681 { 1682 ThreadPlanSP thread_plan_sp (new ThreadPlanStepUntil (*this, address_list, num_addresses, stop_other_threads, frame_idx)); 1683 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1684 return thread_plan_sp; 1685 1686 } 1687 1688 lldb::ThreadPlanSP 1689 Thread::QueueThreadPlanForStepScripted (bool abort_other_plans, 1690 const char *class_name, 1691 bool stop_other_threads) 1692 { 1693 ThreadPlanSP thread_plan_sp (new ThreadPlanPython (*this, class_name)); 1694 QueueThreadPlan (thread_plan_sp, abort_other_plans); 1695 // This seems a little funny, but I don't want to have to split up the constructor and the 1696 // DidPush in the scripted plan, that seems annoying. 1697 // That means the constructor has to be in DidPush. 1698 // So I have to validate the plan AFTER pushing it, and then take it off again... 1699 if (!thread_plan_sp->ValidatePlan(nullptr)) 1700 { 1701 DiscardThreadPlansUpToPlan(thread_plan_sp); 1702 return ThreadPlanSP(); 1703 } 1704 else 1705 return thread_plan_sp; 1706 } 1707 1708 uint32_t 1709 Thread::GetIndexID () const 1710 { 1711 return m_index_id; 1712 } 1713 1714 static void 1715 PrintPlanElement (Stream *s, const ThreadPlanSP &plan, lldb::DescriptionLevel desc_level, int32_t elem_idx) 1716 { 1717 s->IndentMore(); 1718 s->Indent(); 1719 s->Printf ("Element %d: ", elem_idx); 1720 plan->GetDescription (s, desc_level); 1721 s->EOL(); 1722 s->IndentLess(); 1723 } 1724 1725 static void 1726 PrintPlanStack (Stream *s, const std::vector<lldb::ThreadPlanSP> &plan_stack, lldb::DescriptionLevel desc_level, bool include_internal) 1727 { 1728 int32_t print_idx = 0; 1729 for (ThreadPlanSP plan_sp : plan_stack) 1730 { 1731 if (include_internal || !plan_sp->GetPrivate()) 1732 { 1733 PrintPlanElement (s, plan_sp, desc_level, print_idx++); 1734 } 1735 } 1736 } 1737 1738 void 1739 Thread::DumpThreadPlans (Stream *s, 1740 lldb::DescriptionLevel desc_level, 1741 bool include_internal, 1742 bool ignore_boring_threads) const 1743 { 1744 uint32_t stack_size; 1745 1746 if (ignore_boring_threads) 1747 { 1748 uint32_t stack_size = m_plan_stack.size(); 1749 uint32_t completed_stack_size = m_completed_plan_stack.size(); 1750 uint32_t discarded_stack_size = m_discarded_plan_stack.size(); 1751 if (stack_size == 1 && completed_stack_size == 0 && discarded_stack_size == 0) 1752 { 1753 s->Printf ("thread #%u: tid = 0x%4.4" PRIx64 "\n", GetIndexID(), GetID()); 1754 s->IndentMore(); 1755 s->Indent(); 1756 s->Printf("No active thread plans\n"); 1757 s->IndentLess(); 1758 return; 1759 } 1760 } 1761 1762 s->Indent(); 1763 s->Printf ("thread #%u: tid = 0x%4.4" PRIx64 ":\n", GetIndexID(), GetID()); 1764 s->IndentMore(); 1765 s->Indent(); 1766 s->Printf ("Active plan stack:\n"); 1767 PrintPlanStack (s, m_plan_stack, desc_level, include_internal); 1768 1769 stack_size = m_completed_plan_stack.size(); 1770 if (stack_size > 0) 1771 { 1772 s->Indent(); 1773 s->Printf ("Completed Plan Stack:\n"); 1774 PrintPlanStack (s, m_completed_plan_stack, desc_level, include_internal); 1775 } 1776 1777 stack_size = m_discarded_plan_stack.size(); 1778 if (stack_size > 0) 1779 { 1780 s->Indent(); 1781 s->Printf ("Discarded Plan Stack:\n"); 1782 PrintPlanStack (s, m_discarded_plan_stack, desc_level, include_internal); 1783 } 1784 1785 s->IndentLess(); 1786 } 1787 1788 TargetSP 1789 Thread::CalculateTarget () 1790 { 1791 TargetSP target_sp; 1792 ProcessSP process_sp(GetProcess()); 1793 if (process_sp) 1794 target_sp = process_sp->CalculateTarget(); 1795 return target_sp; 1796 } 1797 1798 ProcessSP 1799 Thread::CalculateProcess () 1800 { 1801 return GetProcess(); 1802 } 1803 1804 ThreadSP 1805 Thread::CalculateThread () 1806 { 1807 return shared_from_this(); 1808 } 1809 1810 StackFrameSP 1811 Thread::CalculateStackFrame () 1812 { 1813 return StackFrameSP(); 1814 } 1815 1816 void 1817 Thread::CalculateExecutionContext (ExecutionContext &exe_ctx) 1818 { 1819 exe_ctx.SetContext (shared_from_this()); 1820 } 1821 1822 StackFrameListSP 1823 Thread::GetStackFrameList () 1824 { 1825 StackFrameListSP frame_list_sp; 1826 Mutex::Locker locker(m_frame_mutex); 1827 if (m_curr_frames_sp) 1828 { 1829 frame_list_sp = m_curr_frames_sp; 1830 } 1831 else 1832 { 1833 frame_list_sp.reset(new StackFrameList (*this, m_prev_frames_sp, true)); 1834 m_curr_frames_sp = frame_list_sp; 1835 } 1836 return frame_list_sp; 1837 } 1838 1839 void 1840 Thread::ClearStackFrames () 1841 { 1842 Mutex::Locker locker(m_frame_mutex); 1843 1844 Unwind *unwinder = GetUnwinder (); 1845 if (unwinder) 1846 unwinder->Clear(); 1847 1848 // Only store away the old "reference" StackFrameList if we got all its frames: 1849 // FIXME: At some point we can try to splice in the frames we have fetched into 1850 // the new frame as we make it, but let's not try that now. 1851 if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched()) 1852 m_prev_frames_sp.swap (m_curr_frames_sp); 1853 m_curr_frames_sp.reset(); 1854 1855 m_extended_info.reset(); 1856 m_extended_info_fetched = false; 1857 } 1858 1859 lldb::StackFrameSP 1860 Thread::GetFrameWithConcreteFrameIndex (uint32_t unwind_idx) 1861 { 1862 return GetStackFrameList()->GetFrameWithConcreteFrameIndex (unwind_idx); 1863 } 1864 1865 Error 1866 Thread::ReturnFromFrameWithIndex (uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast) 1867 { 1868 StackFrameSP frame_sp = GetStackFrameAtIndex (frame_idx); 1869 Error return_error; 1870 1871 if (!frame_sp) 1872 { 1873 return_error.SetErrorStringWithFormat("Could not find frame with index %d in thread 0x%" PRIx64 ".", frame_idx, GetID()); 1874 } 1875 1876 return ReturnFromFrame(frame_sp, return_value_sp, broadcast); 1877 } 1878 1879 Error 1880 Thread::ReturnFromFrame (lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast) 1881 { 1882 Error return_error; 1883 1884 if (!frame_sp) 1885 { 1886 return_error.SetErrorString("Can't return to a null frame."); 1887 return return_error; 1888 } 1889 1890 Thread *thread = frame_sp->GetThread().get(); 1891 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1; 1892 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx); 1893 if (!older_frame_sp) 1894 { 1895 return_error.SetErrorString("No older frame to return to."); 1896 return return_error; 1897 } 1898 1899 if (return_value_sp) 1900 { 1901 lldb::ABISP abi = thread->GetProcess()->GetABI(); 1902 if (!abi) 1903 { 1904 return_error.SetErrorString("Could not find ABI to set return value."); 1905 return return_error; 1906 } 1907 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction); 1908 1909 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not for scalars. 1910 // Turn that back on when that works. 1911 if (/* DISABLES CODE */ (0) && sc.function != nullptr) 1912 { 1913 Type *function_type = sc.function->GetType(); 1914 if (function_type) 1915 { 1916 CompilerType return_type = sc.function->GetCompilerType().GetFunctionReturnType(); 1917 if (return_type) 1918 { 1919 StreamString s; 1920 return_type.DumpTypeDescription(&s); 1921 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type); 1922 if (cast_value_sp) 1923 { 1924 cast_value_sp->SetFormat(eFormatHex); 1925 return_value_sp = cast_value_sp; 1926 } 1927 } 1928 } 1929 } 1930 1931 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp); 1932 if (!return_error.Success()) 1933 return return_error; 1934 } 1935 1936 // Now write the return registers for the chosen frame: 1937 // Note, we can't use ReadAllRegisterValues->WriteAllRegisterValues, since the read & write 1938 // cook their data 1939 1940 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0); 1941 if (youngest_frame_sp) 1942 { 1943 lldb::RegisterContextSP reg_ctx_sp (youngest_frame_sp->GetRegisterContext()); 1944 if (reg_ctx_sp) 1945 { 1946 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(older_frame_sp->GetRegisterContext()); 1947 if (copy_success) 1948 { 1949 thread->DiscardThreadPlans(true); 1950 thread->ClearStackFrames(); 1951 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged)) 1952 BroadcastEvent(eBroadcastBitStackChanged, new ThreadEventData (this->shared_from_this())); 1953 } 1954 else 1955 { 1956 return_error.SetErrorString("Could not reset register values."); 1957 } 1958 } 1959 else 1960 { 1961 return_error.SetErrorString("Frame has no register context."); 1962 } 1963 } 1964 else 1965 { 1966 return_error.SetErrorString("Returned past top frame."); 1967 } 1968 return return_error; 1969 } 1970 1971 static void DumpAddressList (Stream &s, const std::vector<Address> &list, ExecutionContextScope *exe_scope) 1972 { 1973 for (size_t n=0;n<list.size();n++) 1974 { 1975 s << "\t"; 1976 list[n].Dump (&s, exe_scope, Address::DumpStyleResolvedDescription, Address::DumpStyleSectionNameOffset); 1977 s << "\n"; 1978 } 1979 } 1980 1981 Error 1982 Thread::JumpToLine (const FileSpec &file, uint32_t line, bool can_leave_function, std::string *warnings) 1983 { 1984 ExecutionContext exe_ctx (GetStackFrameAtIndex(0)); 1985 Target *target = exe_ctx.GetTargetPtr(); 1986 TargetSP target_sp = exe_ctx.GetTargetSP(); 1987 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext(); 1988 StackFrame *frame = exe_ctx.GetFramePtr(); 1989 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction); 1990 1991 // Find candidate locations. 1992 std::vector<Address> candidates, within_function, outside_function; 1993 target->GetImages().FindAddressesForLine (target_sp, file, line, sc.function, within_function, outside_function); 1994 1995 // If possible, we try and stay within the current function. 1996 // Within a function, we accept multiple locations (optimized code may do this, 1997 // there's no solution here so we do the best we can). 1998 // However if we're trying to leave the function, we don't know how to pick the 1999 // right location, so if there's more than one then we bail. 2000 if (!within_function.empty()) 2001 candidates = within_function; 2002 else if (outside_function.size() == 1 && can_leave_function) 2003 candidates = outside_function; 2004 2005 // Check if we got anything. 2006 if (candidates.empty()) 2007 { 2008 if (outside_function.empty()) 2009 { 2010 return Error("Cannot locate an address for %s:%i.", 2011 file.GetFilename().AsCString(), line); 2012 } 2013 else if (outside_function.size() == 1) 2014 { 2015 return Error("%s:%i is outside the current function.", 2016 file.GetFilename().AsCString(), line); 2017 } 2018 else 2019 { 2020 StreamString sstr; 2021 DumpAddressList(sstr, outside_function, target); 2022 return Error("%s:%i has multiple candidate locations:\n%s", 2023 file.GetFilename().AsCString(), line, sstr.GetString().c_str()); 2024 } 2025 } 2026 2027 // Accept the first location, warn about any others. 2028 Address dest = candidates[0]; 2029 if (warnings && candidates.size() > 1) 2030 { 2031 StreamString sstr; 2032 sstr.Printf("%s:%i appears multiple times in this function, selecting the first location:\n", 2033 file.GetFilename().AsCString(), line); 2034 DumpAddressList(sstr, candidates, target); 2035 *warnings = sstr.GetString(); 2036 } 2037 2038 if (!reg_ctx->SetPC (dest)) 2039 return Error("Cannot change PC to target address."); 2040 2041 return Error(); 2042 } 2043 2044 void 2045 Thread::DumpUsingSettingsFormat (Stream &strm, uint32_t frame_idx) 2046 { 2047 ExecutionContext exe_ctx (shared_from_this()); 2048 Process *process = exe_ctx.GetProcessPtr(); 2049 if (process == nullptr) 2050 return; 2051 2052 StackFrameSP frame_sp; 2053 SymbolContext frame_sc; 2054 if (frame_idx != LLDB_INVALID_FRAME_ID) 2055 { 2056 frame_sp = GetStackFrameAtIndex (frame_idx); 2057 if (frame_sp) 2058 { 2059 exe_ctx.SetFrameSP(frame_sp); 2060 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything); 2061 } 2062 } 2063 2064 const FormatEntity::Entry *thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat(); 2065 assert (thread_format); 2066 2067 FormatEntity::Format(*thread_format, 2068 strm, 2069 frame_sp ? &frame_sc : nullptr, 2070 &exe_ctx, 2071 nullptr, 2072 nullptr, 2073 false, 2074 false); 2075 } 2076 2077 void 2078 Thread::SettingsInitialize () 2079 { 2080 } 2081 2082 void 2083 Thread::SettingsTerminate () 2084 { 2085 } 2086 2087 lldb::addr_t 2088 Thread::GetThreadPointer () 2089 { 2090 return LLDB_INVALID_ADDRESS; 2091 } 2092 2093 addr_t 2094 Thread::GetThreadLocalData (const ModuleSP module) 2095 { 2096 // The default implementation is to ask the dynamic loader for it. 2097 // This can be overridden for specific platforms. 2098 DynamicLoader *loader = GetProcess()->GetDynamicLoader(); 2099 if (loader) 2100 return loader->GetThreadLocalData (module, shared_from_this()); 2101 else 2102 return LLDB_INVALID_ADDRESS; 2103 } 2104 2105 bool 2106 Thread::SafeToCallFunctions () 2107 { 2108 Process *process = GetProcess().get(); 2109 if (process) 2110 { 2111 SystemRuntime *runtime = process->GetSystemRuntime (); 2112 if (runtime) 2113 { 2114 return runtime->SafeToCallFunctionsOnThisThread (shared_from_this()); 2115 } 2116 } 2117 return true; 2118 } 2119 2120 lldb::StackFrameSP 2121 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr) 2122 { 2123 return GetStackFrameList()->GetStackFrameSPForStackFramePtr (stack_frame_ptr); 2124 } 2125 2126 const char * 2127 Thread::StopReasonAsCString (lldb::StopReason reason) 2128 { 2129 switch (reason) 2130 { 2131 case eStopReasonInvalid: return "invalid"; 2132 case eStopReasonNone: return "none"; 2133 case eStopReasonTrace: return "trace"; 2134 case eStopReasonBreakpoint: return "breakpoint"; 2135 case eStopReasonWatchpoint: return "watchpoint"; 2136 case eStopReasonSignal: return "signal"; 2137 case eStopReasonException: return "exception"; 2138 case eStopReasonExec: return "exec"; 2139 case eStopReasonPlanComplete: return "plan complete"; 2140 case eStopReasonThreadExiting: return "thread exiting"; 2141 case eStopReasonInstrumentation: return "instrumentation break"; 2142 } 2143 2144 static char unknown_state_string[64]; 2145 snprintf(unknown_state_string, sizeof (unknown_state_string), "StopReason = %i", reason); 2146 return unknown_state_string; 2147 } 2148 2149 const char * 2150 Thread::RunModeAsCString (lldb::RunMode mode) 2151 { 2152 switch (mode) 2153 { 2154 case eOnlyThisThread: return "only this thread"; 2155 case eAllThreads: return "all threads"; 2156 case eOnlyDuringStepping: return "only during stepping"; 2157 } 2158 2159 static char unknown_state_string[64]; 2160 snprintf(unknown_state_string, sizeof (unknown_state_string), "RunMode = %i", mode); 2161 return unknown_state_string; 2162 } 2163 2164 size_t 2165 Thread::GetStatus (Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source) 2166 { 2167 ExecutionContext exe_ctx (shared_from_this()); 2168 Target *target = exe_ctx.GetTargetPtr(); 2169 Process *process = exe_ctx.GetProcessPtr(); 2170 size_t num_frames_shown = 0; 2171 strm.Indent(); 2172 bool is_selected = false; 2173 if (process) 2174 { 2175 if (process->GetThreadList().GetSelectedThread().get() == this) 2176 is_selected = true; 2177 } 2178 strm.Printf("%c ", is_selected ? '*' : ' '); 2179 if (target && target->GetDebugger().GetUseExternalEditor()) 2180 { 2181 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame); 2182 if (frame_sp) 2183 { 2184 SymbolContext frame_sc(frame_sp->GetSymbolContext (eSymbolContextLineEntry)); 2185 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file) 2186 { 2187 Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line); 2188 } 2189 } 2190 } 2191 2192 DumpUsingSettingsFormat (strm, start_frame); 2193 2194 if (num_frames > 0) 2195 { 2196 strm.IndentMore(); 2197 2198 const bool show_frame_info = true; 2199 2200 const char *selected_frame_marker = nullptr; 2201 if (num_frames == 1 || (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID())) 2202 strm.IndentMore (); 2203 else 2204 selected_frame_marker = "* "; 2205 2206 num_frames_shown = GetStackFrameList ()->GetStatus (strm, 2207 start_frame, 2208 num_frames, 2209 show_frame_info, 2210 num_frames_with_source, 2211 selected_frame_marker); 2212 if (num_frames == 1) 2213 strm.IndentLess(); 2214 strm.IndentLess(); 2215 } 2216 return num_frames_shown; 2217 } 2218 2219 bool 2220 Thread::GetDescription (Stream &strm, lldb::DescriptionLevel level, bool print_json_thread, bool print_json_stopinfo) 2221 { 2222 DumpUsingSettingsFormat (strm, 0); 2223 strm.Printf("\n"); 2224 2225 StructuredData::ObjectSP thread_info = GetExtendedInfo(); 2226 2227 if (print_json_thread || print_json_stopinfo) 2228 { 2229 if (thread_info && print_json_thread) 2230 { 2231 thread_info->Dump (strm); 2232 strm.Printf("\n"); 2233 } 2234 2235 if (print_json_stopinfo && m_stop_info_sp) 2236 { 2237 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo(); 2238 if (stop_info) 2239 { 2240 stop_info->Dump (strm); 2241 strm.Printf("\n"); 2242 } 2243 } 2244 2245 return true; 2246 } 2247 2248 if (thread_info) 2249 { 2250 StructuredData::ObjectSP activity = thread_info->GetObjectForDotSeparatedPath("activity"); 2251 StructuredData::ObjectSP breadcrumb = thread_info->GetObjectForDotSeparatedPath("breadcrumb"); 2252 StructuredData::ObjectSP messages = thread_info->GetObjectForDotSeparatedPath("trace_messages"); 2253 2254 bool printed_activity = false; 2255 if (activity && activity->GetType() == StructuredData::Type::eTypeDictionary) 2256 { 2257 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary(); 2258 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id"); 2259 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name"); 2260 if (name && name->GetType() == StructuredData::Type::eTypeString 2261 && id && id->GetType() == StructuredData::Type::eTypeInteger) 2262 { 2263 strm.Printf(" Activity '%s', 0x%" PRIx64 "\n", name->GetAsString()->GetValue().c_str(), id->GetAsInteger()->GetValue()); 2264 } 2265 printed_activity = true; 2266 } 2267 bool printed_breadcrumb = false; 2268 if (breadcrumb && breadcrumb->GetType() == StructuredData::Type::eTypeDictionary) 2269 { 2270 if (printed_activity) 2271 strm.Printf ("\n"); 2272 StructuredData::Dictionary *breadcrumb_dict = breadcrumb->GetAsDictionary(); 2273 StructuredData::ObjectSP breadcrumb_text = breadcrumb_dict->GetValueForKey ("name"); 2274 if (breadcrumb_text && breadcrumb_text->GetType() == StructuredData::Type::eTypeString) 2275 { 2276 strm.Printf (" Current Breadcrumb: %s\n", breadcrumb_text->GetAsString()->GetValue().c_str()); 2277 } 2278 printed_breadcrumb = true; 2279 } 2280 if (messages && messages->GetType() == StructuredData::Type::eTypeArray) 2281 { 2282 if (printed_breadcrumb) 2283 strm.Printf("\n"); 2284 StructuredData::Array *messages_array = messages->GetAsArray(); 2285 const size_t msg_count = messages_array->GetSize(); 2286 if (msg_count > 0) 2287 { 2288 strm.Printf (" %zu trace messages:\n", msg_count); 2289 for (size_t i = 0; i < msg_count; i++) 2290 { 2291 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i); 2292 if (message && message->GetType() == StructuredData::Type::eTypeDictionary) 2293 { 2294 StructuredData::Dictionary *message_dict = message->GetAsDictionary(); 2295 StructuredData::ObjectSP message_text = message_dict->GetValueForKey ("message"); 2296 if (message_text && message_text->GetType() == StructuredData::Type::eTypeString) 2297 { 2298 strm.Printf (" %s\n", message_text->GetAsString()->GetValue().c_str()); 2299 } 2300 } 2301 } 2302 } 2303 } 2304 } 2305 2306 return true; 2307 } 2308 2309 size_t 2310 Thread::GetStackFrameStatus (Stream& strm, 2311 uint32_t first_frame, 2312 uint32_t num_frames, 2313 bool show_frame_info, 2314 uint32_t num_frames_with_source) 2315 { 2316 return GetStackFrameList()->GetStatus (strm, 2317 first_frame, 2318 num_frames, 2319 show_frame_info, 2320 num_frames_with_source); 2321 } 2322 2323 Unwind * 2324 Thread::GetUnwinder () 2325 { 2326 if (!m_unwinder_ap) 2327 { 2328 const ArchSpec target_arch (CalculateTarget()->GetArchitecture ()); 2329 const llvm::Triple::ArchType machine = target_arch.GetMachine(); 2330 switch (machine) 2331 { 2332 case llvm::Triple::x86_64: 2333 case llvm::Triple::x86: 2334 case llvm::Triple::arm: 2335 case llvm::Triple::aarch64: 2336 case llvm::Triple::thumb: 2337 case llvm::Triple::mips: 2338 case llvm::Triple::mipsel: 2339 case llvm::Triple::mips64: 2340 case llvm::Triple::mips64el: 2341 case llvm::Triple::ppc: 2342 case llvm::Triple::ppc64: 2343 case llvm::Triple::systemz: 2344 case llvm::Triple::hexagon: 2345 m_unwinder_ap.reset (new UnwindLLDB (*this)); 2346 break; 2347 2348 default: 2349 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple) 2350 m_unwinder_ap.reset (new UnwindMacOSXFrameBackchain (*this)); 2351 break; 2352 } 2353 } 2354 return m_unwinder_ap.get(); 2355 } 2356 2357 void 2358 Thread::Flush () 2359 { 2360 ClearStackFrames (); 2361 m_reg_context_sp.reset(); 2362 } 2363 2364 bool 2365 Thread::IsStillAtLastBreakpointHit () 2366 { 2367 // If we are currently stopped at a breakpoint, always return that stopinfo and don't reset it. 2368 // This allows threads to maintain their breakpoint stopinfo, such as when thread-stepping in 2369 // multithreaded programs. 2370 if (m_stop_info_sp) { 2371 StopReason stop_reason = m_stop_info_sp->GetStopReason(); 2372 if (stop_reason == lldb::eStopReasonBreakpoint) { 2373 uint64_t value = m_stop_info_sp->GetValue(); 2374 lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext()); 2375 if (reg_ctx_sp) 2376 { 2377 lldb::addr_t pc = reg_ctx_sp->GetPC(); 2378 BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 2379 if (bp_site_sp && 2380 static_cast<break_id_t>(value) == bp_site_sp->GetID()) 2381 return true; 2382 } 2383 } 2384 } 2385 return false; 2386 } 2387 2388 Error 2389 Thread::StepIn (bool source_step, 2390 LazyBool step_in_avoids_code_without_debug_info, 2391 LazyBool step_out_avoids_code_without_debug_info) 2392 2393 { 2394 Error error; 2395 Process *process = GetProcess().get(); 2396 if (StateIsStoppedState (process->GetState(), true)) 2397 { 2398 StackFrameSP frame_sp = GetStackFrameAtIndex (0); 2399 ThreadPlanSP new_plan_sp; 2400 const lldb::RunMode run_mode = eOnlyThisThread; 2401 const bool abort_other_plans = false; 2402 2403 if (source_step && frame_sp && frame_sp->HasDebugInformation ()) 2404 { 2405 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); 2406 new_plan_sp = QueueThreadPlanForStepInRange(abort_other_plans, 2407 sc.line_entry, 2408 sc, 2409 nullptr, 2410 run_mode, 2411 step_in_avoids_code_without_debug_info, 2412 step_out_avoids_code_without_debug_info); 2413 } 2414 else 2415 { 2416 new_plan_sp = QueueThreadPlanForStepSingleInstruction (false, 2417 abort_other_plans, 2418 run_mode); 2419 } 2420 2421 new_plan_sp->SetIsMasterPlan(true); 2422 new_plan_sp->SetOkayToDiscard(false); 2423 2424 // Why do we need to set the current thread by ID here??? 2425 process->GetThreadList().SetSelectedThreadByID (GetID()); 2426 error = process->Resume(); 2427 } 2428 else 2429 { 2430 error.SetErrorString("process not stopped"); 2431 } 2432 return error; 2433 } 2434 2435 Error 2436 Thread::StepOver (bool source_step, 2437 LazyBool step_out_avoids_code_without_debug_info) 2438 { 2439 Error error; 2440 Process *process = GetProcess().get(); 2441 if (StateIsStoppedState (process->GetState(), true)) 2442 { 2443 StackFrameSP frame_sp = GetStackFrameAtIndex (0); 2444 ThreadPlanSP new_plan_sp; 2445 2446 const lldb::RunMode run_mode = eOnlyThisThread; 2447 const bool abort_other_plans = false; 2448 2449 if (source_step && frame_sp && frame_sp->HasDebugInformation ()) 2450 { 2451 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); 2452 new_plan_sp = QueueThreadPlanForStepOverRange (abort_other_plans, 2453 sc.line_entry, 2454 sc, 2455 run_mode, 2456 step_out_avoids_code_without_debug_info); 2457 } 2458 else 2459 { 2460 new_plan_sp = QueueThreadPlanForStepSingleInstruction (true, 2461 abort_other_plans, 2462 run_mode); 2463 } 2464 2465 new_plan_sp->SetIsMasterPlan(true); 2466 new_plan_sp->SetOkayToDiscard(false); 2467 2468 // Why do we need to set the current thread by ID here??? 2469 process->GetThreadList().SetSelectedThreadByID (GetID()); 2470 error = process->Resume(); 2471 } 2472 else 2473 { 2474 error.SetErrorString("process not stopped"); 2475 } 2476 return error; 2477 } 2478 2479 Error 2480 Thread::StepOut () 2481 { 2482 Error error; 2483 Process *process = GetProcess().get(); 2484 if (StateIsStoppedState (process->GetState(), true)) 2485 { 2486 const bool first_instruction = false; 2487 const bool stop_other_threads = false; 2488 const bool abort_other_plans = false; 2489 2490 ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(abort_other_plans, 2491 nullptr, 2492 first_instruction, 2493 stop_other_threads, 2494 eVoteYes, 2495 eVoteNoOpinion, 2496 0)); 2497 2498 new_plan_sp->SetIsMasterPlan(true); 2499 new_plan_sp->SetOkayToDiscard(false); 2500 2501 // Why do we need to set the current thread by ID here??? 2502 process->GetThreadList().SetSelectedThreadByID (GetID()); 2503 error = process->Resume(); 2504 } 2505 else 2506 { 2507 error.SetErrorString("process not stopped"); 2508 } 2509 return error; 2510 } 2511