9#ifndef LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
10#define LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
54 std::variant<std::monostate, InvalidArgumentCountPayload, std::string>
66 return llvm::createStringError(
"scripted Interface has invalid object");
69 PythonObject(PyRefType::Borrowed,
72 if (!py_obj.IsAllocated())
73 return llvm::createStringError(
74 "scripted Interface has invalid python object");
76 PythonObject py_obj_class = py_obj.GetAttributeValue(
"__class__");
77 if (!py_obj_class.IsValid())
78 return llvm::createStringError(
79 "scripted Interface python object is missing '__class__' attribute");
81 PythonObject py_obj_module = py_obj_class.GetAttributeValue(
"__module__");
82 if (!py_obj_module.IsValid())
83 return llvm::createStringError(
84 "scripted Interface python object '__class__' is missing "
85 "'__module__' attribute");
87 PythonString py_obj_module_str = py_obj_module.Str();
88 if (!py_obj_module_str.IsValid())
89 return llvm::createStringError(
90 "scripted Interface python object '__class__.__module__' attribute "
93 llvm::StringRef py_obj_module_str_ref = py_obj_module_str.GetString();
94 PythonModule py_module = PythonModule::AddModule(py_obj_module_str_ref);
95 if (!py_module.IsValid())
96 return llvm::createStringError(
"failed to import '%s' module",
97 py_obj_module_str_ref.data());
99 PythonObject py_module_file = py_module.GetAttributeValue(
"__file__");
100 if (!py_module_file.IsValid())
101 return llvm::createStringError(
102 "module '%s' is missing '__file__' attribute",
103 py_obj_module_str_ref.data());
105 PythonString py_module_file_str = py_module_file.Str();
106 if (!py_module_file_str.IsValid())
107 return llvm::createStringError(
108 "module '%s.__file__' attribute is not a string",
109 py_obj_module_str_ref.data());
111 return FileSpec(py_module_file_str.GetString());
114 llvm::Expected<std::map<llvm::StringLiteral, AbstractMethodCheckerPayload>>
120 std::map<llvm::StringLiteral, AbstractMethodCheckerPayload> checker;
121#define SET_CASE_AND_CONTINUE(method_name, case) \
123 checker[method_name] = {case, {}}; \
129 llvm::StringLiteral method_name = requirement.name;
136 if (!attr.IsAllocated())
140 PythonCallable callable = attr.
AsType<PythonCallable>();
145 if (!requirement.min_arg_count)
148 auto arg_info_or_err = callable.GetArgInfo();
149 if (!arg_info_or_err) {
150 checker[method_name] = {
156 PythonCallable::ArgInfo arg_info = *arg_info_or_err;
157 if (requirement.min_arg_count <= arg_info.max_positional_args) {
160 checker[method_name] = {
163 requirement.min_arg_count, arg_info.max_positional_args)};
167#undef SET_CASE_AND_CONTINUE
172 template <
typename...
Args>
173 llvm::Expected<StructuredData::GenericSP>
180 auto create_error = [](llvm::StringLiteral format,
auto &&...ts) {
181 return llvm::createStringError(
182 llvm::formatv(format.data(), std::forward<
decltype(ts)>(ts)...)
187 llvm::StringRef class_name = scripted_metadata.
GetClassName();
188 bool has_class_name = !class_name.empty();
189 bool has_interpreter_dict =
190 !(llvm::StringRef(
m_interpreter.GetDictionaryName()).empty());
191 if (!has_class_name && !has_interpreter_dict && !script_obj) {
193 return create_error(
"Missing script class name.");
194 else if (!has_interpreter_dict)
195 return create_error(
"Invalid script interpreter dictionary.");
197 return create_error(
"Missing scripting object.");
200 std::optional<PolicyStack::Guard> policy_guard;
207 PythonObject result = {};
210 result = PythonObject(PyRefType::Borrowed,
211 static_cast<PyObject *
>(script_obj->
GetValue()));
216 if (!dict.IsAllocated())
217 return create_error(
"Could not find interpreter dictionary: {0}",
221 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
223 if (!init.IsAllocated())
224 return create_error(
"Could not find script class: {0}",
227 std::tuple<
Args...> original_args = std::forward_as_tuple(args...);
230 std::string error_string;
231 llvm::Expected<PythonCallable::ArgInfo> arg_info = init.GetArgInfo();
233 llvm::handleAllErrors(
234 arg_info.takeError(),
235 [&](PythonException &E) { error_string.append(E.ReadBacktrace()); },
236 [&](
const llvm::ErrorInfoBase &E) {
237 error_string.append(E.message());
239 return llvm::createStringError(llvm::inconvertibleErrorCode(),
243 llvm::Expected<PythonObject> expected_return_object =
244 create_error(
"Resulting object is not initialized.");
258 size_t num_args =
sizeof...(Args);
259 if (arg_info->max_positional_args != PythonCallable::ArgInfo::UNBOUNDED &&
260 num_args != arg_info->max_positional_args) {
261 if (num_args != arg_info->max_positional_args - 1) {
265 llvm::consumeError(expected_return_object.takeError());
266 return create_error(
"Passed arguments ({0}) doesn't match the number "
267 "of expected arguments ({1}).",
268 num_args, arg_info->max_positional_args);
272 [&init, &expected_return_object](
auto &&...args) {
273 if (!expected_return_object)
274 llvm::consumeError(expected_return_object.takeError());
275 expected_return_object = init.Call(args...);
277 std::tuple_cat(transformed_args, std::make_tuple(dict)));
280 [&init, &expected_return_object](
auto &&...args) {
281 if (!expected_return_object)
282 llvm::consumeError(expected_return_object.takeError());
283 expected_return_object = init.Call(args...);
288 if (!expected_return_object)
293 return llvm::createStringError(
295 result = expected_return_object.get();
298 if (!result.IsValid())
299 return create_error(
"Resulting object is not a valid Python Object.");
300 if (!result.HasAttribute(
"__class__"))
301 return create_error(
"Resulting object doesn't have '__class__' member.");
303 PythonObject obj_class = result.GetAttributeValue(
"__class__");
304 if (!obj_class.IsValid())
305 return create_error(
"Resulting class object is not a valid.");
306 if (!obj_class.HasAttribute(
"__name__"))
308 "Resulting object class doesn't have '__name__' member.");
309 PythonString obj_class_name =
310 obj_class.GetAttributeValue(
"__name__").AsType<PythonString>();
314 return checker_or_err.takeError();
316 llvm::Error abstract_method_errors = llvm::Error::success();
317 for (
const auto &method_checker : *checker_or_err)
318 switch (method_checker.second.checker_case) {
320 abstract_method_errors = llvm::joinErrors(
321 std::move(abstract_method_errors),
322 std::move(create_error(
"Abstract method {0}.{1} not implemented.",
323 obj_class_name.GetString(),
324 method_checker.first)));
327 abstract_method_errors = llvm::joinErrors(
328 std::move(abstract_method_errors),
329 std::move(create_error(
"Abstract method {0}.{1} not allocated.",
330 obj_class_name.GetString(),
331 method_checker.first)));
334 abstract_method_errors = llvm::joinErrors(
335 std::move(abstract_method_errors),
336 std::move(create_error(
"Abstract method {0}.{1} not callable.",
337 obj_class_name.GetString(),
338 method_checker.first)));
341 const std::string *py_error =
342 std::get_if<std::string>(&method_checker.second.payload);
343 abstract_method_errors = llvm::joinErrors(
344 std::move(abstract_method_errors),
345 std::move(create_error(
346 "abstract method {0}.{1} has unknown argument count: {2}",
347 obj_class_name.GetString(), method_checker.first,
348 py_error ? *py_error :
"<no further information>")));
351 auto &payload_variant = method_checker.second.payload;
352 if (!std::holds_alternative<
355 abstract_method_errors = llvm::joinErrors(
356 std::move(abstract_method_errors),
357 std::move(create_error(
358 "Abstract method {0}.{1} has unexpected argument count.",
359 obj_class_name.GetString(), method_checker.first)));
361 auto payload = std::get<
364 abstract_method_errors = llvm::joinErrors(
365 std::move(abstract_method_errors),
367 create_error(
"Abstract method {0}.{1} has unexpected "
368 "argument count (expected {2} but has {3}).",
369 obj_class_name.GetString(), method_checker.first,
370 payload.required_argument_count,
371 payload.actual_argument_count)));
375 LLDB_LOG(log,
"Abstract method {0}.{1} implemented & valid.",
376 obj_class_name.GetString(), method_checker.first);
380 if (abstract_method_errors) {
382 LLDB_LOG(log,
"Abstract method error in {0}:\n{1}", class_name,
384 return error.ToError();
388 new StructuredPythonObject(std::move(result)));
411 std::string caller_signature =
412 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(
" (") +
413 llvm::Twine(class_name) + llvm::Twine(
".") +
414 llvm::Twine(method_name) + llvm::Twine(
")"))
417 if (class_name.empty())
421 std::optional<PolicyStack::Guard> policy_guard;
432 if (!dict.IsAllocated())
435 llvm::formatv(
"could not find interpreter dictionary: {0}",
442 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
444 if (!class_obj.IsAllocated())
447 llvm::formatv(
"could not find script class: {0}", class_name).str(),
451 if (!class_obj.HasAttribute(method_name))
454 llvm::formatv(
"class {0} does not have method {1}", class_name,
459 PythonCallable method =
460 class_obj.GetAttributeValue(method_name).AsType<PythonCallable>();
461 if (!method.IsAllocated())
463 llvm::formatv(
"method {0}.{1} is not callable",
464 class_name, method_name)
469 std::tuple<
Args...> original_args = std::forward_as_tuple(args...);
473 llvm::Expected<PythonObject> expected_return_object =
474 llvm::createStringError(
"not initialized");
476 [&method, &expected_return_object](
auto &&...args) {
477 if (!expected_return_object)
478 llvm::consumeError(expected_return_object.takeError());
479 expected_return_object = method.Call(args...);
483 if (llvm::Error e = expected_return_object.takeError()) {
493 llvm::formatv(
"python exception in {0} method '{1}'", class_name,
499 PythonObject py_return = std::move(expected_return_object.get());
502 if (
sizeof...(
Args) > 0)
506 "couldn't re-assign reference and pointer arguments",
error);
522 std::string error_msg;
523 llvm::handleAllErrors(
526 [&](
const llvm::ErrorInfoBase &E) { error_msg = E.message(); });
530 template <
typename T = StructuredData::ObjectSP>
540 std::string caller_signature =
541 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(
" (") +
542 llvm::Twine(method_name) + llvm::Twine(
")"))
548 std::optional<PolicyStack::Guard> policy_guard;
555 PythonObject implementor(PyRefType::Borrowed,
558 if (!implementor.IsAllocated())
561 "python implementor not allocated",
565 std::tuple<
Args...> original_args = std::forward_as_tuple(args...);
571 size_t call_arity =
sizeof...(Args);
572 if (PythonObject py_method = implementor.GetAttributeValue(method_name);
573 py_method.IsAllocated()) {
574 PythonCallable callable = py_method.AsType<PythonCallable>();
575 if (callable.IsAllocated()) {
576 if (llvm::Expected<PythonCallable::ArgInfo> arg_info =
577 callable.GetArgInfo()) {
578 if (arg_info->max_positional_args !=
579 PythonCallable::ArgInfo::UNBOUNDED &&
580 arg_info->max_positional_args < call_arity)
581 call_arity = arg_info->max_positional_args;
583 llvm::consumeError(arg_info.takeError());
588 llvm::Expected<PythonObject> expected_return_object =
589 llvm::createStringError(
"not initialized");
591 std::make_index_sequence<
sizeof...(
Args) + 1>{},
592 [&implementor, &method_name,
593 &expected_return_object](
auto &&...call_args) {
594 if (!expected_return_object)
595 llvm::consumeError(expected_return_object.takeError());
596 expected_return_object = implementor.CallMethod(
597 method_name.data(), call_args...);
600 if (llvm::Error e = expected_return_object.takeError()) {
610 llvm::formatv(
"python exception in {0} method '{1}'",
619 PythonObject py_return = std::move(expected_return_object.get());
625 if (
sizeof...(
Args) > 0)
629 "couldn't re-assign reference and pointer arguments",
error);
631 if (!py_return.IsAllocated())
636 template <
typename...
Args>
666 template <
typename T,
typename = std::enable_if_t<
667 std::is_base_of_v<StructuredData::Object, T>>>
746 for (
const std::string &s : arg)
760 template <
typename T,
typename U>
765 template <
typename T>
775 template <
typename T>
784 original_arg = boolean_arg.
GetValue();
787 "{}: Invalid boolean argument.", LLVM_PRETTY_FUNCTION);
790 template <std::size_t... I,
typename...
Args>
792 std::index_sequence<I...>) {
793 return std::make_tuple(
Transform(std::get<I>(args))...);
798 template <
typename...
Args>
804 template <std::size_t N,
typename Tuple,
typename Fn, std::size_t... I>
806 std::forward<Fn>(fn)(std::get<I>(std::forward<Tuple>(t))...);
809 template <std::
size_t N,
typename Tuple,
typename Fn>
812 std::make_index_sequence<N>{});
818 template <
typename Tuple, std::size_t... Is,
typename Fn>
820 std::index_sequence<Is...>, Fn &&fn) {
821 (void)std::initializer_list<int>{(
827 template <
typename T,
typename U>
836 template <
typename T,
typename SB>
841 template <std::size_t... I,
typename... Ts,
typename... Us>
843 std::tuple<Us...> &transformed_args,
844 std::index_sequence<I...>) {
846 (
TransformBack(std::get<I>(original_args), std::get<I>(transformed_args),
849 return error.Success();
852 template <
typename... Ts,
typename... Us>
854 std::tuple<Us...> &transformed_args) {
855 if (
sizeof...(Ts) !=
sizeof...(Us))
859 std::make_index_sequence<
sizeof...(Ts)>());
862 template <
typename T,
typename...
Args>
868 template <
typename T>
void FormatArgs(std::string &fmt, T arg)
const {
940std::optional<MemoryRegionInfo>
975std::optional<lldb::ValueType>
985std::vector<std::string>
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
ScriptInterpreterPythonImpl::Locker Locker
#define SET_CASE_AND_CONTINUE(method_name, case)
A command line argument class.
Guard PushScriptedExtensionCall()
static PolicyStack & Get()
static Ret ErrorWithMessage(llvm::StringRef caller_name, llvm::StringRef user_msg, Status &error, LLDBLog log_category=LLDBLog::Process)
std::optional< ScriptedMetadata > m_scripted_metadata
llvm::SmallVector< llvm::StringLiteral > const GetAbstractMethods() const
virtual llvm::SmallVector< AbstractMethodRequirement > GetAbstractMethodRequirements() const =0
virtual bool UserCanRunDirectly() const
Whether the user can invoke this extension directly, the way a scripted command can.
ScriptedInterface()=default
const std::optional< ScriptedMetadata > & GetScriptedMetadata() const
StructuredData::GenericSP m_object_instance_sp
python::ScopedPythonObject< lldb::SBCommandReturnObject > Transform(CommandReturnObject *arg)
python::PythonObject Transform(lldb::StackFrameListSP arg)
python::PythonObject Transform(lldb::ThreadPlanSP arg)
Status GetStatusFromMethod(llvm::StringRef method_name, Args &&...args)
python::PythonObject Transform(lldb::ProcessSP arg)
static void ApplyPrefix(Tuple &&t, Fn &&fn)
void TransformBack(T &original_arg, U transformed_arg, Status &error)
ScriptInterpreterPythonImpl & m_interpreter
python::PythonObject Transform(Event *arg)
auto TransformArgs(const std::tuple< Args... > &args)
python::PythonObject Transform(lldb::ExecutionContextRefSP arg)
python::PythonObject Transform(lldb::ThreadSP arg)
python::PythonObject Transform(const StructuredDataImpl &arg)
T ExtractValueFromPythonObject(python::PythonObject &p, Status &error)
~ScriptedPythonInterface() override=default
static void CallWithArity(size_t call_arity, Tuple &&t, std::index_sequence< Is... >, Fn &&fn)
python::PythonObject Transform(const TypeSummaryOptions &arg)
llvm::Expected< FileSpec > GetScriptedModulePath() override
python::PythonObject Transform(lldb::DescriptionLevel arg)
python::PythonObject Transform(const Status &arg)
python::PythonObject Transform(const SymbolContext &arg)
llvm::Expected< std::map< llvm::StringLiteral, AbstractMethodCheckerPayload > > CheckAbstractMethodImplementation(const python::PythonObject &obj_class) const
void ReverseTransform(T &original_arg, python::PythonObject transformed_arg, Status &error)
void FormatArgs(std::string &fmt, T arg, Args... args) const
python::PythonObject Transform(lldb::BreakpointSP arg)
void FormatArgs(std::string &fmt, T arg) const
python::PythonObject Transform(lldb::DebuggerSP arg)
static std::string ExtractPythonError(llvm::Error error)
Extract detailed error message including Python backtrace if available.
ScriptedPythonInterface(ScriptInterpreterPythonImpl &interpreter)
python::PythonObject Transform(const std::vector< std::string > &arg)
void ReverseTransform(T &original_arg, U transformed_arg, Status &error)
T CallStaticMethod(llvm::StringRef class_name, llvm::StringRef method_name, Status &error, Args &&...args)
Call a static method on a Python class without creating an instance.
void FormatArgs(std::string &fmt) const
T Dispatch(llvm::StringRef method_name, Status &error, Args &&...args)
python::PythonObject Transform(lldb::BreakpointLocationSP arg)
python::PythonObject Transform(std::shared_ptr< T > arg)
bool ReassignPtrsOrRefsArgs(std::tuple< Ts... > &original_args, std::tuple< Us... > &transformed_args)
python::PythonObject Transform(lldb::StreamSP arg)
python::PythonObject Transform(Status &&arg)
python::PythonObject Transform(lldb::DataExtractorSP arg)
python::PythonObject Transform(lldb::StackFrameSP arg)
bool ReassignPtrsOrRefsArgs(std::tuple< Ts... > &original_args, std::tuple< Us... > &transformed_args, std::index_sequence< I... >)
python::PythonObject Transform(lldb::ProcessLaunchInfoSP arg)
llvm::Expected< StructuredData::GenericSP > CreatePluginObject(const ScriptedMetadata &scripted_metadata, StructuredData::Generic *script_obj, Args... args)
python::PythonObject Transform(lldb::TargetSP arg)
void TransformBack(T &original_arg, python::ScopedPythonObject< SB > &transformed_arg, Status &error)
auto TransformTuple(const std::tuple< Args... > &args, std::index_sequence< I... >)
static void ApplyPrefixImpl(Tuple &&t, Fn &&fn, std::index_sequence< I... >)
AbstractMethodCheckerCases
void ReverseTransform(bool &original_arg, python::PythonObject transformed_arg, Status &error)
python::PythonObject Transform(lldb::ValueObjectSP arg)
void ReverseTransform(const T &original_arg, python::PythonObject transformed_arg, Status &error)
python::PythonObject Transform(lldb::ProcessAttachInfoSP arg)
python::PythonObject Transform(bool arg)
Status Clone() const
Don't call this function in new code.
static Status FromErrorString(const char *str)
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
std::shared_ptr< Generic > GenericSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
Defines a symbol context baton that can be handed other debug core functions.
std::string ReadBacktrace() const
void AppendItem(const PythonObject &object)
StructuredData::ObjectSP CreateStructuredObject() const
PythonObject GetAttributeValue(llvm::StringRef attribute) const
bool HasAttribute(llvm::StringRef attribute) const
static PythonObject ToSWIGWrapper(std::unique_ptr< lldb::SBValue > value_sb)
A class that automatically clears an SB object when it goes out of scope.
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.
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::ProcessAttachInfo > ProcessAttachInfoSP
std::shared_ptr< lldb_private::Stream > StreamSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::ValueObjectList > ValueObjectListSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::ProcessLaunchInfo > ProcessLaunchInfoSP
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
std::shared_ptr< lldb_private::ExecutionContextRef > ExecutionContextRefSP
InvalidArgumentCountPayload(size_t required, size_t actual)
size_t actual_argument_count
size_t required_argument_count
std::variant< std::monostate, InvalidArgumentCountPayload, std::string > payload
AbstractMethodCheckerCases checker_case