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