Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 11 additions & 4 deletions cuda_core/cuda/core/_rt.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions cuda_core/cuda/core/_rt.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
94 changes: 94 additions & 0 deletions toolshed/check_cython_bool_returns.py
Original file line number Diff line number Diff line change
@@ -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<name>[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<name>[A-Za-z_]\w*)\s*
(?:"(?P<cname>[^"]*)"\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:
Comment on lines +71 to +72

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Heavy lift

Do not identify C++ functions by their unqualified name alone.

If a header contains flags::get() returning bool and counts::get() returning int, a correct Cython declaration of counts::get() as bint fails this check. The collector stores only get, and this lookup ignores the extern block's namespace.

Match the declaration to its C++ namespace and overload before rejecting its return type. Otherwise, the hook rejects valid bindings.

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())
Loading