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