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