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