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