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