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