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