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