xref: /llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp (revision a8f3ae7c9cefa8296d119f92ca444087cdccf712)
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 void ScriptInterpreterPythonImpl::Clear() {
2216   // Release any global variables that might have strong references to
2217   // LLDB objects when clearing the python script interpreter.
2218   Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
2219 
2220   // This may be called as part of Py_Finalize.  In that case the modules are
2221   // destroyed in random order and we can't guarantee that we can access these.
2222   if (Py_IsInitialized())
2223     PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
2224                        "= None; lldb.thread = None; lldb.frame = None");
2225 }
2226 
2227 bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2228     void *baton, StoppointCallbackContext *context, user_id_t break_id,
2229     user_id_t break_loc_id) {
2230   CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2231   const char *python_function_name = bp_option_data->script_source.c_str();
2232 
2233   if (!context)
2234     return true;
2235 
2236   ExecutionContext exe_ctx(context->exe_ctx_ref);
2237   Target *target = exe_ctx.GetTargetPtr();
2238 
2239   if (!target)
2240     return true;
2241 
2242   Debugger &debugger = target->GetDebugger();
2243   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
2244   ScriptInterpreterPythonImpl *python_interpreter =
2245       (ScriptInterpreterPythonImpl *)script_interpreter;
2246 
2247   if (!script_interpreter)
2248     return true;
2249 
2250   if (python_function_name && python_function_name[0]) {
2251     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2252     BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2253     if (breakpoint_sp) {
2254       const BreakpointLocationSP bp_loc_sp(
2255           breakpoint_sp->FindLocationByID(break_loc_id));
2256 
2257       if (stop_frame_sp && bp_loc_sp) {
2258         bool ret_val = true;
2259         {
2260           Locker py_lock(python_interpreter, Locker::AcquireLock |
2261                                                  Locker::InitSession |
2262                                                  Locker::NoSTDIN);
2263           ret_val = LLDBSwigPythonBreakpointCallbackFunction(
2264               python_function_name,
2265               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2266               bp_loc_sp);
2267         }
2268         return ret_val;
2269       }
2270     }
2271   }
2272   // We currently always true so we stop in case anything goes wrong when
2273   // trying to call the script function
2274   return true;
2275 }
2276 
2277 bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2278     void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2279   WatchpointOptions::CommandData *wp_option_data =
2280       (WatchpointOptions::CommandData *)baton;
2281   const char *python_function_name = wp_option_data->script_source.c_str();
2282 
2283   if (!context)
2284     return true;
2285 
2286   ExecutionContext exe_ctx(context->exe_ctx_ref);
2287   Target *target = exe_ctx.GetTargetPtr();
2288 
2289   if (!target)
2290     return true;
2291 
2292   Debugger &debugger = target->GetDebugger();
2293   ScriptInterpreter *script_interpreter = debugger.GetScriptInterpreter();
2294   ScriptInterpreterPythonImpl *python_interpreter =
2295       (ScriptInterpreterPythonImpl *)script_interpreter;
2296 
2297   if (!script_interpreter)
2298     return true;
2299 
2300   if (python_function_name && python_function_name[0]) {
2301     const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2302     WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2303     if (wp_sp) {
2304       if (stop_frame_sp && wp_sp) {
2305         bool ret_val = true;
2306         {
2307           Locker py_lock(python_interpreter, Locker::AcquireLock |
2308                                                  Locker::InitSession |
2309                                                  Locker::NoSTDIN);
2310           ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2311               python_function_name,
2312               python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2313               wp_sp);
2314         }
2315         return ret_val;
2316       }
2317     }
2318   }
2319   // We currently always true so we stop in case anything goes wrong when
2320   // trying to call the script function
2321   return true;
2322 }
2323 
2324 size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2325     const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2326   if (!implementor_sp)
2327     return 0;
2328   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2329   if (!generic)
2330     return 0;
2331   void *implementor = generic->GetValue();
2332   if (!implementor)
2333     return 0;
2334 
2335   size_t ret_val = 0;
2336 
2337   {
2338     Locker py_lock(this,
2339                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2340     ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2341   }
2342 
2343   return ret_val;
2344 }
2345 
2346 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2347     const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2348   if (!implementor_sp)
2349     return lldb::ValueObjectSP();
2350 
2351   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2352   if (!generic)
2353     return lldb::ValueObjectSP();
2354   void *implementor = generic->GetValue();
2355   if (!implementor)
2356     return lldb::ValueObjectSP();
2357 
2358   lldb::ValueObjectSP ret_val;
2359   {
2360     Locker py_lock(this,
2361                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2362     void *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2363     if (child_ptr != nullptr && child_ptr != Py_None) {
2364       lldb::SBValue *sb_value_ptr =
2365           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2366       if (sb_value_ptr == nullptr)
2367         Py_XDECREF(child_ptr);
2368       else
2369         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2370     } else {
2371       Py_XDECREF(child_ptr);
2372     }
2373   }
2374 
2375   return ret_val;
2376 }
2377 
2378 int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2379     const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2380   if (!implementor_sp)
2381     return UINT32_MAX;
2382 
2383   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2384   if (!generic)
2385     return UINT32_MAX;
2386   void *implementor = generic->GetValue();
2387   if (!implementor)
2388     return UINT32_MAX;
2389 
2390   int ret_val = UINT32_MAX;
2391 
2392   {
2393     Locker py_lock(this,
2394                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2395     ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2396   }
2397 
2398   return ret_val;
2399 }
2400 
2401 bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2402     const StructuredData::ObjectSP &implementor_sp) {
2403   bool ret_val = false;
2404 
2405   if (!implementor_sp)
2406     return ret_val;
2407 
2408   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2409   if (!generic)
2410     return ret_val;
2411   void *implementor = generic->GetValue();
2412   if (!implementor)
2413     return ret_val;
2414 
2415   {
2416     Locker py_lock(this,
2417                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2418     ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2419   }
2420 
2421   return ret_val;
2422 }
2423 
2424 bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2425     const StructuredData::ObjectSP &implementor_sp) {
2426   bool ret_val = false;
2427 
2428   if (!implementor_sp)
2429     return ret_val;
2430 
2431   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2432   if (!generic)
2433     return ret_val;
2434   void *implementor = generic->GetValue();
2435   if (!implementor)
2436     return ret_val;
2437 
2438   {
2439     Locker py_lock(this,
2440                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2441     ret_val =
2442         LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2443   }
2444 
2445   return ret_val;
2446 }
2447 
2448 lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2449     const StructuredData::ObjectSP &implementor_sp) {
2450   lldb::ValueObjectSP ret_val(nullptr);
2451 
2452   if (!implementor_sp)
2453     return ret_val;
2454 
2455   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2456   if (!generic)
2457     return ret_val;
2458   void *implementor = generic->GetValue();
2459   if (!implementor)
2460     return ret_val;
2461 
2462   {
2463     Locker py_lock(this,
2464                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2465     void *child_ptr = LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2466     if (child_ptr != nullptr && child_ptr != Py_None) {
2467       lldb::SBValue *sb_value_ptr =
2468           (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2469       if (sb_value_ptr == nullptr)
2470         Py_XDECREF(child_ptr);
2471       else
2472         ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2473     } else {
2474       Py_XDECREF(child_ptr);
2475     }
2476   }
2477 
2478   return ret_val;
2479 }
2480 
2481 ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2482     const StructuredData::ObjectSP &implementor_sp) {
2483   Locker py_lock(this,
2484                  Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2485 
2486   static char callee_name[] = "get_type_name";
2487 
2488   ConstString ret_val;
2489   bool got_string = false;
2490   std::string buffer;
2491 
2492   if (!implementor_sp)
2493     return ret_val;
2494 
2495   StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2496   if (!generic)
2497     return ret_val;
2498   PythonObject implementor(PyRefType::Borrowed,
2499                            (PyObject *)generic->GetValue());
2500   if (!implementor.IsAllocated())
2501     return ret_val;
2502 
2503   PythonObject pmeth(PyRefType::Owned,
2504                      PyObject_GetAttrString(implementor.get(), callee_name));
2505 
2506   if (PyErr_Occurred())
2507     PyErr_Clear();
2508 
2509   if (!pmeth.IsAllocated())
2510     return ret_val;
2511 
2512   if (PyCallable_Check(pmeth.get()) == 0) {
2513     if (PyErr_Occurred())
2514       PyErr_Clear();
2515     return ret_val;
2516   }
2517 
2518   if (PyErr_Occurred())
2519     PyErr_Clear();
2520 
2521   // right now we know this function exists and is callable..
2522   PythonObject py_return(
2523       PyRefType::Owned,
2524       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2525 
2526   // if it fails, print the error but otherwise go on
2527   if (PyErr_Occurred()) {
2528     PyErr_Print();
2529     PyErr_Clear();
2530   }
2531 
2532   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2533     PythonString py_string(PyRefType::Borrowed, py_return.get());
2534     llvm::StringRef return_data(py_string.GetString());
2535     if (!return_data.empty()) {
2536       buffer.assign(return_data.data(), return_data.size());
2537       got_string = true;
2538     }
2539   }
2540 
2541   if (got_string)
2542     ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2543 
2544   return ret_val;
2545 }
2546 
2547 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2548     const char *impl_function, Process *process, std::string &output,
2549     Status &error) {
2550   bool ret_val;
2551   if (!process) {
2552     error.SetErrorString("no process");
2553     return false;
2554   }
2555   if (!impl_function || !impl_function[0]) {
2556     error.SetErrorString("no function to execute");
2557     return false;
2558   }
2559 
2560   {
2561     ProcessSP process_sp(process->shared_from_this());
2562     Locker py_lock(this,
2563                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2564     ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2565         impl_function, m_dictionary_name.c_str(), process_sp, output);
2566     if (!ret_val)
2567       error.SetErrorString("python script evaluation failed");
2568   }
2569   return ret_val;
2570 }
2571 
2572 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2573     const char *impl_function, Thread *thread, std::string &output,
2574     Status &error) {
2575   bool ret_val;
2576   if (!thread) {
2577     error.SetErrorString("no thread");
2578     return false;
2579   }
2580   if (!impl_function || !impl_function[0]) {
2581     error.SetErrorString("no function to execute");
2582     return false;
2583   }
2584 
2585   {
2586     ThreadSP thread_sp(thread->shared_from_this());
2587     Locker py_lock(this,
2588                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2589     ret_val = LLDBSWIGPythonRunScriptKeywordThread(
2590         impl_function, m_dictionary_name.c_str(), thread_sp, output);
2591     if (!ret_val)
2592       error.SetErrorString("python script evaluation failed");
2593   }
2594   return ret_val;
2595 }
2596 
2597 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2598     const char *impl_function, Target *target, std::string &output,
2599     Status &error) {
2600   bool ret_val;
2601   if (!target) {
2602     error.SetErrorString("no thread");
2603     return false;
2604   }
2605   if (!impl_function || !impl_function[0]) {
2606     error.SetErrorString("no function to execute");
2607     return false;
2608   }
2609 
2610   {
2611     TargetSP target_sp(target->shared_from_this());
2612     Locker py_lock(this,
2613                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2614     ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2615         impl_function, m_dictionary_name.c_str(), target_sp, output);
2616     if (!ret_val)
2617       error.SetErrorString("python script evaluation failed");
2618   }
2619   return ret_val;
2620 }
2621 
2622 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2623     const char *impl_function, StackFrame *frame, std::string &output,
2624     Status &error) {
2625   bool ret_val;
2626   if (!frame) {
2627     error.SetErrorString("no frame");
2628     return false;
2629   }
2630   if (!impl_function || !impl_function[0]) {
2631     error.SetErrorString("no function to execute");
2632     return false;
2633   }
2634 
2635   {
2636     StackFrameSP frame_sp(frame->shared_from_this());
2637     Locker py_lock(this,
2638                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2639     ret_val = LLDBSWIGPythonRunScriptKeywordFrame(
2640         impl_function, m_dictionary_name.c_str(), frame_sp, output);
2641     if (!ret_val)
2642       error.SetErrorString("python script evaluation failed");
2643   }
2644   return ret_val;
2645 }
2646 
2647 bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2648     const char *impl_function, ValueObject *value, std::string &output,
2649     Status &error) {
2650   bool ret_val;
2651   if (!value) {
2652     error.SetErrorString("no value");
2653     return false;
2654   }
2655   if (!impl_function || !impl_function[0]) {
2656     error.SetErrorString("no function to execute");
2657     return false;
2658   }
2659 
2660   {
2661     ValueObjectSP value_sp(value->GetSP());
2662     Locker py_lock(this,
2663                    Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2664     ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2665         impl_function, m_dictionary_name.c_str(), value_sp, output);
2666     if (!ret_val)
2667       error.SetErrorString("python script evaluation failed");
2668   }
2669   return ret_val;
2670 }
2671 
2672 uint64_t replace_all(std::string &str, const std::string &oldStr,
2673                      const std::string &newStr) {
2674   size_t pos = 0;
2675   uint64_t matches = 0;
2676   while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2677     matches++;
2678     str.replace(pos, oldStr.length(), newStr);
2679     pos += newStr.length();
2680   }
2681   return matches;
2682 }
2683 
2684 bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2685     const char *pathname, bool can_reload, bool init_session,
2686     lldb_private::Status &error, StructuredData::ObjectSP *module_sp) {
2687   if (!pathname || !pathname[0]) {
2688     error.SetErrorString("invalid pathname");
2689     return false;
2690   }
2691 
2692   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2693 
2694   {
2695     FileSpec target_file(pathname);
2696     FileSystem::Instance().Resolve(target_file);
2697     std::string basename(target_file.GetFilename().GetCString());
2698 
2699     StreamString command_stream;
2700 
2701     // Before executing Python code, lock the GIL.
2702     Locker py_lock(this,
2703                    Locker::AcquireLock |
2704                        (init_session ? Locker::InitSession : 0) |
2705                        Locker::NoSTDIN,
2706                    Locker::FreeAcquiredLock |
2707                        (init_session ? Locker::TearDownSession : 0));
2708     namespace fs = llvm::sys::fs;
2709     fs::file_status st;
2710     std::error_code ec = status(target_file.GetPath(), st);
2711 
2712     if (ec || st.type() == fs::file_type::status_error ||
2713         st.type() == fs::file_type::type_unknown ||
2714         st.type() == fs::file_type::file_not_found) {
2715       // if not a valid file of any sort, check if it might be a filename still
2716       // dot can't be used but / and \ can, and if either is found, reject
2717       if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2718         error.SetErrorString("invalid pathname");
2719         return false;
2720       }
2721       basename = pathname; // not a filename, probably a package of some sort,
2722                            // let it go through
2723     } else if (is_directory(st) || is_regular_file(st)) {
2724       if (target_file.GetDirectory().IsEmpty()) {
2725         error.SetErrorString("invalid directory name");
2726         return false;
2727       }
2728 
2729       std::string directory = target_file.GetDirectory().GetCString();
2730       replace_all(directory, "\\", "\\\\");
2731       replace_all(directory, "'", "\\'");
2732 
2733       // now make sure that Python has "directory" in the search path
2734       StreamString command_stream;
2735       command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2736                             "sys.path.insert(1,'%s');\n\n",
2737                             directory.c_str(), directory.c_str());
2738       bool syspath_retval =
2739           ExecuteMultipleLines(command_stream.GetData(),
2740                                ScriptInterpreter::ExecuteScriptOptions()
2741                                    .SetEnableIO(false)
2742                                    .SetSetLLDBGlobals(false))
2743               .Success();
2744       if (!syspath_retval) {
2745         error.SetErrorString("Python sys.path handling failed");
2746         return false;
2747       }
2748 
2749       // strip .py or .pyc extension
2750       ConstString extension = target_file.GetFileNameExtension();
2751       if (extension) {
2752         if (llvm::StringRef(extension.GetCString()) == ".py")
2753           basename.resize(basename.length() - 3);
2754         else if (llvm::StringRef(extension.GetCString()) == ".pyc")
2755           basename.resize(basename.length() - 4);
2756       }
2757     } else {
2758       error.SetErrorString("no known way to import this module specification");
2759       return false;
2760     }
2761 
2762     // check if the module is already import-ed
2763     command_stream.Clear();
2764     command_stream.Printf("sys.modules.__contains__('%s')", basename.c_str());
2765     bool does_contain = false;
2766     // this call will succeed if the module was ever imported in any Debugger
2767     // in the lifetime of the process in which this LLDB framework is living
2768     bool was_imported_globally =
2769         (ExecuteOneLineWithReturn(
2770              command_stream.GetData(),
2771              ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain,
2772              ScriptInterpreter::ExecuteScriptOptions()
2773                  .SetEnableIO(false)
2774                  .SetSetLLDBGlobals(false)) &&
2775          does_contain);
2776     // this call will fail if the module was not imported in this Debugger
2777     // before
2778     command_stream.Clear();
2779     command_stream.Printf("sys.getrefcount(%s)", basename.c_str());
2780     bool was_imported_locally = GetSessionDictionary()
2781                                     .GetItemForKey(PythonString(basename))
2782                                     .IsAllocated();
2783 
2784     bool was_imported = (was_imported_globally || was_imported_locally);
2785 
2786     if (was_imported && !can_reload) {
2787       error.SetErrorString("module already imported");
2788       return false;
2789     }
2790 
2791     // now actually do the import
2792     command_stream.Clear();
2793 
2794     if (was_imported) {
2795       if (!was_imported_locally)
2796         command_stream.Printf("import %s ; reload_module(%s)", basename.c_str(),
2797                               basename.c_str());
2798       else
2799         command_stream.Printf("reload_module(%s)", basename.c_str());
2800     } else
2801       command_stream.Printf("import %s", basename.c_str());
2802 
2803     error = ExecuteMultipleLines(command_stream.GetData(),
2804                                  ScriptInterpreter::ExecuteScriptOptions()
2805                                      .SetEnableIO(false)
2806                                      .SetSetLLDBGlobals(false));
2807     if (error.Fail())
2808       return false;
2809 
2810     // if we are here, everything worked
2811     // call __lldb_init_module(debugger,dict)
2812     if (!LLDBSwigPythonCallModuleInit(basename.c_str(),
2813                                       m_dictionary_name.c_str(), debugger_sp)) {
2814       error.SetErrorString("calling __lldb_init_module failed");
2815       return false;
2816     }
2817 
2818     if (module_sp) {
2819       // everything went just great, now set the module object
2820       command_stream.Clear();
2821       command_stream.Printf("%s", basename.c_str());
2822       void *module_pyobj = nullptr;
2823       if (ExecuteOneLineWithReturn(
2824               command_stream.GetData(),
2825               ScriptInterpreter::eScriptReturnTypeOpaqueObject,
2826               &module_pyobj) &&
2827           module_pyobj)
2828         *module_sp = std::make_shared<StructuredPythonObject>(module_pyobj);
2829     }
2830 
2831     return true;
2832   }
2833 }
2834 
2835 bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2836   if (!word || !word[0])
2837     return false;
2838 
2839   llvm::StringRef word_sr(word);
2840 
2841   // filter out a few characters that would just confuse us and that are
2842   // clearly not keyword material anyway
2843   if (word_sr.find('"') != llvm::StringRef::npos ||
2844       word_sr.find('\'') != llvm::StringRef::npos)
2845     return false;
2846 
2847   StreamString command_stream;
2848   command_stream.Printf("keyword.iskeyword('%s')", word);
2849   bool result;
2850   ExecuteScriptOptions options;
2851   options.SetEnableIO(false);
2852   options.SetMaskoutErrors(true);
2853   options.SetSetLLDBGlobals(false);
2854   if (ExecuteOneLineWithReturn(command_stream.GetData(),
2855                                ScriptInterpreter::eScriptReturnTypeBool,
2856                                &result, options))
2857     return result;
2858   return false;
2859 }
2860 
2861 ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2862     lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2863     : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2864       m_old_asynch(debugger_sp->GetAsyncExecution()) {
2865   if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2866     m_debugger_sp->SetAsyncExecution(false);
2867   else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2868     m_debugger_sp->SetAsyncExecution(true);
2869 }
2870 
2871 ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2872   if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2873     m_debugger_sp->SetAsyncExecution(m_old_asynch);
2874 }
2875 
2876 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2877     const char *impl_function, llvm::StringRef args,
2878     ScriptedCommandSynchronicity synchronicity,
2879     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2880     const lldb_private::ExecutionContext &exe_ctx) {
2881   if (!impl_function) {
2882     error.SetErrorString("no function to execute");
2883     return false;
2884   }
2885 
2886   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2887   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2888 
2889   if (!debugger_sp.get()) {
2890     error.SetErrorString("invalid Debugger pointer");
2891     return false;
2892   }
2893 
2894   bool ret_val = false;
2895 
2896   std::string err_msg;
2897 
2898   {
2899     Locker py_lock(this,
2900                    Locker::AcquireLock | Locker::InitSession |
2901                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2902                    Locker::FreeLock | Locker::TearDownSession);
2903 
2904     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2905 
2906     std::string args_str = args.str();
2907     ret_val = LLDBSwigPythonCallCommand(
2908         impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2909         cmd_retobj, exe_ctx_ref_sp);
2910   }
2911 
2912   if (!ret_val)
2913     error.SetErrorString("unable to execute script function");
2914   else
2915     error.Clear();
2916 
2917   return ret_val;
2918 }
2919 
2920 bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2921     StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2922     ScriptedCommandSynchronicity synchronicity,
2923     lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2924     const lldb_private::ExecutionContext &exe_ctx) {
2925   if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2926     error.SetErrorString("no function to execute");
2927     return false;
2928   }
2929 
2930   lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2931   lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2932 
2933   if (!debugger_sp.get()) {
2934     error.SetErrorString("invalid Debugger pointer");
2935     return false;
2936   }
2937 
2938   bool ret_val = false;
2939 
2940   std::string err_msg;
2941 
2942   {
2943     Locker py_lock(this,
2944                    Locker::AcquireLock | Locker::InitSession |
2945                        (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2946                    Locker::FreeLock | Locker::TearDownSession);
2947 
2948     SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2949 
2950     std::string args_str = args.str();
2951     ret_val = LLDBSwigPythonCallCommandObject(impl_obj_sp->GetValue(),
2952                                               debugger_sp, args_str.c_str(),
2953                                               cmd_retobj, exe_ctx_ref_sp);
2954   }
2955 
2956   if (!ret_val)
2957     error.SetErrorString("unable to execute script function");
2958   else
2959     error.Clear();
2960 
2961   return ret_val;
2962 }
2963 
2964 // in Python, a special attribute __doc__ contains the docstring for an object
2965 // (function, method, class, ...) if any is defined Otherwise, the attribute's
2966 // value is None
2967 bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2968                                                           std::string &dest) {
2969   dest.clear();
2970   if (!item || !*item)
2971     return false;
2972   std::string command(item);
2973   command += ".__doc__";
2974 
2975   char *result_ptr = nullptr; // Python is going to point this to valid data if
2976                               // ExecuteOneLineWithReturn returns successfully
2977 
2978   if (ExecuteOneLineWithReturn(
2979           command.c_str(), ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2980           &result_ptr,
2981           ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false))) {
2982     if (result_ptr)
2983       dest.assign(result_ptr);
2984     return true;
2985   } else {
2986     StreamString str_stream;
2987     str_stream.Printf(
2988         "Function %s was not found. Containing module might be missing.", item);
2989     dest = str_stream.GetString();
2990     return false;
2991   }
2992 }
2993 
2994 bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2995     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2996   bool got_string = false;
2997   dest.clear();
2998 
2999   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3000 
3001   static char callee_name[] = "get_short_help";
3002 
3003   if (!cmd_obj_sp)
3004     return false;
3005 
3006   PythonObject implementor(PyRefType::Borrowed,
3007                            (PyObject *)cmd_obj_sp->GetValue());
3008 
3009   if (!implementor.IsAllocated())
3010     return false;
3011 
3012   PythonObject pmeth(PyRefType::Owned,
3013                      PyObject_GetAttrString(implementor.get(), callee_name));
3014 
3015   if (PyErr_Occurred())
3016     PyErr_Clear();
3017 
3018   if (!pmeth.IsAllocated())
3019     return false;
3020 
3021   if (PyCallable_Check(pmeth.get()) == 0) {
3022     if (PyErr_Occurred())
3023       PyErr_Clear();
3024     return false;
3025   }
3026 
3027   if (PyErr_Occurred())
3028     PyErr_Clear();
3029 
3030   // right now we know this function exists and is callable..
3031   PythonObject py_return(
3032       PyRefType::Owned,
3033       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3034 
3035   // if it fails, print the error but otherwise go on
3036   if (PyErr_Occurred()) {
3037     PyErr_Print();
3038     PyErr_Clear();
3039   }
3040 
3041   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3042     PythonString py_string(PyRefType::Borrowed, py_return.get());
3043     llvm::StringRef return_data(py_string.GetString());
3044     dest.assign(return_data.data(), return_data.size());
3045     got_string = true;
3046   }
3047   return got_string;
3048 }
3049 
3050 uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3051     StructuredData::GenericSP cmd_obj_sp) {
3052   uint32_t result = 0;
3053 
3054   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3055 
3056   static char callee_name[] = "get_flags";
3057 
3058   if (!cmd_obj_sp)
3059     return result;
3060 
3061   PythonObject implementor(PyRefType::Borrowed,
3062                            (PyObject *)cmd_obj_sp->GetValue());
3063 
3064   if (!implementor.IsAllocated())
3065     return result;
3066 
3067   PythonObject pmeth(PyRefType::Owned,
3068                      PyObject_GetAttrString(implementor.get(), callee_name));
3069 
3070   if (PyErr_Occurred())
3071     PyErr_Clear();
3072 
3073   if (!pmeth.IsAllocated())
3074     return result;
3075 
3076   if (PyCallable_Check(pmeth.get()) == 0) {
3077     if (PyErr_Occurred())
3078       PyErr_Clear();
3079     return result;
3080   }
3081 
3082   if (PyErr_Occurred())
3083     PyErr_Clear();
3084 
3085   // right now we know this function exists and is callable..
3086   PythonObject py_return(
3087       PyRefType::Owned,
3088       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3089 
3090   // if it fails, print the error but otherwise go on
3091   if (PyErr_Occurred()) {
3092     PyErr_Print();
3093     PyErr_Clear();
3094   }
3095 
3096   if (py_return.IsAllocated() && PythonInteger::Check(py_return.get())) {
3097     PythonInteger int_value(PyRefType::Borrowed, py_return.get());
3098     result = int_value.GetInteger();
3099   }
3100 
3101   return result;
3102 }
3103 
3104 bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3105     StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3106   bool got_string = false;
3107   dest.clear();
3108 
3109   Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3110 
3111   static char callee_name[] = "get_long_help";
3112 
3113   if (!cmd_obj_sp)
3114     return false;
3115 
3116   PythonObject implementor(PyRefType::Borrowed,
3117                            (PyObject *)cmd_obj_sp->GetValue());
3118 
3119   if (!implementor.IsAllocated())
3120     return false;
3121 
3122   PythonObject pmeth(PyRefType::Owned,
3123                      PyObject_GetAttrString(implementor.get(), callee_name));
3124 
3125   if (PyErr_Occurred())
3126     PyErr_Clear();
3127 
3128   if (!pmeth.IsAllocated())
3129     return false;
3130 
3131   if (PyCallable_Check(pmeth.get()) == 0) {
3132     if (PyErr_Occurred())
3133       PyErr_Clear();
3134 
3135     return false;
3136   }
3137 
3138   if (PyErr_Occurred())
3139     PyErr_Clear();
3140 
3141   // right now we know this function exists and is callable..
3142   PythonObject py_return(
3143       PyRefType::Owned,
3144       PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3145 
3146   // if it fails, print the error but otherwise go on
3147   if (PyErr_Occurred()) {
3148     PyErr_Print();
3149     PyErr_Clear();
3150   }
3151 
3152   if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3153     PythonString str(PyRefType::Borrowed, py_return.get());
3154     llvm::StringRef str_data(str.GetString());
3155     dest.assign(str_data.data(), str_data.size());
3156     got_string = true;
3157   }
3158 
3159   return got_string;
3160 }
3161 
3162 std::unique_ptr<ScriptInterpreterLocker>
3163 ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3164   std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3165       this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3166       Locker::FreeLock | Locker::TearDownSession));
3167   return py_lock;
3168 }
3169 
3170 void ScriptInterpreterPythonImpl::InitializePrivate() {
3171   if (g_initialized)
3172     return;
3173 
3174   g_initialized = true;
3175 
3176   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
3177   Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
3178 
3179   // RAII-based initialization which correctly handles multiple-initialization,
3180   // version- specific differences among Python 2 and Python 3, and saving and
3181   // restoring various other pieces of state that can get mucked with during
3182   // initialization.
3183   InitializePythonRAII initialize_guard;
3184 
3185   LLDBSwigPyInit();
3186 
3187   // Update the path python uses to search for modules to include the current
3188   // directory.
3189 
3190   PyRun_SimpleString("import sys");
3191   AddToSysPath(AddLocation::End, ".");
3192 
3193   // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3194   // that use a backslash as the path separator, this will result in executing
3195   // python code containing paths with unescaped backslashes.  But Python also
3196   // accepts forward slashes, so to make life easier we just use that.
3197   if (FileSpec file_spec = GetPythonDir())
3198     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3199   if (FileSpec file_spec = HostInfo::GetShlibDir())
3200     AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3201 
3202   PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3203                      "lldb.embedded_interpreter; from "
3204                      "lldb.embedded_interpreter import run_python_interpreter; "
3205                      "from lldb.embedded_interpreter import run_one_line");
3206 }
3207 
3208 void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3209                                                std::string path) {
3210   std::string path_copy;
3211 
3212   std::string statement;
3213   if (location == AddLocation::Beginning) {
3214     statement.assign("sys.path.insert(0,\"");
3215     statement.append(path);
3216     statement.append("\")");
3217   } else {
3218     statement.assign("sys.path.append(\"");
3219     statement.append(path);
3220     statement.append("\")");
3221   }
3222   PyRun_SimpleString(statement.c_str());
3223 }
3224 
3225 // We are intentionally NOT calling Py_Finalize here (this would be the logical
3226 // place to call it).  Calling Py_Finalize here causes test suite runs to seg
3227 // fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3228 // be called 'at_exit'.  When the test suite Python harness finishes up, it
3229 // calls Py_Finalize, which calls all the 'at_exit' registered functions.
3230 // SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3231 // which calls ScriptInterpreter::Terminate, which calls
3232 // ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3233 // end up with Py_Finalize being called from within Py_Finalize, which results
3234 // in a seg fault. Since this function only gets called when lldb is shutting
3235 // down and going away anyway, the fact that we don't actually call Py_Finalize
3236 // should not cause any problems (everything should shut down/go away anyway
3237 // when the process exits).
3238 //
3239 // void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3240 
3241 #endif // LLDB_DISABLE_PYTHON
3242