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