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