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