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