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