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