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