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