LLDB mainline
OperatingSystemPython.cpp
Go to the documentation of this file.
1//===-- OperatingSystemPython.cpp -----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Host/Config.h"
10
11#if LLDB_ENABLE_PYTHON
12
14
18#include "lldb/Core/Debugger.h"
19#include "lldb/Core/Module.h"
25#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
28#include "lldb/Target/Thread.h"
36
37#include <memory>
38
39using namespace lldb;
40using namespace lldb_private;
41
42LLDB_PLUGIN_DEFINE(OperatingSystemPython)
43
44void OperatingSystemPython::Initialize() {
45 PluginManager::RegisterPlugin(GetPluginNameStatic(),
46 GetPluginDescriptionStatic(), CreateInstance,
47 nullptr);
48}
49
50void OperatingSystemPython::Terminate() {
51 PluginManager::UnregisterPlugin(CreateInstance);
52}
53
54OperatingSystem *OperatingSystemPython::CreateInstance(Process *process,
55 bool force) {
56 // Python OperatingSystem plug-ins must be requested by name, so force must
57 // be true
58 FileSpec python_os_plugin_spec(process->GetPythonOSPluginPath());
59 if (python_os_plugin_spec &&
60 FileSystem::Instance().Exists(python_os_plugin_spec)) {
61 std::unique_ptr<OperatingSystemPython> os_up(
62 new OperatingSystemPython(process, python_os_plugin_spec));
63 if (os_up.get() && os_up->IsValid())
64 return os_up.release();
65 }
66 return nullptr;
67}
68
69llvm::StringRef OperatingSystemPython::GetPluginDescriptionStatic() {
70 return "Operating system plug-in that gathers OS information from a python "
71 "class that implements the necessary OperatingSystem functionality.";
72}
73
74OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process,
75 const FileSpec &python_module_path)
76 : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_up(),
77 m_interpreter(nullptr), m_script_object_sp() {
78 if (!process)
79 return;
80 TargetSP target_sp = process->CalculateTarget();
81 if (!target_sp)
82 return;
83 m_interpreter = target_sp->GetDebugger().GetScriptInterpreter();
84 if (!m_interpreter)
85 return;
86
87 std::string os_plugin_class_name(
88 python_module_path.GetFilename().AsCString(""));
89 if (os_plugin_class_name.empty())
90 return;
91
92 LoadScriptOptions options;
93 char python_module_path_cstr[PATH_MAX];
94 python_module_path.GetPath(python_module_path_cstr,
95 sizeof(python_module_path_cstr));
97 if (!m_interpreter->LoadScriptingModule(python_module_path_cstr, options,
98 error))
99 return;
100
101 // Strip the ".py" extension if there is one
102 size_t py_extension_pos = os_plugin_class_name.rfind(".py");
103 if (py_extension_pos != std::string::npos)
104 os_plugin_class_name.erase(py_extension_pos);
105 // Add ".OperatingSystemPlugIn" to the module name to get a string like
106 // "modulename.OperatingSystemPlugIn"
107 os_plugin_class_name += ".OperatingSystemPlugIn";
108
109 auto operating_system_interface =
110 m_interpreter->CreateOperatingSystemInterface();
111 if (!operating_system_interface)
112 // FIXME: We should pass an Status& to raise the error to the user.
113 // return llvm::createStringError(
114 // llvm::inconvertibleErrorCode(),
115 // "Failed to create scripted thread interface.");
116 return;
117
118 ExecutionContext exe_ctx(process);
119 ScriptedMetadata scripted_metadata(os_plugin_class_name, nullptr);
120 auto obj_or_err = operating_system_interface->CreatePluginObject(
121 scripted_metadata, exe_ctx, nullptr);
122
123 if (!obj_or_err) {
124 llvm::consumeError(obj_or_err.takeError());
125 return;
126 }
127
128 StructuredData::GenericSP owned_script_object_sp = *obj_or_err;
129 if (!owned_script_object_sp->IsValid())
130 // return llvm::createStringError(llvm::inconvertibleErrorCode(),
131 // "Created script object is invalid.");
132 return;
133
134 m_script_object_sp = owned_script_object_sp;
135 m_operating_system_interface_sp = operating_system_interface;
136}
137
138OperatingSystemPython::~OperatingSystemPython() = default;
139
140DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() {
141 if (m_register_info_up == nullptr) {
142 if (!m_interpreter || !m_operating_system_interface_sp)
143 return nullptr;
144 Log *log = GetLog(LLDBLog::OS);
145
146 LLDB_LOGF(log,
147 "OperatingSystemPython::GetDynamicRegisterInfo() fetching "
148 "thread register definitions from python for pid %" PRIu64,
149 m_process->GetID());
150
152 m_operating_system_interface_sp->GetRegisterInfo();
153 if (!dictionary)
154 return nullptr;
155
156 m_register_info_up = DynamicRegisterInfo::Create(
157 *dictionary, m_process->GetTarget().GetArchitecture());
158 assert(m_register_info_up);
159 assert(m_register_info_up->GetNumRegisters() > 0);
160 assert(m_register_info_up->GetNumRegisterSets() > 0);
161 }
162 return m_register_info_up.get();
163}
164
165bool OperatingSystemPython::UpdateThreadList(ThreadList &old_thread_list,
166 ThreadList &core_thread_list,
167 ThreadList &new_thread_list) {
168 if (!m_interpreter || !m_operating_system_interface_sp)
169 return false;
170
171 Log *log = GetLog(LLDBLog::OS);
172
173 LLDB_LOGF(log,
174 "OperatingSystemPython::UpdateThreadList() fetching thread "
175 "data from python for pid %" PRIu64,
176 m_process->GetID());
177
178 // The threads that are in "core_thread_list" upon entry are the threads from
179 // the lldb_private::Process subclass, no memory threads will be in this
180 // list.
181 StructuredData::ArraySP threads_list =
182 m_operating_system_interface_sp->GetThreadInfo();
183
184 const uint32_t num_cores = core_thread_list.GetSize(false);
185
186 // Make a map so we can keep track of which cores were used from the
187 // core_thread list. Any real threads/cores that weren't used should later be
188 // put back into the "new_thread_list".
189 std::vector<bool> core_used_map(num_cores, false);
190 if (threads_list) {
191 if (log) {
192 StreamString strm;
193 threads_list->Dump(strm);
194 LLDB_LOGF(log, "threads_list = %s", strm.GetData());
195 }
196
197 const uint32_t num_threads = threads_list->GetSize();
198 for (uint32_t i = 0; i < num_threads; ++i) {
199 StructuredData::ObjectSP thread_dict_obj =
200 threads_list->GetItemAtIndex(i);
201 if (auto thread_dict = thread_dict_obj->GetAsDictionary()) {
202 ThreadSP thread_sp(CreateThreadFromThreadInfo(
203 *thread_dict, core_thread_list, old_thread_list, core_used_map,
204 nullptr));
205 if (thread_sp)
206 new_thread_list.AddThread(thread_sp);
207 }
208 }
209 }
210
211 // Any real core threads that didn't end up backing a memory thread should
212 // still be in the main thread list, and they should be inserted at the
213 // beginning of the list
214 uint32_t insert_idx = 0;
215 for (uint32_t core_idx = 0; core_idx < num_cores; ++core_idx) {
216 if (!core_used_map[core_idx]) {
217 new_thread_list.InsertThread(
218 core_thread_list.GetThreadAtIndex(core_idx, false), insert_idx);
219 ++insert_idx;
220 }
221 }
222
223 return new_thread_list.GetSize(false) > 0;
224}
225
226ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo(
227 StructuredData::Dictionary &thread_dict, ThreadList &core_thread_list,
228 ThreadList &old_thread_list, std::vector<bool> &core_used_map,
229 bool *did_create_ptr) {
230 ThreadSP thread_sp;
232 if (!thread_dict.GetValueForKeyAsInteger("tid", tid))
233 return ThreadSP();
234
235 uint32_t core_number;
236 addr_t reg_data_addr;
237 llvm::StringRef name;
238 llvm::StringRef queue;
239
240 thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX);
241 thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr,
243 thread_dict.GetValueForKeyAsString("name", name);
244 thread_dict.GetValueForKeyAsString("queue", queue);
245
246 // See if a thread already exists for "tid"
247 thread_sp = old_thread_list.FindThreadByID(tid, false);
248 if (thread_sp) {
249 // A thread already does exist for "tid", make sure it was an operating
250 // system
251 // plug-in generated thread.
252 if (!IsOperatingSystemPluginThread(thread_sp)) {
253 // We have thread ID overlap between the protocol threads and the
254 // operating system threads, clear the thread so we create an operating
255 // system thread for this.
256 thread_sp.reset();
257 }
258 }
259
260 if (!thread_sp) {
261 if (did_create_ptr)
262 *did_create_ptr = true;
263 thread_sp = std::make_shared<ThreadMemoryProvidingNameAndQueue>(
264 *m_process, tid, name, queue, reg_data_addr);
265 }
266
267 if (core_number < core_thread_list.GetSize(false)) {
268 ThreadSP core_thread_sp(
269 core_thread_list.GetThreadAtIndex(core_number, false));
270 if (core_thread_sp) {
271 // Keep track of which cores were set as the backing thread for memory
272 // threads...
273 if (core_number < core_used_map.size())
274 core_used_map[core_number] = true;
275
276 ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread());
277 if (backing_core_thread_sp) {
278 thread_sp->SetBackingThread(backing_core_thread_sp);
279 } else {
280 thread_sp->SetBackingThread(core_thread_sp);
281 }
282 }
283 }
284 return thread_sp;
285}
286
287void OperatingSystemPython::ThreadWasSelected(Thread *thread) {}
288
290OperatingSystemPython::CreateRegisterContextForThread(Thread *thread,
291 addr_t reg_data_addr) {
292 RegisterContextSP reg_ctx_sp;
293 if (!m_interpreter || !m_script_object_sp || !thread)
294 return reg_ctx_sp;
295
296 if (!IsOperatingSystemPluginThread(thread->shared_from_this()))
297 return reg_ctx_sp;
298
299 Log *log = GetLog(LLDBLog::Thread);
300
301 if (reg_data_addr != LLDB_INVALID_ADDRESS) {
302 // The registers data is in contiguous memory, just create the register
303 // context using the address provided
304 LLDB_LOGF(log,
305 "OperatingSystemPython::CreateRegisterContextForThread (tid "
306 "= 0x%" PRIx64 ", 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64
307 ") creating memory register context",
308 thread->GetID(), thread->GetProtocolID(), reg_data_addr);
309 reg_ctx_sp = std::make_shared<RegisterContextMemory>(
310 *thread, 0, *GetDynamicRegisterInfo(), reg_data_addr);
311 } else {
312 // No register data address is provided, query the python plug-in to let it
313 // make up the data as it sees fit
314 LLDB_LOGF(log,
315 "OperatingSystemPython::CreateRegisterContextForThread (tid "
316 "= 0x%" PRIx64 ", 0x%" PRIx64
317 ") fetching register data from python",
318 thread->GetID(), thread->GetProtocolID());
319
320 std::optional<std::string> reg_context_data =
321 m_operating_system_interface_sp->GetRegisterContextForTID(
322 thread->GetID());
323 if (reg_context_data) {
324 std::string value = *reg_context_data;
325 DataBufferSP data_sp(new DataBufferHeap(value.c_str(), value.length()));
326 if (data_sp->GetByteSize()) {
327 RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory(
328 *thread, 0, *GetDynamicRegisterInfo(), LLDB_INVALID_ADDRESS);
329 if (reg_ctx_memory) {
330 reg_ctx_sp.reset(reg_ctx_memory);
331 reg_ctx_memory->SetAllRegisterData(data_sp);
332 }
333 }
334 }
335 }
336 // if we still have no register data, fallback on a dummy context to avoid
337 // crashing
338 if (!reg_ctx_sp) {
339 LLDB_LOGF(log,
340 "OperatingSystemPython::CreateRegisterContextForThread (tid "
341 "= 0x%" PRIx64 ") forcing a dummy register context",
342 thread->GetID());
343 Target &target = m_process->GetTarget();
344 reg_ctx_sp = std::make_shared<RegisterContextDummy>(
345 *thread, 0, target.GetArchitecture().GetAddressByteSize());
346 }
347 return reg_ctx_sp;
348}
349
351OperatingSystemPython::CreateThreadStopReason(lldb_private::Thread *thread) {
352 // We should have gotten the thread stop info from the dictionary of data for
353 // the thread in the initial call to get_thread_info(), this should have been
354 // cached so we can return it here
356 stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
357 return stop_info_sp;
358}
359
360lldb::ThreadSP OperatingSystemPython::CreateThread(lldb::tid_t tid,
361 addr_t context) {
362 Log *log = GetLog(LLDBLog::Thread);
363
364 LLDB_LOGF(log,
365 "OperatingSystemPython::CreateThread (tid = 0x%" PRIx64
366 ", context = 0x%" PRIx64 ") fetching register data from python",
367 tid, context);
368
369 if (m_interpreter && m_script_object_sp) {
370
371 StructuredData::DictionarySP thread_info_dict =
372 m_operating_system_interface_sp->CreateThread(tid, context);
373
374 std::vector<bool> core_used_map;
375 if (thread_info_dict) {
376 ThreadList core_threads(*m_process);
377 ThreadList &thread_list = m_process->GetThreadList();
378 bool did_create = false;
379 ThreadSP thread_sp(
380 CreateThreadFromThreadInfo(*thread_info_dict, core_threads,
381 thread_list, core_used_map, &did_create));
382 if (did_create)
383 thread_list.AddThread(thread_sp);
384 return thread_sp;
385 }
386 }
387 return ThreadSP();
388}
389
390bool OperatingSystemPython::DoesPluginReportAllThreads() {
391 // If the python plugin has a "DoesPluginReportAllThreads" method, use it.
392 if (std::optional<bool> plugin_answer =
393 m_operating_system_interface_sp->DoesPluginReportAllThreads())
394 return *plugin_answer;
395 return m_process->GetOSPluginReportsAllThreads();
396}
397
398#endif // #if LLDB_ENABLE_PYTHON
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_PLUGIN_DEFINE(PluginName)
void SetAllRegisterData(const lldb::DataBufferSP &data_sp)
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:690
A subclass of DataBuffer that stores a data buffer on the heap.
static std::unique_ptr< DynamicRegisterInfo > Create(const StructuredData::Dictionary &dict, const ArchSpec &arch)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
static FileSystem & Instance()
A plug-in interface definition class for halted OS helpers.
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
FileSpec GetPythonOSPluginPath() const
Definition Process.cpp:223
A plug-in interface definition class for debugging a process.
Definition Process.h:357
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4811
const char * GetData() const
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
std::shared_ptr< Generic > GenericSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
const ArchSpec & GetArchitecture() const
Definition Target.h:1283
void AddThread(const lldb::ThreadSP &thread_sp)
void InsertThread(const lldb::ThreadSP &thread_sp, uint32_t idx)
uint32_t GetSize(bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
lldb::ThreadSP FindThreadByID(lldb::tid_t tid, bool can_update=true)
#define LLDB_INVALID_THREAD_ID
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
uint64_t tid_t
Definition lldb-types.h:84
#define PATH_MAX