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 LLDB_LOG_ERROR(GetLog(LLDBLog::Script), new_file.takeError(),
594 "ScriptInterpreterPythonImpl::SetStdHandle failed to wrap "
595 "sys.{1}: {0}",
596 py_name);
597 return false;
598 }
599
600 save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
602 sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
603 return true;
604}
605
606bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
607 FileSP in_sp, FileSP out_sp,
608 FileSP err_sp) {
609 // If we have already entered the session, without having officially 'left'
610 // it, then there is no need to 'enter' it again.
611 Log *log = GetLog(LLDBLog::Script);
613 LLDB_LOGF(
614 log,
615 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
616 ") session is already active, returning without doing anything",
617 on_entry_flags);
618 return false;
619 }
620
621 LLDB_LOGF(
622 log,
623 "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
624 on_entry_flags);
625
626 m_session_is_active = true;
627
628 StreamString run_string;
629
630 if (on_entry_flags & Locker::InitGlobals) {
631 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
633 run_string.Printf(
634 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
635 m_debugger.GetID());
636 run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
637 run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
638 run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
639 run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
640 run_string.PutCString("')");
641 } else {
642 // If we aren't initing the globals, we should still always set the
643 // debugger (since that is always unique.)
644 run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
645 m_dictionary_name.c_str(), m_debugger.GetID());
646 run_string.Printf(
647 "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
648 m_debugger.GetID());
649 run_string.PutCString("')");
650 }
651
652 RunSimpleString(run_string.GetData());
653 run_string.Clear();
654
655 PythonDictionary &sys_module_dict = GetSysModuleDictionary();
656 if (sys_module_dict.IsValid()) {
657 lldb::FileSP top_in_sp;
658 lldb::LockableStreamFileSP top_out_sp, top_err_sp;
659 if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
660 m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
661 top_err_sp);
662
663 if (on_entry_flags & Locker::NoSTDIN) {
664 m_saved_stdin.Reset();
665 } else {
666 if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
667 if (top_in_sp)
668 SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
669 }
670 }
671
672 if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
673 if (top_out_sp)
674 SetStdHandle(top_out_sp->GetUnlockedFileSP(), "stdout", m_saved_stdout,
675 "w");
676 }
677
678 if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
679 if (top_err_sp)
680 SetStdHandle(top_err_sp->GetUnlockedFileSP(), "stderr", m_saved_stderr,
681 "w");
682 }
683 }
684
685 if (PyErr_Occurred())
686 PyErr_Clear();
687
688 return true;
689}
690
692 if (!m_main_module.IsValid())
694 return m_main_module;
695}
696
699 return m_session_dict;
700
701 PythonObject &main_module = GetMainModule();
702 if (!main_module.IsValid())
703 return m_session_dict;
704
706 PyModule_GetDict(main_module.get()));
707 if (!main_dict.IsValid())
708 return m_session_dict;
709
717 return m_sys_module_dict;
720 return m_sys_module_dict;
721}
722
723llvm::Expected<unsigned>
725 const llvm::StringRef &callable_name) {
726 if (callable_name.empty()) {
727 return llvm::createStringError(llvm::inconvertibleErrorCode(),
728 "called with empty callable name.");
729 }
730 Locker py_lock(this,
735 callable_name, dict);
736 if (!pfunc.IsAllocated()) {
737 return llvm::createStringError(llvm::inconvertibleErrorCode(),
738 "can't find callable: %s",
739 callable_name.str().c_str());
740 }
741 llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
742 if (!arg_info)
743 return arg_info.takeError();
744 return arg_info.get().max_positional_args;
745}
746
747static std::string GenerateUniqueName(const char *base_name_wanted,
748 uint32_t &functions_counter,
749 const void *name_token = nullptr) {
750 StreamString sstr;
751
752 if (!base_name_wanted)
753 return std::string();
754
755 if (!name_token)
756 sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
757 else
758 sstr.Printf("%s_%p", base_name_wanted, name_token);
759
760 return std::string(sstr.GetString());
761}
762
765 return true;
766
768 PyImport_AddModule("lldb.embedded_interpreter"));
769 if (!module.IsValid())
770 return false;
771
773 PyModule_GetDict(module.get()));
774 if (!module_dict.IsValid())
775 return false;
776
778 module_dict.GetItemForKey(PythonString("run_one_line"));
780 module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
781 return m_run_one_line_function.IsValid();
782}
783
785 llvm::StringRef command, CommandReturnObject *result,
786 const ExecuteScriptOptions &options) {
787 std::string command_str = command.str();
788
789 if (!m_valid_session)
790 return false;
791
792 if (!command.empty()) {
793 // We want to call run_one_line, passing in the dictionary and the command
794 // string. We cannot do this through RunSimpleString here because the
795 // command string may contain escaped characters, and putting it inside
796 // another string to pass to RunSimpleString messes up the escaping. So
797 // we use the following more complicated method to pass the command string
798 // directly down to Python.
799 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
800 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
801 options.GetEnableIO(), m_debugger, result);
802 if (!io_redirect_or_error) {
803 if (result)
805 "failed to redirect I/O: {0}\n",
806 llvm::fmt_consume(io_redirect_or_error.takeError()));
807 else
808 llvm::consumeError(io_redirect_or_error.takeError());
809 return false;
810 }
811
812 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
813
814 bool success = false;
815 {
816 // WARNING! It's imperative that this RAII scope be as tight as
817 // possible. In particular, the scope must end *before* we try to join
818 // the read thread. The reason for this is that a pre-requisite for
819 // joining the read thread is that we close the write handle (to break
820 // the pipe and cause it to wake up and exit). But acquiring the GIL as
821 // below will redirect Python's stdio to use this same handle. If we
822 // close the handle while Python is still using it, bad things will
823 // happen.
824 Locker locker(
825 this,
827 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
828 ((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
830 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
831 io_redirect.GetErrorFile());
832
833 // Find the correct script interpreter dictionary in the main module.
834 PythonDictionary &session_dict = GetSessionDictionary();
835 if (session_dict.IsValid()) {
837 if (PyCallable_Check(m_run_one_line_function.get())) {
838 PythonObject pargs(
840 Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
841 if (pargs.IsValid()) {
842 PythonObject return_value(
844 PyObject_CallObject(m_run_one_line_function.get(),
845 pargs.get()));
846 if (return_value.IsValid())
847 success = true;
848 else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
849 PyErr_Print();
850 PyErr_Clear();
851 }
852 }
853 }
854 }
855 }
856
857 io_redirect.Flush();
858 }
859
860 if (success)
861 return true;
862
863 // The one-liner failed. Append the error message.
864 if (result) {
865 result->AppendErrorWithFormat("python failed attempting to evaluate '%s'",
866 command_str.c_str());
867 }
868 return false;
869 }
870
871 if (result)
872 result->AppendError("empty command passed to python\n");
873 return false;
874}
875
878
879 Debugger &debugger = m_debugger;
880
881 // At the moment, the only time the debugger does not have an input file
882 // handle is when this is called directly from Python, in which case it is
883 // both dangerous and unnecessary (not to mention confusing) to try to embed
884 // a running interpreter loop inside the already running Python interpreter
885 // loop, so we won't do it.
886
887 if (!debugger.GetInputFile().IsValid())
888 return;
889
890 IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
891 if (io_handler_sp) {
892 debugger.RunIOHandlerAsync(io_handler_sp);
893 }
894}
895
897#if LLDB_USE_PYTHON_SET_INTERRUPT
898 // If the interpreter isn't evaluating any Python at the moment then return
899 // false to signal that this function didn't handle the interrupt and the
900 // next component should try handling it.
901 if (!IsExecutingPython())
902 return false;
903
904 // Tell Python that it should pretend to have received a SIGINT.
905 PyErr_SetInterrupt();
906 // PyErr_SetInterrupt has no way to return an error so we can only pretend the
907 // signal got successfully handled and return true.
908 // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
909 // the error handling is limited to checking the arguments which would be
910 // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
911 return true;
912#else
913 Log *log = GetLog(LLDBLog::Script);
914
915 if (IsExecutingPython()) {
916 PyThreadState *state = PyThreadState_Get();
917 if (!state)
918 state = GetThreadState();
919 if (state) {
920 long tid = PyThread_get_thread_ident();
921 PyThreadState_Swap(state);
922 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
923 LLDB_LOGF(log,
924 "ScriptInterpreterPythonImpl::Interrupt() sending "
925 "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
926 tid, num_threads);
927 return true;
928 }
929 }
930 LLDB_LOGF(log,
931 "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
932 "can't interrupt");
933 return false;
934#endif
935}
936
938 llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
939 void *ret_value, const ExecuteScriptOptions &options) {
940
941 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
942 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
943 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
944
945 if (!io_redirect_or_error) {
946 llvm::consumeError(io_redirect_or_error.takeError());
947 return false;
948 }
949
950 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
951
952 Locker locker(this,
954 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
957 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
958 io_redirect.GetErrorFile());
959
960 PythonModule &main_module = GetMainModule();
961 PythonDictionary globals = main_module.GetDictionary();
962
964 if (!locals.IsValid())
965 locals = unwrapIgnoringErrors(
967 if (!locals.IsValid())
968 locals = globals;
969
970 Expected<PythonObject> maybe_py_return =
971 runStringOneLine(in_string, globals, locals);
972
973 if (!maybe_py_return) {
974 llvm::handleAllErrors(
975 maybe_py_return.takeError(),
976 [&](PythonException &E) {
977 E.Restore();
978 if (options.GetMaskoutErrors()) {
979 if (E.Matches(PyExc_SyntaxError)) {
980 PyErr_Print();
981 }
982 PyErr_Clear();
983 }
984 },
985 [](const llvm::ErrorInfoBase &E) {});
986 return false;
987 }
988
989 PythonObject py_return = std::move(maybe_py_return.get());
990 assert(py_return.IsValid());
991
992 switch (return_type) {
993 case eScriptReturnTypeCharPtr: // "char *"
994 {
995 const char format[3] = "s#";
996 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
997 }
998 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
999 // Py_None
1000 {
1001 const char format[3] = "z";
1002 return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1003 }
1004 case eScriptReturnTypeBool: {
1005 const char format[2] = "b";
1006 return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1007 }
1008 case eScriptReturnTypeShortInt: {
1009 const char format[2] = "h";
1010 return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1011 }
1012 case eScriptReturnTypeShortIntUnsigned: {
1013 const char format[2] = "H";
1014 return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1015 }
1016 case eScriptReturnTypeInt: {
1017 const char format[2] = "i";
1018 return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1019 }
1020 case eScriptReturnTypeIntUnsigned: {
1021 const char format[2] = "I";
1022 return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1023 }
1024 case eScriptReturnTypeLongInt: {
1025 const char format[2] = "l";
1026 return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1027 }
1028 case eScriptReturnTypeLongIntUnsigned: {
1029 const char format[2] = "k";
1030 return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1031 }
1032 case eScriptReturnTypeLongLong: {
1033 const char format[2] = "L";
1034 return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1035 }
1036 case eScriptReturnTypeLongLongUnsigned: {
1037 const char format[2] = "K";
1038 return PyArg_Parse(py_return.get(), format,
1039 (unsigned long long *)ret_value);
1040 }
1041 case eScriptReturnTypeFloat: {
1042 const char format[2] = "f";
1043 return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1044 }
1045 case eScriptReturnTypeDouble: {
1046 const char format[2] = "d";
1047 return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1048 }
1049 case eScriptReturnTypeChar: {
1050 const char format[2] = "c";
1051 return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1052 }
1053 case eScriptReturnTypeOpaqueObject: {
1054 *((PyObject **)ret_value) = py_return.release();
1055 return true;
1057 }
1058 llvm_unreachable("Fully covered switch!");
1059}
1060
1062 const char *in_string, const ExecuteScriptOptions &options) {
1063
1064 if (in_string == nullptr)
1065 return Status();
1066
1067 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1068 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1069 options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1070
1071 if (!io_redirect_or_error)
1072 return Status::FromError(io_redirect_or_error.takeError());
1073
1074 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1075
1076 Locker locker(this,
1078 (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
1081 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1082 io_redirect.GetErrorFile());
1083
1084 PythonModule &main_module = GetMainModule();
1085 PythonDictionary globals = main_module.GetDictionary();
1086
1087 PythonDictionary locals = GetSessionDictionary();
1088 if (!locals.IsValid())
1089 locals = unwrapIgnoringErrors(
1091 if (!locals.IsValid())
1092 locals = globals;
1093
1094 Expected<PythonObject> return_value =
1095 runStringMultiLine(in_string, globals, locals);
1096
1097 if (!return_value) {
1098 llvm::Error error =
1099 llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1100 llvm::Error error = llvm::createStringError(
1101 llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1102 if (!options.GetMaskoutErrors())
1103 E.Restore();
1104 return error;
1105 });
1106 return Status::FromError(std::move(error));
1108
1109 return Status();
1110}
1111
1113 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1114 CommandReturnObject &result) {
1116 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1117 " ", *this, &bp_options_vec);
1118}
1119
1121 WatchpointOptions *wp_options, CommandReturnObject &result) {
1123 m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1124 " ", *this, wp_options);
1125}
1126
1128 BreakpointOptions &bp_options, const char *function_name,
1129 StructuredData::ObjectSP extra_args_sp) {
1130 Status error;
1131 // For now just cons up a oneliner that calls the provided function.
1132 std::string function_signature = function_name;
1133
1134 llvm::Expected<unsigned> maybe_args =
1136 if (!maybe_args) {
1138 "could not get num args: %s",
1139 llvm::toString(maybe_args.takeError()).c_str());
1140 return error;
1141 }
1142 size_t max_args = *maybe_args;
1143
1144 bool uses_extra_args = false;
1145 if (max_args >= 4) {
1146 uses_extra_args = true;
1147 function_signature += "(frame, bp_loc, extra_args, internal_dict)";
1148 } else if (max_args >= 3) {
1149 if (extra_args_sp) {
1151 "cannot pass extra_args to a three argument callback");
1152 return error;
1153 }
1154 uses_extra_args = false;
1155 function_signature += "(frame, bp_loc, internal_dict)";
1156 } else {
1157 error = Status::FromErrorStringWithFormat("expected 3 or 4 argument "
1158 "function, %s can only take %zu",
1159 function_name, max_args);
1160 return error;
1161 }
1162
1163 SetBreakpointCommandCallback(bp_options, function_signature.c_str(),
1164 extra_args_sp, uses_extra_args,
1165 /*is_callback=*/true);
1166 return error;
1167}
1168
1170 BreakpointOptions &bp_options,
1171 std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1172 Status error;
1173 error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1174 cmd_data_up->script_source,
1175 /*has_extra_args=*/false,
1176 /*is_callback=*/false);
1177 if (error.Fail()) {
1178 return error;
1179 }
1180 auto baton_sp =
1181 std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1188 BreakpointOptions &bp_options, const char *command_body_text,
1189 bool is_callback) {
1190 return SetBreakpointCommandCallback(bp_options, command_body_text, {},
1191 /*uses_extra_args=*/false, is_callback);
1192}
1193
1194// Set a Python one-liner as the callback for the breakpoint.
1196 BreakpointOptions &bp_options, const char *command_body_text,
1197 StructuredData::ObjectSP extra_args_sp, bool uses_extra_args,
1198 bool is_callback) {
1199 auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1200 // Split the command_body_text into lines, and pass that to
1201 // GenerateBreakpointCommandCallbackData. That will wrap the body in an
1202 // auto-generated function, and return the function name in script_source.
1203 // That is what the callback will actually invoke.
1204
1205 data_up->user_source.SplitIntoLines(command_body_text);
1207 data_up->user_source, data_up->script_source, uses_extra_args,
1208 is_callback);
1209 if (error.Success()) {
1210 auto baton_sp =
1211 std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1212 bp_options.SetCallback(
1214 return error;
1216 return error;
1217}
1218
1219// Set a Python one-liner as the callback for the watchpoint.
1221 WatchpointOptions *wp_options, const char *user_input, bool is_callback) {
1222 auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1223
1224 // It's necessary to set both user_source and script_source to the oneliner.
1225 // The former is used to generate callback description (as in watchpoint
1226 // command list) while the latter is used for Python to interpret during the
1227 // actual callback.
1228
1229 data_up->user_source.AppendString(user_input);
1230 data_up->script_source.assign(user_input);
1231
1233 data_up->user_source, data_up->script_source, is_callback)) {
1234 auto baton_sp =
1235 std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1236 wp_options->SetCallback(
1238 }
1239}
1240
1242 StringList &function_def) {
1243 // Convert StringList to one long, newline delimited, const char *.
1244 std::string function_def_string(function_def.CopyList());
1245 LLDB_LOG(GetLog(LLDBLog::Script), "Added Function:\n{0}\n",
1246 function_def_string.c_str());
1247
1249 function_def_string.c_str(), ExecuteScriptOptions().SetEnableIO(false));
1250 return error;
1251}
1252
1254 const StringList &input,
1255 bool is_callback) {
1256 Status error;
1257 int num_lines = input.GetSize();
1258 if (num_lines == 0) {
1259 error = Status::FromErrorString("No input data.");
1260 return error;
1261 }
1262
1263 if (!signature || *signature == 0) {
1264 error = Status::FromErrorString("No output function name.");
1265 return error;
1266 }
1267
1268 StreamString sstr;
1269 StringList auto_generated_function;
1270 auto_generated_function.AppendString(signature);
1271 auto_generated_function.AppendString(
1272 " global_dict = globals()"); // Grab the global dictionary
1273 auto_generated_function.AppendString(
1274 " new_keys = internal_dict.keys()"); // Make a list of keys in the
1275 // session dict
1276 auto_generated_function.AppendString(
1277 " old_keys = global_dict.keys()"); // Save list of keys in global dict
1278 auto_generated_function.AppendString(
1279 " global_dict.update(internal_dict)"); // Add the session dictionary
1280 // to the global dictionary.
1281
1282 if (is_callback) {
1283 // If the user input is a callback to a python function, make sure the input
1284 // is only 1 line, otherwise appending the user input would break the
1285 // generated wrapped function
1286 if (num_lines == 1) {
1287 sstr.Clear();
1288 sstr.Printf(" __return_val = %s", input.GetStringAtIndex(0));
1289 auto_generated_function.AppendString(sstr.GetData());
1290 } else {
1292 "ScriptInterpreterPythonImpl::GenerateFunction(is_callback="
1293 "true) = ERROR: python function is multiline.");
1294 }
1295 } else {
1296 auto_generated_function.AppendString(
1297 " __return_val = None"); // Initialize user callback return value.
1298 auto_generated_function.AppendString(
1299 " def __user_code():"); // Create a nested function that will wrap
1300 // the user input. This is necessary to
1301 // capture the return value of the user input
1302 // and prevent early returns.
1303 for (int i = 0; i < num_lines; ++i) {
1304 sstr.Clear();
1305 sstr.Printf(" %s", input.GetStringAtIndex(i));
1306 auto_generated_function.AppendString(sstr.GetData());
1307 }
1308 auto_generated_function.AppendString(
1309 " __return_val = __user_code()"); // Call user code and capture
1310 // return value
1311 }
1312 auto_generated_function.AppendString(
1313 " for key in new_keys:"); // Iterate over all the keys from session
1314 // dict
1315 auto_generated_function.AppendString(
1316 " if key in old_keys:"); // If key was originally in
1317 // global dict
1318 auto_generated_function.AppendString(
1319 " internal_dict[key] = global_dict[key]"); // Update it
1320 auto_generated_function.AppendString(
1321 " elif key in global_dict:"); // Then if it is still in the
1322 // global dict
1323 auto_generated_function.AppendString(
1324 " del global_dict[key]"); // remove key/value from the
1325 // global dict
1326 auto_generated_function.AppendString(
1327 " return __return_val"); // Return the user callback return value.
1328
1329 // Verify that the results are valid Python.
1331
1332 return error;
1333}
1334
1336 StringList &user_input, std::string &output, const void *name_token) {
1337 static uint32_t num_created_functions = 0;
1338 user_input.RemoveBlankLines();
1339 StreamString sstr;
1340
1341 // Check to see if we have any data; if not, just return.
1342 if (user_input.GetSize() == 0)
1343 return false;
1344
1345 // Take what the user wrote, wrap it all up inside one big auto-generated
1346 // Python function, passing in the ValueObject as parameter to the function.
1347
1348 std::string auto_generated_function_name(
1349 GenerateUniqueName("lldb_autogen_python_type_print_func",
1350 num_created_functions, name_token));
1351 sstr.Printf("def %s (valobj, internal_dict):",
1352 auto_generated_function_name.c_str());
1353
1354 if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1355 .Success())
1356 return false;
1357
1358 // Store the name of the auto-generated function to be called.
1359 output.assign(auto_generated_function_name);
1360 return true;
1361}
1362
1364 StringList &user_input, std::string &output) {
1365 static uint32_t num_created_functions = 0;
1366 user_input.RemoveBlankLines();
1367 StreamString sstr;
1368
1369 // Check to see if we have any data; if not, just return.
1370 if (user_input.GetSize() == 0)
1371 return false;
1372
1373 std::string auto_generated_function_name(GenerateUniqueName(
1374 "lldb_autogen_python_cmd_alias_func", num_created_functions));
1375
1376 sstr.Printf("def %s (debugger, args, exe_ctx, result, internal_dict):",
1377 auto_generated_function_name.c_str());
1378
1379 if (!GenerateFunction(sstr.GetData(), user_input, /*is_callback=*/false)
1380 .Success())
1381 return false;
1382
1383 // Store the name of the auto-generated function to be called.
1384 output.assign(auto_generated_function_name);
1385 return true;
1386}
1387
1389 StringList &user_input, std::string &output, const void *name_token) {
1390 static uint32_t num_created_classes = 0;
1391 user_input.RemoveBlankLines();
1392 int num_lines = user_input.GetSize();
1393 StreamString sstr;
1394
1395 // Check to see if we have any data; if not, just return.
1396 if (user_input.GetSize() == 0)
1397 return false;
1398
1399 // Wrap all user input into a Python class
1400
1401 std::string auto_generated_class_name(GenerateUniqueName(
1402 "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1403
1404 StringList auto_generated_class;
1405
1406 // Create the function name & definition string.
1407
1408 sstr.Printf("class %s:", auto_generated_class_name.c_str());
1409 auto_generated_class.AppendString(sstr.GetString());
1410
1411 // Wrap everything up inside the class, increasing the indentation. we don't
1412 // need to play any fancy indentation tricks here because there is no
1413 // surrounding code whose indentation we need to honor
1414 for (int i = 0; i < num_lines; ++i) {
1415 sstr.Clear();
1416 sstr.Printf(" %s", user_input.GetStringAtIndex(i));
1417 auto_generated_class.AppendString(sstr.GetString());
1418 }
1419
1420 // Verify that the results are valid Python. (even though the method is
1421 // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1422 // (TODO: rename that method to ExportDefinitionToInterpreter)
1423 if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1424 return false;
1425
1426 // Store the name of the auto-generated class
1427
1428 output.assign(auto_generated_class_name);
1429 return true;
1430}
1431
1434 if (class_name == nullptr || class_name[0] == '\0')
1436
1439 class_name, m_dictionary_name.c_str());
1442 new StructuredPythonObject(std::move(ret_val)));
1443}
1444
1446 const StructuredData::ObjectSP &os_plugin_object_sp,
1447 lldb::StackFrameSP frame_sp) {
1449
1450 if (!os_plugin_object_sp)
1451 return ValueObjectListSP();
1452
1453 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1454 if (!generic)
1455 return nullptr;
1456
1458 (PyObject *)generic->GetValue());
1459
1460 if (!implementor.IsAllocated())
1461 return ValueObjectListSP();
1462
1465 implementor.get(), frame_sp));
1466
1467 // if it fails, print the error but otherwise go on
1468 if (PyErr_Occurred()) {
1469 PyErr_Print();
1470 PyErr_Clear();
1471 }
1472 if (py_return.get()) {
1473 PythonList result_list(PyRefType::Borrowed, py_return.get());
1474 ValueObjectListSP result = std::make_shared<ValueObjectList>();
1475 for (size_t i = 0; i < result_list.GetSize(); i++) {
1476 PyObject *item = result_list.GetItemAtIndex(i).get();
1477 lldb::SBValue *sb_value_ptr =
1479 auto valobj_sp =
1481 if (valobj_sp)
1482 result->Append(valobj_sp);
1483 }
1484 return result;
1485 }
1486 return ValueObjectListSP();
1487}
1488
1490 const StructuredData::ObjectSP &os_plugin_object_sp,
1491 lldb::StackFrameSP frame_sp) {
1493
1494 if (!os_plugin_object_sp)
1495 return false;
1496
1497 StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1498 if (!generic)
1499 return false;
1500
1502 (PyObject *)generic->GetValue());
1503
1504 if (!implementor.IsAllocated())
1505 return false;
1506
1507 bool result =
1508 SWIGBridge::LLDBSwigPython_ShouldHide(implementor.get(), frame_sp);
1509
1510 // if it fails, print the error but otherwise go on
1511 if (PyErr_Occurred()) {
1512 PyErr_Print();
1513 PyErr_Clear();
1515 return result;
1516}
1517
1520 return std::make_unique<ScriptedProcessPythonInterface>(*this);
1521}
1522
1525 return std::make_shared<ScriptedStopHookPythonInterface>(*this);
1526}
1527
1530 return std::make_shared<ScriptedHookPythonInterface>(*this);
1531}
1532
1535 return std::make_shared<ScriptedBreakpointPythonInterface>(*this);
1536}
1537
1540 return std::make_shared<ScriptedThreadPythonInterface>(*this);
1541}
1542
1545 return std::make_shared<ScriptedFramePythonInterface>(*this);
1546}
1547
1550 return std::make_shared<ScriptedFrameProviderPythonInterface>(*this);
1551}
1552
1555 return std::make_shared<ScriptedThreadPlanPythonInterface>(*this);
1556}
1557
1560 return std::make_shared<OperatingSystemPythonInterface>(*this);
1561}
1562
1565 ScriptObject obj) {
1566 void *ptr = const_cast<void *>(obj.GetPointer());
1568 PythonObject py_obj(PyRefType::Borrowed, static_cast<PyObject *>(ptr));
1569 if (!py_obj.IsValid() || py_obj.IsNone())
1570 return {};
1571 return py_obj.CreateStructuredObject();
1572}
1573
1577 if (!FileSystem::Instance().Exists(file_spec)) {
1578 error = Status::FromErrorString("no such file");
1579 return StructuredData::ObjectSP();
1580 }
1581
1582 StructuredData::ObjectSP module_sp;
1583
1584 LoadScriptOptions load_script_options =
1585 LoadScriptOptions().SetInitSession(true).SetSilent(false);
1586 if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1587 error, &module_sp))
1588 return module_sp;
1589
1590 return StructuredData::ObjectSP();
1591}
1592
1594 StructuredData::ObjectSP plugin_module_sp, Target *target,
1595 const char *setting_name, lldb_private::Status &error) {
1596 if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1598 StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1599 if (!generic)
1601
1602 Locker py_lock(this,
1604 TargetSP target_sp(target->shared_from_this());
1605
1606 auto setting = (PyObject *)SWIGBridge::LLDBSWIGPython_GetDynamicSetting(
1607 generic->GetValue(), setting_name, target_sp);
1608
1609 if (!setting)
1611
1612 PythonDictionary py_dict =
1614
1615 if (!py_dict)
1618 return py_dict.CreateStructuredDictionary();
1619}
1620
1623 const char *class_name, lldb::ValueObjectSP valobj) {
1624 if (class_name == nullptr || class_name[0] == '\0')
1625 return StructuredData::ObjectSP();
1626
1627 if (!valobj.get())
1628 return StructuredData::ObjectSP();
1629
1630 ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
1631 Target *target = exe_ctx.GetTargetPtr();
1632
1633 if (!target)
1634 return StructuredData::ObjectSP();
1635
1636 Debugger &debugger = target->GetDebugger();
1637 ScriptInterpreterPythonImpl *python_interpreter =
1638 GetPythonInterpreter(debugger);
1639
1640 if (!python_interpreter)
1641 return StructuredData::ObjectSP();
1642
1643 Locker py_lock(this,
1646 class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
1647
1649 new StructuredPythonObject(std::move(ret_val)));
1650}
1651
1654 DebuggerSP debugger_sp(m_debugger.shared_from_this());
1655
1656 if (class_name == nullptr || class_name[0] == '\0')
1658
1659 if (!debugger_sp.get())
1661
1662 Locker py_lock(this,
1665 class_name, m_dictionary_name.c_str(), debugger_sp);
1666
1667 if (ret_val.IsValid())
1669 new StructuredPythonObject(std::move(ret_val)));
1670 else
1671 return {};
1672}
1673
1675 const char *oneliner, std::string &output, const void *name_token) {
1677 input.SplitIntoLines(oneliner, strlen(oneliner));
1678 return GenerateTypeScriptFunction(input, output, name_token);
1679}
1680
1682 const char *oneliner, std::string &output, const void *name_token) {
1684 input.SplitIntoLines(oneliner, strlen(oneliner));
1685 return GenerateTypeSynthClass(input, output, name_token);
1686}
1687
1689 StringList &user_input, std::string &output, bool has_extra_args,
1690 bool is_callback) {
1691 static uint32_t num_created_functions = 0;
1692 user_input.RemoveBlankLines();
1693 StreamString sstr;
1694 Status error;
1695 if (user_input.GetSize() == 0) {
1696 error = Status::FromErrorString("No input data.");
1697 return error;
1698 }
1699
1700 std::string auto_generated_function_name(GenerateUniqueName(
1701 "lldb_autogen_python_bp_callback_func_", num_created_functions));
1702 if (has_extra_args)
1703 sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
1704 auto_generated_function_name.c_str());
1705 else
1706 sstr.Printf("def %s (frame, bp_loc, internal_dict):",
1707 auto_generated_function_name.c_str());
1708
1709 error = GenerateFunction(sstr.GetData(), user_input, is_callback);
1710 if (!error.Success())
1711 return error;
1712
1713 // Store the name of the auto-generated function to be called.
1714 output.assign(auto_generated_function_name);
1715 return error;
1716}
1717
1719 StringList &user_input, std::string &output, bool is_callback) {
1720 static uint32_t num_created_functions = 0;
1721 user_input.RemoveBlankLines();
1722 StreamString sstr;
1723
1724 if (user_input.GetSize() == 0)
1725 return false;
1726
1727 std::string auto_generated_function_name(GenerateUniqueName(
1728 "lldb_autogen_python_wp_callback_func_", num_created_functions));
1729 sstr.Printf("def %s (frame, wp, internal_dict):",
1730 auto_generated_function_name.c_str());
1731
1732 if (!GenerateFunction(sstr.GetData(), user_input, is_callback).Success())
1733 return false;
1734
1735 // Store the name of the auto-generated function to be called.
1736 output.assign(auto_generated_function_name);
1737 return true;
1738}
1739
1741 const char *python_function_name, lldb::ValueObjectSP valobj,
1742 StructuredData::ObjectSP &callee_wrapper_sp,
1743 const TypeSummaryOptions &options, std::string &retval) {
1744
1746
1747 if (!valobj.get()) {
1748 retval.assign("<no object>");
1749 return false;
1750 }
1751
1752 void *old_callee = nullptr;
1753 StructuredData::Generic *generic = nullptr;
1754 if (callee_wrapper_sp) {
1755 generic = callee_wrapper_sp->GetAsGeneric();
1756 if (generic)
1757 old_callee = generic->GetValue();
1758 }
1759 void *new_callee = old_callee;
1760
1761 bool ret_val;
1762 if (python_function_name && *python_function_name) {
1763 {
1766 {
1767 TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
1768
1769 static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
1770 Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
1772 python_function_name, GetSessionDictionary().get(), valobj,
1773 &new_callee, options_sp, retval);
1774 }
1775 }
1776 } else {
1777 retval.assign("<no function name>");
1778 return false;
1779 }
1780
1781 if (new_callee && old_callee != new_callee) {
1782 Locker py_lock(this,
1784 callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
1785 PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
1787
1788 return ret_val;
1789}
1790
1792 const char *python_function_name, TypeImplSP type_impl_sp) {
1793 Locker py_lock(this,
1796 python_function_name, m_dictionary_name.c_str(), type_impl_sp);
1797}
1798
1800 void *baton, StoppointCallbackContext *context, user_id_t break_id,
1801 user_id_t break_loc_id) {
1802 CommandDataPython *bp_option_data = (CommandDataPython *)baton;
1803 const char *python_function_name = bp_option_data->script_source.c_str();
1804
1805 if (!context)
1806 return true;
1807
1808 ExecutionContext exe_ctx(context->exe_ctx_ref);
1809 Target *target = exe_ctx.GetTargetPtr();
1810
1811 if (!target)
1812 return true;
1813
1814 Debugger &debugger = target->GetDebugger();
1815 ScriptInterpreterPythonImpl *python_interpreter =
1816 GetPythonInterpreter(debugger);
1817
1818 if (!python_interpreter)
1819 return true;
1820
1821 if (python_function_name && python_function_name[0]) {
1822 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1823 BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
1824 if (breakpoint_sp) {
1825 const BreakpointLocationSP bp_loc_sp(
1826 breakpoint_sp->FindLocationByID(break_loc_id));
1827
1828 if (stop_frame_sp && bp_loc_sp) {
1829 bool ret_val = true;
1830 {
1831 Locker py_lock(python_interpreter, Locker::AcquireLock |
1834 Expected<bool> maybe_ret_val =
1836 python_function_name,
1837 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1838 bp_loc_sp, bp_option_data->m_extra_args);
1839
1840 if (!maybe_ret_val) {
1841
1842 llvm::handleAllErrors(
1843 maybe_ret_val.takeError(),
1844 [&](PythonException &E) {
1845 *debugger.GetAsyncErrorStream() << E.ReadBacktrace();
1846 },
1847 [&](const llvm::ErrorInfoBase &E) {
1848 *debugger.GetAsyncErrorStream() << E.message();
1849 });
1850
1851 } else {
1852 ret_val = maybe_ret_val.get();
1853 }
1854 }
1855 return ret_val;
1856 }
1857 }
1858 }
1859 // We currently always true so we stop in case anything goes wrong when
1860 // trying to call the script function
1861 return true;
1862}
1863
1865 void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
1866 WatchpointOptions::CommandData *wp_option_data =
1868 const char *python_function_name = wp_option_data->script_source.c_str();
1869
1870 if (!context)
1871 return true;
1872
1873 ExecutionContext exe_ctx(context->exe_ctx_ref);
1874 Target *target = exe_ctx.GetTargetPtr();
1875
1876 if (!target)
1877 return true;
1878
1879 Debugger &debugger = target->GetDebugger();
1880 ScriptInterpreterPythonImpl *python_interpreter =
1881 GetPythonInterpreter(debugger);
1882
1883 if (!python_interpreter)
1884 return true;
1885
1886 if (python_function_name && python_function_name[0]) {
1887 const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
1888 WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
1889 if (wp_sp) {
1890 if (stop_frame_sp && wp_sp) {
1891 bool ret_val = true;
1892 {
1893 Locker py_lock(python_interpreter, Locker::AcquireLock |
1897 python_function_name,
1898 python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
1899 wp_sp);
1900 }
1901 return ret_val;
1902 }
1903 }
1904 }
1905 // We currently always true so we stop in case anything goes wrong when
1906 // trying to call the script function
1907 return true;
1908}
1909
1911 const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
1912 if (!implementor_sp)
1913 return 0;
1914 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1915 if (!generic)
1916 return 0;
1917 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1918 if (!implementor)
1919 return 0;
1920
1921 size_t ret_val = 0;
1922
1923 {
1924 Locker py_lock(this,
1926 ret_val = SWIGBridge::LLDBSwigPython_CalculateNumChildren(implementor, max);
1928
1929 return ret_val;
1930}
1931
1933 const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
1934 if (!implementor_sp)
1935 return lldb::ValueObjectSP();
1936
1937 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1938 if (!generic)
1939 return lldb::ValueObjectSP();
1940 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1941 if (!implementor)
1942 return lldb::ValueObjectSP();
1943
1944 lldb::ValueObjectSP ret_val;
1945 {
1946 Locker py_lock(this,
1948 PyObject *child_ptr =
1950 if (child_ptr != nullptr && child_ptr != Py_None) {
1951 lldb::SBValue *sb_value_ptr =
1953 if (sb_value_ptr == nullptr)
1954 Py_XDECREF(child_ptr);
1955 else
1957 sb_value_ptr);
1958 } else {
1959 Py_XDECREF(child_ptr);
1960 }
1962
1963 return ret_val;
1964}
1965
1967 const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
1968 if (!implementor_sp)
1969 return llvm::createStringErrorV("type has no child named '{0}'",
1970 child_name);
1971
1972 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
1973 if (!generic)
1974 return llvm::createStringErrorV("type has no child named '{0}'",
1975 child_name);
1976 auto *implementor = static_cast<PyObject *>(generic->GetValue());
1977 if (!implementor)
1978 return llvm::createStringErrorV("type has no child named '{0}'",
1979 child_name);
1980
1981 uint32_t ret_val = UINT32_MAX;
1982
1983 {
1984 Locker py_lock(this,
1987 child_name);
1988 }
1989
1990 if (ret_val == UINT32_MAX)
1991 return llvm::createStringErrorV("type has no child named '{0}'",
1992 child_name);
1993 return ret_val;
1994}
1995
1997 const StructuredData::ObjectSP &implementor_sp) {
1998 bool ret_val = false;
1999
2000 if (!implementor_sp)
2001 return ret_val;
2002
2003 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2004 if (!generic)
2005 return ret_val;
2006 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2007 if (!implementor)
2008 return ret_val;
2009
2010 {
2011 Locker py_lock(this,
2013 ret_val =
2016
2017 return ret_val;
2018}
2019
2021 const StructuredData::ObjectSP &implementor_sp) {
2022 bool ret_val = false;
2023
2024 if (!implementor_sp)
2025 return ret_val;
2026
2027 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2028 if (!generic)
2029 return ret_val;
2030 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2031 if (!implementor)
2032 return ret_val;
2033
2034 {
2035 Locker py_lock(this,
2038 implementor);
2040
2041 return ret_val;
2042}
2043
2045 const StructuredData::ObjectSP &implementor_sp) {
2046 lldb::ValueObjectSP ret_val(nullptr);
2047
2048 if (!implementor_sp)
2049 return ret_val;
2050
2051 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2052 if (!generic)
2053 return ret_val;
2054 auto *implementor = static_cast<PyObject *>(generic->GetValue());
2055 if (!implementor)
2056 return ret_val;
2057
2058 {
2059 Locker py_lock(this,
2061 PyObject *child_ptr =
2063 if (child_ptr != nullptr && child_ptr != Py_None) {
2064 lldb::SBValue *sb_value_ptr =
2066 if (sb_value_ptr == nullptr)
2067 Py_XDECREF(child_ptr);
2068 else
2070 sb_value_ptr);
2071 } else {
2072 Py_XDECREF(child_ptr);
2073 }
2075
2076 return ret_val;
2077}
2078
2080 const StructuredData::ObjectSP &implementor_sp) {
2081 Locker py_lock(this,
2083
2084 if (!implementor_sp)
2085 return {};
2086
2087 StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2088 if (!generic)
2089 return {};
2090
2091 PythonObject implementor(PyRefType::Borrowed,
2092 (PyObject *)generic->GetValue());
2093 if (!implementor.IsAllocated())
2094 return {};
2095
2096 llvm::Expected<PythonObject> expected_py_return =
2097 implementor.CallMethod("get_type_name");
2098
2099 if (!expected_py_return) {
2100 llvm::consumeError(expected_py_return.takeError());
2101 return {};
2102 }
2103
2104 PythonObject py_return = std::move(expected_py_return.get());
2105 if (!py_return.IsAllocated() || !PythonString::Check(py_return.get()))
2106 return {};
2108 PythonString type_name(PyRefType::Borrowed, py_return.get());
2109 return ConstString(type_name.GetString());
2110}
2111
2113 const char *impl_function, Process *process, std::string &output,
2114 Status &error) {
2115 bool ret_val;
2116 if (!process) {
2117 error = Status::FromErrorString("no process");
2118 return false;
2119 }
2120 if (!impl_function || !impl_function[0]) {
2121 error = Status::FromErrorString("no function to execute");
2122 return false;
2123 }
2124
2125 {
2126 Locker py_lock(this,
2129 impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2130 output);
2131 if (!ret_val)
2132 error = Status::FromErrorString("python script evaluation failed");
2133 }
2134 return ret_val;
2135}
2136
2138 const char *impl_function, Thread *thread, std::string &output,
2139 Status &error) {
2140 if (!thread) {
2141 error = Status::FromErrorString("no thread");
2142 return false;
2143 }
2144 if (!impl_function || !impl_function[0]) {
2145 error = Status::FromErrorString("no function to execute");
2146 return false;
2147 }
2148
2149 Locker py_lock(this,
2151 if (std::optional<std::string> result =
2153 impl_function, m_dictionary_name.c_str(),
2154 thread->shared_from_this())) {
2155 output = std::move(*result);
2156 return true;
2158 error = Status::FromErrorString("python script evaluation failed");
2159 return false;
2160}
2161
2163 const char *impl_function, Target *target, std::string &output,
2164 Status &error) {
2165 bool ret_val;
2166 if (!target) {
2167 error = Status::FromErrorString("no thread");
2168 return false;
2169 }
2170 if (!impl_function || !impl_function[0]) {
2171 error = Status::FromErrorString("no function to execute");
2172 return false;
2173 }
2174
2175 {
2176 TargetSP target_sp(target->shared_from_this());
2177 Locker py_lock(this,
2180 impl_function, m_dictionary_name.c_str(), target_sp, output);
2181 if (!ret_val)
2182 error = Status::FromErrorString("python script evaluation failed");
2183 }
2184 return ret_val;
2185}
2186
2188 const char *impl_function, StackFrame *frame, std::string &output,
2189 Status &error) {
2190 if (!frame) {
2191 error = Status::FromErrorString("no frame");
2192 return false;
2193 }
2194 if (!impl_function || !impl_function[0]) {
2195 error = Status::FromErrorString("no function to execute");
2196 return false;
2197 }
2198
2199 Locker py_lock(this,
2201 if (std::optional<std::string> result =
2203 impl_function, m_dictionary_name.c_str(),
2204 frame->shared_from_this())) {
2205 output = std::move(*result);
2206 return true;
2208 error = Status::FromErrorString("python script evaluation failed");
2209 return false;
2210}
2211
2213 const char *impl_function, ValueObject *value, std::string &output,
2214 Status &error) {
2215 bool ret_val;
2216 if (!value) {
2217 error = Status::FromErrorString("no value");
2218 return false;
2219 }
2220 if (!impl_function || !impl_function[0]) {
2221 error = Status::FromErrorString("no function to execute");
2222 return false;
2223 }
2224
2225 {
2226 Locker py_lock(this,
2229 impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2230 if (!ret_val)
2231 error = Status::FromErrorString("python script evaluation failed");
2232 }
2233 return ret_val;
2234}
2235
2236uint64_t replace_all(std::string &str, const std::string &oldStr,
2237 const std::string &newStr) {
2238 size_t pos = 0;
2239 uint64_t matches = 0;
2240 while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2241 matches++;
2242 str.replace(pos, oldStr.length(), newStr);
2243 pos += newStr.length();
2244 }
2245 return matches;
2246}
2247
2249 const char *pathname, const LoadScriptOptions &options,
2251 FileSpec extra_search_dir, lldb::TargetSP target_sp) {
2252 namespace fs = llvm::sys::fs;
2253 namespace path = llvm::sys::path;
2254
2256 .SetEnableIO(!options.GetSilent())
2257 .SetSetLLDBGlobals(false);
2258
2259 if (!pathname || !pathname[0]) {
2260 error = Status::FromErrorString("empty path");
2261 return false;
2262 }
2263
2264 llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2265 io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2266 exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2267
2268 if (!io_redirect_or_error) {
2269 error = Status::FromError(io_redirect_or_error.takeError());
2270 return false;
2271 }
2272
2273 ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2274
2275 // Before executing Python code, lock the GIL.
2276 Locker py_lock(this,
2278 (options.GetInitSession() ? Locker::InitSession : 0) |
2281 (options.GetInitSession() ? Locker::TearDownSession : 0),
2282 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2283 io_redirect.GetErrorFile());
2284
2285 auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2286 if (directory.empty()) {
2287 return llvm::createStringError("invalid directory name");
2288 }
2289
2290 replace_all(directory, "\\", "\\\\");
2291 replace_all(directory, "'", "\\'");
2292
2293 // Make sure that Python has "directory" in the search path.
2294 StreamString command_stream;
2295 command_stream.Printf("if not (sys.path.__contains__('%s')):\n "
2296 "sys.path.insert(1,'%s');\n\n",
2297 directory.c_str(), directory.c_str());
2298 bool syspath_retval =
2299 ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2300 if (!syspath_retval)
2301 return llvm::createStringError("Python sys.path handling failed");
2302
2303 return llvm::Error::success();
2304 };
2305
2306 std::string module_name(pathname);
2307 bool possible_package = false;
2308
2309 if (extra_search_dir) {
2310 if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2311 error = Status::FromError(std::move(e));
2312 return false;
2313 }
2314 } else {
2315 FileSpec module_file(pathname);
2316 FileSystem::Instance().Resolve(module_file);
2317
2318 fs::file_status st;
2319 std::error_code ec = status(module_file.GetPath(), st);
2320
2321 if (ec || st.type() == fs::file_type::status_error ||
2322 st.type() == fs::file_type::type_unknown ||
2323 st.type() == fs::file_type::file_not_found) {
2324 // if not a valid file of any sort, check if it might be a filename still
2325 // dot can't be used but / and \ can, and if either is found, reject
2326 if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2327 error = Status::FromErrorStringWithFormatv("invalid pathname '{0}'",
2328 pathname);
2329 return false;
2330 }
2331 // Not a filename, probably a package of some sort, let it go through.
2332 possible_package = true;
2333 } else if (is_directory(st) || is_regular_file(st)) {
2334 if (module_file.GetDirectory().IsEmpty()) {
2336 "invalid directory name '{0}'", pathname);
2337 return false;
2338 }
2339 if (llvm::Error e =
2340 ExtendSysPath(module_file.GetDirectory().GetCString())) {
2341 error = Status::FromError(std::move(e));
2342 return false;
2343 }
2344 module_name = module_file.GetFilename().GetCString();
2345 } else {
2347 "no known way to import this module specification");
2348 return false;
2349 }
2350 }
2351
2352 // Strip .py or .pyc extension
2353 llvm::StringRef extension = llvm::sys::path::extension(module_name);
2354 if (!extension.empty()) {
2355 if (extension == ".py")
2356 module_name.resize(module_name.length() - 3);
2357 else if (extension == ".pyc")
2358 module_name.resize(module_name.length() - 4);
2359 }
2360
2361 if (!possible_package && module_name.find('.') != llvm::StringRef::npos) {
2363 "Python does not allow dots in module names: %s", module_name.c_str());
2364 return false;
2365 }
2366
2367 if (module_name.find('-') != llvm::StringRef::npos) {
2369 "Python discourages dashes in module names: %s", module_name.c_str());
2370 return false;
2371 }
2372
2373 // Check if the module is already imported.
2374 StreamString command_stream;
2375 command_stream.Clear();
2376 command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2377 bool does_contain = false;
2378 // This call will succeed if the module was ever imported in any Debugger in
2379 // the lifetime of the process in which this LLDB framework is living.
2380 const bool does_contain_executed = ExecuteOneLineWithReturn(
2381 command_stream.GetData(),
2383 exc_options);
2384
2385 const bool was_imported_globally = does_contain_executed && does_contain;
2386 const bool was_imported_locally =
2388 .GetItemForKey(PythonString(module_name))
2389 .IsAllocated();
2390
2391 // now actually do the import
2392 command_stream.Clear();
2393
2394 if (was_imported_globally || was_imported_locally) {
2395 if (!was_imported_locally)
2396 command_stream.Printf("import %s ; reload_module(%s)",
2397 module_name.c_str(), module_name.c_str());
2398 else
2399 command_stream.Printf("reload_module(%s)", module_name.c_str());
2400 } else
2401 command_stream.Printf("import %s", module_name.c_str());
2402
2403 error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2404 if (error.Fail())
2405 return false;
2406
2407 // if we are here, everything worked
2408 // call __lldb_init_module(debugger,dict)
2410 module_name.c_str(), m_dictionary_name.c_str(),
2411 m_debugger.shared_from_this())) {
2412 error = Status::FromErrorString("calling __lldb_init_module failed");
2413 return false;
2414 }
2415
2416 if (module_sp) {
2417 // everything went just great, now set the module object
2418 command_stream.Clear();
2419 command_stream.Printf("%s", module_name.c_str());
2420 void *module_pyobj = nullptr;
2422 command_stream.GetData(),
2424 exc_options) &&
2425 module_pyobj)
2426 *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2427 PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2428 }
2429
2430 // Finally, if we got a target passed in, then we should tell the new module
2431 // about this target:
2432 if (target_sp)
2434 module_name.c_str(), m_dictionary_name.c_str(), target_sp);
2435
2436 return true;
2437}
2438
2439bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2440 if (!word || !word[0])
2441 return false;
2442
2443 llvm::StringRef word_sr(word);
2444
2445 // filter out a few characters that would just confuse us and that are
2446 // clearly not keyword material anyway
2447 if (word_sr.find('"') != llvm::StringRef::npos ||
2448 word_sr.find('\'') != llvm::StringRef::npos)
2449 return false;
2450
2451 StreamString command_stream;
2452 command_stream.Printf("keyword.iskeyword('%s')", word);
2453 bool result;
2454 ExecuteScriptOptions options;
2455 options.SetEnableIO(false);
2456 options.SetMaskoutErrors(true);
2457 options.SetSetLLDBGlobals(false);
2458 if (ExecuteOneLineWithReturn(command_stream.GetData(),
2460 &result, options))
2461 return result;
2462 return false;
2463}
2464
2467 : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2468 m_old_asynch(debugger_sp->GetAsyncExecution()) {
2470 m_debugger_sp->SetAsyncExecution(false);
2472 m_debugger_sp->SetAsyncExecution(true);
2473}
2474
2476 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2477 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2478}
2479
2481 const char *impl_function, llvm::StringRef args,
2482 ScriptedCommandSynchronicity synchronicity,
2484 const lldb_private::ExecutionContext &exe_ctx) {
2485 if (!impl_function) {
2486 error = Status::FromErrorString("no function to execute");
2487 return false;
2488 }
2489
2490 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2491 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2492
2493 if (!debugger_sp.get()) {
2494 error = Status::FromErrorString("invalid Debugger pointer");
2495 return false;
2496 }
2497
2498 bool ret_val = false;
2499
2500 {
2501 Locker py_lock(this,
2503 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2505
2506 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2507
2508 std::string args_str = args.str();
2510 impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2511 cmd_retobj, exe_ctx_ref_sp);
2512 }
2513
2514 if (!ret_val)
2515 error = Status::FromErrorString("unable to execute script function");
2516 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2517 return false;
2519 error.Clear();
2520 return ret_val;
2521}
2522
2524 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2525 ScriptedCommandSynchronicity synchronicity,
2527 const lldb_private::ExecutionContext &exe_ctx) {
2528 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2529 error = Status::FromErrorString("no function to execute");
2530 return false;
2531 }
2532
2533 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2534 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2535
2536 if (!debugger_sp.get()) {
2537 error = Status::FromErrorString("invalid Debugger pointer");
2538 return false;
2539 }
2540
2541 bool ret_val = false;
2542
2543 {
2544 Locker py_lock(this,
2546 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2548
2549 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2550
2551 std::string args_str = args.str();
2553 static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2554 args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2555 }
2556
2557 if (!ret_val)
2558 error = Status::FromErrorString("unable to execute script function");
2559 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2560 return false;
2562 error.Clear();
2563 return ret_val;
2564}
2565
2567 StructuredData::GenericSP impl_obj_sp, Args &args,
2568 ScriptedCommandSynchronicity synchronicity,
2570 const lldb_private::ExecutionContext &exe_ctx) {
2571 if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2572 error = Status::FromErrorString("no function to execute");
2573 return false;
2574 }
2575
2576 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2577 lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2578
2579 if (!debugger_sp.get()) {
2580 error = Status::FromErrorString("invalid Debugger pointer");
2581 return false;
2582 }
2583
2584 bool ret_val = false;
2585
2586 {
2587 Locker py_lock(this,
2589 (cmd_retobj.GetInteractive() ? 0 : Locker::NoSTDIN),
2591
2592 SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2593
2594 StructuredData::ArraySP args_arr_sp(new StructuredData::Array());
2595
2596 for (const Args::ArgEntry &entry : args) {
2597 args_arr_sp->AddStringItem(entry.ref());
2598 }
2599 StructuredDataImpl args_impl(args_arr_sp);
2600
2602 static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2603 args_impl, cmd_retobj, exe_ctx_ref_sp);
2604 }
2605
2606 if (!ret_val)
2607 error = Status::FromErrorString("unable to execute script function");
2608 else if (cmd_retobj.GetStatus() == eReturnStatusFailed)
2609 return false;
2610
2611 error.Clear();
2612 return ret_val;
2613}
2614
2615std::optional<std::string>
2617 StructuredData::GenericSP impl_obj_sp, Args &args) {
2618 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2619 return std::nullopt;
2620
2621 lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2622
2623 if (!debugger_sp.get())
2624 return std::nullopt;
2625
2626 std::optional<std::string> ret_val;
2627
2628 {
2631
2633
2634 // For scripting commands, we send the command string:
2635 std::string command;
2636 args.GetQuotedCommandString(command);
2638 static_cast<PyObject *>(impl_obj_sp->GetValue()), command);
2640 return ret_val;
2641}
2642
2645 StructuredData::GenericSP impl_obj_sp, std::vector<llvm::StringRef> &args,
2646 size_t args_pos, size_t char_in_arg) {
2647 StructuredData::DictionarySP completion_dict_sp;
2648 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2649 return completion_dict_sp;
2650
2651 {
2654
2655 completion_dict_sp =
2657 static_cast<PyObject *>(impl_obj_sp->GetValue()), args, args_pos,
2658 char_in_arg);
2660 return completion_dict_sp;
2661}
2662
2665 StructuredData::GenericSP impl_obj_sp, llvm::StringRef &long_option,
2666 size_t char_in_arg) {
2667 StructuredData::DictionarySP completion_dict_sp;
2668 if (!impl_obj_sp || !impl_obj_sp->IsValid())
2669 return completion_dict_sp;
2670
2671 {
2674
2675 completion_dict_sp = SWIGBridge::
2677 static_cast<PyObject *>(impl_obj_sp->GetValue()), long_option,
2678 char_in_arg);
2679 }
2680 return completion_dict_sp;
2682
2683/// In Python, a special attribute __doc__ contains the docstring for an object
2684/// (function, method, class, ...) if any is defined Otherwise, the attribute's
2685/// value is None.
2687 std::string &dest) {
2688 dest.clear();
2689
2690 if (!item || !*item)
2691 return false;
2692
2693 std::string command(item);
2694 command += ".__doc__";
2695
2696 // Python is going to point this to valid data if ExecuteOneLineWithReturn
2697 // returns successfully.
2698 char *result_ptr = nullptr;
2699
2702 &result_ptr, ExecuteScriptOptions().SetEnableIO(false))) {
2703 if (result_ptr)
2704 dest.assign(result_ptr);
2705 return true;
2706 }
2707
2708 StreamString str_stream;
2709 str_stream << "Function " << item
2710 << " was not found. Containing module might be missing.";
2711 dest = std::string(str_stream.GetString());
2712
2713 return false;
2714}
2715
2717 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2718 dest.clear();
2719
2721
2722 if (!cmd_obj_sp)
2723 return false;
2724
2726 (PyObject *)cmd_obj_sp->GetValue());
2727
2728 if (!implementor.IsAllocated())
2729 return false;
2730
2731 llvm::Expected<PythonObject> expected_py_return =
2732 implementor.CallMethod("get_short_help");
2733
2734 if (!expected_py_return) {
2735 llvm::consumeError(expected_py_return.takeError());
2736 return false;
2737 }
2738
2739 PythonObject py_return = std::move(expected_py_return.get());
2740
2741 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2742 PythonString py_string(PyRefType::Borrowed, py_return.get());
2743 llvm::StringRef return_data(py_string.GetString());
2744 dest.assign(return_data.data(), return_data.size());
2745 return true;
2747
2748 return false;
2749}
2750
2752 StructuredData::GenericSP cmd_obj_sp) {
2753 uint32_t result = 0;
2754
2756
2757 static char callee_name[] = "get_flags";
2758
2759 if (!cmd_obj_sp)
2760 return result;
2761
2763 (PyObject *)cmd_obj_sp->GetValue());
2764
2765 if (!implementor.IsAllocated())
2766 return result;
2767
2769 PyObject_GetAttrString(implementor.get(), callee_name));
2770
2771 if (PyErr_Occurred())
2772 PyErr_Clear();
2773
2774 if (!pmeth.IsAllocated())
2775 return result;
2776
2777 if (PyCallable_Check(pmeth.get()) == 0) {
2778 if (PyErr_Occurred())
2779 PyErr_Clear();
2780 return result;
2781 }
2782
2783 if (PyErr_Occurred())
2784 PyErr_Clear();
2785
2786 long long py_return = unwrapOrSetPythonException(
2787 As<long long>(implementor.CallMethod(callee_name)));
2788
2789 // if it fails, print the error but otherwise go on
2790 if (PyErr_Occurred()) {
2791 PyErr_Print();
2792 PyErr_Clear();
2793 } else {
2794 result = py_return;
2795 }
2797 return result;
2798}
2799
2802 StructuredData::GenericSP cmd_obj_sp) {
2803 StructuredData::ObjectSP result = {};
2804
2806
2807 static char callee_name[] = "get_options_definition";
2808
2809 if (!cmd_obj_sp)
2810 return result;
2811
2813 (PyObject *)cmd_obj_sp->GetValue());
2814
2815 if (!implementor.IsAllocated())
2816 return result;
2817
2819 PyObject_GetAttrString(implementor.get(), callee_name));
2820
2821 if (PyErr_Occurred())
2822 PyErr_Clear();
2823
2824 if (!pmeth.IsAllocated())
2825 return result;
2826
2827 if (PyCallable_Check(pmeth.get()) == 0) {
2828 if (PyErr_Occurred())
2829 PyErr_Clear();
2830 return result;
2831 }
2832
2833 if (PyErr_Occurred())
2834 PyErr_Clear();
2835
2836 PythonDictionary py_return = unwrapOrSetPythonException(
2837 As<PythonDictionary>(implementor.CallMethod(callee_name)));
2838
2839 // if it fails, print the error but otherwise go on
2840 if (PyErr_Occurred()) {
2841 PyErr_Print();
2842 PyErr_Clear();
2843 return {};
2845 return py_return.CreateStructuredObject();
2846}
2847
2850 StructuredData::GenericSP cmd_obj_sp) {
2851 StructuredData::ObjectSP result = {};
2852
2854
2855 static char callee_name[] = "get_args_definition";
2856
2857 if (!cmd_obj_sp)
2858 return result;
2859
2860 PythonObject implementor(PyRefType::Borrowed,
2861 (PyObject *)cmd_obj_sp->GetValue());
2862
2863 if (!implementor.IsAllocated())
2864 return result;
2865
2866 PythonObject pmeth(PyRefType::Owned,
2867 PyObject_GetAttrString(implementor.get(), callee_name));
2868
2869 if (PyErr_Occurred())
2870 PyErr_Clear();
2871
2872 if (!pmeth.IsAllocated())
2873 return result;
2874
2875 if (PyCallable_Check(pmeth.get()) == 0) {
2876 if (PyErr_Occurred())
2877 PyErr_Clear();
2878 return result;
2879 }
2880
2881 if (PyErr_Occurred())
2882 PyErr_Clear();
2883
2884 PythonList py_return = unwrapOrSetPythonException(
2885 As<PythonList>(implementor.CallMethod(callee_name)));
2886
2887 // if it fails, print the error but otherwise go on
2888 if (PyErr_Occurred()) {
2889 PyErr_Print();
2890 PyErr_Clear();
2891 return {};
2892 }
2893 return py_return.CreateStructuredObject();
2894}
2895
2897 StructuredData::GenericSP cmd_obj_sp) {
2898
2900
2901 static char callee_name[] = "option_parsing_started";
2902
2903 if (!cmd_obj_sp)
2904 return;
2905
2906 PythonObject implementor(PyRefType::Borrowed,
2907 (PyObject *)cmd_obj_sp->GetValue());
2908
2909 if (!implementor.IsAllocated())
2910 return;
2911
2912 PythonObject pmeth(PyRefType::Owned,
2913 PyObject_GetAttrString(implementor.get(), callee_name));
2914
2915 if (PyErr_Occurred())
2916 PyErr_Clear();
2917
2918 if (!pmeth.IsAllocated())
2919 return;
2920
2921 if (PyCallable_Check(pmeth.get()) == 0) {
2922 if (PyErr_Occurred())
2923 PyErr_Clear();
2924 return;
2925 }
2926
2927 if (PyErr_Occurred())
2928 PyErr_Clear();
2929
2930 // option_parsing_starting doesn't return anything, ignore anything but
2931 // python errors.
2932 unwrapOrSetPythonException(As<bool>(implementor.CallMethod(callee_name)));
2933
2934 // if it fails, print the error but otherwise go on
2935 if (PyErr_Occurred()) {
2936 PyErr_Print();
2937 PyErr_Clear();
2938 return;
2939 }
2940}
2941
2943 StructuredData::GenericSP cmd_obj_sp, ExecutionContext *exe_ctx,
2944 llvm::StringRef long_option, llvm::StringRef value) {
2945 StructuredData::ObjectSP result = {};
2946
2948
2949 static char callee_name[] = "set_option_value";
2950
2951 if (!cmd_obj_sp)
2952 return false;
2953
2954 PythonObject implementor(PyRefType::Borrowed,
2955 (PyObject *)cmd_obj_sp->GetValue());
2956
2957 if (!implementor.IsAllocated())
2958 return false;
2959
2960 PythonObject pmeth(PyRefType::Owned,
2961 PyObject_GetAttrString(implementor.get(), callee_name));
2962
2963 if (PyErr_Occurred())
2964 PyErr_Clear();
2965
2966 if (!pmeth.IsAllocated())
2967 return false;
2968
2969 if (PyCallable_Check(pmeth.get()) == 0) {
2970 if (PyErr_Occurred())
2971 PyErr_Clear();
2972 return false;
2973 }
2974
2975 if (PyErr_Occurred())
2976 PyErr_Clear();
2977
2978 lldb::ExecutionContextRefSP exe_ctx_ref_sp;
2979 if (exe_ctx)
2980 exe_ctx_ref_sp = std::make_shared<ExecutionContextRef>(exe_ctx);
2981 PythonObject ctx_ref_obj = SWIGBridge::ToSWIGWrapper(exe_ctx_ref_sp);
2982
2983 bool py_return = unwrapOrSetPythonException(As<bool>(
2984 implementor.CallMethod(callee_name, ctx_ref_obj,
2985 long_option.str().c_str(), value.str().c_str())));
2986
2987 // if it fails, print the error but otherwise go on
2988 if (PyErr_Occurred()) {
2989 PyErr_Print();
2990 PyErr_Clear();
2991 return false;
2992 }
2993 return py_return;
2994}
2995
2997 StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2998 dest.clear();
2999
3001
3002 if (!cmd_obj_sp)
3003 return false;
3004
3006 (PyObject *)cmd_obj_sp->GetValue());
3007
3008 if (!implementor.IsAllocated())
3009 return false;
3010
3011 llvm::Expected<PythonObject> expected_py_return =
3012 implementor.CallMethod("get_long_help");
3013
3014 if (!expected_py_return) {
3015 llvm::consumeError(expected_py_return.takeError());
3016 return false;
3017 }
3018
3019 PythonObject py_return = std::move(expected_py_return.get());
3020
3021 bool got_string = false;
3022 if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3023 PythonString str(PyRefType::Borrowed, py_return.get());
3024 llvm::StringRef str_data(str.GetString());
3025 dest.assign(str_data.data(), str_data.size());
3026 got_string = true;
3027 }
3029 return got_string;
3030}
3031
3032std::unique_ptr<ScriptInterpreterLocker>
3034 std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3037 return py_lock;
3038}
3039
3042
3043 // RAII-based initialization which correctly handles multiple-initialization,
3044 // version- specific differences among Python 2 and Python 3, and saving and
3045 // restoring various other pieces of state that can get mucked with during
3046 // initialization.
3047 InitializePythonRAII initialize_guard;
3048
3050
3051 // Update the path python uses to search for modules to include the current
3052 // directory.
3053
3054 RunSimpleString("import sys");
3056
3057 // Don't denormalize paths when calling file_spec.GetPath(). On platforms
3058 // that use a backslash as the path separator, this will result in executing
3059 // python code containing paths with unescaped backslashes. But Python also
3060 // accepts forward slashes, so to make life easier we just use that.
3061 if (FileSpec file_spec = GetPythonDir())
3062 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3063 if (FileSpec file_spec = HostInfo::GetShlibDir())
3064 AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3065
3066 RunSimpleString("sys.dont_write_bytecode = 1; import "
3067 "lldb.embedded_interpreter; from "
3068 "lldb.embedded_interpreter import run_python_interpreter; "
3069 "from lldb.embedded_interpreter import run_one_line");
3070
3071#if LLDB_USE_PYTHON_SET_INTERRUPT
3072 // Python will not just overwrite its internal SIGINT handler but also the
3073 // one from the process. Backup the current SIGINT handler to prevent that
3074 // Python deletes it.
3075 RestoreSignalHandlerScope save_sigint(SIGINT);
3076
3077 // Setup a default SIGINT signal handler that works the same way as the
3078 // normal Python REPL signal handler which raises a KeyboardInterrupt.
3079 // Also make sure to not pollute the user's REPL with the signal module nor
3080 // our utility function.
3081 RunSimpleString("def lldb_setup_sigint_handler():\n"
3082 " import signal;\n"
3083 " def signal_handler(sig, frame):\n"
3084 " raise KeyboardInterrupt()\n"
3085 " signal.signal(signal.SIGINT, signal_handler);\n"
3086 "lldb_setup_sigint_handler();\n"
3087 "del lldb_setup_sigint_handler\n");
3088#endif
3089}
3090
3092 std::string path) {
3093 std::string statement;
3094 if (location == AddLocation::Beginning) {
3095 statement.assign("sys.path.insert(0,\"");
3096 statement.append(path);
3097 statement.append("\")");
3098 } else {
3099 statement.assign("sys.path.append(\"");
3100 statement.append(path);
3101 statement.append("\")");
3102 }
3103 RunSimpleString(statement.c_str());
3104}
3105
3106// We are intentionally NOT calling Py_Finalize here (this would be the logical
3107// place to call it). Calling Py_Finalize here causes test suite runs to seg
3108// fault: The test suite runs in Python. It registers SBDebugger::Terminate to
3109// be called 'at_exit'. When the test suite Python harness finishes up, it
3110// calls Py_Finalize, which calls all the 'at_exit' registered functions.
3111// SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3112// which calls ScriptInterpreter::Terminate, which calls
3113// ScriptInterpreterPythonImpl::Terminate. So if we call Py_Finalize here, we
3114// end up with Py_Finalize being called from within Py_Finalize, which results
3115// in a seg fault. Since this function only gets called when lldb is shutting
3116// down and going away anyway, the fact that we don't actually call Py_Finalize
3117// should not cause any problems (everything should shut down/go away anyway
3118// when the process exits).
3119//
3120// 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_ERROR(log, error,...)
Definition Log.h:394
#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 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:100
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:355
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,...
lldb::ScriptedHookInterfaceSP CreateScriptedHookInterface() override
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:426
Debugger & GetDebugger() const
Definition Target.h:1249
WatchpointList & GetWatchpointList()
Definition Target.h:953
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::ScriptedHookInterface > ScriptedHookInterfaceSP
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