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