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