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