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