Skip to content

Commit 3ac690b

Browse files
authored
Explicitly export exception types. (#2999)
* Set visibility of exceptions to default. Co-authored-by: XZiar <[email protected]> * add test * update docs * Skip failed test.
1 parent 14023c9 commit 3ac690b

File tree

8 files changed

+59
-3
lines changed

8 files changed

+59
-3
lines changed

docs/advanced/exceptions.rst

+4
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,10 @@ section.
164164
may be explicitly (re-)thrown to delegate it to the other,
165165
previously-declared existing exception translators.
166166

167+
Note that ``libc++`` and ``libstdc++`` `behave differently <https://stackoverflow.com/questions/19496643/using-clang-fvisibility-hidden-and-typeinfo-and-type-erasure/28827430>`_
168+
with ``-fvisibility=hidden``. Therefore exceptions that are used across ABI boundaries need to be explicitly exported, as exercised in ``tests/test_exceptions.h``.
169+
See also: "Problems with C++ exceptions" under `GCC Wiki <https://gcc.gnu.org/wiki/Visibility>`_.
170+
167171
.. _handling_python_exceptions_cpp:
168172

169173
Handling exceptions from Python in C++

include/pybind11/detail/common.h

+9-2
Original file line numberDiff line numberDiff line change
@@ -723,16 +723,23 @@ using expand_side_effects = bool[];
723723

724724
PYBIND11_NAMESPACE_END(detail)
725725

726+
#if defined(_MSC_VER)
727+
# pragma warning(push)
728+
# pragma warning(disable: 4275) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class.
729+
#endif
726730
/// C++ bindings of builtin Python exceptions
727-
class builtin_exception : public std::runtime_error {
731+
class PYBIND11_EXPORT builtin_exception : public std::runtime_error {
728732
public:
729733
using std::runtime_error::runtime_error;
730734
/// Set the error using the Python C API
731735
virtual void set_error() const = 0;
732736
};
737+
#if defined(_MSC_VER)
738+
# pragma warning(pop)
739+
#endif
733740

734741
#define PYBIND11_RUNTIME_EXCEPTION(name, type) \
735-
class name : public builtin_exception { public: \
742+
class PYBIND11_EXPORT name : public builtin_exception { public: \
736743
using builtin_exception::builtin_exception; \
737744
name() : name("") { } \
738745
void set_error() const override { PyErr_SetString(type, what()); } \

include/pybind11/detail/internals.h

+2
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,8 @@ PYBIND11_NOINLINE inline internals &get_internals() {
276276
// initial exception translator, below, so add another for our local exception classes.
277277
//
278278
// libstdc++ doesn't require this (types there are identified only by name)
279+
// libc++ with CPython doesn't require this (types are explicitly exported)
280+
// libc++ with PyPy still need it, awaiting further investigation
279281
#if !defined(__GLIBCXX__)
280282
(*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
281283
#endif

include/pybind11/pytypes.h

+8-1
Original file line numberDiff line numberDiff line change
@@ -319,11 +319,15 @@ PYBIND11_NAMESPACE_BEGIN(detail)
319319
inline std::string error_string();
320320
PYBIND11_NAMESPACE_END(detail)
321321

322+
#if defined(_MSC_VER)
323+
# pragma warning(push)
324+
# pragma warning(disable: 4275 4251) // warning C4275: An exported class was derived from a class that wasn't exported. Can be ignored when derived from a STL class.
325+
#endif
322326
/// Fetch and hold an error which was already set in Python. An instance of this is typically
323327
/// thrown to propagate python-side errors back through C++ which can either be caught manually or
324328
/// else falls back to the function dispatcher (which then raises the captured error back to
325329
/// python).
326-
class error_already_set : public std::runtime_error {
330+
class PYBIND11_EXPORT error_already_set : public std::runtime_error {
327331
public:
328332
/// Constructs a new exception from the current Python error indicator, if any. The current
329333
/// Python error indicator will be cleared.
@@ -371,6 +375,9 @@ class error_already_set : public std::runtime_error {
371375
private:
372376
object m_type, m_value, m_trace;
373377
};
378+
#if defined(_MSC_VER)
379+
# pragma warning(pop)
380+
#endif
374381

375382
/** \defgroup python_builtins _
376383
Unless stated otherwise, the following C++ functions behave the same

tests/pybind11_cross_module_tests.cpp

+8
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
#include "pybind11_tests.h"
1111
#include "local_bindings.h"
12+
#include "test_exceptions.h"
1213
#include <pybind11/stl_bind.h>
1314
#include <numeric>
1415

@@ -30,6 +31,13 @@ PYBIND11_MODULE(pybind11_cross_module_tests, m) {
3031
m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); });
3132
m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); });
3233
m.def("throw_stop_iteration", []() { throw py::stop_iteration(); });
34+
py::register_exception_translator([](std::exception_ptr p) {
35+
try {
36+
if (p) std::rethrow_exception(p);
37+
} catch (const shared_exception &e) {
38+
PyErr_SetString(PyExc_KeyError, e.what());
39+
}
40+
});
3341

3442
// test_local_bindings.py
3543
// Local to both:

tests/test_exceptions.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
BSD-style license that can be found in the LICENSE file.
88
*/
99

10+
#include "test_exceptions.h"
1011
#include "pybind11_tests.h"
1112

1213
// A type that should be raised as an exception in Python
@@ -228,4 +229,5 @@ TEST_SUBMODULE(exceptions, m) {
228229
// Test repr that cannot be displayed
229230
m.def("simple_bool_passthrough", [](bool x) {return x;});
230231

232+
m.def("throw_should_be_translated_to_key_error", []() { throw shared_exception(); });
231233
}

tests/test_exceptions.h

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#pragma once
2+
#include "pybind11_tests.h"
3+
#include <stdexcept>
4+
5+
// shared exceptions for cross_module_tests
6+
7+
class PYBIND11_EXPORT shared_exception : public pybind11::builtin_exception {
8+
public:
9+
using builtin_exception::builtin_exception;
10+
explicit shared_exception() : shared_exception("") {}
11+
void set_error() const override { PyErr_SetString(PyExc_RuntimeError, what()); }
12+
};

tests/test_exceptions.py

+14
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
import pytest
55

6+
import env # noqa: F401
7+
68
from pybind11_tests import exceptions as m
79
import pybind11_cross_module_tests as cm
810

@@ -44,6 +46,18 @@ def test_cross_module_exceptions():
4446
cm.throw_stop_iteration()
4547

4648

49+
# TODO: FIXME
50+
@pytest.mark.xfail(
51+
"env.PYPY and env.MACOS",
52+
raises=RuntimeError,
53+
reason="Expected failure with PyPy and libc++ (Issue #2847 & PR #2999)",
54+
)
55+
def test_cross_module_exception_translator():
56+
with pytest.raises(KeyError):
57+
# translator registered in cross_module_tests
58+
m.throw_should_be_translated_to_key_error()
59+
60+
4761
def test_python_call_in_catch():
4862
d = {}
4963
assert m.python_call_in_destructor(d) is True

0 commit comments

Comments
 (0)