xref: /llvm-project/lldb/source/Plugins/OperatingSystem/Python/OperatingSystemPython.cpp (revision 4e26cf2cfb2b140a33ec236153cb2f23b5c44127)
1 //===-- OperatingSystemPython.cpp --------------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Host/Config.h"
10 
11 #if LLDB_ENABLE_PYTHON
12 
13 #include "OperatingSystemPython.h"
14 
15 #include "Plugins/Process/Utility/DynamicRegisterInfo.h"
16 #include "Plugins/Process/Utility/RegisterContextDummy.h"
17 #include "Plugins/Process/Utility/RegisterContextMemory.h"
18 #include "Plugins/Process/Utility/ThreadMemory.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/ValueObjectVariable.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/ScriptInterpreter.h"
25 #include "lldb/Symbol/ObjectFile.h"
26 #include "lldb/Symbol/VariableList.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Target/ThreadList.h"
32 #include "lldb/Utility/DataBufferHeap.h"
33 #include "lldb/Utility/RegisterValue.h"
34 #include "lldb/Utility/StreamString.h"
35 #include "lldb/Utility/StructuredData.h"
36 
37 #include <memory>
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 
42 void OperatingSystemPython::Initialize() {
43   PluginManager::RegisterPlugin(GetPluginNameStatic(),
44                                 GetPluginDescriptionStatic(), CreateInstance,
45                                 nullptr);
46 }
47 
48 void OperatingSystemPython::Terminate() {
49   PluginManager::UnregisterPlugin(CreateInstance);
50 }
51 
52 OperatingSystem *OperatingSystemPython::CreateInstance(Process *process,
53                                                        bool force) {
54   // Python OperatingSystem plug-ins must be requested by name, so force must
55   // be true
56   FileSpec python_os_plugin_spec(process->GetPythonOSPluginPath());
57   if (python_os_plugin_spec &&
58       FileSystem::Instance().Exists(python_os_plugin_spec)) {
59     std::unique_ptr<OperatingSystemPython> os_up(
60         new OperatingSystemPython(process, python_os_plugin_spec));
61     if (os_up.get() && os_up->IsValid())
62       return os_up.release();
63   }
64   return nullptr;
65 }
66 
67 ConstString OperatingSystemPython::GetPluginNameStatic() {
68   static ConstString g_name("python");
69   return g_name;
70 }
71 
72 const char *OperatingSystemPython::GetPluginDescriptionStatic() {
73   return "Operating system plug-in that gathers OS information from a python "
74          "class that implements the necessary OperatingSystem functionality.";
75 }
76 
77 OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process,
78                                              const FileSpec &python_module_path)
79     : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_up(),
80       m_interpreter(nullptr), m_python_object_sp() {
81   if (!process)
82     return;
83   TargetSP target_sp = process->CalculateTarget();
84   if (!target_sp)
85     return;
86   m_interpreter = target_sp->GetDebugger().GetScriptInterpreter();
87   if (m_interpreter) {
88 
89     std::string os_plugin_class_name(
90         python_module_path.GetFilename().AsCString(""));
91     if (!os_plugin_class_name.empty()) {
92       const bool init_session = false;
93       const bool allow_reload = true;
94       char python_module_path_cstr[PATH_MAX];
95       python_module_path.GetPath(python_module_path_cstr,
96                                  sizeof(python_module_path_cstr));
97       Status error;
98       if (m_interpreter->LoadScriptingModule(
99               python_module_path_cstr, allow_reload, init_session, error)) {
100         // Strip the ".py" extension if there is one
101         size_t py_extension_pos = os_plugin_class_name.rfind(".py");
102         if (py_extension_pos != std::string::npos)
103           os_plugin_class_name.erase(py_extension_pos);
104         // Add ".OperatingSystemPlugIn" to the module name to get a string like
105         // "modulename.OperatingSystemPlugIn"
106         os_plugin_class_name += ".OperatingSystemPlugIn";
107         StructuredData::ObjectSP object_sp =
108             m_interpreter->OSPlugin_CreatePluginObject(
109                 os_plugin_class_name.c_str(), process->CalculateProcess());
110         if (object_sp && object_sp->IsValid())
111           m_python_object_sp = object_sp;
112       }
113     }
114   }
115 }
116 
117 OperatingSystemPython::~OperatingSystemPython() {}
118 
119 DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() {
120   if (m_register_info_up == nullptr) {
121     if (!m_interpreter || !m_python_object_sp)
122       return nullptr;
123     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
124 
125     LLDB_LOGF(log,
126               "OperatingSystemPython::GetDynamicRegisterInfo() fetching "
127               "thread register definitions from python for pid %" PRIu64,
128               m_process->GetID());
129 
130     StructuredData::DictionarySP dictionary =
131         m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp);
132     if (!dictionary)
133       return nullptr;
134 
135     m_register_info_up.reset(new DynamicRegisterInfo(
136         *dictionary, m_process->GetTarget().GetArchitecture()));
137     assert(m_register_info_up->GetNumRegisters() > 0);
138     assert(m_register_info_up->GetNumRegisterSets() > 0);
139   }
140   return m_register_info_up.get();
141 }
142 
143 // PluginInterface protocol
144 ConstString OperatingSystemPython::GetPluginName() {
145   return GetPluginNameStatic();
146 }
147 
148 uint32_t OperatingSystemPython::GetPluginVersion() { return 1; }
149 
150 bool OperatingSystemPython::UpdateThreadList(ThreadList &old_thread_list,
151                                              ThreadList &core_thread_list,
152                                              ThreadList &new_thread_list) {
153   if (!m_interpreter || !m_python_object_sp)
154     return false;
155 
156   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
157 
158   // First thing we have to do is to try to get the API lock, and the
159   // interpreter lock. We're going to change the thread content of the process,
160   // and we're going to use python, which requires the API lock to do it. We
161   // need the interpreter lock to make sure thread_info_dict stays alive.
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> api_lock(target.GetAPIMutex(),
170                                                   std::defer_lock);
171   (void)api_lock.try_lock(); // See above.
172   auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
173 
174   LLDB_LOGF(log,
175             "OperatingSystemPython::UpdateThreadList() fetching thread "
176             "data from python for pid %" PRIu64,
177             m_process->GetID());
178 
179   // The threads that are in "core_thread_list" upon entry are the threads from
180   // the lldb_private::Process subclass, no memory threads will be in this
181   // list.
182   StructuredData::ArraySP threads_list =
183       m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp);
184 
185   const uint32_t num_cores = core_thread_list.GetSize(false);
186 
187   // Make a map so we can keep track of which cores were used from the
188   // core_thread list. Any real threads/cores that weren't used should later be
189   // put back into the "new_thread_list".
190   std::vector<bool> core_used_map(num_cores, false);
191   if (threads_list) {
192     if (log) {
193       StreamString strm;
194       threads_list->Dump(strm);
195       LLDB_LOGF(log, "threads_list = %s", strm.GetData());
196     }
197 
198     const uint32_t num_threads = threads_list->GetSize();
199     for (uint32_t i = 0; i < num_threads; ++i) {
200       StructuredData::ObjectSP thread_dict_obj =
201           threads_list->GetItemAtIndex(i);
202       if (auto thread_dict = thread_dict_obj->GetAsDictionary()) {
203         ThreadSP thread_sp(CreateThreadFromThreadInfo(
204             *thread_dict, core_thread_list, old_thread_list, core_used_map,
205             nullptr));
206         if (thread_sp)
207           new_thread_list.AddThread(thread_sp);
208       }
209     }
210   }
211 
212   // Any real core threads that didn't end up backing a memory thread should
213   // still be in the main thread list, and they should be inserted at the
214   // beginning of the list
215   uint32_t insert_idx = 0;
216   for (uint32_t core_idx = 0; core_idx < num_cores; ++core_idx) {
217     if (!core_used_map[core_idx]) {
218       new_thread_list.InsertThread(
219           core_thread_list.GetThreadAtIndex(core_idx, false), insert_idx);
220       ++insert_idx;
221     }
222   }
223 
224   return new_thread_list.GetSize(false) > 0;
225 }
226 
227 ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo(
228     StructuredData::Dictionary &thread_dict, ThreadList &core_thread_list,
229     ThreadList &old_thread_list, std::vector<bool> &core_used_map,
230     bool *did_create_ptr) {
231   ThreadSP thread_sp;
232   tid_t tid = LLDB_INVALID_THREAD_ID;
233   if (!thread_dict.GetValueForKeyAsInteger("tid", tid))
234     return ThreadSP();
235 
236   uint32_t core_number;
237   addr_t reg_data_addr;
238   llvm::StringRef name;
239   llvm::StringRef queue;
240 
241   thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX);
242   thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr,
243                                       LLDB_INVALID_ADDRESS);
244   thread_dict.GetValueForKeyAsString("name", name);
245   thread_dict.GetValueForKeyAsString("queue", queue);
246 
247   // See if a thread already exists for "tid"
248   thread_sp = old_thread_list.FindThreadByID(tid, false);
249   if (thread_sp) {
250     // A thread already does exist for "tid", make sure it was an operating
251     // system
252     // plug-in generated thread.
253     if (!IsOperatingSystemPluginThread(thread_sp)) {
254       // We have thread ID overlap between the protocol threads and the
255       // operating system threads, clear the thread so we create an operating
256       // system thread for this.
257       thread_sp.reset();
258     }
259   }
260 
261   if (!thread_sp) {
262     if (did_create_ptr)
263       *did_create_ptr = true;
264     thread_sp = std::make_shared<ThreadMemory>(*m_process, tid, name, queue,
265                                                reg_data_addr);
266   }
267 
268   if (core_number < core_thread_list.GetSize(false)) {
269     ThreadSP core_thread_sp(
270         core_thread_list.GetThreadAtIndex(core_number, false));
271     if (core_thread_sp) {
272       // Keep track of which cores were set as the backing thread for memory
273       // threads...
274       if (core_number < core_used_map.size())
275         core_used_map[core_number] = true;
276 
277       ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread());
278       if (backing_core_thread_sp) {
279         thread_sp->SetBackingThread(backing_core_thread_sp);
280       } else {
281         thread_sp->SetBackingThread(core_thread_sp);
282       }
283     }
284   }
285   return thread_sp;
286 }
287 
288 void OperatingSystemPython::ThreadWasSelected(Thread *thread) {}
289 
290 RegisterContextSP
291 OperatingSystemPython::CreateRegisterContextForThread(Thread *thread,
292                                                       addr_t reg_data_addr) {
293   RegisterContextSP reg_ctx_sp;
294   if (!m_interpreter || !m_python_object_sp || !thread)
295     return reg_ctx_sp;
296 
297   if (!IsOperatingSystemPluginThread(thread->shared_from_this()))
298     return reg_ctx_sp;
299 
300   // First thing we have to do is to try to get the API lock, and the
301   // interpreter lock. We're going to change the thread content of the process,
302   // and we're going to use python, which requires the API lock to do it. We
303   // need the interpreter lock to make sure thread_info_dict stays alive.
304   //
305   // If someone already has the API lock, that is ok, we just want to avoid
306   // external code from making new API calls while this call is happening.
307   //
308   // This is a recursive lock so we can grant it to any Python code called on
309   // the stack below us.
310   Target &target = m_process->GetTarget();
311   std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
312                                                   std::defer_lock);
313   (void)api_lock.try_lock(); // See above.
314   auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
315 
316   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
317 
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     LLDB_LOGF(log,
322               "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 = std::make_shared<RegisterContextMemory>(
327         *thread, 0, *GetDynamicRegisterInfo(), reg_data_addr);
328   } else {
329     // No register data address is provided, query the python plug-in to let it
330     // make up the data as it sees fit
331     LLDB_LOGF(log,
332               "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     LLDB_LOGF(log,
357               "OperatingSystemPython::CreateRegisterContextForThread (tid "
358               "= 0x%" PRIx64 ") forcing a dummy register context",
359               thread->GetID());
360     reg_ctx_sp = std::make_shared<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   LLDB_LOGF(log,
381             "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 to try to get the API lock, and the
387     // interpreter lock. We're going to change the thread content of the
388     // process, and we're going to use python, which requires the API lock to
389     // do it. We need the interpreter lock to make sure thread_info_dict stays
390     // alive.
391     //
392     // If someone already has the API lock, that is ok, we just want to avoid
393     // external code from making new API calls while this call is happening.
394     //
395     // This is a recursive lock so we can grant it to any Python code called on
396     // the stack below us.
397     Target &target = m_process->GetTarget();
398     std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(),
399                                                     std::defer_lock);
400     (void)api_lock.try_lock(); // See above.
401     auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
402 
403     StructuredData::DictionarySP thread_info_dict =
404         m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context);
405     std::vector<bool> core_used_map;
406     if (thread_info_dict) {
407       ThreadList core_threads(m_process);
408       ThreadList &thread_list = m_process->GetThreadList();
409       bool did_create = false;
410       ThreadSP thread_sp(
411           CreateThreadFromThreadInfo(*thread_info_dict, core_threads,
412                                      thread_list, core_used_map, &did_create));
413       if (did_create)
414         thread_list.AddThread(thread_sp);
415       return thread_sp;
416     }
417   }
418   return ThreadSP();
419 }
420 
421 #endif // #if LLDB_ENABLE_PYTHON
422