diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index aa1dcdf850e..4457469feaf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -78,6 +78,13 @@ repos: language: python files: ^cuda_core/cuda/.*\.pyx$ + - id: check-cython-bool-returns + name: Check C++ bool returns are declared cpp_bool, not bint + entry: python ./toolshed/check_cython_bool_returns.py + language: python + files: ^cuda_core/cuda/core/.*\.(pyx|pxd|pxi|hpp|h|cpp)$ + pass_filenames: false + - id: check-generated-file-seals name: Check generated-file seals entry: python ./toolshed/check_generated_file_seals.py diff --git a/cuda_core/cuda/core/_rt.pxd b/cuda_core/cuda/core/_rt.pxd index 60617192c4b..b67c66db9b3 100644 --- a/cuda_core/cuda/core/_rt.pxd +++ b/cuda_core/cuda/core/_rt.pxd @@ -6,6 +6,7 @@ from cpython.object cimport PyObject from libc.stddef cimport size_t from libc.stdint cimport intptr_t +from libcpp cimport bool as cpp_bool from libcpp.memory cimport shared_ptr, unique_ptr from libcpp.vector cimport vector @@ -188,6 +189,12 @@ cdef extern from "_cpp/rt/handles.hpp" namespace "cuda_core::rt": # Wrapper function declarations (implemented in _rt.pyx) # # Consumer modules cimport these. Calls go through _rt.so. +# +# A consumer calls each function through a pointer of the type declared here, +# not the type in the C++ header, so return types must match the C++ exactly. +# Declare a C++ bool return as cpp_bool, never bint (int): MSVC sets only the +# low byte of the return register for a bool, so reading it as int on Windows +# can turn false into true. # ============================================================================= # Thread-local error handling @@ -256,9 +263,9 @@ cdef EventHandle create_event_handle_ipc( const cydriver.CUipcEventHandle& ipc_handle, bint is_blocking_sync) except+ nogil # Event metadata getters -cdef bint get_event_timing_enabled(const EventHandle& h) noexcept nogil -cdef bint get_event_is_blocking_sync(const EventHandle& h) noexcept nogil -cdef bint get_event_ipc_enabled(const EventHandle& h) noexcept nogil +cdef cpp_bool get_event_timing_enabled(const EventHandle& h) noexcept nogil +cdef cpp_bool get_event_is_blocking_sync(const EventHandle& h) noexcept nogil +cdef cpp_bool get_event_ipc_enabled(const EventHandle& h) noexcept nogil cdef int get_event_device_id(const EventHandle& h) noexcept nogil cdef ContextHandle get_event_context(const EventHandle& h) noexcept nogil @@ -302,7 +309,7 @@ cdef MemAllocationHandle create_mem_allocation_handle( size_t size, const cydriver.CUmemAllocationProp& prop, const cydriver.CUmemAccessDesc* descs, size_t count) except+ nogil cdef size_t mem_allocation_size(const MemAllocationHandle& h) noexcept nogil -cdef bint mem_allocation_is_imported(const MemAllocationHandle& h) noexcept nogil +cdef cpp_bool mem_allocation_is_imported(const MemAllocationHandle& h) noexcept nogil cdef MemAllocationHandle import_mem_allocation_handle( void* os_handle, cydriver.CUmemAllocationHandleType handle_type, size_t size, const cydriver.CUmemAccessDesc* descs, size_t count) except+ nogil diff --git a/cuda_core/cuda/core/_rt.pyx b/cuda_core/cuda/core/_rt.pyx index c8f165203c3..6511643edb5 100644 --- a/cuda_core/cuda/core/_rt.pyx +++ b/cuda_core/cuda/core/_rt.pyx @@ -27,6 +27,7 @@ from cpython.object cimport PyObject from libc.stddef cimport size_t +from libcpp cimport bool as cpp_bool from cuda.bindings cimport cydriver from cuda.bindings cimport cynvrtc @@ -126,11 +127,11 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": const cydriver.CUipcEventHandle& ipc_handle, bint is_blocking_sync) except+ nogil # Event metadata getters - bint get_event_timing_enabled "cuda_core::rt::get_event_timing_enabled" ( + cpp_bool get_event_timing_enabled "cuda_core::rt::get_event_timing_enabled" ( const EventHandle& h) noexcept nogil - bint get_event_is_blocking_sync "cuda_core::rt::get_event_is_blocking_sync" ( + cpp_bool get_event_is_blocking_sync "cuda_core::rt::get_event_is_blocking_sync" ( const EventHandle& h) noexcept nogil - bint get_event_ipc_enabled "cuda_core::rt::get_event_ipc_enabled" ( + cpp_bool get_event_ipc_enabled "cuda_core::rt::get_event_ipc_enabled" ( const EventHandle& h) noexcept nogil int get_event_device_id "cuda_core::rt::get_event_device_id" ( const EventHandle& h) noexcept nogil @@ -183,7 +184,7 @@ cdef extern from "_cpp/rt/rt.hpp" namespace "cuda_core::rt": const cydriver.CUmemAccessDesc* descs, size_t count) except+ nogil size_t mem_allocation_size "cuda_core::rt::mem_allocation_size" ( const MemAllocationHandle& h) noexcept nogil - bint mem_allocation_is_imported "cuda_core::rt::mem_allocation_is_imported" ( + cpp_bool mem_allocation_is_imported "cuda_core::rt::mem_allocation_is_imported" ( const MemAllocationHandle& h) noexcept nogil MemAllocationHandle import_mem_allocation_handle "cuda_core::rt::import_mem_allocation_handle" ( void* os_handle, cydriver.CUmemAllocationHandleType handle_type, size_t size, diff --git a/toolshed/check_cython_bool_returns.py b/toolshed/check_cython_bool_returns.py new file mode 100644 index 00000000000..bb364ed7c20 --- /dev/null +++ b/toolshed/check_cython_bool_returns.py @@ -0,0 +1,94 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Reject Cython declarations that return ``bint`` for a C++ function returning ``bool``. + +A consumer module calls a cimported function through a pointer of the type in +the ``.pxd``, not the type in the C++ header. ``bint`` is ``int``, but MSVC +sets only the low byte of the return register for a ``bool``, so on Windows +the caller can read ``false`` as ``true``. Declare such returns as:: + + from libcpp cimport bool as cpp_bool + + cdef cpp_bool f(...) noexcept nogil +""" + +import re +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +SOURCE_ROOT = REPO_ROOT / "cuda_core" / "cuda" / "core" +CXX_SUFFIXES = (".hpp", ".h", ".cpp") +CYTHON_SUFFIXES = (".pyx", ".pxd", ".pxi") + +# [inline|static|...] bool name( -- the return type may sit on its own line +_CXX_BOOL_FUNCTION = re.compile( + r"""(?:^|[;{}]|\]\])\s* + (?:(?:inline|static|constexpr|virtual|extern)\s+)* + bool\s+(?P[A-Za-z_]\w*)\s*\(""", + re.MULTILINE | re.VERBOSE, +) +# [cdef ][inline ]bint name ["c::name"] ( +_CYTHON_BINT_FUNCTION = re.compile( + r"""^[ \t]*(?:cdef\s+)?(?:inline\s+)? + bint\s+(?P[A-Za-z_]\w*)\s* + (?:"(?P[^"]*)"\s*)?\(""", + re.MULTILINE | re.VERBOSE, +) + + +def _blank(match): + return re.sub(r"[^\n]", " ", match.group(0)) + + +def _strip_cxx_comments(text): + text = re.sub(r"(?s)/\*.*?\*/", _blank, text) + return re.sub(r"//[^\n]*", _blank, text) + + +def _strip_cython_comments(text): + # Keep the quoted C names in extern declarations; only drop ``#`` comments + # and docstrings, whose examples could otherwise look like declarations. + text = re.sub(r'(?s)(?:"""|\'\'\').*?(?:"""|\'\'\')', _blank, text) + return re.sub(r"#[^\n]*", _blank, text) + + +def collect_cxx_bool_functions(root=SOURCE_ROOT): + names = set() + for path in root.rglob("*"): + if path.suffix in CXX_SUFFIXES: + text = _strip_cxx_comments(path.read_text(encoding="utf-8")) + names.update(m.group("name") for m in _CXX_BOOL_FUNCTION.finditer(text)) + return names + + +def find_violations(text, bool_functions): + """Yield ``(offset, message)`` for each ``bint`` declaration of a C++ ``bool`` function.""" + for match in _CYTHON_BINT_FUNCTION.finditer(_strip_cython_comments(text)): + name = match.group("name") + cname = match.group("cname") + target = cname.rsplit("::", 1)[-1] if cname else name + if target in bool_functions: + yield ( + match.start("name"), + f"{name!r} returns C++ bool; declare its return type as cpp_bool, not bint", + ) + + +def main(root=SOURCE_ROOT): + bool_functions = collect_cxx_bool_functions(root) + failed = False + for path in sorted(root.rglob("*")): + if path.suffix not in CYTHON_SUFFIXES: + continue + text = path.read_text(encoding="utf-8") + for offset, message in find_violations(text, bool_functions): + lineno = text.count("\n", 0, offset) + 1 + print(f"{path.relative_to(REPO_ROOT)}:{lineno}: {message}") + failed = True + return int(failed) + + +if __name__ == "__main__": + sys.exit(main())