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