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