blob: 10678ecf415339637f2e76aec6068e5554f07946 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Eugene Zelenko8f30a652015-10-23 18:39:37 +000010// C Includes
11// C++ Includes
12// Other libraries and framework includes
13// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000014#include "lldb/Target/Thread.h"
15#include "Plugins/Process/Utility/UnwindLLDB.h"
16#include "Plugins/Process/Utility/UnwindMacOSXFrameBackchain.h"
Jim Ingham1b54c882010-06-16 02:00:15 +000017#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton0603aa92010-10-04 01:05:56 +000018#include "lldb/Core/Debugger.h"
Greg Clayton554f68d2015-02-04 22:00:53 +000019#include "lldb/Core/FormatEntity.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include "lldb/Core/Log.h"
Jason Molenda03c9cd02015-08-06 21:54:29 +000021#include "lldb/Core/Module.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000022#include "lldb/Core/RegularExpression.h"
Greg Clayton160c9d82013-05-01 21:54:04 +000023#include "lldb/Core/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/Stream.h"
25#include "lldb/Core/StreamString.h"
Jim Ingham0d5a2bd2015-09-03 01:40:51 +000026#include "lldb/Core/ValueObject.h"
Greg Clayton7260f622011-04-18 08:33:37 +000027#include "lldb/Host/Host.h"
Jim Ingham4da62062014-01-23 21:52:47 +000028#include "lldb/Interpreter/OptionValueFileSpecList.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000029#include "lldb/Interpreter/OptionValueProperties.h"
30#include "lldb/Interpreter/Property.h"
Jim Ingham1f51e602012-09-27 01:15:29 +000031#include "lldb/Symbol/Function.h"
Zachary Turner32abc6e2015-03-03 19:23:09 +000032#include "lldb/Target/ABI.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/DynamicLoader.h"
34#include "lldb/Target/ExecutionContext.h"
35#include "lldb/Target/Process.h"
36#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Jason Molendab4892cd2014-05-13 22:02:48 +000038#include "lldb/Target/SystemRuntime.h"
Greg Clayton896dff62010-07-23 16:45:51 +000039#include "lldb/Target/Target.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/ThreadPlan.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Target/ThreadPlanBase.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000042#include "lldb/Target/ThreadPlanCallFunction.h"
Jim Ingham2bdbfd52014-09-29 23:17:18 +000043#include "lldb/Target/ThreadPlanPython.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000044#include "lldb/Target/ThreadPlanRunToAddress.h"
45#include "lldb/Target/ThreadPlanStepInRange.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Target/ThreadPlanStepInstruction.h"
47#include "lldb/Target/ThreadPlanStepOut.h"
48#include "lldb/Target/ThreadPlanStepOverBreakpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Target/ThreadPlanStepOverRange.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000050#include "lldb/Target/ThreadPlanStepThrough.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000051#include "lldb/Target/ThreadPlanStepUntil.h"
Jim Ingham1b54c882010-06-16 02:00:15 +000052#include "lldb/Target/ThreadSpec.h"
Jim Ingham87c11912010-08-12 02:14:28 +000053#include "lldb/Target/Unwind.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000054
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055using namespace lldb;
56using namespace lldb_private;
57
Kate Stoneb9c1b512016-09-06 20:57:50 +000058const 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
Pavel Labath5f05ea82016-10-19 15:12:45 +000061 static ThreadPropertiesSP *g_settings_sp_ptr =
62 new ThreadPropertiesSP(new ThreadProperties(true));
Kate Stoneb9c1b512016-09-06 20:57:50 +000063 return *g_settings_sp_ptr;
Greg Clayton67cc0632012-08-22 17:17:09 +000064}
65
Kate Stoneb9c1b512016-09-06 20:57:50 +000066static PropertyDefinition g_properties[] = {
67 {"step-in-avoid-nodebug", OptionValue::eTypeBoolean, true, true, nullptr,
68 nullptr,
69 "If true, step-in will not stop in functions with no debug information."},
70 {"step-out-avoid-nodebug", OptionValue::eTypeBoolean, true, false, nullptr,
71 nullptr, "If true, when step-in/step-out/step-over leave the current "
72 "frame, they will continue to step out till they come to a "
73 "function with "
74 "debug information. Passing a frame argument to step-out will "
75 "override this option."},
76 {"step-avoid-regexp", OptionValue::eTypeRegex, true, 0, "^std::", nullptr,
77 "A regular expression defining functions step-in won't stop in."},
78 {"step-avoid-libraries", OptionValue::eTypeFileSpecList, true, 0, nullptr,
79 nullptr, "A list of libraries that source stepping won't stop in."},
80 {"trace-thread", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
81 "If true, this thread will single-step and log execution."},
82 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +000083
84enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 ePropertyStepInAvoidsNoDebug,
86 ePropertyStepOutAvoidsNoDebug,
87 ePropertyStepAvoidRegex,
88 ePropertyStepAvoidLibraries,
89 ePropertyEnableThreadTrace
Greg Clayton67cc0632012-08-22 17:17:09 +000090};
91
Kate Stoneb9c1b512016-09-06 20:57:50 +000092class ThreadOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000093public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 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
100 ThreadOptionValueProperties(ThreadProperties *global_properties)
101 : OptionValueProperties(*global_properties->GetValueProperties()) {}
102
103 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 we
108 // just
109 // use the one from this instance.
110 if (exe_ctx) {
111 Thread *thread = exe_ctx->GetThreadPtr();
112 if (thread) {
113 ThreadOptionValueProperties *instance_properties =
114 static_cast<ThreadOptionValueProperties *>(
115 thread->GetValueProperties().get());
116 if (this != instance_properties)
117 return instance_properties->ProtectedGetPropertyAtIndex(idx);
118 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000119 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 return ProtectedGetPropertyAtIndex(idx);
121 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000122};
123
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124ThreadProperties::ThreadProperties(bool is_global) : Properties() {
125 if (is_global) {
126 m_collection_sp.reset(
127 new ThreadOptionValueProperties(ConstString("thread")));
128 m_collection_sp->Initialize(g_properties);
129 } else
130 m_collection_sp.reset(
131 new ThreadOptionValueProperties(Thread::GetGlobalProperties().get()));
Greg Clayton67cc0632012-08-22 17:17:09 +0000132}
133
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000134ThreadProperties::~ThreadProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136const RegularExpression *ThreadProperties::GetSymbolsToAvoidRegexp() {
137 const uint32_t idx = ePropertyStepAvoidRegex;
138 return m_collection_sp->GetPropertyAtIndexAsOptionValueRegex(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +0000139}
140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141FileSpecList &ThreadProperties::GetLibrariesToAvoid() const {
142 const uint32_t idx = ePropertyStepAvoidLibraries;
143 OptionValueFileSpecList *option_value =
144 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
145 false, idx);
146 assert(option_value);
147 return option_value->GetCurrentValue();
Jim Ingham4da62062014-01-23 21:52:47 +0000148}
149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150bool ThreadProperties::GetTraceEnabledState() const {
151 const uint32_t idx = ePropertyEnableThreadTrace;
152 return m_collection_sp->GetPropertyAtIndexAsBoolean(
153 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000154}
155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156bool ThreadProperties::GetStepInAvoidsNoDebug() const {
157 const uint32_t idx = ePropertyStepInAvoidsNoDebug;
158 return m_collection_sp->GetPropertyAtIndexAsBoolean(
159 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham4b4b2472014-03-13 02:47:14 +0000160}
161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162bool ThreadProperties::GetStepOutAvoidsNoDebug() const {
163 const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
164 return m_collection_sp->GetPropertyAtIndexAsBoolean(
165 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham4b4b2472014-03-13 02:47:14 +0000166}
167
Jim Ingham4f465cf2012-10-10 18:32:14 +0000168//------------------------------------------------------------------
169// Thread Event Data
170//------------------------------------------------------------------
Greg Clayton67cc0632012-08-22 17:17:09 +0000171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172const ConstString &Thread::ThreadEventData::GetFlavorString() {
173 static ConstString g_flavor("Thread::ThreadEventData");
174 return g_flavor;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000175}
176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp)
178 : m_thread_sp(thread_sp), m_stack_id() {}
Jim Ingham4f465cf2012-10-10 18:32:14 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180Thread::ThreadEventData::ThreadEventData(const lldb::ThreadSP thread_sp,
181 const StackID &stack_id)
182 : m_thread_sp(thread_sp), m_stack_id(stack_id) {}
Jim Ingham4f465cf2012-10-10 18:32:14 +0000183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184Thread::ThreadEventData::ThreadEventData() : m_thread_sp(), m_stack_id() {}
Jim Ingham4f465cf2012-10-10 18:32:14 +0000185
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000186Thread::ThreadEventData::~ThreadEventData() = default;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188void Thread::ThreadEventData::Dump(Stream *s) const {}
Jim Ingham4f465cf2012-10-10 18:32:14 +0000189
190const Thread::ThreadEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191Thread::ThreadEventData::GetEventDataFromEvent(const Event *event_ptr) {
192 if (event_ptr) {
193 const EventData *event_data = event_ptr->GetData();
194 if (event_data &&
195 event_data->GetFlavor() == ThreadEventData::GetFlavorString())
196 return static_cast<const ThreadEventData *>(event_ptr->GetData());
197 }
198 return nullptr;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000199}
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201ThreadSP Thread::ThreadEventData::GetThreadFromEvent(const Event *event_ptr) {
202 ThreadSP thread_sp;
203 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
204 if (event_data)
205 thread_sp = event_data->GetThread();
206 return thread_sp;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000207}
208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209StackID Thread::ThreadEventData::GetStackIDFromEvent(const Event *event_ptr) {
210 StackID stack_id;
211 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
212 if (event_data)
213 stack_id = event_data->GetStackID();
214 return stack_id;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000215}
216
Jason Molendab57e4a12013-11-04 09:33:30 +0000217StackFrameSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218Thread::ThreadEventData::GetStackFrameFromEvent(const Event *event_ptr) {
219 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
220 StackFrameSP frame_sp;
221 if (event_data) {
222 ThreadSP thread_sp = event_data->GetThread();
223 if (thread_sp) {
224 frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID(
225 event_data->GetStackID());
Jim Ingham4f465cf2012-10-10 18:32:14 +0000226 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 }
228 return frame_sp;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000229}
230
231//------------------------------------------------------------------
232// Thread class
233//------------------------------------------------------------------
234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235ConstString &Thread::GetStaticBroadcasterClass() {
236 static ConstString class_name("lldb.thread");
237 return class_name;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000238}
239
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000240Thread::Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 : ThreadProperties(false), UserID(tid),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000242 Broadcaster(process.GetTarget().GetDebugger().GetBroadcasterManager(),
243 Thread::GetStaticBroadcasterClass().AsCString()),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 m_process_wp(process.shared_from_this()), m_stop_info_sp(),
245 m_stop_info_stop_id(0), m_stop_info_override_stop_id(0),
246 m_index_id(use_invalid_index_id ? LLDB_INVALID_INDEX32
247 : process.GetNextThreadIndexID(tid)),
248 m_reg_context_sp(), m_state(eStateUnloaded), m_state_mutex(),
249 m_plan_stack(), m_completed_plan_stack(), m_frame_mutex(),
250 m_curr_frames_sp(), m_prev_frames_sp(),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000251 m_resume_signal(LLDB_INVALID_SIGNAL_NUMBER),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 m_resume_state(eStateRunning), m_temporary_resume_state(eStateRunning),
253 m_unwinder_ap(), m_destroy_called(false),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000254 m_override_should_notify(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 m_extended_info_fetched(false), m_extended_info() {
256 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
257 if (log)
258 log->Printf("%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
259 static_cast<void *>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000260
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 CheckInWithManager();
262 QueueFundamentalPlan(true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000263}
264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265Thread::~Thread() {
266 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
267 if (log)
268 log->Printf("%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
269 static_cast<void *>(this), GetID());
270 /// If you hit this assert, it means your derived class forgot to call
271 /// DoDestroy in its destructor.
272 assert(m_destroy_called);
Jim Ingham773d9812010-11-18 02:47:07 +0000273}
274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275void Thread::DestroyThread() {
276 // Tell any plans on the plan stacks that the thread is being destroyed since
277 // any plans that have a thread go away in the middle of might need
278 // to do cleanup, or in some cases NOT do cleanup...
279 for (auto plan : m_plan_stack)
280 plan->ThreadDestroyed();
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 for (auto plan : m_discarded_plan_stack)
283 plan->ThreadDestroyed();
Jim Inghamb1499242013-10-18 17:11:02 +0000284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 for (auto plan : m_completed_plan_stack)
286 plan->ThreadDestroyed();
Jim Inghamb1499242013-10-18 17:11:02 +0000287
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288 m_destroy_called = true;
289 m_plan_stack.clear();
290 m_discarded_plan_stack.clear();
291 m_completed_plan_stack.clear();
292
293 // Push a ThreadPlanNull on the plan stack. That way we can continue assuming
294 // that the
295 // plan stack is never empty, but if somebody errantly asks questions of a
296 // destroyed thread
297 // without checking first whether it is destroyed, they won't crash.
298 ThreadPlanSP null_plan_sp(new ThreadPlanNull(*this));
299 m_plan_stack.push_back(null_plan_sp);
300
301 m_stop_info_sp.reset();
302 m_reg_context_sp.reset();
303 m_unwinder_ap.reset();
304 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
305 m_curr_frames_sp.reset();
306 m_prev_frames_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000307}
308
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309void Thread::BroadcastSelectedFrameChange(StackID &new_frame_id) {
310 if (EventTypeHasListeners(eBroadcastBitSelectedFrameChanged))
311 BroadcastEvent(eBroadcastBitSelectedFrameChanged,
312 new ThreadEventData(this->shared_from_this(), new_frame_id));
Jim Ingham4f465cf2012-10-10 18:32:14 +0000313}
314
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315lldb::StackFrameSP Thread::GetSelectedFrame() {
316 StackFrameListSP stack_frame_list_sp(GetStackFrameList());
317 StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex(
318 stack_frame_list_sp->GetSelectedFrameIndex());
319 FunctionOptimizationWarning(frame_sp.get());
320 return frame_sp;
Jason Molendaef7d6412015-08-06 03:27:10 +0000321}
322
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323uint32_t Thread::SetSelectedFrame(lldb_private::StackFrame *frame,
324 bool broadcast) {
325 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
326 if (broadcast)
327 BroadcastSelectedFrameChange(frame->GetStackID());
328 FunctionOptimizationWarning(frame);
329 return ret_value;
330}
331
332bool Thread::SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast) {
333 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex(frame_idx));
334 if (frame_sp) {
335 GetStackFrameList()->SetSelectedFrame(frame_sp.get());
Jim Ingham4f465cf2012-10-10 18:32:14 +0000336 if (broadcast)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 BroadcastSelectedFrameChange(frame_sp->GetStackID());
338 FunctionOptimizationWarning(frame_sp.get());
339 return true;
340 } else
341 return false;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000342}
343
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344bool Thread::SetSelectedFrameByIndexNoisily(uint32_t frame_idx,
345 Stream &output_stream) {
346 const bool broadcast = true;
347 bool success = SetSelectedFrameByIndex(frame_idx, broadcast);
348 if (success) {
349 StackFrameSP frame_sp = GetSelectedFrame();
350 if (frame_sp) {
351 bool already_shown = false;
352 SymbolContext frame_sc(
353 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
354 if (GetProcess()->GetTarget().GetDebugger().GetUseExternalEditor() &&
355 frame_sc.line_entry.file && frame_sc.line_entry.line != 0) {
356 already_shown = Host::OpenFileInExternalEditor(
357 frame_sc.line_entry.file, frame_sc.line_entry.line);
358 }
359
360 bool show_frame_info = true;
361 bool show_source = !already_shown;
362 FunctionOptimizationWarning(frame_sp.get());
363 return frame_sp->GetStatus(output_stream, show_frame_info, show_source);
Jim Ingham4f465cf2012-10-10 18:32:14 +0000364 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 return false;
366 } else
367 return false;
Jim Ingham4f465cf2012-10-10 18:32:14 +0000368}
369
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370void Thread::FunctionOptimizationWarning(StackFrame *frame) {
371 if (frame && frame->HasDebugInformation() &&
372 GetProcess()->GetWarningsOptimization()) {
373 SymbolContext sc =
374 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextModule);
375 GetProcess()->PrintWarningOptimization(sc);
376 }
Jim Ingham93208b82013-01-31 21:46:01 +0000377}
378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379lldb::StopInfoSP Thread::GetStopInfo() {
380 if (m_destroy_called)
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000381 return m_stop_info_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382
383 ThreadPlanSP plan_sp(GetCompletedPlan());
384 ProcessSP process_sp(GetProcess());
385 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
386 if (plan_sp && plan_sp->PlanSucceeded()) {
387 return StopInfo::CreateStopReasonWithPlan(plan_sp, GetReturnValueObject(),
388 GetExpressionVariable());
389 } else {
390 if ((m_stop_info_stop_id == stop_id) || // Stop info is valid, just return
391 // what we have (even if empty)
392 (m_stop_info_sp &&
393 m_stop_info_sp
394 ->IsValid())) // Stop info is valid, just return what we have
395 {
396 return m_stop_info_sp;
397 } else {
398 GetPrivateStopInfo();
399 return m_stop_info_sp;
400 }
401 }
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000402}
403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404lldb::StopInfoSP Thread::GetPrivateStopInfo() {
405 if (m_destroy_called)
406 return m_stop_info_sp;
407
408 ProcessSP process_sp(GetProcess());
409 if (process_sp) {
410 const uint32_t process_stop_id = process_sp->GetStopID();
411 if (m_stop_info_stop_id != process_stop_id) {
412 if (m_stop_info_sp) {
413 if (m_stop_info_sp->IsValid() || IsStillAtLastBreakpointHit() ||
414 GetCurrentPlan()->IsVirtualStep())
415 SetStopInfo(m_stop_info_sp);
416 else
417 m_stop_info_sp.reset();
418 }
419
420 if (!m_stop_info_sp) {
421 if (!CalculateStopInfo())
422 SetStopInfo(StopInfoSP());
423 }
424 }
425
426 // The stop info can be manually set by calling Thread::SetStopInfo()
427 // prior to this function ever getting called, so we can't rely on
428 // "m_stop_info_stop_id != process_stop_id" as the condition for
429 // the if statement below, we must also check the stop info to see
430 // if we need to override it. See the header documentation in
431 // Process::GetStopInfoOverrideCallback() for more information on
432 // the stop info override callback.
433 if (m_stop_info_override_stop_id != process_stop_id) {
434 m_stop_info_override_stop_id = process_stop_id;
435 if (m_stop_info_sp) {
436 ArchSpec::StopInfoOverrideCallbackType callback =
437 GetProcess()->GetStopInfoOverrideCallback();
438 if (callback)
439 callback(*this);
440 }
441 }
442 }
443 return m_stop_info_sp;
Greg Clayton97d5cf02012-09-25 02:40:06 +0000444}
445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446lldb::StopReason Thread::GetStopReason() {
447 lldb::StopInfoSP stop_info_sp(GetStopInfo());
448 if (stop_info_sp)
449 return stop_info_sp->GetStopReason();
450 return eStopReasonNone;
Greg Clayton2e309072015-07-17 23:42:28 +0000451}
Greg Clayton97d5cf02012-09-25 02:40:06 +0000452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453bool Thread::StopInfoIsUpToDate() const {
454 ProcessSP process_sp(GetProcess());
455 if (process_sp)
456 return m_stop_info_stop_id == process_sp->GetStopID();
457 else
458 return true; // Process is no longer around so stop info is always up to
459 // date...
460}
461
462void Thread::SetStopInfo(const lldb::StopInfoSP &stop_info_sp) {
463 m_stop_info_sp = stop_info_sp;
464 if (m_stop_info_sp) {
465 m_stop_info_sp->MakeStopInfoValid();
466 // If we are overriding the ShouldReportStop, do that here:
467 if (m_override_should_notify != eLazyBoolCalculate)
468 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
469 eLazyBoolYes);
470 }
471
472 ProcessSP process_sp(GetProcess());
473 if (process_sp)
474 m_stop_info_stop_id = process_sp->GetStopID();
475 else
476 m_stop_info_stop_id = UINT32_MAX;
477 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
478 if (log)
479 log->Printf("%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
480 static_cast<void *>(this), GetID(),
481 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
482 m_stop_info_stop_id);
483}
484
485void Thread::SetShouldReportStop(Vote vote) {
486 if (vote == eVoteNoOpinion)
487 return;
488 else {
489 m_override_should_notify = (vote == eVoteYes ? eLazyBoolYes : eLazyBoolNo);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +0000490 if (m_stop_info_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
492 eLazyBoolYes);
493 }
494}
495
496void Thread::SetStopInfoToNothing() {
497 // Note, we can't just NULL out the private reason, or the native thread
498 // implementation will try to
499 // go calculate it again. For now, just set it to a Unix Signal with an
500 // invalid signal number.
501 SetStopInfo(
502 StopInfo::CreateStopReasonWithSignal(*this, LLDB_INVALID_SIGNAL_NUMBER));
503}
504
505bool Thread::ThreadStoppedForAReason(void) {
506 return (bool)GetPrivateStopInfo();
507}
508
509bool Thread::CheckpointThreadState(ThreadStateCheckpoint &saved_state) {
510 saved_state.register_backup_sp.reset();
511 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
512 if (frame_sp) {
513 lldb::RegisterCheckpointSP reg_checkpoint_sp(
514 new RegisterCheckpoint(RegisterCheckpoint::Reason::eExpression));
515 if (reg_checkpoint_sp) {
516 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
517 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues(*reg_checkpoint_sp))
518 saved_state.register_backup_sp = reg_checkpoint_sp;
Jim Ingham221d51c2013-05-08 00:35:16 +0000519 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 }
521 if (!saved_state.register_backup_sp)
Greg Claytonf74cf862013-11-13 23:28:31 +0000522 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523
524 saved_state.stop_info_sp = GetStopInfo();
525 ProcessSP process_sp(GetProcess());
526 if (process_sp)
527 saved_state.orig_stop_id = process_sp->GetStopID();
528 saved_state.current_inlined_depth = GetCurrentInlinedDepth();
529
530 return true;
Jim Ingham8559a352012-11-26 23:52:18 +0000531}
532
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533bool Thread::RestoreRegisterStateFromCheckpoint(
534 ThreadStateCheckpoint &saved_state) {
535 if (saved_state.register_backup_sp) {
536 lldb::StackFrameSP frame_sp(GetStackFrameAtIndex(0));
537 if (frame_sp) {
538 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
539 if (reg_ctx_sp) {
540 bool ret =
541 reg_ctx_sp->WriteAllRegisterValues(*saved_state.register_backup_sp);
Jim Ingham77787032011-01-20 02:03:18 +0000542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 // Clear out all stack frames as our world just changed.
Greg Clayton160c9d82013-05-01 21:54:04 +0000544 ClearStackFrames();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 reg_ctx_sp->InvalidateIfNeeded(true);
546 if (m_unwinder_ap.get())
547 m_unwinder_ap->Clear();
548 return ret;
549 }
Greg Clayton160c9d82013-05-01 21:54:04 +0000550 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 }
552 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000553}
554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555bool Thread::RestoreThreadStateFromCheckpoint(
556 ThreadStateCheckpoint &saved_state) {
557 if (saved_state.stop_info_sp)
558 saved_state.stop_info_sp->MakeStopInfoValid();
559 SetStopInfo(saved_state.stop_info_sp);
560 GetStackFrameList()->SetCurrentInlinedDepth(
561 saved_state.current_inlined_depth);
562 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000563}
564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565StateType Thread::GetState() const {
566 // If any other threads access this we will need a mutex for it
567 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
568 return m_state;
Andrew Kaylor29d65742013-05-10 17:19:04 +0000569}
570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571void Thread::SetState(StateType state) {
572 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
573 m_state = state;
574}
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000575
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576void Thread::WillStop() {
577 ThreadPlan *current_plan = GetCurrentPlan();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 // FIXME: I may decide to disallow threads with no plans. In which
580 // case this should go to an assert.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 if (!current_plan)
583 return;
584
585 current_plan->WillStop();
586}
587
588void Thread::SetupForResume() {
589 if (GetResumeState() != eStateSuspended) {
590 // If we're at a breakpoint push the step-over breakpoint plan. Do this
591 // before
592 // telling the current plan it will resume, since we might change what the
593 // current
594 // plan is.
595
596 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
597 if (reg_ctx_sp) {
598 const addr_t thread_pc = reg_ctx_sp->GetPC();
599 BreakpointSiteSP bp_site_sp =
600 GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc);
601 if (bp_site_sp) {
602 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target
603 // may not require anything
604 // special to step over a breakpoint.
605
606 ThreadPlan *cur_plan = GetCurrentPlan();
607
608 bool push_step_over_bp_plan = false;
609 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {
610 ThreadPlanStepOverBreakpoint *bp_plan =
611 (ThreadPlanStepOverBreakpoint *)cur_plan;
612 if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
613 push_step_over_bp_plan = true;
614 } else
615 push_step_over_bp_plan = true;
616
617 if (push_step_over_bp_plan) {
618 ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));
619 if (step_bp_plan_sp) {
620 step_bp_plan_sp->SetPrivate(true);
621
622 if (GetCurrentPlan()->RunState() != eStateStepping) {
623 ThreadPlanStepOverBreakpoint *step_bp_plan =
624 static_cast<ThreadPlanStepOverBreakpoint *>(
625 step_bp_plan_sp.get());
626 step_bp_plan->SetAutoContinue(true);
627 }
628 QueueThreadPlan(step_bp_plan_sp, false);
629 }
630 }
631 }
632 }
633 }
634}
635
636bool Thread::ShouldResume(StateType resume_state) {
637 // At this point clear the completed plan stack.
638 m_completed_plan_stack.clear();
639 m_discarded_plan_stack.clear();
640 m_override_should_notify = eLazyBoolCalculate;
641
642 StateType prev_resume_state = GetTemporaryResumeState();
643
644 SetTemporaryResumeState(resume_state);
645
646 lldb::ThreadSP backing_thread_sp(GetBackingThread());
647 if (backing_thread_sp)
648 backing_thread_sp->SetTemporaryResumeState(resume_state);
649
650 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended
651 // in the previous run.
652 if (prev_resume_state != eStateSuspended)
653 GetPrivateStopInfo();
654
655 // This is a little dubious, but we are trying to limit how often we actually
656 // fetch stop info from
657 // the target, 'cause that slows down single stepping. So assume that if we
658 // got to the point where
659 // we're about to resume, and we haven't yet had to fetch the stop reason,
660 // then it doesn't need to know
661 // about the fact that we are resuming...
662 const uint32_t process_stop_id = GetProcess()->GetStopID();
663 if (m_stop_info_stop_id == process_stop_id &&
664 (m_stop_info_sp && m_stop_info_sp->IsValid())) {
665 StopInfo *stop_info = GetPrivateStopInfo().get();
666 if (stop_info)
667 stop_info->WillResume(resume_state);
668 }
669
670 // Tell all the plans that we are about to resume in case they need to clear
671 // any state.
672 // We distinguish between the plan on the top of the stack and the lower
673 // plans in case a plan needs to do any special business before it runs.
674
675 bool need_to_resume = false;
676 ThreadPlan *plan_ptr = GetCurrentPlan();
677 if (plan_ptr) {
678 need_to_resume = plan_ptr->WillResume(resume_state, true);
679
680 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
681 plan_ptr->WillResume(resume_state, false);
Jim Ingham92087d82012-01-31 23:09:20 +0000682 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684 // If the WillResume for the plan says we are faking a resume, then it will
685 // have set an appropriate stop info.
686 // In that case, don't reset it here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000687
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 if (need_to_resume && resume_state != eStateSuspended) {
689 m_stop_info_sp.reset();
Jim Ingham92087d82012-01-31 23:09:20 +0000690 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000692
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 if (need_to_resume) {
694 ClearStackFrames();
695 // Let Thread subclasses do any special work they need to prior to resuming
696 WillResume(resume_state);
697 }
698
699 return need_to_resume;
700}
701
702void Thread::DidResume() { SetResumeSignal(LLDB_INVALID_SIGNAL_NUMBER); }
703
704void Thread::DidStop() { SetState(eStateStopped); }
705
706bool Thread::ShouldStop(Event *event_ptr) {
707 ThreadPlan *current_plan = GetCurrentPlan();
708
709 bool should_stop = true;
710
711 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
712
713 if (GetResumeState() == eStateSuspended) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 log->Printf("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
716 ", should_stop = 0 (ignore since thread was suspended)",
717 __FUNCTION__, GetID(), GetProtocolID());
718 return false;
719 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000720
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 if (GetTemporaryResumeState() == eStateSuspended) {
722 if (log)
723 log->Printf("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
724 ", should_stop = 0 (ignore since thread was suspended)",
725 __FUNCTION__, GetID(), GetProtocolID());
726 return false;
727 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 // Based on the current thread plan and process stop info, check if this
730 // thread caused the process to stop. NOTE: this must take place before
731 // the plan is moved from the current plan stack to the completed plan
732 // stack.
733 if (!ThreadStoppedForAReason()) {
734 if (log)
735 log->Printf("Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
736 ", pc = 0x%16.16" PRIx64
737 ", should_stop = 0 (ignore since no stop reason)",
738 __FUNCTION__, GetID(), GetProtocolID(),
739 GetRegisterContext() ? GetRegisterContext()->GetPC()
740 : LLDB_INVALID_ADDRESS);
741 return false;
742 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 if (log) {
745 log->Printf("Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
746 ", pc = 0x%16.16" PRIx64,
747 __FUNCTION__, static_cast<void *>(this), GetID(),
748 GetProtocolID(),
749 GetRegisterContext() ? GetRegisterContext()->GetPC()
750 : LLDB_INVALID_ADDRESS);
751 log->Printf("^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
752 StreamString s;
753 s.IndentMore();
754 DumpThreadPlans(&s);
755 log->Printf("Plan stack initial state:\n%s", s.GetData());
756 }
Jim Inghambad39e42012-09-05 21:12:49 +0000757
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758 // The top most plan always gets to do the trace log...
759 current_plan->DoTraceLog();
Jim Inghambad39e42012-09-05 21:12:49 +0000760
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 // First query the stop info's ShouldStopSynchronous. This handles
762 // "synchronous" stop reasons, for example the breakpoint
763 // command on internal breakpoints. If a synchronous stop reason says we
764 // should not stop, then we don't have to
765 // do any more work on this stop.
766 StopInfoSP private_stop_info(GetPrivateStopInfo());
767 if (private_stop_info &&
768 !private_stop_info->ShouldStopSynchronous(event_ptr)) {
769 if (log)
770 log->Printf("StopInfo::ShouldStop async callback says we should not "
771 "stop, returning ShouldStop of false.");
772 return false;
773 }
774
775 // If we've already been restarted, don't query the plans since the state they
776 // would examine is not current.
777 if (Process::ProcessEventData::GetRestartedFromEvent(event_ptr))
778 return false;
779
780 // Before the plans see the state of the world, calculate the current inlined
781 // depth.
782 GetStackFrameList()->CalculateCurrentInlinedDepth();
783
784 // If the base plan doesn't understand why we stopped, then we have to find a
785 // plan that does.
786 // If that plan is still working, then we don't need to do any more work. If
787 // the plan that explains
788 // the stop is done, then we should pop all the plans below it, and pop it,
789 // and then let the plans above it decide
790 // whether they still need to do more work.
791
792 bool done_processing_current_plan = false;
793
794 if (!current_plan->PlanExplainsStop(event_ptr)) {
795 if (current_plan->TracerExplainsStop()) {
796 done_processing_current_plan = true;
797 should_stop = false;
798 } else {
799 // If the current plan doesn't explain the stop, then find one that
800 // does and let it handle the situation.
801 ThreadPlan *plan_ptr = current_plan;
802 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
803 if (plan_ptr->PlanExplainsStop(event_ptr)) {
804 should_stop = plan_ptr->ShouldStop(event_ptr);
805
806 // plan_ptr explains the stop, next check whether plan_ptr is done, if
807 // so, then we should take it
808 // and all the plans below it off the stack.
809
810 if (plan_ptr->MischiefManaged()) {
811 // We're going to pop the plans up to and including the plan that
812 // explains the stop.
813 ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);
814
815 do {
816 if (should_stop)
817 current_plan->WillStop();
818 PopPlan();
819 } while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
820 // Now, if the responsible plan was not "Okay to discard" then we're
821 // done,
822 // otherwise we forward this to the next plan in the stack below.
823 done_processing_current_plan =
824 (plan_ptr->IsMasterPlan() && !plan_ptr->OkayToDiscard());
825 } else
Jim Ingham25f66702011-12-03 01:52:59 +0000826 done_processing_current_plan = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827
828 break;
Jim Ingham25f66702011-12-03 01:52:59 +0000829 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 }
Jim Ingham25f66702011-12-03 01:52:59 +0000831 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 if (!done_processing_current_plan) {
835 bool over_ride_stop = current_plan->ShouldAutoContinue(event_ptr);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 if (log)
838 log->Printf("Plan %s explains stop, auto-continue %i.",
839 current_plan->GetName(), over_ride_stop);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 // We're starting from the base plan, so just let it decide;
842 if (PlanIsBasePlan(current_plan)) {
843 should_stop = current_plan->ShouldStop(event_ptr);
844 if (log)
845 log->Printf("Base plan says should stop: %i.", should_stop);
846 } else {
847 // Otherwise, don't let the base plan override what the other plans say to
848 // do, since
849 // presumably if there were other plans they would know what to do...
850 while (1) {
Jim Ingham0f16e732011-02-08 05:20:59 +0000851 if (PlanIsBasePlan(current_plan))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 break;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000853
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 should_stop = current_plan->ShouldStop(event_ptr);
Greg Clayton2cad65a2010-09-03 17:10:42 +0000855 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 log->Printf("Plan %s should stop: %d.", current_plan->GetName(),
857 should_stop);
858 if (current_plan->MischiefManaged()) {
859 if (should_stop)
860 current_plan->WillStop();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 // If a Master Plan wants to stop, and wants to stick on the stack, we
863 // let it.
864 // Otherwise, see if the plan's parent wants to stop.
Jim Ingham92087d82012-01-31 23:09:20 +0000865
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 if (should_stop && current_plan->IsMasterPlan() &&
867 !current_plan->OkayToDiscard()) {
868 PopPlan();
Jim Ingham2bdbfd52014-09-29 23:17:18 +0000869 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 } else {
871 PopPlan();
872
873 current_plan = GetCurrentPlan();
874 if (current_plan == nullptr) {
875 break;
876 }
877 }
878 } else {
879 break;
Jim Ingham2bdbfd52014-09-29 23:17:18 +0000880 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 }
Jim Ingham2bdbfd52014-09-29 23:17:18 +0000882 }
883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 if (over_ride_stop)
885 should_stop = false;
886 }
Jim Ingham2bdbfd52014-09-29 23:17:18 +0000887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 // One other potential problem is that we set up a master plan, then stop in
889 // before it is complete - for instance
890 // by hitting a breakpoint during a step-over - then do some step/finish/etc
891 // operations that wind up
892 // past the end point condition of the initial plan. We don't want to strand
893 // the original plan on the stack,
894 // This code clears stale plans off the stack.
895
896 if (should_stop) {
897 ThreadPlan *plan_ptr = GetCurrentPlan();
898 while (!PlanIsBasePlan(plan_ptr)) {
899 bool stale = plan_ptr->IsPlanStale();
900 ThreadPlan *examined_plan = plan_ptr;
901 plan_ptr = GetPreviousPlan(examined_plan);
902
903 if (stale) {
904 if (log)
905 log->Printf(
906 "Plan %s being discarded in cleanup, it says it is already done.",
907 examined_plan->GetName());
908 DiscardThreadPlansUpToPlan(examined_plan);
909 }
910 }
911 }
912
913 if (log) {
914 StreamString s;
915 s.IndentMore();
916 DumpThreadPlans(&s);
917 log->Printf("Plan stack final state:\n%s", s.GetData());
918 log->Printf("vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
919 should_stop);
920 }
921 return should_stop;
Jim Ingham2bdbfd52014-09-29 23:17:18 +0000922}
Jim Ingham2bdbfd52014-09-29 23:17:18 +0000923
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924Vote Thread::ShouldReportStop(Event *event_ptr) {
925 StateType thread_state = GetResumeState();
926 StateType temp_thread_state = GetTemporaryResumeState();
Jim Ingham64e7ead2012-05-03 21:19:36 +0000927
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
929
930 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
Jim Ingham399f1ca2010-11-05 19:25:48 +0000931 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
933 ": returning vote %i (state was suspended or invalid)",
934 GetID(), eVoteNoOpinion);
935 return eVoteNoOpinion;
936 }
Jim Ingham399f1ca2010-11-05 19:25:48 +0000937
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938 if (temp_thread_state == eStateSuspended ||
939 temp_thread_state == eStateInvalid) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 log->Printf(
942 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
943 ": returning vote %i (temporary state was suspended or invalid)",
944 GetID(), eVoteNoOpinion);
945 return eVoteNoOpinion;
946 }
947
948 if (!ThreadStoppedForAReason()) {
949 if (log)
950 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
951 ": returning vote %i (thread didn't stop for a reason.)",
952 GetID(), eVoteNoOpinion);
953 return eVoteNoOpinion;
954 }
955
956 if (m_completed_plan_stack.size() > 0) {
957 // Don't use GetCompletedPlan here, since that suppresses private plans.
958 if (log)
959 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
960 ": returning vote for complete stack's back plan",
961 GetID());
962 return m_completed_plan_stack.back()->ShouldReportStop(event_ptr);
963 } else {
964 Vote thread_vote = eVoteNoOpinion;
965 ThreadPlan *plan_ptr = GetCurrentPlan();
966 while (1) {
967 if (plan_ptr->PlanExplainsStop(event_ptr)) {
968 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
969 break;
970 }
971 if (PlanIsBasePlan(plan_ptr))
972 break;
973 else
974 plan_ptr = GetPreviousPlan(plan_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 if (log)
977 log->Printf("Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
978 ": returning vote %i for current plan",
979 GetID(), thread_vote);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 return thread_vote;
982 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983}
984
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985Vote Thread::ShouldReportRun(Event *event_ptr) {
986 StateType thread_state = GetResumeState();
987
988 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
989 return eVoteNoOpinion;
990 }
991
992 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
993 if (m_completed_plan_stack.size() > 0) {
994 // Don't use GetCompletedPlan here, since that suppresses private plans.
995 if (log)
996 log->Printf("Current Plan for thread %d(%p) (0x%4.4" PRIx64
997 ", %s): %s being asked whether we should report run.",
998 GetIndexID(), static_cast<void *>(this), GetID(),
999 StateAsCString(GetTemporaryResumeState()),
1000 m_completed_plan_stack.back()->GetName());
1001
1002 return m_completed_plan_stack.back()->ShouldReportRun(event_ptr);
1003 } else {
1004 if (log)
1005 log->Printf("Current Plan for thread %d(%p) (0x%4.4" PRIx64
1006 ", %s): %s being asked whether we should report run.",
1007 GetIndexID(), static_cast<void *>(this), GetID(),
1008 StateAsCString(GetTemporaryResumeState()),
1009 GetCurrentPlan()->GetName());
1010
1011 return GetCurrentPlan()->ShouldReportRun(event_ptr);
1012 }
1013}
1014
1015bool Thread::MatchesSpec(const ThreadSpec *spec) {
1016 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1017}
1018
1019void Thread::PushPlan(ThreadPlanSP &thread_plan_sp) {
1020 if (thread_plan_sp) {
1021 // If the thread plan doesn't already have a tracer, give it its parent's
1022 // tracer:
1023 if (!thread_plan_sp->GetThreadPlanTracer())
1024 thread_plan_sp->SetThreadPlanTracer(
1025 m_plan_stack.back()->GetThreadPlanTracer());
1026 m_plan_stack.push_back(thread_plan_sp);
1027
1028 thread_plan_sp->DidPush();
1029
1030 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1031 if (log) {
1032 StreamString s;
1033 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
1034 log->Printf("Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1035 static_cast<void *>(this), s.GetData(),
1036 thread_plan_sp->GetThread().GetID());
1037 }
1038 }
1039}
1040
1041void Thread::PopPlan() {
1042 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1043
1044 if (m_plan_stack.size() <= 1)
1045 return;
1046 else {
1047 ThreadPlanSP &plan = m_plan_stack.back();
1048 if (log) {
1049 log->Printf("Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1050 plan->GetName(), plan->GetThread().GetID());
1051 }
1052 m_completed_plan_stack.push_back(plan);
1053 plan->WillPop();
1054 m_plan_stack.pop_back();
1055 }
1056}
1057
1058void Thread::DiscardPlan() {
1059 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1060 if (m_plan_stack.size() > 1) {
1061 ThreadPlanSP &plan = m_plan_stack.back();
1062 if (log)
1063 log->Printf("Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1064 plan->GetName(), plan->GetThread().GetID());
1065
1066 m_discarded_plan_stack.push_back(plan);
1067 plan->WillPop();
1068 m_plan_stack.pop_back();
1069 }
1070}
1071
1072ThreadPlan *Thread::GetCurrentPlan() {
1073 // There will always be at least the base plan. If somebody is mucking with a
1074 // thread with an empty plan stack, we should assert right away.
1075 return m_plan_stack.empty() ? nullptr : m_plan_stack.back().get();
1076}
1077
1078ThreadPlanSP Thread::GetCompletedPlan() {
1079 ThreadPlanSP empty_plan_sp;
1080 if (!m_completed_plan_stack.empty()) {
1081 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1082 ThreadPlanSP completed_plan_sp;
1083 completed_plan_sp = m_completed_plan_stack[i];
1084 if (!completed_plan_sp->GetPrivate())
1085 return completed_plan_sp;
1086 }
1087 }
1088 return empty_plan_sp;
1089}
1090
1091ValueObjectSP Thread::GetReturnValueObject() {
1092 if (!m_completed_plan_stack.empty()) {
1093 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1094 ValueObjectSP return_valobj_sp;
1095 return_valobj_sp = m_completed_plan_stack[i]->GetReturnValueObject();
1096 if (return_valobj_sp)
1097 return return_valobj_sp;
1098 }
1099 }
1100 return ValueObjectSP();
1101}
1102
1103ExpressionVariableSP Thread::GetExpressionVariable() {
1104 if (!m_completed_plan_stack.empty()) {
1105 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1106 ExpressionVariableSP expression_variable_sp;
1107 expression_variable_sp =
1108 m_completed_plan_stack[i]->GetExpressionVariable();
1109 if (expression_variable_sp)
1110 return expression_variable_sp;
1111 }
1112 }
1113 return ExpressionVariableSP();
1114}
1115
1116bool Thread::IsThreadPlanDone(ThreadPlan *plan) {
1117 if (!m_completed_plan_stack.empty()) {
1118 for (int i = m_completed_plan_stack.size() - 1; i >= 0; i--) {
1119 if (m_completed_plan_stack[i].get() == plan)
Jim Inghamcf274f92012-04-09 22:37:39 +00001120 return true;
Jim Ingham93208b82013-01-31 21:46:01 +00001121 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 }
1123 return false;
Jim Ingham93208b82013-01-31 21:46:01 +00001124}
1125
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126bool Thread::WasThreadPlanDiscarded(ThreadPlan *plan) {
1127 if (!m_discarded_plan_stack.empty()) {
1128 for (int i = m_discarded_plan_stack.size() - 1; i >= 0; i--) {
1129 if (m_discarded_plan_stack[i].get() == plan)
1130 return true;
1131 }
1132 }
1133 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134}
1135
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136ThreadPlan *Thread::GetPreviousPlan(ThreadPlan *current_plan) {
1137 if (current_plan == nullptr)
1138 return nullptr;
1139
1140 int stack_size = m_completed_plan_stack.size();
1141 for (int i = stack_size - 1; i > 0; i--) {
1142 if (current_plan == m_completed_plan_stack[i].get())
1143 return m_completed_plan_stack[i - 1].get();
1144 }
1145
1146 if (stack_size > 0 && m_completed_plan_stack[0].get() == current_plan) {
1147 return GetCurrentPlan();
1148 }
1149
1150 stack_size = m_plan_stack.size();
1151 for (int i = stack_size - 1; i > 0; i--) {
1152 if (current_plan == m_plan_stack[i].get())
1153 return m_plan_stack[i - 1].get();
1154 }
1155 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001156}
1157
Kate Stoneb9c1b512016-09-06 20:57:50 +00001158void Thread::QueueThreadPlan(ThreadPlanSP &thread_plan_sp,
1159 bool abort_other_plans) {
1160 if (abort_other_plans)
1161 DiscardThreadPlans(true);
1162
1163 PushPlan(thread_plan_sp);
1164}
1165
1166void Thread::EnableTracer(bool value, bool single_stepping) {
1167 int stack_size = m_plan_stack.size();
1168 for (int i = 0; i < stack_size; i++) {
1169 if (m_plan_stack[i]->GetThreadPlanTracer()) {
1170 m_plan_stack[i]->GetThreadPlanTracer()->EnableTracing(value);
1171 m_plan_stack[i]->GetThreadPlanTracer()->EnableSingleStep(single_stepping);
1172 }
1173 }
1174}
1175
1176void Thread::SetTracer(lldb::ThreadPlanTracerSP &tracer_sp) {
1177 int stack_size = m_plan_stack.size();
1178 for (int i = 0; i < stack_size; i++)
1179 m_plan_stack[i]->SetThreadPlanTracer(tracer_sp);
1180}
1181
1182bool Thread::DiscardUserThreadPlansUpToIndex(uint32_t thread_index) {
1183 // Count the user thread plans from the back end to get the number of the one
1184 // we want
1185 // to discard:
1186
1187 uint32_t idx = 0;
1188 ThreadPlan *up_to_plan_ptr = nullptr;
1189
1190 for (ThreadPlanSP plan_sp : m_plan_stack) {
1191 if (plan_sp->GetPrivate())
1192 continue;
1193 if (idx == thread_index) {
1194 up_to_plan_ptr = plan_sp.get();
1195 break;
1196 } else
1197 idx++;
1198 }
1199
1200 if (up_to_plan_ptr == nullptr)
1201 return false;
1202
1203 DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1204 return true;
1205}
1206
1207void Thread::DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp) {
1208 DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
1209}
1210
1211void Thread::DiscardThreadPlansUpToPlan(ThreadPlan *up_to_plan_ptr) {
1212 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1213 if (log)
1214 log->Printf("Discarding thread plans for thread tid = 0x%4.4" PRIx64
1215 ", up to %p",
1216 GetID(), static_cast<void *>(up_to_plan_ptr));
1217
1218 int stack_size = m_plan_stack.size();
1219
1220 // If the input plan is nullptr, discard all plans. Otherwise make sure this
1221 // plan is in the
1222 // stack, and if so discard up to and including it.
1223
1224 if (up_to_plan_ptr == nullptr) {
1225 for (int i = stack_size - 1; i > 0; i--)
1226 DiscardPlan();
1227 } else {
1228 bool found_it = false;
1229 for (int i = stack_size - 1; i > 0; i--) {
1230 if (m_plan_stack[i].get() == up_to_plan_ptr)
1231 found_it = true;
1232 }
1233 if (found_it) {
1234 bool last_one = false;
1235 for (int i = stack_size - 1; i > 0 && !last_one; i--) {
1236 if (GetCurrentPlan() == up_to_plan_ptr)
1237 last_one = true;
1238 DiscardPlan();
1239 }
1240 }
1241 }
1242}
1243
1244void Thread::DiscardThreadPlans(bool force) {
1245 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
1246 if (log) {
1247 log->Printf("Discarding thread plans for thread (tid = 0x%4.4" PRIx64
1248 ", force %d)",
1249 GetID(), force);
1250 }
1251
1252 if (force) {
1253 int stack_size = m_plan_stack.size();
1254 for (int i = stack_size - 1; i > 0; i--) {
1255 DiscardPlan();
1256 }
1257 return;
1258 }
1259
1260 while (1) {
1261 int master_plan_idx;
1262 bool discard = true;
1263
1264 // Find the first master plan, see if it wants discarding, and if yes
1265 // discard up to it.
1266 for (master_plan_idx = m_plan_stack.size() - 1; master_plan_idx >= 0;
1267 master_plan_idx--) {
1268 if (m_plan_stack[master_plan_idx]->IsMasterPlan()) {
1269 discard = m_plan_stack[master_plan_idx]->OkayToDiscard();
1270 break;
1271 }
1272 }
1273
1274 if (discard) {
1275 // First pop all the dependent plans:
1276 for (int i = m_plan_stack.size() - 1; i > master_plan_idx; i--) {
1277 // FIXME: Do we need a finalize here, or is the rule that
1278 // "PrepareForStop"
1279 // for the plan leaves it in a state that it is safe to pop the plan
1280 // with no more notice?
1281 DiscardPlan();
1282 }
1283
1284 // Now discard the master plan itself.
1285 // The bottom-most plan never gets discarded. "OkayToDiscard" for it
1286 // means
1287 // discard it's dependent plans, but not it...
1288 if (master_plan_idx > 0) {
1289 DiscardPlan();
1290 }
1291 } else {
1292 // If the master plan doesn't want to get discarded, then we're done.
1293 break;
1294 }
1295 }
1296}
1297
1298bool Thread::PlanIsBasePlan(ThreadPlan *plan_ptr) {
1299 if (plan_ptr->IsBasePlan())
1300 return true;
1301 else if (m_plan_stack.size() == 0)
1302 return false;
1303 else
1304 return m_plan_stack[0].get() == plan_ptr;
1305}
1306
1307Error Thread::UnwindInnermostExpression() {
1308 Error error;
1309 int stack_size = m_plan_stack.size();
1310
1311 // If the input plan is nullptr, discard all plans. Otherwise make sure this
1312 // plan is in the
1313 // stack, and if so discard up to and including it.
1314
1315 for (int i = stack_size - 1; i > 0; i--) {
1316 if (m_plan_stack[i]->GetKind() == ThreadPlan::eKindCallFunction) {
1317 DiscardThreadPlansUpToPlan(m_plan_stack[i].get());
1318 return error;
1319 }
1320 }
1321 error.SetErrorString("No expressions currently active on this thread");
1322 return error;
1323}
1324
1325ThreadPlanSP Thread::QueueFundamentalPlan(bool abort_other_plans) {
1326 ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
1327 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1328 return thread_plan_sp;
1329}
1330
1331ThreadPlanSP Thread::QueueThreadPlanForStepSingleInstruction(
1332 bool step_over, bool abort_other_plans, bool stop_other_threads) {
1333 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
1334 *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1335 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1336 return thread_plan_sp;
1337}
1338
1339ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1340 bool abort_other_plans, const AddressRange &range,
1341 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1342 LazyBool step_out_avoids_code_withoug_debug_info) {
1343 ThreadPlanSP thread_plan_sp;
1344 thread_plan_sp.reset(new ThreadPlanStepOverRange(
1345 *this, range, addr_context, stop_other_threads,
1346 step_out_avoids_code_withoug_debug_info));
1347
1348 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1349 return thread_plan_sp;
Jim Inghamc6276822012-12-12 19:58:40 +00001350}
1351
Jason Molenda25d5b102015-12-15 00:40:30 +00001352// Call the QueueThreadPlanForStepOverRange method which takes an address range.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353ThreadPlanSP Thread::QueueThreadPlanForStepOverRange(
1354 bool abort_other_plans, const LineEntry &line_entry,
1355 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1356 LazyBool step_out_avoids_code_withoug_debug_info) {
1357 return QueueThreadPlanForStepOverRange(
1358 abort_other_plans, line_entry.GetSameLineContiguousAddressRange(),
1359 addr_context, stop_other_threads,
1360 step_out_avoids_code_withoug_debug_info);
Jason Molenda25d5b102015-12-15 00:40:30 +00001361}
1362
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1364 bool abort_other_plans, const AddressRange &range,
1365 const SymbolContext &addr_context, const char *step_in_target,
1366 lldb::RunMode stop_other_threads,
1367 LazyBool step_in_avoids_code_without_debug_info,
1368 LazyBool step_out_avoids_code_without_debug_info) {
1369 ThreadPlanSP thread_plan_sp(
1370 new ThreadPlanStepInRange(*this, range, addr_context, stop_other_threads,
1371 step_in_avoids_code_without_debug_info,
1372 step_out_avoids_code_without_debug_info));
1373 ThreadPlanStepInRange *plan =
1374 static_cast<ThreadPlanStepInRange *>(thread_plan_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001375
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376 if (step_in_target)
1377 plan->SetStepInTarget(step_in_target);
1378
1379 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1380 return thread_plan_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001381}
1382
Jason Molenda25d5b102015-12-15 00:40:30 +00001383// Call the QueueThreadPlanForStepInRange method which takes an address range.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384ThreadPlanSP Thread::QueueThreadPlanForStepInRange(
1385 bool abort_other_plans, const LineEntry &line_entry,
1386 const SymbolContext &addr_context, const char *step_in_target,
1387 lldb::RunMode stop_other_threads,
1388 LazyBool step_in_avoids_code_without_debug_info,
1389 LazyBool step_out_avoids_code_without_debug_info) {
1390 return QueueThreadPlanForStepInRange(
1391 abort_other_plans, line_entry.GetSameLineContiguousAddressRange(),
1392 addr_context, step_in_target, stop_other_threads,
1393 step_in_avoids_code_without_debug_info,
1394 step_out_avoids_code_without_debug_info);
Jason Molenda25d5b102015-12-15 00:40:30 +00001395}
1396
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397ThreadPlanSP Thread::QueueThreadPlanForStepOut(
1398 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1399 bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
1400 LazyBool step_out_avoids_code_without_debug_info) {
1401 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1402 *this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
1403 frame_idx, step_out_avoids_code_without_debug_info));
Jason Molenda25d5b102015-12-15 00:40:30 +00001404
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 if (thread_plan_sp->ValidatePlan(nullptr)) {
1406 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1407 return thread_plan_sp;
1408 } else {
1409 return ThreadPlanSP();
1410 }
Jim Ingham4b4b2472014-03-13 02:47:14 +00001411}
1412
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413ThreadPlanSP Thread::QueueThreadPlanForStepOutNoShouldStop(
1414 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1415 bool stop_other_threads, Vote stop_vote, Vote run_vote, uint32_t frame_idx,
1416 bool continue_to_next_branch) {
1417 const bool calculate_return_value =
1418 false; // No need to calculate the return value here.
1419 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1420 *this, addr_context, first_insn, stop_other_threads, stop_vote, run_vote,
1421 frame_idx, eLazyBoolNo, continue_to_next_branch, calculate_return_value));
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001422
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 ThreadPlanStepOut *new_plan =
1424 static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1425 new_plan->ClearShouldStopHereCallbacks();
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001426
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427 if (thread_plan_sp->ValidatePlan(nullptr)) {
1428 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1429 return thread_plan_sp;
1430 } else {
1431 return ThreadPlanSP();
1432 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001433}
1434
Kate Stoneb9c1b512016-09-06 20:57:50 +00001435ThreadPlanSP Thread::QueueThreadPlanForStepThrough(StackID &return_stack_id,
1436 bool abort_other_plans,
1437 bool stop_other_threads) {
1438 ThreadPlanSP thread_plan_sp(
1439 new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
1440 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1441 return ThreadPlanSP();
Jim Ingham25f66702011-12-03 01:52:59 +00001442
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1444 return thread_plan_sp;
1445}
1446
1447ThreadPlanSP Thread::QueueThreadPlanForRunToAddress(bool abort_other_plans,
1448 Address &target_addr,
1449 bool stop_other_threads) {
1450 ThreadPlanSP thread_plan_sp(
1451 new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
1452 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1453 return thread_plan_sp;
1454}
1455
1456ThreadPlanSP Thread::QueueThreadPlanForStepUntil(bool abort_other_plans,
1457 lldb::addr_t *address_list,
1458 size_t num_addresses,
1459 bool stop_other_threads,
1460 uint32_t frame_idx) {
1461 ThreadPlanSP thread_plan_sp(new ThreadPlanStepUntil(
1462 *this, address_list, num_addresses, stop_other_threads, frame_idx));
1463 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1464 return thread_plan_sp;
1465}
1466
1467lldb::ThreadPlanSP Thread::QueueThreadPlanForStepScripted(
1468 bool abort_other_plans, const char *class_name, bool stop_other_threads) {
1469 ThreadPlanSP thread_plan_sp(new ThreadPlanPython(*this, class_name));
1470 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1471 // This seems a little funny, but I don't want to have to split up the
1472 // constructor and the
1473 // DidPush in the scripted plan, that seems annoying.
1474 // That means the constructor has to be in DidPush.
1475 // So I have to validate the plan AFTER pushing it, and then take it off
1476 // again...
1477 if (!thread_plan_sp->ValidatePlan(nullptr)) {
1478 DiscardThreadPlansUpToPlan(thread_plan_sp);
1479 return ThreadPlanSP();
1480 } else
Jim Ingham4d56e9c2013-07-18 21:48:26 +00001481 return thread_plan_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001482}
1483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484uint32_t Thread::GetIndexID() const { return m_index_id; }
1485
1486static void PrintPlanElement(Stream *s, const ThreadPlanSP &plan,
1487 lldb::DescriptionLevel desc_level,
1488 int32_t elem_idx) {
1489 s->IndentMore();
1490 s->Indent();
1491 s->Printf("Element %d: ", elem_idx);
1492 plan->GetDescription(s, desc_level);
1493 s->EOL();
1494 s->IndentLess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001495}
1496
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497static void PrintPlanStack(Stream *s,
1498 const std::vector<lldb::ThreadPlanSP> &plan_stack,
1499 lldb::DescriptionLevel desc_level,
1500 bool include_internal) {
1501 int32_t print_idx = 0;
1502 for (ThreadPlanSP plan_sp : plan_stack) {
1503 if (include_internal || !plan_sp->GetPrivate()) {
1504 PrintPlanElement(s, plan_sp, desc_level, print_idx++);
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001505 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001506 }
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001507}
1508
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509void Thread::DumpThreadPlans(Stream *s, lldb::DescriptionLevel desc_level,
1510 bool include_internal,
1511 bool ignore_boring_threads) const {
1512 uint32_t stack_size;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001513
Kate Stoneb9c1b512016-09-06 20:57:50 +00001514 if (ignore_boring_threads) {
1515 uint32_t stack_size = m_plan_stack.size();
1516 uint32_t completed_stack_size = m_completed_plan_stack.size();
1517 uint32_t discarded_stack_size = m_discarded_plan_stack.size();
1518 if (stack_size == 1 && completed_stack_size == 0 &&
1519 discarded_stack_size == 0) {
1520 s->Printf("thread #%u: tid = 0x%4.4" PRIx64 "\n", GetIndexID(), GetID());
1521 s->IndentMore();
1522 s->Indent();
1523 s->Printf("No active thread plans\n");
1524 s->IndentLess();
1525 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001526 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527 }
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001528
Kate Stoneb9c1b512016-09-06 20:57:50 +00001529 s->Indent();
1530 s->Printf("thread #%u: tid = 0x%4.4" PRIx64 ":\n", GetIndexID(), GetID());
1531 s->IndentMore();
1532 s->Indent();
1533 s->Printf("Active plan stack:\n");
1534 PrintPlanStack(s, m_plan_stack, desc_level, include_internal);
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001535
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536 stack_size = m_completed_plan_stack.size();
1537 if (stack_size > 0) {
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001538 s->Indent();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001539 s->Printf("Completed Plan Stack:\n");
1540 PrintPlanStack(s, m_completed_plan_stack, desc_level, include_internal);
1541 }
1542
1543 stack_size = m_discarded_plan_stack.size();
1544 if (stack_size > 0) {
Jim Ingham2bdbfd52014-09-29 23:17:18 +00001545 s->Indent();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 s->Printf("Discarded Plan Stack:\n");
1547 PrintPlanStack(s, m_discarded_plan_stack, desc_level, include_internal);
1548 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001549
Kate Stoneb9c1b512016-09-06 20:57:50 +00001550 s->IndentLess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001551}
1552
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553TargetSP Thread::CalculateTarget() {
1554 TargetSP target_sp;
1555 ProcessSP process_sp(GetProcess());
1556 if (process_sp)
1557 target_sp = process_sp->CalculateTarget();
1558 return target_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001559}
1560
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561ProcessSP Thread::CalculateProcess() { return GetProcess(); }
1562
1563ThreadSP Thread::CalculateThread() { return shared_from_this(); }
1564
1565StackFrameSP Thread::CalculateStackFrame() { return StackFrameSP(); }
1566
1567void Thread::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1568 exe_ctx.SetContext(shared_from_this());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001569}
1570
Kate Stoneb9c1b512016-09-06 20:57:50 +00001571StackFrameListSP Thread::GetStackFrameList() {
1572 StackFrameListSP frame_list_sp;
1573 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1574 if (m_curr_frames_sp) {
1575 frame_list_sp = m_curr_frames_sp;
1576 } else {
1577 frame_list_sp.reset(new StackFrameList(*this, m_prev_frames_sp, true));
1578 m_curr_frames_sp = frame_list_sp;
1579 }
1580 return frame_list_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001581}
1582
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583void Thread::ClearStackFrames() {
1584 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1585
1586 Unwind *unwinder = GetUnwinder();
1587 if (unwinder)
1588 unwinder->Clear();
1589
1590 // Only store away the old "reference" StackFrameList if we got all its
1591 // frames:
1592 // FIXME: At some point we can try to splice in the frames we have fetched
1593 // into
1594 // the new frame as we make it, but let's not try that now.
1595 if (m_curr_frames_sp && m_curr_frames_sp->GetAllFramesFetched())
1596 m_prev_frames_sp.swap(m_curr_frames_sp);
1597 m_curr_frames_sp.reset();
1598
1599 m_extended_info.reset();
1600 m_extended_info_fetched = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001601}
1602
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603lldb::StackFrameSP Thread::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {
1604 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001605}
1606
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607Error Thread::ReturnFromFrameWithIndex(uint32_t frame_idx,
1608 lldb::ValueObjectSP return_value_sp,
1609 bool broadcast) {
1610 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1611 Error return_error;
1612
1613 if (!frame_sp) {
1614 return_error.SetErrorStringWithFormat(
1615 "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1616 frame_idx, GetID());
1617 }
1618
1619 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
Greg Clayton12daf9462010-08-25 00:35:26 +00001620}
1621
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622Error Thread::ReturnFromFrame(lldb::StackFrameSP frame_sp,
1623 lldb::ValueObjectSP return_value_sp,
1624 bool broadcast) {
1625 Error return_error;
Greg Clayton39d0ab32012-03-29 01:41:38 +00001626
Kate Stoneb9c1b512016-09-06 20:57:50 +00001627 if (!frame_sp) {
1628 return_error.SetErrorString("Can't return to a null frame.");
Greg Claytonabb487f2013-02-01 02:52:31 +00001629 return return_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 }
Jim Ingham44137582012-09-12 00:40:39 +00001631
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632 Thread *thread = frame_sp->GetThread().get();
1633 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1634 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1635 if (!older_frame_sp) {
1636 return_error.SetErrorString("No older frame to return to.");
1637 return return_error;
1638 }
1639
1640 if (return_value_sp) {
1641 lldb::ABISP abi = thread->GetProcess()->GetABI();
1642 if (!abi) {
1643 return_error.SetErrorString("Could not find ABI to set return value.");
1644 return return_error;
Richard Mittonf86248d2013-09-12 02:20:34 +00001645 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
Richard Mittonf86248d2013-09-12 02:20:34 +00001647
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1649 // for scalars.
1650 // Turn that back on when that works.
1651 if (/* DISABLES CODE */ (0) && sc.function != nullptr) {
1652 Type *function_type = sc.function->GetType();
1653 if (function_type) {
1654 CompilerType return_type =
1655 sc.function->GetCompilerType().GetFunctionReturnType();
1656 if (return_type) {
1657 StreamString s;
1658 return_type.DumpTypeDescription(&s);
1659 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1660 if (cast_value_sp) {
1661 cast_value_sp->SetFormat(eFormatHex);
1662 return_value_sp = cast_value_sp;
1663 }
Richard Mittonf86248d2013-09-12 02:20:34 +00001664 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665 }
Richard Mittonf86248d2013-09-12 02:20:34 +00001666 }
1667
Kate Stoneb9c1b512016-09-06 20:57:50 +00001668 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1669 if (!return_error.Success())
1670 return return_error;
1671 }
1672
1673 // Now write the return registers for the chosen frame:
1674 // Note, we can't use ReadAllRegisterValues->WriteAllRegisterValues, since the
1675 // read & write
1676 // cook their data
1677
1678 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1679 if (youngest_frame_sp) {
1680 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1681 if (reg_ctx_sp) {
1682 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1683 older_frame_sp->GetRegisterContext());
1684 if (copy_success) {
1685 thread->DiscardThreadPlans(true);
1686 thread->ClearStackFrames();
1687 if (broadcast && EventTypeHasListeners(eBroadcastBitStackChanged))
1688 BroadcastEvent(eBroadcastBitStackChanged,
1689 new ThreadEventData(this->shared_from_this()));
1690 } else {
1691 return_error.SetErrorString("Could not reset register values.");
1692 }
1693 } else {
1694 return_error.SetErrorString("Frame has no register context.");
Richard Mittonf86248d2013-09-12 02:20:34 +00001695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 } else {
1697 return_error.SetErrorString("Returned past top frame.");
1698 }
1699 return return_error;
Richard Mittonf86248d2013-09-12 02:20:34 +00001700}
1701
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1703 ExecutionContextScope *exe_scope) {
1704 for (size_t n = 0; n < list.size(); n++) {
1705 s << "\t";
1706 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1707 Address::DumpStyleSectionNameOffset);
1708 s << "\n";
1709 }
1710}
Greg Clayton1ac04c32012-02-21 00:09:25 +00001711
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712Error Thread::JumpToLine(const FileSpec &file, uint32_t line,
1713 bool can_leave_function, std::string *warnings) {
1714 ExecutionContext exe_ctx(GetStackFrameAtIndex(0));
1715 Target *target = exe_ctx.GetTargetPtr();
1716 TargetSP target_sp = exe_ctx.GetTargetSP();
1717 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1718 StackFrame *frame = exe_ctx.GetFramePtr();
1719 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1720
1721 // Find candidate locations.
1722 std::vector<Address> candidates, within_function, outside_function;
1723 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1724 within_function, outside_function);
1725
1726 // If possible, we try and stay within the current function.
1727 // Within a function, we accept multiple locations (optimized code may do
1728 // this,
1729 // there's no solution here so we do the best we can).
1730 // However if we're trying to leave the function, we don't know how to pick
1731 // the
1732 // right location, so if there's more than one then we bail.
1733 if (!within_function.empty())
1734 candidates = within_function;
1735 else if (outside_function.size() == 1 && can_leave_function)
1736 candidates = outside_function;
1737
1738 // Check if we got anything.
1739 if (candidates.empty()) {
1740 if (outside_function.empty()) {
1741 return Error("Cannot locate an address for %s:%i.",
1742 file.GetFilename().AsCString(), line);
1743 } else if (outside_function.size() == 1) {
1744 return Error("%s:%i is outside the current function.",
1745 file.GetFilename().AsCString(), line);
1746 } else {
1747 StreamString sstr;
1748 DumpAddressList(sstr, outside_function, target);
1749 return Error("%s:%i has multiple candidate locations:\n%s",
1750 file.GetFilename().AsCString(), line,
1751 sstr.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001752 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 // Accept the first location, warn about any others.
1756 Address dest = candidates[0];
1757 if (warnings && candidates.size() > 1) {
1758 StreamString sstr;
1759 sstr.Printf("%s:%i appears multiple times in this function, selecting the "
1760 "first location:\n",
1761 file.GetFilename().AsCString(), line);
1762 DumpAddressList(sstr, candidates, target);
1763 *warnings = sstr.GetString();
1764 }
1765
1766 if (!reg_ctx->SetPC(dest))
1767 return Error("Cannot change PC to target address.");
1768
1769 return Error();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001770}
1771
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx) {
1773 ExecutionContext exe_ctx(shared_from_this());
1774 Process *process = exe_ctx.GetProcessPtr();
1775 if (process == nullptr)
1776 return;
1777
1778 StackFrameSP frame_sp;
1779 SymbolContext frame_sc;
1780 if (frame_idx != LLDB_INVALID_FRAME_ID) {
1781 frame_sp = GetStackFrameAtIndex(frame_idx);
1782 if (frame_sp) {
1783 exe_ctx.SetFrameSP(frame_sp);
1784 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1785 }
1786 }
1787
1788 const FormatEntity::Entry *thread_format =
1789 exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1790 assert(thread_format);
1791
1792 FormatEntity::Format(*thread_format, strm, frame_sp ? &frame_sc : nullptr,
1793 &exe_ctx, nullptr, nullptr, false, false);
Greg Clayton99d0faf2010-11-18 23:32:35 +00001794}
Jim Inghamee8aea12010-09-08 03:14:33 +00001795
Kate Stoneb9c1b512016-09-06 20:57:50 +00001796void Thread::SettingsInitialize() {}
Jim Inghamee8aea12010-09-08 03:14:33 +00001797
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798void Thread::SettingsTerminate() {}
1799
1800lldb::addr_t Thread::GetThreadPointer() { return LLDB_INVALID_ADDRESS; }
1801
1802addr_t Thread::GetThreadLocalData(const ModuleSP module,
1803 lldb::addr_t tls_file_addr) {
1804 // The default implementation is to ask the dynamic loader for it.
1805 // This can be overridden for specific platforms.
1806 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1807 if (loader)
1808 return loader->GetThreadLocalData(module, shared_from_this(),
1809 tls_file_addr);
1810 else
Richard Mitton0a558352013-10-17 21:14:00 +00001811 return LLDB_INVALID_ADDRESS;
1812}
1813
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814bool Thread::SafeToCallFunctions() {
1815 Process *process = GetProcess().get();
1816 if (process) {
1817 SystemRuntime *runtime = process->GetSystemRuntime();
1818 if (runtime) {
1819 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
Jason Molendab4892cd2014-05-13 22:02:48 +00001820 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001821 }
1822 return true;
Jason Molendab4892cd2014-05-13 22:02:48 +00001823}
1824
Jason Molendab57e4a12013-11-04 09:33:30 +00001825lldb::StackFrameSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826Thread::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {
1827 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
Jim Inghame4284b72010-09-23 17:40:12 +00001828}
Caroline Ticeceb6b132010-10-26 03:11:13 +00001829
Kate Stoneb9c1b512016-09-06 20:57:50 +00001830const char *Thread::StopReasonAsCString(lldb::StopReason reason) {
1831 switch (reason) {
1832 case eStopReasonInvalid:
1833 return "invalid";
1834 case eStopReasonNone:
1835 return "none";
1836 case eStopReasonTrace:
1837 return "trace";
1838 case eStopReasonBreakpoint:
1839 return "breakpoint";
1840 case eStopReasonWatchpoint:
1841 return "watchpoint";
1842 case eStopReasonSignal:
1843 return "signal";
1844 case eStopReasonException:
1845 return "exception";
1846 case eStopReasonExec:
1847 return "exec";
1848 case eStopReasonPlanComplete:
1849 return "plan complete";
1850 case eStopReasonThreadExiting:
1851 return "thread exiting";
1852 case eStopReasonInstrumentation:
1853 return "instrumentation break";
1854 }
Caroline Ticeceb6b132010-10-26 03:11:13 +00001855
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856 static char unknown_state_string[64];
1857 snprintf(unknown_state_string, sizeof(unknown_state_string),
1858 "StopReason = %i", reason);
1859 return unknown_state_string;
Caroline Ticeceb6b132010-10-26 03:11:13 +00001860}
1861
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862const char *Thread::RunModeAsCString(lldb::RunMode mode) {
1863 switch (mode) {
1864 case eOnlyThisThread:
1865 return "only this thread";
1866 case eAllThreads:
1867 return "all threads";
1868 case eOnlyDuringStepping:
1869 return "only during stepping";
1870 }
Caroline Ticeceb6b132010-10-26 03:11:13 +00001871
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 static char unknown_state_string[64];
1873 snprintf(unknown_state_string, sizeof(unknown_state_string), "RunMode = %i",
1874 mode);
1875 return unknown_state_string;
Caroline Ticeceb6b132010-10-26 03:11:13 +00001876}
Jim Ingham06e827c2010-11-11 19:26:09 +00001877
Kate Stoneb9c1b512016-09-06 20:57:50 +00001878size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
1879 uint32_t num_frames, uint32_t num_frames_with_source) {
1880 ExecutionContext exe_ctx(shared_from_this());
1881 Target *target = exe_ctx.GetTargetPtr();
1882 Process *process = exe_ctx.GetProcessPtr();
1883 size_t num_frames_shown = 0;
1884 strm.Indent();
1885 bool is_selected = false;
1886 if (process) {
1887 if (process->GetThreadList().GetSelectedThread().get() == this)
1888 is_selected = true;
1889 }
1890 strm.Printf("%c ", is_selected ? '*' : ' ');
1891 if (target && target->GetDebugger().GetUseExternalEditor()) {
1892 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
1893 if (frame_sp) {
1894 SymbolContext frame_sc(
1895 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
1896 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.file) {
1897 Host::OpenFileInExternalEditor(frame_sc.line_entry.file,
1898 frame_sc.line_entry.line);
1899 }
Greg Clayton1ac04c32012-02-21 00:09:25 +00001900 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001901 }
Jim Ingham8ec10ef2013-10-18 17:38:31 +00001902
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 DumpUsingSettingsFormat(strm, start_frame);
1904
1905 if (num_frames > 0) {
1906 strm.IndentMore();
1907
1908 const bool show_frame_info = true;
1909
1910 const char *selected_frame_marker = nullptr;
1911 if (num_frames == 1 ||
1912 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
1913 strm.IndentMore();
1914 else
1915 selected_frame_marker = "* ";
1916
1917 num_frames_shown = GetStackFrameList()->GetStatus(
1918 strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
1919 selected_frame_marker);
1920 if (num_frames == 1)
1921 strm.IndentLess();
1922 strm.IndentLess();
1923 }
1924 return num_frames_shown;
Greg Clayton7260f622011-04-18 08:33:37 +00001925}
1926
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927bool Thread::GetDescription(Stream &strm, lldb::DescriptionLevel level,
1928 bool print_json_thread, bool print_json_stopinfo) {
1929 DumpUsingSettingsFormat(strm, 0);
1930 strm.Printf("\n");
Jason Molenda705b1802014-06-13 02:37:02 +00001931
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932 StructuredData::ObjectSP thread_info = GetExtendedInfo();
Chaoren Lin7c4f6c42015-04-08 21:19:12 +00001933
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934 if (print_json_thread || print_json_stopinfo) {
1935 if (thread_info && print_json_thread) {
1936 thread_info->Dump(strm);
1937 strm.Printf("\n");
Jason Molenda705b1802014-06-13 02:37:02 +00001938 }
1939
Kate Stoneb9c1b512016-09-06 20:57:50 +00001940 if (print_json_stopinfo && m_stop_info_sp) {
1941 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
1942 if (stop_info) {
1943 stop_info->Dump(strm);
1944 strm.Printf("\n");
1945 }
Jason Molenda705b1802014-06-13 02:37:02 +00001946 }
1947
1948 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 }
Jason Molenda705b1802014-06-13 02:37:02 +00001950
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951 if (thread_info) {
1952 StructuredData::ObjectSP activity =
1953 thread_info->GetObjectForDotSeparatedPath("activity");
1954 StructuredData::ObjectSP breadcrumb =
1955 thread_info->GetObjectForDotSeparatedPath("breadcrumb");
1956 StructuredData::ObjectSP messages =
1957 thread_info->GetObjectForDotSeparatedPath("trace_messages");
Greg Clayton7260f622011-04-18 08:33:37 +00001958
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959 bool printed_activity = false;
1960 if (activity &&
1961 activity->GetType() == StructuredData::Type::eTypeDictionary) {
1962 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
1963 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
1964 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
1965 if (name && name->GetType() == StructuredData::Type::eTypeString && id &&
1966 id->GetType() == StructuredData::Type::eTypeInteger) {
1967 strm.Printf(" Activity '%s', 0x%" PRIx64 "\n",
1968 name->GetAsString()->GetValue().c_str(),
1969 id->GetAsInteger()->GetValue());
1970 }
1971 printed_activity = true;
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001972 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001973 bool printed_breadcrumb = false;
1974 if (breadcrumb &&
1975 breadcrumb->GetType() == StructuredData::Type::eTypeDictionary) {
1976 if (printed_activity)
1977 strm.Printf("\n");
1978 StructuredData::Dictionary *breadcrumb_dict =
1979 breadcrumb->GetAsDictionary();
1980 StructuredData::ObjectSP breadcrumb_text =
1981 breadcrumb_dict->GetValueForKey("name");
1982 if (breadcrumb_text &&
1983 breadcrumb_text->GetType() == StructuredData::Type::eTypeString) {
1984 strm.Printf(" Current Breadcrumb: %s\n",
1985 breadcrumb_text->GetAsString()->GetValue().c_str());
1986 }
1987 printed_breadcrumb = true;
1988 }
1989 if (messages && messages->GetType() == StructuredData::Type::eTypeArray) {
1990 if (printed_breadcrumb)
1991 strm.Printf("\n");
1992 StructuredData::Array *messages_array = messages->GetAsArray();
1993 const size_t msg_count = messages_array->GetSize();
1994 if (msg_count > 0) {
1995 strm.Printf(" %zu trace messages:\n", msg_count);
1996 for (size_t i = 0; i < msg_count; i++) {
1997 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
1998 if (message &&
1999 message->GetType() == StructuredData::Type::eTypeDictionary) {
2000 StructuredData::Dictionary *message_dict =
2001 message->GetAsDictionary();
2002 StructuredData::ObjectSP message_text =
2003 message_dict->GetValueForKey("message");
2004 if (message_text &&
2005 message_text->GetType() == StructuredData::Type::eTypeString) {
2006 strm.Printf(" %s\n",
2007 message_text->GetAsString()->GetValue().c_str());
Greg Clayton1afa68e2013-04-02 20:32:37 +00002008 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002009 }
Jim Ingham5d88a062012-10-16 00:09:33 +00002010 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002011 }
Jim Ingham5d88a062012-10-16 00:09:33 +00002012 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013 }
2014
2015 return true;
Jim Ingham5d88a062012-10-16 00:09:33 +00002016}
Greg Clayton44d93782014-01-27 23:43:24 +00002017
Kate Stoneb9c1b512016-09-06 20:57:50 +00002018size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
2019 uint32_t num_frames, bool show_frame_info,
2020 uint32_t num_frames_with_source) {
2021 return GetStackFrameList()->GetStatus(
2022 strm, first_frame, num_frames, show_frame_info, num_frames_with_source);
Greg Clayton44d93782014-01-27 23:43:24 +00002023}
2024
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025Unwind *Thread::GetUnwinder() {
2026 if (!m_unwinder_ap) {
2027 const ArchSpec target_arch(CalculateTarget()->GetArchitecture());
2028 const llvm::Triple::ArchType machine = target_arch.GetMachine();
2029 switch (machine) {
2030 case llvm::Triple::x86_64:
2031 case llvm::Triple::x86:
2032 case llvm::Triple::arm:
2033 case llvm::Triple::aarch64:
2034 case llvm::Triple::thumb:
2035 case llvm::Triple::mips:
2036 case llvm::Triple::mipsel:
2037 case llvm::Triple::mips64:
2038 case llvm::Triple::mips64el:
2039 case llvm::Triple::ppc:
2040 case llvm::Triple::ppc64:
2041 case llvm::Triple::systemz:
2042 case llvm::Triple::hexagon:
2043 m_unwinder_ap.reset(new UnwindLLDB(*this));
2044 break;
2045
2046 default:
2047 if (target_arch.GetTriple().getVendor() == llvm::Triple::Apple)
2048 m_unwinder_ap.reset(new UnwindMacOSXFrameBackchain(*this));
2049 break;
Greg Clayton44d93782014-01-27 23:43:24 +00002050 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051 }
2052 return m_unwinder_ap.get();
Greg Clayton44d93782014-01-27 23:43:24 +00002053}
2054
Kate Stoneb9c1b512016-09-06 20:57:50 +00002055void Thread::Flush() {
2056 ClearStackFrames();
2057 m_reg_context_sp.reset();
2058}
Greg Clayton44d93782014-01-27 23:43:24 +00002059
Kate Stoneb9c1b512016-09-06 20:57:50 +00002060bool Thread::IsStillAtLastBreakpointHit() {
2061 // If we are currently stopped at a breakpoint, always return that stopinfo
2062 // and don't reset it.
2063 // This allows threads to maintain their breakpoint stopinfo, such as when
2064 // thread-stepping in
2065 // multithreaded programs.
2066 if (m_stop_info_sp) {
2067 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2068 if (stop_reason == lldb::eStopReasonBreakpoint) {
2069 uint64_t value = m_stop_info_sp->GetValue();
2070 lldb::RegisterContextSP reg_ctx_sp(GetRegisterContext());
2071 if (reg_ctx_sp) {
2072 lldb::addr_t pc = reg_ctx_sp->GetPC();
2073 BreakpointSiteSP bp_site_sp =
2074 GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2075 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
2076 return true;
2077 }
Greg Clayton44d93782014-01-27 23:43:24 +00002078 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 }
2080 return false;
2081}
2082
2083Error Thread::StepIn(bool source_step,
2084 LazyBool step_in_avoids_code_without_debug_info,
2085 LazyBool step_out_avoids_code_without_debug_info)
2086
2087{
2088 Error error;
2089 Process *process = GetProcess().get();
2090 if (StateIsStoppedState(process->GetState(), true)) {
2091 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2092 ThreadPlanSP new_plan_sp;
2093 const lldb::RunMode run_mode = eOnlyThisThread;
2094 const bool abort_other_plans = false;
2095
2096 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2097 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2098 new_plan_sp = QueueThreadPlanForStepInRange(
2099 abort_other_plans, sc.line_entry, sc, nullptr, run_mode,
2100 step_in_avoids_code_without_debug_info,
2101 step_out_avoids_code_without_debug_info);
2102 } else {
2103 new_plan_sp = QueueThreadPlanForStepSingleInstruction(
2104 false, abort_other_plans, run_mode);
Greg Clayton44d93782014-01-27 23:43:24 +00002105 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106
2107 new_plan_sp->SetIsMasterPlan(true);
2108 new_plan_sp->SetOkayToDiscard(false);
2109
2110 // Why do we need to set the current thread by ID here???
2111 process->GetThreadList().SetSelectedThreadByID(GetID());
2112 error = process->Resume();
2113 } else {
2114 error.SetErrorString("process not stopped");
2115 }
2116 return error;
2117}
2118
2119Error Thread::StepOver(bool source_step,
2120 LazyBool step_out_avoids_code_without_debug_info) {
2121 Error error;
2122 Process *process = GetProcess().get();
2123 if (StateIsStoppedState(process->GetState(), true)) {
2124 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2125 ThreadPlanSP new_plan_sp;
2126
2127 const lldb::RunMode run_mode = eOnlyThisThread;
2128 const bool abort_other_plans = false;
2129
2130 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2131 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2132 new_plan_sp = QueueThreadPlanForStepOverRange(
2133 abort_other_plans, sc.line_entry, sc, run_mode,
2134 step_out_avoids_code_without_debug_info);
2135 } else {
2136 new_plan_sp = QueueThreadPlanForStepSingleInstruction(
2137 true, abort_other_plans, run_mode);
2138 }
2139
2140 new_plan_sp->SetIsMasterPlan(true);
2141 new_plan_sp->SetOkayToDiscard(false);
2142
2143 // Why do we need to set the current thread by ID here???
2144 process->GetThreadList().SetSelectedThreadByID(GetID());
2145 error = process->Resume();
2146 } else {
2147 error.SetErrorString("process not stopped");
2148 }
2149 return error;
2150}
2151
2152Error Thread::StepOut() {
2153 Error error;
2154 Process *process = GetProcess().get();
2155 if (StateIsStoppedState(process->GetState(), true)) {
2156 const bool first_instruction = false;
2157 const bool stop_other_threads = false;
2158 const bool abort_other_plans = false;
2159
2160 ThreadPlanSP new_plan_sp(QueueThreadPlanForStepOut(
2161 abort_other_plans, nullptr, first_instruction, stop_other_threads,
2162 eVoteYes, eVoteNoOpinion, 0));
2163
2164 new_plan_sp->SetIsMasterPlan(true);
2165 new_plan_sp->SetOkayToDiscard(false);
2166
2167 // Why do we need to set the current thread by ID here???
2168 process->GetThreadList().SetSelectedThreadByID(GetID());
2169 error = process->Resume();
2170 } else {
2171 error.SetErrorString("process not stopped");
2172 }
2173 return error;
Jim Ingham4b4b2472014-03-13 02:47:14 +00002174}