1 //===-- OperatingSystemPython.cpp --------------------------------*- C++-*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLDB_DISABLE_PYTHON
12 #include "OperatingSystemPython.h"
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"
39 using namespace lldb_private;
41 void OperatingSystemPython::Initialize() {
42 PluginManager::RegisterPlugin(GetPluginNameStatic(),
43 GetPluginDescriptionStatic(), CreateInstance,
47 void OperatingSystemPython::Terminate() {
48 PluginManager::UnregisterPlugin(CreateInstance);
51 OperatingSystem *OperatingSystemPython::CreateInstance(Process *process,
53 // Python OperatingSystem plug-ins must be requested by name, so force must
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();
65 ConstString OperatingSystemPython::GetPluginNameStatic() {
66 static ConstString g_name("python");
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.";
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() {
81 TargetSP target_sp = process->CalculateTarget();
85 target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
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));
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;
116 OperatingSystemPython::~OperatingSystemPython() {}
118 DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() {
119 if (m_register_info_ap.get() == NULL) {
120 if (!m_interpreter || !m_python_object_sp)
122 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
125 log->Printf("OperatingSystemPython::GetDynamicRegisterInfo() fetching "
126 "thread register definitions from python for pid %" PRIu64,
129 StructuredData::DictionarySP dictionary =
130 m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp);
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);
139 return m_register_info_ap.get();
142 //------------------------------------------------------------------
143 // PluginInterface protocol
144 //------------------------------------------------------------------
145 ConstString OperatingSystemPython::GetPluginName() {
146 return GetPluginNameStatic();
149 uint32_t OperatingSystemPython::GetPluginVersion() { return 1; }
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)
157 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
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.
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.
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(),
173 auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
176 log->Printf("OperatingSystemPython::UpdateThreadList() fetching thread "
177 "data from python for pid %" PRIu64,
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
183 StructuredData::ArraySP threads_list =
184 m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp);
186 const uint32_t num_cores = core_thread_list.GetSize(false);
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);
195 threads_list->Dump(strm);
196 log->Printf("threads_list = %s", strm.GetData());
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()) {
205 CreateThreadFromThreadInfo(*thread_dict, core_thread_list,
206 old_thread_list, core_used_map, NULL));
208 new_thread_list.AddThread(thread_sp);
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);
225 return new_thread_list.GetSize(false) > 0;
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) {
233 tid_t tid = LLDB_INVALID_THREAD_ID;
234 if (!thread_dict.GetValueForKeyAsInteger("tid", tid))
237 uint32_t core_number;
238 addr_t reg_data_addr;
239 llvm::StringRef name;
240 llvm::StringRef queue;
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);
248 // See if a thread already exists for "tid"
249 thread_sp = old_thread_list.FindThreadByID(tid, false);
251 // A thread already does exist for "tid", make sure it was an operating
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.
264 *did_create_ptr = true;
266 new ThreadMemory(*m_process, tid, name, queue, reg_data_addr));
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
275 if (core_number < core_used_map.size())
276 core_used_map[core_number] = true;
278 ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread());
279 if (backing_core_thread_sp) {
280 thread_sp->SetBackingThread(backing_core_thread_sp);
282 thread_sp->SetBackingThread(core_thread_sp);
289 void OperatingSystemPython::ThreadWasSelected(Thread *thread) {}
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)
298 if (!IsOperatingSystemPluginThread(thread->shared_from_this()))
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.
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.
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(),
315 auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
317 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
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
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));
330 // No register data address is provided, query the python plug-in to let it
331 // make up the data as it sees fit
333 log->Printf("OperatingSystemPython::CreateRegisterContextForThread (tid "
334 "= 0x%" PRIx64 ", 0x%" PRIx64
335 ") fetching register data from python",
336 thread->GetID(), thread->GetProtocolID());
338 StructuredData::StringSP reg_context_data =
339 m_interpreter->OSPlugin_RegisterContextData(m_python_object_sp,
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);
354 // if we still have no register data, fallback on a dummy context to avoid
358 log->Printf("OperatingSystemPython::CreateRegisterContextForThread (tid "
359 "= 0x%" PRIx64 ") forcing a dummy register context",
361 reg_ctx_sp.reset(new RegisterContextDummy(
362 *thread, 0, target.GetArchitecture().GetAddressByteSize()));
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
373 stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
377 lldb::ThreadSP OperatingSystemPython::CreateThread(lldb::tid_t tid,
379 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
382 log->Printf("OperatingSystemPython::CreateThread (tid = 0x%" PRIx64
383 ", context = 0x%" PRIx64 ") fetching register data from python",
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
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.
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(),
402 auto interpreter_lock = m_interpreter->AcquireInterpreterLock();
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;
412 CreateThreadFromThreadInfo(*thread_info_dict, core_threads,
413 thread_list, core_used_map, &did_create));
415 thread_list.AddThread(thread_sp);
422 #endif // #ifndef LLDB_DISABLE_PYTHON