LLDB mainline
ScriptedThread.cpp
Go to the documentation of this file.
1//===-- ScriptedThread.cpp ------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ScriptedThread.h"
10#include "ScriptedFrame.h"
11
14#include "lldb/Core/Debugger.h"
16#include "lldb/Target/Process.h"
19#include "lldb/Target/Unwind.h"
22#include <memory>
23#include <optional>
24
25using namespace lldb;
26using namespace lldb_private;
27
29 lldbassert(m_script_object_sp && "Invalid Script Object.");
30 lldbassert(GetInterface() && "Invalid Scripted Thread Interface.");
31}
32
33llvm::Expected<std::shared_ptr<ScriptedThread>>
35 StructuredData::Generic *script_object) {
36 if (!process.IsValid())
37 return llvm::createStringError(llvm::inconvertibleErrorCode(),
38 "Invalid scripted process.");
39
40 process.CheckScriptedInterface();
41
42 auto scripted_thread_interface =
44 if (!scripted_thread_interface)
45 return llvm::createStringError(
46 llvm::inconvertibleErrorCode(),
47 "Failed to create scripted thread interface.");
48
49 llvm::StringRef thread_class_name;
50 if (!script_object) {
51 std::optional<std::string> class_name =
53 if (!class_name || class_name->empty())
54 return llvm::createStringError(
55 llvm::inconvertibleErrorCode(),
56 "Failed to get scripted thread class name.");
57 thread_class_name = *class_name;
58 }
59
60 ExecutionContext exe_ctx(process);
61 // The legacy thread-spawn path (no script_object) needs to instantiate a
62 // *thread* Python class whose name comes from the process plugin, not the
63 // process's own class name. Build a thread-specific metadata for that case;
64 // when script_object is non-null the class name is unused so we just forward
65 // the process's metadata.
66 ScriptedMetadata thread_metadata =
67 script_object ? process.m_scripted_metadata
68 : ScriptedMetadata(thread_class_name,
70 auto obj_or_err = scripted_thread_interface->CreatePluginObject(
71 thread_metadata, exe_ctx, script_object);
72
73 if (!obj_or_err)
74 return obj_or_err.takeError();
75
76 StructuredData::GenericSP owned_script_object_sp = *obj_or_err;
77
78 if (!owned_script_object_sp->IsValid())
79 return llvm::createStringError(llvm::inconvertibleErrorCode(),
80 "Created script object is invalid.");
81
82 lldb::tid_t tid = scripted_thread_interface->GetThreadID();
83
84 return std::make_shared<ScriptedThread>(process, scripted_thread_interface,
85 tid, owned_script_object_sp);
86}
87
89 ScriptedThreadInterfaceSP interface_sp,
90 lldb::tid_t tid,
91 StructuredData::GenericSP script_object_sp)
92 : Thread(process, tid), m_scripted_process(process),
94 m_script_object_sp(script_object_sp) {}
95
97
100 std::optional<std::string> thread_name = GetInterface()->GetName();
101 if (!thread_name)
102 return nullptr;
103 return ConstString(*thread_name).AsCString(nullptr);
104}
105
108 std::optional<std::string> queue_name = GetInterface()->GetQueue();
109 if (!queue_name)
110 return nullptr;
111 return ConstString(*queue_name).AsCString(nullptr);
112}
113
115
117
123
126 const uint32_t concrete_frame_idx =
127 frame ? frame->GetConcreteFrameIndex() : 0;
128
129 if (concrete_frame_idx)
131
132 lldb::RegisterContextSP reg_ctx_sp;
134
135 std::optional<std::string> reg_data = GetInterface()->GetRegisterContext();
136 if (!reg_data)
138 LLVM_PRETTY_FUNCTION, "Failed to get scripted thread registers data.",
140
141 DataBufferSP data_sp(
142 std::make_shared<DataBufferHeap>(reg_data->c_str(), reg_data->size()));
143
144 if (!data_sp->GetByteSize())
146 LLVM_PRETTY_FUNCTION, "Failed to copy raw registers data.", error,
148
149 std::shared_ptr<RegisterContextMemory> reg_ctx_memory =
150 std::make_shared<RegisterContextMemory>(
152 if (!reg_ctx_memory)
154 LLVM_PRETTY_FUNCTION, "Failed to create a register context.", error,
156
157 reg_ctx_memory->SetAllRegisterData(data_sp);
158 m_reg_context_sp = reg_ctx_memory;
159
160 return m_reg_context_sp;
161}
162
164 StructuredData::ArraySP arr_sp = GetInterface()->GetStackFrames();
165
167 if (!arr_sp)
169 LLVM_PRETTY_FUNCTION, "Failed to get scripted thread stackframes.",
171
172 size_t arr_size = arr_sp->GetSize();
173 if (!arr_size)
175 LLVM_PRETTY_FUNCTION, "StackFrame array is empty.", error,
177
178 if (arr_size > std::numeric_limits<uint32_t>::max())
180 LLVM_PRETTY_FUNCTION,
181 llvm::Twine(
182 "StackFrame array size (" + llvm::Twine(arr_size) +
183 ") is greater than maximum authorized for a StackFrameList.")
184 .str(),
186
187 auto create_frame_from_dict =
188 [this, arr_sp](size_t idx,
189 uint32_t frame_list_idx) -> llvm::Expected<StackFrameSP> {
191 std::optional<StructuredData::Dictionary *> maybe_dict =
192 arr_sp->GetItemAtIndexAsDictionary(idx);
193 if (!maybe_dict) {
195 LLVM_PRETTY_FUNCTION,
196 llvm::Twine(
197 "Couldn't get artificial stackframe dictionary at index (" +
198 llvm::Twine(idx) + llvm::Twine(") from stackframe array."))
199 .str(),
201 return error.ToError();
202 }
203 StructuredData::Dictionary *dict = *maybe_dict;
204
206 if (!dict->GetValueForKeyAsInteger("pc", pc)) {
208 LLVM_PRETTY_FUNCTION,
209 "Couldn't find value for key 'pc' in stackframe dictionary.", error,
211 return error.ToError();
212 }
213
214 Address symbol_addr;
215 symbol_addr.SetLoadAddress(pc, &this->GetProcess()->GetTarget());
216
218 bool cfa_is_valid = false;
219 const bool artificial = false;
220 const bool behaves_like_zeroth_frame = (frame_list_idx == 0);
221 SymbolContext sc;
222 symbol_addr.CalculateSymbolContext(&sc);
223
224 return std::make_shared<StackFrame>(shared_from_this(), frame_list_idx, idx,
225 cfa, cfa_is_valid, pc,
226 StackFrame::Kind::Synthetic, artificial,
227 behaves_like_zeroth_frame, &sc);
228 };
229
230 auto create_frame_from_script_object =
231 [this, arr_sp](size_t idx) -> llvm::Expected<StackFrameSP> {
233 StructuredData::ObjectSP object_sp = arr_sp->GetItemAtIndex(idx);
234 if (!object_sp || !object_sp->GetAsGeneric()) {
236 LLVM_PRETTY_FUNCTION,
237 llvm::Twine("Couldn't get artificial stackframe object at index (" +
238 llvm::Twine(idx) +
239 llvm::Twine(") from stackframe array."))
240 .str(),
242 return error.ToError();
243 }
244
245 auto frame_or_error = ScriptedFrame::Create(
246 shared_from_this(), GetInterface(), nullptr, object_sp->GetAsGeneric());
247
248 if (!frame_or_error) {
250 LLVM_PRETTY_FUNCTION, toString(frame_or_error.takeError()), error);
251 return error.ToError();
252 }
253
254 StackFrameSP frame_sp = frame_or_error.get();
255 lldbassert(frame_sp && "Couldn't initialize scripted frame.");
256
257 return frame_sp;
258 };
259
261 uint32_t frame_list_idx = 0;
262
263 for (size_t idx = 0; idx < arr_size; idx++) {
264 StackFrameSP synth_frame_sp = nullptr;
265
266 auto frame_from_dict_or_err = create_frame_from_dict(idx, frame_list_idx);
267 if (!frame_from_dict_or_err) {
268 auto frame_from_script_obj_or_err = create_frame_from_script_object(idx);
269
270 if (!frame_from_script_obj_or_err) {
271 llvm::consumeError(frame_from_dict_or_err.takeError());
273 llvm::formatv(
274 "couldn't add artificial frame ({0}) to ScriptedThread "
275 "StackFrameList: {1}",
276 idx, llvm::toString(frame_from_script_obj_or_err.takeError()))
277 .str(),
278 GetProcess()->GetTarget().GetDebugger().GetID());
279 return false;
280 } else {
281 llvm::consumeError(frame_from_dict_or_err.takeError());
282 synth_frame_sp = *frame_from_script_obj_or_err;
283 }
284 } else {
285 synth_frame_sp = *frame_from_dict_or_err;
286 }
287
288 if (!frames->SetFrameAtIndex(frame_list_idx, synth_frame_sp))
290 LLVM_PRETTY_FUNCTION,
291 llvm::Twine("Couldn't add frame (" + llvm::Twine(idx) +
292 llvm::Twine(") to ScriptedThread StackFrameList."))
293 .str(),
295 frame_list_idx++;
296
297 // Synthesize inline frames, mirroring StackFrameList::FetchFramesUpTo().
298 frame_list_idx += frames->SynthesizeInlineFrames(
299 synth_frame_sp, /*cfa=*/LLDB_INVALID_ADDRESS);
300 }
301
302 // Mark the stack as fully unwound so the regular unwinder doesn't try to
303 // extend it beyond the artificial frames (e.g. by reading lr/fp from the
304 // register context).
305 frames->SetAllFramesFetched();
306
307 return true;
308}
309
311 StructuredData::DictionarySP dict_sp = GetInterface()->GetStopReason();
312
314 if (!dict_sp)
316 LLVM_PRETTY_FUNCTION, "Failed to get scripted thread stop info.", error,
318
319 // If we're at a BreakpointSite, mark that we stopped there and
320 // need to hit the breakpoint when we resume. This will be cleared
321 // if we CreateStopReasonWithBreakpointSiteID.
322 if (RegisterContextSP reg_ctx_sp = GetRegisterContext()) {
323 addr_t pc = reg_ctx_sp->GetPC();
324 ProcessSP proc = GetProcess();
325 if (BreakpointSiteSP bp_site_sp =
326 proc->GetBreakpointSiteList().FindByAddress(pc))
327 if (proc->IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
329 }
330
331 lldb::StopInfoSP stop_info_sp;
332 lldb::StopReason stop_reason_type;
333
334 if (!dict_sp->GetValueForKeyAsInteger("type", stop_reason_type))
336 LLVM_PRETTY_FUNCTION,
337 "Couldn't find value for key 'type' in stop reason dictionary.", error,
339
341 if (!dict_sp->GetValueForKeyAsDictionary("data", data_dict))
343 LLVM_PRETTY_FUNCTION,
344 "Couldn't find value for key 'data' in stop reason dictionary.", error,
346
347 switch (stop_reason_type) {
349 return true;
351 lldb::break_id_t break_id;
352 data_dict->GetValueForKeyAsInteger("break_id", break_id,
354 stop_info_sp =
356 } break;
358 uint32_t signal;
359 llvm::StringRef description;
360 if (!data_dict->GetValueForKeyAsInteger("signal", signal)) {
362 return false;
363 }
364 data_dict->GetValueForKeyAsString("desc", description);
365 stop_info_sp =
366 StopInfo::CreateStopReasonWithSignal(*this, signal, description.data());
367 } break;
369 stop_info_sp = StopInfo::CreateStopReasonToTrace(*this);
370 } break;
372#if defined(__APPLE__)
373 StructuredData::Dictionary *mach_exception;
374 if (data_dict->GetValueForKeyAsDictionary("mach_exception",
375 mach_exception)) {
376 llvm::StringRef value;
377 mach_exception->GetValueForKeyAsString("type", value);
378 auto exc_type =
379 StopInfoMachException::MachException::ExceptionCode(value.data());
380
381 if (!exc_type)
382 return false;
383
384 uint32_t exc_data_size = 0;
385 llvm::SmallVector<uint64_t, 3> raw_codes;
386
387 StructuredData::Array *exc_rawcodes;
388 mach_exception->GetValueForKeyAsArray("rawCodes", exc_rawcodes);
389 if (exc_rawcodes) {
390 auto fetch_data = [&raw_codes](StructuredData::Object *obj) {
391 if (!obj)
392 return false;
393 raw_codes.push_back(obj->GetUnsignedIntegerValue());
394 return true;
395 };
396
397 exc_rawcodes->ForEach(fetch_data);
398 exc_data_size = raw_codes.size();
399 }
400
402 *this, *exc_type, exc_data_size,
403 exc_data_size >= 1 ? raw_codes[0] : 0,
404 exc_data_size >= 2 ? raw_codes[1] : 0,
405 exc_data_size >= 3 ? raw_codes[2] : 0);
406
407 break;
408 }
409#endif
410 stop_info_sp =
411 StopInfo::CreateStopReasonWithException(*this, "EXC_BAD_ACCESS");
412 } break;
413 default:
415 LLVM_PRETTY_FUNCTION,
416 llvm::Twine("Unsupported stop reason type (" +
417 llvm::Twine(stop_reason_type) + llvm::Twine(")."))
418 .str(),
420 }
421
422 if (!stop_info_sp)
423 return false;
424
425 SetStopInfo(stop_info_sp);
426 return true;
427}
428
430 GetRegisterContext()->InvalidateIfNeeded(/*force=*/false);
432}
433
437
438std::shared_ptr<DynamicRegisterInfo> ScriptedThread::GetDynamicRegisterInfo() {
440
441 if (!m_register_info_sp) {
442 StructuredData::DictionarySP reg_info = GetInterface()->GetRegisterInfo();
443
445 if (!reg_info)
447 std::shared_ptr<DynamicRegisterInfo>>(
448 LLVM_PRETTY_FUNCTION, "Failed to get scripted thread registers info.",
450
452 *reg_info, m_scripted_process.GetTarget().GetArchitecture());
453 }
454
455 return m_register_info_sp;
456}
457
460
462 StructuredData::ArraySP extended_info_sp = GetInterface()->GetExtendedInfo();
463
464 if (!extended_info_sp || !extended_info_sp->GetSize())
466 LLVM_PRETTY_FUNCTION, "No extended information found", error);
467
468 return extended_info_sp;
469}
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
A section + offset based address class.
Definition Address.h:62
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition Address.cpp:1028
uint32_t CalculateSymbolContext(SymbolContext *sc, lldb::SymbolContextItem resolve_scope=lldb::eSymbolContextEverything) const
Reconstruct a symbol context from an address.
Definition Address.cpp:819
A uniqued constant string class.
Definition ConstString.h:40
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
static std::unique_ptr< DynamicRegisterInfo > Create(const StructuredData::Dictionary &dict, const ArchSpec &arch)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
bool IsValid() const
Return whether this object is valid (i.e.
Definition Process.h:578
static llvm::Expected< std::shared_ptr< ScriptedFrame > > Create(lldb::ThreadSP thread_sp, lldb::ScriptedThreadInterfaceSP scripted_thread_interface_sp, StructuredData::DictionarySP args_sp, StructuredData::Generic *script_object=nullptr)
Create a ScriptedFrame from a object instanciated in the script interpreter.
static Ret ErrorWithMessage(llvm::StringRef caller_name, llvm::StringRef user_msg, Status &error, LLDBLog log_category=LLDBLog::Process)
StructuredData::DictionarySP GetArgsSP() const
virtual lldb::ScriptedThreadInterfaceSP CreateScriptedThreadInterface()
virtual std::optional< std::string > GetScriptedThreadPluginName()
const ScriptedMetadata m_scripted_metadata
ScriptedProcessInterface & GetInterface() const
void CheckInterpreterAndScriptObject() const
std::shared_ptr< DynamicRegisterInfo > GetDynamicRegisterInfo()
lldb_private::StructuredData::GenericSP m_script_object_sp
const char * GetQueueName() override
Retrieve the Queue name for the queue currently using this Thread.
lldb::RegisterContextSP CreateRegisterContextForFrame(lldb_private::StackFrame *frame) override
std::shared_ptr< DynamicRegisterInfo > m_register_info_sp
lldb::ScriptedThreadInterfaceSP GetInterface() const
StructuredData::ObjectSP FetchThreadExtendedInfo() override
lldb::ScriptedThreadInterfaceSP m_scripted_thread_interface_sp
static llvm::Expected< std::shared_ptr< ScriptedThread > > Create(ScriptedProcess &process, StructuredData::Generic *script_object=nullptr)
void WillResume(lldb::StateType resume_state) override
ScriptedThread(ScriptedProcess &process, lldb::ScriptedThreadInterfaceSP interface_sp, lldb::tid_t tid, StructuredData::GenericSP script_object_sp=nullptr)
const char * GetName() override
bool CalculateStopInfo() override
Ask the thread subclass to set its stop info.
const ScriptedProcess & m_scripted_process
lldb::RegisterContextSP GetRegisterContext() override
virtual uint32_t GetConcreteFrameIndex()
Query this frame to find what frame it is in this Thread's StackFrameList, not counting inlined frame...
Definition StackFrame.h:486
@ Synthetic
An synthetic stack frame (e.g.
Definition StackFrame.h:72
An error handling class.
Definition Status.h:118
static lldb::StopInfoSP CreateStopReasonWithMachException(Thread &thread, uint32_t exc_type, uint32_t exc_data_count, uint64_t exc_code, uint64_t exc_sub_code, uint64_t exc_sub_sub_code, bool pc_already_adjusted=true, bool adjust_pc_if_needed=false)
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread)
static lldb::StopInfoSP CreateStopReasonWithSignal(Thread &thread, int signo, const char *description=nullptr, std::optional< int > code=std::nullopt)
static lldb::StopInfoSP CreateStopReasonWithException(Thread &thread, const char *description)
static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID(Thread &thread, lldb::break_id_t break_id)
bool ForEach(std::function< bool(Object *object)> const &foreach_callback) const
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
bool GetValueForKeyAsArray(llvm::StringRef key, Array *&result) const
bool GetValueForKeyAsDictionary(llvm::StringRef key, Dictionary *&result) const
std::shared_ptr< Generic > GenericSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
Defines a symbol context baton that can be handed other debug core functions.
void SetStopInfo(const lldb::StopInfoSP &stop_info_sp)
Definition Thread.cpp:479
virtual void DestroyThread()
Definition Thread.cpp:259
virtual void ClearStackFrames()
Definition Thread.cpp:1753
virtual Unwind & GetUnwinder()
Definition Thread.cpp:2256
Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id=false)
Constructor.
Definition Thread.cpp:226
void SetThreadStoppedAtUnexecutedBP(lldb::addr_t pc)
When a thread stops at an enabled BreakpointSite that has not executed, the Process plugin should cal...
Definition Thread.h:403
lldb::ProcessSP GetProcess() const
Definition Thread.h:162
friend class StackFrame
Definition Thread.h:1371
lldb::StackFrameListSP GetStackFrameList()
Definition Thread.cpp:1499
lldb::RegisterContextSP m_reg_context_sp
The register context for this thread's current register state.
Definition Thread.h:1436
lldb::RegisterContextSP CreateRegisterContextForFrame(StackFrame *frame)
Definition Unwind.h:56
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
StateType
Process and Thread States.
int32_t break_id_t
Definition lldb-types.h:87
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::ScriptedThreadInterface > ScriptedThreadInterfaceSP
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
StopReason
Thread stop reasons.
@ eStopReasonBreakpoint
@ eStopReasonException
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47