xref: /llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp (revision e01e07b6e76ad6f571cefe679d112fede88cf1db)
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 #include "lldb/lldb-python.h"
11 
12 #ifndef LLDB_DISABLE_PYTHON
13 
14 #include "OperatingSystemPython.h"
15 // C Includes
16 // C++ Includes
17 // Other libraries and framework includes
18 #include "lldb/Core/ArchSpec.h"
19 #include "lldb/Core/DataBufferHeap.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/PythonDataObjects.h"
27 #include "lldb/Symbol/ClangNamespaceDecl.h"
28 #include "lldb/Symbol/ObjectFile.h"
29 #include "lldb/Symbol/VariableList.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/StopInfo.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/ThreadList.h"
34 #include "lldb/Target/Thread.h"
35 #include "Plugins/Process/Utility/DynamicRegisterInfo.h"
36 #include "Plugins/Process/Utility/RegisterContextMemory.h"
37 #include "Plugins/Process/Utility/ThreadMemory.h"
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 
42 void
43 OperatingSystemPython::Initialize()
44 {
45     PluginManager::RegisterPlugin (GetPluginNameStatic(),
46                                    GetPluginDescriptionStatic(),
47                                    CreateInstance);
48 }
49 
50 void
51 OperatingSystemPython::Terminate()
52 {
53     PluginManager::UnregisterPlugin (CreateInstance);
54 }
55 
56 OperatingSystem *
57 OperatingSystemPython::CreateInstance (Process *process, bool force)
58 {
59     // Python OperatingSystem plug-ins must be requested by name, so force must be true
60     FileSpec python_os_plugin_spec (process->GetPythonOSPluginPath());
61     if (python_os_plugin_spec && python_os_plugin_spec.Exists())
62     {
63         STD_UNIQUE_PTR(OperatingSystemPython) os_ap (new OperatingSystemPython (process, python_os_plugin_spec));
64         if (os_ap.get() && os_ap->IsValid())
65             return os_ap.release();
66     }
67     return NULL;
68 }
69 
70 
71 const char *
72 OperatingSystemPython::GetPluginNameStatic()
73 {
74     return "python";
75 }
76 
77 const char *
78 OperatingSystemPython::GetPluginDescriptionStatic()
79 {
80     return "Operating system plug-in that gathers OS information from a python class that implements the necessary OperatingSystem functionality.";
81 }
82 
83 
84 OperatingSystemPython::OperatingSystemPython (lldb_private::Process *process, const FileSpec &python_module_path) :
85     OperatingSystem (process),
86     m_thread_list_valobj_sp (),
87     m_register_info_ap (),
88     m_interpreter (NULL),
89     m_python_object_sp ()
90 {
91     if (!process)
92         return;
93     TargetSP target_sp = process->CalculateTarget();
94     if (!target_sp)
95         return;
96     m_interpreter = target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
97     if (m_interpreter)
98     {
99 
100         std::string os_plugin_class_name (python_module_path.GetFilename().AsCString(""));
101         if (!os_plugin_class_name.empty())
102         {
103             const bool init_session = false;
104             const bool allow_reload = true;
105             char python_module_path_cstr[PATH_MAX];
106             python_module_path.GetPath(python_module_path_cstr, sizeof(python_module_path_cstr));
107             Error error;
108             if (m_interpreter->LoadScriptingModule (python_module_path_cstr, allow_reload, init_session, error))
109             {
110                 // Strip the ".py" extension if there is one
111                 size_t py_extension_pos = os_plugin_class_name.rfind(".py");
112                 if (py_extension_pos != std::string::npos)
113                     os_plugin_class_name.erase (py_extension_pos);
114                 // Add ".OperatingSystemPlugIn" to the module name to get a string like "modulename.OperatingSystemPlugIn"
115                 os_plugin_class_name += ".OperatingSystemPlugIn";
116                 ScriptInterpreterObjectSP object_sp = m_interpreter->OSPlugin_CreatePluginObject(os_plugin_class_name.c_str(), process->CalculateProcess());
117                 if (object_sp && object_sp->GetObject())
118                     m_python_object_sp = object_sp;
119             }
120         }
121     }
122 }
123 
124 OperatingSystemPython::~OperatingSystemPython ()
125 {
126 }
127 
128 DynamicRegisterInfo *
129 OperatingSystemPython::GetDynamicRegisterInfo ()
130 {
131     if (m_register_info_ap.get() == NULL)
132     {
133         if (!m_interpreter || !m_python_object_sp)
134             return NULL;
135         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
136 
137         if (log)
138             log->Printf ("OperatingSystemPython::GetDynamicRegisterInfo() fetching thread register definitions from python for pid %" PRIu64, m_process->GetID());
139 
140         PythonDictionary dictionary(m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp));
141         if (!dictionary)
142             return NULL;
143 
144         m_register_info_ap.reset (new DynamicRegisterInfo (dictionary));
145         assert (m_register_info_ap->GetNumRegisters() > 0);
146         assert (m_register_info_ap->GetNumRegisterSets() > 0);
147     }
148     return m_register_info_ap.get();
149 }
150 
151 //------------------------------------------------------------------
152 // PluginInterface protocol
153 //------------------------------------------------------------------
154 const char *
155 OperatingSystemPython::GetPluginName()
156 {
157     return "OperatingSystemPython";
158 }
159 
160 const char *
161 OperatingSystemPython::GetShortPluginName()
162 {
163     return GetPluginNameStatic();
164 }
165 
166 uint32_t
167 OperatingSystemPython::GetPluginVersion()
168 {
169     return 1;
170 }
171 
172 bool
173 OperatingSystemPython::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
174 {
175     if (!m_interpreter || !m_python_object_sp)
176         return false;
177 
178     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
179 
180     // First thing we have to do is get the API lock, and the run lock.  We're going to change the thread
181     // content of the process, and we're going to use python, which requires the API lock to do it.
182     // So get & hold that.  This is a recursive lock so we can grant it to any Python code called on the stack below us.
183     Target &target = m_process->GetTarget();
184     Mutex::Locker api_locker (target.GetAPIMutex());
185 
186     if (log)
187         log->Printf ("OperatingSystemPython::UpdateThreadList() fetching thread data from python for pid %" PRIu64, m_process->GetID());
188 
189     // The threads that are in "new_thread_list" upon entry are the threads from the
190     // lldb_private::Process subclass, no memory threads will be in this list.
191 
192     auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure threads_list stays alive
193     PythonList threads_list(m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp));
194     if (threads_list)
195     {
196         ThreadList core_thread_list(new_thread_list);
197 
198         uint32_t i;
199         const uint32_t num_threads = threads_list.GetSize();
200         for (i=0; i<num_threads; ++i)
201         {
202             PythonDictionary thread_dict(threads_list.GetItemAtIndex(i));
203             if (thread_dict)
204             {
205                 if (thread_dict.GetItemForKey("core"))
206                 {
207                     // We have some threads that are saying they are on a "core", which means
208                     // they map the threads that are gotten from the lldb_private::Process subclass
209                     // so clear the new threads list so the core threads don't show up
210                     new_thread_list.Clear();
211                     break;
212                 }
213             }
214         }
215         for (i=0; i<num_threads; ++i)
216         {
217             PythonDictionary thread_dict(threads_list.GetItemAtIndex(i));
218             if (thread_dict)
219             {
220                 ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_dict, core_thread_list, old_thread_list, NULL));
221                 if (thread_sp)
222                     new_thread_list.AddThread(thread_sp);
223             }
224         }
225     }
226     else
227     {
228         new_thread_list = old_thread_list;
229     }
230     return new_thread_list.GetSize(false) > 0;
231 }
232 
233 ThreadSP
234 OperatingSystemPython::CreateThreadFromThreadInfo (PythonDictionary &thread_dict,
235                                                    ThreadList &core_thread_list,
236                                                    ThreadList &old_thread_list,
237                                                    bool *did_create_ptr)
238 {
239     ThreadSP thread_sp;
240     if (thread_dict)
241     {
242         PythonString tid_pystr("tid");
243         const tid_t tid = thread_dict.GetItemForKeyAsInteger (tid_pystr, LLDB_INVALID_THREAD_ID);
244         if (tid != LLDB_INVALID_THREAD_ID)
245         {
246             PythonString core_pystr("core");
247             PythonString name_pystr("name");
248             PythonString queue_pystr("queue");
249             PythonString state_pystr("state");
250             PythonString stop_reason_pystr("stop_reason");
251             PythonString reg_data_addr_pystr ("register_data_addr");
252 
253             const uint32_t core_number = thread_dict.GetItemForKeyAsInteger (core_pystr, UINT32_MAX);
254             const addr_t reg_data_addr = thread_dict.GetItemForKeyAsInteger (reg_data_addr_pystr, LLDB_INVALID_ADDRESS);
255             const char *name = thread_dict.GetItemForKeyAsString (name_pystr);
256             const char *queue = thread_dict.GetItemForKeyAsString (queue_pystr);
257             //const char *state = thread_dict.GetItemForKeyAsString (state_pystr);
258             //const char *stop_reason = thread_dict.GetItemForKeyAsString (stop_reason_pystr);
259 
260             thread_sp = old_thread_list.FindThreadByID (tid, false);
261             if (!thread_sp)
262             {
263                 if (did_create_ptr)
264                     *did_create_ptr = true;
265                 thread_sp.reset (new ThreadMemory (*m_process,
266                                                    tid,
267                                                    name,
268                                                    queue,
269                                                    reg_data_addr));
270 
271             }
272 
273             if (core_number < core_thread_list.GetSize(false))
274             {
275                 thread_sp->SetBackingThread(core_thread_list.GetThreadAtIndex(core_number, false));
276             }
277         }
278     }
279     return thread_sp;
280 }
281 
282 
283 
284 void
285 OperatingSystemPython::ThreadWasSelected (Thread *thread)
286 {
287 }
288 
289 RegisterContextSP
290 OperatingSystemPython::CreateRegisterContextForThread (Thread *thread, addr_t reg_data_addr)
291 {
292     RegisterContextSP reg_ctx_sp;
293     if (!m_interpreter || !m_python_object_sp || !thread)
294         return RegisterContextSP();
295 
296     // First thing we have to do is get the API lock, and the run lock.  We're going to change the thread
297     // content of the process, and we're going to use python, which requires the API lock to do it.
298     // So get & hold that.  This is a recursive lock so we can grant it to any Python code called on the stack below us.
299     Target &target = m_process->GetTarget();
300     Mutex::Locker api_locker (target.GetAPIMutex());
301 
302     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
303 
304     auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure python objects stays alive
305     if (reg_data_addr != LLDB_INVALID_ADDRESS)
306     {
307         // The registers data is in contiguous memory, just create the register
308         // context using the address provided
309         if (log)
310             log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64 ") creating memory register context", thread->GetID(), reg_data_addr);
311         reg_ctx_sp.reset (new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), reg_data_addr));
312     }
313     else
314     {
315         // No register data address is provided, query the python plug-in to let
316         // it make up the data as it sees fit
317         if (log)
318             log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ") fetching register data from python", thread->GetID());
319 
320         PythonString reg_context_data(m_interpreter->OSPlugin_RegisterContextData (m_python_object_sp, thread->GetID()));
321         if (reg_context_data)
322         {
323             DataBufferSP data_sp (new DataBufferHeap (reg_context_data.GetString(),
324                                                       reg_context_data.GetSize()));
325             if (data_sp->GetByteSize())
326             {
327                 RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), LLDB_INVALID_ADDRESS);
328                 if (reg_ctx_memory)
329                 {
330                     reg_ctx_sp.reset(reg_ctx_memory);
331                     reg_ctx_memory->SetAllRegisterData (data_sp);
332                 }
333             }
334         }
335     }
336     return reg_ctx_sp;
337 }
338 
339 StopInfoSP
340 OperatingSystemPython::CreateThreadStopReason (lldb_private::Thread *thread)
341 {
342     // We should have gotten the thread stop info from the dictionary of data for
343     // the thread in the initial call to get_thread_info(), this should have been
344     // cached so we can return it here
345     StopInfoSP stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
346     return stop_info_sp;
347 }
348 
349 lldb::ThreadSP
350 OperatingSystemPython::CreateThread (lldb::tid_t tid, addr_t context)
351 {
352     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
353 
354     if (log)
355         log->Printf ("OperatingSystemPython::CreateThread (tid = 0x%" PRIx64 ", context = 0x%" PRIx64 ") fetching register data from python", tid, context);
356 
357     if (m_interpreter && m_python_object_sp)
358     {
359         // First thing we have to do is get the API lock, and the run lock.  We're going to change the thread
360         // content of the process, and we're going to use python, which requires the API lock to do it.
361         // So get & hold that.  This is a recursive lock so we can grant it to any Python code called on the stack below us.
362         Target &target = m_process->GetTarget();
363         Mutex::Locker api_locker (target.GetAPIMutex());
364 
365         auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure thread_info_dict stays alive
366         PythonDictionary thread_info_dict (m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context));
367         if (thread_info_dict)
368         {
369             ThreadList core_threads(m_process);
370             ThreadList &thread_list = m_process->GetThreadList();
371             bool did_create = false;
372             ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_info_dict, core_threads, thread_list, &did_create));
373             if (did_create)
374                 thread_list.AddThread(thread_sp);
375             return thread_sp;
376         }
377     }
378     return ThreadSP();
379 }
380 
381 
382 
383 #endif // #ifndef LLDB_DISABLE_PYTHON
384