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