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