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