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