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