xref: /llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp (revision d04f0edad9afe46f18b86de9199884ea1dceb220)
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()));
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 to try to get the API lock, and the run lock.
182     // We're going to change the thread content of the process, and we're going
183     // to use python, which requires the API lock to do it.
184     //
185     // If someone already has the API lock, that is ok, we just want to avoid
186     // external code from making new API calls while this call is happening.
187     //
188     // This is a recursive lock so we can grant it to any Python code called on
189     // the stack below us.
190     Target &target = m_process->GetTarget();
191     Mutex::Locker api_locker;
192     api_locker.TryLock(target.GetAPIMutex());
193 
194     if (log)
195         log->Printf ("OperatingSystemPython::UpdateThreadList() fetching thread data from python for pid %" PRIu64, m_process->GetID());
196 
197     // The threads that are in "new_thread_list" upon entry are the threads from the
198     // lldb_private::Process subclass, no memory threads will be in this list.
199 
200     auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure threads_list stays alive
201     StructuredData::ArraySP threads_list = m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp);
202 
203     const uint32_t num_cores = core_thread_list.GetSize(false);
204 
205     // Make a map so we can keep track of which cores were used from the
206     // core_thread list. Any real threads/cores that weren't used should
207     // later be put back into the "new_thread_list".
208     std::vector<bool> core_used_map(num_cores, false);
209     if (threads_list)
210     {
211         if (log)
212         {
213             StreamString strm;
214             threads_list->Dump(strm);
215             log->Printf("threads_list = %s", strm.GetString().c_str());
216         }
217 
218         const uint32_t num_threads = threads_list->GetSize();
219         for (uint32_t i = 0; i < num_threads; ++i)
220         {
221             StructuredData::ObjectSP thread_dict_obj = threads_list->GetItemAtIndex(i);
222             if (auto thread_dict = thread_dict_obj->GetAsDictionary())
223             {
224                 ThreadSP thread_sp(CreateThreadFromThreadInfo(*thread_dict, core_thread_list, old_thread_list, core_used_map, NULL));
225                 if (thread_sp)
226                     new_thread_list.AddThread(thread_sp);
227             }
228         }
229     }
230 
231     // Any real core threads that didn't end up backing a memory thread should
232     // still be in the main thread list, and they should be inserted at the beginning
233     // of the list
234     uint32_t insert_idx = 0;
235     for (uint32_t core_idx = 0; core_idx < num_cores; ++core_idx)
236     {
237         if (core_used_map[core_idx] == false)
238         {
239             new_thread_list.InsertThread (core_thread_list.GetThreadAtIndex(core_idx, false), insert_idx);
240             ++insert_idx;
241         }
242     }
243 
244     return new_thread_list.GetSize(false) > 0;
245 }
246 
247 ThreadSP
248 OperatingSystemPython::CreateThreadFromThreadInfo(StructuredData::Dictionary &thread_dict, ThreadList &core_thread_list,
249                                                   ThreadList &old_thread_list, std::vector<bool> &core_used_map, bool *did_create_ptr)
250 {
251     ThreadSP thread_sp;
252     tid_t tid = LLDB_INVALID_THREAD_ID;
253     if (!thread_dict.GetValueForKeyAsInteger("tid", tid))
254         return ThreadSP();
255 
256     uint32_t core_number;
257     addr_t reg_data_addr;
258     std::string name;
259     std::string queue;
260 
261     thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX);
262     thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr, LLDB_INVALID_ADDRESS);
263     thread_dict.GetValueForKeyAsString("name", name);
264     thread_dict.GetValueForKeyAsString("queue", queue);
265 
266     // See if a thread already exists for "tid"
267     thread_sp = old_thread_list.FindThreadByID(tid, false);
268     if (thread_sp)
269     {
270         // A thread already does exist for "tid", make sure it was an operating system
271         // plug-in generated thread.
272         if (!IsOperatingSystemPluginThread(thread_sp))
273         {
274             // We have thread ID overlap between the protocol threads and the
275             // operating system threads, clear the thread so we create an
276             // operating system thread for this.
277             thread_sp.reset();
278         }
279     }
280 
281     if (!thread_sp)
282     {
283         if (did_create_ptr)
284             *did_create_ptr = true;
285         thread_sp.reset(new ThreadMemory(*m_process, tid, name.c_str(), queue.c_str(), reg_data_addr));
286     }
287 
288     if (core_number < core_thread_list.GetSize(false))
289     {
290         ThreadSP core_thread_sp(core_thread_list.GetThreadAtIndex(core_number, false));
291         if (core_thread_sp)
292         {
293             // Keep track of which cores were set as the backing thread for memory threads...
294             if (core_number < core_used_map.size())
295                 core_used_map[core_number] = true;
296 
297             ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread());
298             if (backing_core_thread_sp)
299             {
300                 thread_sp->SetBackingThread(backing_core_thread_sp);
301             }
302             else
303             {
304                 thread_sp->SetBackingThread(core_thread_sp);
305             }
306         }
307     }
308     return thread_sp;
309 }
310 
311 
312 
313 void
314 OperatingSystemPython::ThreadWasSelected (Thread *thread)
315 {
316 }
317 
318 RegisterContextSP
319 OperatingSystemPython::CreateRegisterContextForThread (Thread *thread, addr_t reg_data_addr)
320 {
321     RegisterContextSP reg_ctx_sp;
322     if (!m_interpreter || !m_python_object_sp || !thread)
323         return reg_ctx_sp;
324 
325     if (!IsOperatingSystemPluginThread(thread->shared_from_this()))
326         return reg_ctx_sp;
327 
328     // First thing we have to do is get the API lock, and the run lock.  We're going to change the thread
329     // content of the process, and we're going to use python, which requires the API lock to do it.
330     // So get & hold that.  This is a recursive lock so we can grant it to any Python code called on the stack below us.
331     Target &target = m_process->GetTarget();
332     Mutex::Locker api_locker (target.GetAPIMutex());
333 
334     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
335 
336     auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure python objects stays alive
337     if (reg_data_addr != LLDB_INVALID_ADDRESS)
338     {
339         // The registers data is in contiguous memory, just create the register
340         // context using the address provided
341         if (log)
342             log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ", 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64 ") creating memory register context",
343                          thread->GetID(),
344                          thread->GetProtocolID(),
345                          reg_data_addr);
346         reg_ctx_sp.reset (new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), reg_data_addr));
347     }
348     else
349     {
350         // No register data address is provided, query the python plug-in to let
351         // it make up the data as it sees fit
352         if (log)
353             log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ", 0x%" PRIx64 ") fetching register data from python",
354                          thread->GetID(),
355                          thread->GetProtocolID());
356 
357         StructuredData::StringSP reg_context_data = m_interpreter->OSPlugin_RegisterContextData(m_python_object_sp, thread->GetID());
358         if (reg_context_data)
359         {
360             std::string value = reg_context_data->GetValue();
361             DataBufferSP data_sp(new DataBufferHeap(value.c_str(), value.length()));
362             if (data_sp->GetByteSize())
363             {
364                 RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), LLDB_INVALID_ADDRESS);
365                 if (reg_ctx_memory)
366                 {
367                     reg_ctx_sp.reset(reg_ctx_memory);
368                     reg_ctx_memory->SetAllRegisterData (data_sp);
369                 }
370             }
371         }
372     }
373     // if we still have no register data, fallback on a dummy context to avoid crashing
374     if (!reg_ctx_sp)
375     {
376         if (log)
377             log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ") forcing a dummy register context", thread->GetID());
378         reg_ctx_sp.reset(new RegisterContextDummy(*thread,0,target.GetArchitecture().GetAddressByteSize()));
379     }
380     return reg_ctx_sp;
381 }
382 
383 StopInfoSP
384 OperatingSystemPython::CreateThreadStopReason (lldb_private::Thread *thread)
385 {
386     // We should have gotten the thread stop info from the dictionary of data for
387     // the thread in the initial call to get_thread_info(), this should have been
388     // cached so we can return it here
389     StopInfoSP stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
390     return stop_info_sp;
391 }
392 
393 lldb::ThreadSP
394 OperatingSystemPython::CreateThread (lldb::tid_t tid, addr_t context)
395 {
396     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
397 
398     if (log)
399         log->Printf ("OperatingSystemPython::CreateThread (tid = 0x%" PRIx64 ", context = 0x%" PRIx64 ") fetching register data from python", tid, context);
400 
401     if (m_interpreter && m_python_object_sp)
402     {
403         // First thing we have to do is get the API lock, and the run lock.  We're going to change the thread
404         // content of the process, and we're going to use python, which requires the API lock to do it.
405         // So get & hold that.  This is a recursive lock so we can grant it to any Python code called on the stack below us.
406         Target &target = m_process->GetTarget();
407         Mutex::Locker api_locker (target.GetAPIMutex());
408 
409         auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure thread_info_dict stays alive
410         StructuredData::DictionarySP thread_info_dict = m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context);
411         std::vector<bool> core_used_map;
412         if (thread_info_dict)
413         {
414             ThreadList core_threads(m_process);
415             ThreadList &thread_list = m_process->GetThreadList();
416             bool did_create = false;
417             ThreadSP thread_sp(CreateThreadFromThreadInfo(*thread_info_dict, core_threads, thread_list, core_used_map, &did_create));
418             if (did_create)
419                 thread_list.AddThread(thread_sp);
420             return thread_sp;
421         }
422     }
423     return ThreadSP();
424 }
425 
426 
427 
428 #endif // #ifndef LLDB_DISABLE_PYTHON
429