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