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