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