xref: /llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp (revision a4d8747d0f52e12b905b1dd61b117605021b14db)
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::auto_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         LogSP 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     LogSP 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     PythonList threads_list(m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp));
190     if (threads_list)
191     {
192         const uint32_t num_threads = threads_list.GetSize();
193         for (uint32_t i=0; i<num_threads; ++i)
194         {
195             PythonDictionary thread_dict(threads_list.GetItemAtIndex(i));
196             if (thread_dict)
197             {
198                 ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_dict, &old_thread_list, NULL));
199                 if (thread_sp)
200                     new_thread_list.AddThread(thread_sp);
201             }
202         }
203     }
204     else
205     {
206         new_thread_list = old_thread_list;
207     }
208     return new_thread_list.GetSize(false) > 0;
209 }
210 
211 ThreadSP
212 OperatingSystemPython::CreateThreadFromThreadInfo (PythonDictionary &thread_dict, ThreadList *old_thread_list_ptr, bool *did_create_ptr)
213 {
214     ThreadSP thread_sp;
215     if (thread_dict)
216     {
217         PythonString tid_pystr("tid");
218         PythonString name_pystr("name");
219         PythonString queue_pystr("queue");
220         PythonString state_pystr("state");
221         PythonString stop_reason_pystr("stop_reason");
222         PythonString reg_data_addr_pystr ("register_data_addr");
223 
224         const tid_t tid = thread_dict.GetItemForKeyAsInteger (tid_pystr, LLDB_INVALID_THREAD_ID);
225         const addr_t reg_data_addr = thread_dict.GetItemForKeyAsInteger (reg_data_addr_pystr, LLDB_INVALID_ADDRESS);
226         const char *name = thread_dict.GetItemForKeyAsString (name_pystr);
227         const char *queue = thread_dict.GetItemForKeyAsString (queue_pystr);
228         //const char *state = thread_dict.GetItemForKeyAsString (state_pystr);
229         //const char *stop_reason = thread_dict.GetItemForKeyAsString (stop_reason_pystr);
230 
231         if (old_thread_list_ptr)
232             thread_sp = old_thread_list_ptr->FindThreadByID (tid, false);
233         if (!thread_sp)
234         {
235             if (did_create_ptr)
236                 *did_create_ptr = true;
237             thread_sp.reset (new ThreadMemory (*m_process,
238                                                tid,
239                                                name,
240                                                queue,
241                                                reg_data_addr));
242         }
243     }
244     return thread_sp;
245 }
246 
247 
248 
249 void
250 OperatingSystemPython::ThreadWasSelected (Thread *thread)
251 {
252 }
253 
254 RegisterContextSP
255 OperatingSystemPython::CreateRegisterContextForThread (Thread *thread, addr_t reg_data_addr)
256 {
257     RegisterContextSP reg_ctx_sp;
258     if (!m_interpreter || !m_python_object_sp || !thread)
259         return RegisterContextSP();
260 
261     // First thing we have to do is get the API lock, and the run lock.  We're going to change the thread
262     // content of the process, and we're going to use python, which requires the API lock to do it.
263     // So get & hold that.  This is a recursive lock so we can grant it to any Python code called on the stack below us.
264     Target &target = m_process->GetTarget();
265     Mutex::Locker api_locker (target.GetAPIMutex());
266 
267     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
268 
269     if (reg_data_addr != LLDB_INVALID_ADDRESS)
270     {
271         // The registers data is in contiguous memory, just create the register
272         // context using the address provided
273         if (log)
274             log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64 ") creating memory register context", thread->GetID(), reg_data_addr);
275         reg_ctx_sp.reset (new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), reg_data_addr));
276     }
277     else
278     {
279         // No register data address is provided, query the python plug-in to let
280         // it make up the data as it sees fit
281         if (log)
282             log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ") fetching register data from python", thread->GetID());
283 
284         PythonString reg_context_data(m_interpreter->OSPlugin_RegisterContextData (m_python_object_sp, thread->GetID()));
285         if (reg_context_data)
286         {
287             DataBufferSP data_sp (new DataBufferHeap (reg_context_data.GetString(),
288                                                       reg_context_data.GetSize()));
289             if (data_sp->GetByteSize())
290             {
291                 RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), LLDB_INVALID_ADDRESS);
292                 if (reg_ctx_memory)
293                 {
294                     reg_ctx_sp.reset(reg_ctx_memory);
295                     reg_ctx_memory->SetAllRegisterData (data_sp);
296                 }
297             }
298         }
299     }
300     return reg_ctx_sp;
301 }
302 
303 StopInfoSP
304 OperatingSystemPython::CreateThreadStopReason (lldb_private::Thread *thread)
305 {
306     // We should have gotten the thread stop info from the dictionary of data for
307     // the thread in the initial call to get_thread_info(), this should have been
308     // cached so we can return it here
309     StopInfoSP stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
310     return stop_info_sp;
311 }
312 
313 lldb::ThreadSP
314 OperatingSystemPython::CreateThread (lldb::tid_t tid, addr_t context)
315 {
316     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
317 
318     if (log)
319         log->Printf ("OperatingSystemPython::CreateThread (tid = 0x%" PRIx64 ", context = 0x%" PRIx64 ") fetching register data from python", tid, context);
320 
321     if (m_interpreter && m_python_object_sp)
322     {
323         // First thing we have to do is get the API lock, and the run lock.  We're going to change the thread
324         // content of the process, and we're going to use python, which requires the API lock to do it.
325         // So get & hold that.  This is a recursive lock so we can grant it to any Python code called on the stack below us.
326         Target &target = m_process->GetTarget();
327         Mutex::Locker api_locker (target.GetAPIMutex());
328 
329         PythonDictionary thread_info_dict (m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context));
330         if (thread_info_dict)
331         {
332             ThreadList &thread_list = m_process->GetThreadList();
333             bool did_create = false;
334             ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_info_dict, &thread_list, &did_create));
335             if (did_create)
336                 thread_list.AddThread(thread_sp);
337             return thread_sp;
338         }
339     }
340     return ThreadSP();
341 }
342 
343 
344 
345 #endif // #ifndef LLDB_DISABLE_PYTHON
346