xref: /llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp (revision a3939e159fc9528b097672794035a1cdfda520e8)
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 
13 #include "OperatingSystemPython.h"
14 
15 #include "Plugins/Process/Utility/RegisterContextDummy.h"
16 #include "Plugins/Process/Utility/RegisterContextMemory.h"
17 #include "Plugins/Process/Utility/ThreadMemory.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Core/ValueObjectVariable.h"
22 #include "lldb/Interpreter/CommandInterpreter.h"
23 #include "lldb/Interpreter/ScriptInterpreter.h"
24 #include "lldb/Symbol/ObjectFile.h"
25 #include "lldb/Symbol/VariableList.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/StopInfo.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Thread.h"
30 #include "lldb/Target/ThreadList.h"
31 #include "lldb/Utility/DataBufferHeap.h"
32 #include "lldb/Utility/RegisterValue.h"
33 #include "lldb/Utility/StreamString.h"
34 #include "lldb/Utility/StructuredData.h"
35 
36 #include <memory>
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 
41 LLDB_PLUGIN_DEFINE(OperatingSystemPython)
42 
43 void OperatingSystemPython::Initialize() {
44   PluginManager::RegisterPlugin(GetPluginNameStatic(),
45                                 GetPluginDescriptionStatic(), CreateInstance,
46                                 nullptr);
47 }
48 
49 void OperatingSystemPython::Terminate() {
50   PluginManager::UnregisterPlugin(CreateInstance);
51 }
52 
53 OperatingSystem *OperatingSystemPython::CreateInstance(Process *process,
54                                                        bool force) {
55   // Python OperatingSystem plug-ins must be requested by name, so force must
56   // be true
57   FileSpec python_os_plugin_spec(process->GetPythonOSPluginPath());
58   if (python_os_plugin_spec &&
59       FileSystem::Instance().Exists(python_os_plugin_spec)) {
60     std::unique_ptr<OperatingSystemPython> os_up(
61         new OperatingSystemPython(process, python_os_plugin_spec));
62     if (os_up.get() && os_up->IsValid())
63       return os_up.release();
64   }
65   return nullptr;
66 }
67 
68 ConstString OperatingSystemPython::GetPluginNameStatic() {
69   static ConstString g_name("python");
70   return g_name;
71 }
72 
73 const char *OperatingSystemPython::GetPluginDescriptionStatic() {
74   return "Operating system plug-in that gathers OS information from a python "
75          "class that implements the necessary OperatingSystem functionality.";
76 }
77 
78 OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process,
79                                              const FileSpec &python_module_path)
80     : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_up(),
81       m_interpreter(nullptr), m_python_object_sp() {
82   if (!process)
83     return;
84   TargetSP target_sp = process->CalculateTarget();
85   if (!target_sp)
86     return;
87   m_interpreter = target_sp->GetDebugger().GetScriptInterpreter();
88   if (m_interpreter) {
89 
90     std::string os_plugin_class_name(
91         python_module_path.GetFilename().AsCString(""));
92     if (!os_plugin_class_name.empty()) {
93       LoadScriptOptions options;
94       char python_module_path_cstr[PATH_MAX];
95       python_module_path.GetPath(python_module_path_cstr,
96                                  sizeof(python_module_path_cstr));
97       Status error;
98       if (m_interpreter->LoadScriptingModule(python_module_path_cstr, options,
99                                              error)) {
100         // Strip the ".py" extension if there is one
101         size_t py_extension_pos = os_plugin_class_name.rfind(".py");
102         if (py_extension_pos != std::string::npos)
103           os_plugin_class_name.erase(py_extension_pos);
104         // Add ".OperatingSystemPlugIn" to the module name to get a string like
105         // "modulename.OperatingSystemPlugIn"
106         os_plugin_class_name += ".OperatingSystemPlugIn";
107         StructuredData::ObjectSP object_sp =
108             m_interpreter->OSPlugin_CreatePluginObject(
109                 os_plugin_class_name.c_str(), process->CalculateProcess());
110         if (object_sp && object_sp->IsValid())
111           m_python_object_sp = object_sp;
112       }
113     }
114   }
115 }
116 
117 OperatingSystemPython::~OperatingSystemPython() = default;
118 
119 DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() {
120   if (m_register_info_up == nullptr) {
121     if (!m_interpreter || !m_python_object_sp)
122       return nullptr;
123     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
124 
125     LLDB_LOGF(log,
126               "OperatingSystemPython::GetDynamicRegisterInfo() fetching "
127               "thread register definitions from python for pid %" PRIu64,
128               m_process->GetID());
129 
130     StructuredData::DictionarySP dictionary =
131         m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp);
132     if (!dictionary)
133       return nullptr;
134 
135     m_register_info_up = std::make_unique<DynamicRegisterInfo>(
136         *dictionary, m_process->GetTarget().GetArchitecture());
137     assert(m_register_info_up->GetNumRegisters() > 0);
138     assert(m_register_info_up->GetNumRegisterSets() > 0);
139   }
140   return m_register_info_up.get();
141 }
142 
143 bool OperatingSystemPython::UpdateThreadList(ThreadList &old_thread_list,
144                                              ThreadList &core_thread_list,
145                                              ThreadList &new_thread_list) {
146   if (!m_interpreter || !m_python_object_sp)
147     return false;
148 
149   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
150 
151   // First thing we have to do is to try to get the API lock, and the
152   // interpreter lock. We're going to change the thread content of the process,
153   // and we're going to use python, which requires the API lock to do it. We
154   // need the interpreter lock to make sure thread_info_dict stays alive.
155   //
156   // If someone already has the API lock, that is ok, we just want to avoid
157   // external code from making new API calls while this call is happening.
158   //
159   // This is a recursive lock so we can grant it to any Python code called on
160   // the stack below us.
161   Target &target = m_process->GetTarget();
162   std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
163                                                   std::defer_lock);
164   (void)api_lock.try_lock(); // See above.
165   auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
166 
167   LLDB_LOGF(log,
168             "OperatingSystemPython::UpdateThreadList() fetching thread "
169             "data from python for pid %" PRIu64,
170             m_process->GetID());
171 
172   // The threads that are in "core_thread_list" upon entry are the threads from
173   // the lldb_private::Process subclass, no memory threads will be in this
174   // list.
175   StructuredData::ArraySP threads_list =
176       m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp);
177 
178   const uint32_t num_cores = core_thread_list.GetSize(false);
179 
180   // Make a map so we can keep track of which cores were used from the
181   // core_thread list. Any real threads/cores that weren't used should later be
182   // put back into the "new_thread_list".
183   std::vector<bool> core_used_map(num_cores, false);
184   if (threads_list) {
185     if (log) {
186       StreamString strm;
187       threads_list->Dump(strm);
188       LLDB_LOGF(log, "threads_list = %s", strm.GetData());
189     }
190 
191     const uint32_t num_threads = threads_list->GetSize();
192     for (uint32_t i = 0; i < num_threads; ++i) {
193       StructuredData::ObjectSP thread_dict_obj =
194           threads_list->GetItemAtIndex(i);
195       if (auto thread_dict = thread_dict_obj->GetAsDictionary()) {
196         ThreadSP thread_sp(CreateThreadFromThreadInfo(
197             *thread_dict, core_thread_list, old_thread_list, core_used_map,
198             nullptr));
199         if (thread_sp)
200           new_thread_list.AddThread(thread_sp);
201       }
202     }
203   }
204 
205   // Any real core threads that didn't end up backing a memory thread should
206   // still be in the main thread list, and they should be inserted at the
207   // beginning of the list
208   uint32_t insert_idx = 0;
209   for (uint32_t core_idx = 0; core_idx < num_cores; ++core_idx) {
210     if (!core_used_map[core_idx]) {
211       new_thread_list.InsertThread(
212           core_thread_list.GetThreadAtIndex(core_idx, false), insert_idx);
213       ++insert_idx;
214     }
215   }
216 
217   return new_thread_list.GetSize(false) > 0;
218 }
219 
220 ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo(
221     StructuredData::Dictionary &thread_dict, ThreadList &core_thread_list,
222     ThreadList &old_thread_list, std::vector<bool> &core_used_map,
223     bool *did_create_ptr) {
224   ThreadSP thread_sp;
225   tid_t tid = LLDB_INVALID_THREAD_ID;
226   if (!thread_dict.GetValueForKeyAsInteger("tid", tid))
227     return ThreadSP();
228 
229   uint32_t core_number;
230   addr_t reg_data_addr;
231   llvm::StringRef name;
232   llvm::StringRef queue;
233 
234   thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX);
235   thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr,
236                                       LLDB_INVALID_ADDRESS);
237   thread_dict.GetValueForKeyAsString("name", name);
238   thread_dict.GetValueForKeyAsString("queue", queue);
239 
240   // See if a thread already exists for "tid"
241   thread_sp = old_thread_list.FindThreadByID(tid, false);
242   if (thread_sp) {
243     // A thread already does exist for "tid", make sure it was an operating
244     // system
245     // plug-in generated thread.
246     if (!IsOperatingSystemPluginThread(thread_sp)) {
247       // We have thread ID overlap between the protocol threads and the
248       // operating system threads, clear the thread so we create an operating
249       // system thread for this.
250       thread_sp.reset();
251     }
252   }
253 
254   if (!thread_sp) {
255     if (did_create_ptr)
256       *did_create_ptr = true;
257     thread_sp = std::make_shared<ThreadMemory>(*m_process, tid, name, queue,
258                                                reg_data_addr);
259   }
260 
261   if (core_number < core_thread_list.GetSize(false)) {
262     ThreadSP core_thread_sp(
263         core_thread_list.GetThreadAtIndex(core_number, false));
264     if (core_thread_sp) {
265       // Keep track of which cores were set as the backing thread for memory
266       // threads...
267       if (core_number < core_used_map.size())
268         core_used_map[core_number] = true;
269 
270       ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread());
271       if (backing_core_thread_sp) {
272         thread_sp->SetBackingThread(backing_core_thread_sp);
273       } else {
274         thread_sp->SetBackingThread(core_thread_sp);
275       }
276     }
277   }
278   return thread_sp;
279 }
280 
281 void OperatingSystemPython::ThreadWasSelected(Thread *thread) {}
282 
283 RegisterContextSP
284 OperatingSystemPython::CreateRegisterContextForThread(Thread *thread,
285                                                       addr_t reg_data_addr) {
286   RegisterContextSP reg_ctx_sp;
287   if (!m_interpreter || !m_python_object_sp || !thread)
288     return reg_ctx_sp;
289 
290   if (!IsOperatingSystemPluginThread(thread->shared_from_this()))
291     return reg_ctx_sp;
292 
293   // First thing we have to do is to try to get the API lock, and the
294   // interpreter lock. We're going to change the thread content of the process,
295   // and we're going to use python, which requires the API lock to do it. We
296   // need the interpreter lock to make sure thread_info_dict stays alive.
297   //
298   // If someone already has the API lock, that is ok, we just want to avoid
299   // external code from making new API calls while this call is happening.
300   //
301   // This is a recursive lock so we can grant it to any Python code called on
302   // the stack below us.
303   Target &target = m_process->GetTarget();
304   std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
305                                                   std::defer_lock);
306   (void)api_lock.try_lock(); // See above.
307   auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
308 
309   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
310 
311   if (reg_data_addr != LLDB_INVALID_ADDRESS) {
312     // The registers data is in contiguous memory, just create the register
313     // context using the address provided
314     LLDB_LOGF(log,
315               "OperatingSystemPython::CreateRegisterContextForThread (tid "
316               "= 0x%" PRIx64 ", 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64
317               ") creating memory register context",
318               thread->GetID(), thread->GetProtocolID(), reg_data_addr);
319     reg_ctx_sp = std::make_shared<RegisterContextMemory>(
320         *thread, 0, *GetDynamicRegisterInfo(), reg_data_addr);
321   } else {
322     // No register data address is provided, query the python plug-in to let it
323     // make up the data as it sees fit
324     LLDB_LOGF(log,
325               "OperatingSystemPython::CreateRegisterContextForThread (tid "
326               "= 0x%" PRIx64 ", 0x%" PRIx64
327               ") fetching register data from python",
328               thread->GetID(), thread->GetProtocolID());
329 
330     StructuredData::StringSP reg_context_data =
331         m_interpreter->OSPlugin_RegisterContextData(m_python_object_sp,
332                                                     thread->GetID());
333     if (reg_context_data) {
334       std::string value = std::string(reg_context_data->GetValue());
335       DataBufferSP data_sp(new DataBufferHeap(value.c_str(), value.length()));
336       if (data_sp->GetByteSize()) {
337         RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory(
338             *thread, 0, *GetDynamicRegisterInfo(), LLDB_INVALID_ADDRESS);
339         if (reg_ctx_memory) {
340           reg_ctx_sp.reset(reg_ctx_memory);
341           reg_ctx_memory->SetAllRegisterData(data_sp);
342         }
343       }
344     }
345   }
346   // if we still have no register data, fallback on a dummy context to avoid
347   // crashing
348   if (!reg_ctx_sp) {
349     LLDB_LOGF(log,
350               "OperatingSystemPython::CreateRegisterContextForThread (tid "
351               "= 0x%" PRIx64 ") forcing a dummy register context",
352               thread->GetID());
353     reg_ctx_sp = std::make_shared<RegisterContextDummy>(
354         *thread, 0, target.GetArchitecture().GetAddressByteSize());
355   }
356   return reg_ctx_sp;
357 }
358 
359 StopInfoSP
360 OperatingSystemPython::CreateThreadStopReason(lldb_private::Thread *thread) {
361   // We should have gotten the thread stop info from the dictionary of data for
362   // the thread in the initial call to get_thread_info(), this should have been
363   // cached so we can return it here
364   StopInfoSP
365       stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
366   return stop_info_sp;
367 }
368 
369 lldb::ThreadSP OperatingSystemPython::CreateThread(lldb::tid_t tid,
370                                                    addr_t context) {
371   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
372 
373   LLDB_LOGF(log,
374             "OperatingSystemPython::CreateThread (tid = 0x%" PRIx64
375             ", context = 0x%" PRIx64 ") fetching register data from python",
376             tid, context);
377 
378   if (m_interpreter && m_python_object_sp) {
379     // First thing we have to do is to try to get the API lock, and the
380     // interpreter lock. We're going to change the thread content of the
381     // process, and we're going to use python, which requires the API lock to
382     // do it. We need the interpreter lock to make sure thread_info_dict stays
383     // alive.
384     //
385     // If someone already has the API lock, that is ok, we just want to avoid
386     // external code from making new API calls while this call is happening.
387     //
388     // This is a recursive lock so we can grant it to any Python code called on
389     // the stack below us.
390     Target &target = m_process->GetTarget();
391     std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
392                                                     std::defer_lock);
393     (void)api_lock.try_lock(); // See above.
394     auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
395 
396     StructuredData::DictionarySP thread_info_dict =
397         m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context);
398     std::vector<bool> core_used_map;
399     if (thread_info_dict) {
400       ThreadList core_threads(m_process);
401       ThreadList &thread_list = m_process->GetThreadList();
402       bool did_create = false;
403       ThreadSP thread_sp(
404           CreateThreadFromThreadInfo(*thread_info_dict, core_threads,
405                                      thread_list, core_used_map, &did_create));
406       if (did_create)
407         thread_list.AddThread(thread_sp);
408       return thread_sp;
409     }
410   }
411   return ThreadSP();
412 }
413 
414 #endif // #if LLDB_ENABLE_PYTHON
415