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