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