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