LLDB mainline
ScriptedPythonInterface.h
Go to the documentation of this file.
1//===-- ScriptedPythonInterface.h -------------------------------*- C++ -*-===//
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#ifndef LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
10#define LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
11
12#include <optional>
13#include <sstream>
14#include <tuple>
15#include <type_traits>
16#include <utility>
17
21#include "lldb/Utility/Policy.h"
22
24#include "../SWIGPythonBridge.h"
26
27namespace lldb_private {
30public:
32 ~ScriptedPythonInterface() override = default;
33
42
44
52
54 std::variant<std::monostate, InvalidArgumentCountPayload, std::string>
56 };
57
58 llvm::Expected<FileSpec> GetScriptedModulePath() override {
59 using namespace python;
61
64
66 return llvm::createStringError("scripted Interface has invalid object");
67
68 PythonObject py_obj =
69 PythonObject(PyRefType::Borrowed,
70 static_cast<PyObject *>(m_object_instance_sp->GetValue()));
71
72 if (!py_obj.IsAllocated())
73 return llvm::createStringError(
74 "scripted Interface has invalid python object");
75
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");
80
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");
86
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 "
91 "is not a string");
92
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());
98
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());
104
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());
110
111 return FileSpec(py_module_file_str.GetString());
112 }
113
114 llvm::Expected<std::map<llvm::StringLiteral, AbstractMethodCheckerPayload>>
116 const python::PythonObject &obj_class) const {
117
118 using namespace python;
119
120 std::map<llvm::StringLiteral, AbstractMethodCheckerPayload> checker;
121#define SET_CASE_AND_CONTINUE(method_name, case) \
122 { \
123 checker[method_name] = {case, {}}; \
124 continue; \
125 }
126
127 for (const AbstractMethodRequirement &requirement :
129 llvm::StringLiteral method_name = requirement.name;
130 // Look up via attribute access so inherited methods are found; the
131 // class's own __dict__ omits anything defined on a base class.
132 if (!obj_class.HasAttribute(method_name))
133 SET_CASE_AND_CONTINUE(method_name,
135 PythonObject attr = obj_class.GetAttributeValue(method_name);
136 if (!attr.IsAllocated())
137 SET_CASE_AND_CONTINUE(method_name,
139
140 PythonCallable callable = attr.AsType<PythonCallable>();
141 if (!callable)
142 SET_CASE_AND_CONTINUE(method_name,
144
145 if (!requirement.min_arg_count)
147
148 auto arg_info_or_err = callable.GetArgInfo();
149 if (!arg_info_or_err) {
150 checker[method_name] = {
152 ExtractPythonError(arg_info_or_err.takeError())};
153 continue;
154 }
155
156 PythonCallable::ArgInfo arg_info = *arg_info_or_err;
157 if (requirement.min_arg_count <= arg_info.max_positional_args) {
159 } else {
160 checker[method_name] = {
163 requirement.min_arg_count, arg_info.max_positional_args)};
164 }
165 }
166
167#undef SET_CASE_AND_CONTINUE
168
169 return checker;
170 }
171
172 /// Diagnose every abstract-method violation on \a obj_class at once.
173 ///
174 /// \a obj_class is a class object, whether resolved by name or taken from an
175 /// instance's `__class__`. Resolving it by name means this can run before any
176 /// instance exists (see CreatePluginObject), which uses it to reject a
177 /// malformed class without executing its `__init__`.
178 llvm::Error CheckAbstractMethods(const python::PythonObject &obj_class,
179 llvm::StringRef qualified_class_name) const {
180 Log *log = GetLog(LLDBLog::Script);
181
182 // Per-method diagnostics name the class the way Python does, unqualified.
183 python::PythonString obj_class_name =
184 obj_class.GetAttributeValue("__name__").AsType<python::PythonString>();
185 llvm::StringRef class_name = obj_class_name.IsValid()
186 ? obj_class_name.GetString()
187 : qualified_class_name;
188 auto create_error = [](llvm::StringLiteral format, auto &&...ts) {
189 return llvm::createStringError(
190 llvm::formatv(format.data(), std::forward<decltype(ts)>(ts)...)
191 .str());
192 };
193
194 auto checker_or_err = CheckAbstractMethodImplementation(obj_class);
195 if (!checker_or_err)
196 return checker_or_err.takeError();
197
198 llvm::Error abstract_method_errors = llvm::Error::success();
199 for (const auto &method_checker : *checker_or_err)
200 switch (method_checker.second.checker_case) {
202 abstract_method_errors = llvm::joinErrors(
203 std::move(abstract_method_errors),
204 create_error("abstract method {0}.{1} not implemented", class_name,
205 method_checker.first));
206 break;
208 abstract_method_errors = llvm::joinErrors(
209 std::move(abstract_method_errors),
210 create_error("abstract method {0}.{1} not allocated", class_name,
211 method_checker.first));
212 break;
214 abstract_method_errors = llvm::joinErrors(
215 std::move(abstract_method_errors),
216 create_error("abstract method {0}.{1} not callable", class_name,
217 method_checker.first));
218 break;
220 const std::string *py_error =
221 std::get_if<std::string>(&method_checker.second.payload);
222 abstract_method_errors = llvm::joinErrors(
223 std::move(abstract_method_errors),
224 create_error(
225 "abstract method {0}.{1} has unknown argument count: {2}",
226 class_name, method_checker.first,
227 py_error ? *py_error : "<no further information>"));
228 } break;
230 auto &payload_variant = method_checker.second.payload;
231 if (!std::holds_alternative<
233 payload_variant)) {
234 abstract_method_errors = llvm::joinErrors(
235 std::move(abstract_method_errors),
236 create_error(
237 "abstract method {0}.{1} has unexpected argument count",
238 class_name, method_checker.first));
239 } else {
240 auto payload = std::get<
242 payload_variant);
243 abstract_method_errors = llvm::joinErrors(
244 std::move(abstract_method_errors),
245 create_error("abstract method {0}.{1} has unexpected "
246 "argument count (expected {2} but has {3})",
247 class_name, method_checker.first,
248 payload.required_argument_count,
249 payload.actual_argument_count));
250 }
251 } break;
253 LLDB_LOG(log, "Abstract method {0}.{1} implemented & valid.",
254 class_name, method_checker.first);
255 break;
256 }
257
258 if (abstract_method_errors) {
259 Status error = Status::FromError(std::move(abstract_method_errors));
260 LLDB_LOG(log, "Abstract method error in {0}:\n{1}", qualified_class_name,
261 error.AsCString());
262 return error.ToError();
263 }
264
265 return llvm::Error::success();
266 }
267
268 template <typename... Args>
269 llvm::Expected<StructuredData::GenericSP>
270 CreatePluginObject(const ScriptedMetadata &scripted_metadata,
271 StructuredData::Generic *script_obj, Args... args) {
272 using namespace python;
274
275 auto create_error = [](llvm::StringLiteral format, auto &&...ts) {
276 return llvm::createStringError(
277 llvm::formatv(format.data(), std::forward<decltype(ts)>(ts)...)
278 .str());
279 };
280
281 m_scripted_metadata = scripted_metadata;
282 llvm::StringRef class_name = scripted_metadata.GetClassName();
283 bool has_class_name = !class_name.empty();
284 bool has_interpreter_dict =
285 !(llvm::StringRef(m_interpreter.GetDictionaryName()).empty());
286 if (!has_class_name && !has_interpreter_dict && !script_obj) {
287 if (!has_class_name)
288 return create_error("missing script class name");
289 else if (!has_interpreter_dict)
290 return create_error("invalid script interpreter dictionary");
291 else
292 return create_error("missing scripting object");
293 }
294
295 std::optional<PolicyStack::Guard> policy_guard;
296 if (!UserCanRunDirectly())
298
301
302 PythonObject result = {};
303
304 if (script_obj) {
305 result = PythonObject(PyRefType::Borrowed,
306 static_cast<PyObject *>(script_obj->GetValue()));
307 } else {
308 auto dict =
309 PythonModule::MainModule().ResolveName<python::PythonDictionary>(
310 m_interpreter.GetDictionaryName());
311 if (!dict.IsAllocated())
312 return create_error("could not find interpreter dictionary: {0}",
313 m_interpreter.GetDictionaryName());
314
315 auto init =
316 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
317 class_name, dict);
318 if (!init.IsAllocated())
319 return create_error("could not find script class: {0}",
320 class_name.data());
321
322 std::tuple<Args...> original_args = std::forward_as_tuple(args...);
323 auto transformed_args = TransformArgs(original_args);
324
325 std::string error_string;
326 llvm::Expected<PythonCallable::ArgInfo> arg_info = init.GetArgInfo();
327 if (!arg_info) {
328 llvm::handleAllErrors(
329 arg_info.takeError(),
330 [&](PythonException &E) { error_string.append(E.ReadBacktrace()); },
331 [&](const llvm::ErrorInfoBase &E) {
332 error_string.append(E.message());
333 });
334 return llvm::createStringError(llvm::inconvertibleErrorCode(),
335 error_string);
336 }
337
338 if (llvm::Error error = CheckAbstractMethods(init, class_name))
339 return std::move(error);
340
341 llvm::Expected<PythonObject> expected_return_object =
342 create_error("resulting object is not initialized");
343
344 // This relax the requirement on the number of argument for
345 // initializing scripting extension if the size of the interface
346 // parameter pack contains 1 less element than the extension maximum
347 // number of positional arguments for this initializer.
348 //
349 // This addresses the cases where the embedded interpreter session
350 // dictionary is passed to the extension initializer which is not used
351 // most of the time.
352 // Note, though none of our API's suggest defining the interfaces with
353 // varargs, we have some extant clients that were doing that. To keep
354 // from breaking them, we just say putting a varargs in these signatures
355 // turns off argument checking.
356 size_t num_args = sizeof...(Args);
357 if (arg_info->max_positional_args != PythonCallable::ArgInfo::UNBOUNDED &&
358 num_args != arg_info->max_positional_args) {
359 if (num_args != arg_info->max_positional_args - 1) {
360 // `expected_return_object` starts in an error state; consume it
361 // before we return with a different error, or its destructor
362 // will abort.
363 llvm::consumeError(expected_return_object.takeError());
364 return create_error("passed arguments ({0}) doesn't match the number "
365 "of expected arguments ({1})",
366 num_args, arg_info->max_positional_args);
367 }
368
369 std::apply(
370 [&init, &expected_return_object](auto &&...args) {
371 if (!expected_return_object)
372 llvm::consumeError(expected_return_object.takeError());
373 expected_return_object = init.Call(args...);
374 },
375 std::tuple_cat(transformed_args, std::make_tuple(dict)));
376 } else {
377 std::apply(
378 [&init, &expected_return_object](auto &&...args) {
379 if (!expected_return_object)
380 llvm::consumeError(expected_return_object.takeError());
381 expected_return_object = init.Call(args...);
382 },
383 transformed_args);
384 }
385
386 if (!expected_return_object)
387 // Drain the Python exception into a plain string while the GIL is
388 // still held: `PythonException` owns raw `PyObject*` references, and
389 // `py_lock` (and the GIL it holds) is released as this function
390 // returns, before the caller gets a chance to touch the error.
391 return llvm::createStringError(
392 ExtractPythonError(expected_return_object.takeError()));
393 result = expected_return_object.get();
394 }
395
396 if (!result.IsValid())
397 return create_error("resulting object is not a valid Python Object");
398 if (!result.HasAttribute("__class__"))
399 return create_error("resulting object doesn't have '__class__' member");
400
401 PythonObject obj_class = result.GetAttributeValue("__class__");
402 if (!obj_class.IsValid())
403 return create_error("resulting class object is not a valid");
404 if (!obj_class.HasAttribute("__name__"))
405 return create_error(
406 "resulting object class doesn't have '__name__' member");
407 PythonString obj_class_name =
408 obj_class.GetAttributeValue("__name__").AsType<PythonString>();
409
410 // We were handed an instance rather than building one, so there was no
411 // constructor to run the check ahead of; validate it now.
412 if (script_obj)
413 if (llvm::Error error =
414 CheckAbstractMethods(obj_class, obj_class_name.GetString()))
415 return std::move(error);
416
418 new StructuredPythonObject(std::move(result)));
420 }
421
422 /// Call a static method on a Python class without creating an instance.
423 ///
424 /// This method resolves a Python class by name and calls a static method
425 /// on it, returning the result. This is useful for calling class-level
426 /// methods that don't require an instance.
427 ///
428 /// \param class_name The fully-qualified name of the Python class.
429 /// \param method_name The name of the static method to call.
430 /// \param args Arguments to pass to the static method.
431 ///
432 /// \return The return value of the static method call, or an error.
433 template <typename T = StructuredData::ObjectSP, typename... Args>
434 llvm::Expected<T> CallStaticMethod(llvm::StringRef class_name,
435 llvm::StringRef method_name,
436 Args &&...args) {
437 using namespace python;
439
440 std::string caller_signature =
441 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(" (") +
442 llvm::Twine(class_name) + llvm::Twine(".") +
443 llvm::Twine(method_name) + llvm::Twine(")"))
444 .str();
445
446 if (class_name.empty())
447 return LogAndError(caller_signature, "missing script class name");
448
449 std::optional<PolicyStack::Guard> policy_guard;
450 if (!UserCanRunDirectly())
452
455
456 // Get the interpreter dictionary.
457 auto dict =
458 PythonModule::MainModule().ResolveName<python::PythonDictionary>(
459 m_interpreter.GetDictionaryName());
460 if (!dict.IsAllocated())
461 return LogAndError(caller_signature,
462 "could not find interpreter dictionary: {0}",
463 m_interpreter.GetDictionaryName());
464
465 // Resolve the class.
466 auto class_obj =
467 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
468 class_name, dict);
469 if (!class_obj.IsAllocated())
470 return LogAndError(caller_signature, "could not find script class: {0}",
471 class_name);
472
473 // Get the static method from the class.
474 if (!class_obj.HasAttribute(method_name))
475 return llvm::make_error<UnimplementedError>(
476 llvm::formatv("{0}.{1}", class_name, method_name).str());
477
478 PythonCallable method =
479 class_obj.GetAttributeValue(method_name).AsType<PythonCallable>();
480 if (!method.IsAllocated())
481 return LogAndError(caller_signature, "method {0}.{1} is not callable",
482 class_name, method_name);
483
484 // Transform the arguments.
485 std::tuple<Args...> original_args = std::forward_as_tuple(args...);
486 auto transformed_args = TransformArgs(original_args);
487
488 // Call the static method.
489 llvm::Expected<PythonObject> expected_return_object =
490 llvm::createStringError("not initialized");
491 std::apply(
492 [&method, &expected_return_object](auto &&...args) {
493 if (!expected_return_object)
494 llvm::consumeError(expected_return_object.takeError());
495 expected_return_object = method.Call(args...);
496 },
497 transformed_args);
498
499 if (llvm::Error e = expected_return_object.takeError()) {
500 // TODO: Stringify `args` and include them in the message so users
501 // can see what was passed to the failing call (e.g.
502 // `read_memory_at_address(0x500000000, 4)`). Requires a SFINAE
503 // helper that falls back to a placeholder for types without a
504 // format_provider / operator<<.
505 return LogAndError(
506 caller_signature, "python exception in {0} method '{1}': {2}",
507 class_name, method_name, ExtractPythonError(std::move(e)));
508 }
509
510 PythonObject py_return = std::move(expected_return_object.get());
511
512 // Re-assign reference and pointer arguments if needed.
513 if (sizeof...(Args) > 0)
514 if (!ReassignPtrsOrRefsArgs(original_args, transformed_args))
515 return LogAndError(
516 caller_signature,
517 "couldn't re-assign reference and pointer arguments");
518
519 // Extract value from Python object (handles unallocated case).
520 if (!py_return.IsAllocated())
521 return T{};
522 return ExtractValueFromPythonObject<T>(py_return);
523 }
524
525protected:
526 /// Extract detailed error message including Python backtrace if available.
527 ///
528 /// This helper processes llvm::Error objects that may contain PythonException
529 /// instances, extracting full Python backtraces when available.
530 ///
531 /// \param error The llvm::Error to extract information from.
532 /// \return A string containing the error message, including full Python
533 /// backtrace if the error was a PythonException.
534 static std::string ExtractPythonError(llvm::Error error) {
535 std::string error_msg;
536 llvm::handleAllErrors(
537 std::move(error),
538 [&](python::PythonException &E) { error_msg = E.ReadBacktrace(); },
539 [&](const llvm::ErrorInfoBase &E) { error_msg = E.message(); });
540 return error_msg;
541 }
542
543 /// Log \a message against \a caller_name and return it as an error.
544 ///
545 /// The `Expected`-returning counterpart of
546 /// `ScriptedInterface::ErrorWithMessage`: it reports the failure instead of
547 /// folding it into a default-constructed value.
548 template <typename... Ts>
549 static llvm::Error LogAndError(llvm::StringRef caller_name,
550 const char *format, Ts &&...ts) {
551 std::string message = llvm::formatv(format, std::forward<Ts>(ts)...).str();
552 LLDB_LOGF(GetLog(LLDBLog::Script), "%s ERROR = %s", caller_name.data(),
553 message.c_str());
554 return llvm::createStringError(message);
555 }
556
557 /// Log the failure in \a value_or_err and fall back to a default-constructed
558 /// \c T.
559 ///
560 /// For entry points whose return type cannot express failure. Prefer
561 /// propagating the error wherever the signature can carry it; this is the
562 /// stop-gap, and it is at least strictly better than dropping the error.
563 ///
564 /// Logs any failure, an unimplemented method included: a site that dispatches
565 /// with Dispatch() rather than DispatchToOptional() is asserting the method
566 /// should have been there.
567 template <typename T>
568 static T LogAndDefault(llvm::Expected<T> value_or_err,
569 llvm::StringRef caller) {
570 if (value_or_err)
571 return std::move(*value_or_err);
572
573 // Consume the error before logging: LLDB_LOGF doesn't evaluate its
574 // arguments when the channel is disabled, which would leave the error
575 // unchecked and abort.
576 std::string message = llvm::toString(value_or_err.takeError());
577 LLDB_LOGF(GetLog(LLDBLog::Script), "%s failed: %s", caller.str().c_str(),
578 message.c_str());
579 return T{};
580 }
581
582 /// Call an optional \a method_name, reporting "the script doesn't implement
583 /// it" as \c std::nullopt rather than as a failure.
584 ///
585 /// Use this for callbacks a script may legitimately leave out. Any other
586 /// failure - in particular an exception raised inside the method -
587 /// propagates; this never papers over a method that ran and failed.
588 template <typename T = StructuredData::ObjectSP, typename... Args>
589 llvm::Expected<std::optional<T>>
590 DispatchToOptional(llvm::StringRef method_name, Args &&...args) {
591 if (!llvm::is_contained(GetOptionalMethods(), method_name))
592 return LogAndError(
593 LLVM_PRETTY_FUNCTION,
594 "method '{0}' is not declared optional: list it in "
595 "GetOptionalMethods(), or dispatch it with Dispatch(), "
596 "where a missing method is an error",
597 method_name);
598
599 llvm::Expected<T> value_or_err =
600 Dispatch<T>(method_name, std::forward<Args>(args)...);
601 if (value_or_err)
602 return std::move(*value_or_err);
603
604 if (value_or_err.template errorIsA<UnimplementedError>()) {
605 llvm::consumeError(value_or_err.takeError());
606 return std::nullopt;
607 }
608 return value_or_err.takeError();
609 }
610
611 template <typename T = StructuredData::ObjectSP>
613 return p.CreateStructuredObject();
614 }
615
616 /// Call \a method_name on the scripted object.
617 ///
618 /// The returned \c Expected separates the two outcomes that a plain return
619 /// value cannot: a successfully extracted value (which may legitimately be
620 /// empty or null, e.g. when the Python method returns \c None) and a
621 /// failure to call the method at all.
622 ///
623 /// A class that simply doesn't implement \a method_name fails with an
624 /// \c UnimplementedError, so callers of optional callbacks can recognize
625 /// and ignore that case without also swallowing real exceptions.
626 template <typename T = StructuredData::ObjectSP, typename... Args>
627 llvm::Expected<T> Dispatch(llvm::StringRef method_name, Args &&...args) {
628 using namespace python;
630
631 std::string caller_signature =
632 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(" (") +
633 llvm::Twine(method_name) + llvm::Twine(")"))
634 .str();
636 return LogAndError(caller_signature, "python object ill-formed");
637
638 std::optional<PolicyStack::Guard> policy_guard;
639 if (!UserCanRunDirectly())
641
644
645 PythonObject implementor(PyRefType::Borrowed,
646 (PyObject *)m_object_instance_sp->GetValue());
647
648 if (!implementor.IsAllocated())
649 return LogAndError(caller_signature, "python implementor not allocated");
650
651 PythonObject py_method = implementor.GetAttributeValue(method_name);
652 if (!py_method.IsAllocated())
653 return llvm::make_error<UnimplementedError>(
654 llvm::formatv("{0}.{1}",
656 ? GetScriptedMetadata()->GetClassName()
657 : "<unknown>",
658 method_name)
659 .str());
660
661 std::tuple<Args...> original_args = std::forward_as_tuple(args...);
662 auto transformed_args = TransformArgs(original_args);
663
664 // Trim trailing args if the Python method accepts fewer positional
665 // parameters than we're passing (e.g. `num_children(self)` vs.
666 // `num_children(self, max_count)`).
667 size_t call_arity = sizeof...(Args);
668 if (PythonCallable callable = py_method.AsType<PythonCallable>();
669 callable.IsAllocated()) {
670 if (llvm::Expected<PythonCallable::ArgInfo> arg_info =
671 callable.GetArgInfo()) {
672 if (arg_info->max_positional_args !=
673 PythonCallable::ArgInfo::UNBOUNDED &&
674 arg_info->max_positional_args < call_arity)
675 call_arity = arg_info->max_positional_args;
676 } else {
677 llvm::consumeError(arg_info.takeError());
678 }
679 }
680
681 llvm::Expected<PythonObject> expected_return_object =
682 llvm::createStringError("not initialized");
683 CallWithArity(call_arity, transformed_args,
684 std::make_index_sequence<sizeof...(Args) + 1>{},
685 [&implementor, &method_name,
686 &expected_return_object](auto &&...call_args) {
687 if (!expected_return_object)
688 llvm::consumeError(expected_return_object.takeError());
689 expected_return_object = implementor.CallMethod(
690 method_name.data(), call_args...);
691 });
692
693 if (llvm::Error e = expected_return_object.takeError()) {
694 // TODO: Stringify `args` and include them in the message so users
695 // can see what was passed to the failing call (e.g.
696 // `read_memory_at_address(0x500000000, 4)`). Requires a SFINAE
697 // helper that falls back to a placeholder for types without a
698 // format_provider / operator<<.
699 //
700 // Drain the Python exception into a plain string while the GIL is
701 // still held: `PythonException` owns raw `PyObject*` references, and
702 // `py_lock` is released as this function returns.
703 return LogAndError(
704 caller_signature, "python exception in {0} method '{1}': {2}",
705 GetScriptedMetadata() ? GetScriptedMetadata()->GetClassName()
706 : "<unknown>",
707 method_name, ExtractPythonError(std::move(e)));
708 }
709
710 PythonObject py_return = std::move(expected_return_object.get());
711
712 // Now that we called the python method with the transformed arguments,
713 // we need to iterate again over both the original and transformed
714 // parameter pack, and transform back the parameter that were passed in
715 // the original parameter pack as references or pointers.
716 if (sizeof...(Args) > 0)
717 if (!ReassignPtrsOrRefsArgs(original_args, transformed_args))
718 return LogAndError(
719 caller_signature,
720 "couldn't re-assign reference and pointer arguments");
721
722 if (!py_return.IsAllocated())
723 return T{};
724 return ExtractValueFromPythonObject<T>(py_return);
725 }
726
727 /// Call \a method_name and fold both failure channels into one `Status`:
728 /// a failure to call the method at all, and the `SBError` the method
729 /// returned. The latter used to be dropped on the floor.
730 template <typename... Args>
731 Status GetStatusFromMethod(llvm::StringRef method_name, Args &&...args) {
732 llvm::Expected<Status> status_or_err =
733 Dispatch<Status>(method_name, std::forward<Args>(args)...);
734 if (!status_or_err)
735 return Status::FromError(status_or_err.takeError());
736
737 return std::move(*status_or_err);
738 }
739
740 template <typename T> T Transform(T object) {
741 // No Transformation for generic usage
742 return {object};
743 }
744
746 // Boolean arguments need to be turned into python objects.
747 return python::PythonBoolean(arg);
748 }
749
753
755 return python::SWIGBridge::ToSWIGWrapper(std::move(arg));
756 }
757
761
762 template <typename T, typename = std::enable_if_t<
763 std::is_base_of_v<StructuredData::Object, T>>>
764 python::PythonObject Transform(std::shared_ptr<T> arg) {
765 return Transform(StructuredDataImpl(arg));
766 }
767
771
775
779
783
787
791
795
799
803
807
811
815
819
823
827
831
835
839
843
844 python::PythonObject Transform(const std::vector<std::string> &arg) {
846 for (const std::string &s : arg)
848 return list;
849 }
850
855
859
860 template <typename T, typename U>
861 void ReverseTransform(T &original_arg, U transformed_arg, Status &error) {
862 // If U is not a PythonObject, don't touch it!
863 }
864
865 template <typename T>
866 void ReverseTransform(T &original_arg, python::PythonObject transformed_arg,
867 Status &error) {
868 llvm::Expected<T> value_or_err =
869 ExtractValueFromPythonObject<T>(transformed_arg);
870 if (!value_or_err) {
871 error = Status::FromError(value_or_err.takeError());
872 return;
873 }
874 original_arg = std::move(*value_or_err);
875 }
876
877 // Read-only arguments (passed as `const T&`) have nothing to write back:
878 // there's no `T` value to reassign into a const reference, and no
879 // `ExtractValueFromPythonObject<T>` specialization should be required just
880 // to satisfy this round-trip for a value the callee never mutates.
881 template <typename T>
882 void ReverseTransform(const T &original_arg,
883 python::PythonObject transformed_arg, Status &error) {}
884
885 void ReverseTransform(bool &original_arg,
886 python::PythonObject transformed_arg, Status &error) {
888 python::PyRefType::Borrowed, transformed_arg.get());
889 if (boolean_arg.IsValid())
890 original_arg = boolean_arg.GetValue();
891 else
893 "{}: Invalid boolean argument.", LLVM_PRETTY_FUNCTION);
894 }
895
896 template <std::size_t... I, typename... Args>
897 auto TransformTuple(const std::tuple<Args...> &args,
898 std::index_sequence<I...>) {
899 return std::make_tuple(Transform(std::get<I>(args))...);
900 }
901
902 // This will iterate over the Dispatch parameter pack and replace in-place
903 // every `lldb_private` argument that has a SB counterpart.
904 template <typename... Args>
905 auto TransformArgs(const std::tuple<Args...> &args) {
906 return TransformTuple(args, std::make_index_sequence<sizeof...(Args)>());
907 }
908
909 // Apply `fn` with the first `N` elements of `t`, for compile-time `N`.
910 template <std::size_t N, typename Tuple, typename Fn, std::size_t... I>
911 static void ApplyPrefixImpl(Tuple &&t, Fn &&fn, std::index_sequence<I...>) {
912 std::forward<Fn>(fn)(std::get<I>(std::forward<Tuple>(t))...);
913 }
914
915 template <std::size_t N, typename Tuple, typename Fn>
916 static void ApplyPrefix(Tuple &&t, Fn &&fn) {
917 ApplyPrefixImpl<N>(std::forward<Tuple>(t), std::forward<Fn>(fn),
918 std::make_index_sequence<N>{});
919 }
920
921 // Call `fn` with a runtime-selected prefix of `t`: exactly `call_arity`
922 // leading elements. `Is...` enumerates every compile-time count in
923 // `[0, sizeof...(Args)]`; the runtime check picks the matching one.
924 template <typename Tuple, std::size_t... Is, typename Fn>
925 static void CallWithArity(size_t call_arity, Tuple &&t,
926 std::index_sequence<Is...>, Fn &&fn) {
927 (void)std::initializer_list<int>{(
928 Is == call_arity
929 ? (ApplyPrefix<Is>(std::forward<Tuple>(t), std::forward<Fn>(fn)), 0)
930 : 0)...};
931 }
932
933 template <typename T, typename U>
934 void TransformBack(T &original_arg, U transformed_arg, Status &error) {
935 ReverseTransform(original_arg, transformed_arg, error);
936 }
937
938 // ScopedPythonObject is non-copyable — passing it through the generic
939 // TransformBack would trigger the deleted copy ctor. It manages its own
940 // cleanup via the destructor when the transformed-args tuple destructs, so
941 // there is nothing to reverse-transform back into the original arg.
942 template <typename T, typename SB>
943 void TransformBack(T &original_arg,
944 python::ScopedPythonObject<SB> &transformed_arg,
945 Status &error) {}
946
947 template <std::size_t... I, typename... Ts, typename... Us>
948 bool ReassignPtrsOrRefsArgs(std::tuple<Ts...> &original_args,
949 std::tuple<Us...> &transformed_args,
950 std::index_sequence<I...>) {
952 (TransformBack(std::get<I>(original_args), std::get<I>(transformed_args),
953 error),
954 ...);
955 return error.Success();
956 }
957
958 template <typename... Ts, typename... Us>
959 bool ReassignPtrsOrRefsArgs(std::tuple<Ts...> &original_args,
960 std::tuple<Us...> &transformed_args) {
961 if (sizeof...(Ts) != sizeof...(Us))
962 return false;
963
964 return ReassignPtrsOrRefsArgs(original_args, transformed_args,
965 std::make_index_sequence<sizeof...(Ts)>());
966 }
967
968 template <typename T, typename... Args>
969 void FormatArgs(std::string &fmt, T arg, Args... args) const {
970 FormatArgs(fmt, arg);
971 FormatArgs(fmt, args...);
972 }
973
974 template <typename T> void FormatArgs(std::string &fmt, T arg) const {
976 }
977
978 void FormatArgs(std::string &fmt) const {}
979
980 // The lifetime is managed by the ScriptInterpreter
982};
983
984template <>
985llvm::Expected<StructuredData::ArraySP>
988
989template <>
990llvm::Expected<StructuredData::DictionarySP>
993
994template <>
995llvm::Expected<Status>
998
999template <>
1000llvm::Expected<Event *>
1003
1004template <>
1005llvm::Expected<SymbolContext>
1008
1009template <>
1010llvm::Expected<lldb::StreamSP>
1013
1014template <>
1015llvm::Expected<lldb::ThreadSP>
1018
1019template <>
1020llvm::Expected<lldb::StackFrameSP>
1023
1024template <>
1025llvm::Expected<lldb::BreakpointSP>
1028
1029template <>
1030llvm::Expected<lldb::BreakpointLocationSP>
1033
1034template <>
1035llvm::Expected<lldb::ProcessAttachInfoSP>
1038
1039template <>
1040llvm::Expected<lldb::ProcessLaunchInfoSP>
1043
1044template <>
1045llvm::Expected<lldb::DataExtractorSP>
1048
1049template <>
1050llvm::Expected<lldb::ThreadPlanSP>
1053
1054template <>
1055llvm::Expected<std::optional<MemoryRegionInfo>>
1057 std::optional<MemoryRegionInfo>>(python::PythonObject &p);
1058
1059template <>
1060llvm::Expected<lldb::ExecutionContextRefSP>
1063
1064template <>
1065llvm::Expected<lldb::DescriptionLevel>
1068
1069template <>
1070llvm::Expected<lldb::StepType>
1073
1074template <>
1075llvm::Expected<lldb::StackFrameListSP>
1078
1079template <>
1080llvm::Expected<lldb::ValueObjectSP>
1083
1084template <>
1085llvm::Expected<lldb::TargetSP>
1088
1089template <>
1090llvm::Expected<lldb::ValueObjectListSP>
1093
1094template <>
1095llvm::Expected<std::optional<lldb::ValueType>>
1097 std::optional<lldb::ValueType>>(python::PythonObject &p);
1098
1099template <>
1100llvm::Expected<lldb::DebuggerSP>
1103
1104template <>
1105llvm::Expected<std::vector<std::string>>
1108
1109} // namespace lldb_private
1110
1111#endif // LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
ScriptInterpreterPythonImpl::Locker Locker
#define SET_CASE_AND_CONTINUE(method_name, case)
A command line argument class.
Definition Args.h:33
A file utility class.
Definition FileSpec.h:56
Guard PushScriptedExtensionCall()
Definition Policy.h:145
static PolicyStack & Get()
Definition Policy.cpp:21
std::optional< ScriptedMetadata > m_scripted_metadata
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.
virtual llvm::SmallVector< llvm::StringLiteral > GetOptionalMethods() const
Methods a script may legitimately leave out, for which LLDB has a documented answer.
const std::optional< ScriptedMetadata > & GetScriptedMetadata() const
StructuredData::GenericSP m_object_instance_sp
llvm::StringRef GetClassName() const
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)
Call method_name and fold both failure channels into one Status: a failure to call the method at all,...
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)
python::PythonObject Transform(lldb::StepType arg)
auto TransformArgs(const std::tuple< Args... > &args)
python::PythonObject Transform(lldb::ExecutionContextRefSP arg)
python::PythonObject Transform(lldb::ThreadSP arg)
static T LogAndDefault(llvm::Expected< T > value_or_err, llvm::StringRef caller)
Log the failure in value_or_err and fall back to a default-constructed T.
python::PythonObject Transform(const StructuredDataImpl &arg)
llvm::Expected< T > ExtractValueFromPythonObject(python::PythonObject &p)
llvm::Error CheckAbstractMethods(const python::PythonObject &obj_class, llvm::StringRef qualified_class_name) const
Diagnose every abstract-method violation on obj_class at once.
~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)
llvm::Expected< T > CallStaticMethod(llvm::StringRef class_name, llvm::StringRef method_name, Args &&...args)
Call a static method on a Python class without creating an instance.
static llvm::Error LogAndError(llvm::StringRef caller_name, const char *format, Ts &&...ts)
Log message against caller_name and return it as an error.
llvm::Expected< T > Dispatch(llvm::StringRef method_name, Args &&...args)
Call method_name on the scripted object.
llvm::Expected< std::optional< T > > DispatchToOptional(llvm::StringRef method_name, Args &&...args)
Call an optional method_name, reporting "the script doesn't implementit" as std::nullopt rather than ...
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... >)
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)
An error handling class.
Definition Status.h:118
Status Clone() const
Don't call this function in new code.
Definition Status.h:174
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
std::shared_ptr< Generic > GenericSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
Defines a symbol context baton that can be handed other debug core functions.
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.
Definition Log.h:338
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::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
std::variant< std::monostate, InvalidArgumentCountPayload, std::string > payload