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