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 void 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 } 543 544 StateType Thread::GetState() const { 545 // If any other threads access this we will need a mutex for it 546 std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 547 return m_state; 548 } 549 550 void Thread::SetState(StateType state) { 551 std::lock_guard<std::recursive_mutex> guard(m_state_mutex); 552 m_state = state; 553 } 554 555 std::string Thread::GetStopDescription() { 556 StackFrameSP frame_sp = GetStackFrameAtIndex(0); 557 558 if (!frame_sp) 559 return GetStopDescriptionRaw(); 560 561 auto recognized_frame_sp = frame_sp->GetRecognizedFrame(); 562 563 if (!recognized_frame_sp) 564 return GetStopDescriptionRaw(); 565 566 std::string recognized_stop_description = 567 recognized_frame_sp->GetStopDescription(); 568 569 if (!recognized_stop_description.empty()) 570 return recognized_stop_description; 571 572 return GetStopDescriptionRaw(); 573 } 574 575 std::string Thread::GetStopDescriptionRaw() { 576 StopInfoSP stop_info_sp = GetStopInfo(); 577 std::string raw_stop_description; 578 if (stop_info_sp && stop_info_sp->IsValid()) { 579 raw_stop_description = stop_info_sp->GetDescription(); 580 assert((!raw_stop_description.empty() || 581 stop_info_sp->GetStopReason() == eStopReasonNone) && 582 "StopInfo returned an empty description."); 583 } 584 return raw_stop_description; 585 } 586 587 void Thread::SelectMostRelevantFrame() { 588 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD); 589 590 auto frames_list_sp = GetStackFrameList(); 591 592 // Only the top frame should be recognized. 593 auto frame_sp = frames_list_sp->GetFrameAtIndex(0); 594 595 auto recognized_frame_sp = frame_sp->GetRecognizedFrame(); 596 597 if (!recognized_frame_sp) { 598 LLDB_LOG(log, "Frame #0 not recognized"); 599 return; 600 } 601 602 if (StackFrameSP most_relevant_frame_sp = 603 recognized_frame_sp->GetMostRelevantFrame()) { 604 LLDB_LOG(log, "Found most relevant frame at index {0}", 605 most_relevant_frame_sp->GetFrameIndex()); 606 SetSelectedFrame(most_relevant_frame_sp.get()); 607 } else { 608 LLDB_LOG(log, "No relevant frame!"); 609 } 610 } 611 612 void Thread::WillStop() { 613 ThreadPlan *current_plan = GetCurrentPlan(); 614 615 SelectMostRelevantFrame(); 616 617 // FIXME: I may decide to disallow threads with no plans. In which 618 // case this should go to an assert. 619 620 if (!current_plan) 621 return; 622 623 current_plan->WillStop(); 624 } 625 626 void Thread::SetupForResume() { 627 if (GetResumeState() != eStateSuspended) { 628 // If we're at a breakpoint push the step-over breakpoint plan. Do this 629 // before telling the current plan it will resume, since we might change 630 // what the current plan is. 631 632 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext()); 633 if (reg_ctx_sp) { 634 const addr_t thread_pc = reg_ctx_sp->GetPC(); 635 BreakpointSiteSP bp_site_sp = 636 GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc); 637 if (bp_site_sp) { 638 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the 639 // target may not require anything special to step over a breakpoint. 640 641 ThreadPlan *cur_plan = GetCurrentPlan(); 642 643 bool push_step_over_bp_plan = false; 644 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) { 645 ThreadPlanStepOverBreakpoint *bp_plan = 646 (ThreadPlanStepOverBreakpoint *)cur_plan; 647 if (bp_plan->GetBreakpointLoadAddress() != thread_pc) 648 push_step_over_bp_plan = true; 649 } else 650 push_step_over_bp_plan = true; 651 652 if (push_step_over_bp_plan) { 653 ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this)); 654 if (step_bp_plan_sp) { 655 step_bp_plan_sp->SetPrivate(true); 656 657 if (GetCurrentPlan()->RunState() != eStateStepping) { 658 ThreadPlanStepOverBreakpoint *step_bp_plan = 659 static_cast<ThreadPlanStepOverBreakpoint *>( 660 step_bp_plan_sp.get()); 661 step_bp_plan->SetAutoContinue(true); 662 } 663 QueueThreadPlan(step_bp_plan_sp, false); 664 } 665 } 666 } 667 } 668 } 669 } 670 671 bool Thread::ShouldResume(StateType resume_state) { 672 // At this point clear the completed plan stack. 673 GetPlans().WillResume(); 674 m_override_should_notify = eLazyBoolCalculate; 675 676 StateType prev_resume_state = GetTemporaryResumeState(); 677 678 SetTemporaryResumeState(resume_state); 679 680 lldb::ThreadSP backing_thread_sp(GetBackingThread()); 681 if (backing_thread_sp) 682 backing_thread_sp->SetTemporaryResumeState(resume_state); 683 684 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended 685 // in the previous run. 686 if (prev_resume_state != eStateSuspended) 687 GetPrivateStopInfo(); 688 689 // This is a little dubious, but we are trying to limit how often we actually 690 // fetch stop info from the target, 'cause that slows down single stepping. 691 // So assume that if we got to the point where we're about to resume, and we 692 // haven't yet had to fetch the stop reason, then it doesn't need to know 693 // about the fact that we are resuming... 694 const uint32_t process_stop_id = GetProcess()->GetStopID(); 695 if (m_stop_info_stop_id == process_stop_id && 696 (m_stop_info_sp && m_stop_info_sp->IsValid())) { 697 StopInfo *stop_info = GetPrivateStopInfo().get(); 698 if (stop_info) 699 stop_info->WillResume(resume_state); 700 } 701 702 // Tell all the plans that we are about to resume in case they need to clear 703 // any state. We distinguish between the plan on the top of the stack and the 704 // lower plans in case a plan needs to do any special business before it 705 // runs. 706 707 bool need_to_resume = false; 708 ThreadPlan *plan_ptr = GetCurrentPlan(); 709 if (plan_ptr) { 710 need_to_resume = plan_ptr->WillResume(resume_state, true); 711 712 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) { 713 plan_ptr->WillResume(resume_state, false); 714 } 715 716 // If the WillResume for the plan says we are faking a resume, then it will 717 // have set an appropriate stop info. In that case, don't reset it here. 718 719 if (need_to_resume && resume_state != eStateSuspended) { 720 m_stop_info_sp.reset(); 721 } 722 } 723 724 if (need_to_resume) { 725 ClearStackFrames(); 726 // Let Thread subclasses do any special work they need to prior to resuming 727 WillResume(resume_state); 728 } 729 730 return need_to_resume; 731 } 732 733 void Thread::DidResume() { SetResumeSignal(LLDB_INVALID_SIGNAL_NUMBER); } 734 735 void Thread::DidStop() { SetState(eStateStopped); } 736 737 bool Thread::ShouldStop(Event *event_ptr) { 738 ThreadPlan *current_plan = GetCurrentPlan(); 739 740 bool should_stop = true; 741 742 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 743 744 if (GetResumeState() == 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 if (GetTemporaryResumeState() == eStateSuspended) { 753 LLDB_LOGF(log, 754 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 755 ", should_stop = 0 (ignore since thread was suspended)", 756 __FUNCTION__, GetID(), GetProtocolID()); 757 return false; 758 } 759 760 // Based on the current thread plan and process stop info, check if this 761 // thread caused the process to stop. NOTE: this must take place before the 762 // plan is moved from the current plan stack to the completed plan stack. 763 if (!ThreadStoppedForAReason()) { 764 LLDB_LOGF(log, 765 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 766 ", pc = 0x%16.16" PRIx64 767 ", should_stop = 0 (ignore since no stop reason)", 768 __FUNCTION__, GetID(), GetProtocolID(), 769 GetRegisterContext() ? GetRegisterContext()->GetPC() 770 : LLDB_INVALID_ADDRESS); 771 return false; 772 } 773 774 if (log) { 775 LLDB_LOGF(log, 776 "Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64 777 ", pc = 0x%16.16" PRIx64, 778 __FUNCTION__, static_cast<void *>(this), GetID(), GetProtocolID(), 779 GetRegisterContext() ? GetRegisterContext()->GetPC() 780 : LLDB_INVALID_ADDRESS); 781 LLDB_LOGF(log, "^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^"); 782 StreamString s; 783 s.IndentMore(); 784 GetProcess()->DumpThreadPlansForTID( 785 s, GetID(), eDescriptionLevelVerbose, true /* internal */, 786 false /* condense_trivial */, true /* skip_unreported */); 787 LLDB_LOGF(log, "Plan stack initial state:\n%s", s.GetData()); 788 } 789 790 // The top most plan always gets to do the trace log... 791 current_plan->DoTraceLog(); 792 793 // First query the stop info's ShouldStopSynchronous. This handles 794 // "synchronous" stop reasons, for example the breakpoint command on internal 795 // breakpoints. If a synchronous stop reason says we should not stop, then 796 // we don't have to do any more work on this stop. 797 StopInfoSP private_stop_info(GetPrivateStopInfo()); 798 if (private_stop_info && 799 !private_stop_info->ShouldStopSynchronous(event_ptr)) { 800 LLDB_LOGF(log, "StopInfo::ShouldStop async callback says we should not " 801 "stop, returning ShouldStop of false."); 802 return false; 803 } 804 805 // If we've already been restarted, don't query the plans since the state 806 // they would examine is not current. 807 if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr)) 808 return false; 809 810 // Before the plans see the state of the world, calculate the current inlined 811 // depth. 812 GetStackFrameList()->CalculateCurrentInlinedDepth(); 813 814 // If the base plan doesn't understand why we stopped, then we have to find a 815 // plan that does. If that plan is still working, then we don't need to do 816 // any more work. If the plan that explains the stop is done, then we should 817 // pop all the plans below it, and pop it, and then let the plans above it 818 // decide whether they still need to do more work. 819 820 bool done_processing_current_plan = false; 821 822 if (!current_plan->PlanExplainsStop(event_ptr)) { 823 if (current_plan->TracerExplainsStop()) { 824 done_processing_current_plan = true; 825 should_stop = false; 826 } else { 827 // If the current plan doesn't explain the stop, then find one that does 828 // and let it handle the situation. 829 ThreadPlan *plan_ptr = current_plan; 830 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) { 831 if (plan_ptr->PlanExplainsStop(event_ptr)) { 832 LLDB_LOGF(log, "Plan %s explains stop.", plan_ptr->GetName()); 833 834 should_stop = plan_ptr->ShouldStop(event_ptr); 835 836 // plan_ptr explains the stop, next check whether plan_ptr is done, 837 // if so, then we should take it and all the plans below it off the 838 // stack. 839 840 if (plan_ptr->MischiefManaged()) { 841 // We're going to pop the plans up to and including the plan that 842 // explains the stop. 843 ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr); 844 845 do { 846 if (should_stop) 847 current_plan->WillStop(); 848 PopPlan(); 849 } while ((current_plan = GetCurrentPlan()) != prev_plan_ptr); 850 // Now, if the responsible plan was not "Okay to discard" then 851 // we're done, otherwise we forward this to the next plan in the 852 // stack below. 853 done_processing_current_plan = 854 (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard()); 855 } else 856 done_processing_current_plan = true; 857 858 break; 859 } 860 } 861 } 862 } 863 864 if (!done_processing_current_plan) { 865 bool override_stop = false; 866 867 // We're starting from the base plan, so just let it decide; 868 if (current_plan->IsBasePlan()) { 869 should_stop = current_plan->ShouldStop(event_ptr); 870 LLDB_LOGF(log, "Base plan says should stop: %i.", should_stop); 871 } else { 872 // Otherwise, don't let the base plan override what the other plans say 873 // to do, since presumably if there were other plans they would know what 874 // to do... 875 while (true) { 876 if (current_plan->IsBasePlan()) 877 break; 878 879 should_stop = current_plan->ShouldStop(event_ptr); 880 LLDB_LOGF(log, "Plan %s should stop: %d.", current_plan->GetName(), 881 should_stop); 882 if (current_plan->MischiefManaged()) { 883 if (should_stop) 884 current_plan->WillStop(); 885 886 if (current_plan->ShouldAutoContinue(event_ptr)) { 887 override_stop = true; 888 LLDB_LOGF(log, "Plan %s auto-continue: true.", 889 current_plan->GetName()); 890 } 891 892 // If a Master Plan wants to stop, we let it. Otherwise, see if the 893 // plan's parent wants to stop. 894 895 PopPlan(); 896 if (should_stop && current_plan->IsMasterPlan() && 897 !current_plan->OkayToDiscard()) { 898 break; 899 } 900 901 current_plan = GetCurrentPlan(); 902 if (current_plan == nullptr) { 903 break; 904 } 905 } else { 906 break; 907 } 908 } 909 } 910 911 if (override_stop) 912 should_stop = false; 913 } 914 915 // One other potential problem is that we set up a master plan, then stop in 916 // before it is complete - for instance by hitting a breakpoint during a 917 // step-over - then do some step/finish/etc operations that wind up past the 918 // end point condition of the initial plan. We don't want to strand the 919 // original plan on the stack, This code clears stale plans off the stack. 920 921 if (should_stop) { 922 ThreadPlan *plan_ptr = GetCurrentPlan(); 923 924 // Discard the stale plans and all plans below them in the stack, plus move 925 // the completed plans to the completed plan stack 926 while (!plan_ptr->IsBasePlan()) { 927 bool stale = plan_ptr->IsPlanStale(); 928 ThreadPlan *examined_plan = plan_ptr; 929 plan_ptr = GetPreviousPlan(examined_plan); 930 931 if (stale) { 932 LLDB_LOGF( 933 log, 934 "Plan %s being discarded in cleanup, it says it is already done.", 935 examined_plan->GetName()); 936 while (GetCurrentPlan() != examined_plan) { 937 DiscardPlan(); 938 } 939 if (examined_plan->IsPlanComplete()) { 940 // plan is complete but does not explain the stop (example: step to a 941 // line with breakpoint), let us move the plan to 942 // completed_plan_stack anyway 943 PopPlan(); 944 } else 945 DiscardPlan(); 946 } 947 } 948 } 949 950 if (log) { 951 StreamString s; 952 s.IndentMore(); 953 GetProcess()->DumpThreadPlansForTID( 954 s, GetID(), eDescriptionLevelVerbose, true /* internal */, 955 false /* condense_trivial */, true /* skip_unreported */); 956 LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData()); 957 LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv", 958 should_stop); 959 } 960 return should_stop; 961 } 962 963 Vote Thread::ShouldReportStop(Event *event_ptr) { 964 StateType thread_state = GetResumeState(); 965 StateType temp_thread_state = GetTemporaryResumeState(); 966 967 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 968 969 if (thread_state == eStateSuspended || thread_state == eStateInvalid) { 970 LLDB_LOGF(log, 971 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 972 ": returning vote %i (state was suspended or invalid)", 973 GetID(), eVoteNoOpinion); 974 return eVoteNoOpinion; 975 } 976 977 if (temp_thread_state == eStateSuspended || 978 temp_thread_state == eStateInvalid) { 979 LLDB_LOGF(log, 980 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 981 ": returning vote %i (temporary state was suspended or invalid)", 982 GetID(), eVoteNoOpinion); 983 return eVoteNoOpinion; 984 } 985 986 if (!ThreadStoppedForAReason()) { 987 LLDB_LOGF(log, 988 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 989 ": returning vote %i (thread didn't stop for a reason.)", 990 GetID(), eVoteNoOpinion); 991 return eVoteNoOpinion; 992 } 993 994 if (GetPlans().AnyCompletedPlans()) { 995 // Pass skip_private = false to GetCompletedPlan, since we want to ask 996 // the last plan, regardless of whether it is private or not. 997 LLDB_LOGF(log, 998 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 999 ": returning vote for complete stack's back plan", 1000 GetID()); 1001 return GetPlans().GetCompletedPlan(false)->ShouldReportStop(event_ptr); 1002 } else { 1003 Vote thread_vote = eVoteNoOpinion; 1004 ThreadPlan *plan_ptr = GetCurrentPlan(); 1005 while (true) { 1006 if (plan_ptr->PlanExplainsStop(event_ptr)) { 1007 thread_vote = plan_ptr->ShouldReportStop(event_ptr); 1008 break; 1009 } 1010 if (plan_ptr->IsBasePlan()) 1011 break; 1012 else 1013 plan_ptr = GetPreviousPlan(plan_ptr); 1014 } 1015 LLDB_LOGF(log, 1016 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64 1017 ": returning vote %i for current plan", 1018 GetID(), thread_vote); 1019 1020 return thread_vote; 1021 } 1022 } 1023 1024 Vote Thread::ShouldReportRun(Event *event_ptr) { 1025 StateType thread_state = GetResumeState(); 1026 1027 if (thread_state == eStateSuspended || thread_state == eStateInvalid) { 1028 return eVoteNoOpinion; 1029 } 1030 1031 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 1032 if (GetPlans().AnyCompletedPlans()) { 1033 // Pass skip_private = false to GetCompletedPlan, since we want to ask 1034 // the last plan, regardless of whether it is private or not. 1035 LLDB_LOGF(log, 1036 "Current Plan for thread %d(%p) (0x%4.4" PRIx64 1037 ", %s): %s being asked whether we should report run.", 1038 GetIndexID(), static_cast<void *>(this), GetID(), 1039 StateAsCString(GetTemporaryResumeState()), 1040 GetCompletedPlan()->GetName()); 1041 1042 return GetPlans().GetCompletedPlan(false)->ShouldReportRun(event_ptr); 1043 } else { 1044 LLDB_LOGF(log, 1045 "Current Plan for thread %d(%p) (0x%4.4" PRIx64 1046 ", %s): %s being asked whether we should report run.", 1047 GetIndexID(), static_cast<void *>(this), GetID(), 1048 StateAsCString(GetTemporaryResumeState()), 1049 GetCurrentPlan()->GetName()); 1050 1051 return GetCurrentPlan()->ShouldReportRun(event_ptr); 1052 } 1053 } 1054 1055 bool Thread::MatchesSpec(const ThreadSpec *spec) { 1056 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this); 1057 } 1058 1059 ThreadPlanStack &Thread::GetPlans() const { 1060 ThreadPlanStack *plans = GetProcess()->FindThreadPlans(GetID()); 1061 if (plans) 1062 return *plans; 1063 1064 // History threads don't have a thread plan, but they do ask get asked to 1065 // describe themselves, which usually involves pulling out the stop reason. 1066 // That in turn will check for a completed plan on the ThreadPlanStack. 1067 // Instead of special-casing at that point, we return a Stack with a 1068 // ThreadPlanNull as its base plan. That will give the right answers to the 1069 // queries GetDescription makes, and only assert if you try to run the thread. 1070 if (!m_null_plan_stack_up) 1071 m_null_plan_stack_up = std::make_unique<ThreadPlanStack>(*this, true); 1072 return *(m_null_plan_stack_up.get()); 1073 } 1074 1075 void Thread::PushPlan(ThreadPlanSP thread_plan_sp) { 1076 assert(thread_plan_sp && "Don't push an empty thread plan."); 1077 1078 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 1079 if (log) { 1080 StreamString s; 1081 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull); 1082 LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".", 1083 static_cast<void *>(this), s.GetData(), 1084 thread_plan_sp->GetThread().GetID()); 1085 } 1086 1087 GetPlans().PushPlan(std::move(thread_plan_sp)); 1088 } 1089 1090 void Thread::PopPlan() { 1091 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 1092 ThreadPlanSP popped_plan_sp = GetPlans().PopPlan(); 1093 if (log) { 1094 LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".", 1095 popped_plan_sp->GetName(), popped_plan_sp->GetThread().GetID()); 1096 } 1097 } 1098 1099 void Thread::DiscardPlan() { 1100 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 1101 ThreadPlanSP discarded_plan_sp = GetPlans().PopPlan(); 1102 1103 LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".", 1104 discarded_plan_sp->GetName(), 1105 discarded_plan_sp->GetThread().GetID()); 1106 } 1107 1108 void Thread::AutoCompleteThreadPlans(CompletionRequest &request) const { 1109 const ThreadPlanStack &plans = GetPlans(); 1110 if (!plans.AnyPlans()) 1111 return; 1112 1113 // Iterate from the second plan (index: 1) to skip the base plan. 1114 ThreadPlanSP p; 1115 uint32_t i = 1; 1116 while ((p = plans.GetPlanByIndex(i, false))) { 1117 StreamString strm; 1118 p->GetDescription(&strm, eDescriptionLevelInitial); 1119 request.TryCompleteCurrentArg(std::to_string(i), strm.GetString()); 1120 i++; 1121 } 1122 } 1123 1124 ThreadPlan *Thread::GetCurrentPlan() const { 1125 return GetPlans().GetCurrentPlan().get(); 1126 } 1127 1128 ThreadPlanSP Thread::GetCompletedPlan() const { 1129 return GetPlans().GetCompletedPlan(); 1130 } 1131 1132 ValueObjectSP Thread::GetReturnValueObject() const { 1133 return GetPlans().GetReturnValueObject(); 1134 } 1135 1136 ExpressionVariableSP Thread::GetExpressionVariable() const { 1137 return GetPlans().GetExpressionVariable(); 1138 } 1139 1140 bool Thread::IsThreadPlanDone(ThreadPlan *plan) const { 1141 return GetPlans().IsPlanDone(plan); 1142 } 1143 1144 bool Thread::WasThreadPlanDiscarded(ThreadPlan *plan) const { 1145 return GetPlans().WasPlanDiscarded(plan); 1146 } 1147 1148 bool Thread::CompletedPlanOverridesBreakpoint() const { 1149 return GetPlans().AnyCompletedPlans(); 1150 } 1151 1152 ThreadPlan *Thread::GetPreviousPlan(ThreadPlan *current_plan) const{ 1153 return GetPlans().GetPreviousPlan(current_plan); 1154 } 1155 1156 Status Thread::QueueThreadPlan(ThreadPlanSP &thread_plan_sp, 1157 bool abort_other_plans) { 1158 Status status; 1159 StreamString s; 1160 if (!thread_plan_sp->ValidatePlan(&s)) { 1161 DiscardThreadPlansUpToPlan(thread_plan_sp); 1162 thread_plan_sp.reset(); 1163 status.SetErrorString(s.GetString()); 1164 return status; 1165 } 1166 1167 if (abort_other_plans) 1168 DiscardThreadPlans(true); 1169 1170 PushPlan(thread_plan_sp); 1171 1172 // This seems a little funny, but I don't want to have to split up the 1173 // constructor and the DidPush in the scripted plan, that seems annoying. 1174 // That means the constructor has to be in DidPush. So I have to validate the 1175 // plan AFTER pushing it, and then take it off again... 1176 if (!thread_plan_sp->ValidatePlan(&s)) { 1177 DiscardThreadPlansUpToPlan(thread_plan_sp); 1178 thread_plan_sp.reset(); 1179 status.SetErrorString(s.GetString()); 1180 return status; 1181 } 1182 1183 return status; 1184 } 1185 1186 bool Thread::DiscardUserThreadPlansUpToIndex(uint32_t plan_index) { 1187 // Count the user thread plans from the back end to get the number of the one 1188 // we want to discard: 1189 1190 ThreadPlan *up_to_plan_ptr = GetPlans().GetPlanByIndex(plan_index).get(); 1191 if (up_to_plan_ptr == nullptr) 1192 return false; 1193 1194 DiscardThreadPlansUpToPlan(up_to_plan_ptr); 1195 return true; 1196 } 1197 1198 void Thread::DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp) { 1199 DiscardThreadPlansUpToPlan(up_to_plan_sp.get()); 1200 } 1201 1202 void Thread::DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr) { 1203 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 1204 LLDB_LOGF(log, 1205 "Discarding thread plans for thread tid = 0x%4.4" PRIx64 1206 ", up to %p", 1207 GetID(), static_cast<void *>(up_to_plan_ptr)); 1208 GetPlans().DiscardPlansUpToPlan(up_to_plan_ptr); 1209 } 1210 1211 void Thread::DiscardThreadPlans(bool force) { 1212 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 1213 if (log) { 1214 LLDB_LOGF(log, 1215 "Discarding thread plans for thread (tid = 0x%4.4" PRIx64 1216 ", force %d)", 1217 GetID(), force); 1218 } 1219 1220 if (force) { 1221 GetPlans().DiscardAllPlans(); 1222 return; 1223 } 1224 GetPlans().DiscardConsultingMasterPlans(); 1225 } 1226 1227 Status Thread::UnwindInnermostExpression() { 1228 Status error; 1229 ThreadPlan *innermost_expr_plan = GetPlans().GetInnermostExpression(); 1230 if (!innermost_expr_plan) { 1231 error.SetErrorString("No expressions currently active on this thread"); 1232 return error; 1233 } 1234 DiscardThreadPlansUpToPlan(innermost_expr_plan); 1235 return error; 1236 } 1237 1238 ThreadPlanSP Thread::QueueFundamentalPlan(bool abort_other_plans) { 1239 ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this)); 1240 QueueThreadPlan(thread_plan_sp, abort_other_plans); 1241 return thread_plan_sp; 1242 } 1243 1244 ThreadPlanSP Thread::QueueThreadPlanForStepSingleInstruction( 1245 bool step_over, bool abort_other_plans, bool stop_other_threads, 1246 Status &status) { 1247 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction( 1248 *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion)); 1249 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1250 return thread_plan_sp; 1251 } 1252 1253 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange( 1254 bool abort_other_plans, const AddressRange &range, 1255 const SymbolContext &addr_context, lldb::RunMode stop_other_threads, 1256 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) { 1257 ThreadPlanSP thread_plan_sp; 1258 thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>( 1259 *this, range, addr_context, stop_other_threads, 1260 step_out_avoids_code_withoug_debug_info); 1261 1262 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1263 return thread_plan_sp; 1264 } 1265 1266 // Call the QueueThreadPlanForStepOverRange method which takes an address 1267 // range. 1268 ThreadPlanSP Thread::QueueThreadPlanForStepOverRange( 1269 bool abort_other_plans, const LineEntry &line_entry, 1270 const SymbolContext &addr_context, lldb::RunMode stop_other_threads, 1271 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) { 1272 const bool include_inlined_functions = true; 1273 auto address_range = 1274 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions); 1275 return QueueThreadPlanForStepOverRange( 1276 abort_other_plans, address_range, addr_context, stop_other_threads, 1277 status, step_out_avoids_code_withoug_debug_info); 1278 } 1279 1280 ThreadPlanSP Thread::QueueThreadPlanForStepInRange( 1281 bool abort_other_plans, const AddressRange &range, 1282 const SymbolContext &addr_context, const char *step_in_target, 1283 lldb::RunMode stop_other_threads, Status &status, 1284 LazyBool step_in_avoids_code_without_debug_info, 1285 LazyBool step_out_avoids_code_without_debug_info) { 1286 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInRange( 1287 *this, range, addr_context, step_in_target, stop_other_threads, 1288 step_in_avoids_code_without_debug_info, 1289 step_out_avoids_code_without_debug_info)); 1290 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1291 return thread_plan_sp; 1292 } 1293 1294 // Call the QueueThreadPlanForStepInRange method which takes an address range. 1295 ThreadPlanSP Thread::QueueThreadPlanForStepInRange( 1296 bool abort_other_plans, const LineEntry &line_entry, 1297 const SymbolContext &addr_context, const char *step_in_target, 1298 lldb::RunMode stop_other_threads, Status &status, 1299 LazyBool step_in_avoids_code_without_debug_info, 1300 LazyBool step_out_avoids_code_without_debug_info) { 1301 const bool include_inlined_functions = false; 1302 return QueueThreadPlanForStepInRange( 1303 abort_other_plans, 1304 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions), 1305 addr_context, step_in_target, stop_other_threads, status, 1306 step_in_avoids_code_without_debug_info, 1307 step_out_avoids_code_without_debug_info); 1308 } 1309 1310 ThreadPlanSP Thread::QueueThreadPlanForStepOut( 1311 bool abort_other_plans, SymbolContext *addr_context, bool first_insn, 1312 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote, 1313 uint32_t frame_idx, Status &status, 1314 LazyBool step_out_avoids_code_without_debug_info) { 1315 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut( 1316 *this, addr_context, first_insn, stop_other_threads, report_stop_vote, 1317 report_run_vote, frame_idx, step_out_avoids_code_without_debug_info)); 1318 1319 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1320 return thread_plan_sp; 1321 } 1322 1323 ThreadPlanSP Thread::QueueThreadPlanForStepOutNoShouldStop( 1324 bool abort_other_plans, SymbolContext *addr_context, bool first_insn, 1325 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote, 1326 uint32_t frame_idx, Status &status, bool continue_to_next_branch) { 1327 const bool calculate_return_value = 1328 false; // No need to calculate the return value here. 1329 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut( 1330 *this, addr_context, first_insn, stop_other_threads, report_stop_vote, 1331 report_run_vote, frame_idx, eLazyBoolNo, continue_to_next_branch, 1332 calculate_return_value)); 1333 1334 ThreadPlanStepOut *new_plan = 1335 static_cast<ThreadPlanStepOut *>(thread_plan_sp.get()); 1336 new_plan->ClearShouldStopHereCallbacks(); 1337 1338 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1339 return thread_plan_sp; 1340 } 1341 1342 ThreadPlanSP Thread::QueueThreadPlanForStepThrough(StackID &return_stack_id, 1343 bool abort_other_plans, 1344 bool stop_other_threads, 1345 Status &status) { 1346 ThreadPlanSP thread_plan_sp( 1347 new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads)); 1348 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr)) 1349 return ThreadPlanSP(); 1350 1351 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1352 return thread_plan_sp; 1353 } 1354 1355 ThreadPlanSP Thread::QueueThreadPlanForRunToAddress(bool abort_other_plans, 1356 Address &target_addr, 1357 bool stop_other_threads, 1358 Status &status) { 1359 ThreadPlanSP thread_plan_sp( 1360 new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads)); 1361 1362 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1363 return thread_plan_sp; 1364 } 1365 1366 ThreadPlanSP Thread::QueueThreadPlanForStepUntil( 1367 bool abort_other_plans, lldb::addr_t *address_list, size_t num_addresses, 1368 bool stop_other_threads, uint32_t frame_idx, Status &status) { 1369 ThreadPlanSP thread_plan_sp(new ThreadPlanStepUntil( 1370 *this, address_list, num_addresses, stop_other_threads, frame_idx)); 1371 1372 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1373 return thread_plan_sp; 1374 } 1375 1376 lldb::ThreadPlanSP Thread::QueueThreadPlanForStepScripted( 1377 bool abort_other_plans, const char *class_name, 1378 StructuredData::ObjectSP extra_args_sp, bool stop_other_threads, 1379 Status &status) { 1380 1381 StructuredDataImpl *extra_args_impl = nullptr; 1382 if (extra_args_sp) { 1383 extra_args_impl = new StructuredDataImpl(); 1384 extra_args_impl->SetObjectSP(extra_args_sp); 1385 } 1386 1387 ThreadPlanSP thread_plan_sp(new ThreadPlanPython(*this, class_name, 1388 extra_args_impl)); 1389 thread_plan_sp->SetStopOthers(stop_other_threads); 1390 status = QueueThreadPlan(thread_plan_sp, abort_other_plans); 1391 return thread_plan_sp; 1392 } 1393 1394 uint32_t Thread::GetIndexID() const { return m_index_id; } 1395 1396 TargetSP Thread::CalculateTarget() { 1397 TargetSP target_sp; 1398 ProcessSP process_sp(GetProcess()); 1399 if (process_sp) 1400 target_sp = process_sp->CalculateTarget(); 1401 return target_sp; 1402 } 1403 1404 ProcessSP Thread::CalculateProcess() { return GetProcess(); } 1405 1406 ThreadSP Thread::CalculateThread() { return shared_from_this(); } 1407 1408 StackFrameSP Thread::CalculateStackFrame() { return StackFrameSP(); } 1409 1410 void Thread::CalculateExecutionContext(ExecutionContext &exe_ctx) { 1411 exe_ctx.SetContext(shared_from_this()); 1412 } 1413 1414 StackFrameListSP Thread::GetStackFrameList() { 1415 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex); 1416 1417 if (!m_curr_frames_sp) 1418 m_curr_frames_sp = 1419 std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true); 1420 1421 return m_curr_frames_sp; 1422 } 1423 1424 void Thread::ClearStackFrames() { 1425 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex); 1426 1427 GetUnwinder().Clear(); 1428 1429 // Only store away the old "reference" StackFrameList if we got all its 1430 // frames: 1431 // FIXME: At some point we can try to splice in the frames we have fetched 1432 // into 1433 // the new frame as we make it, but let's not try that now. 1434 if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched()) 1435 m_prev_frames_sp.swap(m_curr_frames_sp); 1436 m_curr_frames_sp.reset(); 1437 1438 m_extended_info.reset(); 1439 m_extended_info_fetched = false; 1440 } 1441 1442 lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) { 1443 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx); 1444 } 1445 1446 Status Thread::ReturnFromFrameWithIndex(uint32_t frame_idx, 1447 lldb::ValueObjectSP return_value_sp, 1448 bool broadcast) { 1449 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx); 1450 Status return_error; 1451 1452 if (!frame_sp) { 1453 return_error.SetErrorStringWithFormat( 1454 "Could not find frame with index %d in thread 0x%" PRIx64 ".", 1455 frame_idx, GetID()); 1456 } 1457 1458 return ReturnFromFrame(frame_sp, return_value_sp, broadcast); 1459 } 1460 1461 Status Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp, 1462 lldb::ValueObjectSP return_value_sp, 1463 bool broadcast) { 1464 Status return_error; 1465 1466 if (!frame_sp) { 1467 return_error.SetErrorString("Can't return to a null frame."); 1468 return return_error; 1469 } 1470 1471 Thread *thread = frame_sp->GetThread().get(); 1472 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1; 1473 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx); 1474 if (!older_frame_sp) { 1475 return_error.SetErrorString("No older frame to return to."); 1476 return return_error; 1477 } 1478 1479 if (return_value_sp) { 1480 lldb::ABISP abi = thread->GetProcess()->GetABI(); 1481 if (!abi) { 1482 return_error.SetErrorString("Could not find ABI to set return value."); 1483 return return_error; 1484 } 1485 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction); 1486 1487 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not 1488 // for scalars. 1489 // Turn that back on when that works. 1490 if (/* DISABLES CODE */ (false) && sc.function != nullptr) { 1491 Type *function_type = sc.function->GetType(); 1492 if (function_type) { 1493 CompilerType return_type = 1494 sc.function->GetCompilerType().GetFunctionReturnType(); 1495 if (return_type) { 1496 StreamString s; 1497 return_type.DumpTypeDescription(&s); 1498 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type); 1499 if (cast_value_sp) { 1500 cast_value_sp->SetFormat(eFormatHex); 1501 return_value_sp = cast_value_sp; 1502 } 1503 } 1504 } 1505 } 1506 1507 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp); 1508 if (!return_error.Success()) 1509 return return_error; 1510 } 1511 1512 // Now write the return registers for the chosen frame: Note, we can't use 1513 // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook 1514 // their data 1515 1516 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0); 1517 if (youngest_frame_sp) { 1518 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext()); 1519 if (reg_ctx_sp) { 1520 bool copy_success = reg_ctx_sp->CopyFromRegisterContext( 1521 older_frame_sp->GetRegisterContext()); 1522 if (copy_success) { 1523 thread->DiscardThreadPlans(true); 1524 thread->ClearStackFrames(); 1525 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged)) 1526 BroadcastEvent(eBroadcastBitStackChanged, 1527 new ThreadEventData(this->shared_from_this())); 1528 } else { 1529 return_error.SetErrorString("Could not reset register values."); 1530 } 1531 } else { 1532 return_error.SetErrorString("Frame has no register context."); 1533 } 1534 } else { 1535 return_error.SetErrorString("Returned past top frame."); 1536 } 1537 return return_error; 1538 } 1539 1540 static void DumpAddressList(Stream &s, const std::vector<Address> &list, 1541 ExecutionContextScope *exe_scope) { 1542 for (size_t n = 0; n < list.size(); n++) { 1543 s << "\t"; 1544 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription, 1545 Address::DumpStyleSectionNameOffset); 1546 s << "\n"; 1547 } 1548 } 1549 1550 Status Thread::JumpToLine(const FileSpec &file, uint32_t line, 1551 bool can_leave_function, std::string *warnings) { 1552 ExecutionContext exe_ctx(GetStackFrameAtIndex(0)); 1553 Target *target = exe_ctx.GetTargetPtr(); 1554 TargetSP target_sp = exe_ctx.GetTargetSP(); 1555 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext(); 1556 StackFrame *frame = exe_ctx.GetFramePtr(); 1557 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction); 1558 1559 // Find candidate locations. 1560 std::vector<Address> candidates, within_function, outside_function; 1561 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function, 1562 within_function, outside_function); 1563 1564 // If possible, we try and stay within the current function. Within a 1565 // function, we accept multiple locations (optimized code may do this, 1566 // there's no solution here so we do the best we can). However if we're 1567 // trying to leave the function, we don't know how to pick the right 1568 // location, so if there's more than one then we bail. 1569 if (!within_function.empty()) 1570 candidates = within_function; 1571 else if (outside_function.size() == 1 && can_leave_function) 1572 candidates = outside_function; 1573 1574 // Check if we got anything. 1575 if (candidates.empty()) { 1576 if (outside_function.empty()) { 1577 return Status("Cannot locate an address for %s:%i.", 1578 file.GetFilename().AsCString(), line); 1579 } else if (outside_function.size() == 1) { 1580 return Status("%s:%i is outside the current function.", 1581 file.GetFilename().AsCString(), line); 1582 } else { 1583 StreamString sstr; 1584 DumpAddressList(sstr, outside_function, target); 1585 return Status("%s:%i has multiple candidate locations:\n%s", 1586 file.GetFilename().AsCString(), line, sstr.GetData()); 1587 } 1588 } 1589 1590 // Accept the first location, warn about any others. 1591 Address dest = candidates[0]; 1592 if (warnings && candidates.size() > 1) { 1593 StreamString sstr; 1594 sstr.Printf("%s:%i appears multiple times in this function, selecting the " 1595 "first location:\n", 1596 file.GetFilename().AsCString(), line); 1597 DumpAddressList(sstr, candidates, target); 1598 *warnings = std::string(sstr.GetString()); 1599 } 1600 1601 if (!reg_ctx->SetPC(dest)) 1602 return Status("Cannot change PC to target address."); 1603 1604 return Status(); 1605 } 1606 1607 void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx, 1608 bool stop_format) { 1609 ExecutionContext exe_ctx(shared_from_this()); 1610 Process *process = exe_ctx.GetProcessPtr(); 1611 if (process == nullptr) 1612 return; 1613 1614 StackFrameSP frame_sp; 1615 SymbolContext frame_sc; 1616 if (frame_idx != LLDB_INVALID_FRAME_ID) { 1617 frame_sp = GetStackFrameAtIndex(frame_idx); 1618 if (frame_sp) { 1619 exe_ctx.SetFrameSP(frame_sp); 1620 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything); 1621 } 1622 } 1623 1624 const FormatEntity::Entry *thread_format; 1625 if (stop_format) 1626 thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat(); 1627 else 1628 thread_format = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat(); 1629 1630 assert(thread_format); 1631 1632 FormatEntity::Format(*thread_format, strm, frame_sp ? &frame_sc : nullptr, 1633 &exe_ctx, nullptr, nullptr, false, false); 1634 } 1635 1636 void Thread::SettingsInitialize() {} 1637 1638 void Thread::SettingsTerminate() {} 1639 1640 lldb::addr_t Thread::GetThreadPointer() { return LLDB_INVALID_ADDRESS; } 1641 1642 addr_t Thread::GetThreadLocalData(const ModuleSP module, 1643 lldb::addr_t tls_file_addr) { 1644 // The default implementation is to ask the dynamic loader for it. This can 1645 // be overridden for specific platforms. 1646 DynamicLoader *loader = GetProcess()->GetDynamicLoader(); 1647 if (loader) 1648 return loader->GetThreadLocalData(module, shared_from_this(), 1649 tls_file_addr); 1650 else 1651 return LLDB_INVALID_ADDRESS; 1652 } 1653 1654 bool Thread::SafeToCallFunctions() { 1655 Process *process = GetProcess().get(); 1656 if (process) { 1657 SystemRuntime *runtime = process->GetSystemRuntime(); 1658 if (runtime) { 1659 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this()); 1660 } 1661 } 1662 return true; 1663 } 1664 1665 lldb::StackFrameSP 1666 Thread::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) { 1667 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr); 1668 } 1669 1670 std::string Thread::StopReasonAsString(lldb::StopReason reason) { 1671 switch (reason) { 1672 case eStopReasonInvalid: 1673 return "invalid"; 1674 case eStopReasonNone: 1675 return "none"; 1676 case eStopReasonTrace: 1677 return "trace"; 1678 case eStopReasonBreakpoint: 1679 return "breakpoint"; 1680 case eStopReasonWatchpoint: 1681 return "watchpoint"; 1682 case eStopReasonSignal: 1683 return "signal"; 1684 case eStopReasonException: 1685 return "exception"; 1686 case eStopReasonExec: 1687 return "exec"; 1688 case eStopReasonPlanComplete: 1689 return "plan complete"; 1690 case eStopReasonThreadExiting: 1691 return "thread exiting"; 1692 case eStopReasonInstrumentation: 1693 return "instrumentation break"; 1694 } 1695 1696 return "StopReason = " + std::to_string(reason); 1697 } 1698 1699 std::string Thread::RunModeAsString(lldb::RunMode mode) { 1700 switch (mode) { 1701 case eOnlyThisThread: 1702 return "only this thread"; 1703 case eAllThreads: 1704 return "all threads"; 1705 case eOnlyDuringStepping: 1706 return "only during stepping"; 1707 } 1708 1709 return "RunMode = " + std::to_string(mode); 1710 } 1711 1712 size_t Thread::GetStatus(Stream &strm, uint32_t start_frame, 1713 uint32_t num_frames, uint32_t num_frames_with_source, 1714 bool stop_format, bool only_stacks) { 1715 1716 if (!only_stacks) { 1717 ExecutionContext exe_ctx(shared_from_this()); 1718 Target *target = exe_ctx.GetTargetPtr(); 1719 Process *process = exe_ctx.GetProcessPtr(); 1720 strm.Indent(); 1721 bool is_selected = false; 1722 if (process) { 1723 if (process->GetThreadList().GetSelectedThread().get() == this) 1724 is_selected = true; 1725 } 1726 strm.Printf("%c ", is_selected ? '*' : ' '); 1727 if (target && target->GetDebugger().GetUseExternalEditor()) { 1728 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame); 1729 if (frame_sp) { 1730 SymbolContext frame_sc( 1731 frame_sp->GetSymbolContext(eSymbolContextLineEntry)); 1732 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file) { 1733 Host::OpenFileInExternalEditor(frame_sc.line_entry.file, 1734 frame_sc.line_entry.line); 1735 } 1736 } 1737 } 1738 1739 DumpUsingSettingsFormat(strm, start_frame, stop_format); 1740 } 1741 1742 size_t num_frames_shown = 0; 1743 if (num_frames > 0) { 1744 strm.IndentMore(); 1745 1746 const bool show_frame_info = true; 1747 const bool show_frame_unique = only_stacks; 1748 const char *selected_frame_marker = nullptr; 1749 if (num_frames == 1 || only_stacks || 1750 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID())) 1751 strm.IndentMore(); 1752 else 1753 selected_frame_marker = "* "; 1754 1755 num_frames_shown = GetStackFrameList()->GetStatus( 1756 strm, start_frame, num_frames, show_frame_info, num_frames_with_source, 1757 show_frame_unique, selected_frame_marker); 1758 if (num_frames == 1) 1759 strm.IndentLess(); 1760 strm.IndentLess(); 1761 } 1762 return num_frames_shown; 1763 } 1764 1765 bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level, 1766 bool print_json_thread, bool print_json_stopinfo) { 1767 const bool stop_format = false; 1768 DumpUsingSettingsFormat(strm, 0, stop_format); 1769 strm.Printf("\n"); 1770 1771 StructuredData::ObjectSP thread_info = GetExtendedInfo(); 1772 1773 if (print_json_thread || print_json_stopinfo) { 1774 if (thread_info && print_json_thread) { 1775 thread_info->Dump(strm); 1776 strm.Printf("\n"); 1777 } 1778 1779 if (print_json_stopinfo && m_stop_info_sp) { 1780 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo(); 1781 if (stop_info) { 1782 stop_info->Dump(strm); 1783 strm.Printf("\n"); 1784 } 1785 } 1786 1787 return true; 1788 } 1789 1790 if (thread_info) { 1791 StructuredData::ObjectSP activity = 1792 thread_info->GetObjectForDotSeparatedPath("activity"); 1793 StructuredData::ObjectSP breadcrumb = 1794 thread_info->GetObjectForDotSeparatedPath("breadcrumb"); 1795 StructuredData::ObjectSP messages = 1796 thread_info->GetObjectForDotSeparatedPath("trace_messages"); 1797 1798 bool printed_activity = false; 1799 if (activity && activity->GetType() == eStructuredDataTypeDictionary) { 1800 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary(); 1801 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id"); 1802 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name"); 1803 if (name && name->GetType() == eStructuredDataTypeString && id && 1804 id->GetType() == eStructuredDataTypeInteger) { 1805 strm.Format(" Activity '{0}', {1:x}\n", 1806 name->GetAsString()->GetValue(), 1807 id->GetAsInteger()->GetValue()); 1808 } 1809 printed_activity = true; 1810 } 1811 bool printed_breadcrumb = false; 1812 if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) { 1813 if (printed_activity) 1814 strm.Printf("\n"); 1815 StructuredData::Dictionary *breadcrumb_dict = 1816 breadcrumb->GetAsDictionary(); 1817 StructuredData::ObjectSP breadcrumb_text = 1818 breadcrumb_dict->GetValueForKey("name"); 1819 if (breadcrumb_text && 1820 breadcrumb_text->GetType() == eStructuredDataTypeString) { 1821 strm.Format(" Current Breadcrumb: {0}\n", 1822 breadcrumb_text->GetAsString()->GetValue()); 1823 } 1824 printed_breadcrumb = true; 1825 } 1826 if (messages && messages->GetType() == eStructuredDataTypeArray) { 1827 if (printed_breadcrumb) 1828 strm.Printf("\n"); 1829 StructuredData::Array *messages_array = messages->GetAsArray(); 1830 const size_t msg_count = messages_array->GetSize(); 1831 if (msg_count > 0) { 1832 strm.Printf(" %zu trace messages:\n", msg_count); 1833 for (size_t i = 0; i < msg_count; i++) { 1834 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i); 1835 if (message && message->GetType() == eStructuredDataTypeDictionary) { 1836 StructuredData::Dictionary *message_dict = 1837 message->GetAsDictionary(); 1838 StructuredData::ObjectSP message_text = 1839 message_dict->GetValueForKey("message"); 1840 if (message_text && 1841 message_text->GetType() == eStructuredDataTypeString) { 1842 strm.Format(" {0}\n", message_text->GetAsString()->GetValue()); 1843 } 1844 } 1845 } 1846 } 1847 } 1848 } 1849 1850 return true; 1851 } 1852 1853 size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame, 1854 uint32_t num_frames, bool show_frame_info, 1855 uint32_t num_frames_with_source) { 1856 return GetStackFrameList()->GetStatus( 1857 strm, first_frame, num_frames, show_frame_info, num_frames_with_source); 1858 } 1859 1860 Unwind &Thread::GetUnwinder() { 1861 if (!m_unwinder_up) 1862 m_unwinder_up = std::make_unique<UnwindLLDB>(*this); 1863 return *m_unwinder_up; 1864 } 1865 1866 void Thread::Flush() { 1867 ClearStackFrames(); 1868 m_reg_context_sp.reset(); 1869 } 1870 1871 bool Thread::IsStillAtLastBreakpointHit() { 1872 // If we are currently stopped at a breakpoint, always return that stopinfo 1873 // and don't reset it. This allows threads to maintain their breakpoint 1874 // stopinfo, such as when thread-stepping in multithreaded programs. 1875 if (m_stop_info_sp) { 1876 StopReason stop_reason = m_stop_info_sp->GetStopReason(); 1877 if (stop_reason == lldb::eStopReasonBreakpoint) { 1878 uint64_t value = m_stop_info_sp->GetValue(); 1879 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext()); 1880 if (reg_ctx_sp) { 1881 lldb::addr_t pc = reg_ctx_sp->GetPC(); 1882 BreakpointSiteSP bp_site_sp = 1883 GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1884 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID()) 1885 return true; 1886 } 1887 } 1888 } 1889 return false; 1890 } 1891 1892 Status Thread::StepIn(bool source_step, 1893 LazyBool step_in_avoids_code_without_debug_info, 1894 LazyBool step_out_avoids_code_without_debug_info) 1895 1896 { 1897 Status error; 1898 Process *process = GetProcess().get(); 1899 if (StateIsStoppedState(process->GetState(), true)) { 1900 StackFrameSP frame_sp = GetStackFrameAtIndex(0); 1901 ThreadPlanSP new_plan_sp; 1902 const lldb::RunMode run_mode = eOnlyThisThread; 1903 const bool abort_other_plans = false; 1904 1905 if (source_step && frame_sp && frame_sp->HasDebugInformation()) { 1906 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); 1907 new_plan_sp = QueueThreadPlanForStepInRange( 1908 abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error, 1909 step_in_avoids_code_without_debug_info, 1910 step_out_avoids_code_without_debug_info); 1911 } else { 1912 new_plan_sp = QueueThreadPlanForStepSingleInstruction( 1913 false, abort_other_plans, run_mode, error); 1914 } 1915 1916 new_plan_sp->SetIsMasterPlan(true); 1917 new_plan_sp->SetOkayToDiscard(false); 1918 1919 // Why do we need to set the current thread by ID here??? 1920 process->GetThreadList().SetSelectedThreadByID(GetID()); 1921 error = process->Resume(); 1922 } else { 1923 error.SetErrorString("process not stopped"); 1924 } 1925 return error; 1926 } 1927 1928 Status Thread::StepOver(bool source_step, 1929 LazyBool step_out_avoids_code_without_debug_info) { 1930 Status error; 1931 Process *process = GetProcess().get(); 1932 if (StateIsStoppedState(process->GetState(), true)) { 1933 StackFrameSP frame_sp = GetStackFrameAtIndex(0); 1934 ThreadPlanSP new_plan_sp; 1935 1936 const lldb::RunMode run_mode = eOnlyThisThread; 1937 const bool abort_other_plans = false; 1938 1939 if (source_step && frame_sp && frame_sp->HasDebugInformation()) { 1940 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything)); 1941 new_plan_sp = QueueThreadPlanForStepOverRange( 1942 abort_other_plans, sc.line_entry, sc, run_mode, error, 1943 step_out_avoids_code_without_debug_info); 1944 } else { 1945 new_plan_sp = QueueThreadPlanForStepSingleInstruction( 1946 true, abort_other_plans, run_mode, error); 1947 } 1948 1949 new_plan_sp->SetIsMasterPlan(true); 1950 new_plan_sp->SetOkayToDiscard(false); 1951 1952 // Why do we need to set the current thread by ID here??? 1953 process->GetThreadList().SetSelectedThreadByID(GetID()); 1954 error = process->Resume(); 1955 } else { 1956 error.SetErrorString("process not stopped"); 1957 } 1958 return error; 1959 } 1960 1961 Status Thread::StepOut() { 1962 Status error; 1963 Process *process = GetProcess().get(); 1964 if (StateIsStoppedState(process->GetState(), true)) { 1965 const bool first_instruction = false; 1966 const bool stop_other_threads = false; 1967 const bool abort_other_plans = false; 1968 1969 ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut( 1970 abort_other_plans, nullptr, first_instruction, stop_other_threads, 1971 eVoteYes, eVoteNoOpinion, 0, error)); 1972 1973 new_plan_sp->SetIsMasterPlan(true); 1974 new_plan_sp->SetOkayToDiscard(false); 1975 1976 // Why do we need to set the current thread by ID here??? 1977 process->GetThreadList().SetSelectedThreadByID(GetID()); 1978 error = process->Resume(); 1979 } else { 1980 error.SetErrorString("process not stopped"); 1981 } 1982 return error; 1983 } 1984 1985 ValueObjectSP Thread::GetCurrentException() { 1986 if (auto frame_sp = GetStackFrameAtIndex(0)) 1987 if (auto recognized_frame = frame_sp->GetRecognizedFrame()) 1988 if (auto e = recognized_frame->GetExceptionObject()) 1989 return e; 1990 1991 // NOTE: Even though this behavior is generalized, only ObjC is actually 1992 // supported at the moment. 1993 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) { 1994 if (auto e = runtime->GetExceptionObjectForThread(shared_from_this())) 1995 return e; 1996 } 1997 1998 return ValueObjectSP(); 1999 } 2000 2001 ThreadSP Thread::GetCurrentExceptionBacktrace() { 2002 ValueObjectSP exception = GetCurrentException(); 2003 if (!exception) 2004 return ThreadSP(); 2005 2006 // NOTE: Even though this behavior is generalized, only ObjC is actually 2007 // supported at the moment. 2008 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) { 2009 if (auto bt = runtime->GetBacktraceThreadFromException(exception)) 2010 return bt; 2011 } 2012 2013 return ThreadSP(); 2014 } 2015