LLDB mainline
ScriptInterpreterPython.cpp
Go to the documentation of this file.
1//===-- ScriptInterpreterPython.cpp ---------------------------------------===//
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// LLDB Python header must be included first
10#include "lldb-python.h"
11
13#include "PythonDataObjects.h"
14#include "PythonReadline.h"
15#include "SWIGPythonBridge.h"
17
18#include "lldb/API/SBError.h"
20#include "lldb/API/SBFrame.h"
21#include "lldb/API/SBValue.h"
24#include "lldb/Core/Debugger.h"
28#include "lldb/Host/Config.h"
30#include "lldb/Host/HostInfo.h"
31#include "lldb/Host/Pipe.h"
35#include "lldb/Target/Thread.h"
39#include "lldb/Utility/Timer.h"
42#include "lldb/lldb-forward.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringRef.h"
45#include "llvm/Support/Error.h"
46#include "llvm/Support/FileSystem.h"
47#include "llvm/Support/FormatAdapters.h"
48
49#include <cstdio>
50#include <cstdlib>
51#include <memory>
52#include <optional>
53#include <stdlib.h>
54#include <string>
55
56using namespace lldb;
57using namespace lldb_private;
58using namespace lldb_private::python;
59using llvm::Expected;
60
62
63// Defined in the SWIG source file
64extern "C" PyObject *PyInit__lldb(void);
65
66#define LLDBSwigPyInit PyInit__lldb
67
68#if defined(_WIN32)
69// Don't mess with the signal handlers on Windows.
70#define LLDB_USE_PYTHON_SET_INTERRUPT 0
71#else
72#define LLDB_USE_PYTHON_SET_INTERRUPT 1
73#endif
74
76 ScriptInterpreter *script_interpreter =
78 return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
79}
80
81namespace {
82
83// Initializing Python is not a straightforward process. We cannot control
84// what external code may have done before getting to this point in LLDB,
85// including potentially having already initialized Python, so we need to do a
86// lot of work to ensure that the existing state of the system is maintained
87// across our initialization. We do this by using an RAII pattern where we
88// save off initial state at the beginning, and restore it at the end
89struct InitializePythonRAII {
90public:
91 InitializePythonRAII() {
92 // The table of built-in modules can only be extended before Python is
93 // initialized.
94 if (!Py_IsInitialized()) {
95#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
96 // Python's readline is incompatible with libedit being linked into lldb.
97 // Provide a patched version local to the embedded interpreter.
98 PyImport_AppendInittab("readline", initlldb_readline);
99#endif
100
101 // Register _lldb as a built-in module.
102 PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
103 }
104
105#if LLDB_EMBED_PYTHON_HOME
106 PyConfig config;
107 PyConfig_InitPythonConfig(&config);
108
109 static std::string g_python_home = []() -> std::string {
110 if (llvm::sys::path::is_absolute(LLDB_PYTHON_HOME))
111 return LLDB_PYTHON_HOME;
112
113 FileSpec spec = HostInfo::GetShlibDir();
114 if (!spec)
115 return {};
116 spec.AppendPathComponent(LLDB_PYTHON_HOME);
117 return spec.GetPath();
118 }();
119 if (!g_python_home.empty()) {
120 PyConfig_SetBytesString(&config, &config.home, g_python_home.c_str());
121 }
122
123 config.install_signal_handlers = 0;
124 Py_InitializeFromConfig(&config);
125 PyConfig_Clear(&config);
126#else
127 Py_InitializeEx(/*install_sigs=*/0);
128#endif
129
130 // The only case we should go further and acquire the GIL: it is unlocked.
131 PyGILState_STATE gil_state = PyGILState_Ensure();
132 if (gil_state != PyGILState_UNLOCKED)
133 return;
134
135 m_was_already_initialized = true;
136 m_gil_state = gil_state;
137 LLDB_LOGV(GetLog(LLDBLog::Script),
138 "Ensured PyGILState. Previous state = {0}",
139 m_gil_state == PyGILState_UNLOCKED ? "unlocked" : "locked");
140 }
141
142 ~InitializePythonRAII() {
143 if (m_was_already_initialized) {
144 LLDB_LOGV(GetLog(LLDBLog::Script),
145 "Releasing PyGILState. Returning to state = {0}",
146 m_gil_state == PyGILState_UNLOCKED ? "unlocked" : "locked");
147 PyGILState_Release(m_gil_state);
148 } else {
149 // We initialized the threads in this function, just unlock the GIL.
150 PyEval_SaveThread();
151 }
152 }
153
154private:
155 PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
156 bool m_was_already_initialized = false;
157};
158
159#if LLDB_USE_PYTHON_SET_INTERRUPT
160/// Saves the current signal handler for the specified signal and restores
161/// it at the end of the current scope.
162struct RestoreSignalHandlerScope {
163 /// The signal handler.
164 struct sigaction m_prev_handler;
165 int m_signal_code;
166 RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
167 // Initialize sigaction to their default state.
168 std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
169 // Don't install a new handler, just read back the old one.
170 struct sigaction *new_handler = nullptr;
171 int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
172 lldbassert(signal_err == 0 && "sigaction failed to read handler");
173 }
174 ~RestoreSignalHandlerScope() {
175 int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
176 lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
177 }
178};
179#endif
180} // namespace
181
184 auto style = llvm::sys::path::Style::posix;
185
186 llvm::StringRef path_ref(path.begin(), path.size());
187 auto rbegin = llvm::sys::path::rbegin(path_ref, style);
188 auto rend = llvm::sys::path::rend(path_ref);
189 auto framework = std::find(rbegin, rend, "LLDB.framework");
190 if (framework == rend) {
191 ComputePythonDir(path);
192 return;
193 }
194 path.resize(framework - rend);
195 llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
196}
197
200 // Build the path by backing out of the lib dir, then building with whatever
201 // the real python interpreter uses. (e.g. lib for most, lib64 on RHEL
202 // x86_64, or bin on Windows).
203 llvm::sys::path::remove_filename(path);
204 llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
205
206#if defined(_WIN32)
207 // This will be injected directly through FileSpec.SetDirectory(),
208 // so we need to normalize manually.
209 std::replace(path.begin(), path.end(), '\\', '/');
210#endif
211}
212
214 static FileSpec g_spec = []() {
215 FileSpec spec = HostInfo::GetShlibDir();
216 if (!spec)
217 return FileSpec();
218 llvm::SmallString<64> path;
219 spec.GetPath(path);
220
221#if defined(__APPLE__)
223#else
224 ComputePythonDir(path);
225#endif
226 spec.SetDirectory(path);
227 return spec;
228 }();
229 return g_spec;
230}
231
232static const char GetInterpreterInfoScript[] = R"(
233import os
234import sys
235
236def main(lldb_python_dir, python_exe_relative_path):
237 info = {
238 "lldb-pythonpath": lldb_python_dir,
239 "language": "python",
240 "prefix": sys.prefix,
241 "executable": os.path.join(sys.prefix, python_exe_relative_path)
242 }
243 return info
244)";
245
246static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
247
249 GIL gil;
250 FileSpec python_dir_spec = GetPythonDir();
251 if (!python_dir_spec)
252 return nullptr;
254 auto info_json = unwrapIgnoringErrors(
255 As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
257 if (!info_json)
258 return nullptr;
259 return info_json.CreateStructuredDictionary();
260}
261
263 FileSpec &this_file) {
264 // When we're loaded from python, this_file will point to the file inside the
265 // python package directory. Replace it with the one in the lib directory.
266#ifdef _WIN32
267 // On windows, we need to manually back out of the python tree, and go into
268 // the bin directory. This is pretty much the inverse of what ComputePythonDir
269 // does.
270 if (this_file.GetFileNameExtension() == ".pyd") {
271 this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
272 this_file.RemoveLastPathComponent(); // native
273 this_file.RemoveLastPathComponent(); // lldb
274 llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
275 for (auto it = llvm::sys::path::begin(libdir),
276 end = llvm::sys::path::end(libdir);
277 it != end; ++it)
278 this_file.RemoveLastPathComponent();
279 this_file.AppendPathComponent("bin");
280 this_file.AppendPathComponent("liblldb.dll");
281 }
282#else
283 // The python file is a symlink, so we can find the real library by resolving
284 // it. We can do this unconditionally.
285 FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
286#endif
287}
288
290 return "Embedded Python interpreter";
291}
292
294#if LLDB_ENABLE_MTE
295 // Python's allocator (pymalloc) is not aware of Memory Tagging Extension
296 // (MTE) and crashes.
297 // https://bugs.python.org/issue43593
298 setenv("PYTHONMALLOC", "malloc", /*overwrite=*/true);
299#endif
300
301 HostInfo::SetSharedLibraryDirectoryHelper(
309}
310
315
317 ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
318 uint16_t on_leave, FileSP in, FileSP out, FileSP err)
321 m_python_interpreter(py_interpreter) {
323 if ((on_entry & InitSession) == InitSession) {
324 if (!DoInitSession(on_entry, in, out, err)) {
325 // Don't teardown the session if we didn't init it.
326 m_teardown_session = false;
327 }
328 }
329}
330
332 m_GILState = PyGILState_Ensure();
333 LLDB_LOGV(GetLog(LLDBLog::Script), "Ensured PyGILState. Previous state = {0}",
334 m_GILState == PyGILState_UNLOCKED ? "unlocked" : "locked");
335
336 // we need to save the thread state when we first start the command because
337 // we might decide to interrupt it while some action is taking place outside
338 // of Python (e.g. printing to screen, waiting for the network, ...) in that
339 // case, _PyThreadState_Current will be NULL - and we would be unable to set
340 // the asynchronous exception - not a desirable situation
341 m_python_interpreter->SetThreadState(PyThreadState_Get());
342 m_python_interpreter->IncrementLockCount();
343 return true;
344}
345
347 FileSP in, FileSP out,
348 FileSP err) {
350 return false;
351 return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
352}
353
356 "Releasing PyGILState. Returning to state = {0}",
357 m_GILState == PyGILState_UNLOCKED ? "unlocked" : "locked");
358 PyGILState_Release(m_GILState);
359 m_python_interpreter->DecrementLockCount();
360 return true;
361}
362
365 return false;
366 m_python_interpreter->LeaveSession();
367 return true;
368}
369
375
382 m_dictionary_name(m_debugger.GetInstanceName()),
385 m_command_thread_state(nullptr) {
386
387 m_dictionary_name.append("_dict");
388 StreamString run_string;
389 run_string.Printf("%s = dict()", m_dictionary_name.c_str());
390
392 RunSimpleString(run_string.GetData());
393
394 run_string.Clear();
395 run_string.Printf(
396 "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
397 m_dictionary_name.c_str());
398 RunSimpleString(run_string.GetData());
399
400 // Reloading modules requires a different syntax in Python 2 and Python 3.
401 // This provides a consistent syntax no matter what version of Python.
402 run_string.Clear();
403 run_string.Printf(
404 "run_one_line (%s, 'from importlib import reload as reload_module')",
405 m_dictionary_name.c_str());
406 RunSimpleString(run_string.GetData());
407
408 // WARNING: temporary code that loads Cocoa formatters - this should be done
409 // on a per-platform basis rather than loading the whole set and letting the
410 // individual formatter classes exploit APIs to check whether they can/cannot
411 // do their task
412 run_string.Clear();
413 run_string.Printf(
414 "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
415 m_dictionary_name.c_str());
416 RunSimpleString(run_string.GetData());
417 run_string.Clear();
418
419 run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
420 "lldb.embedded_interpreter import run_python_interpreter; "
421 "from lldb.embedded_interpreter import run_one_line')",
422 m_dictionary_name.c_str());
423 RunSimpleString(run_string.GetData());
424 run_string.Clear();
425
426 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
427 "')",
428 m_dictionary_name.c_str(), m_debugger.GetID());
429 RunSimpleString(run_string.GetData());
430}
431
433 // the session dictionary may hold objects with complex state which means
434 // that they may need to be torn down with some level of smarts and that, in
435 // turn, requires a valid thread state force Python to procure itself such a
436 // thread state, nuke the session dictionary and then release it for others
437 // to use and proceed with the rest of the shutdown
438 auto gil_state = PyGILState_Ensure();
439 m_session_dict.Reset();
440 PyGILState_Release(gil_state);
441}
442
444 bool interactive) {
445 const char *instructions = nullptr;
446
447 switch (m_active_io_handler) {
448 case eIOHandlerNone:
449 break;
451 instructions = R"(Enter your Python command(s). Type 'DONE' to end.
452def function (frame, bp_loc, internal_dict):
453 """frame: the lldb.SBFrame for the location at which you stopped
454 bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
455 internal_dict: an LLDB support object not to be used"""
456)";
457 break;
459 instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
460 break;
461 }
462
463 if (instructions && interactive) {
464 if (LockableStreamFileSP stream_sp = io_handler.GetOutputStreamFileSP()) {
465 LockedStreamFile locked_stream = stream_sp->Lock();
466 locked_stream.PutCString(instructions);
467 locked_stream.Flush();
468 }
469 }
470}
471
473 std::string &data) {
474 io_handler.SetIsDone(true);
475 bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
476
477 switch (m_active_io_handler) {
478 case eIOHandlerNone:
479 break;
481 std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
482 (std::vector<std::reference_wrapper<BreakpointOptions>> *)
483 io_handler.GetUserData();
484 for (BreakpointOptions &bp_options : *bp_options_vec) {
485
486 auto data_up = std::make_unique<CommandDataPython>();
487 if (!data_up)
488 break;
489 data_up->user_source.SplitIntoLines(data);
490
491 if (GenerateBreakpointCommandCallbackData(data_up->user_source,
492 data_up->script_source,
493 /*has_extra_args=*/false,
494 /*is_callback=*/false)
495 .Success()) {
496 auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
497 std::move(data_up));
498 bp_options.SetCallback(
500 } else if (!batch_mode) {
501 if (LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP()) {
502 LockedStreamFile locked_stream = error_sp->Lock();
503 locked_stream.Printf("Warning: No command attached to breakpoint.\n");
504 }
505 }
506 }
508 } break;
510 WatchpointOptions *wp_options =
511 (WatchpointOptions *)io_handler.GetUserData();
512 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
513 data_up->user_source.SplitIntoLines(data);
514
515 if (GenerateWatchpointCommandCallbackData(data_up->user_source,
516 data_up->script_source,
517 /*is_callback=*/false)) {
518 auto baton_sp =
519 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
520 wp_options->SetCallback(
522 } else if (!batch_mode) {
523 if (LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP()) {
524 LockedStreamFile locked_stream = error_sp->Lock();
525 locked_stream.Printf("Warning: No command attached to breakpoint.\n");
526 }
527 }
529 } break;
530 }
531}
532
535 return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
536}
537
539 Log *log = GetLog(LLDBLog::Script);
540 if (log)
541 log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
542
543 // Unset the LLDB global variables.
544 RunSimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
545 "= None; lldb.thread = None; lldb.frame = None");
546
547 // checking that we have a valid thread state - since we use our own
548 // threading and locking in some (rare) cases during cleanup Python may end
549 // up believing we have no thread state and PyImport_AddModule will crash if
550 // that is the case - since that seems to only happen when destroying the
551 // SBDebugger, we can make do without clearing up stdout and stderr
552 if (PyThreadState_GetDict()) {
553 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
554 if (sys_module_dict.IsValid()) {
555 if (m_saved_stdin.IsValid()) {
556 sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
558 }
559 if (m_saved_stdout.IsValid()) {
560 sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
562 }
563 if (m_saved_stderr.IsValid()) {
564 sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
565 m_saved_stderr.Reset();
566 }
567 }
569
570 m_session_is_active = false;
571}
572
574 const char *py_name,
575 PythonObject &save_file,
576 const char *mode) {
577 if (!file_sp || !*file_sp) {
578 save_file.Reset();
579 return false;
580 }
581 File &file = *file_sp;
582
583 // Flush the file before giving it to python to avoid interleaved output.
584 file.Flush();
585
586 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
587
588 auto new_file = PythonFile::FromFile(file, mode);
589 if (!new_file) {
590 llvm::consumeError(new_file.takeError());
591 return false;
592 }
593
594 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
596 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
597 return true;
598}
599
600bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
601 FileSP in_sp, FileSP out_sp,
602 FileSP err_sp) {
603 // If we have already entered the session, without having officially 'left'
604 // it, then there is no need to 'enter' it again.
605 Log *log = GetLog(LLDBLog::Script);
607 LLDB_LOGF(
608 log,
609 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
610 ") session is already active, returning without doing anything",
611 on_entry_flags);
612 return false;
613 }
614
615 LLDB_LOGF(
616 log,
617 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
618 on_entry_flags);
619
620 m_session_is_active = true;
621
622 StreamString run_string;
623
624 if (on_entry_flags & Locker::InitGlobals) {
625 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
627 run_string.Printf(
628 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
629 m_debugger.GetID());
630 run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
631 run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
632 run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
633 run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
634 run_string.PutCString("')");
635 } else {
636 // If we aren't initing the globals, we should still always set the
637 // debugger (since that is always unique.)
638 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
639 m_dictionary_name.c_str(), m_debugger.GetID());
640 run_string.Printf(
641 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
642 m_debugger.GetID());
643 run_string.PutCString("')");
644 }
645
646 RunSimpleString(run_string.GetData());
647 run_string.Clear();
648
649 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
650 if (sys_module_dict.IsValid()) {
651 lldb::FileSP top_in_sp;
652 lldb::LockableStreamFileSP top_out_sp, top_err_sp;
653 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
654 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
655 top_err_sp);
656
657 if (on_entry_flags & Locker::NoSTDIN) {
658 m_saved_stdin.Reset();
659 } else {
660 if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
661 if (top_in_sp)
662 SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
663 }
664 }
665
666 if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
667 if (top_out_sp)
668 SetStdHandle(top_out_sp->GetUnlockedFileSP(), "stdout", m_saved_stdout,
669 "w");
670 }
671
672 if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
673 if (top_err_sp)
674 SetStdHandle(top_err_sp->GetUnlockedFileSP(), "stderr", m_saved_stderr,
675 "w");
676 }
677 }
678
679 if (PyErr_Occurred())
680 PyErr_Clear();
681
682 return true;
683}
684
686 if (!m_main_module.IsValid())
688 return m_main_module;
689}
690
693 return m_session_dict;
694
695 PythonObject &main_module = GetMainModule();
696 if (!main_module.IsValid())
697 return m_session_dict;
698
700 PyModule_GetDict(main_module.get()));
701 if (!main_dict.IsValid())
702 return m_session_dict;
703
711 return m_sys_module_dict;
714 return m_sys_module_dict;
715}
716
717llvm::Expected<unsigned>
719 const llvm::StringRef &callable_name) {
720 if (callable_name.empty()) {
721 return llvm::createStringError(llvm::inconvertibleErrorCode(),
722 "called with empty callable name.");
723 }
724 Locker py_lock(this,
729 callable_name, dict);
730 if (!pfunc.IsAllocated()) {
731 return llvm::createStringError(llvm::inconvertibleErrorCode(),
732 "can't find callable: %s",
733 callable_name.str().c_str());
734 }
735 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
736 if (!arg_info)
737 return arg_info.takeError();
738 return arg_info.get().max_positional_args;
739}
740
741static std::string GenerateUniqueName(const char *base_name_wanted,
742 uint32_t &functions_counter,
743 const void *name_token = nullptr) {
744 StreamString sstr;
745
746 if (!base_name_wanted)
747 return std::string();
748
749 if (!name_token)
750 sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
751 else
752 sstr.Printf("%s_%p", base_name_wanted, name_token);
753
754 return std::string(sstr.GetString());
755}
756
759 return true;
760
762 PyImport_AddModule("lldb.embedded_interpreter"));
763 if (!module.IsValid())
764 return false;
765
767 PyModule_GetDict(module.get()));
768 if (!module_dict.IsValid())
769 return false;
770
772 module_dict.GetItemForKey(PythonString("run_one_line"));
774 module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
775 return m_run_one_line_function.IsValid();
776}
777
779 llvm::StringRef command, CommandReturnObject *result,
780 const ExecuteScriptOptions &options) {
781 std::string command_str = command.str();
782
783 if (!m_valid_session)
784 return false;
785
786 if (!command.empty()) {
787 // We want to call run_one_line, passing in the dictionary and the command
788 // string. We cannot do this through RunSimpleString here because the
789 // command string may contain escaped characters, and putting it inside
790 // another string to pass to RunSimpleString messes up the escaping. So
791 // we use the following more complicated method to pass the command string
792 // directly down to Python.
793 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
794 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
795 options.GetEnableIO(), m_debugger, result);
796 if (!io_redirect_or_error) {
797 if (result)
799 "failed to redirect I/O: {0}\n",
800 llvm::fmt_consume(io_redirect_or_error.takeError()));
801 else
802 llvm::consumeError(io_redirect_or_error.takeError());
803 return false;
804 }
805
806 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
807
808 bool success = false;
809 {
810 // WARNING! It's imperative that this RAII scope be as tight as
811 // possible. In particular, the scope must end *before* we try to join
812 // the read thread. The reason for this is that a pre-requisite for
813 // joining the read thread is that we close the write handle (to break
814 // the pipe and cause it to wake up and exit). But acquiring the GIL as
815 // below will redirect Python's stdio to use this same handle. If we
816 // close the handle while Python is still using it, bad things will
817 // happen.
818 Locker locker(
819 this,
821 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
822 ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
824 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
825 io_redirect.GetErrorFile());
826
827 // Find the correct script interpreter dictionary in the main module.
828 PythonDictionary &session_dict = GetSessionDictionary();
829 if (session_dict.IsValid()) {
831 if (PyCallable_Check(m_run_one_line_function.get())) {
832 PythonObject pargs(
834 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
835 if (pargs.IsValid()) {
836 PythonObject return_value(
838 PyObject_CallObject(m_run_one_line_function.get(),
839 pargs.get()));
840 if (return_value.IsValid())
841 success = true;
842 else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
843 PyErr_Print();
844 PyErr_Clear();
845 }
846 }
847 }
848 }
849 }
850
851 io_redirect.Flush();
852 }
853
854 if (success)
855 return true;
856
857 // The one-liner failed. Append the error message.
858 if (result) {
859 result->AppendErrorWithFormat(
860 "python failed attempting to evaluate '%s'\n", command_str.c_str());
861 }
862 return false;
863 }
864
865 if (result)
866 result->AppendError("empty command passed to python\n");
867 return false;
868}
869
872
873 Debugger &debugger = m_debugger;
874
875 // At the moment, the only time the debugger does not have an input file
876 // handle is when this is called directly from Python, in which case it is
877 // both dangerous and unnecessary (not to mention confusing) to try to embed
878 // a running interpreter loop inside the already running Python interpreter
879 // loop, so we won't do it.
880
881 if (!debugger.GetInputFile().IsValid())
882 return;
883
884 IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
885 if (io_handler_sp) {
886 debugger.RunIOHandlerAsync(io_handler_sp);
887 }
888}
889
891#if LLDB_USE_PYTHON_SET_INTERRUPT
892 // If the interpreter isn't evaluating any Python at the moment then return
893 // false to signal that this function didn't handle the interrupt and the
894 // next component should try handling it.
895 if (!IsExecutingPython())
896 return false;
897
898 // Tell Python that it should pretend to have received a SIGINT.
899 PyErr_SetInterrupt();
900 // PyErr_SetInterrupt has no way to return an error so we can only pretend the
901 // signal got successfully handled and return true.
902 // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
903 // the error handling is limited to checking the arguments which would be
904 // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
905 return true;
906#else
907 Log *log = GetLog(LLDBLog::Script);
908
909 if (IsExecutingPython()) {
910 PyThreadState *state = PyThreadState_Get();
911 if (!state)
912 state = GetThreadState();
913 if (state) {
914 long tid = PyThread_get_thread_ident();
915 PyThreadState_Swap(state);
916 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
917 LLDB_LOGF(log,
918 "ScriptInterpreterPythonImpl::Interrupt() sending "
919 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
920 tid, num_threads);
921 return true;
922 }
923 }
924 LLDB_LOGF(log,
925 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
926 "can't interrupt");
927 return false;
928#endif
929}
930
932 llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
933 void *ret_value, const ExecuteScriptOptions &options) {
934
935 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
936 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
937 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
938
939 if (!io_redirect_or_error) {
940 llvm::consumeError(io_redirect_or_error.takeError());
941 return false;
942 }
943
944 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
945
946 Locker locker(this,
948 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
951 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
952 io_redirect.GetErrorFile());
953
954 PythonModule &main_module = GetMainModule();
955 PythonDictionary globals = main_module.GetDictionary();
956
958 if (!locals.IsValid())
959 locals = unwrapIgnoringErrors(
961 if (!locals.IsValid())
962 locals = globals;
963
964 Expected<PythonObject> maybe_py_return =
965 runStringOneLine(in_string, globals, locals);
966
967 if (!maybe_py_return) {
968 llvm::handleAllErrors(
969 maybe_py_return.takeError(),
970 [&](PythonException &E) {
971 E.Restore();
972 if (options.GetMaskoutErrors()) {
973 if (E.Matches(PyExc_SyntaxError)) {
974 PyErr_Print();
975 }
976 PyErr_Clear();
977 }
978 },
979 [](const llvm::ErrorInfoBase &E) {});
980 return false;
981 }
982
983 PythonObject py_return = std::move(maybe_py_return.get());
984 assert(py_return.IsValid());
985
986 switch (return_type) {
987 case eScriptReturnTypeCharPtr: // "char *"
988 {
989 const char format[3] = "s#";
990 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
991 }
992 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
993 // Py_None
994 {
995 const char format[3] = "z";
996 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
997 }
998 case eScriptReturnTypeBool: {
999 const char format[2] = "b";
1000 return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1001 }
1002 case eScriptReturnTypeShortInt: {
1003 const char format[2] = "h";
1004 return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1005 }
1006 case eScriptReturnTypeShortIntUnsigned: {
1007 const char format[2] = "H";
1008 return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1009 }
1010 case eScriptReturnTypeInt: {
1011 const char format[2] = "i";
1012 return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1013 }
1014 case eScriptReturnTypeIntUnsigned: {
1015 const char format[2] = "I";
1016 return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1017 }
1018 case eScriptReturnTypeLongInt: {
1019 const char format[2] = "l";
1020 return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1021 }
1022 case eScriptReturnTypeLongIntUnsigned: {
1023 const char format[2] = "k";
1024 return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1025 }
1026 case eScriptReturnTypeLongLong: {
1027 const char format[2] = "L";
1028 return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1029 }
1030 case eScriptReturnTypeLongLongUnsigned: {
1031 const char format[2] = "K";
1032 return PyArg_Parse(py_return.get(), format,
1033 (unsigned long long *)ret_value);
1034 }
1035 case eScriptReturnTypeFloat: {
1036 const char format[2] = "f";
1037 return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1038 }
1039 case eScriptReturnTypeDouble: {
1040 const char format[2] = "d";
1041 return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1042 }
1043 case eScriptReturnTypeChar: {
1044 const char format[2] = "c";
1045 return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1046 }
1047 case eScriptReturnTypeOpaqueObject: {
1048 *((PyObject **)ret_value) = py_return.release();
1049 return true;
1051 }
1052 llvm_unreachable("Fully covered switch!");
1053}
1054
1056 const char *in_string, const ExecuteScriptOptions &options) {
1057
1058 if (in_string == nullptr)
1059 return Status();
1060
1061 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1062 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1063 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1064
1065 if (!io_redirect_or_error)
1066 return Status::FromError(io_redirect_or_error.takeError());
1067
1068 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1069
1070 Locker locker(this,
1072 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1075 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1076 io_redirect.GetErrorFile());
1077
1078 PythonModule &main_module = GetMainModule();
1079 PythonDictionary globals = main_module.GetDictionary();
1080
1081 PythonDictionary locals = GetSessionDictionary();
1082 if (!locals.IsValid())
1083 locals = unwrapIgnoringErrors(
1085 if (!locals.IsValid())
1086 locals = globals;
1087
1088 Expected<PythonObject> return_value =
1089 runStringMultiLine(in_string, globals, locals);
1090
1091 if (!return_value) {
1092 llvm::Error error =
1093 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1094 llvm::Error error = llvm::createStringError(
1095 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1096 if (!options.GetMaskoutErrors())
1097 E.Restore();
1098 return error;
1099 });
1100 return Status::FromError(std::move(error));
1102
1103 return Status();
1104}
1105
1107 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1108 CommandReturnObject &result) {
1110 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1111 " ", *this, &bp_options_vec);
1112}
1113
1115 WatchpointOptions *wp_options, CommandReturnObject &result) {
1117 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1118 " ", *this, wp_options);
1119}
1120
1122 BreakpointOptions &bp_options, const char *function_name,
1123 StructuredData::ObjectSP extra_args_sp) {
1124 Status error;
1125 // For now just cons up a oneliner that calls the provided function.
1126 std::string function_signature = function_name;
1127
1128 llvm::Expected<unsigned> maybe_args =
1130 if (!maybe_args) {
1132 "could not get num args: %s",
1133 llvm::toString(maybe_args.takeError()).c_str());
1134 return error;
1135 }
1136 size_t max_args = *maybe_args;
1137
1138 bool uses_extra_args = false;
1139 if (max_args >= 4) {
1140 uses_extra_args = true;
1141 function_signature += "(frame, bp_loc, extra_args, internal_dict)";
1142 } else if (max_args >= 3) {
1143 if (extra_args_sp) {
1145 "cannot pass extra_args to a three argument callback");
1146 return error;
1147 }
1148 uses_extra_args = false;
1149 function_signature += "(frame, bp_loc, internal_dict)";
1150 } else {
1151 error = Status::FromErrorStringWithFormat("expected 3 or 4 argument "
1152 "function, %s can only take %zu",
1153 function_name, max_args);
1154 return error;
1155 }
1156
1157 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1158 extra_args_sp, uses_extra_args,
1159 /*is_callback=*/true);
1160 return error;
1161}
1162
1164 BreakpointOptions &bp_options,
1165 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1166 Status error;
1167 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1168 cmd_data_up->script_source,
1169 /*has_extra_args=*/false,
1170 /*is_callback=*/false);
1171 if (error.Fail()) {
1172 return error;
1173 }
1174 auto baton_sp =
1175 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1182 BreakpointOptions &bp_options, const char *command_body_text,
1183 bool is_callback) {
1184 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1185 /*uses_extra_args=*/false, is_callback);
1186}
1187
1188// Set a Python one-liner as the callback for the breakpoint.
1190 BreakpointOptions &bp_options, const char *command_body_text,
1191 StructuredData::ObjectSP extra_args_sp, bool uses_extra_args,
1192 bool is_callback) {
1193 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1194 // Split the command_body_text into lines, and pass that to
1195 // GenerateBreakpointCommandCallbackData. That will wrap the body in an
1196 // auto-generated function, and return the function name in script_source.
1197 // That is what the callback will actually invoke.
1198
1199 data_up->user_source.SplitIntoLines(command_body_text);
1201 data_up->user_source, data_up->script_source, uses_extra_args,
1202 is_callback);
1203 if (error.Success()) {
1204 auto baton_sp =
1205 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1206 bp_options.SetCallback(
1208 return error;
1210 return error;
1211}
1212
1213// Set a Python one-liner as the callback for the watchpoint.
1215 WatchpointOptions *wp_options, const char *user_input, bool is_callback) {
1216 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1217
1218 // It's necessary to set both user_source and script_source to the oneliner.
1219 // The former is used to generate callback description (as in watchpoint
1220 // command list) while the latter is used for Python to interpret during the
1221 // actual callback.
1222
1223 data_up->user_source.AppendString(user_input);
1224 data_up->script_source.assign(user_input);
1225
1227 data_up->user_source, data_up->script_source, is_callback)) {
1228 auto baton_sp =
1229 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1230 wp_options->SetCallback(
1232 }
1233}
1234
1236 StringList &function_def) {
1237 // Convert StringList to one long, newline delimited, const char *.
1238 std::string function_def_string(function_def.CopyList());
1239 LLDB_LOG(GetLog(LLDBLog::Script), "Added Function:\n{0}\n",
1240 function_def_string.c_str());
1241
1243 function_def_string.c_str(), ExecuteScriptOptions().SetEnableIO(false));
1244 return error;
1245}
1246
1248 const StringList &input,
1249 bool is_callback) {
1250 Status error;
1251 int num_lines = input.GetSize();
1252 if (num_lines == 0) {
1253 error = Status::FromErrorString("No input data.");
1254 return error;
1255 }
1256
1257 if (!signature || *signature == 0) {
1258 error = Status::FromErrorString("No output function name.");
1259 return error;
1260 }
1261
1262 StreamString sstr;
1263 StringList auto_generated_function;
1264 auto_generated_function.AppendString(signature);
1265 auto_generated_function.AppendString(
1266 " global_dict = globals()"); // Grab the global dictionary
1267 auto_generated_function.AppendString(
1268 " new_keys = internal_dict.keys()"); // Make a list of keys in the
1269 // session dict
1270 auto_generated_function.AppendString(
1271 " old_keys = global_dict.keys()"); // Save list of keys in global dict
1272 auto_generated_function.AppendString(
1273 " global_dict.update(internal_dict)"); // Add the session dictionary
1274 // to the global dictionary.
1275
1276 if (is_callback) {
1277 // If the user input is a callback to a python function, make sure the input
1278 // is only 1 line, otherwise appending the user input would break the
1279 // generated wrapped function
1280 if (num_lines == 1) {
1281 sstr.Clear();
1282 sstr.Printf(" __return_val = %s", input.GetStringAtIndex(0));
1283 auto_generated_function.AppendString(sstr.GetData());
1284 } else {
1286 "ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1287 "true) = ERROR: python function is multiline.");
1288 }
1289 } else {
1290 auto_generated_function.AppendString(
1291 " __return_val = None"); // Initialize user callback return value.
1292 auto_generated_function.AppendString(
1293 " def __user_code():"); // Create a nested function that will wrap
1294 // the user input. This is necessary to
1295 // capture the return value of the user input
1296 // and prevent early returns.
1297 for (int i = 0; i < num_lines; ++i) {
1298 sstr.Clear();
1299 sstr.Printf(" %s", input.GetStringAtIndex(i));
1300 auto_generated_function.AppendString(sstr.GetData());
1301 }
1302 auto_generated_function.AppendString(
1303 " __return_val = __user_code()"); // Call user code and capture
1304 // return value
1305 }
1306 auto_generated_function.AppendString(
1307 " for key in new_keys:"); // Iterate over all the keys from session
1308 // dict
1309 auto_generated_function.AppendString(
1310 " if key in old_keys:"); // If key was originally in
1311 // global dict
1312 auto_generated_function.AppendString(
1313 " internal_dict[key] = global_dict[key]"); // Update it
1314 auto_generated_function.AppendString(
1315 " elif key in global_dict:"); // Then if it is still in the
1316 // global dict
1317 auto_generated_function.AppendString(
1318 " del global_dict[key]"); // remove key/value from the
1319 // global dict
1320 auto_generated_function.AppendString(
1321 " return __return_val"); // Return the user callback return value.
1322
1323 // Verify that the results are valid Python.
1325
1326 return error;
1327}
1328
1330 StringList &user_input, std::string &output, const void *name_token) {
1331 static uint32_t num_created_functions = 0;
1332 user_input.RemoveBlankLines();
1333 StreamString sstr;
1334
1335 // Check to see if we have any data; if not, just return.
1336 if (user_input.GetSize() == 0)
1337 return false;
1338
1339 // Take what the user wrote, wrap it all up inside one big auto-generated
1340 // Python function, passing in the ValueObject as parameter to the function.
1341
1342 std::string auto_generated_function_name(
1343 GenerateUniqueName("lldb_autogen_python_type_print_func",
1344 num_created_functions, name_token));
1345 sstr.Printf("def %s (valobj, internal_dict):",
1346 auto_generated_function_name.c_str());
1347
1348 if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1349 .Success())
1350 return false;
1351
1352 // Store the name of the auto-generated function to be called.
1353 output.assign(auto_generated_function_name);
1354 return true;
1355}
1356
1358 StringList &user_input, std::string &output) {
1359 static uint32_t num_created_functions = 0;
1360 user_input.RemoveBlankLines();
1361 StreamString sstr;
1362
1363 // Check to see if we have any data; if not, just return.
1364 if (user_input.GetSize() == 0)
1365 return false;
1366
1367 std::string auto_generated_function_name(GenerateUniqueName(
1368 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1369
1370 sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
1371 auto_generated_function_name.c_str());
1372
1373 if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1374 .Success())
1375 return false;
1376
1377 // Store the name of the auto-generated function to be called.
1378 output.assign(auto_generated_function_name);
1379 return true;
1380}
1381
1383 StringList &user_input, std::string &output, const void *name_token) {
1384 static uint32_t num_created_classes = 0;
1385 user_input.RemoveBlankLines();
1386 int num_lines = user_input.GetSize();
1387 StreamString sstr;
1388
1389 // Check to see if we have any data; if not, just return.
1390 if (user_input.GetSize() == 0)
1391 return false;
1392
1393 // Wrap all user input into a Python class
1394
1395 std::string auto_generated_class_name(GenerateUniqueName(
1396 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1397
1398 StringList auto_generated_class;
1399
1400 // Create the function name & definition string.
1401
1402 sstr.Printf("class %s:", auto_generated_class_name.c_str());
1403 auto_generated_class.AppendString(sstr.GetString());
1404
1405 // Wrap everything up inside the class, increasing the indentation. we don't
1406 // need to play any fancy indentation tricks here because there is no
1407 // surrounding code whose indentation we need to honor
1408 for (int i = 0; i < num_lines; ++i) {
1409 sstr.Clear();
1410 sstr.Printf(" %s", user_input.GetStringAtIndex(i));
1411 auto_generated_class.AppendString(sstr.GetString());
1412 }
1413
1414 // Verify that the results are valid Python. (even though the method is
1415 // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1416 // (TODO: rename that method to ExportDefinitionToInterpreter)
1417 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1418 return false;
1419
1420 // Store the name of the auto-generated class
1421
1422 output.assign(auto_generated_class_name);
1423 return true;
1424}
1425
1428 if (class_name == nullptr || class_name[0] == '\0')
1430
1433 class_name, m_dictionary_name.c_str());
1436 new StructuredPythonObject(std::move(ret_val)));
1437}
1438
1440 const StructuredData::ObjectSP &os_plugin_object_sp,
1441 lldb::StackFrameSP frame_sp) {
1443
1444 if (!os_plugin_object_sp)
1445 return ValueObjectListSP();
1446
1447 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1448 if (!generic)
1449 return nullptr;
1450
1452 (PyObject *)generic->GetValue());
1453
1454 if (!implementor.IsAllocated())
1455 return ValueObjectListSP();
1456
1459 implementor.get(), frame_sp));
1460
1461 // if it fails, print the error but otherwise go on
1462 if (PyErr_Occurred()) {
1463 PyErr_Print();
1464 PyErr_Clear();
1465 }
1466 if (py_return.get()) {
1467 PythonList result_list(PyRefType::Borrowed, py_return.get());
1468 ValueObjectListSP result = std::make_shared<ValueObjectList>();
1469 for (size_t i = 0; i < result_list.GetSize(); i++) {
1470 PyObject *item = result_list.GetItemAtIndex(i).get();
1471 lldb::SBValue *sb_value_ptr =
1473 auto valobj_sp =
1475 if (valobj_sp)
1476 result->Append(valobj_sp);
1477 }
1478 return result;
1479 }
1480 return ValueObjectListSP();
1481}
1482
1484 const StructuredData::ObjectSP &os_plugin_object_sp,
1485 lldb::StackFrameSP frame_sp) {
1487
1488 if (!os_plugin_object_sp)
1489 return false;
1490
1491 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1492 if (!generic)
1493 return false;
1494
1496 (PyObject *)generic->GetValue());
1497
1498 if (!implementor.IsAllocated())
1499 return false;
1500
1501 bool result =
1502 SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1503
1504 // if it fails, print the error but otherwise go on
1505 if (PyErr_Occurred()) {
1506 PyErr_Print();
1507 PyErr_Clear();
1509 return result;
1510}
1511
1514 return std::make_unique<ScriptedProcessPythonInterface>(*this);
1515}
1516
1519 return std::make_shared<ScriptedStopHookPythonInterface>(*this);
1520}
1521
1524 return std::make_shared<ScriptedBreakpointPythonInterface>(*this);
1525}
1526
1529 return std::make_shared<ScriptedThreadPythonInterface>(*this);
1530}
1531
1534 return std::make_shared<ScriptedFramePythonInterface>(*this);
1535}
1536
1539 return std::make_shared<ScriptedFrameProviderPythonInterface>(*this);
1540}
1541
1544 return std::make_shared<ScriptedThreadPlanPythonInterface>(*this);
1545}
1546
1549 return std::make_shared<OperatingSystemPythonInterface>(*this);
1550}
1551
1554 ScriptObject obj) {
1555 void *ptr = const_cast<void *>(obj.GetPointer());
1557 PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr));
1558 if (!py_obj.IsValid() || py_obj.IsNone())
1559 return {};
1560 return py_obj.CreateStructuredObject();
1561}
1562
1566 if (!FileSystem::Instance().Exists(file_spec)) {
1567 error = Status::FromErrorString("no such file");
1568 return StructuredData::ObjectSP();
1569 }
1570
1571 StructuredData::ObjectSP module_sp;
1572
1573 LoadScriptOptions load_script_options =
1574 LoadScriptOptions().SetInitSession(true).SetSilent(false);
1575 if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1576 error, &module_sp))
1577 return module_sp;
1578
1579 return StructuredData::ObjectSP();
1580}
1581
1583 StructuredData::ObjectSP plugin_module_sp, Target *target,
1584 const char *setting_name, lldb_private::Status &error) {
1585 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1587 StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1588 if (!generic)
1590
1591 Locker py_lock(this,
1593 TargetSP target_sp(target->shared_from_this());
1594
1595 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1596 generic->GetValue(), setting_name, target_sp);
1597
1598 if (!setting)
1600
1601 PythonDictionary py_dict =
1603
1604 if (!py_dict)
1607 return py_dict.CreateStructuredDictionary();
1608}
1609
1612 const char *class_name, lldb::ValueObjectSP valobj) {
1613 if (class_name == nullptr || class_name[0] == '\0')
1614 return StructuredData::ObjectSP();
1615
1616 if (!valobj.get())
1617 return StructuredData::ObjectSP();
1618
1619 ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1620 Target *target = exe_ctx.GetTargetPtr();
1621
1622 if (!target)
1623 return StructuredData::ObjectSP();
1624
1625 Debugger &debugger = target->GetDebugger();
1626 ScriptInterpreterPythonImpl *python_interpreter =
1627 GetPythonInterpreter(debugger);
1628
1629 if (!python_interpreter)
1630 return StructuredData::ObjectSP();
1631
1632 Locker py_lock(this,
1635 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1636
1638 new StructuredPythonObject(std::move(ret_val)));
1639}
1640
1643 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1644
1645 if (class_name == nullptr || class_name[0] == '\0')
1647
1648 if (!debugger_sp.get())
1650
1651 Locker py_lock(this,
1654 class_name, m_dictionary_name.c_str(), debugger_sp);
1655
1656 if (ret_val.IsValid())
1658 new StructuredPythonObject(std::move(ret_val)));
1659 else
1660 return {};
1661}
1662
1664 const char *oneliner, std::string &output, const void *name_token) {
1666 input.SplitIntoLines(oneliner, strlen(oneliner));
1667 return GenerateTypeScriptFunction(input, output, name_token);
1668}
1669
1671 const char *oneliner, std::string &output, const void *name_token) {
1673 input.SplitIntoLines(oneliner, strlen(oneliner));
1674 return GenerateTypeSynthClass(input, output, name_token);
1675}
1676
1678 StringList &user_input, std::string &output, bool has_extra_args,
1679 bool is_callback) {
1680 static uint32_t num_created_functions = 0;
1681 user_input.RemoveBlankLines();
1682 StreamString sstr;
1683 Status error;
1684 if (user_input.GetSize() == 0) {
1685 error = Status::FromErrorString("No input data.");
1686 return error;
1687 }
1688
1689 std::string auto_generated_function_name(GenerateUniqueName(
1690 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1691 if (has_extra_args)
1692 sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1693 auto_generated_function_name.c_str());
1694 else
1695 sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1696 auto_generated_function_name.c_str());
1697
1698 error = GenerateFunction(sstr.GetData(), user_input, is_callback);
1699 if (!error.Success())
1700 return error;
1701
1702 // Store the name of the auto-generated function to be called.
1703 output.assign(auto_generated_function_name);
1704 return error;
1705}
1706
1708 StringList &user_input, std::string &output, bool is_callback) {
1709 static uint32_t num_created_functions = 0;
1710 user_input.RemoveBlankLines();
1711 StreamString sstr;
1712
1713 if (user_input.GetSize() == 0)
1714 return false;
1715
1716 std::string auto_generated_function_name(GenerateUniqueName(
1717 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1718 sstr.Printf("def %s (frame, wp, internal_dict):",
1719 auto_generated_function_name.c_str());
1720
1721 if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
1722 return false;
1723
1724 // Store the name of the auto-generated function to be called.
1725 output.assign(auto_generated_function_name);
1726 return true;
1727}
1728
1730 const char *python_function_name, lldb::ValueObjectSP valobj,
1731 StructuredData::ObjectSP &callee_wrapper_sp,
1732 const TypeSummaryOptions &options, std::string &retval) {
1733
1735
1736 if (!valobj.get()) {
1737 retval.assign("<no object>");
1738 return false;
1739 }
1740
1741 void *old_callee = nullptr;
1742 StructuredData::Generic *generic = nullptr;
1743 if (callee_wrapper_sp) {
1744 generic = callee_wrapper_sp->GetAsGeneric();
1745 if (generic)
1746 old_callee = generic->GetValue();
1747 }
1748 void *new_callee = old_callee;
1749
1750 bool ret_val;
1751 if (python_function_name && *python_function_name) {
1752 {
1755 {
1756 TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
1757
1758 static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
1759 Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
1761 python_function_name, GetSessionDictionary().get(), valobj,
1762 &new_callee, options_sp, retval);
1763 }
1764 }
1765 } else {
1766 retval.assign("<no function name>");
1767 return false;
1768 }
1769
1770 if (new_callee && old_callee != new_callee) {
1771 Locker py_lock(this,
1773 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1774 PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
1776
1777 return ret_val;
1778}
1779
1781 const char *python_function_name, TypeImplSP type_impl_sp) {
1782 Locker py_lock(this,
1785 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1786}
1787
1789 void *baton, StoppointCallbackContext *context, user_id_t break_id,
1790 user_id_t break_loc_id) {
1791 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1792 const char *python_function_name = bp_option_data->script_source.c_str();
1793
1794 if (!context)
1795 return true;
1796
1797 ExecutionContext exe_ctx(context->exe_ctx_ref);
1798 Target *target = exe_ctx.GetTargetPtr();
1799
1800 if (!target)
1801 return true;
1802
1803 Debugger &debugger = target->GetDebugger();
1804 ScriptInterpreterPythonImpl *python_interpreter =
1805 GetPythonInterpreter(debugger);
1806
1807 if (!python_interpreter)
1808 return true;
1809
1810 if (python_function_name && python_function_name[0]) {
1811 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1812 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
1813 if (breakpoint_sp) {
1814 const BreakpointLocationSP bp_loc_sp(
1815 breakpoint_sp->FindLocationByID(break_loc_id));
1816
1817 if (stop_frame_sp && bp_loc_sp) {
1818 bool ret_val = true;
1819 {
1820 Locker py_lock(python_interpreter, Locker::AcquireLock |
1823 Expected<bool> maybe_ret_val =
1825 python_function_name,
1826 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1827 bp_loc_sp, bp_option_data->m_extra_args);
1828
1829 if (!maybe_ret_val) {
1830
1831 llvm::handleAllErrors(
1832 maybe_ret_val.takeError(),
1833 [&](PythonException &E) {
1834 *debugger.GetAsyncErrorStream() << E.ReadBacktrace();
1835 },
1836 [&](const llvm::ErrorInfoBase &E) {
1837 *debugger.GetAsyncErrorStream() << E.message();
1838 });
1839
1840 } else {
1841 ret_val = maybe_ret_val.get();
1842 }
1843 }
1844 return ret_val;
1845 }
1846 }
1847 }
1848 // We currently always true so we stop in case anything goes wrong when
1849 // trying to call the script function
1850 return true;
1851}
1852
1854 void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
1855 WatchpointOptions::CommandData *wp_option_data =
1857 const char *python_function_name = wp_option_data->script_source.c_str();
1858
1859 if (!context)
1860 return true;
1861
1862 ExecutionContext exe_ctx(context->exe_ctx_ref);
1863 Target *target = exe_ctx.GetTargetPtr();
1864
1865 if (!target)
1866 return true;
1867
1868 Debugger &debugger = target->GetDebugger();
1869 ScriptInterpreterPythonImpl *python_interpreter =
1870 GetPythonInterpreter(debugger);
1871
1872 if (!python_interpreter)
1873 return true;
1874
1875 if (python_function_name && python_function_name[0]) {
1876 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1877 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
1878 if (wp_sp) {
1879 if (stop_frame_sp && wp_sp) {
1880 bool ret_val = true;
1881 {
1882 Locker py_lock(python_interpreter, Locker::AcquireLock |
1886 python_function_name,
1887 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1888 wp_sp);
1889 }
1890 return ret_val;
1891 }
1892 }
1893 }
1894 // We currently always true so we stop in case anything goes wrong when
1895 // trying to call the script function
1896 return true;
1897}
1898
1900 const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
1901 if (!implementor_sp)
1902 return 0;
1903 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1904 if (!generic)
1905 return 0;
1906 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1907 if (!implementor)
1908 return 0;
1909
1910 size_t ret_val = 0;
1911
1912 {
1913 Locker py_lock(this,
1915 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
1917
1918 return ret_val;
1919}
1920
1922 const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
1923 if (!implementor_sp)
1924 return lldb::ValueObjectSP();
1925
1926 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1927 if (!generic)
1928 return lldb::ValueObjectSP();
1929 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1930 if (!implementor)
1931 return lldb::ValueObjectSP();
1932
1933 lldb::ValueObjectSP ret_val;
1934 {
1935 Locker py_lock(this,
1937 PyObject *child_ptr =
1939 if (child_ptr != nullptr && child_ptr != Py_None) {
1940 lldb::SBValue *sb_value_ptr =
1942 if (sb_value_ptr == nullptr)
1943 Py_XDECREF(child_ptr);
1944 else
1946 sb_value_ptr);
1947 } else {
1948 Py_XDECREF(child_ptr);
1949 }
1951
1952 return ret_val;
1953}
1954
1956 const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
1957 if (!implementor_sp)
1958 return llvm::createStringError("Type has no child named '%s'", child_name);
1959
1960 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1961 if (!generic)
1962 return llvm::createStringError("Type has no child named '%s'", child_name);
1963 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1964 if (!implementor)
1965 return llvm::createStringError("Type has no child named '%s'", child_name);
1966
1967 uint32_t ret_val = UINT32_MAX;
1968
1969 {
1970 Locker py_lock(this,
1973 child_name);
1974 }
1975
1976 if (ret_val == UINT32_MAX)
1977 return llvm::createStringError("Type has no child named '%s'", child_name);
1978 return ret_val;
1979}
1980
1982 const StructuredData::ObjectSP &implementor_sp) {
1983 bool ret_val = false;
1984
1985 if (!implementor_sp)
1986 return ret_val;
1987
1988 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1989 if (!generic)
1990 return ret_val;
1991 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1992 if (!implementor)
1993 return ret_val;
1994
1995 {
1996 Locker py_lock(this,
1998 ret_val =
2001
2002 return ret_val;
2003}
2004
2006 const StructuredData::ObjectSP &implementor_sp) {
2007 bool ret_val = false;
2008
2009 if (!implementor_sp)
2010 return ret_val;
2011
2012 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2013 if (!generic)
2014 return ret_val;
2015 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2016 if (!implementor)
2017 return ret_val;
2018
2019 {
2020 Locker py_lock(this,
2023 implementor);
2025
2026 return ret_val;
2027}
2028
2030 const StructuredData::ObjectSP &implementor_sp) {
2031 lldb::ValueObjectSP ret_val(nullptr);
2032
2033 if (!implementor_sp)
2034 return ret_val;
2035
2036 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2037 if (!generic)
2038 return ret_val;
2039 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2040 if (!implementor)
2041 return ret_val;
2042
2043 {
2044 Locker py_lock(this,
2046 PyObject *child_ptr =
2048 if (child_ptr != nullptr && child_ptr != Py_None) {
2049 lldb::SBValue *sb_value_ptr =
2051 if (sb_value_ptr == nullptr)
2052 Py_XDECREF(child_ptr);
2053 else
2055 sb_value_ptr);
2056 } else {
2057 Py_XDECREF(child_ptr);
2058 }
2060
2061 return ret_val;
2062}
2063
2065 const StructuredData::ObjectSP &implementor_sp) {
2066 Locker py_lock(this,
2068
2069 if (!implementor_sp)
2070 return {};
2071
2072 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2073 if (!generic)
2074 return {};
2075
2076 PythonObject implementor(PyRefType::Borrowed,
2077 (PyObject *)generic->GetValue());
2078 if (!implementor.IsAllocated())
2079 return {};
2080
2081 llvm::Expected<PythonObject> expected_py_return =
2082 implementor.CallMethod("get_type_name");
2083
2084 if (!expected_py_return) {
2085 llvm::consumeError(expected_py_return.takeError());
2086 return {};
2087 }
2088
2089 PythonObject py_return = std::move(expected_py_return.get());
2090 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2091 return {};
2093 PythonString type_name(PyRefType::Borrowed, py_return.get());
2094 return ConstString(type_name.GetString());
2095}
2096
2098 const char *impl_function, Process *process, std::string &output,
2099 Status &error) {
2100 bool ret_val;
2101 if (!process) {
2102 error = Status::FromErrorString("no process");
2103 return false;
2104 }
2105 if (!impl_function || !impl_function[0]) {
2106 error = Status::FromErrorString("no function to execute");
2107 return false;
2108 }
2109
2110 {
2111 Locker py_lock(this,
2114 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2115 output);
2116 if (!ret_val)
2117 error = Status::FromErrorString("python script evaluation failed");
2118 }
2119 return ret_val;
2120}
2121
2123 const char *impl_function, Thread *thread, std::string &output,
2124 Status &error) {
2125 if (!thread) {
2126 error = Status::FromErrorString("no thread");
2127 return false;
2128 }
2129 if (!impl_function || !impl_function[0]) {
2130 error = Status::FromErrorString("no function to execute");
2131 return false;
2132 }
2133
2134 Locker py_lock(this,
2136 if (std::optional<std::string> result =
2138 impl_function, m_dictionary_name.c_str(),
2139 thread->shared_from_this())) {
2140 output = std::move(*result);
2141 return true;
2143 error = Status::FromErrorString("python script evaluation failed");
2144 return false;
2145}
2146
2148 const char *impl_function, Target *target, std::string &output,
2149 Status &error) {
2150 bool ret_val;
2151 if (!target) {
2152 error = Status::FromErrorString("no thread");
2153 return false;
2154 }
2155 if (!impl_function || !impl_function[0]) {
2156 error = Status::FromErrorString("no function to execute");
2157 return false;
2158 }
2159
2160 {
2161 TargetSP target_sp(target->shared_from_this());
2162 Locker py_lock(this,
2165 impl_function, m_dictionary_name.c_str(), target_sp, output);
2166 if (!ret_val)
2167 error = Status::FromErrorString("python script evaluation failed");
2168 }
2169 return ret_val;
2170}
2171
2173 const char *impl_function, StackFrame *frame, std::string &output,
2174 Status &error) {
2175 if (!frame) {
2176 error = Status::FromErrorString("no frame");
2177 return false;
2178 }
2179 if (!impl_function || !impl_function[0]) {
2180 error = Status::FromErrorString("no function to execute");
2181 return false;
2182 }
2183
2184 Locker py_lock(this,
2186 if (std::optional<std::string> result =
2188 impl_function, m_dictionary_name.c_str(),
2189 frame->shared_from_this())) {
2190 output = std::move(*result);
2191 return true;
2193 error = Status::FromErrorString("python script evaluation failed");
2194 return false;
2195}
2196
2198 const char *impl_function, ValueObject *value, std::string &output,
2199 Status &error) {
2200 bool ret_val;
2201 if (!value) {
2202 error = Status::FromErrorString("no value");
2203 return false;
2204 }
2205 if (!impl_function || !impl_function[0]) {
2206 error = Status::FromErrorString("no function to execute");
2207 return false;
2208 }
2209
2210 {
2211 Locker py_lock(this,
2214 impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2215 if (!ret_val)
2216 error = Status::FromErrorString("python script evaluation failed");
2217 }
2218 return ret_val;
2219}
2220
2221uint64_t replace_all(std::string &str, const std::string &oldStr,
2222 const std::string &newStr) {
2223 size_t pos = 0;
2224 uint64_t matches = 0;
2225 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2226 matches++;
2227 str.replace(pos, oldStr.length(), newStr);
2228 pos += newStr.length();
2229 }
2230 return matches;
2231}
2232
2234 const char *pathname, const LoadScriptOptions &options,
2236 FileSpec extra_search_dir, lldb::TargetSP target_sp) {
2237 namespace fs = llvm::sys::fs;
2238 namespace path = llvm::sys::path;
2239
2241 .SetEnableIO(!options.GetSilent())
2242 .SetSetLLDBGlobals(false);
2243
2244 if (!pathname || !pathname[0]) {
2245 error = Status::FromErrorString("empty path");
2246 return false;
2247 }
2248
2249 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2250 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2251 exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2252
2253 if (!io_redirect_or_error) {
2254 error = Status::FromError(io_redirect_or_error.takeError());
2255 return false;
2256 }
2257
2258 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2259
2260 // Before executing Python code, lock the GIL.
2261 Locker py_lock(this,
2263 (options.GetInitSession() ? Locker::InitSession : 0) |
2266 (options.GetInitSession() ? Locker::TearDownSession : 0),
2267 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2268 io_redirect.GetErrorFile());
2269
2270 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2271 if (directory.empty()) {
2272 return llvm::createStringError("invalid directory name");
2273 }
2274
2275 replace_all(directory, "\\", "\\\\");
2276 replace_all(directory, "'", "\\'");
2277
2278 // Make sure that Python has "directory" in the search path.
2279 StreamString command_stream;
2280 command_stream.Printf("if not (sys.path.__contains__('%s')):\n "
2281 "sys.path.insert(1,'%s');\n\n",
2282 directory.c_str(), directory.c_str());
2283 bool syspath_retval =
2284 ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2285 if (!syspath_retval)
2286 return llvm::createStringError("Python sys.path handling failed");
2287
2288 return llvm::Error::success();
2289 };
2290
2291 std::string module_name(pathname);
2292 bool possible_package = false;
2293
2294 if (extra_search_dir) {
2295 if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2296 error = Status::FromError(std::move(e));
2297 return false;
2298 }
2299 } else {
2300 FileSpec module_file(pathname);
2301 FileSystem::Instance().Resolve(module_file);
2302
2303 fs::file_status st;
2304 std::error_code ec = status(module_file.GetPath(), st);
2305
2306 if (ec || st.type() == fs::file_type::status_error ||
2307 st.type() == fs::file_type::type_unknown ||
2308 st.type() == fs::file_type::file_not_found) {
2309 // if not a valid file of any sort, check if it might be a filename still
2310 // dot can't be used but / and \ can, and if either is found, reject
2311 if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2312 error = Status::FromErrorStringWithFormatv("invalid pathname '{0}'",
2313 pathname);
2314 return false;
2315 }
2316 // Not a filename, probably a package of some sort, let it go through.
2317 possible_package = true;
2318 } else if (is_directory(st) || is_regular_file(st)) {
2319 if (module_file.GetDirectory().IsEmpty()) {
2321 "invalid directory name '{0}'", pathname);
2322 return false;
2323 }
2324 if (llvm::Error e =
2325 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2326 error = Status::FromError(std::move(e));
2327 return false;
2328 }
2329 module_name = module_file.GetFilename().GetCString();
2330 } else {
2332 "no known way to import this module specification");
2333 return false;
2334 }
2335 }
2336
2337 // Strip .py or .pyc extension
2338 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2339 if (!extension.empty()) {
2340 if (extension == ".py")
2341 module_name.resize(module_name.length() - 3);
2342 else if (extension == ".pyc")
2343 module_name.resize(module_name.length() - 4);
2344 }
2345
2346 if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2348 "Python does not allow dots in module names: %s", module_name.c_str());
2349 return false;
2350 }
2351
2352 if (module_name.find('-') != llvm::StringRef::npos) {
2354 "Python discourages dashes in module names: %s", module_name.c_str());
2355 return false;
2356 }
2357
2358 // Check if the module is already imported.
2359 StreamString command_stream;
2360 command_stream.Clear();
2361 command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2362 bool does_contain = false;
2363 // This call will succeed if the module was ever imported in any Debugger in
2364 // the lifetime of the process in which this LLDB framework is living.
2365 const bool does_contain_executed = ExecuteOneLineWithReturn(
2366 command_stream.GetData(),
2368 exc_options);
2369
2370 const bool was_imported_globally = does_contain_executed && does_contain;
2371 const bool was_imported_locally =
2373 .GetItemForKey(PythonString(module_name))
2374 .IsAllocated();
2375
2376 // now actually do the import
2377 command_stream.Clear();
2378
2379 if (was_imported_globally || was_imported_locally) {
2380 if (!was_imported_locally)
2381 command_stream.Printf("import %s ; reload_module(%s)",
2382 module_name.c_str(), module_name.c_str());
2383 else
2384 command_stream.Printf("reload_module(%s)", module_name.c_str());
2385 } else
2386 command_stream.Printf("import %s", module_name.c_str());
2387
2388 error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2389 if (error.Fail())
2390 return false;
2391
2392 // if we are here, everything worked
2393 // call __lldb_init_module(debugger,dict)
2395 module_name.c_str(), m_dictionary_name.c_str(),
2396 m_debugger.shared_from_this())) {
2397 error = Status::FromErrorString("calling __lldb_init_module failed");
2398 return false;
2399 }
2400
2401 if (module_sp) {
2402 // everything went just great, now set the module object
2403 command_stream.Clear();
2404 command_stream.Printf("%s", module_name.c_str());
2405 void *module_pyobj = nullptr;
2407 command_stream.GetData(),
2409 exc_options) &&
2410 module_pyobj)
2411 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2412 PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2413 }
2414
2415 // Finally, if we got a target passed in, then we should tell the new module
2416 // about this target:
2417 if (target_sp)
2419 module_name.c_str(), m_dictionary_name.c_str(), target_sp);
2420
2421 return true;
2422}
2423
2424bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2425 if (!word || !word[0])
2426 return false;
2427
2428 llvm::StringRef word_sr(word);
2429
2430 // filter out a few characters that would just confuse us and that are
2431 // clearly not keyword material anyway
2432 if (word_sr.find('"') != llvm::StringRef::npos ||
2433 word_sr.find('\'') != llvm::StringRef::npos)
2434 return false;
2435
2436 StreamString command_stream;
2437 command_stream.Printf("keyword.iskeyword('%s')", word);
2438 bool result;
2439 ExecuteScriptOptions options;
2440 options.SetEnableIO(false);
2441 options.SetMaskoutErrors(true);
2442 options.SetSetLLDBGlobals(false);
2443 if (ExecuteOneLineWithReturn(command_stream.GetData(),
2445 &result, options))
2446 return result;
2447 return false;
2448}
2449
2452 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2453 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2455 m_debugger_sp->SetAsyncExecution(false);
2457 m_debugger_sp->SetAsyncExecution(true);
2458}
2459
2461 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2462 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2463}
2464
2466 const char *impl_function, llvm::StringRef args,
2467 ScriptedCommandSynchronicity synchronicity,
2469 const lldb_private::ExecutionContext &exe_ctx) {
2470 if (!impl_function) {
2471 error = Status::FromErrorString("no function to execute");
2472 return false;
2473 }
2474
2475 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2476 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2477
2478 if (!debugger_sp.get()) {
2479 error = Status::FromErrorString("invalid Debugger pointer");
2480 return false;
2481 }
2482
2483 bool ret_val = false;
2484
2485 {
2486 Locker py_lock(this,
2488 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2490
2491 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2492
2493 std::string args_str = args.str();
2495 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2496 cmd_retobj, exe_ctx_ref_sp);
2497 }
2498
2499 if (!ret_val)
2500 error = Status::FromErrorString("unable to execute script function");
2501 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2502 return false;
2504 error.Clear();
2505 return ret_val;
2506}
2507
2509 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2510 ScriptedCommandSynchronicity synchronicity,
2512 const lldb_private::ExecutionContext &exe_ctx) {
2513 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2514 error = Status::FromErrorString("no function to execute");
2515 return false;
2516 }
2517
2518 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2519 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2520
2521 if (!debugger_sp.get()) {
2522 error = Status::FromErrorString("invalid Debugger pointer");
2523 return false;
2524 }
2525
2526 bool ret_val = false;
2527
2528 {
2529 Locker py_lock(this,
2531 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2533
2534 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2535
2536 std::string args_str = args.str();
2538 static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2539 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2540 }
2541
2542 if (!ret_val)
2543 error = Status::FromErrorString("unable to execute script function");
2544 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2545 return false;
2547 error.Clear();
2548 return ret_val;
2549}
2550
2552 StructuredData::GenericSP impl_obj_sp, Args &args,
2553 ScriptedCommandSynchronicity synchronicity,
2555 const lldb_private::ExecutionContext &exe_ctx) {
2556 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2557 error = Status::FromErrorString("no function to execute");
2558 return false;
2559 }
2560
2561 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2562 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2563
2564 if (!debugger_sp.get()) {
2565 error = Status::FromErrorString("invalid Debugger pointer");
2566 return false;
2567 }
2568
2569 bool ret_val = false;
2570
2571 {
2572 Locker py_lock(this,
2574 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2576
2577 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2578
2579 StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2580
2581 for (const Args::ArgEntry &entry : args) {
2582 args_arr_sp->AddStringItem(entry.ref());
2583 }
2584 StructuredDataImpl args_impl(args_arr_sp);
2585
2587 static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2588 args_impl, cmd_retobj, exe_ctx_ref_sp);
2589 }
2590
2591 if (!ret_val)
2592 error = Status::FromErrorString("unable to execute script function");
2593 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2594 return false;
2595
2596 error.Clear();
2597 return ret_val;
2598}
2599
2600std::optional<std::string>
2602 StructuredData::GenericSP impl_obj_sp, Args &args) {
2603 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2604 return std::nullopt;
2605
2606 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2607
2608 if (!debugger_sp.get())
2609 return std::nullopt;
2610
2611 std::optional<std::string> ret_val;
2612
2613 {
2616
2618
2619 // For scripting commands, we send the command string:
2620 std::string command;
2621 args.GetQuotedCommandString(command);
2623 static_cast<PyObject *>(impl_obj_sp->GetValue()), command);
2625 return ret_val;
2626}
2627
2630 StructuredData::GenericSP impl_obj_sp, std::vector<llvm::StringRef> &args,
2631 size_t args_pos, size_t char_in_arg) {
2632 StructuredData::DictionarySP completion_dict_sp;
2633 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2634 return completion_dict_sp;
2635
2636 {
2639
2640 completion_dict_sp =
2642 static_cast<PyObject *>(impl_obj_sp->GetValue()), args, args_pos,
2643 char_in_arg);
2645 return completion_dict_sp;
2646}
2647
2650 StructuredData::GenericSP impl_obj_sp, llvm::StringRef &long_option,
2651 size_t char_in_arg) {
2652 StructuredData::DictionarySP completion_dict_sp;
2653 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2654 return completion_dict_sp;
2655
2656 {
2659
2660 completion_dict_sp = SWIGBridge::
2662 static_cast<PyObject *>(impl_obj_sp->GetValue()), long_option,
2663 char_in_arg);
2664 }
2665 return completion_dict_sp;
2667
2668/// In Python, a special attribute __doc__ contains the docstring for an object
2669/// (function, method, class, ...) if any is defined Otherwise, the attribute's
2670/// value is None.
2672 std::string &dest) {
2673 dest.clear();
2674
2675 if (!item || !*item)
2676 return false;
2677
2678 std::string command(item);
2679 command += ".__doc__";
2680
2681 // Python is going to point this to valid data if ExecuteOneLineWithReturn
2682 // returns successfully.
2683 char *result_ptr = nullptr;
2684
2687 &result_ptr, ExecuteScriptOptions().SetEnableIO(false))) {
2688 if (result_ptr)
2689 dest.assign(result_ptr);
2690 return true;
2691 }
2692
2693 StreamString str_stream;
2694 str_stream << "Function " << item
2695 << " was not found. Containing module might be missing.";
2696 dest = std::string(str_stream.GetString());
2697
2698 return false;
2699}
2700
2702 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2703 dest.clear();
2704
2706
2707 if (!cmd_obj_sp)
2708 return false;
2709
2711 (PyObject *)cmd_obj_sp->GetValue());
2712
2713 if (!implementor.IsAllocated())
2714 return false;
2715
2716 llvm::Expected<PythonObject> expected_py_return =
2717 implementor.CallMethod("get_short_help");
2718
2719 if (!expected_py_return) {
2720 llvm::consumeError(expected_py_return.takeError());
2721 return false;
2722 }
2723
2724 PythonObject py_return = std::move(expected_py_return.get());
2725
2726 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2727 PythonString py_string(PyRefType::Borrowed, py_return.get());
2728 llvm::StringRef return_data(py_string.GetString());
2729 dest.assign(return_data.data(), return_data.size());
2730 return true;
2732
2733 return false;
2734}
2735
2737 StructuredData::GenericSP cmd_obj_sp) {
2738 uint32_t result = 0;
2739
2741
2742 static char callee_name[] = "get_flags";
2743
2744 if (!cmd_obj_sp)
2745 return result;
2746
2748 (PyObject *)cmd_obj_sp->GetValue());
2749
2750 if (!implementor.IsAllocated())
2751 return result;
2752
2754 PyObject_GetAttrString(implementor.get(), callee_name));
2755
2756 if (PyErr_Occurred())
2757 PyErr_Clear();
2758
2759 if (!pmeth.IsAllocated())
2760 return result;
2761
2762 if (PyCallable_Check(pmeth.get()) == 0) {
2763 if (PyErr_Occurred())
2764 PyErr_Clear();
2765 return result;
2766 }
2767
2768 if (PyErr_Occurred())
2769 PyErr_Clear();
2770
2771 long long py_return = unwrapOrSetPythonException(
2772 As<long long>(implementor.CallMethod(callee_name)));
2773
2774 // if it fails, print the error but otherwise go on
2775 if (PyErr_Occurred()) {
2776 PyErr_Print();
2777 PyErr_Clear();
2778 } else {
2779 result = py_return;
2780 }
2782 return result;
2783}
2784
2787 StructuredData::GenericSP cmd_obj_sp) {
2788 StructuredData::ObjectSP result = {};
2789
2791
2792 static char callee_name[] = "get_options_definition";
2793
2794 if (!cmd_obj_sp)
2795 return result;
2796
2798 (PyObject *)cmd_obj_sp->GetValue());
2799
2800 if (!implementor.IsAllocated())
2801 return result;
2802
2804 PyObject_GetAttrString(implementor.get(), callee_name));
2805
2806 if (PyErr_Occurred())
2807 PyErr_Clear();
2808
2809 if (!pmeth.IsAllocated())
2810 return result;
2811
2812 if (PyCallable_Check(pmeth.get()) == 0) {
2813 if (PyErr_Occurred())
2814 PyErr_Clear();
2815 return result;
2816 }
2817
2818 if (PyErr_Occurred())
2819 PyErr_Clear();
2820
2821 PythonDictionary py_return = unwrapOrSetPythonException(
2822 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2823
2824 // if it fails, print the error but otherwise go on
2825 if (PyErr_Occurred()) {
2826 PyErr_Print();
2827 PyErr_Clear();
2828 return {};
2830 return py_return.CreateStructuredObject();
2831}
2832
2835 StructuredData::GenericSP cmd_obj_sp) {
2836 StructuredData::ObjectSP result = {};
2837
2839
2840 static char callee_name[] = "get_args_definition";
2841
2842 if (!cmd_obj_sp)
2843 return result;
2844
2845 PythonObject implementor(PyRefType::Borrowed,
2846 (PyObject *)cmd_obj_sp->GetValue());
2847
2848 if (!implementor.IsAllocated())
2849 return result;
2850
2851 PythonObject pmeth(PyRefType::Owned,
2852 PyObject_GetAttrString(implementor.get(), callee_name));
2853
2854 if (PyErr_Occurred())
2855 PyErr_Clear();
2856
2857 if (!pmeth.IsAllocated())
2858 return result;
2859
2860 if (PyCallable_Check(pmeth.get()) == 0) {
2861 if (PyErr_Occurred())
2862 PyErr_Clear();
2863 return result;
2864 }
2865
2866 if (PyErr_Occurred())
2867 PyErr_Clear();
2868
2869 PythonList py_return = unwrapOrSetPythonException(
2870 As<PythonList>(implementor.CallMethod(callee_name)));
2871
2872 // if it fails, print the error but otherwise go on
2873 if (PyErr_Occurred()) {
2874 PyErr_Print();
2875 PyErr_Clear();
2876 return {};
2877 }
2878 return py_return.CreateStructuredObject();
2879}
2880
2882 StructuredData::GenericSP cmd_obj_sp) {
2883
2885
2886 static char callee_name[] = "option_parsing_started";
2887
2888 if (!cmd_obj_sp)
2889 return;
2890
2891 PythonObject implementor(PyRefType::Borrowed,
2892 (PyObject *)cmd_obj_sp->GetValue());
2893
2894 if (!implementor.IsAllocated())
2895 return;
2896
2897 PythonObject pmeth(PyRefType::Owned,
2898 PyObject_GetAttrString(implementor.get(), callee_name));
2899
2900 if (PyErr_Occurred())
2901 PyErr_Clear();
2902
2903 if (!pmeth.IsAllocated())
2904 return;
2905
2906 if (PyCallable_Check(pmeth.get()) == 0) {
2907 if (PyErr_Occurred())
2908 PyErr_Clear();
2909 return;
2910 }
2911
2912 if (PyErr_Occurred())
2913 PyErr_Clear();
2914
2915 // option_parsing_starting doesn't return anything, ignore anything but
2916 // python errors.
2917 unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name)));
2918
2919 // if it fails, print the error but otherwise go on
2920 if (PyErr_Occurred()) {
2921 PyErr_Print();
2922 PyErr_Clear();
2923 return;
2924 }
2925}
2926
2928 StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx,
2929 llvm::StringRef long_option, llvm::StringRef value) {
2930 StructuredData::ObjectSP result = {};
2931
2933
2934 static char callee_name[] = "set_option_value";
2935
2936 if (!cmd_obj_sp)
2937 return false;
2938
2939 PythonObject implementor(PyRefType::Borrowed,
2940 (PyObject *)cmd_obj_sp->GetValue());
2941
2942 if (!implementor.IsAllocated())
2943 return false;
2944
2945 PythonObject pmeth(PyRefType::Owned,
2946 PyObject_GetAttrString(implementor.get(), callee_name));
2947
2948 if (PyErr_Occurred())
2949 PyErr_Clear();
2950
2951 if (!pmeth.IsAllocated())
2952 return false;
2953
2954 if (PyCallable_Check(pmeth.get()) == 0) {
2955 if (PyErr_Occurred())
2956 PyErr_Clear();
2957 return false;
2958 }
2959
2960 if (PyErr_Occurred())
2961 PyErr_Clear();
2962
2963 lldb::ExecutionContextRefSP exe_ctx_ref_sp;
2964 if (exe_ctx)
2965 exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx);
2966 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
2967
2968 bool py_return = unwrapOrSetPythonException(As<bool>(
2969 implementor.CallMethod(callee_name, ctx_ref_obj,
2970 long_option.str().c_str(), value.str().c_str())));
2971
2972 // if it fails, print the error but otherwise go on
2973 if (PyErr_Occurred()) {
2974 PyErr_Print();
2975 PyErr_Clear();
2976 return false;
2977 }
2978 return py_return;
2979}
2980
2982 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2983 dest.clear();
2984
2986
2987 if (!cmd_obj_sp)
2988 return false;
2989
2991 (PyObject *)cmd_obj_sp->GetValue());
2992
2993 if (!implementor.IsAllocated())
2994 return false;
2995
2996 llvm::Expected<PythonObject> expected_py_return =
2997 implementor.CallMethod("get_long_help");
2998
2999 if (!expected_py_return) {
3000 llvm::consumeError(expected_py_return.takeError());
3001 return false;
3002 }
3003
3004 PythonObject py_return = std::move(expected_py_return.get());
3005
3006 bool got_string = false;
3007 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3008 PythonString str(PyRefType::Borrowed, py_return.get());
3009 llvm::StringRef str_data(str.GetString());
3010 dest.assign(str_data.data(), str_data.size());
3011 got_string = true;
3012 }
3014 return got_string;
3015}
3016
3017std::unique_ptr<ScriptInterpreterLocker>
3019 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3022 return py_lock;
3023}
3024
3027
3028 // RAII-based initialization which correctly handles multiple-initialization,
3029 // version- specific differences among Python 2 and Python 3, and saving and
3030 // restoring various other pieces of state that can get mucked with during
3031 // initialization.
3032 InitializePythonRAII initialize_guard;
3033
3035
3036 // Update the path python uses to search for modules to include the current
3037 // directory.
3038
3039 RunSimpleString("import sys");
3041
3042 // Don't denormalize paths when calling file_spec.GetPath(). On platforms
3043 // that use a backslash as the path separator, this will result in executing
3044 // python code containing paths with unescaped backslashes. But Python also
3045 // accepts forward slashes, so to make life easier we just use that.
3046 if (FileSpec file_spec = GetPythonDir())
3047 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3048 if (FileSpec file_spec = HostInfo::GetShlibDir())
3049 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3050
3051 RunSimpleString("sys.dont_write_bytecode = 1; import "
3052 "lldb.embedded_interpreter; from "
3053 "lldb.embedded_interpreter import run_python_interpreter; "
3054 "from lldb.embedded_interpreter import run_one_line");
3055
3056#if LLDB_USE_PYTHON_SET_INTERRUPT
3057 // Python will not just overwrite its internal SIGINT handler but also the
3058 // one from the process. Backup the current SIGINT handler to prevent that
3059 // Python deletes it.
3060 RestoreSignalHandlerScope save_sigint(SIGINT);
3061
3062 // Setup a default SIGINT signal handler that works the same way as the
3063 // normal Python REPL signal handler which raises a KeyboardInterrupt.
3064 // Also make sure to not pollute the user's REPL with the signal module nor
3065 // our utility function.
3066 RunSimpleString("def lldb_setup_sigint_handler():\n"
3067 " import signal;\n"
3068 " def signal_handler(sig, frame):\n"
3069 " raise KeyboardInterrupt()\n"
3070 " signal.signal(signal.SIGINT, signal_handler);\n"
3071 "lldb_setup_sigint_handler();\n"
3072 "del lldb_setup_sigint_handler\n");
3073#endif
3074}
3075
3077 std::string path) {
3078 std::string statement;
3079 if (location == AddLocation::Beginning) {
3080 statement.assign("sys.path.insert(0,\"");
3081 statement.append(path);
3082 statement.append("\")");
3083 } else {
3084 statement.assign("sys.path.append(\"");
3085 statement.append(path);
3086 statement.append("\")");
3087 }
3088 RunSimpleString(statement.c_str());
3089}
3090
3091// We are intentionally NOT calling Py_Finalize here (this would be the logical
3092// place to call it). Calling Py_Finalize here causes test suite runs to seg
3093// fault: The test suite runs in Python. It registers SBDebugger::Terminate to
3094// be called 'at_exit'. When the test suite Python harness finishes up, it
3095// calls Py_Finalize, which calls all the 'at_exit' registered functions.
3096// SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3097// which calls ScriptInterpreter::Terminate, which calls
3098// ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we
3099// end up with Py_Finalize being called from within Py_Finalize, which results
3100// in a seg fault. Since this function only gets called when lldb is shutting
3101// down and going away anyway, the fact that we don't actually call Py_Finalize
3102// should not cause any problems (everything should shut down/go away anyway
3103// when the process exits).
3104//
3105// void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
#define LLDB_LOGV(log,...)
Definition Log.h:383
ScriptInterpreterPythonImpl::Locker Locker
#define LLDB_PLUGIN_DEFINE(PluginName)
PyObject * PyInit__lldb(void)
static std::string GenerateUniqueName(const char *base_name_wanted, uint32_t &functions_counter, const void *name_token=nullptr)
#define LLDBSwigPyInit
static ScriptInterpreterPythonImpl * GetPythonInterpreter(Debugger &debugger)
static const char python_exe_relative_path[]
uint64_t replace_all(std::string &str, const std::string &oldStr, const std::string &newStr)
static const char GetInterpreterInfoScript[]
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
A command line argument class.
Definition Args.h:33
bool GetQuotedCommandString(std::string &command) const
Definition Args.cpp:232
"lldb/Breakpoint/BreakpointOptions.h" Class that manages the options on a breakpoint or breakpoint lo...
void SetCallback(BreakpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the breakpoint option set.
void void AppendError(llvm::StringRef in_string)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void AppendErrorWithFormatv(const char *format, Args &&...args)
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:87
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
ExecuteScriptOptions & SetMaskoutErrors(bool maskout)
ExecuteScriptOptions & SetSetLLDBGlobals(bool set)
ExecuteScriptOptions & SetEnableIO(bool enable)
Execution context objects refer to objects in the execution of the program that is being debugged.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
A file utility class.
Definition FileSpec.h:57
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition FileSpec.cpp:342
bool RemoveLastPathComponent()
Removes the last path component by replacing the current path with its parent.
Definition FileSpec.cpp:465
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
llvm::StringRef GetFileNameExtension() const
Extract the extension of the file.
Definition FileSpec.cpp:410
Status ResolveSymbolicLink(const FileSpec &src, FileSpec &dst)
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
bool IsValid() const override
IsValid.
Definition File.cpp:113
virtual Status Flush()
Flush the current stream.
Definition File.cpp:156
lldb::LockableStreamFileSP GetErrorStreamFileSP()
Definition IOHandler.cpp:95
lldb::LockableStreamFileSP GetOutputStreamFileSP()
Definition IOHandler.cpp:93
void SetIsDone(bool b)
Definition IOHandler.h:81
void PutCString(const char *cstr)
Definition Log.cpp:145
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:354
void Flush()
Flush our output and error file handles.
static llvm::Expected< std::unique_ptr< ScriptInterpreterIORedirect > > Create(bool enable_io, Debugger &debugger, CommandReturnObject *result)
Create an IO redirect.
bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
Locker(ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry=AcquireLock|InitSession, uint16_t on_leave=FreeLock|TearDownSession, lldb::FileSP in=nullptr, lldb::FileSP out=nullptr, lldb::FileSP err=nullptr)
SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity)
bool GenerateTypeScriptFunction(StringList &input, std::string &output, const void *name_token=nullptr) override
Status GenerateFunction(const char *signature, const StringList &input, bool is_callback) override
bool GenerateScriptAliasFunction(StringList &input, std::string &output) override
lldb_private::Status ExecuteMultipleLines(const char *in_string, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool ShouldHide(const StructuredData::ObjectSP &implementor, lldb::StackFrameSP frame_sp) override
bool GenerateWatchpointCommandCallbackData(StringList &input, std::string &output, bool is_callback) override
StructuredData::DictionarySP HandleOptionArgumentCompletionForScriptedCommand(StructuredData::GenericSP impl_obj_sp, llvm::StringRef &long_options, size_t char_in_arg) override
bool RunScriptBasedParsedCommand(StructuredData::GenericSP impl_obj_sp, Args &args, ScriptedCommandSynchronicity synchronicity, lldb_private::CommandReturnObject &cmd_retobj, Status &error, const lldb_private::ExecutionContext &exe_ctx) override
void OptionParsingStartedForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string &dest) override
lldb::ScriptedStopHookInterfaceSP CreateScriptedStopHookInterface() override
Status SetBreakpointCommandCallbackFunction(BreakpointOptions &bp_options, const char *function_name, StructuredData::ObjectSP extra_args_sp) override
Set a script function as the callback for the breakpoint.
lldb::ScriptedThreadInterfaceSP CreateScriptedThreadInterface() override
static bool BreakpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, lldb_private::Status &error) override
void CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, CommandReturnObject &result) override
StructuredData::DictionarySP HandleArgumentCompletionForScriptedCommand(StructuredData::GenericSP impl_obj_sp, std::vector< llvm::StringRef > &args, size_t args_pos, size_t char_in_arg) override
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
lldb::ScriptedFrameProviderInterfaceSP CreateScriptedFrameProviderInterface() override
std::optional< std::string > GetRepeatCommandForScriptedCommand(StructuredData::GenericSP impl_obj_sp, Args &args) override
Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, const char *callback_body, bool is_callback) override
Set the callback body text into the callback for the breakpoint.
StructuredData::ObjectSP GetArgumentsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, lldb::FileSP err)
void SetWatchpointCommandCallback(WatchpointOptions *wp_options, const char *user_input, bool is_callback) override
Set a one-liner as the callback for the watchpoint.
lldb::ValueObjectSP GetSyntheticValue(const StructuredData::ObjectSP &implementor) override
std::unique_ptr< ScriptInterpreterLocker > AcquireInterpreterLock() override
void CollectDataForBreakpointCommandCallback(std::vector< std::reference_wrapper< BreakpointOptions > > &bp_options_vec, CommandReturnObject &result) override
bool UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
static void AddToSysPath(AddLocation location, std::string path)
bool MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor) override
bool LoadScriptingModule(const char *filename, const LoadScriptOptions &options, lldb_private::Status &error, StructuredData::ObjectSP *module_sp=nullptr, FileSpec extra_search_dir={}, lldb::TargetSP loaded_into_target_sp={}) override
StructuredData::GenericSP CreateFrameRecognizer(const char *class_name) override
ConstString GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override
Status GenerateBreakpointCommandCallbackData(StringList &input, std::string &output, bool has_extra_args, bool is_callback) override
lldb::OperatingSystemInterfaceSP CreateOperatingSystemInterface() override
bool SetOptionValueForCommandObject(StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx, llvm::StringRef long_option, llvm::StringRef value) override
llvm::Expected< uint32_t > GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, const char *child_name) override
bool FormatterCallbackFunction(const char *function_name, lldb::TypeImplSP type_impl_sp) override
Status ExportFunctionDefinitionToInterpreter(StringList &function_def) override
StructuredData::ObjectSP CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj) override
bool ExecuteOneLine(llvm::StringRef command, CommandReturnObject *result, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
bool GetDocumentationForItem(const char *item, std::string &dest) override
In Python, a special attribute doc contains the docstring for an object (function,...
uint32_t GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
void IOHandlerInputComplete(IOHandler &io_handler, std::string &data) override
Called when a line or lines have been retrieved.
void IOHandlerActivated(IOHandler &io_handler, bool interactive) override
bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp, const TypeSummaryOptions &options, std::string &retval) override
lldb::ScriptedFrameInterfaceSP CreateScriptedFrameInterface() override
lldb::ScriptedProcessInterfaceUP CreateScriptedProcessInterface() override
StructuredData::GenericSP CreateScriptCommandObject(const char *class_name) override
size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, uint32_t max) override
bool ExecuteOneLineWithReturn(llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type, void *ret_value, const ExecuteScriptOptions &options=ExecuteScriptOptions()) override
lldb::ScriptedBreakpointInterfaceSP CreateScriptedBreakpointInterface() override
bool RunScriptFormatKeyword(const char *impl_function, Process *process, std::string &output, Status &error) override
bool SetStdHandle(lldb::FileSP file, const char *py_name, python::PythonObject &save_file, const char *mode)
lldb::ValueObjectSP GetChildAtIndex(const StructuredData::ObjectSP &implementor, uint32_t idx) override
bool GenerateTypeSynthClass(StringList &input, std::string &output, const void *name_token=nullptr) override
StructuredData::ObjectSP CreateStructuredDataFromScriptObject(ScriptObject obj) override
StructuredData::ObjectSP GetOptionsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override
StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, lldb_private::Status &error) override
bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string &dest) override
llvm::Expected< unsigned > GetMaxPositionalArgumentsForCallable(const llvm::StringRef &callable_name) override
static bool WatchpointCallbackFunction(void *baton, StoppointCallbackContext *context, lldb::user_id_t watch_id)
static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger)
lldb::ValueObjectListSP GetRecognizedArguments(const StructuredData::ObjectSP &implementor, lldb::StackFrameSP frame_sp) override
lldb::ScriptedThreadPlanInterfaceSP CreateScriptedThreadPlanInterface() override
Abstract interface for the Python script interpreter.
static void ComputePythonDir(llvm::SmallVectorImpl< char > &path)
static void ComputePythonDirForApple(llvm::SmallVectorImpl< char > &path)
StructuredData::DictionarySP GetInterpreterInfo() override
static void SharedLibraryDirectoryHelper(FileSpec &this_file)
const void * GetPointer() const
This base class provides an interface to stack frames.
Definition StackFrame.h:44
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
void Flush() override
Flush the stream.
const char * GetData() const
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
std::string CopyList(const char *item_preamble=nullptr, const char *items_sep="\n") const
size_t SplitIntoLines(const std::string &lines)
void AppendString(const std::string &s)
const char * GetStringAtIndex(size_t idx) const
std::shared_ptr< Generic > GenericSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:422
Debugger & GetDebugger() const
Definition Target.h:1223
WatchpointList & GetWatchpointList()
Definition Target.h:927
lldb::ValueObjectSP GetSP()
lldb::WatchpointSP FindByID(lldb::watch_id_t watchID) const
Returns a shared pointer to the watchpoint with id watchID, const version.
"lldb/Breakpoint/WatchpointOptions.h" Class that manages the options on a watchpoint.
void SetCallback(WatchpointHitCallback callback, const lldb::BatonSP &baton_sp, bool synchronous=false)
Adds a callback to the watchpoint option set.
StructuredData::DictionarySP CreateStructuredDictionary() const
PythonObject GetItemForKey(const PythonObject &key) const
void SetItemForKey(const PythonObject &key, const PythonObject &value)
static llvm::Expected< PythonFile > FromFile(File &file, const char *mode=nullptr)
static llvm::Expected< PythonModule > Import(const llvm::Twine &name)
PythonObject ResolveName(llvm::StringRef name) const
StructuredData::ObjectSP CreateStructuredObject() const
static PythonObject ResolveNameWithDictionary(llvm::StringRef name, const PythonDictionary &dict)
llvm::Expected< PythonObject > GetAttribute(const llvm::Twine &name) const
llvm::Expected< PythonObject > CallMethod(const char *name, const T &... t) const
static bool Check(PyObject *py_obj)
static PyObject * LLDBSwigPython_GetRecognizedArguments(PyObject *implementor, const lldb::StackFrameSP &frame_sp)
static bool LLDBSWIGPythonRunScriptKeywordValue(const char *python_function_name, const char *session_dictionary_name, const lldb::ValueObjectSP &value, std::string &output)
static bool LLDBSwigPythonCallParsedCommandObject(PyObject *implementor, lldb::DebuggerSP debugger, StructuredDataImpl &args_impl, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static bool LLDBSwigPythonCallTypeScript(const char *python_function_name, const void *session_dictionary, const lldb::ValueObjectSP &valobj_sp, void **pyfunct_wrapper, const lldb::TypeSummaryOptionsSP &options_sp, std::string &retval)
static void * LLDBSWIGPython_GetDynamicSetting(void *module, const char *setting, const lldb::TargetSP &target_sp)
static lldb::ValueObjectSP LLDBSWIGPython_GetValueObjectSPFromSBValue(void *data)
static std::optional< std::string > LLDBSWIGPythonRunScriptKeywordThread(const char *python_function_name, const char *session_dictionary_name, lldb::ThreadSP thread)
static StructuredData::DictionarySP LLDBSwigPythonHandleArgumentCompletionForScriptedCommand(PyObject *implementor, std::vector< llvm::StringRef > &args_impl, size_t args_pos, size_t pos_in_arg)
static 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)
static PyObject * LLDBSwigPython_GetValueSynthProviderInstance(PyObject *implementor)
static bool LLDBSwigPython_UpdateSynthProviderInstance(PyObject *implementor)
static StructuredData::DictionarySP LLDBSwigPythonHandleOptionArgumentCompletionForScriptedCommand(PyObject *implementor, llvm::StringRef &long_option, size_t pos_in_arg)
static bool LLDBSWIGPythonRunScriptKeywordTarget(const char *python_function_name, const char *session_dictionary_name, const lldb::TargetSP &target, std::string &output)
static uint32_t LLDBSwigPython_GetIndexOfChildWithName(PyObject *implementor, const char *child_name)
static std::optional< std::string > LLDBSwigPythonGetRepeatCommandForScriptedCommand(PyObject *implementor, std::string &command)
static std::optional< std::string > LLDBSWIGPythonRunScriptKeywordFrame(const char *python_function_name, const char *session_dictionary_name, lldb::StackFrameSP frame)
static PyObject * LLDBSwigPython_GetChildAtIndex(PyObject *implementor, uint32_t idx)
static bool LLDBSWIGPythonRunScriptKeywordProcess(const char *python_function_name, const char *session_dictionary_name, const lldb::ProcessSP &process, std::string &output)
static bool LLDBSwigPythonFormatterCallbackFunction(const char *python_function_name, const char *session_dictionary_name, lldb::TypeImplSP type_impl_sp)
static bool LLDBSwigPythonCallModuleInit(const char *python_module_name, const char *session_dictionary_name, lldb::DebuggerSP debugger)
static python::PythonObject LLDBSwigPythonCreateSyntheticProvider(const char *python_class_name, const char *session_dictionary_name, const lldb::ValueObjectSP &valobj_sp)
static bool LLDBSwigPythonWatchpointCallbackFunction(const char *python_function_name, const char *session_dictionary_name, const lldb::StackFrameSP &sb_frame, const lldb::WatchpointSP &sb_wp)
static python::PythonObject LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name, const char *session_dictionary_name)
static size_t LLDBSwigPython_CalculateNumChildren(PyObject *implementor, uint32_t max)
static PythonObject ToSWIGWrapper(std::unique_ptr< lldb::SBValue > value_sb)
static bool LLDBSwigPythonCallCommandObject(PyObject *implementor, lldb::DebuggerSP debugger, const char *args, lldb_private::CommandReturnObject &cmd_retobj, lldb::ExecutionContextRefSP exe_ctx_ref_sp)
static bool LLDBSwigPython_MightHaveChildrenSynthProviderInstance(PyObject *implementor)
static bool LLDBSwigPythonCallModuleNewTarget(const char *python_module_name, const char *session_dictionary_name, lldb::TargetSP target)
static python::PythonObject LLDBSwigPythonCreateCommandObject(const char *python_class_name, const char *session_dictionary_name, lldb::DebuggerSP debugger_sp)
static bool LLDBSwigPython_ShouldHide(PyObject *implementor, const lldb::StackFrameSP &frame_sp)
static llvm::Expected< bool > LLDBSwigPythonBreakpointCallbackFunction(const char *python_function_name, const char *session_dictionary_name, const lldb::StackFrameSP &sb_frame, const lldb::BreakpointLocationSP &sb_bp_loc, const lldb_private::StructuredDataImpl &args_impl)
#define UINT32_MAX
llvm::Expected< T > As(llvm::Expected< PythonObject > &&obj)
T unwrapOrSetPythonException(llvm::Expected< T > expected)
T unwrapIgnoringErrors(llvm::Expected< T > expected)
llvm::Expected< PythonObject > runStringMultiLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
int RunSimpleString(const char *str)
llvm::Expected< long long > As< long long >(llvm::Expected< PythonObject > &&obj)
void * LLDBSWIGPython_CastPyObjectToSBValue(PyObject *data)
llvm::Expected< bool > As< bool >(llvm::Expected< PythonObject > &&obj)
llvm::Expected< PythonObject > runStringOneLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
@ eScriptLanguagePython
std::shared_ptr< lldb_private::ScriptedStopHookInterface > ScriptedStopHookInterfaceSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
std::shared_ptr< lldb_private::IOHandler > IOHandlerSP
std::shared_ptr< lldb_private::ScriptInterpreter > ScriptInterpreterSP
std::shared_ptr< lldb_private::ScriptedThreadPlanInterface > ScriptedThreadPlanInterfaceSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::TypeSummaryOptions > TypeSummaryOptionsSP
std::shared_ptr< lldb_private::OperatingSystemInterface > OperatingSystemInterfaceSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::ScriptedBreakpointInterface > ScriptedBreakpointInterfaceSP
std::shared_ptr< lldb_private::ScriptedThreadInterface > ScriptedThreadInterfaceSP
std::shared_ptr< lldb_private::ValueObjectList > ValueObjectListSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
@ eReturnStatusFailed
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::ScriptedFrameProviderInterface > ScriptedFrameProviderInterfaceSP
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::LockableStreamFile > LockableStreamFileSP
std::shared_ptr< lldb_private::TypeImpl > TypeImplSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::File > FileSP
std::unique_ptr< lldb_private::ScriptedProcessInterface > ScriptedProcessInterfaceUP
std::shared_ptr< lldb_private::ScriptedFrameInterface > ScriptedFrameInterfaceSP
std::shared_ptr< lldb_private::ExecutionContextRef > ExecutionContextRefSP
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47