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