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