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