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