9#ifndef LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
10#define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
20#include "lldb/Host/Config.h"
29class ScriptInterpreterPythonImpl;
32 ScriptedPythonInterface(ScriptInterpreterPythonImpl &interpreter);
33 ~ScriptedPythonInterface()
override =
default;
35 enum class AbstractMethodCheckerCases {
39 eUnknownArgumentCount,
40 eInvalidArgumentCount,
44 struct AbstrackMethodCheckerPayload {
46 struct InvalidArgumentCountPayload {
47 InvalidArgumentCountPayload(
size_t required,
size_t actual)
48 : required_argument_count(required), actual_argument_count(actual) {}
50 size_t required_argument_count;
51 size_t actual_argument_count;
54 AbstractMethodCheckerCases checker_case;
55 std::variant<std::monostate, InvalidArgumentCountPayload> payload;
58 llvm::Expected<std::map<llvm::StringLiteral, AbstrackMethodCheckerPayload>>
59 CheckAbstractMethodImplementation(
60 const python::PythonDictionary &class_dict)
const {
62 using namespace python;
64 std::map<llvm::StringLiteral, AbstrackMethodCheckerPayload> checker;
65#define SET_CASE_AND_CONTINUE(method_name, case) \
67 checker[method_name] = {case, {}}; \
71 for (
const AbstractMethodRequirement &requirement :
72 GetAbstractMethodRequirements()) {
73 llvm::StringLiteral method_name = requirement.name;
74 if (!class_dict.HasKey(method_name))
75 SET_CASE_AND_CONTINUE(method_name,
76 AbstractMethodCheckerCases::eNotImplemented)
77 auto callable_or_err = class_dict.GetItem(method_name);
78 if (!callable_or_err) {
79 llvm::consumeError(callable_or_err.takeError());
80 SET_CASE_AND_CONTINUE(method_name,
81 AbstractMethodCheckerCases::eNotAllocated)
84 PythonCallable callable = callable_or_err->AsType<PythonCallable>();
86 SET_CASE_AND_CONTINUE(method_name,
87 AbstractMethodCheckerCases::eNotCallable)
89 if (!requirement.min_arg_count)
90 SET_CASE_AND_CONTINUE(method_name, AbstractMethodCheckerCases::eValid)
92 auto arg_info_or_err = callable.GetArgInfo();
93 if (!arg_info_or_err) {
94 llvm::consumeError(arg_info_or_err.takeError());
95 SET_CASE_AND_CONTINUE(method_name,
96 AbstractMethodCheckerCases::eUnknownArgumentCount)
99 PythonCallable::ArgInfo arg_info = *arg_info_or_err;
100 if (requirement.min_arg_count <= arg_info.max_positional_args) {
101 SET_CASE_AND_CONTINUE(method_name, AbstractMethodCheckerCases::eValid)
103 checker[method_name] = {
104 AbstractMethodCheckerCases::eInvalidArgumentCount,
105 AbstrackMethodCheckerPayload::InvalidArgumentCountPayload(
106 requirement.min_arg_count, arg_info.max_positional_args)};
110#undef SET_CASE_AND_CONTINUE
115 template <
typename... Args>
116 llvm::Expected<StructuredData::GenericSP>
117 CreatePluginObject(llvm::StringRef class_name,
118 StructuredData::Generic *script_obj, Args... args) {
119 using namespace python;
120 using Locker = ScriptInterpreterPythonImpl::Locker;
122 Log *log =
GetLog(LLDBLog::Script);
123 auto create_error = [](llvm::StringLiteral format,
auto &&...ts) {
124 return llvm::createStringError(
125 llvm::formatv(format.data(), std::forward<
decltype(ts)>(ts)...)
129 bool has_class_name = !class_name.empty();
130 bool has_interpreter_dict =
131 !(llvm::StringRef(m_interpreter.GetDictionaryName()).empty());
132 if (!has_class_name && !has_interpreter_dict && !script_obj) {
134 return create_error(
"Missing script class name.");
135 else if (!has_interpreter_dict)
136 return create_error(
"Invalid script interpreter dictionary.");
138 return create_error(
"Missing scripting object.");
141 Locker py_lock(&m_interpreter, Locker::AcquireLock | Locker::NoSTDIN,
144 PythonObject result = {};
147 result = PythonObject(PyRefType::Borrowed,
148 static_cast<PyObject *
>(script_obj->GetValue()));
151 PythonModule::MainModule().ResolveName<python::PythonDictionary>(
152 m_interpreter.GetDictionaryName());
153 if (!dict.IsAllocated())
154 return create_error(
"Could not find interpreter dictionary: {0}",
155 m_interpreter.GetDictionaryName());
158 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
160 if (!init.IsAllocated())
161 return create_error(
"Could not find script class: {0}",
164 std::tuple<Args...> original_args = std::forward_as_tuple(args...);
165 auto transformed_args = TransformArgs(original_args);
167 std::string error_string;
168 llvm::Expected<PythonCallable::ArgInfo> arg_info = init.GetArgInfo();
170 llvm::handleAllErrors(
171 arg_info.takeError(),
172 [&](PythonException &E) { error_string.append(E.ReadBacktrace()); },
173 [&](
const llvm::ErrorInfoBase &E) {
174 error_string.append(E.message());
176 return llvm::createStringError(llvm::inconvertibleErrorCode(),
180 llvm::Expected<PythonObject> expected_return_object =
181 create_error(
"Resulting object is not initialized.");
195 size_t num_args =
sizeof...(Args);
196 if (arg_info->max_positional_args != PythonCallable::ArgInfo::UNBOUNDED &&
197 num_args != arg_info->max_positional_args) {
198 if (num_args != arg_info->max_positional_args - 1)
199 return create_error(
"Passed arguments ({0}) doesn't match the number "
200 "of expected arguments ({1}).",
201 num_args, arg_info->max_positional_args);
204 [&init, &expected_return_object](
auto &&...args) {
205 llvm::consumeError(expected_return_object.takeError());
206 expected_return_object = init(args...);
208 std::tuple_cat(transformed_args, std::make_tuple(dict)));
211 [&init, &expected_return_object](
auto &&...args) {
212 llvm::consumeError(expected_return_object.takeError());
213 expected_return_object = init(args...);
218 if (!expected_return_object)
219 return expected_return_object.takeError();
220 result = expected_return_object.get();
223 if (!result.IsValid())
224 return create_error(
"Resulting object is not a valid Python Object.");
225 if (!result.HasAttribute(
"__class__"))
226 return create_error(
"Resulting object doesn't have '__class__' member.");
228 PythonObject obj_class = result.GetAttributeValue(
"__class__");
229 if (!obj_class.IsValid())
230 return create_error(
"Resulting class object is not a valid.");
231 if (!obj_class.HasAttribute(
"__name__"))
233 "Resulting object class doesn't have '__name__' member.");
234 PythonString obj_class_name =
235 obj_class.GetAttributeValue(
"__name__").AsType<PythonString>();
237 PythonObject object_class_mapping_proxy =
238 obj_class.GetAttributeValue(
"__dict__");
239 if (!obj_class.HasAttribute(
"__dict__"))
241 "Resulting object class doesn't have '__dict__' member.");
243 PythonCallable dict_converter = PythonModule::BuiltinsModule()
245 .AsType<PythonCallable>();
246 if (!dict_converter.IsAllocated())
248 "Python 'builtins' module doesn't have 'dict' class.");
250 PythonDictionary object_class_dict =
251 dict_converter(object_class_mapping_proxy).AsType<PythonDictionary>();
252 if (!object_class_dict.IsAllocated())
253 return create_error(
"Coudn't create dictionary from resulting object "
254 "class mapping proxy object.");
256 auto checker_or_err = CheckAbstractMethodImplementation(object_class_dict);
258 return checker_or_err.takeError();
260 llvm::Error abstract_method_errors = llvm::Error::success();
261 for (
const auto &method_checker : *checker_or_err)
262 switch (method_checker.second.checker_case) {
263 case AbstractMethodCheckerCases::eNotImplemented:
264 abstract_method_errors = llvm::joinErrors(
265 std::move(abstract_method_errors),
266 std::move(create_error(
"Abstract method {0}.{1} not implemented.",
267 obj_class_name.GetString(),
268 method_checker.first)));
270 case AbstractMethodCheckerCases::eNotAllocated:
271 abstract_method_errors = llvm::joinErrors(
272 std::move(abstract_method_errors),
273 std::move(create_error(
"Abstract method {0}.{1} not allocated.",
274 obj_class_name.GetString(),
275 method_checker.first)));
277 case AbstractMethodCheckerCases::eNotCallable:
278 abstract_method_errors = llvm::joinErrors(
279 std::move(abstract_method_errors),
280 std::move(create_error(
"Abstract method {0}.{1} not callable.",
281 obj_class_name.GetString(),
282 method_checker.first)));
284 case AbstractMethodCheckerCases::eUnknownArgumentCount:
285 abstract_method_errors = llvm::joinErrors(
286 std::move(abstract_method_errors),
287 std::move(create_error(
288 "Abstract method {0}.{1} has unknown argument count.",
289 obj_class_name.GetString(), method_checker.first)));
291 case AbstractMethodCheckerCases::eInvalidArgumentCount: {
292 auto &payload_variant = method_checker.second.payload;
293 if (!std::holds_alternative<
294 AbstrackMethodCheckerPayload::InvalidArgumentCountPayload>(
296 abstract_method_errors = llvm::joinErrors(
297 std::move(abstract_method_errors),
298 std::move(create_error(
299 "Abstract method {0}.{1} has unexpected argument count.",
300 obj_class_name.GetString(), method_checker.first)));
302 auto payload = std::get<
303 AbstrackMethodCheckerPayload::InvalidArgumentCountPayload>(
305 abstract_method_errors = llvm::joinErrors(
306 std::move(abstract_method_errors),
308 create_error(
"Abstract method {0}.{1} has unexpected "
309 "argument count (expected {2} but has {3}).",
310 obj_class_name.GetString(), method_checker.first,
311 payload.required_argument_count,
312 payload.actual_argument_count)));
315 case AbstractMethodCheckerCases::eValid:
316 LLDB_LOG(log,
"Abstract method {0}.{1} implemented & valid.",
317 obj_class_name.GetString(), method_checker.first);
321 if (abstract_method_errors) {
322 Status error = Status::FromError(std::move(abstract_method_errors));
323 LLDB_LOG(log,
"Abstract method error in {0}:\n{1}", class_name,
325 return error.ToError();
328 m_object_instance_sp = StructuredData::GenericSP(
329 new StructuredPythonObject(std::move(result)));
330 return m_object_instance_sp;
346 template <
typename T = StructuredData::ObjectSP,
typename... Args>
347 T CallStaticMethod(llvm::StringRef class_name, llvm::StringRef method_name,
348 Status &
error, Args &&...args) {
349 using namespace python;
350 using Locker = ScriptInterpreterPythonImpl::Locker;
352 std::string caller_signature =
353 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(
" (") +
354 llvm::Twine(class_name) + llvm::Twine(
".") +
355 llvm::Twine(method_name) + llvm::Twine(
")"))
358 if (class_name.empty())
359 return ErrorWithMessage<T>(caller_signature,
"missing script class name",
362 Locker py_lock(&m_interpreter, Locker::AcquireLock | Locker::NoSTDIN,
367 PythonModule::MainModule().ResolveName<python::PythonDictionary>(
368 m_interpreter.GetDictionaryName());
369 if (!dict.IsAllocated())
370 return ErrorWithMessage<T>(
372 llvm::formatv(
"could not find interpreter dictionary: {0}",
373 m_interpreter.GetDictionaryName())
379 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
381 if (!class_obj.IsAllocated())
382 return ErrorWithMessage<T>(
384 llvm::formatv(
"could not find script class: {0}", class_name).str(),
388 if (!class_obj.HasAttribute(method_name))
389 return ErrorWithMessage<T>(
391 llvm::formatv(
"class {0} does not have method {1}", class_name,
396 PythonCallable method =
397 class_obj.GetAttributeValue(method_name).AsType<PythonCallable>();
398 if (!method.IsAllocated())
399 return ErrorWithMessage<T>(caller_signature,
400 llvm::formatv(
"method {0}.{1} is not callable",
401 class_name, method_name)
406 std::tuple<Args...> original_args = std::forward_as_tuple(args...);
407 auto transformed_args = TransformArgs(original_args);
410 llvm::Expected<PythonObject> expected_return_object =
411 llvm::make_error<llvm::StringError>(
"Not initialized.",
412 llvm::inconvertibleErrorCode());
414 [&method, &expected_return_object](
auto &&...args) {
415 llvm::consumeError(expected_return_object.takeError());
416 expected_return_object = method(args...);
420 if (llvm::Error e = expected_return_object.takeError()) {
421 error = Status::FromError(std::move(e));
422 return ErrorWithMessage<T>(
423 caller_signature,
"python static method could not be called",
error);
426 PythonObject py_return = std::move(expected_return_object.get());
429 if (
sizeof...(Args) > 0)
430 if (!ReassignPtrsOrRefsArgs(original_args, transformed_args))
431 return ErrorWithMessage<T>(
433 "couldn't re-assign reference and pointer arguments",
error);
436 return ExtractValueFromPythonObject<T>(py_return,
error);
440 template <
typename T = StructuredData::ObjectSP>
441 T ExtractValueFromPythonObject(python::PythonObject &p, Status &
error) {
442 return p.CreateStructuredObject();
445 template <
typename T = StructuredData::ObjectSP,
typename... Args>
446 T Dispatch(llvm::StringRef method_name, Status &
error, Args &&...args) {
447 using namespace python;
448 using Locker = ScriptInterpreterPythonImpl::Locker;
450 std::string caller_signature =
451 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(
" (") +
452 llvm::Twine(method_name) + llvm::Twine(
")"))
454 if (!m_object_instance_sp)
455 return ErrorWithMessage<T>(caller_signature,
"python object ill-formed",
458 Locker py_lock(&m_interpreter, Locker::AcquireLock | Locker::NoSTDIN,
461 PythonObject implementor(PyRefType::Borrowed,
462 (PyObject *)m_object_instance_sp->GetValue());
464 if (!implementor.IsAllocated())
465 return llvm::is_contained(GetAbstractMethods(), method_name)
466 ? ErrorWithMessage<T>(caller_signature,
467 "python implementor not allocated",
471 std::tuple<Args...> original_args = std::forward_as_tuple(args...);
472 auto transformed_args = TransformArgs(original_args);
474 llvm::Expected<PythonObject> expected_return_object =
475 llvm::make_error<llvm::StringError>(
"Not initialized.",
476 llvm::inconvertibleErrorCode());
478 [&implementor, &method_name, &expected_return_object](
auto &&...args) {
479 llvm::consumeError(expected_return_object.takeError());
480 expected_return_object =
481 implementor.CallMethod(method_name.data(), args...);
485 if (llvm::Error e = expected_return_object.takeError()) {
486 error = Status::FromError(std::move(e));
487 return ErrorWithMessage<T>(caller_signature,
488 "python method could not be called",
error);
491 PythonObject py_return = std::move(expected_return_object.get());
497 if (
sizeof...(Args) > 0)
498 if (!ReassignPtrsOrRefsArgs(original_args, transformed_args))
499 return ErrorWithMessage<T>(
501 "couldn't re-assign reference and pointer arguments",
error);
503 if (!py_return.IsAllocated())
505 return ExtractValueFromPythonObject<T>(py_return,
error);
508 template <
typename... Args>
509 Status GetStatusFromMethod(llvm::StringRef method_name, Args &&...args) {
511 Dispatch<Status>(method_name,
error, std::forward<Args>(args)...);
516 template <
typename T> T Transform(T
object) {
521 python::PythonObject Transform(
bool arg) {
523 return python::PythonBoolean(arg);
526 python::PythonObject Transform(
const Status &arg) {
527 return python::SWIGBridge::ToSWIGWrapper(arg.Clone());
530 python::PythonObject Transform(Status &&arg) {
531 return python::SWIGBridge::ToSWIGWrapper(std::move(arg));
534 python::PythonObject Transform(
const StructuredDataImpl &arg) {
535 return python::SWIGBridge::ToSWIGWrapper(arg);
539 return python::SWIGBridge::ToSWIGWrapper(arg);
543 return python::SWIGBridge::ToSWIGWrapper(arg);
547 return python::SWIGBridge::ToSWIGWrapper(arg);
551 return python::SWIGBridge::ToSWIGWrapper(arg);
555 return python::SWIGBridge::ToSWIGWrapper(arg);
559 return python::SWIGBridge::ToSWIGWrapper(arg);
563 return python::SWIGBridge::ToSWIGWrapper(arg);
567 return python::SWIGBridge::ToSWIGWrapper(arg);
571 return python::SWIGBridge::ToSWIGWrapper(arg);
575 return python::SWIGBridge::ToSWIGWrapper(arg);
578 python::PythonObject Transform(Event *arg) {
579 return python::SWIGBridge::ToSWIGWrapper(arg);
582 python::PythonObject Transform(
const SymbolContext &arg) {
583 return python::SWIGBridge::ToSWIGWrapper(arg);
587 return python::SWIGBridge::ToSWIGWrapper(arg.get());
591 return python::SWIGBridge::ToSWIGWrapper(arg);
595 return python::SWIGBridge::ToSWIGWrapper(arg);
599 return python::SWIGBridge::ToSWIGWrapper(arg);
602 template <
typename T,
typename U>
603 void ReverseTransform(T &original_arg, U transformed_arg, Status &
error) {
607 template <
typename T>
608 void ReverseTransform(T &original_arg, python::PythonObject transformed_arg,
610 original_arg = ExtractValueFromPythonObject<T>(transformed_arg,
error);
613 void ReverseTransform(
bool &original_arg,
614 python::PythonObject transformed_arg, Status &
error) {
615 python::PythonBoolean boolean_arg = python::PythonBoolean(
616 python::PyRefType::Borrowed, transformed_arg.get());
617 if (boolean_arg.IsValid())
618 original_arg = boolean_arg.GetValue();
620 error = Status::FromErrorStringWithFormatv(
621 "{}: Invalid boolean argument.", LLVM_PRETTY_FUNCTION);
624 template <std::size_t... I,
typename... Args>
625 auto TransformTuple(
const std::tuple<Args...> &args,
626 std::index_sequence<I...>) {
627 return std::make_tuple(Transform(std::get<I>(args))...);
632 template <
typename... Args>
633 auto TransformArgs(
const std::tuple<Args...> &args) {
634 return TransformTuple(args, std::make_index_sequence<
sizeof...(Args)>());
637 template <
typename T,
typename U>
638 void TransformBack(T &original_arg, U transformed_arg, Status &
error) {
639 ReverseTransform(original_arg, transformed_arg,
error);
642 template <std::size_t... I,
typename... Ts,
typename... Us>
643 bool ReassignPtrsOrRefsArgs(std::tuple<Ts...> &original_args,
644 std::tuple<Us...> &transformed_args,
645 std::index_sequence<I...>) {
647 (TransformBack(std::get<I>(original_args), std::get<I>(transformed_args),
650 return error.Success();
653 template <
typename... Ts,
typename... Us>
654 bool ReassignPtrsOrRefsArgs(std::tuple<Ts...> &original_args,
655 std::tuple<Us...> &transformed_args) {
656 if (
sizeof...(Ts) !=
sizeof...(Us))
659 return ReassignPtrsOrRefsArgs(original_args, transformed_args,
660 std::make_index_sequence<
sizeof...(Ts)>());
663 template <
typename T,
typename... Args>
664 void FormatArgs(std::string &fmt, T arg, Args... args)
const {
665 FormatArgs(fmt, arg);
666 FormatArgs(fmt, args...);
669 template <
typename T>
void FormatArgs(std::string &fmt, T arg)
const {
670 fmt += python::PythonFormat<T>::format;
673 void FormatArgs(std::string &fmt)
const {}
676 ScriptInterpreterPythonImpl &m_interpreter;
681ScriptedPythonInterface::ExtractValueFromPythonObject<StructuredData::ArraySP>(
686ScriptedPythonInterface::ExtractValueFromPythonObject<
690Status ScriptedPythonInterface::ExtractValueFromPythonObject<Status>(
694Event *ScriptedPythonInterface::ExtractValueFromPythonObject<Event *>(
699ScriptedPythonInterface::ExtractValueFromPythonObject<SymbolContext>(
704ScriptedPythonInterface::ExtractValueFromPythonObject<lldb::StreamSP>(
709ScriptedPythonInterface::ExtractValueFromPythonObject<lldb::ThreadSP>(
714ScriptedPythonInterface::ExtractValueFromPythonObject<lldb::StackFrameSP>(
719ScriptedPythonInterface::ExtractValueFromPythonObject<lldb::BreakpointSP>(
724ScriptedPythonInterface::ExtractValueFromPythonObject<
737ScriptedPythonInterface::ExtractValueFromPythonObject<lldb::DataExtractorSP>(
741std::optional<MemoryRegionInfo>
742ScriptedPythonInterface::ExtractValueFromPythonObject<
743 std::optional<MemoryRegionInfo>>(python::PythonObject &p,
Status &
error);
747ScriptedPythonInterface::ExtractValueFromPythonObject<
752ScriptedPythonInterface::ExtractValueFromPythonObject<lldb::DescriptionLevel>(
757ScriptedPythonInterface::ExtractValueFromPythonObject<lldb::StackFrameListSP>(
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Array > ArraySP
Defines a symbol context baton that can be handed other debug core functions.
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::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::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