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