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