1 //===-- ScriptInterpreterPython.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 #include "lldb/lldb-enumerations.h"
11 
12 #if LLDB_ENABLE_PYTHON
13 
14 // LLDB Python header must be included first
15 #include "lldb-python.h"
16 
17 #include "PythonDataObjects.h"
18 #include "PythonReadline.h"
19 #include "ScriptInterpreterPythonImpl.h"
20 #include "lldb/API/SBFrame.h"
21 #include "lldb/API/SBValue.h"
22 #include "lldb/Breakpoint/StoppointCallbackContext.h"
23 #include "lldb/Breakpoint/WatchpointOptions.h"
24 #include "lldb/Core/Communication.h"
25 #include "lldb/Core/Debugger.h"
26 #include "lldb/Core/PluginManager.h"
27 #include "lldb/Core/ValueObject.h"
28 #include "lldb/DataFormatters/TypeSummary.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/HostInfo.h"
31 #include "lldb/Host/Pipe.h"
32 #include "lldb/Interpreter/CommandInterpreter.h"
33 #include "lldb/Interpreter/CommandReturnObject.h"
34 #include "lldb/Target/Thread.h"
35 #include "lldb/Target/ThreadPlan.h"
36 #include "lldb/Utility/ReproducerInstrumentation.h"
37 #include "lldb/Utility/Timer.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/FormatAdapters.h"
43 
44 #include <memory>
45 #include <mutex>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string>
49 
50 using namespace lldb;
51 using namespace lldb_private;
52 using namespace lldb_private::python;
53 using llvm::Expected;
54 
55 LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
56 
57 // Defined in the SWIG source file
58 #if PY_MAJOR_VERSION >= 3
59 extern "C" PyObject *PyInit__lldb(void);
60 
61 #define LLDBSwigPyInit PyInit__lldb
62 
63 #else
64 extern "C" void init_lldb(void);
65 
66 #define LLDBSwigPyInit init_lldb
67 #endif
68 
69 // These prototypes are the Pythonic implementations of the required callbacks.
70 // Although these are scripting-language specific, their definition depends on
71 // the public API.
72 
73 #pragma clang diagnostic push
74 #pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
75 
76 // Disable warning C4190: 'LLDBSwigPythonBreakpointCallbackFunction' has
77 // C-linkage specified, but returns UDT 'llvm::Expected<bool>' which is
78 // incompatible with C
79 #if _MSC_VER
80 #pragma warning (push)
81 #pragma warning (disable : 4190)
82 #endif
83 
84 extern "C" llvm::Expected<bool> LLDBSwigPythonBreakpointCallbackFunction(
85     const char *python_function_name, const char *session_dictionary_name,
86     const lldb::StackFrameSP &sb_frame,
87     const lldb::BreakpointLocationSP &sb_bp_loc, StructuredDataImpl *args_impl);
88 
89 #if _MSC_VER
90 #pragma warning (pop)
91 #endif
92 
93 #pragma clang diagnostic pop
94 
95 extern "C" bool LLDBSwigPythonWatchpointCallbackFunction(
96     const char *python_function_name, const char *session_dictionary_name,
97     const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp);
98 
99 extern "C" bool LLDBSwigPythonCallTypeScript(
100     const char *python_function_name, void *session_dictionary,
101     const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper,
102     const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval);
103 
104 extern "C" void *
105 LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name,
106                                       const char *session_dictionary_name,
107                                       const lldb::ValueObjectSP &valobj_sp);
108 
109 extern "C" void *
110 LLDBSwigPythonCreateCommandObject(const char *python_class_name,
111                                   const char *session_dictionary_name,
112                                   const lldb::DebuggerSP debugger_sp);
113 
114 extern "C" void *LLDBSwigPythonCreateScriptedThreadPlan(
115     const char *python_class_name, const char *session_dictionary_name,
116     StructuredDataImpl *args_data,
117     std::string &error_string,
118     const lldb::ThreadPlanSP &thread_plan_sp);
119 
120 extern "C" bool LLDBSWIGPythonCallThreadPlan(void *implementor,
121                                              const char *method_name,
122                                              Event *event_sp, bool &got_error);
123 
124 extern "C" void *LLDBSwigPythonCreateScriptedBreakpointResolver(
125     const char *python_class_name, const char *session_dictionary_name,
126     lldb_private::StructuredDataImpl *args, lldb::BreakpointSP &bkpt_sp);
127 
128 extern "C" unsigned int
129 LLDBSwigPythonCallBreakpointResolver(void *implementor, const char *method_name,
130                                      lldb_private::SymbolContext *sym_ctx);
131 
132 extern "C" void *LLDBSwigPythonCreateScriptedStopHook(
133     TargetSP target_sp, const char *python_class_name,
134     const char *session_dictionary_name, lldb_private::StructuredDataImpl *args,
135     lldb_private::Status &error);
136 
137 extern "C" bool
138 LLDBSwigPythonStopHookCallHandleStop(void *implementor,
139                                      lldb::ExecutionContextRefSP exc_ctx,
140                                      lldb::StreamSP stream);
141 
142 extern "C" size_t LLDBSwigPython_CalculateNumChildren(void *implementor,
143                                                       uint32_t max);
144 
145 extern "C" void *LLDBSwigPython_GetChildAtIndex(void *implementor,
146                                                 uint32_t idx);
147 
148 extern "C" int LLDBSwigPython_GetIndexOfChildWithName(void *implementor,
149                                                       const char *child_name);
150 
151 extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data);
152 
153 extern lldb::ValueObjectSP
154 LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data);
155 
156 extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance(void *implementor);
157 
158 extern "C" bool
159 LLDBSwigPython_MightHaveChildrenSynthProviderInstance(void *implementor);
160 
161 extern "C" void *
162 LLDBSwigPython_GetValueSynthProviderInstance(void *implementor);
163 
164 extern "C" bool
165 LLDBSwigPythonCallCommand(const char *python_function_name,
166                           const char *session_dictionary_name,
167                           lldb::DebuggerSP &debugger, const char *args,
168                           lldb_private::CommandReturnObject &cmd_retobj,
169                           lldb::ExecutionContextRefSP exe_ctx_ref_sp);
170 
171 extern "C" bool
172 LLDBSwigPythonCallCommandObject(void *implementor, lldb::DebuggerSP &debugger,
173                                 const char *args,
174                                 lldb_private::CommandReturnObject &cmd_retobj,
175                                 lldb::ExecutionContextRefSP exe_ctx_ref_sp);
176 
177 extern "C" bool
178 LLDBSwigPythonCallModuleInit(const char *python_module_name,
179                              const char *session_dictionary_name,
180                              lldb::DebuggerSP &debugger);
181 
182 extern "C" void *
183 LLDBSWIGPythonCreateOSPlugin(const char *python_class_name,
184                              const char *session_dictionary_name,
185                              const lldb::ProcessSP &process_sp);
186 
187 extern "C" void *
188 LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name,
189                                      const char *session_dictionary_name);
190 
191 extern "C" void *
192 LLDBSwigPython_GetRecognizedArguments(void *implementor,
193                                       const lldb::StackFrameSP &frame_sp);
194 
195 extern "C" bool LLDBSWIGPythonRunScriptKeywordProcess(
196     const char *python_function_name, const char *session_dictionary_name,
197     lldb::ProcessSP &process, std::string &output);
198 
199 extern "C" bool LLDBSWIGPythonRunScriptKeywordThread(
200     const char *python_function_name, const char *session_dictionary_name,
201     lldb::ThreadSP &thread, std::string &output);
202 
203 extern "C" bool LLDBSWIGPythonRunScriptKeywordTarget(
204     const char *python_function_name, const char *session_dictionary_name,
205     lldb::TargetSP &target, std::string &output);
206 
207 extern "C" bool LLDBSWIGPythonRunScriptKeywordFrame(
208     const char *python_function_name, const char *session_dictionary_name,
209     lldb::StackFrameSP &frame, std::string &output);
210 
211 extern "C" bool LLDBSWIGPythonRunScriptKeywordValue(
212     const char *python_function_name, const char *session_dictionary_name,
213     lldb::ValueObjectSP &value, std::string &output);
214 
215 extern "C" void *
216 LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting,
217                                  const lldb::TargetSP &target_sp);
218 
GetPythonInterpreter(Debugger & debugger)219 static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
220   ScriptInterpreter *script_interpreter =
221       debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
222   return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
223 }
224 
225 static bool g_initialized = false;
226 
227 namespace {
228 
229 // Initializing Python is not a straightforward process.  We cannot control
230 // what external code may have done before getting to this point in LLDB,
231 // including potentially having already initialized Python, so we need to do a
232 // lot of work to ensure that the existing state of the system is maintained
233 // across our initialization.  We do this by using an RAII pattern where we
234 // save off initial state at the beginning, and restore it at the end
235 struct InitializePythonRAII {
236 public:
InitializePythonRAII__anon261b3de20111::InitializePythonRAII237   InitializePythonRAII()
238       : m_gil_state(PyGILState_UNLOCKED), m_was_already_initialized(false) {
239     InitializePythonHome();
240 
241 #ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
242     // Python's readline is incompatible with libedit being linked into lldb.
243     // Provide a patched version local to the embedded interpreter.
244     bool ReadlinePatched = false;
245     for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
246       if (strcmp(p->name, "readline") == 0) {
247         p->initfunc = initlldb_readline;
248         break;
249       }
250     }
251     if (!ReadlinePatched) {
252       PyImport_AppendInittab("readline", initlldb_readline);
253       ReadlinePatched = true;
254     }
255 #endif
256 
257     // Register _lldb as a built-in module.
258     PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
259 
260 // Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
261 // calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
262 // call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
263 #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
264     Py_InitializeEx(0);
265     InitializeThreadsPrivate();
266 #else
267     InitializeThreadsPrivate();
268     Py_InitializeEx(0);
269 #endif
270   }
271 
~InitializePythonRAII__anon261b3de20111::InitializePythonRAII272   ~InitializePythonRAII() {
273     if (m_was_already_initialized) {
274       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
275       LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
276                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
277       PyGILState_Release(m_gil_state);
278     } else {
279       // We initialized the threads in this function, just unlock the GIL.
280       PyEval_SaveThread();
281     }
282   }
283 
284 private:
InitializePythonHome__anon261b3de20111::InitializePythonRAII285   void InitializePythonHome() {
286 #if LLDB_EMBED_PYTHON_HOME
287 #if PY_MAJOR_VERSION >= 3
288     typedef wchar_t* str_type;
289 #else
290     typedef char* str_type;
291 #endif
292     static str_type g_python_home = []() -> str_type {
293       const char *lldb_python_home = LLDB_PYTHON_HOME;
294       const char *absolute_python_home = nullptr;
295       llvm::SmallString<64> path;
296       if (llvm::sys::path::is_absolute(lldb_python_home)) {
297         absolute_python_home = lldb_python_home;
298       } else {
299         FileSpec spec = HostInfo::GetShlibDir();
300         if (!spec)
301           return nullptr;
302         spec.GetPath(path);
303         llvm::sys::path::append(path, lldb_python_home);
304         absolute_python_home = path.c_str();
305       }
306 #if PY_MAJOR_VERSION >= 3
307       size_t size = 0;
308       return Py_DecodeLocale(absolute_python_home, &size);
309 #else
310       return strdup(absolute_python_home);
311 #endif
312     }();
313     if (g_python_home != nullptr) {
314       Py_SetPythonHome(g_python_home);
315     }
316 #else
317 #if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
318     // For Darwin, the only Python version supported is the one shipped in the
319     // OS OS and linked with lldb. Other installation of Python may have higher
320     // priorities in the path, overriding PYTHONHOME and causing
321     // problems/incompatibilities. In order to avoid confusion, always hardcode
322     // the PythonHome to be right, as it's not going to change.
323     static char path[] =
324         "/System/Library/Frameworks/Python.framework/Versions/2.7";
325     Py_SetPythonHome(path);
326 #endif
327 #endif
328   }
329 
InitializeThreadsPrivate__anon261b3de20111::InitializePythonRAII330   void InitializeThreadsPrivate() {
331 // Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
332 // so there is no way to determine whether the embedded interpreter
333 // was already initialized by some external code. `PyEval_ThreadsInitialized`
334 // would always return `true` and `PyGILState_Ensure/Release` flow would be
335 // executed instead of unlocking GIL with `PyEval_SaveThread`. When
336 // an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
337 #if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
338     // The only case we should go further and acquire the GIL: it is unlocked.
339     if (PyGILState_Check())
340       return;
341 #endif
342 
343     if (PyEval_ThreadsInitialized()) {
344       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
345 
346       m_was_already_initialized = true;
347       m_gil_state = PyGILState_Ensure();
348       LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
349                 m_gil_state == PyGILState_UNLOCKED ? "un" : "");
350       return;
351     }
352 
353     // InitThreads acquires the GIL if it hasn't been called before.
354     PyEval_InitThreads();
355   }
356 
357   TerminalState m_stdin_tty_state;
358   PyGILState_STATE m_gil_state;
359   bool m_was_already_initialized;
360 };
361 } // namespace
362 
ComputePythonDirForApple(llvm::SmallVectorImpl<char> & path)363 void ScriptInterpreterPython::ComputePythonDirForApple(
364     llvm::SmallVectorImpl<char> &path) {
365   auto style = llvm::sys::path::Style::posix;
366 
367   llvm::StringRef path_ref(path.begin(), path.size());
368   auto rbegin = llvm::sys::path::rbegin(path_ref, style);
369   auto rend = llvm::sys::path::rend(path_ref);
370   auto framework = std::find(rbegin, rend, "LLDB.framework");
371   if (framework == rend) {
372     ComputePythonDir(path);
373     return;
374   }
375   path.resize(framework - rend);
376   llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
377 }
378 
ComputePythonDir(llvm::SmallVectorImpl<char> & path)379 void ScriptInterpreterPython::ComputePythonDir(
380     llvm::SmallVectorImpl<char> &path) {
381   // Build the path by backing out of the lib dir, then building with whatever
382   // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
383   // x86_64, or bin on Windows).
384   llvm::sys::path::remove_filename(path);
385   llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
386 
387 #if defined(_WIN32)
388   // This will be injected directly through FileSpec.GetDirectory().SetString(),
389   // so we need to normalize manually.
390   std::replace(path.begin(), path.end(), '\\', '/');
391 #endif
392 }
393 
GetPythonDir()394 FileSpec ScriptInterpreterPython::GetPythonDir() {
395   static FileSpec g_spec = []() {
396     FileSpec spec = HostInfo::GetShlibDir();
397     if (!spec)
398       return FileSpec();
399     llvm::SmallString<64> path;
400     spec.GetPath(path);
401 
402 #if defined(__APPLE__)
403     ComputePythonDirForApple(path);
404 #else
405     ComputePythonDir(path);
406 #endif
407     spec.GetDirectory().SetString(path);
408     return spec;
409   }();
410   return g_spec;
411 }
412 
GetPluginNameStatic()413 lldb_private::ConstString ScriptInterpreterPython::GetPluginNameStatic() {
414   static ConstString g_name("script-python");
415   return g_name;
416 }
417 
GetPluginDescriptionStatic()418 const char *ScriptInterpreterPython::GetPluginDescriptionStatic() {
419   return "Embedded Python interpreter";
420 }
421 
Initialize()422 void ScriptInterpreterPython::Initialize() {
423   static llvm::once_flag g_once_flag;
424 
425   llvm::call_once(g_once_flag, []() {
426     PluginManager::RegisterPlugin(GetPluginNameStatic(),
427                                   GetPluginDescriptionStatic(),
428                                   lldb::eScriptLanguagePython,
429                                   ScriptInterpreterPythonImpl::CreateInstance);
430   });
431 }
432 
Terminate()433 void ScriptInterpreterPython::Terminate() {}
434 
Locker(ScriptInterpreterPythonImpl * py_interpreter,uint16_t on_entry,uint16_t on_leave,FileSP in,FileSP out,FileSP err)435 ScriptInterpreterPythonImpl::Locker::Locker(
436     ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
437     uint16_t on_leave, FileSP in, FileSP out, FileSP err)
438     : ScriptInterpreterLocker(),
439       m_teardown_session((on_leave & TearDownSession) == TearDownSession),
440       m_python_interpreter(py_interpreter) {
441   repro::Recorder::PrivateThread();
442   DoAcquireLock();
443   if ((on_entry & InitSession) == InitSession) {
444     if (!DoInitSession(on_entry, in, out, err)) {
445       // Don't teardown the session if we didn't init it.
446       m_teardown_session = false;
447     }
448   }
449 }
450 
DoAcquireLock()451 bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
452   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
453   m_GILState = PyGILState_Ensure();
454   LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
455             m_GILState == PyGILState_UNLOCKED ? "un" : "");
456 
457   // we need to save the thread state when we first start the command because
458   // we might decide to interrupt it while some action is taking place outside
459   // of Python (e.g. printing to screen, waiting for the network, ...) in that
460   // case, _PyThreadState_Current will be NULL - and we would be unable to set
461   // the asynchronous exception - not a desirable situation
462   m_python_interpreter->SetThreadState(PyThreadState_Get());
463   m_python_interpreter->IncrementLockCount();
464   return true;
465 }
466 
DoInitSession(uint16_t on_entry_flags,FileSP in,FileSP out,FileSP err)467 bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
468                                                         FileSP in, FileSP out,
469                                                         FileSP err) {
470   if (!m_python_interpreter)
471     return false;
472   return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
473 }
474 
DoFreeLock()475 bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
476   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
477   LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
478             m_GILState == PyGILState_UNLOCKED ? "un" : "");
479   PyGILState_Release(m_GILState);
480   m_python_interpreter->DecrementLockCount();
481   return true;
482 }
483 
DoTearDownSession()484 bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
485   if (!m_python_interpreter)
486     return false;
487   m_python_interpreter->LeaveSession();
488   return true;
489 }
490 
~Locker()491 ScriptInterpreterPythonImpl::Locker::~Locker() {
492   if (m_teardown_session)
493     DoTearDownSession();
494   DoFreeLock();
495 }
496 
ScriptInterpreterPythonImpl(Debugger & debugger)497 ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
498     : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
499       m_saved_stderr(), m_main_module(),
500       m_session_dict(PyInitialValue::Invalid),
501       m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
502       m_run_one_line_str_global(),
503       m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
504       m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
505       m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
506       m_command_thread_state(nullptr) {
507   InitializePrivate();
508 
509   m_dictionary_name.append("_dict");
510   StreamString run_string;
511   run_string.Printf("%s = dict()", m_dictionary_name.c_str());
512 
513   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
514   PyRun_SimpleString(run_string.GetData());
515 
516   run_string.Clear();
517   run_string.Printf(
518       "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
519       m_dictionary_name.c_str());
520   PyRun_SimpleString(run_string.GetData());
521 
522   // Reloading modules requires a different syntax in Python 2 and Python 3.
523   // This provides a consistent syntax no matter what version of Python.
524   run_string.Clear();
525   run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
526                     m_dictionary_name.c_str());
527   PyRun_SimpleString(run_string.GetData());
528 
529   // WARNING: temporary code that loads Cocoa formatters - this should be done
530   // on a per-platform basis rather than loading the whole set and letting the
531   // individual formatter classes exploit APIs to check whether they can/cannot
532   // do their task
533   run_string.Clear();
534   run_string.Printf(
535       "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
536       m_dictionary_name.c_str());
537   PyRun_SimpleString(run_string.GetData());
538   run_string.Clear();
539 
540   run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
541                     "lldb.embedded_interpreter import run_python_interpreter; "
542                     "from lldb.embedded_interpreter import run_one_line')",
543                     m_dictionary_name.c_str());
544   PyRun_SimpleString(run_string.GetData());
545   run_string.Clear();
546 
547   run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
548                     "; pydoc.pager = pydoc.plainpager')",
549                     m_dictionary_name.c_str(), m_debugger.GetID());
550   PyRun_SimpleString(run_string.GetData());
551 }
552 
~ScriptInterpreterPythonImpl()553 ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
554   // the session dictionary may hold objects with complex state which means
555   // that they may need to be torn down with some level of smarts and that, in
556   // turn, requires a valid thread state force Python to procure itself such a
557   // thread state, nuke the session dictionary and then release it for others
558   // to use and proceed with the rest of the shutdown
559   auto gil_state = PyGILState_Ensure();
560   m_session_dict.Reset();
561   PyGILState_Release(gil_state);
562 }
563 
GetPluginName()564 lldb_private::ConstString ScriptInterpreterPythonImpl::GetPluginName() {
565   return GetPluginNameStatic();
566 }
567 
GetPluginVersion()568 uint32_t ScriptInterpreterPythonImpl::GetPluginVersion() { return 1; }
569 
IOHandlerActivated(IOHandler & io_handler,bool interactive)570 void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
571                                                      bool interactive) {
572   const char *instructions = nullptr;
573 
574   switch (m_active_io_handler) {
575   case eIOHandlerNone:
576     break;
577   case eIOHandlerBreakpoint:
578     instructions = R"(Enter your Python command(s). Type 'DONE' to end.
579 def function (frame, bp_loc, internal_dict):
580     """frame: the lldb.SBFrame for the location at which you stopped
581        bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
582        internal_dict: an LLDB support object not to be used"""
583 )";
584     break;
585   case eIOHandlerWatchpoint:
586     instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
587     break;
588   }
589 
590   if (instructions) {
591     StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
592     if (output_sp && interactive) {
593       output_sp->PutCString(instructions);
594       output_sp->Flush();
595     }
596   }
597 }
598 
IOHandlerInputComplete(IOHandler & io_handler,std::string & data)599 void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
600                                                          std::string &data) {
601   io_handler.SetIsDone(true);
602   bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
603 
604   switch (m_active_io_handler) {
605   case eIOHandlerNone:
606     break;
607   case eIOHandlerBreakpoint: {
608     std::vector<BreakpointOptions *> *bp_options_vec =
609         (std::vector<BreakpointOptions *> *)io_handler.GetUserData();
610     for (auto bp_options : *bp_options_vec) {
611       if (!bp_options)
612         continue;
613 
614       auto data_up = std::make_unique<CommandDataPython>();
615       if (!data_up)
616         break;
617       data_up->user_source.SplitIntoLines(data);
618 
619       StructuredData::ObjectSP empty_args_sp;
620       if (GenerateBreakpointCommandCallbackData(data_up->user_source,
621                                                 data_up->script_source,
622                                                 false)
623               .Success()) {
624         auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
625             std::move(data_up));
626         bp_options->SetCallback(
627             ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
628       } else if (!batch_mode) {
629         StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
630         if (error_sp) {
631           error_sp->Printf("Warning: No command attached to breakpoint.\n");
632           error_sp->Flush();
633         }
634       }
635     }
636     m_active_io_handler = eIOHandlerNone;
637   } break;
638   case eIOHandlerWatchpoint: {
639     WatchpointOptions *wp_options =
640         (WatchpointOptions *)io_handler.GetUserData();
641     auto data_up = std::make_unique<WatchpointOptions::CommandData>();
642     data_up->user_source.SplitIntoLines(data);
643 
644     if (GenerateWatchpointCommandCallbackData(data_up->user_source,
645                                               data_up->script_source)) {
646       auto baton_sp =
647           std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
648       wp_options->SetCallback(
649           ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
650     } else if (!batch_mode) {
651       StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
652       if (error_sp) {
653         error_sp->Printf("Warning: No command attached to breakpoint.\n");
654         error_sp->Flush();
655       }
656     }
657     m_active_io_handler = eIOHandlerNone;
658   } break;
659   }
660 }
661 
662 lldb::ScriptInterpreterSP
CreateInstance(Debugger & debugger)663 ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
664   return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
665 }
666 
LeaveSession()667 void ScriptInterpreterPythonImpl::LeaveSession() {
668   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
669   if (log)
670     log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
671 
672   // Unset the LLDB global variables.
673   PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
674                      "= None; lldb.thread = None; lldb.frame = None");
675 
676   // checking that we have a valid thread state - since we use our own
677   // threading and locking in some (rare) cases during cleanup Python may end
678   // up believing we have no thread state and PyImport_AddModule will crash if
679   // that is the case - since that seems to only happen when destroying the
680   // SBDebugger, we can make do without clearing up stdout and stderr
681 
682   // rdar://problem/11292882
683   // When the current thread state is NULL, PyThreadState_Get() issues a fatal
684   // error.
685   if (PyThreadState_GetDict()) {
686     PythonDictionary &sys_module_dict = GetSysModuleDictionary();
687     if (sys_module_dict.IsValid()) {
688       if (m_saved_stdin.IsValid()) {
689         sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
690         m_saved_stdin.Reset();
691       }
692       if (m_saved_stdout.IsValid()) {
693         sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
694         m_saved_stdout.Reset();
695       }
696       if (m_saved_stderr.IsValid()) {
697         sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
698         m_saved_stderr.Reset();
699       }
700     }
701   }
702 
703   m_session_is_active = false;
704 }
705 
SetStdHandle(FileSP file_sp,const char * py_name,PythonObject & save_file,const char * mode)706 bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
707                                                const char *py_name,
708                                                PythonObject &save_file,
709                                                const char *mode) {
710   if (!file_sp || !*file_sp) {
711     save_file.Reset();
712     return false;
713   }
714   File &file = *file_sp;
715 
716   // Flush the file before giving it to python to avoid interleaved output.
717   file.Flush();
718 
719   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
720 
721   auto new_file = PythonFile::FromFile(file, mode);
722   if (!new_file) {
723     llvm::consumeError(new_file.takeError());
724     return false;
725   }
726 
727   save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
728 
729   sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
730   return true;
731 }
732 
EnterSession(uint16_t on_entry_flags,FileSP in_sp,FileSP out_sp,FileSP err_sp)733 bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
734                                                FileSP in_sp, FileSP out_sp,
735                                                FileSP err_sp) {
736   // If we have already entered the session, without having officially 'left'
737   // it, then there is no need to 'enter' it again.
738   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
739   if (m_session_is_active) {
740     LLDB_LOGF(
741         log,
742         "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
743         ") session is already active, returning without doing anything",
744         on_entry_flags);
745     return false;
746   }
747 
748   LLDB_LOGF(
749       log,
750       "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
751       on_entry_flags);
752 
753   m_session_is_active = true;
754 
755   StreamString run_string;
756 
757   if (on_entry_flags & Locker::InitGlobals) {
758     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
759                       m_dictionary_name.c_str(), m_debugger.GetID());
760     run_string.Printf(
761         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
762         m_debugger.GetID());
763     run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
764     run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
765     run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
766     run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
767     run_string.PutCString("')");
768   } else {
769     // If we aren't initing the globals, we should still always set the
770     // debugger (since that is always unique.)
771     run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
772                       m_dictionary_name.c_str(), m_debugger.GetID());
773     run_string.Printf(
774         "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
775         m_debugger.GetID());
776     run_string.PutCString("')");
777   }
778 
779   PyRun_SimpleString(run_string.GetData());
780   run_string.Clear();
781 
782   PythonDictionary &sys_module_dict = GetSysModuleDictionary();
783   if (sys_module_dict.IsValid()) {
784     lldb::FileSP top_in_sp;
785     lldb::StreamFileSP top_out_sp, top_err_sp;
786     if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
787       m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
788                                                  top_err_sp);
789 
790     if (on_entry_flags & Locker::NoSTDIN) {
791       m_saved_stdin.Reset();
792     } else {
793       if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
794         if (top_in_sp)
795           SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
796       }
797     }
798 
799     if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
800       if (top_out_sp)
801         SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
802     }
803 
804     if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
805       if (top_err_sp)
806         SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
807     }
808   }
809 
810   if (PyErr_Occurred())
811     PyErr_Clear();
812 
813   return true;
814 }
815 
GetMainModule()816 PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
817   if (!m_main_module.IsValid())
818     m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
819   return m_main_module;
820 }
821 
GetSessionDictionary()822 PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
823   if (m_session_dict.IsValid())
824     return m_session_dict;
825 
826   PythonObject &main_module = GetMainModule();
827   if (!main_module.IsValid())
828     return m_session_dict;
829 
830   PythonDictionary main_dict(PyRefType::Borrowed,
831                              PyModule_GetDict(main_module.get()));
832   if (!main_dict.IsValid())
833     return m_session_dict;
834 
835   m_session_dict = unwrapIgnoringErrors(
836       As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
837   return m_session_dict;
838 }
839 
GetSysModuleDictionary()840 PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
841   if (m_sys_module_dict.IsValid())
842     return m_sys_module_dict;
843   PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
844   m_sys_module_dict = sys_module.GetDictionary();
845   return m_sys_module_dict;
846 }
847 
848 llvm::Expected<unsigned>
GetMaxPositionalArgumentsForCallable(const llvm::StringRef & callable_name)849 ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
850     const llvm::StringRef &callable_name) {
851   if (callable_name.empty()) {
852     return llvm::createStringError(
853         llvm::inconvertibleErrorCode(),
854         "called with empty callable name.");
855   }
856   Locker py_lock(this, Locker::AcquireLock |
857                  Locker::InitSession |
858                  Locker::NoSTDIN);
859   auto dict = PythonModule::MainModule()
860       .ResolveName<PythonDictionary>(m_dictionary_name);
861   auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
862       callable_name, dict);
863   if (!pfunc.IsAllocated()) {
864     return llvm::createStringError(
865         llvm::inconvertibleErrorCode(),
866         "can't find callable: %s", callable_name.str().c_str());
867   }
868   llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
869   if (!arg_info)
870     return arg_info.takeError();
871   return arg_info.get().max_positional_args;
872 }
873 
GenerateUniqueName(const char * base_name_wanted,uint32_t & functions_counter,const void * name_token=nullptr)874 static std::string GenerateUniqueName(const char *base_name_wanted,
875                                       uint32_t &functions_counter,
876                                       const void *name_token = nullptr) {
877   StreamString sstr;
878 
879   if (!base_name_wanted)
880     return std::string();
881 
882   if (!name_token)
883     sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
884   else
885     sstr.Printf("%s_%p", base_name_wanted, name_token);
886 
887   return std::string(sstr.GetString());
888 }
889 
GetEmbeddedInterpreterModuleObjects()890 bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
891   if (m_run_one_line_function.IsValid())
892     return true;
893 
894   PythonObject module(PyRefType::Borrowed,
895                       PyImport_AddModule("lldb.embedded_interpreter"));
896   if (!module.IsValid())
897     return false;
898 
899   PythonDictionary module_dict(PyRefType::Borrowed,
900                                PyModule_GetDict(module.get()));
901   if (!module_dict.IsValid())
902     return false;
903 
904   m_run_one_line_function =
905       module_dict.GetItemForKey(PythonString("run_one_line"));
906   m_run_one_line_str_global =
907       module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
908   return m_run_one_line_function.IsValid();
909 }
910 
ExecuteOneLine(llvm::StringRef command,CommandReturnObject * result,const ExecuteScriptOptions & options)911 bool ScriptInterpreterPythonImpl::ExecuteOneLine(
912     llvm::StringRef command, CommandReturnObject *result,
913     const ExecuteScriptOptions &options) {
914   std::string command_str = command.str();
915 
916   if (!m_valid_session)
917     return false;
918 
919   if (!command.empty()) {
920     // We want to call run_one_line, passing in the dictionary and the command
921     // string.  We cannot do this through PyRun_SimpleString here because the
922     // command string may contain escaped characters, and putting it inside
923     // another string to pass to PyRun_SimpleString messes up the escaping.  So
924     // we use the following more complicated method to pass the command string
925     // directly down to Python.
926     llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
927         io_redirect_or_error = ScriptInterpreterIORedirect::Create(
928             options.GetEnableIO(), m_debugger, result);
929     if (!io_redirect_or_error) {
930       if (result)
931         result->AppendErrorWithFormatv(
932             "failed to redirect I/O: {0}\n",
933             llvm::fmt_consume(io_redirect_or_error.takeError()));
934       else
935         llvm::consumeError(io_redirect_or_error.takeError());
936       return false;
937     }
938 
939     ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
940 
941     bool success = false;
942     {
943       // WARNING!  It's imperative that this RAII scope be as tight as
944       // possible. In particular, the scope must end *before* we try to join
945       // the read thread.  The reason for this is that a pre-requisite for
946       // joining the read thread is that we close the write handle (to break
947       // the pipe and cause it to wake up and exit).  But acquiring the GIL as
948       // below will redirect Python's stdio to use this same handle.  If we
949       // close the handle while Python is still using it, bad things will
950       // happen.
951       Locker locker(
952           this,
953           Locker::AcquireLock | Locker::InitSession |
954               (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
955               ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
956           Locker::FreeAcquiredLock | Locker::TearDownSession,
957           io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
958           io_redirect.GetErrorFile());
959 
960       // Find the correct script interpreter dictionary in the main module.
961       PythonDictionary &session_dict = GetSessionDictionary();
962       if (session_dict.IsValid()) {
963         if (GetEmbeddedInterpreterModuleObjects()) {
964           if (PyCallable_Check(m_run_one_line_function.get())) {
965             PythonObject pargs(
966                 PyRefType::Owned,
967                 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
968             if (pargs.IsValid()) {
969               PythonObject return_value(
970                   PyRefType::Owned,
971                   PyObject_CallObject(m_run_one_line_function.get(),
972                                       pargs.get()));
973               if (return_value.IsValid())
974                 success = true;
975               else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
976                 PyErr_Print();
977                 PyErr_Clear();
978               }
979             }
980           }
981         }
982       }
983 
984       io_redirect.Flush();
985     }
986 
987     if (success)
988       return true;
989 
990     // The one-liner failed.  Append the error message.
991     if (result) {
992       result->AppendErrorWithFormat(
993           "python failed attempting to evaluate '%s'\n", command_str.c_str());
994     }
995     return false;
996   }
997 
998   if (result)
999     result->AppendError("empty command passed to python\n");
1000   return false;
1001 }
1002 
ExecuteInterpreterLoop()1003 void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
1004   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1005   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
1006 
1007   Debugger &debugger = m_debugger;
1008 
1009   // At the moment, the only time the debugger does not have an input file
1010   // handle is when this is called directly from Python, in which case it is
1011   // both dangerous and unnecessary (not to mention confusing) to try to embed
1012   // a running interpreter loop inside the already running Python interpreter
1013   // loop, so we won't do it.
1014 
1015   if (!debugger.GetInputFile().IsValid())
1016     return;
1017 
1018   IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
1019   if (io_handler_sp) {
1020     debugger.RunIOHandlerAsync(io_handler_sp);
1021   }
1022 }
1023 
Interrupt()1024 bool ScriptInterpreterPythonImpl::Interrupt() {
1025   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
1026 
1027   if (IsExecutingPython()) {
1028     PyThreadState *state = PyThreadState_GET();
1029     if (!state)
1030       state = GetThreadState();
1031     if (state) {
1032       long tid = state->thread_id;
1033       PyThreadState_Swap(state);
1034       int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
1035       LLDB_LOGF(log,
1036                 "ScriptInterpreterPythonImpl::Interrupt() sending "
1037                 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
1038                 tid, num_threads);
1039       return true;
1040     }
1041   }
1042   LLDB_LOGF(log,
1043             "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
1044             "can't interrupt");
1045   return false;
1046 }
1047 
ExecuteOneLineWithReturn(llvm::StringRef in_string,ScriptInterpreter::ScriptReturnType return_type,void * ret_value,const ExecuteScriptOptions & options)1048 bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
1049     llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
1050     void *ret_value, const ExecuteScriptOptions &options) {
1051 
1052   Locker locker(this,
1053                 Locker::AcquireLock | Locker::InitSession |
1054                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1055                     Locker::NoSTDIN,
1056                 Locker::FreeAcquiredLock | Locker::TearDownSession);
1057 
1058   PythonModule &main_module = GetMainModule();
1059   PythonDictionary globals = main_module.GetDictionary();
1060 
1061   PythonDictionary locals = GetSessionDictionary();
1062   if (!locals.IsValid())
1063     locals = unwrapIgnoringErrors(
1064         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1065   if (!locals.IsValid())
1066     locals = globals;
1067 
1068   Expected<PythonObject> maybe_py_return =
1069       runStringOneLine(in_string, globals, locals);
1070 
1071   if (!maybe_py_return) {
1072     llvm::handleAllErrors(
1073         maybe_py_return.takeError(),
1074         [&](PythonException &E) {
1075           E.Restore();
1076           if (options.GetMaskoutErrors()) {
1077             if (E.Matches(PyExc_SyntaxError)) {
1078               PyErr_Print();
1079             }
1080             PyErr_Clear();
1081           }
1082         },
1083         [](const llvm::ErrorInfoBase &E) {});
1084     return false;
1085   }
1086 
1087   PythonObject py_return = std::move(maybe_py_return.get());
1088   assert(py_return.IsValid());
1089 
1090   switch (return_type) {
1091   case eScriptReturnTypeCharPtr: // "char *"
1092   {
1093     const char format[3] = "s#";
1094     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1095   }
1096   case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1097                                        // Py_None
1098   {
1099     const char format[3] = "z";
1100     return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1101   }
1102   case eScriptReturnTypeBool: {
1103     const char format[2] = "b";
1104     return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1105   }
1106   case eScriptReturnTypeShortInt: {
1107     const char format[2] = "h";
1108     return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1109   }
1110   case eScriptReturnTypeShortIntUnsigned: {
1111     const char format[2] = "H";
1112     return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1113   }
1114   case eScriptReturnTypeInt: {
1115     const char format[2] = "i";
1116     return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1117   }
1118   case eScriptReturnTypeIntUnsigned: {
1119     const char format[2] = "I";
1120     return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1121   }
1122   case eScriptReturnTypeLongInt: {
1123     const char format[2] = "l";
1124     return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1125   }
1126   case eScriptReturnTypeLongIntUnsigned: {
1127     const char format[2] = "k";
1128     return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1129   }
1130   case eScriptReturnTypeLongLong: {
1131     const char format[2] = "L";
1132     return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1133   }
1134   case eScriptReturnTypeLongLongUnsigned: {
1135     const char format[2] = "K";
1136     return PyArg_Parse(py_return.get(), format,
1137                        (unsigned long long *)ret_value);
1138   }
1139   case eScriptReturnTypeFloat: {
1140     const char format[2] = "f";
1141     return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1142   }
1143   case eScriptReturnTypeDouble: {
1144     const char format[2] = "d";
1145     return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1146   }
1147   case eScriptReturnTypeChar: {
1148     const char format[2] = "c";
1149     return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1150   }
1151   case eScriptReturnTypeOpaqueObject: {
1152     *((PyObject **)ret_value) = py_return.release();
1153     return true;
1154   }
1155   }
1156   llvm_unreachable("Fully covered switch!");
1157 }
1158 
ExecuteMultipleLines(const char * in_string,const ExecuteScriptOptions & options)1159 Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1160     const char *in_string, const ExecuteScriptOptions &options) {
1161 
1162   if (in_string == nullptr)
1163     return Status();
1164 
1165   Locker locker(this,
1166                 Locker::AcquireLock | Locker::InitSession |
1167                     (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1168                     Locker::NoSTDIN,
1169                 Locker::FreeAcquiredLock | Locker::TearDownSession);
1170 
1171   PythonModule &main_module = GetMainModule();
1172   PythonDictionary globals = main_module.GetDictionary();
1173 
1174   PythonDictionary locals = GetSessionDictionary();
1175   if (!locals.IsValid())
1176     locals = unwrapIgnoringErrors(
1177         As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1178   if (!locals.IsValid())
1179     locals = globals;
1180 
1181   Expected<PythonObject> return_value =
1182       runStringMultiLine(in_string, globals, locals);
1183 
1184   if (!return_value) {
1185     llvm::Error error =
1186         llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1187           llvm::Error error = llvm::createStringError(
1188               llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1189           if (!options.GetMaskoutErrors())
1190             E.Restore();
1191           return error;
1192         });
1193     return Status(std::move(error));
1194   }
1195 
1196   return Status();
1197 }
1198 
CollectDataForBreakpointCommandCallback(std::vector<BreakpointOptions * > & bp_options_vec,CommandReturnObject & result)1199 void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1200     std::vector<BreakpointOptions *> &bp_options_vec,
1201     CommandReturnObject &result) {
1202   m_active_io_handler = eIOHandlerBreakpoint;
1203   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1204       "    ", *this, &bp_options_vec);
1205 }
1206 
CollectDataForWatchpointCommandCallback(WatchpointOptions * wp_options,CommandReturnObject & result)1207 void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1208     WatchpointOptions *wp_options, CommandReturnObject &result) {
1209   m_active_io_handler = eIOHandlerWatchpoint;
1210   m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1211       "    ", *this, wp_options);
1212 }
1213 
SetBreakpointCommandCallbackFunction(BreakpointOptions * bp_options,const char * function_name,StructuredData::ObjectSP extra_args_sp)1214 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1215     BreakpointOptions *bp_options, const char *function_name,
1216     StructuredData::ObjectSP extra_args_sp) {
1217   Status error;
1218   // For now just cons up a oneliner that calls the provided function.
1219   std::string oneliner("return ");
1220   oneliner += function_name;
1221 
1222   llvm::Expected<unsigned> maybe_args =
1223       GetMaxPositionalArgumentsForCallable(function_name);
1224   if (!maybe_args) {
1225     error.SetErrorStringWithFormat(
1226         "could not get num args: %s",
1227         llvm::toString(maybe_args.takeError()).c_str());
1228     return error;
1229   }
1230   size_t max_args = *maybe_args;
1231 
1232   bool uses_extra_args = false;
1233   if (max_args >= 4) {
1234     uses_extra_args = true;
1235     oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1236   } else if (max_args >= 3) {
1237     if (extra_args_sp) {
1238       error.SetErrorString("cannot pass extra_args to a three argument callback"
1239                           );
1240       return error;
1241     }
1242     uses_extra_args = false;
1243     oneliner += "(frame, bp_loc, internal_dict)";
1244   } else {
1245     error.SetErrorStringWithFormat("expected 3 or 4 argument "
1246                                    "function, %s can only take %zu",
1247                                    function_name, max_args);
1248     return error;
1249   }
1250 
1251   SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1252                                uses_extra_args);
1253   return error;
1254 }
1255 
SetBreakpointCommandCallback(BreakpointOptions * bp_options,std::unique_ptr<BreakpointOptions::CommandData> & cmd_data_up)1256 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1257     BreakpointOptions *bp_options,
1258     std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1259   Status error;
1260   error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1261                                                 cmd_data_up->script_source,
1262                                                 false);
1263   if (error.Fail()) {
1264     return error;
1265   }
1266   auto baton_sp =
1267       std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1268   bp_options->SetCallback(
1269       ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1270   return error;
1271 }
1272 
SetBreakpointCommandCallback(BreakpointOptions * bp_options,const char * command_body_text)1273 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1274     BreakpointOptions *bp_options, const char *command_body_text) {
1275   return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1276 }
1277 
1278 // Set a Python one-liner as the callback for the breakpoint.
SetBreakpointCommandCallback(BreakpointOptions * bp_options,const char * command_body_text,StructuredData::ObjectSP extra_args_sp,bool uses_extra_args)1279 Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1280     BreakpointOptions *bp_options, const char *command_body_text,
1281     StructuredData::ObjectSP extra_args_sp,
1282     bool uses_extra_args) {
1283   auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1284   // Split the command_body_text into lines, and pass that to
1285   // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
1286   // auto-generated function, and return the function name in script_source.
1287   // That is what the callback will actually invoke.
1288 
1289   data_up->user_source.SplitIntoLines(command_body_text);
1290   Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1291                                                        data_up->script_source,
1292                                                        uses_extra_args);
1293   if (error.Success()) {
1294     auto baton_sp =
1295         std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1296     bp_options->SetCallback(
1297         ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1298     return error;
1299   }
1300   return error;
1301 }
1302 
1303 // Set a Python one-liner as the callback for the watchpoint.
SetWatchpointCommandCallback(WatchpointOptions * wp_options,const char * oneliner)1304 void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1305     WatchpointOptions *wp_options, const char *oneliner) {
1306   auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1307 
1308   // It's necessary to set both user_source and script_source to the oneliner.
1309   // The former is used to generate callback description (as in watchpoint
1310   // command list) while the latter is used for Python to interpret during the
1311   // actual callback.
1312 
1313   data_up->user_source.AppendString(oneliner);
1314   data_up->script_source.assign(oneliner);
1315 
1316   if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1317                                             data_up->script_source)) {
1318     auto baton_sp =
1319         std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1320     wp_options->SetCallback(
1321         ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1322   }
1323 
1324   return;
1325 }
1326 
ExportFunctionDefinitionToInterpreter(StringList & function_def)1327 Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1328     StringList &function_def) {
1329   // Convert StringList to one long, newline delimited, const char *.
1330   std::string function_def_string(function_def.CopyList());
1331 
1332   Status error = ExecuteMultipleLines(
1333       function_def_string.c_str(),
1334       ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
1335   return error;
1336 }
1337 
GenerateFunction(const char * signature,const StringList & input)1338 Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1339                                                      const StringList &input) {
1340   Status error;
1341   int num_lines = input.GetSize();
1342   if (num_lines == 0) {
1343     error.SetErrorString("No input data.");
1344     return error;
1345   }
1346 
1347   if (!signature || *signature == 0) {
1348     error.SetErrorString("No output function name.");
1349     return error;
1350   }
1351 
1352   StreamString sstr;
1353   StringList auto_generated_function;
1354   auto_generated_function.AppendString(signature);
1355   auto_generated_function.AppendString(
1356       "     global_dict = globals()"); // Grab the global dictionary
1357   auto_generated_function.AppendString(
1358       "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1359                                                // session dict
1360   auto_generated_function.AppendString(
1361       "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1362   auto_generated_function.AppendString(
1363       "     global_dict.update (internal_dict)"); // Add the session dictionary
1364                                                   // to the
1365   // global dictionary.
1366 
1367   // Wrap everything up inside the function, increasing the indentation.
1368 
1369   auto_generated_function.AppendString("     if True:");
1370   for (int i = 0; i < num_lines; ++i) {
1371     sstr.Clear();
1372     sstr.Printf("       %s", input.GetStringAtIndex(i));
1373     auto_generated_function.AppendString(sstr.GetData());
1374   }
1375   auto_generated_function.AppendString(
1376       "     for key in new_keys:"); // Iterate over all the keys from session
1377                                     // dict
1378   auto_generated_function.AppendString(
1379       "         internal_dict[key] = global_dict[key]"); // Update session dict
1380                                                          // values
1381   auto_generated_function.AppendString(
1382       "         if key not in old_keys:"); // If key was not originally in
1383                                            // global dict
1384   auto_generated_function.AppendString(
1385       "             del global_dict[key]"); //  ...then remove key/value from
1386                                             //  global dict
1387 
1388   // Verify that the results are valid Python.
1389 
1390   error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1391 
1392   return error;
1393 }
1394 
GenerateTypeScriptFunction(StringList & user_input,std::string & output,const void * name_token)1395 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1396     StringList &user_input, std::string &output, const void *name_token) {
1397   static uint32_t num_created_functions = 0;
1398   user_input.RemoveBlankLines();
1399   StreamString sstr;
1400 
1401   // Check to see if we have any data; if not, just return.
1402   if (user_input.GetSize() == 0)
1403     return false;
1404 
1405   // Take what the user wrote, wrap it all up inside one big auto-generated
1406   // Python function, passing in the ValueObject as parameter to the function.
1407 
1408   std::string auto_generated_function_name(
1409       GenerateUniqueName("lldb_autogen_python_type_print_func",
1410                          num_created_functions, name_token));
1411   sstr.Printf("def %s (valobj, internal_dict):",
1412               auto_generated_function_name.c_str());
1413 
1414   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1415     return false;
1416 
1417   // Store the name of the auto-generated function to be called.
1418   output.assign(auto_generated_function_name);
1419   return true;
1420 }
1421 
GenerateScriptAliasFunction(StringList & user_input,std::string & output)1422 bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1423     StringList &user_input, std::string &output) {
1424   static uint32_t num_created_functions = 0;
1425   user_input.RemoveBlankLines();
1426   StreamString sstr;
1427 
1428   // Check to see if we have any data; if not, just return.
1429   if (user_input.GetSize() == 0)
1430     return false;
1431 
1432   std::string auto_generated_function_name(GenerateUniqueName(
1433       "lldb_autogen_python_cmd_alias_func", num_created_functions));
1434 
1435   sstr.Printf("def %s (debugger, args, result, internal_dict):",
1436               auto_generated_function_name.c_str());
1437 
1438   if (!GenerateFunction(sstr.GetData(), user_input).Success())
1439     return false;
1440 
1441   // Store the name of the auto-generated function to be called.
1442   output.assign(auto_generated_function_name);
1443   return true;
1444 }
1445 
GenerateTypeSynthClass(StringList & user_input,std::string & output,const void * name_token)1446 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1447     StringList &user_input, std::string &output, const void *name_token) {
1448   static uint32_t num_created_classes = 0;
1449   user_input.RemoveBlankLines();
1450   int num_lines = user_input.GetSize();
1451   StreamString sstr;
1452 
1453   // Check to see if we have any data; if not, just return.
1454   if (user_input.GetSize() == 0)
1455     return false;
1456 
1457   // Wrap all user input into a Python class
1458 
1459   std::string auto_generated_class_name(GenerateUniqueName(
1460       "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1461 
1462   StringList auto_generated_class;
1463 
1464   // Create the function name & definition string.
1465 
1466   sstr.Printf("class %s:", auto_generated_class_name.c_str());
1467   auto_generated_class.AppendString(sstr.GetString());
1468 
1469   // Wrap everything up inside the class, increasing the indentation. we don't
1470   // need to play any fancy indentation tricks here because there is no
1471   // surrounding code whose indentation we need to honor
1472   for (int i = 0; i < num_lines; ++i) {
1473     sstr.Clear();
1474     sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1475     auto_generated_class.AppendString(sstr.GetString());
1476   }
1477 
1478   // Verify that the results are valid Python. (even though the method is
1479   // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1480   // (TODO: rename that method to ExportDefinitionToInterpreter)
1481   if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1482     return false;
1483 
1484   // Store the name of the auto-generated class
1485 
1486   output.assign(auto_generated_class_name);
1487   return true;
1488 }
1489 
1490 StructuredData::GenericSP
CreateFrameRecognizer(const char * class_name)1491 ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1492   if (class_name == nullptr || class_name[0] == '\0')
1493     return StructuredData::GenericSP();
1494 
1495   void *ret_val;
1496 
1497   {
1498     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1499                    Locker::FreeLock);
1500     ret_val = LLDBSWIGPython_CreateFrameRecognizer(class_name,
1501                                                    m_dictionary_name.c_str());
1502   }
1503 
1504   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1505 }
1506 
GetRecognizedArguments(const StructuredData::ObjectSP & os_plugin_object_sp,lldb::StackFrameSP frame_sp)1507 lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1508     const StructuredData::ObjectSP &os_plugin_object_sp,
1509     lldb::StackFrameSP frame_sp) {
1510   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1511 
1512   if (!os_plugin_object_sp)
1513     return ValueObjectListSP();
1514 
1515   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1516   if (!generic)
1517     return nullptr;
1518 
1519   PythonObject implementor(PyRefType::Borrowed,
1520                            (PyObject *)generic->GetValue());
1521 
1522   if (!implementor.IsAllocated())
1523     return ValueObjectListSP();
1524 
1525   PythonObject py_return(PyRefType::Owned,
1526                          (PyObject *)LLDBSwigPython_GetRecognizedArguments(
1527                              implementor.get(), frame_sp));
1528 
1529   // if it fails, print the error but otherwise go on
1530   if (PyErr_Occurred()) {
1531     PyErr_Print();
1532     PyErr_Clear();
1533   }
1534   if (py_return.get()) {
1535     PythonList result_list(PyRefType::Borrowed, py_return.get());
1536     ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1537     for (size_t i = 0; i < result_list.GetSize(); i++) {
1538       PyObject *item = result_list.GetItemAtIndex(i).get();
1539       lldb::SBValue *sb_value_ptr =
1540           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1541       auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1542       if (valobj_sp)
1543         result->Append(valobj_sp);
1544     }
1545     return result;
1546   }
1547   return ValueObjectListSP();
1548 }
1549 
1550 StructuredData::GenericSP
OSPlugin_CreatePluginObject(const char * class_name,lldb::ProcessSP process_sp)1551 ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1552     const char *class_name, lldb::ProcessSP process_sp) {
1553   if (class_name == nullptr || class_name[0] == '\0')
1554     return StructuredData::GenericSP();
1555 
1556   if (!process_sp)
1557     return StructuredData::GenericSP();
1558 
1559   void *ret_val;
1560 
1561   {
1562     Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN,
1563                    Locker::FreeLock);
1564     ret_val = LLDBSWIGPythonCreateOSPlugin(
1565         class_name, m_dictionary_name.c_str(), process_sp);
1566   }
1567 
1568   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1569 }
1570 
OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp)1571 StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1572     StructuredData::ObjectSP os_plugin_object_sp) {
1573   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1574 
1575   static char callee_name[] = "get_register_info";
1576 
1577   if (!os_plugin_object_sp)
1578     return StructuredData::DictionarySP();
1579 
1580   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1581   if (!generic)
1582     return nullptr;
1583 
1584   PythonObject implementor(PyRefType::Borrowed,
1585                            (PyObject *)generic->GetValue());
1586 
1587   if (!implementor.IsAllocated())
1588     return StructuredData::DictionarySP();
1589 
1590   PythonObject pmeth(PyRefType::Owned,
1591                      PyObject_GetAttrString(implementor.get(), callee_name));
1592 
1593   if (PyErr_Occurred())
1594     PyErr_Clear();
1595 
1596   if (!pmeth.IsAllocated())
1597     return StructuredData::DictionarySP();
1598 
1599   if (PyCallable_Check(pmeth.get()) == 0) {
1600     if (PyErr_Occurred())
1601       PyErr_Clear();
1602 
1603     return StructuredData::DictionarySP();
1604   }
1605 
1606   if (PyErr_Occurred())
1607     PyErr_Clear();
1608 
1609   // right now we know this function exists and is callable..
1610   PythonObject py_return(
1611       PyRefType::Owned,
1612       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1613 
1614   // if it fails, print the error but otherwise go on
1615   if (PyErr_Occurred()) {
1616     PyErr_Print();
1617     PyErr_Clear();
1618   }
1619   if (py_return.get()) {
1620     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1621     return result_dict.CreateStructuredDictionary();
1622   }
1623   return StructuredData::DictionarySP();
1624 }
1625 
OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp)1626 StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1627     StructuredData::ObjectSP os_plugin_object_sp) {
1628   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1629 
1630   static char callee_name[] = "get_thread_info";
1631 
1632   if (!os_plugin_object_sp)
1633     return StructuredData::ArraySP();
1634 
1635   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1636   if (!generic)
1637     return nullptr;
1638 
1639   PythonObject implementor(PyRefType::Borrowed,
1640                            (PyObject *)generic->GetValue());
1641 
1642   if (!implementor.IsAllocated())
1643     return StructuredData::ArraySP();
1644 
1645   PythonObject pmeth(PyRefType::Owned,
1646                      PyObject_GetAttrString(implementor.get(), callee_name));
1647 
1648   if (PyErr_Occurred())
1649     PyErr_Clear();
1650 
1651   if (!pmeth.IsAllocated())
1652     return StructuredData::ArraySP();
1653 
1654   if (PyCallable_Check(pmeth.get()) == 0) {
1655     if (PyErr_Occurred())
1656       PyErr_Clear();
1657 
1658     return StructuredData::ArraySP();
1659   }
1660 
1661   if (PyErr_Occurred())
1662     PyErr_Clear();
1663 
1664   // right now we know this function exists and is callable..
1665   PythonObject py_return(
1666       PyRefType::Owned,
1667       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1668 
1669   // if it fails, print the error but otherwise go on
1670   if (PyErr_Occurred()) {
1671     PyErr_Print();
1672     PyErr_Clear();
1673   }
1674 
1675   if (py_return.get()) {
1676     PythonList result_list(PyRefType::Borrowed, py_return.get());
1677     return result_list.CreateStructuredArray();
1678   }
1679   return StructuredData::ArraySP();
1680 }
1681 
1682 // GetPythonValueFormatString provides a system independent type safe way to
1683 // convert a variable's type into a python value format. Python value formats
1684 // are defined in terms of builtin C types and could change from system to as
1685 // the underlying typedef for uint* types, size_t, off_t and other values
1686 // change.
1687 
1688 template <typename T> const char *GetPythonValueFormatString(T t);
GetPythonValueFormatString(char *)1689 template <> const char *GetPythonValueFormatString(char *) { return "s"; }
GetPythonValueFormatString(char)1690 template <> const char *GetPythonValueFormatString(char) { return "b"; }
GetPythonValueFormatString(unsigned char)1691 template <> const char *GetPythonValueFormatString(unsigned char) {
1692   return "B";
1693 }
GetPythonValueFormatString(short)1694 template <> const char *GetPythonValueFormatString(short) { return "h"; }
GetPythonValueFormatString(unsigned short)1695 template <> const char *GetPythonValueFormatString(unsigned short) {
1696   return "H";
1697 }
GetPythonValueFormatString(int)1698 template <> const char *GetPythonValueFormatString(int) { return "i"; }
GetPythonValueFormatString(unsigned int)1699 template <> const char *GetPythonValueFormatString(unsigned int) { return "I"; }
GetPythonValueFormatString(long)1700 template <> const char *GetPythonValueFormatString(long) { return "l"; }
GetPythonValueFormatString(unsigned long)1701 template <> const char *GetPythonValueFormatString(unsigned long) {
1702   return "k";
1703 }
GetPythonValueFormatString(long long)1704 template <> const char *GetPythonValueFormatString(long long) { return "L"; }
GetPythonValueFormatString(unsigned long long)1705 template <> const char *GetPythonValueFormatString(unsigned long long) {
1706   return "K";
1707 }
GetPythonValueFormatString(float t)1708 template <> const char *GetPythonValueFormatString(float t) { return "f"; }
GetPythonValueFormatString(double t)1709 template <> const char *GetPythonValueFormatString(double t) { return "d"; }
1710 
1711 StructuredData::StringSP
OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid)1712 ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1713     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1714   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1715 
1716   static char callee_name[] = "get_register_data";
1717   static char *param_format =
1718       const_cast<char *>(GetPythonValueFormatString(tid));
1719 
1720   if (!os_plugin_object_sp)
1721     return StructuredData::StringSP();
1722 
1723   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1724   if (!generic)
1725     return nullptr;
1726   PythonObject implementor(PyRefType::Borrowed,
1727                            (PyObject *)generic->GetValue());
1728 
1729   if (!implementor.IsAllocated())
1730     return StructuredData::StringSP();
1731 
1732   PythonObject pmeth(PyRefType::Owned,
1733                      PyObject_GetAttrString(implementor.get(), callee_name));
1734 
1735   if (PyErr_Occurred())
1736     PyErr_Clear();
1737 
1738   if (!pmeth.IsAllocated())
1739     return StructuredData::StringSP();
1740 
1741   if (PyCallable_Check(pmeth.get()) == 0) {
1742     if (PyErr_Occurred())
1743       PyErr_Clear();
1744     return StructuredData::StringSP();
1745   }
1746 
1747   if (PyErr_Occurred())
1748     PyErr_Clear();
1749 
1750   // right now we know this function exists and is callable..
1751   PythonObject py_return(
1752       PyRefType::Owned,
1753       PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1754 
1755   // if it fails, print the error but otherwise go on
1756   if (PyErr_Occurred()) {
1757     PyErr_Print();
1758     PyErr_Clear();
1759   }
1760 
1761   if (py_return.get()) {
1762     PythonBytes result(PyRefType::Borrowed, py_return.get());
1763     return result.CreateStructuredString();
1764   }
1765   return StructuredData::StringSP();
1766 }
1767 
OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp,lldb::tid_t tid,lldb::addr_t context)1768 StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1769     StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1770     lldb::addr_t context) {
1771   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1772 
1773   static char callee_name[] = "create_thread";
1774   std::string param_format;
1775   param_format += GetPythonValueFormatString(tid);
1776   param_format += GetPythonValueFormatString(context);
1777 
1778   if (!os_plugin_object_sp)
1779     return StructuredData::DictionarySP();
1780 
1781   StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1782   if (!generic)
1783     return nullptr;
1784 
1785   PythonObject implementor(PyRefType::Borrowed,
1786                            (PyObject *)generic->GetValue());
1787 
1788   if (!implementor.IsAllocated())
1789     return StructuredData::DictionarySP();
1790 
1791   PythonObject pmeth(PyRefType::Owned,
1792                      PyObject_GetAttrString(implementor.get(), callee_name));
1793 
1794   if (PyErr_Occurred())
1795     PyErr_Clear();
1796 
1797   if (!pmeth.IsAllocated())
1798     return StructuredData::DictionarySP();
1799 
1800   if (PyCallable_Check(pmeth.get()) == 0) {
1801     if (PyErr_Occurred())
1802       PyErr_Clear();
1803     return StructuredData::DictionarySP();
1804   }
1805 
1806   if (PyErr_Occurred())
1807     PyErr_Clear();
1808 
1809   // right now we know this function exists and is callable..
1810   PythonObject py_return(PyRefType::Owned,
1811                          PyObject_CallMethod(implementor.get(), callee_name,
1812                                              &param_format[0], tid, context));
1813 
1814   // if it fails, print the error but otherwise go on
1815   if (PyErr_Occurred()) {
1816     PyErr_Print();
1817     PyErr_Clear();
1818   }
1819 
1820   if (py_return.get()) {
1821     PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1822     return result_dict.CreateStructuredDictionary();
1823   }
1824   return StructuredData::DictionarySP();
1825 }
1826 
CreateScriptedThreadPlan(const char * class_name,StructuredDataImpl * args_data,std::string & error_str,lldb::ThreadPlanSP thread_plan_sp)1827 StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
1828     const char *class_name, StructuredDataImpl *args_data,
1829     std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
1830   if (class_name == nullptr || class_name[0] == '\0')
1831     return StructuredData::ObjectSP();
1832 
1833   if (!thread_plan_sp.get())
1834     return {};
1835 
1836   Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1837   ScriptInterpreterPythonImpl *python_interpreter =
1838       GetPythonInterpreter(debugger);
1839 
1840   if (!python_interpreter)
1841     return {};
1842 
1843   void *ret_val;
1844 
1845   {
1846     Locker py_lock(this,
1847                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1848     ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1849         class_name, python_interpreter->m_dictionary_name.c_str(),
1850         args_data, error_str, thread_plan_sp);
1851     if (!ret_val)
1852       return {};
1853   }
1854 
1855   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
1856 }
1857 
ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)1858 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1859     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1860   bool explains_stop = true;
1861   StructuredData::Generic *generic = nullptr;
1862   if (implementor_sp)
1863     generic = implementor_sp->GetAsGeneric();
1864   if (generic) {
1865     Locker py_lock(this,
1866                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1867     explains_stop = LLDBSWIGPythonCallThreadPlan(
1868         generic->GetValue(), "explains_stop", event, script_error);
1869     if (script_error)
1870       return true;
1871   }
1872   return explains_stop;
1873 }
1874 
ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp,Event * event,bool & script_error)1875 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1876     StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1877   bool should_stop = true;
1878   StructuredData::Generic *generic = nullptr;
1879   if (implementor_sp)
1880     generic = implementor_sp->GetAsGeneric();
1881   if (generic) {
1882     Locker py_lock(this,
1883                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1884     should_stop = LLDBSWIGPythonCallThreadPlan(
1885         generic->GetValue(), "should_stop", event, script_error);
1886     if (script_error)
1887       return true;
1888   }
1889   return should_stop;
1890 }
1891 
ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp,bool & script_error)1892 bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1893     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1894   bool is_stale = true;
1895   StructuredData::Generic *generic = nullptr;
1896   if (implementor_sp)
1897     generic = implementor_sp->GetAsGeneric();
1898   if (generic) {
1899     Locker py_lock(this,
1900                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1901     is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
1902                                             nullptr, script_error);
1903     if (script_error)
1904       return true;
1905   }
1906   return is_stale;
1907 }
1908 
ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp,bool & script_error)1909 lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1910     StructuredData::ObjectSP implementor_sp, bool &script_error) {
1911   bool should_step = false;
1912   StructuredData::Generic *generic = nullptr;
1913   if (implementor_sp)
1914     generic = implementor_sp->GetAsGeneric();
1915   if (generic) {
1916     Locker py_lock(this,
1917                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1918     should_step = LLDBSWIGPythonCallThreadPlan(
1919         generic->GetValue(), "should_step", nullptr, script_error);
1920     if (script_error)
1921       should_step = true;
1922   }
1923   if (should_step)
1924     return lldb::eStateStepping;
1925   return lldb::eStateRunning;
1926 }
1927 
1928 StructuredData::GenericSP
CreateScriptedBreakpointResolver(const char * class_name,StructuredDataImpl * args_data,lldb::BreakpointSP & bkpt_sp)1929 ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1930     const char *class_name, StructuredDataImpl *args_data,
1931     lldb::BreakpointSP &bkpt_sp) {
1932 
1933   if (class_name == nullptr || class_name[0] == '\0')
1934     return StructuredData::GenericSP();
1935 
1936   if (!bkpt_sp.get())
1937     return StructuredData::GenericSP();
1938 
1939   Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1940   ScriptInterpreterPythonImpl *python_interpreter =
1941       GetPythonInterpreter(debugger);
1942 
1943   if (!python_interpreter)
1944     return StructuredData::GenericSP();
1945 
1946   void *ret_val;
1947 
1948   {
1949     Locker py_lock(this,
1950                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1951 
1952     ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
1953         class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1954         bkpt_sp);
1955   }
1956 
1957   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
1958 }
1959 
ScriptedBreakpointResolverSearchCallback(StructuredData::GenericSP implementor_sp,SymbolContext * sym_ctx)1960 bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1961     StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1962   bool should_continue = false;
1963 
1964   if (implementor_sp) {
1965     Locker py_lock(this,
1966                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1967     should_continue = LLDBSwigPythonCallBreakpointResolver(
1968         implementor_sp->GetValue(), "__callback__", sym_ctx);
1969     if (PyErr_Occurred()) {
1970       PyErr_Print();
1971       PyErr_Clear();
1972     }
1973   }
1974   return should_continue;
1975 }
1976 
1977 lldb::SearchDepth
ScriptedBreakpointResolverSearchDepth(StructuredData::GenericSP implementor_sp)1978 ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1979     StructuredData::GenericSP implementor_sp) {
1980   int depth_as_int = lldb::eSearchDepthModule;
1981   if (implementor_sp) {
1982     Locker py_lock(this,
1983                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1984     depth_as_int = LLDBSwigPythonCallBreakpointResolver(
1985         implementor_sp->GetValue(), "__get_depth__", nullptr);
1986     if (PyErr_Occurred()) {
1987       PyErr_Print();
1988       PyErr_Clear();
1989     }
1990   }
1991   if (depth_as_int == lldb::eSearchDepthInvalid)
1992     return lldb::eSearchDepthModule;
1993 
1994   if (depth_as_int <= lldb::kLastSearchDepthKind)
1995     return (lldb::SearchDepth)depth_as_int;
1996   return lldb::eSearchDepthModule;
1997 }
1998 
CreateScriptedStopHook(TargetSP target_sp,const char * class_name,StructuredDataImpl * args_data,Status & error)1999 StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
2000     TargetSP target_sp, const char *class_name, StructuredDataImpl *args_data,
2001     Status &error) {
2002 
2003   if (!target_sp) {
2004     error.SetErrorString("No target for scripted stop-hook.");
2005     return StructuredData::GenericSP();
2006   }
2007 
2008   if (class_name == nullptr || class_name[0] == '\0') {
2009     error.SetErrorString("No class name for scripted stop-hook.");
2010     return StructuredData::GenericSP();
2011   }
2012 
2013   ScriptInterpreterPythonImpl *python_interpreter =
2014       GetPythonInterpreter(m_debugger);
2015 
2016   if (!python_interpreter) {
2017     error.SetErrorString("No script interpreter for scripted stop-hook.");
2018     return StructuredData::GenericSP();
2019   }
2020 
2021   void *ret_val;
2022 
2023   {
2024     Locker py_lock(this,
2025                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2026 
2027     ret_val = LLDBSwigPythonCreateScriptedStopHook(
2028         target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
2029         args_data, error);
2030   }
2031 
2032   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
2033 }
2034 
ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp,ExecutionContext & exc_ctx,lldb::StreamSP stream_sp)2035 bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
2036     StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
2037     lldb::StreamSP stream_sp) {
2038   assert(implementor_sp &&
2039          "can't call a stop hook with an invalid implementor");
2040   assert(stream_sp && "can't call a stop hook with an invalid stream");
2041 
2042   Locker py_lock(this,
2043                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2044 
2045   lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
2046 
2047   bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
2048       implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
2049   return ret_val;
2050 }
2051 
2052 StructuredData::ObjectSP
LoadPluginModule(const FileSpec & file_spec,lldb_private::Status & error)2053 ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
2054                                               lldb_private::Status &error) {
2055   if (!FileSystem::Instance().Exists(file_spec)) {
2056     error.SetErrorString("no such file");
2057     return StructuredData::ObjectSP();
2058   }
2059 
2060   StructuredData::ObjectSP module_sp;
2061 
2062   if (LoadScriptingModule(file_spec.GetPath().c_str(), true, error, &module_sp))
2063     return module_sp;
2064 
2065   return StructuredData::ObjectSP();
2066 }
2067 
GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp,Target * target,const char * setting_name,lldb_private::Status & error)2068 StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
2069     StructuredData::ObjectSP plugin_module_sp, Target *target,
2070     const char *setting_name, lldb_private::Status &error) {
2071   if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
2072     return StructuredData::DictionarySP();
2073   StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
2074   if (!generic)
2075     return StructuredData::DictionarySP();
2076 
2077   Locker py_lock(this,
2078                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2079   TargetSP target_sp(target->shared_from_this());
2080 
2081   auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
2082       generic->GetValue(), setting_name, target_sp);
2083 
2084   if (!setting)
2085     return StructuredData::DictionarySP();
2086 
2087   PythonDictionary py_dict =
2088       unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
2089 
2090   if (!py_dict)
2091     return StructuredData::DictionarySP();
2092 
2093   return py_dict.CreateStructuredDictionary();
2094 }
2095 
2096 StructuredData::ObjectSP
CreateSyntheticScriptedProvider(const char * class_name,lldb::ValueObjectSP valobj)2097 ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2098     const char *class_name, lldb::ValueObjectSP valobj) {
2099   if (class_name == nullptr || class_name[0] == '\0')
2100     return StructuredData::ObjectSP();
2101 
2102   if (!valobj.get())
2103     return StructuredData::ObjectSP();
2104 
2105   ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
2106   Target *target = exe_ctx.GetTargetPtr();
2107 
2108   if (!target)
2109     return StructuredData::ObjectSP();
2110 
2111   Debugger &debugger = target->GetDebugger();
2112   ScriptInterpreterPythonImpl *python_interpreter =
2113       GetPythonInterpreter(debugger);
2114 
2115   if (!python_interpreter)
2116     return StructuredData::ObjectSP();
2117 
2118   void *ret_val = nullptr;
2119 
2120   {
2121     Locker py_lock(this,
2122                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2123     ret_val = LLDBSwigPythonCreateSyntheticProvider(
2124         class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
2125   }
2126 
2127   return StructuredData::ObjectSP(new StructuredPythonObject(ret_val));
2128 }
2129 
2130 StructuredData::GenericSP
CreateScriptCommandObject(const char * class_name)2131 ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
2132   DebuggerSP debugger_sp(m_debugger.shared_from_this());
2133 
2134   if (class_name == nullptr || class_name[0] == '\0')
2135     return StructuredData::GenericSP();
2136 
2137   if (!debugger_sp.get())
2138     return StructuredData::GenericSP();
2139 
2140   void *ret_val;
2141 
2142   {
2143     Locker py_lock(this,
2144                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2145     ret_val = LLDBSwigPythonCreateCommandObject(
2146         class_name, m_dictionary_name.c_str(), debugger_sp);
2147   }
2148 
2149   return StructuredData::GenericSP(new StructuredPythonObject(ret_val));
2150 }
2151 
GenerateTypeScriptFunction(const char * oneliner,std::string & output,const void * name_token)2152 bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2153     const char *oneliner, std::string &output, const void *name_token) {
2154   StringList input;
2155   input.SplitIntoLines(oneliner, strlen(oneliner));
2156   return GenerateTypeScriptFunction(input, output, name_token);
2157 }
2158 
GenerateTypeSynthClass(const char * oneliner,std::string & output,const void * name_token)2159 bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
2160     const char *oneliner, std::string &output, const void *name_token) {
2161   StringList input;
2162   input.SplitIntoLines(oneliner, strlen(oneliner));
2163   return GenerateTypeSynthClass(input, output, name_token);
2164 }
2165 
GenerateBreakpointCommandCallbackData(StringList & user_input,std::string & output,bool has_extra_args)2166 Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2167     StringList &user_input, std::string &output,
2168     bool has_extra_args) {
2169   static uint32_t num_created_functions = 0;
2170   user_input.RemoveBlankLines();
2171   StreamString sstr;
2172   Status error;
2173   if (user_input.GetSize() == 0) {
2174     error.SetErrorString("No input data.");
2175     return error;
2176   }
2177 
2178   std::string auto_generated_function_name(GenerateUniqueName(
2179       "lldb_autogen_python_bp_callback_func_", num_created_functions));
2180   if (has_extra_args)
2181     sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2182                 auto_generated_function_name.c_str());
2183   else
2184     sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2185                 auto_generated_function_name.c_str());
2186 
2187   error = GenerateFunction(sstr.GetData(), user_input);
2188   if (!error.Success())
2189     return error;
2190 
2191   // Store the name of the auto-generated function to be called.
2192   output.assign(auto_generated_function_name);
2193   return error;
2194 }
2195 
GenerateWatchpointCommandCallbackData(StringList & user_input,std::string & output)2196 bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2197     StringList &user_input, std::string &output) {
2198   static uint32_t num_created_functions = 0;
2199   user_input.RemoveBlankLines();
2200   StreamString sstr;
2201 
2202   if (user_input.GetSize() == 0)
2203     return false;
2204 
2205   std::string auto_generated_function_name(GenerateUniqueName(
2206       "lldb_autogen_python_wp_callback_func_", num_created_functions));
2207   sstr.Printf("def %s (frame, wp, internal_dict):",
2208               auto_generated_function_name.c_str());
2209 
2210   if (!GenerateFunction(sstr.GetData(), user_input).Success())
2211     return false;
2212 
2213   // Store the name of the auto-generated function to be called.
2214   output.assign(auto_generated_function_name);
2215   return true;
2216 }
2217 
GetScriptedSummary(const char * python_function_name,lldb::ValueObjectSP valobj,StructuredData::ObjectSP & callee_wrapper_sp,const TypeSummaryOptions & options,std::string & retval)2218 bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2219     const char *python_function_name, lldb::ValueObjectSP valobj,
2220     StructuredData::ObjectSP &callee_wrapper_sp,
2221     const TypeSummaryOptions &options, std::string &retval) {
2222 
2223   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2224   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
2225 
2226   if (!valobj.get()) {
2227     retval.assign("<no object>");
2228     return false;
2229   }
2230 
2231   void *old_callee = nullptr;
2232   StructuredData::Generic *generic = nullptr;
2233   if (callee_wrapper_sp) {
2234     generic = callee_wrapper_sp->GetAsGeneric();
2235     if (generic)
2236       old_callee = generic->GetValue();
2237   }
2238   void *new_callee = old_callee;
2239 
2240   bool ret_val;
2241   if (python_function_name && *python_function_name) {
2242     {
2243       Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2244                                Locker::NoSTDIN);
2245       {
2246         TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2247 
2248         static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2249         Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2250         ret_val = LLDBSwigPythonCallTypeScript(
2251             python_function_name, GetSessionDictionary().get(), valobj,
2252             &new_callee, options_sp, retval);
2253       }
2254     }
2255   } else {
2256     retval.assign("<no function name>");
2257     return false;
2258   }
2259 
2260   if (new_callee && old_callee != new_callee)
2261     callee_wrapper_sp = std::make_shared<StructuredPythonObject>(new_callee);
2262 
2263   return ret_val;
2264 }
2265 
BreakpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t break_id,user_id_t break_loc_id)2266 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2267     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2268     user_id_t break_loc_id) {
2269   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2270   const char *python_function_name = bp_option_data->script_source.c_str();
2271 
2272   if (!context)
2273     return true;
2274 
2275   ExecutionContext exe_ctx(context->exe_ctx_ref);
2276   Target *target = exe_ctx.GetTargetPtr();
2277 
2278   if (!target)
2279     return true;
2280 
2281   Debugger &debugger = target->GetDebugger();
2282   ScriptInterpreterPythonImpl *python_interpreter =
2283       GetPythonInterpreter(debugger);
2284 
2285   if (!python_interpreter)
2286     return true;
2287 
2288   if (python_function_name && python_function_name[0]) {
2289     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2290     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2291     if (breakpoint_sp) {
2292       const BreakpointLocationSP bp_loc_sp(
2293           breakpoint_sp->FindLocationByID(break_loc_id));
2294 
2295       if (stop_frame_sp && bp_loc_sp) {
2296         bool ret_val = true;
2297         {
2298           Locker py_lock(python_interpreter, Locker::AcquireLock |
2299                                                  Locker::InitSession |
2300                                                  Locker::NoSTDIN);
2301           Expected<bool> maybe_ret_val =
2302               LLDBSwigPythonBreakpointCallbackFunction(
2303                   python_function_name,
2304                   python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2305                   bp_loc_sp, bp_option_data->m_extra_args_up.get());
2306 
2307           if (!maybe_ret_val) {
2308 
2309             llvm::handleAllErrors(
2310                 maybe_ret_val.takeError(),
2311                 [&](PythonException &E) {
2312                   debugger.GetErrorStream() << E.ReadBacktrace();
2313                 },
2314                 [&](const llvm::ErrorInfoBase &E) {
2315                   debugger.GetErrorStream() << E.message();
2316                 });
2317 
2318           } else {
2319             ret_val = maybe_ret_val.get();
2320           }
2321         }
2322         return ret_val;
2323       }
2324     }
2325   }
2326   // We currently always true so we stop in case anything goes wrong when
2327   // trying to call the script function
2328   return true;
2329 }
2330 
WatchpointCallbackFunction(void * baton,StoppointCallbackContext * context,user_id_t watch_id)2331 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2332     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2333   WatchpointOptions::CommandData *wp_option_data =
2334       (WatchpointOptions::CommandData *)baton;
2335   const char *python_function_name = wp_option_data->script_source.c_str();
2336 
2337   if (!context)
2338     return true;
2339 
2340   ExecutionContext exe_ctx(context->exe_ctx_ref);
2341   Target *target = exe_ctx.GetTargetPtr();
2342 
2343   if (!target)
2344     return true;
2345 
2346   Debugger &debugger = target->GetDebugger();
2347   ScriptInterpreterPythonImpl *python_interpreter =
2348       GetPythonInterpreter(debugger);
2349 
2350   if (!python_interpreter)
2351     return true;
2352 
2353   if (python_function_name && python_function_name[0]) {
2354     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2355     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2356     if (wp_sp) {
2357       if (stop_frame_sp && wp_sp) {
2358         bool ret_val = true;
2359         {
2360           Locker py_lock(python_interpreter, Locker::AcquireLock |
2361                                                  Locker::InitSession |
2362                                                  Locker::NoSTDIN);
2363           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2364               python_function_name,
2365               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2366               wp_sp);
2367         }
2368         return ret_val;
2369       }
2370     }
2371   }
2372   // We currently always true so we stop in case anything goes wrong when
2373   // trying to call the script function
2374   return true;
2375 }
2376 
CalculateNumChildren(const StructuredData::ObjectSP & implementor_sp,uint32_t max)2377 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2378     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2379   if (!implementor_sp)
2380     return 0;
2381   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2382   if (!generic)
2383     return 0;
2384   void *implementor = generic->GetValue();
2385   if (!implementor)
2386     return 0;
2387 
2388   size_t ret_val = 0;
2389 
2390   {
2391     Locker py_lock(this,
2392                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2393     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2394   }
2395 
2396   return ret_val;
2397 }
2398 
GetChildAtIndex(const StructuredData::ObjectSP & implementor_sp,uint32_t idx)2399 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2400     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2401   if (!implementor_sp)
2402     return lldb::ValueObjectSP();
2403 
2404   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2405   if (!generic)
2406     return lldb::ValueObjectSP();
2407   void *implementor = generic->GetValue();
2408   if (!implementor)
2409     return lldb::ValueObjectSP();
2410 
2411   lldb::ValueObjectSP ret_val;
2412   {
2413     Locker py_lock(this,
2414                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2415     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2416     if (child_ptr != nullptr && child_ptr != Py_None) {
2417       lldb::SBValue *sb_value_ptr =
2418           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2419       if (sb_value_ptr == nullptr)
2420         Py_XDECREF(child_ptr);
2421       else
2422         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2423     } else {
2424       Py_XDECREF(child_ptr);
2425     }
2426   }
2427 
2428   return ret_val;
2429 }
2430 
GetIndexOfChildWithName(const StructuredData::ObjectSP & implementor_sp,const char * child_name)2431 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2432     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2433   if (!implementor_sp)
2434     return UINT32_MAX;
2435 
2436   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2437   if (!generic)
2438     return UINT32_MAX;
2439   void *implementor = generic->GetValue();
2440   if (!implementor)
2441     return UINT32_MAX;
2442 
2443   int ret_val = UINT32_MAX;
2444 
2445   {
2446     Locker py_lock(this,
2447                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2448     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2449   }
2450 
2451   return ret_val;
2452 }
2453 
UpdateSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)2454 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2455     const StructuredData::ObjectSP &implementor_sp) {
2456   bool ret_val = false;
2457 
2458   if (!implementor_sp)
2459     return ret_val;
2460 
2461   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2462   if (!generic)
2463     return ret_val;
2464   void *implementor = generic->GetValue();
2465   if (!implementor)
2466     return ret_val;
2467 
2468   {
2469     Locker py_lock(this,
2470                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2471     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2472   }
2473 
2474   return ret_val;
2475 }
2476 
MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP & implementor_sp)2477 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2478     const StructuredData::ObjectSP &implementor_sp) {
2479   bool ret_val = false;
2480 
2481   if (!implementor_sp)
2482     return ret_val;
2483 
2484   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2485   if (!generic)
2486     return ret_val;
2487   void *implementor = generic->GetValue();
2488   if (!implementor)
2489     return ret_val;
2490 
2491   {
2492     Locker py_lock(this,
2493                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2494     ret_val =
2495         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2496   }
2497 
2498   return ret_val;
2499 }
2500 
GetSyntheticValue(const StructuredData::ObjectSP & implementor_sp)2501 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2502     const StructuredData::ObjectSP &implementor_sp) {
2503   lldb::ValueObjectSP ret_val(nullptr);
2504 
2505   if (!implementor_sp)
2506     return ret_val;
2507 
2508   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2509   if (!generic)
2510     return ret_val;
2511   void *implementor = generic->GetValue();
2512   if (!implementor)
2513     return ret_val;
2514 
2515   {
2516     Locker py_lock(this,
2517                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2518     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2519     if (child_ptr != nullptr && child_ptr != Py_None) {
2520       lldb::SBValue *sb_value_ptr =
2521           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2522       if (sb_value_ptr == nullptr)
2523         Py_XDECREF(child_ptr);
2524       else
2525         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2526     } else {
2527       Py_XDECREF(child_ptr);
2528     }
2529   }
2530 
2531   return ret_val;
2532 }
2533 
GetSyntheticTypeName(const StructuredData::ObjectSP & implementor_sp)2534 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2535     const StructuredData::ObjectSP &implementor_sp) {
2536   Locker py_lock(this,
2537                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2538 
2539   static char callee_name[] = "get_type_name";
2540 
2541   ConstString ret_val;
2542   bool got_string = false;
2543   std::string buffer;
2544 
2545   if (!implementor_sp)
2546     return ret_val;
2547 
2548   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2549   if (!generic)
2550     return ret_val;
2551   PythonObject implementor(PyRefType::Borrowed,
2552                            (PyObject *)generic->GetValue());
2553   if (!implementor.IsAllocated())
2554     return ret_val;
2555 
2556   PythonObject pmeth(PyRefType::Owned,
2557                      PyObject_GetAttrString(implementor.get(), callee_name));
2558 
2559   if (PyErr_Occurred())
2560     PyErr_Clear();
2561 
2562   if (!pmeth.IsAllocated())
2563     return ret_val;
2564 
2565   if (PyCallable_Check(pmeth.get()) == 0) {
2566     if (PyErr_Occurred())
2567       PyErr_Clear();
2568     return ret_val;
2569   }
2570 
2571   if (PyErr_Occurred())
2572     PyErr_Clear();
2573 
2574   // right now we know this function exists and is callable..
2575   PythonObject py_return(
2576       PyRefType::Owned,
2577       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2578 
2579   // if it fails, print the error but otherwise go on
2580   if (PyErr_Occurred()) {
2581     PyErr_Print();
2582     PyErr_Clear();
2583   }
2584 
2585   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2586     PythonString py_string(PyRefType::Borrowed, py_return.get());
2587     llvm::StringRef return_data(py_string.GetString());
2588     if (!return_data.empty()) {
2589       buffer.assign(return_data.data(), return_data.size());
2590       got_string = true;
2591     }
2592   }
2593 
2594   if (got_string)
2595     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2596 
2597   return ret_val;
2598 }
2599 
RunScriptFormatKeyword(const char * impl_function,Process * process,std::string & output,Status & error)2600 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2601     const char *impl_function, Process *process, std::string &output,
2602     Status &error) {
2603   bool ret_val;
2604   if (!process) {
2605     error.SetErrorString("no process");
2606     return false;
2607   }
2608   if (!impl_function || !impl_function[0]) {
2609     error.SetErrorString("no function to execute");
2610     return false;
2611   }
2612 
2613   {
2614     ProcessSP process_sp(process->shared_from_this());
2615     Locker py_lock(this,
2616                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2617     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2618         impl_function, m_dictionary_name.c_str(), process_sp, output);
2619     if (!ret_val)
2620       error.SetErrorString("python script evaluation failed");
2621   }
2622   return ret_val;
2623 }
2624 
RunScriptFormatKeyword(const char * impl_function,Thread * thread,std::string & output,Status & error)2625 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2626     const char *impl_function, Thread *thread, std::string &output,
2627     Status &error) {
2628   bool ret_val;
2629   if (!thread) {
2630     error.SetErrorString("no thread");
2631     return false;
2632   }
2633   if (!impl_function || !impl_function[0]) {
2634     error.SetErrorString("no function to execute");
2635     return false;
2636   }
2637 
2638   {
2639     ThreadSP thread_sp(thread->shared_from_this());
2640     Locker py_lock(this,
2641                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2642     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
2643         impl_function, m_dictionary_name.c_str(), thread_sp, output);
2644     if (!ret_val)
2645       error.SetErrorString("python script evaluation failed");
2646   }
2647   return ret_val;
2648 }
2649 
RunScriptFormatKeyword(const char * impl_function,Target * target,std::string & output,Status & error)2650 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2651     const char *impl_function, Target *target, std::string &output,
2652     Status &error) {
2653   bool ret_val;
2654   if (!target) {
2655     error.SetErrorString("no thread");
2656     return false;
2657   }
2658   if (!impl_function || !impl_function[0]) {
2659     error.SetErrorString("no function to execute");
2660     return false;
2661   }
2662 
2663   {
2664     TargetSP target_sp(target->shared_from_this());
2665     Locker py_lock(this,
2666                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2667     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2668         impl_function, m_dictionary_name.c_str(), target_sp, output);
2669     if (!ret_val)
2670       error.SetErrorString("python script evaluation failed");
2671   }
2672   return ret_val;
2673 }
2674 
RunScriptFormatKeyword(const char * impl_function,StackFrame * frame,std::string & output,Status & error)2675 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2676     const char *impl_function, StackFrame *frame, std::string &output,
2677     Status &error) {
2678   bool ret_val;
2679   if (!frame) {
2680     error.SetErrorString("no frame");
2681     return false;
2682   }
2683   if (!impl_function || !impl_function[0]) {
2684     error.SetErrorString("no function to execute");
2685     return false;
2686   }
2687 
2688   {
2689     StackFrameSP frame_sp(frame->shared_from_this());
2690     Locker py_lock(this,
2691                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2692     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
2693         impl_function, m_dictionary_name.c_str(), frame_sp, output);
2694     if (!ret_val)
2695       error.SetErrorString("python script evaluation failed");
2696   }
2697   return ret_val;
2698 }
2699 
RunScriptFormatKeyword(const char * impl_function,ValueObject * value,std::string & output,Status & error)2700 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2701     const char *impl_function, ValueObject *value, std::string &output,
2702     Status &error) {
2703   bool ret_val;
2704   if (!value) {
2705     error.SetErrorString("no value");
2706     return false;
2707   }
2708   if (!impl_function || !impl_function[0]) {
2709     error.SetErrorString("no function to execute");
2710     return false;
2711   }
2712 
2713   {
2714     ValueObjectSP value_sp(value->GetSP());
2715     Locker py_lock(this,
2716                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2717     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2718         impl_function, m_dictionary_name.c_str(), value_sp, output);
2719     if (!ret_val)
2720       error.SetErrorString("python script evaluation failed");
2721   }
2722   return ret_val;
2723 }
2724 
replace_all(std::string & str,const std::string & oldStr,const std::string & newStr)2725 uint64_t replace_all(std::string &str, const std::string &oldStr,
2726                      const std::string &newStr) {
2727   size_t pos = 0;
2728   uint64_t matches = 0;
2729   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2730     matches++;
2731     str.replace(pos, oldStr.length(), newStr);
2732     pos += newStr.length();
2733   }
2734   return matches;
2735 }
2736 
LoadScriptingModule(const char * pathname,bool init_session,lldb_private::Status & error,StructuredData::ObjectSP * module_sp,FileSpec extra_search_dir)2737 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2738     const char *pathname, bool init_session, lldb_private::Status &error,
2739     StructuredData::ObjectSP *module_sp, FileSpec extra_search_dir) {
2740   namespace fs = llvm::sys::fs;
2741   namespace path = llvm::sys::path;
2742 
2743   if (!pathname || !pathname[0]) {
2744     error.SetErrorString("invalid pathname");
2745     return false;
2746   }
2747 
2748   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2749 
2750   // Before executing Python code, lock the GIL.
2751   Locker py_lock(this,
2752                  Locker::AcquireLock |
2753                      (init_session ? Locker::InitSession : 0) | Locker::NoSTDIN,
2754                  Locker::FreeAcquiredLock |
2755                      (init_session ? Locker::TearDownSession : 0));
2756 
2757   auto ExtendSysPath = [this](std::string directory) -> llvm::Error {
2758     if (directory.empty()) {
2759       return llvm::make_error<llvm::StringError>(
2760           "invalid directory name", llvm::inconvertibleErrorCode());
2761     }
2762 
2763     replace_all(directory, "\\", "\\\\");
2764     replace_all(directory, "'", "\\'");
2765 
2766     // Make sure that Python has "directory" in the search path.
2767     StreamString command_stream;
2768     command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2769                           "sys.path.insert(1,'%s');\n\n",
2770                           directory.c_str(), directory.c_str());
2771     bool syspath_retval =
2772         ExecuteMultipleLines(command_stream.GetData(),
2773                              ScriptInterpreter::ExecuteScriptOptions()
2774                                  .SetEnableIO(false)
2775                                  .SetSetLLDBGlobals(false))
2776             .Success();
2777     if (!syspath_retval) {
2778       return llvm::make_error<llvm::StringError>(
2779           "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2780     }
2781 
2782     return llvm::Error::success();
2783   };
2784 
2785   std::string module_name(pathname);
2786 
2787   if (extra_search_dir) {
2788     if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2789       error = std::move(e);
2790       return false;
2791     }
2792   } else {
2793     FileSpec module_file(pathname);
2794     FileSystem::Instance().Resolve(module_file);
2795     FileSystem::Instance().Collect(module_file);
2796 
2797     fs::file_status st;
2798     std::error_code ec = status(module_file.GetPath(), st);
2799 
2800     if (ec || st.type() == fs::file_type::status_error ||
2801         st.type() == fs::file_type::type_unknown ||
2802         st.type() == fs::file_type::file_not_found) {
2803       // if not a valid file of any sort, check if it might be a filename still
2804       // dot can't be used but / and \ can, and if either is found, reject
2805       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2806         error.SetErrorString("invalid pathname");
2807         return false;
2808       }
2809       // Not a filename, probably a package of some sort, let it go through.
2810     } else if (is_directory(st) || is_regular_file(st)) {
2811       if (module_file.GetDirectory().IsEmpty()) {
2812         error.SetErrorString("invalid directory name");
2813         return false;
2814       }
2815       if (llvm::Error e =
2816               ExtendSysPath(module_file.GetDirectory().GetCString())) {
2817         error = std::move(e);
2818         return false;
2819       }
2820       module_name = module_file.GetFilename().GetCString();
2821     } else {
2822       error.SetErrorString("no known way to import this module specification");
2823       return false;
2824     }
2825   }
2826 
2827   // Strip .py or .pyc extension
2828   llvm::StringRef extension = llvm::sys::path::extension(module_name);
2829   if (!extension.empty()) {
2830     if (extension == ".py")
2831       module_name.resize(module_name.length() - 3);
2832     else if (extension == ".pyc")
2833       module_name.resize(module_name.length() - 4);
2834   }
2835 
2836   // check if the module is already import-ed
2837   StreamString command_stream;
2838   command_stream.Clear();
2839   command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2840   bool does_contain = false;
2841   // this call will succeed if the module was ever imported in any Debugger
2842   // in the lifetime of the process in which this LLDB framework is living
2843   bool was_imported_globally =
2844       (ExecuteOneLineWithReturn(
2845            command_stream.GetData(),
2846            ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2847            ScriptInterpreter::ExecuteScriptOptions()
2848                .SetEnableIO(false)
2849                .SetSetLLDBGlobals(false)) &&
2850        does_contain);
2851   // this call will fail if the module was not imported in this Debugger
2852   // before
2853   command_stream.Clear();
2854   command_stream.Printf("sys.getrefcount(%s)", module_name.c_str());
2855   bool was_imported_locally = GetSessionDictionary()
2856                                   .GetItemForKey(PythonString(module_name))
2857                                   .IsAllocated();
2858 
2859   bool was_imported = (was_imported_globally || was_imported_locally);
2860 
2861   // now actually do the import
2862   command_stream.Clear();
2863 
2864   if (was_imported) {
2865     if (!was_imported_locally)
2866       command_stream.Printf("import %s ; reload_module(%s)",
2867                             module_name.c_str(), module_name.c_str());
2868     else
2869       command_stream.Printf("reload_module(%s)", module_name.c_str());
2870   } else
2871     command_stream.Printf("import %s", module_name.c_str());
2872 
2873   error = ExecuteMultipleLines(command_stream.GetData(),
2874                                ScriptInterpreter::ExecuteScriptOptions()
2875                                    .SetEnableIO(false)
2876                                    .SetSetLLDBGlobals(false));
2877   if (error.Fail())
2878     return false;
2879 
2880   // if we are here, everything worked
2881   // call __lldb_init_module(debugger,dict)
2882   if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2883                                     m_dictionary_name.c_str(), debugger_sp)) {
2884     error.SetErrorString("calling __lldb_init_module failed");
2885     return false;
2886   }
2887 
2888   if (module_sp) {
2889     // everything went just great, now set the module object
2890     command_stream.Clear();
2891     command_stream.Printf("%s", module_name.c_str());
2892     void *module_pyobj = nullptr;
2893     if (ExecuteOneLineWithReturn(
2894             command_stream.GetData(),
2895             ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj) &&
2896         module_pyobj)
2897       *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
2898   }
2899 
2900   return true;
2901 }
2902 
IsReservedWord(const char * word)2903 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2904   if (!word || !word[0])
2905     return false;
2906 
2907   llvm::StringRef word_sr(word);
2908 
2909   // filter out a few characters that would just confuse us and that are
2910   // clearly not keyword material anyway
2911   if (word_sr.find('"') != llvm::StringRef::npos ||
2912       word_sr.find('\'') != llvm::StringRef::npos)
2913     return false;
2914 
2915   StreamString command_stream;
2916   command_stream.Printf("keyword.iskeyword('%s')", word);
2917   bool result;
2918   ExecuteScriptOptions options;
2919   options.SetEnableIO(false);
2920   options.SetMaskoutErrors(true);
2921   options.SetSetLLDBGlobals(false);
2922   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2923                                ScriptInterpreter::eScriptReturnTypeBool,
2924                                &result, options))
2925     return result;
2926   return false;
2927 }
2928 
SynchronicityHandler(lldb::DebuggerSP debugger_sp,ScriptedCommandSynchronicity synchro)2929 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2930     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2931     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2932       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2933   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2934     m_debugger_sp->SetAsyncExecution(false);
2935   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2936     m_debugger_sp->SetAsyncExecution(true);
2937 }
2938 
~SynchronicityHandler()2939 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2940   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2941     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2942 }
2943 
RunScriptBasedCommand(const char * impl_function,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)2944 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2945     const char *impl_function, llvm::StringRef args,
2946     ScriptedCommandSynchronicity synchronicity,
2947     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2948     const lldb_private::ExecutionContext &exe_ctx) {
2949   if (!impl_function) {
2950     error.SetErrorString("no function to execute");
2951     return false;
2952   }
2953 
2954   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2955   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2956 
2957   if (!debugger_sp.get()) {
2958     error.SetErrorString("invalid Debugger pointer");
2959     return false;
2960   }
2961 
2962   bool ret_val = false;
2963 
2964   std::string err_msg;
2965 
2966   {
2967     Locker py_lock(this,
2968                    Locker::AcquireLock | Locker::InitSession |
2969                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2970                    Locker::FreeLock | Locker::TearDownSession);
2971 
2972     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2973 
2974     std::string args_str = args.str();
2975     ret_val = LLDBSwigPythonCallCommand(
2976         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2977         cmd_retobj, exe_ctx_ref_sp);
2978   }
2979 
2980   if (!ret_val)
2981     error.SetErrorString("unable to execute script function");
2982   else
2983     error.Clear();
2984 
2985   return ret_val;
2986 }
2987 
RunScriptBasedCommand(StructuredData::GenericSP impl_obj_sp,llvm::StringRef args,ScriptedCommandSynchronicity synchronicity,lldb_private::CommandReturnObject & cmd_retobj,Status & error,const lldb_private::ExecutionContext & exe_ctx)2988 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2989     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2990     ScriptedCommandSynchronicity synchronicity,
2991     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2992     const lldb_private::ExecutionContext &exe_ctx) {
2993   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2994     error.SetErrorString("no function to execute");
2995     return false;
2996   }
2997 
2998   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2999   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
3000 
3001   if (!debugger_sp.get()) {
3002     error.SetErrorString("invalid Debugger pointer");
3003     return false;
3004   }
3005 
3006   bool ret_val = false;
3007 
3008   std::string err_msg;
3009 
3010   {
3011     Locker py_lock(this,
3012                    Locker::AcquireLock | Locker::InitSession |
3013                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
3014                    Locker::FreeLock | Locker::TearDownSession);
3015 
3016     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
3017 
3018     std::string args_str = args.str();
3019     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
3020                                               debugger_sp, args_str.c_str(),
3021                                               cmd_retobj, exe_ctx_ref_sp);
3022   }
3023 
3024   if (!ret_val)
3025     error.SetErrorString("unable to execute script function");
3026   else
3027     error.Clear();
3028 
3029   return ret_val;
3030 }
3031 
3032 /// In Python, a special attribute __doc__ contains the docstring for an object
3033 /// (function, method, class, ...) if any is defined Otherwise, the attribute's
3034 /// value is None.
GetDocumentationForItem(const char * item,std::string & dest)3035 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
3036                                                           std::string &dest) {
3037   dest.clear();
3038 
3039   if (!item || !*item)
3040     return false;
3041 
3042   std::string command(item);
3043   command += ".__doc__";
3044 
3045   // Python is going to point this to valid data if ExecuteOneLineWithReturn
3046   // returns successfully.
3047   char *result_ptr = nullptr;
3048 
3049   if (ExecuteOneLineWithReturn(
3050           command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
3051           &result_ptr,
3052           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
3053     if (result_ptr)
3054       dest.assign(result_ptr);
3055     return true;
3056   }
3057 
3058   StreamString str_stream;
3059   str_stream << "Function " << item
3060              << " was not found. Containing module might be missing.";
3061   dest = std::string(str_stream.GetString());
3062 
3063   return false;
3064 }
3065 
GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)3066 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
3067     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3068   dest.clear();
3069 
3070   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3071 
3072   static char callee_name[] = "get_short_help";
3073 
3074   if (!cmd_obj_sp)
3075     return false;
3076 
3077   PythonObject implementor(PyRefType::Borrowed,
3078                            (PyObject *)cmd_obj_sp->GetValue());
3079 
3080   if (!implementor.IsAllocated())
3081     return false;
3082 
3083   PythonObject pmeth(PyRefType::Owned,
3084                      PyObject_GetAttrString(implementor.get(), callee_name));
3085 
3086   if (PyErr_Occurred())
3087     PyErr_Clear();
3088 
3089   if (!pmeth.IsAllocated())
3090     return false;
3091 
3092   if (PyCallable_Check(pmeth.get()) == 0) {
3093     if (PyErr_Occurred())
3094       PyErr_Clear();
3095     return false;
3096   }
3097 
3098   if (PyErr_Occurred())
3099     PyErr_Clear();
3100 
3101   // Right now we know this function exists and is callable.
3102   PythonObject py_return(
3103       PyRefType::Owned,
3104       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3105 
3106   // If it fails, print the error but otherwise go on.
3107   if (PyErr_Occurred()) {
3108     PyErr_Print();
3109     PyErr_Clear();
3110   }
3111 
3112   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3113     PythonString py_string(PyRefType::Borrowed, py_return.get());
3114     llvm::StringRef return_data(py_string.GetString());
3115     dest.assign(return_data.data(), return_data.size());
3116     return true;
3117   }
3118 
3119   return false;
3120 }
3121 
GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp)3122 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3123     StructuredData::GenericSP cmd_obj_sp) {
3124   uint32_t result = 0;
3125 
3126   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3127 
3128   static char callee_name[] = "get_flags";
3129 
3130   if (!cmd_obj_sp)
3131     return result;
3132 
3133   PythonObject implementor(PyRefType::Borrowed,
3134                            (PyObject *)cmd_obj_sp->GetValue());
3135 
3136   if (!implementor.IsAllocated())
3137     return result;
3138 
3139   PythonObject pmeth(PyRefType::Owned,
3140                      PyObject_GetAttrString(implementor.get(), callee_name));
3141 
3142   if (PyErr_Occurred())
3143     PyErr_Clear();
3144 
3145   if (!pmeth.IsAllocated())
3146     return result;
3147 
3148   if (PyCallable_Check(pmeth.get()) == 0) {
3149     if (PyErr_Occurred())
3150       PyErr_Clear();
3151     return result;
3152   }
3153 
3154   if (PyErr_Occurred())
3155     PyErr_Clear();
3156 
3157   long long py_return = unwrapOrSetPythonException(
3158       As<long long>(implementor.CallMethod(callee_name)));
3159 
3160   // if it fails, print the error but otherwise go on
3161   if (PyErr_Occurred()) {
3162     PyErr_Print();
3163     PyErr_Clear();
3164   } else {
3165     result = py_return;
3166   }
3167 
3168   return result;
3169 }
3170 
GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp,std::string & dest)3171 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3172     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3173   bool got_string = false;
3174   dest.clear();
3175 
3176   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3177 
3178   static char callee_name[] = "get_long_help";
3179 
3180   if (!cmd_obj_sp)
3181     return false;
3182 
3183   PythonObject implementor(PyRefType::Borrowed,
3184                            (PyObject *)cmd_obj_sp->GetValue());
3185 
3186   if (!implementor.IsAllocated())
3187     return false;
3188 
3189   PythonObject pmeth(PyRefType::Owned,
3190                      PyObject_GetAttrString(implementor.get(), callee_name));
3191 
3192   if (PyErr_Occurred())
3193     PyErr_Clear();
3194 
3195   if (!pmeth.IsAllocated())
3196     return false;
3197 
3198   if (PyCallable_Check(pmeth.get()) == 0) {
3199     if (PyErr_Occurred())
3200       PyErr_Clear();
3201 
3202     return false;
3203   }
3204 
3205   if (PyErr_Occurred())
3206     PyErr_Clear();
3207 
3208   // right now we know this function exists and is callable..
3209   PythonObject py_return(
3210       PyRefType::Owned,
3211       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3212 
3213   // if it fails, print the error but otherwise go on
3214   if (PyErr_Occurred()) {
3215     PyErr_Print();
3216     PyErr_Clear();
3217   }
3218 
3219   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3220     PythonString str(PyRefType::Borrowed, py_return.get());
3221     llvm::StringRef str_data(str.GetString());
3222     dest.assign(str_data.data(), str_data.size());
3223     got_string = true;
3224   }
3225 
3226   return got_string;
3227 }
3228 
3229 std::unique_ptr<ScriptInterpreterLocker>
AcquireInterpreterLock()3230 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3231   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3232       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3233       Locker::FreeLock | Locker::TearDownSession));
3234   return py_lock;
3235 }
3236 
InitializePrivate()3237 void ScriptInterpreterPythonImpl::InitializePrivate() {
3238   if (g_initialized)
3239     return;
3240 
3241   g_initialized = true;
3242 
3243   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
3244   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
3245 
3246   // RAII-based initialization which correctly handles multiple-initialization,
3247   // version- specific differences among Python 2 and Python 3, and saving and
3248   // restoring various other pieces of state that can get mucked with during
3249   // initialization.
3250   InitializePythonRAII initialize_guard;
3251 
3252   LLDBSwigPyInit();
3253 
3254   // Update the path python uses to search for modules to include the current
3255   // directory.
3256 
3257   PyRun_SimpleString("import sys");
3258   AddToSysPath(AddLocation::End, ".");
3259 
3260   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3261   // that use a backslash as the path separator, this will result in executing
3262   // python code containing paths with unescaped backslashes.  But Python also
3263   // accepts forward slashes, so to make life easier we just use that.
3264   if (FileSpec file_spec = GetPythonDir())
3265     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3266   if (FileSpec file_spec = HostInfo::GetShlibDir())
3267     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3268 
3269   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3270                      "lldb.embedded_interpreter; from "
3271                      "lldb.embedded_interpreter import run_python_interpreter; "
3272                      "from lldb.embedded_interpreter import run_one_line");
3273 }
3274 
AddToSysPath(AddLocation location,std::string path)3275 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3276                                                std::string path) {
3277   std::string path_copy;
3278 
3279   std::string statement;
3280   if (location == AddLocation::Beginning) {
3281     statement.assign("sys.path.insert(0,\"");
3282     statement.append(path);
3283     statement.append("\")");
3284   } else {
3285     statement.assign("sys.path.append(\"");
3286     statement.append(path);
3287     statement.append("\")");
3288   }
3289   PyRun_SimpleString(statement.c_str());
3290 }
3291 
3292 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3293 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3294 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3295 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3296 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3297 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3298 // which calls ScriptInterpreter::Terminate, which calls
3299 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3300 // end up with Py_Finalize being called from within Py_Finalize, which results
3301 // in a seg fault. Since this function only gets called when lldb is shutting
3302 // down and going away anyway, the fact that we don't actually call Py_Finalize
3303 // should not cause any problems (everything should shut down/go away anyway
3304 // when the process exits).
3305 //
3306 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3307 
3308 #endif
3309