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