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