Skip to content

Commit 6f0376d

Browse files
authored
Check every function a header declares is exported (#92)
Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com>
1 parent 7c223e0 commit 6f0376d

10 files changed

Lines changed: 260 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,26 @@ include-import-lib = true
183183
command = ["python", "scripts/validate_abi.py", "{destination}", "{header}"]
184184
```
185185

186+
With `expected-symbols`, the build checks only the symbols in that list, so a
187+
function left out of it is never checked. To check every function a header
188+
declares, set `header-symbol-prefix` instead. Every function in
189+
`expected-headers` whose name starts with the prefix must then be exported by
190+
the copied library. Comments, preprocessor lines, and `static inline`
191+
definitions are skipped, since the library does not export them:
192+
193+
```toml
194+
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
195+
name = "project_ffi"
196+
manifest = "rust/Cargo.toml"
197+
destination = "project/lib/{shared_library}"
198+
expected-headers = ["project/include/project.h"]
199+
header-symbol-prefix = "project_ffi_"
200+
```
201+
202+
hatch-rs finds the declarations with regular expressions rather than a C
203+
parser, which works for a hand-written or generated ABI header. If a header
204+
declares functions through macros, list them in `expected-symbols`.
205+
186206
`include-import-lib` only packages an import library on Windows targets, where
187207
Cargo emits `.dll.lib` or `.dll.a` files for downstream native linkers.
188208

‎hatch_rs/structs.py‎

Lines changed: 52 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from os import environ
1010
from pathlib import Path
1111
from platform import machine as platform_machine
12-
from re import sub
12+
from re import DOTALL, MULTILINE, escape, findall, sub
1313
from shlex import join as shell_join
1414
from shutil import copy2
1515
from subprocess import run
@@ -31,6 +31,7 @@
3131
"RustArtifactConfig",
3232
"ValidationCommandConfig",
3333
"executable_name",
34+
"header_symbols",
3435
"python_extension_name",
3536
"resolve_target_triple",
3637
"shared_library_name",
@@ -431,6 +432,23 @@ def _cargo_artifact_stem(path: Path) -> str:
431432
return stem
432433

433434

435+
def header_symbols(text: str, prefix: str) -> list[str]:
436+
"""Functions declared in a C header whose names start with `prefix`.
437+
438+
Comments, preprocessor lines and `static inline` definitions are skipped,
439+
since none of them is exported by the library. Declarations are found with
440+
regular expressions rather than a C parser, which works for a hand-written
441+
or generated ABI header.
442+
"""
443+
text = sub(r"/\*.*?\*/", " ", text, flags=DOTALL)
444+
text = sub(r"//[^\n]*", " ", text)
445+
text = sub(r"^\s*#.*?(?<!\\)$", " ", text, flags=MULTILINE | DOTALL)
446+
text = sub(r"\bstatic\s+inline\b[^;{]*\{", "static inline {", text)
447+
declared = findall(rf"\b({escape(prefix)}\w*)\s*\(", text)
448+
inline = set(findall(rf"\bstatic\s+(?:inline\s+)?[^;{{(]*?\b({escape(prefix)}\w*)\s*\(", text))
449+
return sorted(set(declared) - inline)
450+
451+
434452
def _resolve_path(path: Path | str, *, base: Path) -> Path:
435453
path = Path(path)
436454
if path.is_absolute():
@@ -583,6 +601,11 @@ class RustArtifactConfig(BaseModel):
583601
cpp_compat: bool = Field(default=False, alias="cpp-compat", description="Reserved for cbindgen C++ compatibility presets.")
584602
depfile: Path | None = Field(default=None, description="Reserved depfile path for generated headers.")
585603
expected_symbols: list[str] = Field(default_factory=list, alias="expected-symbols", description="Exported symbols expected in a copied library.")
604+
header_symbol_prefix: str | None = Field(
605+
default=None,
606+
alias="header-symbol-prefix",
607+
description="Expect every function in expected-headers whose name starts with this prefix to be exported.",
608+
)
586609
expected_headers: list[Path] = Field(default_factory=list, alias="expected-headers", description="Header files expected to exist after build.")
587610
expected_abi_strings: list[str] = Field(
588611
default_factory=list,
@@ -680,6 +703,12 @@ def validate_optional_path(cls, path: Path | None) -> Path | None:
680703
path = Path(path)
681704
return path
682705

706+
@model_validator(mode="after")
707+
def validate_header_symbol_prefix(self) -> RustArtifactConfig:
708+
if self.header_symbol_prefix is not None and not self.expected_headers:
709+
raise ValueError(f"Artifact '{self.name}' must set expected-headers when using header-symbol-prefix.")
710+
return self
711+
683712

684713
@dataclass(frozen=True)
685714
class PlannedArtifact:
@@ -1592,9 +1621,22 @@ def _validate_expected_headers(self, artifact: RustArtifactConfig) -> list[Path]
15921621
raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' expected ABI string was not found in headers: {expected}")
15931622
return headers
15941623

1595-
def _validate_library_exports(self, planned_artifact: PlannedArtifact, copied_artifacts: list[CopiedArtifact]) -> None:
1624+
def _header_symbols(self, artifact: RustArtifactConfig, headers: list[Path]) -> list[str]:
1625+
if artifact.header_symbol_prefix is None:
1626+
return []
1627+
symbols = sorted(
1628+
{symbol for header in headers for symbol in header_symbols(header.read_text(errors="replace"), artifact.header_symbol_prefix)}
1629+
)
1630+
if not symbols:
1631+
raise RuntimeError(
1632+
f"Artifact '{self._artifact_label(artifact)}' expected headers declare no functions starting with '{artifact.header_symbol_prefix}'."
1633+
)
1634+
return symbols
1635+
1636+
def _validate_library_exports(self, planned_artifact: PlannedArtifact, copied_artifacts: list[CopiedArtifact], headers: list[Path]) -> None:
15961637
artifact = planned_artifact.artifact
1597-
if not artifact.validate_artifact and not artifact.expected_symbols:
1638+
expected = list(dict.fromkeys([*artifact.expected_symbols, *self._header_symbols(artifact, headers)]))
1639+
if not artifact.validate_artifact and not expected:
15981640
return
15991641
if not copied_artifacts:
16001642
raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' has no copied library to validate.")
@@ -1607,11 +1649,14 @@ def _validate_library_exports(self, planned_artifact: PlannedArtifact, copied_ar
16071649
f"Artifact '{self._artifact_label(artifact)}' failed validation load check for '{copied_library.distribution_path}': {error}"
16081650
) from error
16091651

1610-
for symbol in artifact.expected_symbols:
1652+
missing = []
1653+
for symbol in expected:
16111654
try:
16121655
getattr(library, symbol)
1613-
except AttributeError as error:
1614-
raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' expected symbol was not exported: {symbol}") from error
1656+
except AttributeError:
1657+
missing.append(symbol)
1658+
if missing:
1659+
raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' expected symbol was not exported: {', '.join(missing)}")
16151660

16161661
def _validation_tokens(self, planned_artifact: PlannedArtifact, copied_artifacts: list[CopiedArtifact], headers: list[Path]) -> dict[str, str]:
16171662
artifact = planned_artifact.artifact
@@ -1675,7 +1720,7 @@ def _run_validation_commands(
16751720

16761721
def _validate_artifact(self, planned_artifact: PlannedArtifact, *, build_root: Path, copied_artifacts: list[CopiedArtifact]) -> None:
16771722
headers = self._validate_expected_headers(planned_artifact.artifact)
1678-
self._validate_library_exports(planned_artifact, copied_artifacts)
1723+
self._validate_library_exports(planned_artifact, copied_artifacts, headers)
16791724
self._run_validation_commands(planned_artifact, build_root=build_root, copied_artifacts=copied_artifacts, headers=headers)
16801725

16811726
def _format_artifact_manifest_destination(self) -> Path:

‎hatch_rs/tests/test_project_c_abi_header_symbols/Cargo.lock‎

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
name = "header_symbols"
3+
version = "0.1.0"
4+
edition = "2021"
5+
publish = false
6+
7+
[lib]
8+
name = "header_symbols"
9+
path = "src/lib.rs"
10+
crate-type = ["cdylib"]

‎hatch_rs/tests/test_project_c_abi_header_symbols/header_symbols_project/__init__.py‎

Whitespace-only changes.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#ifndef HEADER_SYMBOLS_H
2+
#define HEADER_SYMBOLS_H
3+
4+
int header_symbols_answer(void);
5+
6+
/* Declared but not exported: the build must fail. */
7+
int header_symbols_missing(void);
8+
9+
static inline int header_symbols_check(void) {
10+
return header_symbols_answer() == 42;
11+
}
12+
13+
#endif
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
[build-system]
2+
requires = ["hatchling>=1.20"]
3+
build-backend = "hatchling.build"
4+
5+
[project]
6+
name = "hatch-rs-test-project-c-abi-header-symbols"
7+
description = "Header symbol validation test project for hatch-rs"
8+
version = "0.1.0"
9+
requires-python = ">=3.9"
10+
dependencies = [
11+
"hatchling>=1.20",
12+
"hatch-rs",
13+
]
14+
15+
[tool.hatch.build]
16+
artifacts = [
17+
"header_symbols_project/lib/*.dll",
18+
"header_symbols_project/lib/*.dylib",
19+
"header_symbols_project/lib/*.so",
20+
]
21+
22+
[tool.hatch.build.sources]
23+
src = "/"
24+
25+
[tool.hatch.build.targets.sdist]
26+
packages = ["header_symbols_project"]
27+
28+
[tool.hatch.build.targets.wheel]
29+
packages = ["header_symbols_project"]
30+
31+
[tool.hatch.build.hooks.hatch-rs]
32+
verbose = true
33+
path = "."
34+
module = "header_symbols_project"
35+
target-dir = "isolated"
36+
37+
[[tool.hatch.build.hooks.hatch-rs.artifacts]]
38+
name = "header_symbols"
39+
manifest = "Cargo.toml"
40+
destination = "header_symbols_project/lib/{shared_library}"
41+
expected-headers = ["header_symbols_project/include/header_symbols.h"]
42+
header-symbol-prefix = "header_symbols_"
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#[no_mangle]
2+
pub extern "C" fn header_symbols_answer() -> i32 {
3+
42
4+
}

‎hatch_rs/tests/test_projects.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,36 @@ def test_c_abi_symbol_validation_failure(self):
363363
assert completed.returncode != 0
364364
assert "validation_failure_missing_symbol" in completed.stdout
365365

366+
def test_c_abi_header_symbol_validation_failure(self):
367+
project_folder = "test_project_c_abi_header_symbols"
368+
project_root = Path("hatch_rs/tests") / project_folder
369+
package_dir = project_root / "header_symbols_project"
370+
371+
# cleanup
372+
rmtree(project_root / "dist", ignore_errors=True)
373+
rmtree(project_root / "target", ignore_errors=True)
374+
rmtree(package_dir / "lib", ignore_errors=True)
375+
376+
completed = run(
377+
[
378+
executable,
379+
"-m",
380+
"hatchling",
381+
"build",
382+
"--hooks-only",
383+
],
384+
cwd=project_root,
385+
env=_subprocess_env(),
386+
stderr=STDOUT,
387+
stdout=PIPE,
388+
text=True,
389+
check=False,
390+
)
391+
392+
assert completed.returncode != 0
393+
assert "header_symbols_missing" in completed.stdout
394+
assert "header_symbols_check" not in completed.stdout
395+
366396
def test_editable_debug(self):
367397
project_folder = "test_project_editable_debug"
368398
# cleanup

‎hatch_rs/tests/test_structs.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
HatchRustBuildPlan,
1313
RustArtifactConfig,
1414
executable_name,
15+
header_symbols,
1516
python_extension_name,
1617
resolve_target_triple,
1718
shared_library_name,
@@ -853,6 +854,87 @@ def test_build_plan_missing_expected_header_string_fails_clearly(tmp_path):
853854
plan._copy_outputs(planned_artifact, build_root=tmp_path)
854855

855856

857+
def test_header_symbols_lists_prefixed_declarations():
858+
header = """
859+
#define PROJECT_ABI_VERSION 1
860+
#define project_ffi_macro(x) (x)
861+
/* int project_ffi_commented(void); */
862+
// int project_ffi_line_commented(void);
863+
typedef struct project_ffi_handle project_ffi_handle;
864+
865+
int project_ffi_answer(void);
866+
project_ffi_handle *project_ffi_new(
867+
const char *name,
868+
int flags);
869+
void other_library_call(void);
870+
871+
static inline int project_ffi_inline_check(void) {
872+
return project_ffi_answer() == 42;
873+
}
874+
"""
875+
assert header_symbols(header, "project_ffi_") == ["project_ffi_answer", "project_ffi_new"]
876+
877+
878+
def _plan_with_header(tmp_path, header_text, **artifact):
879+
header = tmp_path / "project" / "include" / "project.h"
880+
header.parent.mkdir(parents=True)
881+
header.write_text(header_text)
882+
plan = HatchRustBuildPlan(
883+
module="project",
884+
path=tmp_path,
885+
target="x86_64-unknown-linux-gnu",
886+
artifacts=[{"name": "project_ffi", "expected-headers": ["project/include/project.h"], **artifact}],
887+
)
888+
plan.generate()
889+
source = tmp_path / "target" / "x86_64-unknown-linux-gnu" / "release" / "libproject_ffi.so"
890+
source.parent.mkdir(parents=True)
891+
source.write_bytes(b"shared library")
892+
return plan
893+
894+
895+
class _FakeLibrary:
896+
def __init__(self, exported):
897+
self._exported = set(exported)
898+
899+
def __getattr__(self, name):
900+
if name in self._exported:
901+
return object()
902+
raise AttributeError(name)
903+
904+
905+
def test_build_plan_expects_every_header_symbol(tmp_path, monkeypatch):
906+
monkeypatch.setattr("hatch_rs.structs.CDLL", lambda path: _FakeLibrary({"project_ffi_answer", "project_ffi_free"}))
907+
plan = _plan_with_header(
908+
tmp_path,
909+
"int project_ffi_answer(void);\nvoid project_ffi_free(void *p);\n",
910+
**{"header-symbol-prefix": "project_ffi_"},
911+
)
912+
plan._copy_outputs(plan._artifact_plans[0], build_root=tmp_path)
913+
914+
915+
def test_build_plan_missing_header_symbol_fails_clearly(tmp_path, monkeypatch):
916+
monkeypatch.setattr("hatch_rs.structs.CDLL", lambda path: _FakeLibrary({"project_ffi_answer"}))
917+
plan = _plan_with_header(
918+
tmp_path,
919+
"int project_ffi_answer(void);\nvoid project_ffi_free(void *p);\n",
920+
**{"header-symbol-prefix": "project_ffi_"},
921+
)
922+
with pytest.raises(RuntimeError, match="project_ffi_free"):
923+
plan._copy_outputs(plan._artifact_plans[0], build_root=tmp_path)
924+
925+
926+
def test_build_plan_header_without_prefixed_symbols_fails_clearly(tmp_path, monkeypatch):
927+
monkeypatch.setattr("hatch_rs.structs.CDLL", lambda path: _FakeLibrary(set()))
928+
plan = _plan_with_header(tmp_path, "int other_answer(void);\n", **{"header-symbol-prefix": "project_ffi_"})
929+
with pytest.raises(RuntimeError, match="no functions starting with 'project_ffi_'"):
930+
plan._copy_outputs(plan._artifact_plans[0], build_root=tmp_path)
931+
932+
933+
def test_header_symbol_prefix_requires_headers():
934+
with pytest.raises(ValueError, match="expected-headers"):
935+
RustArtifactConfig.model_validate({"name": "project_ffi", "header-symbol-prefix": "project_ffi_"})
936+
937+
856938
def test_build_plan_copies_windows_import_library(tmp_path):
857939
plan = HatchRustBuildPlan(
858940
module="project",

0 commit comments

Comments
 (0)