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