Skip to content

Commit d35af78

Browse files
committed
Wrap ensure_internals() in try-catch in PYBIND11_MODULE_PYINIT
Previously, ensure_internals() was called without exception handling in the PyInit_* function (PYBIND11_MODULE_PYINIT), while the same call in PYBIND11_MODULE_EXEC was already wrapped in try-catch. On MSVC, a C++ exception propagating through the extern "C" PyInit_* boundary is undefined behavior, which can manifest as an access violation instead of a clean error message. This is a potential contributor to crashes like gh-5993. Wrap the entire PyInit body in try/catch using the existing PYBIND11_CATCH_INIT_EXCEPTIONS pattern. Made-with: Cursor
1 parent 3b62426 commit d35af78

1 file changed

Lines changed: 18 additions & 13 deletions

File tree

include/pybind11/detail/common.h

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -457,19 +457,24 @@ PyModuleDef_Init should be treated like any other PyObject (so not shared across
457457
static int PYBIND11_CONCAT(pybind11_exec_, name)(PyObject *); \
458458
PYBIND11_PLUGIN_IMPL(name) { \
459459
PYBIND11_CHECK_PYTHON_VERSION \
460-
pybind11::detail::ensure_internals(); \
461-
static ::pybind11::detail::slots_array mod_def_slots = ::pybind11::detail::init_slots( \
462-
&PYBIND11_CONCAT(pybind11_exec_, name), ##__VA_ARGS__); \
463-
static PyModuleDef def{/* m_base */ PyModuleDef_HEAD_INIT, \
464-
/* m_name */ PYBIND11_TOSTRING(name), \
465-
/* m_doc */ nullptr, \
466-
/* m_size */ 0, \
467-
/* m_methods */ nullptr, \
468-
/* m_slots */ mod_def_slots.data(), \
469-
/* m_traverse */ nullptr, \
470-
/* m_clear */ nullptr, \
471-
/* m_free */ nullptr}; \
472-
return PyModuleDef_Init(&def); \
460+
try { \
461+
pybind11::detail::ensure_internals(); \
462+
static ::pybind11::detail::slots_array mod_def_slots \
463+
= ::pybind11::detail::init_slots(&PYBIND11_CONCAT(pybind11_exec_, name), \
464+
##__VA_ARGS__); \
465+
static PyModuleDef def{/* m_base */ PyModuleDef_HEAD_INIT, \
466+
/* m_name */ PYBIND11_TOSTRING(name), \
467+
/* m_doc */ nullptr, \
468+
/* m_size */ 0, \
469+
/* m_methods */ nullptr, \
470+
/* m_slots */ mod_def_slots.data(), \
471+
/* m_traverse */ nullptr, \
472+
/* m_clear */ nullptr, \
473+
/* m_free */ nullptr}; \
474+
return PyModuleDef_Init(&def); \
475+
} \
476+
PYBIND11_CATCH_INIT_EXCEPTIONS \
477+
return nullptr; \
473478
}
474479

475480
#define PYBIND11_MODULE_EXEC(name, variable) \

0 commit comments

Comments
 (0)