Skip to content

Commit c4c5605

Browse files
authored
Validate C ABI libraries and link extensions against them (#141)
* Validate C ABI libraries and write an artifact manifest Libraries entries accept the hatch-rs validation fields through hatch-native: expected headers, ABI strings, a header symbol prefix, expected exports, an optional ctypes load, and validation commands. A top-level artifacts list validates files that libraries does not name, such as CMake install output, by path or by library name. The artifact-manifest option records each packaged binary in a JSON file in the wheel. Library output directories are created before compiling, so a library can be built into a lib/ subdirectory. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> * Link libraries entries against generic libraries through depends An entry's depends names generic libraries declared before it. The entry links each one's output and gets an $ORIGIN or @loader_path rpath to its directory. On Windows it links the import library, which is packaged next to the DLL. Generic libraries get a SONAME or an @rpath install name unless the project sets one, so the link does not record a build-tree path. depends raises for Emscripten builds. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> * Add library-source for libraries named in depends library-source, or HATCH_CPP_LIBRARY_SOURCE, picks bundled (the default and the existing behavior), external, or direct. In external mode the library is not built: hatch-native finds it under library-root, HATCH_CPP_LIBRARY_ROOT, pkg-config, or the conda prefix, the consumer links it without an rpath, and validation checks the external file. In direct mode its sources are compiled into each consumer. static and python-package raise until hatch-cpp supports them. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> * Add a CMake fixture that validates an installed C ABI library by name Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> * Rename build plan validate to validate_artifacts A validate instance method is an incompatible override of pydantic's BaseModel.validate classmethod, which fails ty. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com> --------- Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com>
1 parent ed37b9b commit c4c5605

17 files changed

Lines changed: 752 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,72 @@ cmake_env_args = {} # env-specific cmake args to pass
8383
include_flags = {} # include flags to pass -D
8484
```
8585

86+
### Linking an extension against a library
87+
88+
A `generic` library can ship next to the extension that links it, in the layout pyarrow uses. List the library first and name it in the extension's `depends`:
89+
90+
```toml
91+
[[tool.hatch.build.hooks.hatch-cpp.libraries]]
92+
name = "project/lib/libdemo"
93+
sources = ["cpp/demo.c"]
94+
language = "c"
95+
binding = "generic"
96+
include-dirs = ["cpp/include"]
97+
define-macros = ["DEMO_BUILD"]
98+
99+
[[tool.hatch.build.hooks.hatch-cpp.libraries]]
100+
name = "project/extension"
101+
sources = ["cpp/extension.c"]
102+
language = "c"
103+
include-dirs = ["cpp/include"]
104+
depends = ["project/lib/libdemo"]
105+
```
106+
107+
The library builds first. On Linux it gets `-soname libdemo.so` and on macOS the install name `@rpath/libdemo.dylib`, unless `extra-link-args` already set one. The extension links the built file and gets an rpath to its directory (`$ORIGIN/lib`, `@loader_path/lib`), so the wheel works wherever it is installed. On Windows the extension links the import library `project/lib/libdemo.lib`, which is packaged next to the DLL. Windows has no rpath, so the package `__init__.py` must call `os.add_dll_directory` on `lib/` before importing the extension, and the library's header must mark its functions `__declspec(dllexport)` when building it and `__declspec(dllimport)` otherwise. `depends` is not supported for Emscripten builds.
108+
109+
`library-source` (or `HATCH_CPP_LIBRARY_SOURCE`, which wins) picks how libraries named in `depends` are provided:
110+
111+
- `bundled` (default): built and shipped in the wheel as above.
112+
- `external`: not built. Each one is found under `library-root` (or `HATCH_CPP_LIBRARY_ROOT`) with `lib/` and `include/`, through `pkg-config = "demo"`, or under `$PREFIX`/`$CONDA_PREFIX` (`Library/` on Windows), by its name without the `lib` prefix. The extension links it with `-L`/`-l` and gets no rpath, so the packager supplies the runtime path; this is the mode a conda recipe uses. Validation fields on the entry check the external library.
113+
- `direct`: not built. Its sources, include directories, and macros are compiled into each entry that depends on it, and no library ships. Use this for Pyodide.
114+
115+
`static` and `python-package` are not supported yet.
116+
117+
Wheel repair tools need to leave the bundled library in place: `auditwheel repair --exclude 'libdemo.so'`, `delocate-wheel --exclude libdemo`, `delvewheel repair --exclude libdemo.dll`.
118+
119+
### C ABI validation
120+
121+
A library that other code links against can be checked after it is built. Validation reads the export table from the binary, so it also works for cross builds and Pyodide. The field names match [hatch-rs](https://github.com/python-project-templates/hatch-rs) and come from [hatch-native](https://github.com/python-project-templates/hatch-native).
122+
123+
Set the fields on a `libraries` entry:
124+
125+
```toml
126+
[[tool.hatch.build.hooks.hatch-cpp.libraries]]
127+
name = "project/lib/libdemo"
128+
sources = ["cpp/demo.c"]
129+
language = "c"
130+
binding = "generic"
131+
include-dirs = ["cpp/include"]
132+
expected-headers = ["cpp/include/demo/demo.h"]
133+
header-symbol-prefix = "demo_" # every demo_* function in the headers must be exported
134+
expected-abi-strings = ["DEMO_ABI_VERSION 1"]
135+
expected-symbols = [] # extra symbols to require
136+
validate = false # also load the library with ctypes
137+
```
138+
139+
Or list `artifacts` to validate files that `libraries` does not name, such as the output of a CMake install. Each entry takes the same fields plus `name` and an optional `path` relative to the project root. Without `path`, `name` matches a `libraries` entry, or else the one packaged file called `lib<name>.so`, `lib<name>.dylib`, or `<name>.dll`:
140+
141+
```toml
142+
[[tool.hatch.build.hooks.hatch-cpp.artifacts]]
143+
name = "demo"
144+
expected-headers = ["project/include/demo/demo.h"]
145+
header-symbol-prefix = "demo_"
146+
```
147+
148+
`validation-commands` run after the checks, with `{name}`, `{path}`, and `{header}` substituted and `HATCH_CPP_ARTIFACT_NAME` and `HATCH_CPP_ARTIFACT_PATH` in the environment.
149+
150+
To record what was packaged, set `artifact-manifest = true` and `artifact-manifest-destination = "project/lib/hatch-cpp-artifacts.json"`. The JSON lists each packaged binary with its role (`python-extension` or `library`), platform, and profile, and is added to the wheel.
151+
86152
### CLI
87153

88154
`hatch-cpp` is integrated with [`hatch-build`](https://github.com/python-project-templates/hatch-build) to allow easy configuration of options via command line:

‎hatch_cpp/config.py‎

Lines changed: 190 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,33 @@
11
from __future__ import annotations
22

3+
from importlib.machinery import EXTENSION_SUFFIXES
34
from os import environ, system as system_call
45
from pathlib import Path
56

7+
from hatch_native import (
8+
ExternalLibrary,
9+
LibraryValidationConfig,
10+
check_exports,
11+
check_headers,
12+
prefixed_header_symbols,
13+
resolve_external_library,
14+
resolve_library_source,
15+
run_validation_command,
16+
shared_library_name,
17+
write_artifact_manifest,
18+
)
619
from pkn import getSimpleLogger
7-
from pydantic import BaseModel, Field, model_validator
20+
from pydantic import AliasChoices, BaseModel, Field, PrivateAttr, model_validator
821

9-
from .toolchains import BuildType, HatchCppCmakeConfiguration, HatchCppLibrary, HatchCppPlatform, HatchCppVcpkgConfiguration, Toolchain
22+
from .toolchains import (
23+
BuildType,
24+
HatchCppArtifact,
25+
HatchCppCmakeConfiguration,
26+
HatchCppLibrary,
27+
HatchCppPlatform,
28+
HatchCppVcpkgConfiguration,
29+
Toolchain,
30+
)
1031

1132
__all__ = (
1233
"HatchCppBuildConfig",
@@ -27,6 +48,18 @@ class HatchCppBuildConfig(BaseModel):
2748
cmake: HatchCppCmakeConfiguration | None = Field(default=None)
2849
platform: HatchCppPlatform = Field(default_factory=HatchCppPlatform.default)
2950
vcpkg: HatchCppVcpkgConfiguration | None = Field(default_factory=HatchCppVcpkgConfiguration)
51+
library_source: str = Field(
52+
default="bundled",
53+
validation_alias=AliasChoices("library-source", "library_source"),
54+
description="How libraries named in depends are provided: bundled, external, or direct. Overridden by HATCH_CPP_LIBRARY_SOURCE.",
55+
)
56+
artifacts: list[HatchCppArtifact] = Field(default_factory=list)
57+
artifact_manifest: bool = Field(default=False, validation_alias=AliasChoices("artifact-manifest", "artifact_manifest"))
58+
artifact_manifest_destination: str | None = Field(
59+
default=None,
60+
validation_alias=AliasChoices("artifact-manifest-destination", "artifact_manifest_destination"),
61+
description="Wheel-relative path of the artifact manifest JSON, such as project/lib/hatch-cpp-artifacts.json.",
62+
)
3063

3164
@model_validator(mode="wrap")
3265
@classmethod
@@ -50,6 +83,16 @@ def validate_model(cls, data, handler):
5083
model = handler(data)
5184
if model.cmake and model.libraries:
5285
raise ValueError("Must not provide libraries when using cmake toolchain.")
86+
declared: dict[str, HatchCppLibrary] = {}
87+
for library in model.libraries:
88+
if library.python_package is not None:
89+
raise ValueError(f"Library '{library.name}' sets python-package, which hatch-cpp does not support yet.")
90+
for name in library.depends:
91+
if name not in declared or declared[name].binding != "generic":
92+
raise ValueError(f"Library '{library.name}' depends on '{name}', which must be a generic library declared before it.")
93+
declared[library.name] = library
94+
if model.artifact_manifest and not model.artifact_manifest_destination:
95+
raise ValueError("artifact-manifest requires artifact-manifest-destination.")
5396
return model
5497

5598

@@ -58,6 +101,48 @@ class HatchCppBuildPlan(HatchCppBuildConfig):
58101
commands: list[str] = Field(default_factory=list)
59102

60103
_active_toolchains: list[Toolchain] = []
104+
_external_libraries: dict[str, ExternalLibrary] = PrivateAttr(default_factory=dict)
105+
_skipped_libraries: set[str] = PrivateAttr(default_factory=set)
106+
107+
def built_libraries(self) -> list[HatchCppLibrary]:
108+
"""Libraries this build compiles; external and direct mode skip the ones other entries depend on."""
109+
return [library for library in self.libraries if library.name not in self._skipped_libraries]
110+
111+
def _resolve_external(self, library: HatchCppLibrary) -> ExternalLibrary:
112+
root = environ.get("HATCH_CPP_LIBRARY_ROOT") or (str(library.library_root) if library.library_root is not None else None)
113+
name = Path(library.name).name
114+
if name.startswith("lib") and len(name) > 3:
115+
name = name[3:]
116+
return resolve_external_library(
117+
name,
118+
label=library.name,
119+
platform=self.platform.platform,
120+
root_env_var="HATCH_CPP_LIBRARY_ROOT",
121+
root=Path(root).resolve() if root else None,
122+
pkg_config=library.pkg_config,
123+
)
124+
125+
def _consumer(self, library: HatchCppLibrary, source: str) -> tuple[HatchCppLibrary, list[HatchCppLibrary]]:
126+
"""The library to compile and the libraries it links, after applying the library-source mode to its depends."""
127+
dependencies = [next(other for other in self.libraries if other.name == name) for name in library.depends]
128+
if not dependencies or source == "bundled":
129+
return library, dependencies
130+
if source == "external":
131+
externals = [self._external_libraries[dependency.name] for dependency in dependencies]
132+
return library.model_copy(
133+
update={
134+
"include_dirs": [*library.include_dirs, *(str(external.include_dir) for external in externals if external.include_dir)],
135+
"library_dirs": [*library.library_dirs, *(str(external.library_dir) for external in externals)],
136+
"libraries": [*library.libraries, *(external.link_name for external in externals)],
137+
}
138+
), []
139+
return library.model_copy(
140+
update={
141+
"sources": [*library.sources, *(path for dependency in dependencies for path in dependency.sources)],
142+
"include_dirs": [*library.include_dirs, *(path for dependency in dependencies for path in dependency.include_dirs)],
143+
"define_macros": [*library.define_macros, *(macro for dependency in dependencies for macro in dependency.define_macros)],
144+
}
145+
), []
61146

62147
def generate(self):
63148
self.commands = []
@@ -94,9 +179,20 @@ def generate(self):
94179
if "vcpkg" in self._active_toolchains:
95180
log.warning("vcpkg toolchain is active; ensure that your compiler is configured to use vcpkg includes and libs.")
96181

182+
source = resolve_library_source(self.library_source, env_var="HATCH_CPP_LIBRARY_SOURCE")
183+
if source == "static":
184+
raise ValueError("library-source 'static' is not supported by hatch-cpp; use bundled, external, or direct.")
185+
linked = {name for library in self.libraries for name in library.depends}
186+
self._external_libraries = {}
187+
self._skipped_libraries = set() if source == "bundled" else linked
97188
for library_index, library in enumerate(self.libraries):
189+
if library.name in self._skipped_libraries:
190+
if source == "external":
191+
self._external_libraries[library.name] = self._resolve_external(library)
192+
continue
193+
library, dependencies = self._consumer(library, source)
98194
compile_flags = self.platform.get_compile_flags(library, self.build_type)
99-
link_flags = self.platform.get_link_flags(library, self.build_type)
195+
link_flags = self.platform.get_link_flags(library, self.build_type, dependencies)
100196
compiler = self.platform.cc if library.language == "c" else self.platform.cxx
101197
if self.platform.platform == "emscripten":
102198
objects = []
@@ -117,6 +213,9 @@ def generate(self):
117213
def execute(self):
118214
if self.platform.platform == "emscripten" and "vanilla" in self._active_toolchains:
119215
Path("build/hatch-cpp").mkdir(parents=True, exist_ok=True)
216+
if "vanilla" in self._active_toolchains:
217+
for library in self.built_libraries():
218+
Path(self._library_output(library)).parent.mkdir(parents=True, exist_ok=True)
120219
for command in self.commands:
121220
ret = system_call(command)
122221
if ret != 0:
@@ -127,3 +226,91 @@ def cleanup(self):
127226
if self.platform.platform == "win32":
128227
for temp_obj in Path(".").glob("*.obj"):
129228
temp_obj.unlink()
229+
230+
def _library_output(self, library: HatchCppLibrary) -> str:
231+
return library.get_qualified_name(self.platform.platform)
232+
233+
def _artifact_path(self, artifact: HatchCppArtifact, packaged: list[str]) -> str:
234+
if artifact.path:
235+
return artifact.path
236+
library = next((library for library in self.libraries if library.name == artifact.name), None)
237+
if library is not None:
238+
return self._library_output(library)
239+
filename = shared_library_name(Path(artifact.name).name, platform=self.platform.platform)
240+
matches = [path for path in packaged if Path(path).name == filename]
241+
if len(matches) != 1:
242+
found = ", ".join(matches) if matches else "none"
243+
raise FileNotFoundError(f"Artifact '{artifact.name}' needs a path: expected one packaged '{filename}', found {found}.")
244+
return matches[0]
245+
246+
def validation_targets(self, packaged: list[str]) -> list[tuple[str, LibraryValidationConfig, str]]:
247+
"""Libraries with validation fields set, plus every `artifacts` entry, as (label, config, project-relative path)."""
248+
targets: list[tuple[str, LibraryValidationConfig, str]] = []
249+
for library in self.libraries:
250+
if not _has_validation(library):
251+
continue
252+
if library.name in self._external_libraries:
253+
targets.append((library.name, library, str(self._external_libraries[library.name].library)))
254+
elif library.name not in self._skipped_libraries:
255+
targets.append((library.name, library, self._library_output(library)))
256+
targets.extend((artifact.name, artifact, self._artifact_path(artifact, packaged)) for artifact in self.artifacts)
257+
return targets
258+
259+
def validate_artifacts(self, root: Path, packaged: list[str]) -> None:
260+
"""Check headers, ABI strings, and exports of each validation target, then run its validation commands."""
261+
for label, config, relative in self.validation_targets(packaged):
262+
library = root / relative
263+
if not library.is_file():
264+
raise FileNotFoundError(f"Artifact '{label}' library was not built: {relative}")
265+
headers = check_headers(config.expected_headers, config.expected_abi_strings, base=root, label=label)
266+
expected = list(dict.fromkeys([*config.expected_symbols, *prefixed_header_symbols(headers, config.header_symbol_prefix, label=label)]))
267+
check_exports(library, expected=expected, load=config.validate_artifact, label=label, display_path=relative)
268+
tokens = {"name": label, "path": str(library), "header": str(headers[0]) if headers else ""}
269+
for command in config.validation_commands:
270+
env = {**environ, **{key: value.format(**tokens) for key, value in command.env.items()}}
271+
env.update({"HATCH_CPP_ARTIFACT_NAME": label, "HATCH_CPP_ARTIFACT_PATH": str(library)})
272+
cwd = root / command.working_directory if command.working_directory else root
273+
run_validation_command([value.format(**tokens) for value in command.command], cwd=cwd, env=env, label=label)
274+
275+
def write_manifest(self, root: Path, packaged: list[str]) -> str | None:
276+
"""Write the manifest of packaged binaries under the project root and return its relative path."""
277+
if not self.artifact_manifest:
278+
return None
279+
assert self.artifact_manifest_destination is not None
280+
records = [
281+
{
282+
"name": Path(path).name,
283+
"role": _artifact_role(path, self.platform.platform),
284+
"platform": self.platform.platform,
285+
"profile": self.build_type,
286+
"destination": Path(path).as_posix(),
287+
}
288+
for path in sorted(packaged)
289+
]
290+
write_artifact_manifest(root / self.artifact_manifest_destination, module=self.name or "", records=records)
291+
return self.artifact_manifest_destination
292+
293+
294+
def _has_validation(config: LibraryValidationConfig) -> bool:
295+
return bool(
296+
config.expected_symbols
297+
or config.expected_headers
298+
or config.expected_abi_strings
299+
or config.header_symbol_prefix
300+
or config.validate_artifact
301+
or config.validation_commands
302+
)
303+
304+
305+
def _artifact_role(path: str, platform: str) -> str:
306+
"""Classify a packaged binary: a Python extension module or a plain shared library."""
307+
filename = Path(path).name
308+
if filename.endswith(".pyd"):
309+
return "python-extension"
310+
if platform != "win32" and filename.startswith("lib"):
311+
return "library"
312+
if any(filename.endswith(suffix) for suffix in EXTENSION_SUFFIXES if suffix != ".so") or ".abi3." in filename:
313+
return "python-extension"
314+
if filename.endswith(".so") and platform in ("linux", "darwin", "emscripten"):
315+
return "python-extension"
316+
return "library"

‎hatch_cpp/plugin.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,12 @@ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
8888

8989
if build_plan.libraries:
9090
# force include libraries
91-
for library in build_plan.libraries:
91+
for library in build_plan.built_libraries():
9292
name = library.get_qualified_name(build_plan.platform.platform)
9393
build_data["force_include"][name] = name
94+
import_library = Path(name).with_suffix(".lib")
95+
if build_plan.platform.platform == "win32" and library.binding == "generic" and import_library.is_file():
96+
build_data["force_include"][import_library.as_posix()] = import_library.as_posix()
9497

9598
build_data["pure_python"] = False
9699
machine = platform_machine()
@@ -101,7 +104,7 @@ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
101104
machine,
102105
version_major,
103106
version_minor,
104-
all(lib.py_limited_api for lib in build_plan.libraries),
107+
all(lib.py_limited_api for lib in build_plan.built_libraries()),
105108
)
106109
else:
107110
assert build_plan.cmake is not None
@@ -120,5 +123,11 @@ def initialize(self, version: str, build_data: dict[str, Any]) -> None:
120123
if path.suffix in (".pyd", ".dll", ".so", ".dylib"):
121124
build_data["force_include"][str(path)] = str(path)
122125

126+
packaged = list(build_data["force_include"])
127+
build_plan.validate_artifacts(Path(self.root), packaged)
128+
manifest = build_plan.write_manifest(Path(self.root), packaged)
129+
if manifest is not None:
130+
build_data["force_include"][manifest] = manifest
131+
123132
for path in build_data["force_include"]:
124133
self._logger.info(f"Force include: {path}")
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#include "demo/demo.h"
2+
3+
int demo_abi_version(void) { return DEMO_ABI_VERSION; }
4+
5+
int demo_answer(void) { return 42; }
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#include <Python.h>
2+
3+
#include "demo/demo.h"
4+
5+
static PyObject *answer(PyObject *self, PyObject *args) { return PyLong_FromLong(demo_answer()); }
6+
7+
static PyMethodDef methods[] = {{"answer", answer, METH_NOARGS, NULL}, {NULL, NULL, 0, NULL}};
8+
9+
static struct PyModuleDef module = {PyModuleDef_HEAD_INIT, "extension", NULL, -1, methods};
10+
11+
PyMODINIT_FUNC PyInit_extension(void) { return PyModule_Create(&module); }

0 commit comments

Comments
 (0)