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