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