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