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