forked from upstream-mirrors/OrcaSlicer
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 13824091a4 |
@@ -484,6 +484,7 @@ thread_local std::string PluginAuditManager::m_current_capability_name = "";
|
||||
thread_local std::vector<AllowedRoot> PluginAuditManager::m_scoped_allowed_roots;
|
||||
thread_local std::vector<PyObject*> PluginAuditManager::m_root_frames;
|
||||
thread_local int PluginAuditManager::m_releasing_frames = 0;
|
||||
thread_local int PluginAuditManager::m_prompt_suppression_depth = 0;
|
||||
thread_local bool PluginAuditManager::m_audit_denial_pending = false;
|
||||
thread_local bool PluginAuditManager::m_has_last_violation = false;
|
||||
thread_local AuditViolation PluginAuditManager::m_last_violation;
|
||||
@@ -508,9 +509,8 @@ ScopedPluginAuditContext::~ScopedPluginAuditContext()
|
||||
PluginAuditManager& mgr = PluginAuditManager::instance();
|
||||
|
||||
// Let this scope's root frames go while it is still the current context, and as its own
|
||||
// plugin: the trampoline's denial path clears the key before the scope ends, and a finalizer
|
||||
// must never be judged as the outer plugin, or bypass the audit when there is none. A
|
||||
// finalizer may record a new root frame, so repeat until none is held.
|
||||
// plugin: a finalizer must never be judged as an outer plugin, or bypass the audit when there
|
||||
// is none. A finalizer may record a new root frame, so repeat until none is held.
|
||||
if (!PluginAuditManager::m_root_frames.empty()) {
|
||||
assert(PyGILState_Check());
|
||||
mgr.set_current_plugin(m_plugin_key);
|
||||
@@ -528,6 +528,35 @@ ScopedPluginAuditContext::~ScopedPluginAuditContext()
|
||||
PluginAuditManager::m_root_frames = std::move(m_previous_root_frames);
|
||||
}
|
||||
|
||||
bool PluginAuditManager::prompts_suppressed() const
|
||||
{
|
||||
return m_prompt_suppression_depth > 0;
|
||||
}
|
||||
|
||||
ScopedPluginAuditPromptSuppression::ScopedPluginAuditPromptSuppression()
|
||||
{
|
||||
++PluginAuditManager::m_prompt_suppression_depth;
|
||||
}
|
||||
|
||||
ScopedPluginAuditPromptSuppression::~ScopedPluginAuditPromptSuppression()
|
||||
{
|
||||
--PluginAuditManager::m_prompt_suppression_depth;
|
||||
}
|
||||
|
||||
ScopedPluginAuditDenialState::ScopedPluginAuditDenialState()
|
||||
: m_pending(PluginAuditManager::m_audit_denial_pending)
|
||||
, m_has_violation(PluginAuditManager::m_has_last_violation)
|
||||
, m_violation(PluginAuditManager::m_last_violation)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedPluginAuditDenialState::~ScopedPluginAuditDenialState()
|
||||
{
|
||||
PluginAuditManager::m_audit_denial_pending = m_pending;
|
||||
PluginAuditManager::m_has_last_violation = m_has_violation;
|
||||
PluginAuditManager::m_last_violation = m_violation;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PluginAuditManager
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1375,6 +1404,7 @@ void persist_grant(const std::string& plugin_key, AuditEventCategory category, b
|
||||
}
|
||||
|
||||
static PluginAuditManager::PermissionPrompt s_permission_prompt_for_testing;
|
||||
static PluginAuditManager::PermissionPromptDispatch s_permission_prompt_dispatch_for_testing;
|
||||
static PluginAuditManager::PermissionMessagePrompt s_permission_message_prompt_for_testing;
|
||||
|
||||
static const char* audit_category_name(AuditEventCategory category)
|
||||
@@ -1421,6 +1451,23 @@ bool request_permission(AuditEventCategory category, const std::string& plugin_k
|
||||
<< " category=" << audit_category_name(category) << " targets=[" << targets_text << "]"
|
||||
<< (by_event && !keys.empty() ? " grant=" + keys.front() : std::string{});
|
||||
|
||||
// The same ask-and-persist body production posts to the GUI thread. The dispatch seam below
|
||||
// hands tests this callback so they can run it later, after the denied event has returned.
|
||||
auto ask_and_persist = [category, plugin_key, plugin_name, event_name, by_event, keys, shown]() {
|
||||
bool granted = false;
|
||||
if (s_permission_prompt_for_testing)
|
||||
granted = s_permission_prompt_for_testing(event_name, shown);
|
||||
else if (wxTheApp != nullptr && !GUI::wxGetApp().is_closing())
|
||||
granted = prompt_for_targets(category, plugin_name, event_name, shown);
|
||||
if (granted)
|
||||
persist_grant(plugin_key, category, by_event, keys);
|
||||
};
|
||||
|
||||
if (s_permission_prompt_dispatch_for_testing) {
|
||||
s_permission_prompt_dispatch_for_testing(ask_and_persist);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (s_permission_prompt_for_testing)
|
||||
return s_permission_prompt_for_testing(event_name, shown);
|
||||
|
||||
@@ -1430,12 +1477,7 @@ bool request_permission(AuditEventCategory category, const std::string& plugin_k
|
||||
if (wxIsMainThread())
|
||||
return prompt_for_targets(category, plugin_name, event_name, shown);
|
||||
|
||||
GUI::wxGetApp().CallAfter([category, plugin_key, plugin_name, event_name, by_event, keys, shown]() {
|
||||
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
|
||||
return;
|
||||
if (prompt_for_targets(category, plugin_name, event_name, shown))
|
||||
persist_grant(plugin_key, category, by_event, keys);
|
||||
});
|
||||
GUI::wxGetApp().CallAfter(ask_and_persist);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1471,8 +1513,10 @@ int decide_audited_event(PluginAuditManager& mgr,
|
||||
}
|
||||
|
||||
// Letting a root frame go runs finalizers inside a scope destructor or another event's hook,
|
||||
// where no dialog may open: what they do must already be granted.
|
||||
if (mgr.releasing_frames())
|
||||
// where no dialog may open: what they do must already be granted. The same fail-closed rule
|
||||
// applies while deterministic cleanup releases plugin-owned objects or formats a plugin
|
||||
// exception: saved grants still allow the operation, but nothing may prompt recursively.
|
||||
if (mgr.releasing_frames() || mgr.prompts_suppressed())
|
||||
return report_denied(mgr, event_name, {false, "audit permission required"});
|
||||
|
||||
if (!request_permission(category, plugin_key, plugin_name, event_name, by_event, unresolved))
|
||||
@@ -1756,6 +1800,11 @@ void PluginAuditManager::set_permission_prompt_for_testing(PermissionPrompt prom
|
||||
PluginAuditDetail::s_permission_prompt_for_testing = std::move(prompt);
|
||||
}
|
||||
|
||||
void PluginAuditManager::set_permission_prompt_dispatch_for_testing(PermissionPromptDispatch dispatch)
|
||||
{
|
||||
PluginAuditDetail::s_permission_prompt_dispatch_for_testing = std::move(dispatch);
|
||||
}
|
||||
|
||||
void PluginAuditManager::set_permission_message_prompt_for_testing(PermissionMessagePrompt prompt)
|
||||
{
|
||||
PluginAuditDetail::s_permission_message_prompt_for_testing = std::move(prompt);
|
||||
|
||||
@@ -209,6 +209,11 @@ public:
|
||||
bool covered_by_root_frame() const;
|
||||
bool releasing_frames() const;
|
||||
|
||||
// True while deterministic cleanup is releasing plugin-owned objects or formatting a plugin
|
||||
// exception. Audited operations still run and saved grants still apply, but an un-granted one
|
||||
// is denied without opening a permission prompt.
|
||||
bool prompts_suppressed() const;
|
||||
|
||||
// True when code from `filename` (a code object's co_filename) is the interpreter's own
|
||||
// stdlib: the only code a root frame's coverage passes through. Valid after install_hook().
|
||||
static bool is_stdlib_file(const std::string& filename);
|
||||
@@ -217,6 +222,15 @@ public:
|
||||
using PermissionPrompt = std::function<bool(const std::string& event_name, const std::vector<std::string>& targets)>;
|
||||
static void set_permission_prompt_for_testing(PermissionPrompt prompt);
|
||||
|
||||
// Test-only dispatch for audited-event prompts. When set, request_permission() hands it the
|
||||
// same ask-and-persist callback production would post to the GUI thread, then returns false
|
||||
// (the event is denied now, as on production's worker path). The test runs the callback when
|
||||
// it wants to simulate the user answering later; the callback uses the synchronous
|
||||
// PermissionPrompt above when one is installed, otherwise it asks through the normal dialog
|
||||
// path. Leave unset in production. Setting nullptr restores the synchronous behavior.
|
||||
using PermissionPromptDispatch = std::function<void(std::function<void()> prompt_and_persist)>;
|
||||
static void set_permission_prompt_dispatch_for_testing(PermissionPromptDispatch dispatch);
|
||||
|
||||
// Answers the combined permission-request prompt in place of the dialog, receiving the message
|
||||
// it would show. Tests run without a wxApp, so this seam also stands in for the app check.
|
||||
// Production never sets it.
|
||||
@@ -227,6 +241,8 @@ public:
|
||||
|
||||
private:
|
||||
friend class ScopedPluginAuditContext;
|
||||
friend class ScopedPluginAuditPromptSuppression;
|
||||
friend class ScopedPluginAuditDenialState;
|
||||
|
||||
PluginAuditManager() = default;
|
||||
|
||||
@@ -245,6 +261,7 @@ private:
|
||||
static thread_local std::vector<AllowedRoot> m_scoped_allowed_roots;
|
||||
static thread_local std::vector<PyObject*> m_root_frames; // strong references
|
||||
static thread_local int m_releasing_frames;
|
||||
static thread_local int m_prompt_suppression_depth;
|
||||
static thread_local bool m_audit_denial_pending;
|
||||
static thread_local bool m_has_last_violation;
|
||||
static thread_local AuditViolation m_last_violation;
|
||||
@@ -285,6 +302,38 @@ private:
|
||||
std::vector<PyObject*> m_previous_root_frames;
|
||||
};
|
||||
|
||||
// RAII guard for deterministic host cleanup that may execute plugin finalizers or plugin-authored
|
||||
// exception formatting. While active, audited operations still run as the current plugin and
|
||||
// saved grants still apply, but an un-granted operation is denied fail-closed without opening a
|
||||
// permission prompt. Nesting is supported and does not require the GIL.
|
||||
class ScopedPluginAuditPromptSuppression
|
||||
{
|
||||
public:
|
||||
ScopedPluginAuditPromptSuppression();
|
||||
~ScopedPluginAuditPromptSuppression();
|
||||
|
||||
ScopedPluginAuditPromptSuppression(const ScopedPluginAuditPromptSuppression&) = delete;
|
||||
ScopedPluginAuditPromptSuppression& operator=(const ScopedPluginAuditPromptSuppression&) = delete;
|
||||
};
|
||||
|
||||
// RAII snapshot of the pending-denial flag and last violation. Formatting a plugin exception may
|
||||
// itself trigger a denied operation; that violation is reported and denied, but must not replace
|
||||
// the state of the error being reported. Restores the snapshot on scope exit.
|
||||
class ScopedPluginAuditDenialState
|
||||
{
|
||||
public:
|
||||
ScopedPluginAuditDenialState();
|
||||
~ScopedPluginAuditDenialState();
|
||||
|
||||
ScopedPluginAuditDenialState(const ScopedPluginAuditDenialState&) = delete;
|
||||
ScopedPluginAuditDenialState& operator=(const ScopedPluginAuditDenialState&) = delete;
|
||||
|
||||
private:
|
||||
bool m_pending;
|
||||
bool m_has_violation;
|
||||
AuditViolation m_violation;
|
||||
};
|
||||
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif // slic3r_PluginAuditManager_hpp_
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "slic3r/GUI/format.hpp"
|
||||
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <pybind11/pytypes.h>
|
||||
|
||||
#include <exception>
|
||||
#include <cstddef>
|
||||
@@ -111,6 +112,13 @@ void install_slicing_pipeline_hook()
|
||||
r = cap->execute(ctx);
|
||||
} catch (const CanceledException&) {
|
||||
throw; // cancellation must reach process(), never become a slicing error
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
// A Python raise reaches here as pybind11::error_already_set; surface it as a
|
||||
// (non-critical) slicing error instead of a crash. Format it under the
|
||||
// capability's audit scope and with the GIL, which the trampoline released.
|
||||
throw SlicingError(GUI::format(_u8L("Slicing pipeline plugin '%1%' error: %2%"),
|
||||
ref.capability_name,
|
||||
python_exception_text(err, cap->audit_plugin_key(), cap->name())));
|
||||
} catch (const std::exception& ex) {
|
||||
// A Python raise reaches here as pybind11::error_already_set; surface it as a
|
||||
// (non-critical) slicing error instead of a crash.
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// service header stays free of the manager.
|
||||
#include "PluginManager.hpp"
|
||||
|
||||
#include "PluginAuditManager.hpp"
|
||||
#include "PluginConfig.hpp"
|
||||
#include "PluginFsUtils.hpp"
|
||||
#include "PythonInterpreter.hpp"
|
||||
@@ -23,6 +24,7 @@
|
||||
#include <boost/filesystem/directory.hpp>
|
||||
#include <boost/filesystem/file_status.hpp>
|
||||
#include <boost/log/trivial.hpp>
|
||||
#include <pybind11/pytypes.h>
|
||||
#include <slic3r/Utils/BoostProcessCompat.hpp>
|
||||
#include "slic3r/plugin/PluginDescriptor.hpp"
|
||||
#include <optional>
|
||||
@@ -116,7 +118,9 @@ bool read_local_plugin_package_metadata(const boost::filesystem::path& source_pa
|
||||
// on_unload() the first `lifecycle_count` capabilities — the ones that actually got on_load() —
|
||||
// then drop them all.
|
||||
//
|
||||
void teardown_capabilities(std::vector<std::shared_ptr<PluginCapabilityInterface>>& capabilities, std::size_t lifecycle_count)
|
||||
void teardown_capabilities(std::vector<std::shared_ptr<PluginCapabilityInterface>>& capabilities,
|
||||
std::size_t lifecycle_count,
|
||||
const std::string& plugin_key)
|
||||
{
|
||||
if (capabilities.empty())
|
||||
return;
|
||||
@@ -139,13 +143,19 @@ void teardown_capabilities(std::vector<std::shared_ptr<PluginCapabilityInterface
|
||||
continue;
|
||||
try {
|
||||
capability->on_unload();
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Plugin on_unload failed: "
|
||||
<< python_exception_text(err, capability->audit_plugin_key(), capability->name());
|
||||
} catch (const std::exception& ex) {
|
||||
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Plugin on_unload failed: " << ex.what();
|
||||
} catch (...) {
|
||||
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Plugin on_unload failed";
|
||||
}
|
||||
}
|
||||
capabilities.clear();
|
||||
|
||||
// Capability finalizers run as the owning plugin. The GIL is already held here, and each
|
||||
// handle still sees its module alive because release_module() runs afterwards.
|
||||
release_capabilities_under_audit(capabilities, plugin_key);
|
||||
}
|
||||
|
||||
// Add every .whl sitting next to the plugin entry file to sys.path, extracting it first.
|
||||
@@ -220,7 +230,7 @@ void unload(Plugin& plugin)
|
||||
{
|
||||
// Dropping the capabilities drops their state with them; the user's enable choices survive in
|
||||
// the .install_state.json sidecar, which the next load seeds from.
|
||||
teardown_capabilities(plugin.capabilities, plugin.capabilities.size());
|
||||
teardown_capabilities(plugin.capabilities, plugin.capabilities.size(), plugin.descriptor.plugin_key);
|
||||
plugin.release_module();
|
||||
}
|
||||
|
||||
@@ -284,7 +294,21 @@ bool load(const PluginDescriptor& descriptor,
|
||||
}
|
||||
|
||||
std::string load_error;
|
||||
PyObject* module = import_plugin_module(descriptor, plugin.plugin_sys_paths, plugin.plugin_modules, load_error);
|
||||
PyObject* module = nullptr;
|
||||
{
|
||||
// The import runs the plugin's module-level code, so its audited operations belong to
|
||||
// the plugin. The GIL is held here (the interpreter call reacquires it reentrantly),
|
||||
// which lets the scope release any operation root frames it recorded before it ends.
|
||||
PythonGILState gil;
|
||||
if (!gil) {
|
||||
bridge.cancel_plugin_capture(descriptor.entry_path);
|
||||
error = _u8L("Python interpreter is shutting down");
|
||||
return false;
|
||||
}
|
||||
|
||||
ScopedPluginAuditContext audit_scope(descriptor.plugin_key);
|
||||
module = import_plugin_module(descriptor, plugin.plugin_sys_paths, plugin.plugin_modules, load_error);
|
||||
}
|
||||
if (module == nullptr) {
|
||||
bridge.cancel_plugin_capture(descriptor.entry_path);
|
||||
error = GUI::format(_u8L("Failed to load plugin module: %1%"), load_error);
|
||||
@@ -332,6 +356,10 @@ bool load(const PluginDescriptor& descriptor,
|
||||
if (!gil) {
|
||||
materialization_error = "Python interpreter is shutting down";
|
||||
} else {
|
||||
// The whole materialization pass runs plugin-authored code (get_type and the optional
|
||||
// config-UI/texture hooks) and owns the partially materialized capability list. One
|
||||
// scope covers both those calls and the destruction of anything left on failure.
|
||||
ScopedPluginAuditContext materialization_scope(descriptor.plugin_key);
|
||||
try {
|
||||
for (auto& found : capabilities_found) {
|
||||
if (!found.instance) {
|
||||
@@ -340,7 +368,15 @@ bool load(const PluginDescriptor& descriptor,
|
||||
}
|
||||
|
||||
std::shared_ptr<PluginCapabilityInterface> instance = std::move(found.instance);
|
||||
const PluginCapabilityType type = instance->get_type();
|
||||
|
||||
// Publish the owner before get_type(): the trampoline then opens (and, on a
|
||||
// denial, clears) its own inner scope, leaving the materialization scope that
|
||||
// still owns this instance's cleanup intact.
|
||||
instance->set_audit_plugin_key(descriptor.plugin_key);
|
||||
|
||||
// get_type() is plugin-authored and is called before the capability's identity
|
||||
// is resolved below.
|
||||
PluginCapabilityType type = instance->get_type();
|
||||
|
||||
// An empty request restores the sidecar state (or enables capabilities by
|
||||
// default). An explicit request overrides the sidecar for that capability;
|
||||
@@ -365,7 +401,6 @@ bool load(const PluginDescriptor& descriptor,
|
||||
break;
|
||||
}
|
||||
|
||||
instance->set_audit_plugin_key(descriptor.plugin_key);
|
||||
instance->set_resolved_identity(found.name, type);
|
||||
instance->set_enabled(enabled);
|
||||
|
||||
@@ -375,6 +410,13 @@ bool load(const PluginDescriptor& descriptor,
|
||||
// capability its custom UI, so it is caught locally rather than failing the load.
|
||||
try {
|
||||
instance->set_config_ui_available(instance->has_config_ui());
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
BOOST_LOG_TRIVIAL(warning)
|
||||
<< "Plugin capability '" << found.name << "' of plugin '" << descriptor.plugin_key
|
||||
<< "': has_config_ui() failed ("
|
||||
<< python_exception_text(err, instance->audit_plugin_key(), instance->name())
|
||||
<< "); falling back to the default JSON editor";
|
||||
instance->set_config_ui_available(false);
|
||||
} catch (const std::exception& ex) {
|
||||
BOOST_LOG_TRIVIAL(warning)
|
||||
<< "Plugin capability '" << found.name << "' of plugin '" << descriptor.plugin_key
|
||||
@@ -404,6 +446,13 @@ bool load(const PluginDescriptor& descriptor,
|
||||
resource_texture->set_texture_dir({});
|
||||
}
|
||||
}
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
BOOST_LOG_TRIVIAL(warning)
|
||||
<< "Plugin capability '" << found.name << "' of plugin '" << descriptor.plugin_key
|
||||
<< "': get_texture_dir() failed ("
|
||||
<< python_exception_text(err, instance->audit_plugin_key(), instance->name())
|
||||
<< "); the capability will provide no textures";
|
||||
resource_texture->set_texture_dir({});
|
||||
} catch (const std::exception& ex) {
|
||||
BOOST_LOG_TRIVIAL(warning)
|
||||
<< "Plugin capability '" << found.name << "' of plugin '" << descriptor.plugin_key
|
||||
@@ -415,6 +464,9 @@ bool load(const PluginDescriptor& descriptor,
|
||||
|
||||
capabilities.push_back(std::move(instance));
|
||||
}
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
materialization_error = GUI::format(_u8L("Plugin capability materialization failed: %1%"),
|
||||
python_exception_text(err, descriptor.plugin_key));
|
||||
} catch (const std::exception& ex) {
|
||||
materialization_error = GUI::format(_u8L("Plugin capability materialization failed: %1%"), ex.what());
|
||||
} catch (...) {
|
||||
@@ -423,8 +475,18 @@ bool load(const PluginDescriptor& descriptor,
|
||||
}
|
||||
|
||||
if (!materialization_error.empty()) {
|
||||
capabilities.clear();
|
||||
capabilities_found.clear();
|
||||
// Re-establish the owner explicitly: a denial in get_type() clears the current key
|
||||
// before the exception unwinds, and the partially built lists still need to run their
|
||||
// finalizers as the plugin. Without the GIL there is no audit context to enter, so
|
||||
// leave the wrappers to their existing no-GIL fallback.
|
||||
if (gil) {
|
||||
ScopedPluginAuditContext cleanup_scope(descriptor.plugin_key);
|
||||
capabilities.clear();
|
||||
capabilities_found.clear();
|
||||
} else {
|
||||
capabilities.clear();
|
||||
capabilities_found.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!materialization_error.empty()) {
|
||||
@@ -440,7 +502,7 @@ bool load(const PluginDescriptor& descriptor,
|
||||
if (registry_precheck) {
|
||||
std::string precheck_error = registry_precheck(plugin);
|
||||
if (!precheck_error.empty()) {
|
||||
teardown_capabilities(plugin.capabilities, 0);
|
||||
teardown_capabilities(plugin.capabilities, 0, descriptor.plugin_key);
|
||||
error = std::move(precheck_error);
|
||||
return false;
|
||||
}
|
||||
@@ -457,13 +519,19 @@ bool load(const PluginDescriptor& descriptor,
|
||||
++lifecycle_count;
|
||||
capability->on_load();
|
||||
}
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
teardown_capabilities(plugin.capabilities, lifecycle_count, descriptor.plugin_key);
|
||||
// TRN on_load is the name of the plugin's startup function; keep it untranslated.
|
||||
error = GUI::format(_u8L("Plugin on_load failed: %1%"),
|
||||
python_exception_text(err, descriptor.plugin_key));
|
||||
return false;
|
||||
} catch (const std::exception& ex) {
|
||||
teardown_capabilities(plugin.capabilities, lifecycle_count);
|
||||
teardown_capabilities(plugin.capabilities, lifecycle_count, descriptor.plugin_key);
|
||||
// TRN on_load is the name of the plugin's startup function; keep it untranslated.
|
||||
error = GUI::format(_u8L("Plugin on_load failed: %1%"), ex.what());
|
||||
return false;
|
||||
} catch (...) {
|
||||
teardown_capabilities(plugin.capabilities, lifecycle_count);
|
||||
teardown_capabilities(plugin.capabilities, lifecycle_count, descriptor.plugin_key);
|
||||
error = _u8L("Plugin on_load failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
#include <slic3r/plugin/PythonPluginInterface.hpp>
|
||||
#include <slic3r/plugin/pluginTypes/script/ScriptPluginCapability.hpp>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
@@ -59,12 +60,54 @@ const char* const LOAD_CANCELLED = "__plugin_load_cancelled__";
|
||||
|
||||
} // namespace
|
||||
|
||||
void release_capabilities_under_audit(std::vector<std::shared_ptr<PluginCapabilityInterface>>& capabilities,
|
||||
const std::string& plugin_key)
|
||||
{
|
||||
if (capabilities.empty())
|
||||
return;
|
||||
|
||||
PythonGILState gil;
|
||||
if (!gil) {
|
||||
// No safe way to DECREF the Python wrappers. Clearing the vector still degrades exactly as
|
||||
// PluginInstanceHandle does: the handle abandons its Python reference when it cannot take
|
||||
// the GIL.
|
||||
capabilities.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
ScopedPluginAuditPromptSuppression no_prompts;
|
||||
ScopedPluginAuditContext audit_scope(plugin_key);
|
||||
capabilities.clear();
|
||||
}
|
||||
|
||||
void Plugin::release_capabilities()
|
||||
{
|
||||
try {
|
||||
release_capabilities_under_audit(capabilities, descriptor.plugin_key);
|
||||
} catch (...) {
|
||||
// Destructors must not throw. A failure to open the audit context is not a reason to
|
||||
// terminate; the handles still abandon their Python references if the GIL is gone.
|
||||
capabilities.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void Plugin::release_module()
|
||||
{
|
||||
if (module == nullptr && plugin_sys_paths.empty() && plugin_modules.empty())
|
||||
return;
|
||||
|
||||
PythonInterpreter::instance().unload_module(module, module_name, plugin_sys_paths, plugin_modules);
|
||||
{
|
||||
PythonGILState gil;
|
||||
if (gil) {
|
||||
// Tearing down the module namespace can run module-level finalizers. Judge that work
|
||||
// as the package rather than letting it escape the audit context, but never prompt
|
||||
// from a deterministic finalizer release.
|
||||
ScopedPluginAuditPromptSuppression no_prompts;
|
||||
ScopedPluginAuditContext audit_scope(descriptor.plugin_key);
|
||||
PythonInterpreter::instance().unload_module(module, module_name, plugin_sys_paths, plugin_modules);
|
||||
}
|
||||
}
|
||||
|
||||
module = nullptr;
|
||||
module_name.clear();
|
||||
plugin_sys_paths.clear();
|
||||
@@ -779,6 +822,10 @@ void PluginManager::cancel_and_wait_for_capabilities(
|
||||
|
||||
try {
|
||||
capability->on_cancelled();
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
BOOST_LOG_TRIVIAL(warning) << "Plugin on_cancelled failed for '" << capability->audit_plugin_key() << "/"
|
||||
<< capability->name() << "': "
|
||||
<< python_exception_text(err, capability->audit_plugin_key(), capability->name());
|
||||
} catch (const std::exception& ex) {
|
||||
BOOST_LOG_TRIVIAL(warning) << "Plugin on_cancelled failed for '" << capability->audit_plugin_key() << "/"
|
||||
<< capability->name() << "': " << ex.what();
|
||||
@@ -935,6 +982,9 @@ void PluginManager::load_plugin(const std::string& plugin_key, bool skip_deps, s
|
||||
|
||||
try {
|
||||
load_plugin_impl(plugin_id, skip_deps, capabilities_to_enable);
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
fail_unexpected(GUI::format(_u8L("Unexpected plugin load failure: %1%"),
|
||||
python_exception_text(err, plugin_id)));
|
||||
} catch (const std::exception& ex) {
|
||||
fail_unexpected(GUI::format(_u8L("Unexpected plugin load failure: %1%"), ex.what()));
|
||||
} catch (...) {
|
||||
@@ -1128,6 +1178,10 @@ void PluginManager::unload_all_plugins()
|
||||
// starving a later plugin while an earlier plugin uses the full cancellation grace period.
|
||||
cancel_and_wait_for_capabilities(capabilities);
|
||||
|
||||
// These are extra references only: each Plugin still owns its capabilities, so dropping them
|
||||
// here runs no Python finalizer and avoids a later release that has no owner context.
|
||||
capabilities.clear();
|
||||
|
||||
for (Plugin& plugin : removed)
|
||||
plugin_loader::unload(plugin);
|
||||
}
|
||||
@@ -2548,6 +2602,12 @@ void PluginManager::dispatch_lifecycle_event(LifecycleEvent evt, const Lifecycle
|
||||
break;
|
||||
try {
|
||||
cap->on_lifecycle_event(evt, ctx);
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": plugin '" << cap->audit_plugin_key() << "/" << cap->name()
|
||||
<< "' on_lifecycle_event(" << lifecycle_event_to_string(evt) << ") threw: "
|
||||
<< python_exception_text(err, cap->audit_plugin_key(), cap->name())
|
||||
<< " [ctx name='" << ctx.name << "', code=" << lifecycle_evt_code_to_string(ctx.code)
|
||||
<< ", msg='" << ctx.msg << "']";
|
||||
} catch (const std::exception& ex) {
|
||||
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": plugin '" << cap->audit_plugin_key() << "/" << cap->name()
|
||||
<< "' on_lifecycle_event(" << lifecycle_event_to_string(evt) << ") threw: " << ex.what()
|
||||
|
||||
@@ -78,6 +78,9 @@ struct Plugin
|
||||
Plugin& operator=(Plugin&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
// Registry compaction only move-assigns into entries that were unloaded first, so the
|
||||
// target's capability list is empty here and this does not take the GIL under m_mutex.
|
||||
release_capabilities();
|
||||
release_module();
|
||||
descriptor = std::move(other.descriptor);
|
||||
module = other.module;
|
||||
@@ -90,7 +93,14 @@ struct Plugin
|
||||
return *this;
|
||||
}
|
||||
|
||||
~Plugin() { release_module(); }
|
||||
~Plugin()
|
||||
{
|
||||
// Capabilities first: their Python wrappers may reference the module's namespace, so the
|
||||
// module must still be alive when they are released. Both run under the package's audit
|
||||
// context so a plugin finalizer is judged as the plugin.
|
||||
release_capabilities();
|
||||
release_module();
|
||||
}
|
||||
|
||||
bool is_loaded() const { return module != nullptr; }
|
||||
|
||||
@@ -98,8 +108,19 @@ struct Plugin
|
||||
// reference. If the interpreter is already finalized, PythonInterpreter deliberately leaves
|
||||
// the raw reference untouched because there is no safe way to DECREF it.
|
||||
void release_module();
|
||||
|
||||
// Drops every capability reference under the package's audit context, keeping Python wrapper
|
||||
// destruction on the GIL. Must run before release_module(). Do not call while holding the
|
||||
// plugin registry lock: it can execute Python finalizers.
|
||||
void release_capabilities();
|
||||
};
|
||||
|
||||
// Drops every capability reference in `capabilities` under `plugin_key`'s audit context. The GIL
|
||||
// is acquired once for the whole release; if it is unavailable, the wrappers abandon their Python
|
||||
// references exactly as PluginInstanceHandle does. Callers must not hold the plugin registry lock.
|
||||
void release_capabilities_under_audit(std::vector<std::shared_ptr<PluginCapabilityInterface>>& capabilities,
|
||||
const std::string& plugin_key);
|
||||
|
||||
// Outcome of one Script invocation, delivered to a script completion callback.
|
||||
//
|
||||
// `cancelled` marks a run terminated by PluginManager's own cancellation (plugin unload / shutdown):
|
||||
|
||||
@@ -32,13 +32,16 @@
|
||||
// Logs (and rethrows) a Python exception from a pybind11 override call, preserving the
|
||||
// traceback. Internal helper shared by the public macros below and by trampolines that
|
||||
// manage their own audit scope (e.g. the G-code plugin).
|
||||
//
|
||||
// The audit-denial flag can be sticky: a plugin may catch a PermissionError and then raise a
|
||||
// different exception. Do not clear the current plugin just because the flag is set -- that would
|
||||
// format the new exception's __str__ outside the plugin context. log_python_exception_keep()
|
||||
// formats under the retained owner and suppresses any permission prompt it might otherwise raise.
|
||||
#define ORCA_PY_LOGGED_OVERRIDE_BODY(override_call) \
|
||||
try { \
|
||||
override_call; \
|
||||
} catch (pybind11::error_already_set & err) { \
|
||||
const bool _orca_audit_denial = ::Slic3r::PluginAuditManager::instance().audit_denial_pending(); \
|
||||
if (_orca_audit_denial) \
|
||||
::Slic3r::PluginAuditManager::instance().clear_current_plugin(); \
|
||||
::Slic3r::log_python_exception_keep(err); \
|
||||
if (_orca_audit_denial) \
|
||||
::Slic3r::PluginAuditManager::instance().clear_audit_denial(); \
|
||||
@@ -125,10 +128,21 @@ inline ScriptExecuteInvocation invoke_script_execute(const std::shared_ptr<Plugi
|
||||
invocation.result = returned.cast<ExecutionResult>();
|
||||
} catch (pybind11::error_already_set& err) {
|
||||
const bool audit_denial = PluginAuditManager::instance().audit_denial_pending();
|
||||
if (audit_denial)
|
||||
PluginAuditManager::instance().clear_current_plugin();
|
||||
invocation.error = err.what();
|
||||
log_python_exception_keep(err);
|
||||
|
||||
{
|
||||
PythonGILState gil;
|
||||
if (gil) {
|
||||
// The audited scope that raised is gone by now. Re-open the capability's owner so
|
||||
// err.what() and traceback formatting are judged as the plugin. A sticky denial
|
||||
// flag from an earlier, caught PermissionError must not suppress this context.
|
||||
ScopedPluginAuditContext format_scope(capability->audit_plugin_key(), capability->name());
|
||||
invocation.error = python_exception_text(err, capability->audit_plugin_key(), capability->name());
|
||||
log_python_exception_keep(err);
|
||||
} else {
|
||||
invocation.error = "Python exception (interpreter unavailable)";
|
||||
}
|
||||
}
|
||||
|
||||
if (audit_denial)
|
||||
PluginAuditManager::instance().clear_audit_denial();
|
||||
} catch (const std::exception& ex) {
|
||||
|
||||
@@ -103,29 +103,42 @@ void log_python_exception_keep(pybind11::error_already_set& err)
|
||||
if (!gil)
|
||||
return;
|
||||
|
||||
// Traceback output is host-owned work. In particular, the stderr tee opens the Python log
|
||||
// file on every write. Keep that open outside the plugin audit context, otherwise an ordinary
|
||||
// exception raised by a plugin can recursively trigger the filesystem permission dialog while
|
||||
// its original exception is being reported.
|
||||
ScopedPluginAuditContext audit_suppression("");
|
||||
// pybind11's C++ formatter is the trusted renderer: it does not import `traceback` (which a
|
||||
// plugin can shadow) and it does not touch `sys.stderr` (which a plugin can replace).
|
||||
// python_exception_text() runs it under the current owner so plugin-authored __str__/__repr__
|
||||
// and __notes__ access stay audited, and it preserves the denial state across formatting.
|
||||
const std::string plugin_key = PluginAuditManager::instance().current_plugin();
|
||||
const std::string capability = PluginAuditManager::instance().current_capability();
|
||||
const std::string text = python_exception_text(err, plugin_key, capability);
|
||||
|
||||
// Non-destructive: print the traceback to sys.stderr (tee'd to the session log)
|
||||
// WITHOUT consuming err, so the caller can rethrow it intact. For example, downstream C++
|
||||
// catchers can still read err.what() for the user-facing dialog. We must NOT use
|
||||
// restore()+PyErr_Print() here as those empty err.
|
||||
try {
|
||||
namespace py = pybind11;
|
||||
py::module_ tb = py::module_::import("traceback");
|
||||
py::module_ sys = py::module_::import("sys");
|
||||
tb.attr("print_exception")(err.type(), err.value(), err.trace(), py::none(), sys.attr("stderr"));
|
||||
} catch (...) {
|
||||
// Fallback: at least get the formatted message out. err.what() includes the
|
||||
// traceback in recent pybind11 and does not consume err.
|
||||
try {
|
||||
pybind11::module_::import("sys").attr("stderr").attr("write")(std::string(err.what()) + "\n");
|
||||
} catch (...) {
|
||||
}
|
||||
// Native C++ logging is the trusted sink. It is the session log, not a Python object the
|
||||
// plugin can replace. It keeps the rendered type, message, notes, and frame locations, but
|
||||
// pybind's formatter does not render chained exceptions or source-code lines.
|
||||
if (!text.empty())
|
||||
BOOST_LOG_TRIVIAL(error) << text;
|
||||
}
|
||||
|
||||
std::string python_exception_text(pybind11::error_already_set& err,
|
||||
const std::string& plugin_key,
|
||||
const std::string& capability_name)
|
||||
{
|
||||
PythonGILState gil;
|
||||
if (!gil)
|
||||
return "Python exception (interpreter unavailable)";
|
||||
|
||||
// err.what() is pybind11's C++ formatter: it is not a Python module or stream the plugin can
|
||||
// shadow. Run it under the owner, preserve the denial state across a denied __str__, and deny
|
||||
// any un-granted audited operation without prompting while formatting.
|
||||
ScopedPluginAuditPromptSuppression no_prompts;
|
||||
ScopedPluginAuditDenialState preserve_denial;
|
||||
|
||||
std::string text;
|
||||
{
|
||||
ScopedPluginAuditContext audit_scope(plugin_key, capability_name);
|
||||
text = err.what();
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
namespace {
|
||||
@@ -138,18 +151,32 @@ std::string format_python_error(PyObject* ptype, PyObject* pvalue, PyObject* ptr
|
||||
PyObject* type_name = PyObject_GetAttrString(ptype, "__name__");
|
||||
if (type_name) {
|
||||
const char* s = PyUnicode_AsUTF8(type_name);
|
||||
if (s) result += s;
|
||||
if (s)
|
||||
result += s;
|
||||
else
|
||||
PyErr_Clear();
|
||||
Py_DECREF(type_name);
|
||||
} else {
|
||||
PyErr_Clear();
|
||||
}
|
||||
}
|
||||
|
||||
if (pvalue) {
|
||||
if (!result.empty()) result += ": ";
|
||||
if (!result.empty())
|
||||
result += ": ";
|
||||
PyObject* s = PyObject_Str(pvalue);
|
||||
if (s) {
|
||||
const char* cstr = PyUnicode_AsUTF8(s);
|
||||
if (cstr) result += cstr;
|
||||
if (cstr)
|
||||
result += cstr;
|
||||
else
|
||||
PyErr_Clear();
|
||||
Py_DECREF(s);
|
||||
} else {
|
||||
// Formatting the exception value is plugin-authored when the plugin raises its own
|
||||
// exception type; a failure here must not leave an error indicator behind on the
|
||||
// import-failure path.
|
||||
PyErr_Clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,18 +185,22 @@ std::string format_python_error(PyObject* ptype, PyObject* pvalue, PyObject* ptr
|
||||
PyTracebackObject* tb = reinterpret_cast<PyTracebackObject*>(ptraceback);
|
||||
while (tb) {
|
||||
PyFrameObject* frame = tb->tb_frame;
|
||||
int line = PyFrame_GetLineNumber(frame);
|
||||
PyCodeObject* code = PyFrame_GetCode(frame); // returns a NEW strong reference; must be released
|
||||
const char* filename = code ? PyUnicode_AsUTF8(code->co_filename) : nullptr;
|
||||
const char* funcname = code ? PyUnicode_AsUTF8(code->co_name) : nullptr;
|
||||
result += "\n File \"" + std::string(filename ? filename : "?") +
|
||||
"\", line " + std::to_string(line) +
|
||||
int line = PyFrame_GetLineNumber(frame);
|
||||
PyCodeObject* code = PyFrame_GetCode(frame); // returns a NEW strong reference; must be released
|
||||
const char* filename = code ? PyUnicode_AsUTF8(code->co_filename) : nullptr;
|
||||
const char* funcname = code ? PyUnicode_AsUTF8(code->co_name) : nullptr;
|
||||
if (!filename || !funcname)
|
||||
PyErr_Clear();
|
||||
result += "\n File \"" + std::string(filename ? filename : "?") + "\", line " + std::to_string(line) +
|
||||
", in " + std::string(funcname ? funcname : "?");
|
||||
Py_XDECREF(code);
|
||||
tb = tb->tb_next;
|
||||
}
|
||||
}
|
||||
|
||||
// The caller has already fetched the original exception, so any error raised while rendering
|
||||
// this text belongs to the formatter, not to the import that is about to report its failure.
|
||||
PyErr_Clear();
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,17 +23,27 @@ namespace Slic3r {
|
||||
|
||||
class PythonRuntimeLease;
|
||||
|
||||
// Print a Python exception's full traceback to sys.stderr (tee'd to the session
|
||||
// log) WITHOUT consuming err.
|
||||
// Render a Python exception through pybind11's C++ formatter and log it through native C++
|
||||
// logging, WITHOUT consuming err. Deliberately avoids importing `traceback` and writing to
|
||||
// `sys.stderr`: a plugin can shadow the module or replace the stream, which would execute
|
||||
// plugin code outside the audit context. The rendered text includes the type, message, notes, and
|
||||
// frame locations, but not chained exceptions or source-code lines.
|
||||
//
|
||||
// Used by the ORCA_PY_OVERRIDE_AUDITED trampoline macro: the
|
||||
// traceback is logged centrally at the C++<->Python boundary, then the original
|
||||
// error_already_set is rethrown intact so downstream C++ catchers can still build
|
||||
// the user-facing dialog from err.what(). Because it is non-destructive it does
|
||||
// NOT call restore()/PyErr_Print() (those will empty err); it prints via Python's
|
||||
// traceback module instead.
|
||||
// Used by the ORCA_PY_OVERRIDE_AUDITED trampoline macro: the traceback is logged centrally at the
|
||||
// C++<->Python boundary, then the original error_already_set is rethrown intact so downstream C++
|
||||
// catchers can still build the user-facing dialog from err.what(). Because it is non-destructive
|
||||
// it does NOT call restore()/PyErr_Print() (those will empty err).
|
||||
void log_python_exception_keep(pybind11::error_already_set& err);
|
||||
|
||||
// Formats `err` for a log line or user-facing error while attributing the formatting work to the
|
||||
// plugin that raised it. err.what() calls the exception value's __str__/__repr__ and __notes__,
|
||||
// which is plugin-authored code, so the formatting runs under `plugin_key`'s audit scope. The GIL
|
||||
// is acquired for the call; when the interpreter is already shutting down this returns a fixed
|
||||
// placeholder instead of touching Python without the GIL. Does not consume err.
|
||||
std::string python_exception_text(pybind11::error_already_set& err,
|
||||
const std::string& plugin_key,
|
||||
const std::string& capability_name = {});
|
||||
|
||||
|
||||
// RAII wrapper for Python interpreter initialization/finalization
|
||||
class PythonInterpreter
|
||||
|
||||
@@ -58,6 +58,12 @@ struct PluginInstanceHandle
|
||||
std::shared_ptr<PluginCapabilityInterface> plugin;
|
||||
py::object keep_alive;
|
||||
|
||||
// The owner recorded at capture time. The handle can outlive the Plugin's capability vector
|
||||
// (dispatch copies, an async run, the GC), so its destructor opens the audit context itself
|
||||
// rather than relying on the site that happens to drop the last reference.
|
||||
std::string plugin_key;
|
||||
std::string capability_name;
|
||||
|
||||
~PluginInstanceHandle()
|
||||
{
|
||||
if (keep_alive) {
|
||||
@@ -65,6 +71,18 @@ struct PluginInstanceHandle
|
||||
// the GIL. If shutdown has already won the lease, intentionally abandon the wrapper.
|
||||
PythonGILState gil;
|
||||
if (gil) {
|
||||
// Read the live identity when it is available: keep_installed_plugin_as_local()
|
||||
// can rekey a loaded capability, and the captured strings are only a fallback for
|
||||
// a capability that failed before its resolved identity was cached.
|
||||
const std::string& key = (plugin && !plugin->audit_plugin_key().empty())
|
||||
? plugin->audit_plugin_key()
|
||||
: plugin_key;
|
||||
const std::string& name = (plugin && !plugin->name().empty()) ? plugin->name() : capability_name;
|
||||
|
||||
// Deterministic destruction may run a plugin finalizer. Keep it attributed but
|
||||
// fail un-granted operations closed instead of prompting from the destructor.
|
||||
ScopedPluginAuditPromptSuppression no_prompts;
|
||||
ScopedPluginAuditContext audit_scope(key, name);
|
||||
keep_alive = py::object();
|
||||
} else {
|
||||
(void) keep_alive.release();
|
||||
@@ -171,9 +189,14 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
|
||||
|
||||
// The package instance is only a registration coordinator. It is not returned
|
||||
// to the rest of the plugin system; only the capability classes it registers
|
||||
// are kept.
|
||||
py::object package = package_cls();
|
||||
package.attr("register_capabilities")();
|
||||
// are kept. Constructing it and running register_capabilities() executes
|
||||
// plugin-authored code, so attribute both to the plugin. The scope ends before
|
||||
// the permission prompt below, which is host setup and releases the GIL.
|
||||
{
|
||||
ScopedPluginAuditContext audit_scope(plugin_key);
|
||||
py::object package = package_cls();
|
||||
package.attr("register_capabilities")();
|
||||
}
|
||||
|
||||
// Permission declarations are collected while register_capabilities() runs so the
|
||||
// plugin can describe its needs without touching wx from the Python load worker. Ask
|
||||
@@ -206,8 +229,12 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
|
||||
}
|
||||
}
|
||||
} catch (py::error_already_set& err) {
|
||||
// The registration scope is gone by the time the catch runs. Re-open it for the
|
||||
// exception formatting so a plugin-authored __str__ or __notes__ is judged as the
|
||||
// plugin, not as host work.
|
||||
ScopedPluginAuditContext format_scope(plugin_key);
|
||||
log_python_exception_keep(err);
|
||||
error = err.what();
|
||||
error = python_exception_text(err, plugin_key);
|
||||
BOOST_LOG_TRIVIAL(error) << "Plugin register_capabilities raised Python exception for key " << plugin_key
|
||||
<< " error=" << error;
|
||||
discard_pending_for_key();
|
||||
@@ -242,71 +269,86 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << "Collected " << classes.size() << " registered capability class(es) for key " << capture_key;
|
||||
|
||||
std::vector<CapturedCapability> capabilities;
|
||||
capabilities.reserve(classes.size());
|
||||
|
||||
// Phase 3: instantiate each registered capability class and convert it to the common
|
||||
// C++ interface used by the rest of OrcaSlicer.
|
||||
for (auto& cls : classes) {
|
||||
try {
|
||||
py::object instance = cls();
|
||||
if (!py::isinstance<PluginCapabilityInterface>(instance)) {
|
||||
error = "Registered capability must inherit from a PluginCapability base";
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture failed type check for key " << capture_key
|
||||
// C++ interface used by the rest of OrcaSlicer. Constructing the class and calling get_name()
|
||||
// executes plugin-authored code before the capability's audit key is cached on it, so the
|
||||
// whole loop runs under the plugin's audit scope. Declaring the vector after the scope also
|
||||
// makes a failure return destroy the partially built list while that scope is still current,
|
||||
// so constructor/get_name finalizers are judged as the plugin. The GIL is held in both cases.
|
||||
{
|
||||
ScopedPluginAuditContext audit_scope(plugin_key);
|
||||
std::vector<CapturedCapability> capabilities;
|
||||
capabilities.reserve(classes.size());
|
||||
|
||||
for (auto& cls : classes) {
|
||||
try {
|
||||
py::object instance = cls();
|
||||
if (!py::isinstance<PluginCapabilityInterface>(instance)) {
|
||||
error = "Registered capability must inherit from a PluginCapability base";
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture failed type check for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto capability_iface = instance.cast<std::shared_ptr<PluginCapabilityInterface>>();
|
||||
if (!capability_iface) {
|
||||
error = "Failed to cast Python capability to PluginCapabilityInterface";
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture failed cast for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
}
|
||||
|
||||
// Publish the owner before the first trampoline call. ORCA_PY_AUDIT_SCOPE() then
|
||||
// opens (and, on a denial, clears) its own inner scope instead of clearing the
|
||||
// capture scope that still owns this instance's cleanup.
|
||||
capability_iface->set_audit_plugin_key(plugin_key);
|
||||
|
||||
// This is a registered capability, not the transient orca.base package.
|
||||
// get_name() is required on capabilities and is cached for preset lookup.
|
||||
std::string name = capability_iface->get_name();
|
||||
|
||||
// Capability names feed ';'-delimited config/preset serialization and drive
|
||||
// dispatch, so unlike display names they cannot be silently rewritten — a ';'
|
||||
// here is a hard error that rejects the whole plugin capture.
|
||||
if (name.find(';') != std::string::npos) {
|
||||
error = "Capability name must not contain ';': " + name;
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture rejected capability for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto handle = std::make_shared<PluginInstanceHandle>();
|
||||
handle->keep_alive = instance;
|
||||
handle->plugin = std::move(capability_iface);
|
||||
handle->plugin_key = plugin_key;
|
||||
handle->capability_name = name;
|
||||
|
||||
CapturedCapability captured;
|
||||
// Return a shared_ptr<PluginCapabilityInterface> while keeping PluginInstanceHandle
|
||||
// as the owner, so the Python instance stays alive as long as the C++ interface does.
|
||||
captured.instance = std::shared_ptr<PluginCapabilityInterface>(handle, handle->plugin.get());
|
||||
captured.name = std::move(name);
|
||||
capabilities.emplace_back(std::move(captured));
|
||||
} catch (py::error_already_set& err) {
|
||||
// Direct Python call (cls() / get_name() above), not a trampoline override —
|
||||
// log the traceback here. GIL is held for the duration of finalize_plugin_capture.
|
||||
log_python_exception_keep(err);
|
||||
error = python_exception_text(err, plugin_key);
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture raised Python exception for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
} catch (const std::exception& ex) {
|
||||
error = ex.what();
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture raised exception for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto capability_iface = instance.cast<std::shared_ptr<PluginCapabilityInterface>>();
|
||||
if (!capability_iface) {
|
||||
error = "Failed to cast Python capability to PluginCapabilityInterface";
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture failed cast for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
}
|
||||
|
||||
// This is a registered capability, not the transient orca.base package.
|
||||
// get_name() is required on capabilities and is cached for preset lookup.
|
||||
std::string name = capability_iface->get_name();
|
||||
|
||||
// Capability names feed ';'-delimited config/preset serialization and drive
|
||||
// dispatch, so unlike display names they cannot be silently rewritten — a ';'
|
||||
// here is a hard error that rejects the whole plugin capture.
|
||||
if (name.find(';') != std::string::npos) {
|
||||
error = "Capability name must not contain ';': " + name;
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture rejected capability for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
}
|
||||
|
||||
auto handle = std::make_shared<PluginInstanceHandle>();
|
||||
handle->keep_alive = instance;
|
||||
handle->plugin = std::move(capability_iface);
|
||||
|
||||
CapturedCapability captured;
|
||||
// Return a shared_ptr<PluginCapabilityInterface> while keeping PluginInstanceHandle
|
||||
// as the owner, so the Python instance stays alive as long as the C++ interface does.
|
||||
captured.instance = std::shared_ptr<PluginCapabilityInterface>(handle, handle->plugin.get());
|
||||
captured.name = std::move(name);
|
||||
capabilities.emplace_back(std::move(captured));
|
||||
} catch (py::error_already_set& err) {
|
||||
// Direct Python call (cls() / get_name() above), not a trampoline override —
|
||||
// log the traceback here. GIL is held for the duration of finalize_plugin_capture.
|
||||
log_python_exception_keep(err);
|
||||
error = err.what();
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture raised Python exception for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
} catch (const std::exception& ex) {
|
||||
error = ex.what();
|
||||
BOOST_LOG_TRIVIAL(error) << "Python plugin capture raised exception for key " << capture_key
|
||||
<< " error=" << error;
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
BOOST_LOG_TRIVIAL(info) << "Instantiated " << capabilities.size() << " Python capability instance(s) for key " << plugin_key;
|
||||
return capabilities;
|
||||
BOOST_LOG_TRIVIAL(info) << "Instantiated " << capabilities.size()
|
||||
<< " Python capability instance(s) for key " << plugin_key;
|
||||
return capabilities;
|
||||
}
|
||||
}
|
||||
|
||||
void PythonPluginBridge::cancel_plugin_capture(const std::string& plugin_key)
|
||||
|
||||
@@ -32,6 +32,9 @@
|
||||
// the plugin does may leave the trampoline as an exception: a Python raise, a missing override or a
|
||||
// wrongly typed return is logged and answered with what NetworkAgent returns when no agent is set.
|
||||
#define ORCA_PY_AGENT_CATCH(name) \
|
||||
catch (pybind11::error_already_set& err) { \
|
||||
this->log_failure(#name, ::Slic3r::python_exception_text(err, this->audit_plugin_key(), this->name()).c_str()); \
|
||||
} \
|
||||
catch (const std::exception& ex) { this->log_failure(#name, ex.what()); } \
|
||||
catch (...) { this->log_failure(#name, "unknown error"); }
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user