1 //===-- OperatingSystemPython.cpp --------------------------------*- C++-*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLDB_DISABLE_PYTHON
11 #include "OperatingSystemPython.h"
13 #include "Plugins/Process/Utility/DynamicRegisterInfo.h"
14 #include "Plugins/Process/Utility/RegisterContextDummy.h"
15 #include "Plugins/Process/Utility/RegisterContextMemory.h"
16 #include "Plugins/Process/Utility/ThreadMemory.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/ValueObjectVariable.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/ScriptInterpreter.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Symbol/VariableList.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Target/StopInfo.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
29 #include "lldb/Target/ThreadList.h"
30 #include "lldb/Utility/DataBufferHeap.h"
31 #include "lldb/Utility/RegisterValue.h"
32 #include "lldb/Utility/StreamString.h"
33 #include "lldb/Utility/StructuredData.h"
38 using namespace lldb_private;
40 void OperatingSystemPython::Initialize() {
41 PluginManager::RegisterPlugin(GetPluginNameStatic(),
42 GetPluginDescriptionStatic(), CreateInstance,
46 void OperatingSystemPython::Terminate() {
47 PluginManager::UnregisterPlugin(CreateInstance);
50 OperatingSystem *OperatingSystemPython::CreateInstance(Process *process,
52 // Python OperatingSystem plug-ins must be requested by name, so force must
54 FileSpec python_os_plugin_spec(process->GetPythonOSPluginPath());
55 if (python_os_plugin_spec &&
56 FileSystem::Instance().Exists(python_os_plugin_spec)) {
57 std::unique_ptr<OperatingSystemPython> os_up(
58 new OperatingSystemPython(process, python_os_plugin_spec));
59 if (os_up.get() && os_up->IsValid())
60 return os_up.release();
65 ConstString OperatingSystemPython::GetPluginNameStatic() {
66 static ConstString g_name("python");
70 const char *OperatingSystemPython::GetPluginDescriptionStatic() {
71 return "Operating system plug-in that gathers OS information from a python "
72 "class that implements the necessary OperatingSystem functionality.";
75 OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process,
76 const FileSpec &python_module_path)
77 : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_up(),
78 m_interpreter(nullptr), m_python_object_sp() {
81 TargetSP target_sp = process->CalculateTarget();
84 m_interpreter = target_sp->GetDebugger().GetScriptInterpreter();
87 std::string os_plugin_class_name(
88 python_module_path.GetFilename().AsCString(""));
89 if (!os_plugin_class_name.empty()) {
90 const bool init_session = false;
91 const bool allow_reload = true;
92 char python_module_path_cstr[PATH_MAX];
93 python_module_path.GetPath(python_module_path_cstr,
94 sizeof(python_module_path_cstr));
96 if (m_interpreter->LoadScriptingModule(
97 python_module_path_cstr, allow_reload, init_session, error)) {
98 // Strip the ".py" extension if there is one
99 size_t py_extension_pos = os_plugin_class_name.rfind(".py");
100 if (py_extension_pos != std::string::npos)
101 os_plugin_class_name.erase(py_extension_pos);
102 // Add ".OperatingSystemPlugIn" to the module name to get a string like
103 // "modulename.OperatingSystemPlugIn"
104 os_plugin_class_name += ".OperatingSystemPlugIn";
105 StructuredData::ObjectSP object_sp =
106 m_interpreter->OSPlugin_CreatePluginObject(
107 os_plugin_class_name.c_str(), process->CalculateProcess());
108 if (object_sp && object_sp->IsValid())
109 m_python_object_sp = object_sp;
115 OperatingSystemPython::~OperatingSystemPython() {}
117 DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() {
118 if (m_register_info_up == nullptr) {
119 if (!m_interpreter || !m_python_object_sp)
121 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
124 log->Printf("OperatingSystemPython::GetDynamicRegisterInfo() fetching "
125 "thread register definitions from python for pid %" PRIu64,
128 StructuredData::DictionarySP dictionary =
129 m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp);
133 m_register_info_up.reset(new DynamicRegisterInfo(
134 *dictionary, m_process->GetTarget().GetArchitecture()));
135 assert(m_register_info_up->GetNumRegisters() > 0);
136 assert(m_register_info_up->GetNumRegisterSets() > 0);
138 return m_register_info_up.get();
141 // PluginInterface protocol
142 ConstString OperatingSystemPython::GetPluginName() {
143 return GetPluginNameStatic();
146 uint32_t OperatingSystemPython::GetPluginVersion() { return 1; }
148 bool OperatingSystemPython::UpdateThreadList(ThreadList &old_thread_list,
149 ThreadList &core_thread_list,
150 ThreadList &new_thread_list) {
151 if (!m_interpreter || !m_python_object_sp)
154 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
156 // First thing we have to do is to try to get the API lock, and the
157 // interpreter lock. We're going to change the thread content of the process,
158 // and we're going to use python, which requires the API lock to do it. We
159 // need the interpreter lock to make sure thread_info_dict stays alive.
161 // If someone already has the API lock, that is ok, we just want to avoid
162 // external code from making new API calls while this call is happening.
164 // This is a recursive lock so we can grant it to any Python code called on
165 // the stack below us.
166 Target &target = m_process->GetTarget();
167 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
170 auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
173 log->Printf("OperatingSystemPython::UpdateThreadList() fetching thread "
174 "data from python for pid %" PRIu64,
177 // The threads that are in "new_thread_list" upon entry are the threads from
178 // the lldb_private::Process subclass, no memory threads will be in this
180 StructuredData::ArraySP threads_list =
181 m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp);
183 const uint32_t num_cores = core_thread_list.GetSize(false);
185 // Make a map so we can keep track of which cores were used from the
186 // core_thread list. Any real threads/cores that weren't used should later be
187 // put back into the "new_thread_list".
188 std::vector<bool> core_used_map(num_cores, false);
192 threads_list->Dump(strm);
193 log->Printf("threads_list = %s", strm.GetData());
196 const uint32_t num_threads = threads_list->GetSize();
197 for (uint32_t i = 0; i < num_threads; ++i) {
198 StructuredData::ObjectSP thread_dict_obj =
199 threads_list->GetItemAtIndex(i);
200 if (auto thread_dict = thread_dict_obj->GetAsDictionary()) {
201 ThreadSP thread_sp(CreateThreadFromThreadInfo(
202 *thread_dict, core_thread_list, old_thread_list, core_used_map,
205 new_thread_list.AddThread(thread_sp);
210 // Any real core threads that didn't end up backing a memory thread should
211 // still be in the main thread list, and they should be inserted at the
212 // beginning of the list
213 uint32_t insert_idx = 0;
214 for (uint32_t core_idx = 0; core_idx < num_cores; ++core_idx) {
215 if (!core_used_map[core_idx]) {
216 new_thread_list.InsertThread(
217 core_thread_list.GetThreadAtIndex(core_idx, false), insert_idx);
222 return new_thread_list.GetSize(false) > 0;
225 ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo(
226 StructuredData::Dictionary &thread_dict, ThreadList &core_thread_list,
227 ThreadList &old_thread_list, std::vector<bool> &core_used_map,
228 bool *did_create_ptr) {
230 tid_t tid = LLDB_INVALID_THREAD_ID;
231 if (!thread_dict.GetValueForKeyAsInteger("tid", tid))
234 uint32_t core_number;
235 addr_t reg_data_addr;
236 llvm::StringRef name;
237 llvm::StringRef queue;
239 thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX);
240 thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr,
241 LLDB_INVALID_ADDRESS);
242 thread_dict.GetValueForKeyAsString("name", name);
243 thread_dict.GetValueForKeyAsString("queue", queue);
245 // See if a thread already exists for "tid"
246 thread_sp = old_thread_list.FindThreadByID(tid, false);
248 // A thread already does exist for "tid", make sure it was an operating
250 // plug-in generated thread.
251 if (!IsOperatingSystemPluginThread(thread_sp)) {
252 // We have thread ID overlap between the protocol threads and the
253 // operating system threads, clear the thread so we create an operating
254 // system thread for this.
261 *did_create_ptr = true;
262 thread_sp = std::make_shared<ThreadMemory>(*m_process, tid, name, queue,
266 if (core_number < core_thread_list.GetSize(false)) {
267 ThreadSP core_thread_sp(
268 core_thread_list.GetThreadAtIndex(core_number, false));
269 if (core_thread_sp) {
270 // Keep track of which cores were set as the backing thread for memory
272 if (core_number < core_used_map.size())
273 core_used_map[core_number] = true;
275 ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread());
276 if (backing_core_thread_sp) {
277 thread_sp->SetBackingThread(backing_core_thread_sp);
279 thread_sp->SetBackingThread(core_thread_sp);
286 void OperatingSystemPython::ThreadWasSelected(Thread *thread) {}
289 OperatingSystemPython::CreateRegisterContextForThread(Thread *thread,
290 addr_t reg_data_addr) {
291 RegisterContextSP reg_ctx_sp;
292 if (!m_interpreter || !m_python_object_sp || !thread)
295 if (!IsOperatingSystemPluginThread(thread->shared_from_this()))
298 // First thing we have to do is to try to get the API lock, and the
299 // interpreter lock. We're going to change the thread content of the process,
300 // and we're going to use python, which requires the API lock to do it. We
301 // need the interpreter lock to make sure thread_info_dict stays alive.
303 // If someone already has the API lock, that is ok, we just want to avoid
304 // external code from making new API calls while this call is happening.
306 // This is a recursive lock so we can grant it to any Python code called on
307 // the stack below us.
308 Target &target = m_process->GetTarget();
309 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
312 auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
314 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
316 if (reg_data_addr != LLDB_INVALID_ADDRESS) {
317 // The registers data is in contiguous memory, just create the register
318 // context using the address provided
320 log->Printf("OperatingSystemPython::CreateRegisterContextForThread (tid "
321 "= 0x%" PRIx64 ", 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64
322 ") creating memory register context",
323 thread->GetID(), thread->GetProtocolID(), reg_data_addr);
324 reg_ctx_sp = std::make_shared<RegisterContextMemory>(
325 *thread, 0, *GetDynamicRegisterInfo(), reg_data_addr);
327 // No register data address is provided, query the python plug-in to let it
328 // make up the data as it sees fit
330 log->Printf("OperatingSystemPython::CreateRegisterContextForThread (tid "
331 "= 0x%" PRIx64 ", 0x%" PRIx64
332 ") fetching register data from python",
333 thread->GetID(), thread->GetProtocolID());
335 StructuredData::StringSP reg_context_data =
336 m_interpreter->OSPlugin_RegisterContextData(m_python_object_sp,
338 if (reg_context_data) {
339 std::string value = reg_context_data->GetValue();
340 DataBufferSP data_sp(new DataBufferHeap(value.c_str(), value.length()));
341 if (data_sp->GetByteSize()) {
342 RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory(
343 *thread, 0, *GetDynamicRegisterInfo(), LLDB_INVALID_ADDRESS);
344 if (reg_ctx_memory) {
345 reg_ctx_sp.reset(reg_ctx_memory);
346 reg_ctx_memory->SetAllRegisterData(data_sp);
351 // if we still have no register data, fallback on a dummy context to avoid
355 log->Printf("OperatingSystemPython::CreateRegisterContextForThread (tid "
356 "= 0x%" PRIx64 ") forcing a dummy register context",
358 reg_ctx_sp = std::make_shared<RegisterContextDummy>(
359 *thread, 0, target.GetArchitecture().GetAddressByteSize());
365 OperatingSystemPython::CreateThreadStopReason(lldb_private::Thread *thread) {
366 // We should have gotten the thread stop info from the dictionary of data for
367 // the thread in the initial call to get_thread_info(), this should have been
368 // cached so we can return it here
370 stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
374 lldb::ThreadSP OperatingSystemPython::CreateThread(lldb::tid_t tid,
376 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
379 log->Printf("OperatingSystemPython::CreateThread (tid = 0x%" PRIx64
380 ", context = 0x%" PRIx64 ") fetching register data from python",
383 if (m_interpreter && m_python_object_sp) {
384 // First thing we have to do is to try to get the API lock, and the
385 // interpreter lock. We're going to change the thread content of the
386 // process, and we're going to use python, which requires the API lock to
387 // do it. We need the interpreter lock to make sure thread_info_dict stays
390 // If someone already has the API lock, that is ok, we just want to avoid
391 // external code from making new API calls while this call is happening.
393 // This is a recursive lock so we can grant it to any Python code called on
394 // the stack below us.
395 Target &target = m_process->GetTarget();
396 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
399 auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
401 StructuredData::DictionarySP thread_info_dict =
402 m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context);
403 std::vector<bool> core_used_map;
404 if (thread_info_dict) {
405 ThreadList core_threads(m_process);
406 ThreadList &thread_list = m_process->GetThreadList();
407 bool did_create = false;
409 CreateThreadFromThreadInfo(*thread_info_dict, core_threads,
410 thread_list, core_used_map, &did_create));
412 thread_list.AddThread(thread_sp);
419 #endif // #ifndef LLDB_DISABLE_PYTHON