diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 6904d8e..c47a248 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -49,8 +49,8 @@ jobs: - name: Install dependencies run: make develop - - name: Install Cargo license collector - run: cargo install cargo-bundle-licenses --version 4.2.0 --locked + - name: Install Cargo license collector and cbindgen + run: cargo install cargo-bundle-licenses@4.2.0 cbindgen@0.29.4 --locked - name: Lint run: make lint diff --git a/.gitignore b/.gitignore index de0b1e1..19821fc 100644 --- a/.gitignore +++ b/.gitignore @@ -164,3 +164,7 @@ AGENTS.md # Generated by test_project_generated_files fixture during the test suite hatch_rs/tests/test_project_generated_files/generated_files_project/generated/ hatch_rs/tests/test_project_generated_files/generated_files_project/include/ + +# generated fixture headers +hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/include/ +hatch_rs/tests/test_project_cbindgen_build_script/build_script_project/include/ diff --git a/README.md b/README.md index 8147fa5..a1754c7 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,116 @@ destination = "include/project/project.h" install-scheme = "shared-data" ``` +### cbindgen headers + +`generator = "cbindgen"` declares a header artifact. hatch-rs runs the +`cbindgen` executable with the crate, config, language, and first output path, +so the header does not need to be checked in. `verify = true` passes +`--verify`, which fails when a checked-in header is stale. + +```toml +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "project_ffi_header" +generator = "cbindgen" +crate = "rust" +config = "rust/cbindgen.toml" +inputs = ["rust/src/lib.rs", "rust/cbindgen.toml"] + +[[tool.hatch.build.hooks.hatch-rs.artifacts.outputs]] +source = "project/include/project.h" +install-scheme = "validate-only" +``` + +When the crate's `build.rs` writes the header through the `cbindgen` library +instead, no generator artifact is needed. The header exists once the Cargo +build finishes, so validate it on the library artifact: + +```toml +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "project_ffi" +manifest = "rust/Cargo.toml" +destination = "project/lib/{shared_library}" +expected-headers = ["project/include/project.h"] +header-symbol-prefix = "project_ffi_" +``` + +Use `validate-only` when the header already reaches the wheel through +`tool.hatch.build.artifacts`; use `package` or `shared-data` to have hatch-rs +place it. + +### Linking an extension against a C ABI library + +A Python extension can link a `cdylib` artifact instead of compiling the +library crate into itself, so one copy of the library serves every extension +in a process. The extension artifact names the library with `links`, and +`library-source` chooses where that library comes from: + +| `library-source` | Library artifact | Extension links | +| ---------------- | ------------------------ | ------------------------------------------------- | +| `bundled` | built, shipped in `lib/` | the bundled copy, with an rpath to it | +| `external` | not built | a prebuilt library found outside the project | +| `static` | not built | nothing; the crate compiles the C ABI in | +| `direct` | not built | nothing; the crate uses the Rust library directly | + +`bundled` is the default and the wheel layout. `HATCH_RS_LIBRARY_SOURCE` +overrides the configured value, which is how a conda recipe builds the same +project in `external` mode against its own `libfoo` package. + +```toml +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "project_ffi" +manifest = "rust/Cargo.toml" +destination = "project/lib/{shared_library}" +pkg-config = "project" + +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "project_py" +destination = "project/{python_extension_name}" +links = ["project_ffi"] + +[tool.hatch.build.hooks.hatch-rs.artifacts.library-source-features] +bundled = ["capi"] +external = ["capi"] +static = ["capi-static"] +direct = ["direct"] +``` + +Cargo cannot switch dependencies from an environment variable, so +`library-source-features` maps each mode to the Cargo features of the +extension crate; the selected list is passed with `--no-default-features`. +Typically one feature depends on a `-sys` crate with `extern "C"` +declarations and another on the Rust library crate itself. + +Every Cargo invocation sees `HATCH_RS_LIBRARY_SOURCE`. An artifact with +`links` also gets `HATCH_RS_LIBRARY__DIR` and, in external mode, +`HATCH_RS_LIBRARY__INCLUDE_DIR`, for a `build.rs` that needs them. + +In `bundled` mode hatch-rs builds the library first, gives it a layout-neutral +identity (`-soname libfoo.so` on Linux, `@rpath/libfoo.dylib` as the install +name on macOS; every `cdylib` artifact gets this, linked or not), copies it to +its destination, and links the extension with +`-L`/`-l dylib` plus an rpath relative to the extension (`$ORIGIN/lib` or +`@loader_path/lib` for the layout above). On Windows the import library is +packaged next to the DLL, and the package must call +`os.add_dll_directory()` on its `lib/` directory before importing the +extension. The library crate's own `Cargo.toml` must declare +`crate-type = ["cdylib"]` (an `rlib` crate built with `--crate-type cdylib` +keeps Cargo's metadata hash in the DLL name, which the import library then +records); hatch-rs fails the build when the import library names a different +DLL. Wheel repair tools must keep the bundled library rather than +vendoring a second copy: `auditwheel repair --exclude 'libfoo.so*'`, +`delocate-wheel --exclude libfoo`, `delvewheel repair --no-mangle foo.dll`. + +In `external` mode the library is resolved, in order, from +`HATCH_RS_LIBRARY_ROOT`, the artifact's `library-root`, its `pkg-config` +module (`libdir` and `includedir` variables), or `$PREFIX`/`$CONDA_PREFIX` +(`Library\` on Windows). The library must exist as `lib/libfoo.so`, +`lib/libfoo.so.N`, `lib/libfoo.dylib`, or `bin/foo.dll` with `lib/foo.lib`. +No rpath is added; the environment's loader path is expected to find the +library. Header, symbol, and validation-command checks still run against the +external file, and the artifact manifest records it with role +`external-library`. + ### ABI validation and artifact metadata `cdylib` artifacts can validate the copied C ABI library before the wheel is @@ -163,6 +273,10 @@ strings/macros, load the copied library with `ctypes.CDLL` when `validate = true run project validation commands, include Windows import libraries, and emit a package-local artifact manifest. +Symbol checks read the export table of the copied ELF, Mach-O, PE, or +WebAssembly file, so they work for cross-compiled and Pyodide artifacts. Only +`validate = true` loads the library, which requires a build for the host. + ```toml [tool.hatch.build.hooks.hatch-rs] module = "project" @@ -187,8 +301,9 @@ With `expected-symbols`, the build checks only the symbols in that list, so a function left out of it is never checked. To check every function a header declares, set `header-symbol-prefix` instead. Every function in `expected-headers` whose name starts with the prefix must then be exported by -the copied library. Comments, preprocessor lines, and `static inline` -definitions are skipped, since the library does not export them: +the copied library. Comments, preprocessor lines, `static inline` +definitions, and function pointer fields such as `foo_status (*open)(...)` are +skipped, since the library does not export them: ```toml [[tool.hatch.build.hooks.hatch-rs.artifacts]] diff --git a/hatch_rs/structs.py b/hatch_rs/structs.py index 019c926..293fd27 100644 --- a/hatch_rs/structs.py +++ b/hatch_rs/structs.py @@ -7,6 +7,7 @@ from glob import glob from json import dumps, loads from os import environ +from os.path import relpath from pathlib import Path from platform import machine as platform_machine from re import DOTALL, MULTILINE, escape, findall, sub @@ -20,10 +21,13 @@ from packaging.tags import cpython_tags, mac_platforms, platform_tags from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator, model_validator +from .symbols import exported_symbols + __all__ = ( "CargoInvocation", "CargoLicenseConfig", "CopiedArtifact", + "ExternalLibrary", "GeneratedOutputConfig", "HatchRustBuildConfig", "HatchRustBuildPlan", @@ -40,12 +44,12 @@ BuildType = Literal["debug", "release"] CargoTargetKind = Literal["lib", "bin", "example", "test", "bench"] -CbindgenMode = Literal["cli", "build-script"] CompilerToolchain = Literal["gcc", "clang", "msvc"] InstallScheme = Literal["package", "shared-data", "shared-scripts", "validate-only"] Language = Literal["c", "c++"] Binding = Literal["cpython", "pybind11", "nanobind", "generic"] Platform = Literal["linux", "darwin", "win32", "emscripten"] +LibrarySource = Literal["bundled", "external", "static", "direct"] @dataclass(frozen=True) @@ -80,6 +84,17 @@ class CopiedArtifact: distribution_path: str +@dataclass(frozen=True) +class ExternalLibrary: + """A prebuilt C ABI library resolved outside the build in external mode.""" + + name: str + library: Path + library_dir: Path + include_dir: Path | None + link_name: str + + WINDOWS_TARGETS = { "x86_64": "x86_64-pc-windows-msvc", "i686": "i686-pc-windows-msvc", @@ -435,8 +450,9 @@ def _cargo_artifact_stem(path: Path) -> str: def header_symbols(text: str, prefix: str) -> list[str]: """Functions declared in a C header whose names start with `prefix`. - Comments, preprocessor lines and `static inline` definitions are skipped, - since none of them is exported by the library. Declarations are found with + Comments, preprocessor lines, `static inline` definitions, and function + pointer declarators such as `prefix_status (*open)(...)` are skipped, since + none of them is exported by the library. Declarations are found with regular expressions rather than a C parser, which works for a hand-written or generated ABI header. """ @@ -444,8 +460,8 @@ def header_symbols(text: str, prefix: str) -> list[str]: text = sub(r"//[^\n]*", " ", text) text = sub(r"^\s*#.*?(? list[str]: return [values] return [str(value) for value in values] - @field_validator("expected_symbols", "expected_abi_strings", mode="before") + @field_validator("expected_symbols", "expected_abi_strings", "links", mode="before") @classmethod def validate_string_list(cls, values: Any) -> list[str]: if values is None: @@ -694,7 +721,7 @@ def validate_validation_commands(cls, values: Any) -> list[Any]: return [{"command": values}] return list(values) - @field_validator("working_directory", "config", "depfile", mode="before") + @field_validator("working_directory", "config", "library_root", mode="before") @classmethod def validate_optional_path(cls, path: Path | None) -> Path | None: if path is None: @@ -720,6 +747,7 @@ class PlannedArtifact: profile: str target_dir: Path set_target_dir_env: bool + external_library: ExternalLibrary | None = None class HatchRustBuildConfig(BaseModel): @@ -750,6 +778,11 @@ class HatchRustBuildConfig(BaseModel): target_dir: str | None = Field(default=None, alias="target-dir", description="Cargo target directory mode or explicit path.") env: dict[str, str] = Field(default_factory=dict, description="Additional environment variables for Cargo.") artifacts: list[RustArtifactConfig] = Field(default_factory=list, description="Explicit Rust artifacts to build and package.") + library_source: LibrarySource = Field( + default="bundled", + alias="library-source", + description="How linked cdylib artifacts are resolved; HATCH_RS_LIBRARY_SOURCE overrides it.", + ) licenses: CargoLicenseConfig | None = Field(default=None, description="Collect and package Cargo dependency license texts when configured.") artifact_manifest: bool = Field( default=False, @@ -828,6 +861,9 @@ class HatchRustBuildPlan(HatchRustBuildConfig): _set_target_dir_env: bool = PrivateAttr(default=False) _temporary_target_dir: TemporaryDirectory[str] | None = PrivateAttr(default=None) _editable_install: bool = PrivateAttr(default=False) + _resolved_library_source: str = PrivateAttr(default="bundled") + _linked_names: set[str] = PrivateAttr(default_factory=set) + _external_libraries: dict[str, ExternalLibrary] = PrivateAttr(default_factory=dict) @property def libraries(self) -> list[str]: @@ -899,8 +935,16 @@ def _artifact_profile(self, artifact: RustArtifactConfig) -> str: return artifact.profile or self.profile or build_type def _artifact_features(self, artifact: RustArtifactConfig) -> list[str]: + mode_features = artifact.library_source_features.get(self._resolved_library_source) + if mode_features is not None: + return list(mode_features) return list(artifact.features if artifact.features is not None else self.features) + def _artifact_no_default_features(self, artifact: RustArtifactConfig) -> bool: + if self._resolved_library_source in artifact.library_source_features: + return True + return self._artifact_bool(artifact.no_default_features, self.no_default_features) + def _artifact_cargo_args(self, artifact: RustArtifactConfig) -> list[str]: return list(artifact.cargo_args if artifact.cargo_args is not None else self.cargo_args) @@ -937,6 +981,7 @@ def _resolve_target_dir(self, manifest: Path | None = None, artifact_env: dict[s def _build_environment(self, artifact_env: dict[str, str], target_dir: Path, set_target_dir_env: bool) -> dict[str, str]: environment = {str(key): str(value) for key, value in environ.items()} + environment["HATCH_RS_LIBRARY_SOURCE"] = self._resolved_library_source environment.update(artifact_env) if set_target_dir_env: environment["CARGO_TARGET_DIR"] = str(target_dir) @@ -964,6 +1009,7 @@ def _build_artifact_plan(self, artifact: RustArtifactConfig, *, global_target: s profile = self._artifact_profile(artifact) manifest = self._artifact_manifest(artifact) artifact_env = self._artifact_env(artifact) + artifact_env.update(self._library_env(artifact, resolved_target)) target_dir, set_target_dir_env = self._resolve_target_dir(manifest, artifact_env) build_command = ["cargo", "rustc"] @@ -979,7 +1025,7 @@ def _build_artifact_plan(self, artifact: RustArtifactConfig, *, global_target: s build_command.extend(("--features", ",".join(features))) if self._artifact_bool(artifact.all_features, self.all_features): build_command.append("--all-features") - if self._artifact_bool(artifact.no_default_features, self.no_default_features): + if self._artifact_no_default_features(artifact): build_command.append("--no-default-features") if self._artifact_bool(artifact.locked, self.locked): build_command.append("--locked") @@ -1021,6 +1067,7 @@ def _build_artifact_plan(self, artifact: RustArtifactConfig, *, global_target: s ) if "crt-static" not in target_features: rustc_args.extend(("-C", "target-feature=-crt-static")) + rustc_args.extend(self._library_rustc_args(artifact, resolved_target)) rustc_args.extend(user_rustc_args) # Executables (bin/example) are not crate-type artifacts; injecting # --crate-type would build them as a library instead of a binary. @@ -1085,7 +1132,7 @@ def _build_command_artifact_plan(self, artifact: RustArtifactConfig, *, global_t target_dir, set_target_dir_env = self._resolve_target_dir(manifest, self._artifact_env(artifact)) command = artifact.command - if artifact.generator == "cbindgen" and artifact.cbindgen_mode == "cli" and command is None: + if artifact.generator == "cbindgen" and command is None: command = self._build_cbindgen_command(artifact) invocation = None @@ -1119,8 +1166,16 @@ def generate(self): self._artifact_manifest_records = [] self._libraries = [] global_target = self.target - for artifact in self._configured_artifacts(): - if self._is_generated_artifact(artifact): + artifacts = self._configured_artifacts() + self._resolved_library_source = self._resolve_library_source() + self._linked_names = self._linked_library_names(artifacts) + self._external_libraries = {} + for artifact in artifacts: + if artifact.name in self._linked_names and self._resolved_library_source in ("static", "direct"): + continue + if artifact.name in self._linked_names and self._resolved_library_source == "external": + planned_artifact = self._plan_external_library(artifact, global_target=global_target) + elif self._is_generated_artifact(artifact): planned_artifact = self._build_command_artifact_plan(artifact, global_target=global_target) else: planned_artifact = self._build_artifact_plan(artifact, global_target=global_target) @@ -1139,6 +1194,176 @@ def generate(self): return self.commands + def _resolve_library_source(self) -> str: + value = environ.get("HATCH_RS_LIBRARY_SOURCE") or self.library_source + if value not in ("bundled", "external", "static", "direct"): + raise ValueError(f"Unsupported HATCH_RS_LIBRARY_SOURCE: {value}") + return value + + def _linked_library_names(self, artifacts: list[RustArtifactConfig]) -> set[str]: + names = set() + declared = [] + for artifact in artifacts: + for link in artifact.links: + if link not in declared: + raise ValueError( + f"Artifact '{self._artifact_label(artifact)}' links '{link}', which must be a named cdylib artifact declared before it." + ) + names.add(link) + if artifact.name and not self._is_generated_artifact(artifact): + declared.append(artifact.name) + return names + + def _artifact_by_name(self, name: str) -> RustArtifactConfig: + return next(artifact for artifact in self.artifacts if artifact.name == name) + + def _destination_directory(self, artifact: RustArtifactConfig, resolved_target: ResolvedTarget) -> Path: + if self._is_python_extension_artifact(artifact) or artifact.destination is None and not artifact.name: + template = artifact.destination or f"{self.module}/{{python_extension_name}}" + else: + template = artifact.destination or f"{self.module}/lib/{{shared_library}}" + shared_library = shared_library_name(artifact.name, platform=resolved_target.platform) if artifact.name else "" + rendered = template.format( + module=self.module, + target=resolved_target.triple, + profile=self._artifact_profile(artifact), + name=artifact.name or "", + shared_library=shared_library or "library", + import_library="library", + python_extension_name="extension", + executable="executable", + ) + return Path(rendered).parent + + def _bundled_library_dir(self, name: str, resolved_target: ResolvedTarget) -> Path: + return Path.cwd().resolve() / self._destination_directory(self._artifact_by_name(name), resolved_target) + + def _library_env(self, artifact: RustArtifactConfig, resolved_target: ResolvedTarget) -> dict[str, str]: + environment = {} + for link in artifact.links: + key = sub(r"[^A-Za-z0-9]", "_", link).upper() + if self._resolved_library_source == "bundled": + environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(self._bundled_library_dir(link, resolved_target)) + elif self._resolved_library_source == "external": + external = self._external_libraries[link] + environment[f"HATCH_RS_LIBRARY_{key}_DIR"] = str(external.library_dir) + if external.include_dir is not None: + environment[f"HATCH_RS_LIBRARY_{key}_INCLUDE_DIR"] = str(external.include_dir) + return environment + + def _library_rustc_args(self, artifact: RustArtifactConfig, resolved_target: ResolvedTarget) -> list[str]: + mode = self._resolved_library_source + platform = resolved_target.platform + args = [] + if artifact.name and mode == "bundled" and self._artifact_role(artifact) == "cdylib": + shared_library = shared_library_name(artifact.name, platform=platform) + if platform == "darwin": + args.extend(("-C", f"link-arg=-Wl,-install_name,@rpath/{shared_library}")) + elif platform == "linux": + args.extend(("-C", f"link-arg=-Wl,-soname,{shared_library}")) + if mode in ("static", "direct"): + return args + for link in artifact.links: + if mode == "bundled": + library_dir = self._bundled_library_dir(link, resolved_target) + link_name = f"{link}.dll" if platform == "win32" else link + args.extend(("-L", f"native={library_dir}", "-l", f"dylib={link_name}")) + if platform in ("linux", "darwin"): + relative = relpath( + self._destination_directory(self._artifact_by_name(link), resolved_target), + self._destination_directory(artifact, resolved_target), + ) + origin = "$ORIGIN" if platform == "linux" else "@loader_path" + rpath = origin if relative == "." else f"{origin}/{Path(relative).as_posix()}" + args.extend(("-C", f"link-arg=-Wl,-rpath,{rpath}")) + else: + external = self._external_libraries[link] + args.extend(("-L", f"native={external.library_dir}", "-l", f"dylib={external.link_name}")) + return args + + def _pkg_config_variable(self, artifact: RustArtifactConfig, variable: str) -> Path: + assert artifact.pkg_config is not None + command = ["pkg-config", f"--variable={variable}", artifact.pkg_config] + try: + completed = run(command, capture_output=True, text=True, check=False) + except FileNotFoundError as error: + raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' needs pkg-config on PATH to resolve '{artifact.pkg_config}'.") from error + if completed.returncode != 0 or not completed.stdout.strip(): + raise RuntimeError( + f"Artifact '{self._artifact_label(artifact)}' pkg-config lookup failed: {shell_join(command)}: {completed.stderr.strip()}" + ) + return Path(completed.stdout.strip()) + + def _resolve_external_library(self, artifact: RustArtifactConfig, *, platform: str) -> ExternalLibrary: + name = self._artifact_name(artifact) + label = self._artifact_label(artifact) + root = environ.get("HATCH_RS_LIBRARY_ROOT") or (str(artifact.library_root) if artifact.library_root is not None else None) + if root: + prefix = _resolve_path(root, base=Path(self.path)) + library_dir, include_dir = prefix / "lib", prefix / "include" + elif artifact.pkg_config: + library_dir = self._pkg_config_variable(artifact, "libdir") + include_dir = self._pkg_config_variable(artifact, "includedir") + else: + conda_prefix = environ.get("PREFIX") or environ.get("CONDA_PREFIX") + if not conda_prefix: + raise ValueError( + f"Artifact '{label}' is external but has no library-root, pkg-config, HATCH_RS_LIBRARY_ROOT, PREFIX, or CONDA_PREFIX." + ) + prefix = Path(conda_prefix) / "Library" if platform == "win32" else Path(conda_prefix) + library_dir, include_dir = prefix / "lib", prefix / "include" + + shared_library = shared_library_name(name, platform=platform) + if platform == "win32": + candidates = [library_dir.parent / "bin" / shared_library, library_dir / shared_library] + link_name = name if (library_dir / f"{name}.lib").is_file() else f"{name}.dll" + elif platform == "darwin": + candidates = [library_dir / shared_library, *sorted(library_dir.glob(f"lib{name}.*.dylib"))] + link_name = name + else: + candidates = [library_dir / shared_library, *sorted(library_dir.glob(f"{shared_library}.*"))] + link_name = name + library = next((candidate for candidate in candidates if candidate.is_file()), None) + if library is None: + searched = ", ".join(str(candidate.parent) for candidate in candidates[:2]) + raise FileNotFoundError(f"Artifact '{label}' external library '{shared_library}' was not found under {searched}.") + return ExternalLibrary( + name=name, + library=library, + library_dir=library_dir, + include_dir=include_dir if include_dir.is_dir() else None, + link_name=link_name, + ) + + def _plan_external_library(self, artifact: RustArtifactConfig, *, global_target: str | None) -> PlannedArtifact: + resolved_target = _resolve_target(artifact.target if artifact.target is not None else global_target) + target_dir, set_target_dir_env = self._resolve_target_dir(self._artifact_manifest(artifact), self._artifact_env(artifact)) + external = self._resolve_external_library(artifact, platform=resolved_target.platform) + self._external_libraries[external.name] = external + return PlannedArtifact( + artifact=artifact, + invocation=None, + resolved_target=resolved_target, + profile=self._artifact_profile(artifact), + target_dir=target_dir, + set_target_dir_env=set_target_dir_env, + external_library=external, + ) + + def _validate_external_library(self, planned_artifact: PlannedArtifact, *, build_root: Path) -> list[CopiedArtifact]: + external = planned_artifact.external_library + assert external is not None + self._record_packaged_artifact( + planned_artifact=planned_artifact, + source=external.library, + distribution_path="", + install_scheme="external", + role="external-library", + ) + copied = CopiedArtifact(source=external.library, destination=external.library, distribution_path=external.library.as_posix()) + self._validate_artifact(planned_artifact, build_root=build_root, copied_artifacts=[copied]) + return [] + def _target_path(self, planned_artifact: PlannedArtifact) -> Path: return planned_artifact.target_dir / planned_artifact.resolved_target.triple / _profile_output_dir(planned_artifact.profile) @@ -1401,6 +1626,21 @@ def _default_import_library_destination(self, artifact: RustArtifactConfig) -> s return (Path(artifact.destination).parent / "{import_library}").as_posix() return f"{self.module}/lib/{{import_library}}" + def _check_import_library_dll_name(self, import_library: Path, artifact: RustArtifactConfig, *, shared_library: str) -> None: + """An import library records the DLL name it was linked with. + + Cargo adds a metadata hash to the deps filename unless the crate's own + Cargo.toml declares `cdylib`, so a `--crate-type cdylib` override on an + rlib crate yields an import library for `name-.dll`, which the + wheel never ships. + """ + if shared_library.encode() in import_library.read_bytes(): + return + raise RuntimeError( + f"Artifact '{self._artifact_label(artifact)}' import library '{import_library.name}' does not reference '{shared_library}'. " + 'Declare crate-type = ["cdylib"] in the library\'s Cargo.toml so Cargo names the DLL without a metadata hash.' + ) + def _copy_import_library( self, planned_artifact: PlannedArtifact, @@ -1410,10 +1650,13 @@ def _copy_import_library( build_root: Path, ) -> CopiedArtifact | None: artifact = planned_artifact.artifact - if not artifact.include_import_lib or planned_artifact.resolved_target.platform != "win32": + linked = artifact.name in self._linked_names + if not (artifact.include_import_lib or linked) or planned_artifact.resolved_target.platform != "win32": return None source, import_library = self._find_import_library(target_path, artifact, shared_library=shared_library) + if linked: + self._check_import_library_dll_name(source, artifact, shared_library=shared_library) template = self._default_import_library_destination(artifact) distribution_path = self._format_destination( template, @@ -1642,21 +1885,24 @@ def _validate_library_exports(self, planned_artifact: PlannedArtifact, copied_ar raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' has no copied library to validate.") copied_library = copied_artifacts[0] - try: - library = CDLL(str(copied_library.destination)) - except OSError as error: - raise RuntimeError( - f"Artifact '{self._artifact_label(artifact)}' failed validation load check for '{copied_library.distribution_path}': {error}" - ) from error + if expected: + try: + exported = exported_symbols(copied_library.destination) + except (OSError, ValueError) as error: + raise RuntimeError( + f"Artifact '{self._artifact_label(artifact)}' could not read exported symbols from '{copied_library.distribution_path}': {error}" + ) from error + missing = [symbol for symbol in expected if symbol not in exported] + if missing: + raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' expected symbol was not exported: {', '.join(missing)}") - missing = [] - for symbol in expected: + if artifact.validate_artifact: try: - getattr(library, symbol) - except AttributeError: - missing.append(symbol) - if missing: - raise RuntimeError(f"Artifact '{self._artifact_label(artifact)}' expected symbol was not exported: {', '.join(missing)}") + CDLL(str(copied_library.destination)) + except OSError as error: + raise RuntimeError( + f"Artifact '{self._artifact_label(artifact)}' failed validation load check for '{copied_library.distribution_path}': {error}" + ) from error def _validation_tokens(self, planned_artifact: PlannedArtifact, copied_artifacts: list[CopiedArtifact], headers: list[Path]) -> dict[str, str]: artifact = planned_artifact.artifact @@ -1758,6 +2004,8 @@ def _write_artifact_manifest(self, *, build_root: Path) -> None: def _copy_outputs(self, planned_artifact: PlannedArtifact, *, build_root: Path) -> list[CopiedArtifact]: artifact = planned_artifact.artifact + if planned_artifact.external_library is not None: + return self._validate_external_library(planned_artifact, build_root=build_root) copied_artifacts = [] if self._is_generated_artifact(artifact): copied_artifacts.extend(self._process_generated_outputs(planned_artifact, build_root=build_root)) @@ -1797,7 +2045,7 @@ def _license_package(self, planned_artifact: PlannedArtifact, *, manifest: Path, def _collect_licenses(self, planned_artifact: PlannedArtifact, *, build_root: Path) -> None: config = self.licenses artifact = planned_artifact.artifact - if config is None or self._is_generated_artifact(artifact): + if config is None or self._is_generated_artifact(artifact) or planned_artifact.external_library is not None: return label = self._artifact_label(artifact) @@ -1898,7 +2146,7 @@ def execute(self): if executable == "cbindgen": raise RuntimeError( f"Artifact '{self._artifact_label(planned_artifact.artifact)}' requires the cbindgen CLI. " - "Install cbindgen or use cbindgen-mode = 'build-script'." + "Install cbindgen, or emit the header from build.rs and validate it with expected-headers on the library artifact." ) from error raise RuntimeError(f"Artifact '{self._artifact_label(planned_artifact.artifact)}' command was not found: {executable}") from error if completed.returncode != 0: diff --git a/hatch_rs/symbols.py b/hatch_rs/symbols.py new file mode 100644 index 0000000..7f930cd --- /dev/null +++ b/hatch_rs/symbols.py @@ -0,0 +1,172 @@ +"""Read exported symbol names from shared libraries without loading them. + +Supports ELF, Mach-O (including fat binaries), PE, and WebAssembly so that +cross-compiled and Pyodide artifacts can be checked on any host. +""" + +from __future__ import annotations + +from pathlib import Path +from struct import Struct, unpack_from + +__all__ = ("exported_symbols",) + +_ELF_MAGIC = b"\x7fELF" +_PE_MAGIC = b"MZ" +_WASM_MAGIC = b"\x00asm" +_MACHO_MAGICS = { + b"\xcf\xfa\xed\xfe": ("<", 64), + b"\xfe\xed\xfa\xcf": (">", 64), + b"\xce\xfa\xed\xfe": ("<", 32), + b"\xfe\xed\xfa\xce": (">", 32), +} +_FAT_MAGICS = {b"\xca\xfe\xba\xbe": 32, b"\xca\xfe\xba\xbf": 64} + + +def exported_symbols(path: Path | str) -> set[str]: + """Return the names a shared library exports, as a C caller would spell them.""" + data = Path(path).read_bytes() + if data[:4] == _ELF_MAGIC: + return _elf_exports(data) + if data[:4] in _MACHO_MAGICS: + return _macho_exports(data) + if data[:4] in _FAT_MAGICS: + return _fat_exports(data) + if data[:2] == _PE_MAGIC: + return _pe_exports(data) + if data[:4] == _WASM_MAGIC: + return _wasm_exports(data) + raise ValueError(f"Unrecognized shared library format: {path}") + + +def _cstring(data: bytes, offset: int) -> str: + end = data.index(b"\x00", offset) + return data[offset:end].decode("utf-8", errors="replace") + + +def _elf_exports(data: bytes) -> set[str]: + is_64 = data[4] == 2 + endian = "<" if data[5] == 1 else ">" + if is_64: + shoff, shentsize, shnum = unpack_from(f"{endian}Q", data, 0x28)[0], *unpack_from(f"{endian}HH", data, 0x3A) + section_header = Struct(f"{endian}IIQQQQIIQQ") + symbol = Struct(f"{endian}IBBHQQ") + else: + shoff, shentsize, shnum = unpack_from(f"{endian}I", data, 0x20)[0], *unpack_from(f"{endian}HH", data, 0x2E) + section_header = Struct(f"{endian}IIIIIIIIII") + symbol = Struct(f"{endian}IIIBBH") + + sections = [section_header.unpack_from(data, shoff + index * shentsize) for index in range(shnum)] + dynsym = next((section for section in sections if section[1] == 11), None) + if dynsym is None: + raise ValueError("ELF file has no dynamic symbol table") + _, _, _, _, sym_offset, sym_size, link, _, _, entsize = dynsym + str_offset = sections[link][4] + + exported = set() + for index in range(sym_size // (entsize or symbol.size)): + fields = symbol.unpack_from(data, sym_offset + index * (entsize or symbol.size)) + if is_64: + name, info, _, shndx = fields[0], fields[1], fields[2], fields[3] + else: + name, info, shndx = fields[0], fields[3], fields[5] + if shndx == 0 or info >> 4 not in (1, 2) or name == 0: + continue + exported.add(_cstring(data, str_offset + name)) + return exported + + +def _macho_exports(data: bytes, base: int = 0) -> set[str]: + endian, bits = _MACHO_MAGICS[data[base : base + 4]] + header_size = 32 if bits == 64 else 28 + ncmds = unpack_from(f"{endian}I", data, base + 16)[0] + nlist = Struct(f"{endian}IBBHQ") if bits == 64 else Struct(f"{endian}IBBhI") + + offset = base + header_size + symtab = None + for _ in range(ncmds): + cmd, cmdsize = unpack_from(f"{endian}II", data, offset) + if cmd == 0x2: + symtab = unpack_from(f"{endian}IIII", data, offset + 8) + offset += cmdsize + if symtab is None: + raise ValueError("Mach-O file has no symbol table") + symoff, nsyms, stroff, _ = symtab + + exported = set() + for index in range(nsyms): + strx, n_type, _, _, _ = nlist.unpack_from(data, base + symoff + index * nlist.size) + if n_type & 0xE0 or not n_type & 0x01 or n_type & 0x0E != 0x0E: + continue + name = _cstring(data, base + stroff + strx) + exported.add(name.removeprefix("_")) + return exported + + +def _fat_exports(data: bytes) -> set[str]: + bits = _FAT_MAGICS[data[:4]] + narch = unpack_from(">I", data, 4)[0] + arch = Struct(">IIQQII") if bits == 64 else Struct(">IIIII") + exported = set() + for index in range(narch): + fields = arch.unpack_from(data, 8 + index * arch.size) + exported |= _macho_exports(data, base=fields[2]) + return exported + + +def _pe_exports(data: bytes) -> set[str]: + pe_offset = unpack_from(" int: + for _, virtual_size, virtual_address, raw_size, raw_pointer, *_ in sections: + if virtual_address <= rva < virtual_address + max(virtual_size, raw_size): + return rva - virtual_address + raw_pointer + raise ValueError(f"PE RVA {rva:#x} is not inside any section") + + export_offset = file_offset(export_rva) + nnames, _, names_rva = unpack_from(" tuple[int, int]: + result = shift = 0 + while True: + byte = data[offset] + offset += 1 + result |= (byte & 0x7F) << shift + shift += 7 + if not byte & 0x80: + return result, offset + + +def _wasm_exports(data: bytes) -> set[str]: + offset = 8 + while offset < len(data): + section_id = data[offset] + size, offset = _leb128(data, offset + 1) + if section_id != 7: + offset += size + continue + count, offset = _leb128(data, offset) + exported = set() + for _ in range(count): + length, offset = _leb128(data, offset) + exported.add(data[offset : offset + length].decode("utf-8", errors="replace")) + offset += length + _, offset = _leb128(data, offset + 1) + return exported + return set() diff --git a/hatch_rs/tests/test_project_cbindgen_build_script/Cargo.lock b/hatch_rs/tests/test_project_cbindgen_build_script/Cargo.lock new file mode 100644 index 0000000..f15462e --- /dev/null +++ b/hatch_rs/tests/test_project_cbindgen_build_script/Cargo.lock @@ -0,0 +1,333 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "build_script_header" +version = "0.1.0" +dependencies = [ + "cbindgen", +] + +[[package]] +name = "cbindgen" +version = "0.29.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ecb53484c9c167ba674026b656d8a27d7657a58e6066aa902bfb1a4aa00ae20" +dependencies = [ + "heck", + "indexmap", + "log", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "tempfile", + "toml", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/hatch_rs/tests/test_project_cbindgen_build_script/Cargo.toml b/hatch_rs/tests/test_project_cbindgen_build_script/Cargo.toml new file mode 100644 index 0000000..7bb2b70 --- /dev/null +++ b/hatch_rs/tests/test_project_cbindgen_build_script/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "build_script_header" +version = "0.1.0" +edition = "2021" +publish = false +build = "build.rs" + +[lib] +name = "build_script_header" +path = "src/lib.rs" +crate-type = ["cdylib"] + +[build-dependencies] +cbindgen = { version = "0.29", default-features = false } + +[profile.release] +panic = "abort" diff --git a/hatch_rs/tests/test_project_cbindgen_build_script/build.rs b/hatch_rs/tests/test_project_cbindgen_build_script/build.rs new file mode 100644 index 0000000..2b7afe1 --- /dev/null +++ b/hatch_rs/tests/test_project_cbindgen_build_script/build.rs @@ -0,0 +1,15 @@ +use std::env; +use std::path::PathBuf; + +fn main() { + let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let header = crate_dir.join("build_script_project").join("include").join("build_script_header.h"); + println!("cargo:rerun-if-changed=src/lib.rs"); + println!("cargo:rerun-if-changed=cbindgen.toml"); + cbindgen::Builder::new() + .with_crate(&crate_dir) + .with_config(cbindgen::Config::from_file(crate_dir.join("cbindgen.toml")).unwrap()) + .generate() + .expect("cbindgen failed") + .write_to_file(header); +} diff --git a/hatch_rs/tests/test_project_cbindgen_build_script/build_script_project/__init__.py b/hatch_rs/tests/test_project_cbindgen_build_script/build_script_project/__init__.py new file mode 100644 index 0000000..b0b92d9 --- /dev/null +++ b/hatch_rs/tests/test_project_cbindgen_build_script/build_script_project/__init__.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from ctypes import CDLL, c_int +from pathlib import Path +from sys import platform + +_SHARED_LIBRARY_NAME = ( + "build_script_header.dll" if platform == "win32" else "libbuild_script_header.dylib" if platform == "darwin" else "libbuild_script_header.so" +) +_SHARED_LIBRARY = CDLL(str(Path(__file__).parent / "lib" / _SHARED_LIBRARY_NAME)) +_SHARED_LIBRARY.build_script_header_answer.restype = c_int + + +def answer() -> int: + return int(_SHARED_LIBRARY.build_script_header_answer()) diff --git a/hatch_rs/tests/test_project_cbindgen_build_script/cbindgen.toml b/hatch_rs/tests/test_project_cbindgen_build_script/cbindgen.toml new file mode 100644 index 0000000..704c57c --- /dev/null +++ b/hatch_rs/tests/test_project_cbindgen_build_script/cbindgen.toml @@ -0,0 +1,2 @@ +language = "C" +include_guard = "BUILD_SCRIPT_HEADER_H" diff --git a/hatch_rs/tests/test_project_cbindgen_build_script/pyproject.toml b/hatch_rs/tests/test_project_cbindgen_build_script/pyproject.toml new file mode 100644 index 0000000..93ad67d --- /dev/null +++ b/hatch_rs/tests/test_project_cbindgen_build_script/pyproject.toml @@ -0,0 +1,44 @@ +[build-system] +requires = ["hatchling>=1.20"] +build-backend = "hatchling.build" + +[project] +name = "hatch-rs-test-project-cbindgen-build-script" +description = "cbindgen build-script header test project for hatch-rs" +version = "0.1.0" +requires-python = ">=3.9" +dependencies = [ + "hatchling>=1.20", + "hatch-rs", +] + +[tool.hatch.build] +artifacts = [ + "build_script_project/include/*.h", + "build_script_project/lib/*.dll", + "build_script_project/lib/*.dylib", + "build_script_project/lib/*.so", +] + +[tool.hatch.build.sources] +src = "/" + +[tool.hatch.build.targets.sdist] +packages = ["build_script_project"] + +[tool.hatch.build.targets.wheel] +packages = ["build_script_project"] + +[tool.hatch.build.hooks.hatch-rs] +verbose = true +path = "." +module = "build_script_project" +target-dir = "isolated" + +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "build_script_header" +manifest = "Cargo.toml" +destination = "build_script_project/lib/{shared_library}" +expected-headers = ["build_script_project/include/build_script_header.h"] +header-symbol-prefix = "build_script_header_" +expected-abi-strings = ["BUILD_SCRIPT_HEADER_ABI_VERSION"] diff --git a/hatch_rs/tests/test_project_cbindgen_build_script/src/lib.rs b/hatch_rs/tests/test_project_cbindgen_build_script/src/lib.rs new file mode 100644 index 0000000..9d06af0 --- /dev/null +++ b/hatch_rs/tests/test_project_cbindgen_build_script/src/lib.rs @@ -0,0 +1,11 @@ +pub const BUILD_SCRIPT_HEADER_ABI_VERSION: u32 = 1; + +#[no_mangle] +pub extern "C" fn build_script_header_answer() -> i32 { + 9 +} + +#[no_mangle] +pub extern "C" fn build_script_header_abi_version() -> u32 { + BUILD_SCRIPT_HEADER_ABI_VERSION +} diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.lock b/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.lock index 1bba948..457f0f6 100644 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.lock +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.lock @@ -5,3 +5,10 @@ version = 4 [[package]] name = "c_abi_bundle_extension_py" version = "0.1.0" +dependencies = [ + "c_abi_library", +] + +[[package]] +name = "c_abi_library" +version = "0.1.0" diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.toml b/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.toml index f431f23..83cf600 100644 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.toml +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/Cargo.toml @@ -9,5 +9,13 @@ name = "c_abi_bundle_extension" path = "src/lib.rs" crate-type = ["cdylib"] +[dependencies] +c_abi_library = { path = "rust", optional = true } + +[features] +default = ["direct"] +capi = [] +direct = ["dep:c_abi_library"] + [profile.release] panic = "abort" diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/__init__.py b/hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/__init__.py index 8133711..9ceb9ab 100644 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/__init__.py +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/__init__.py @@ -1,23 +1,34 @@ from __future__ import annotations +import os from ctypes import CDLL, c_int from pathlib import Path from sys import platform -_PACKAGE_DIR = Path(__file__).parent +_PACKAGE_DIR = Path(__file__).resolve().parent +_LIBRARY_DIR = _PACKAGE_DIR / "lib" _EXTENSION_SUFFIX = ".pyd" if platform == "win32" else ".so" _SHARED_LIBRARY_NAME = "c_abi_library.dll" if platform == "win32" else "libc_abi_library.dylib" if platform == "darwin" else "libc_abi_library.so" -_EXTENSION = CDLL(str(_PACKAGE_DIR / f"c_abi_bundle_extension{_EXTENSION_SUFFIX}")) -_SHARED_LIBRARY = CDLL(str(_PACKAGE_DIR / "lib" / _SHARED_LIBRARY_NAME)) +if platform == "win32" and _LIBRARY_DIR.is_dir(): + os.add_dll_directory(str(_LIBRARY_DIR)) +_EXTENSION = CDLL(str(_PACKAGE_DIR / f"c_abi_bundle_extension{_EXTENSION_SUFFIX}")) _EXTENSION.c_abi_bundle_extension_answer.restype = c_int -_SHARED_LIBRARY.c_abi_library_answer.restype = c_int +_EXTENSION.c_abi_bundle_extension_library_answer.restype = c_int def extension_answer() -> int: return int(_EXTENSION.c_abi_bundle_extension_answer()) +def library_answer() -> int: + """The bundled library's answer, reached through the extension that links it.""" + return int(_EXTENSION.c_abi_bundle_extension_library_answer()) + + def shared_answer() -> int: - return int(_SHARED_LIBRARY.c_abi_library_answer()) + """The bundled library's answer, loaded directly from the package's lib directory.""" + library = CDLL(str(_LIBRARY_DIR / _SHARED_LIBRARY_NAME)) + library.c_abi_library_answer.restype = c_int + return int(library.c_abi_library_answer()) diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/include/c_abi_library.h b/hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/include/c_abi_library.h deleted file mode 100644 index 12c09a5..0000000 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/c_abi_bundle_project/include/c_abi_library.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef C_ABI_LIBRARY_H -#define C_ABI_LIBRARY_H - -#define C_ABI_LIBRARY_ABI_VERSION 1 - -int c_abi_library_answer(void); -unsigned int c_abi_library_abi_version(void); - -#endif diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/pyproject.toml b/hatch_rs/tests/test_project_python_extension_c_abi_library/pyproject.toml index 0ae7a9b..8038be4 100644 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/pyproject.toml +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/pyproject.toml @@ -43,9 +43,15 @@ target-dir = "isolated" artifact-manifest = true [[tool.hatch.build.hooks.hatch-rs.artifacts]] -name = "c_abi_bundle_extension" -manifest = "Cargo.toml" -destination = "c_abi_bundle_project/{python_extension_name}" +name = "c_abi_library_header" +generator = "cbindgen" +crate = "rust" +config = "rust/cbindgen.toml" +inputs = ["rust/src/lib.rs", "rust/cbindgen.toml"] + +[[tool.hatch.build.hooks.hatch-rs.artifacts.outputs]] +source = "c_abi_bundle_project/include/c_abi_library.h" +install-scheme = "validate-only" [[tool.hatch.build.hooks.hatch-rs.artifacts]] name = "c_abi_library" @@ -59,3 +65,15 @@ include-import-lib = true [[tool.hatch.build.hooks.hatch-rs.artifacts.validation-commands]] command = ["python", "scripts/validate_c_abi.py", "{destination}", "{header}"] + +[[tool.hatch.build.hooks.hatch-rs.artifacts]] +name = "c_abi_bundle_extension" +manifest = "Cargo.toml" +destination = "c_abi_bundle_project/{python_extension_name}" +links = ["c_abi_library"] + +[tool.hatch.build.hooks.hatch-rs.artifacts.library-source-features] +bundled = ["capi"] +external = ["capi"] +static = ["direct"] +direct = ["direct"] diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/Cargo.toml b/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/Cargo.toml index 1ea3a95..ea9a7d6 100644 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/Cargo.toml +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/Cargo.toml @@ -7,7 +7,7 @@ publish = false [lib] name = "c_abi_library" path = "src/lib.rs" -crate-type = ["rlib"] +crate-type = ["cdylib", "rlib"] [profile.release] panic = "abort" diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/cbindgen.toml b/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/cbindgen.toml new file mode 100644 index 0000000..946bb41 --- /dev/null +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/cbindgen.toml @@ -0,0 +1,2 @@ +language = "C" +include_guard = "C_ABI_LIBRARY_H" diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/src/lib.rs b/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/src/lib.rs index ee3ba8f..715d1b4 100644 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/src/lib.rs +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/rust/src/lib.rs @@ -1,3 +1,5 @@ +pub const C_ABI_LIBRARY_ABI_VERSION: u32 = 1; + #[no_mangle] pub extern "C" fn c_abi_library_answer() -> i32 { 7 @@ -5,5 +7,5 @@ pub extern "C" fn c_abi_library_answer() -> i32 { #[no_mangle] pub extern "C" fn c_abi_library_abi_version() -> u32 { - 1 + C_ABI_LIBRARY_ABI_VERSION } diff --git a/hatch_rs/tests/test_project_python_extension_c_abi_library/src/lib.rs b/hatch_rs/tests/test_project_python_extension_c_abi_library/src/lib.rs index 36d71af..7b47082 100644 --- a/hatch_rs/tests/test_project_python_extension_c_abi_library/src/lib.rs +++ b/hatch_rs/tests/test_project_python_extension_c_abi_library/src/lib.rs @@ -1,4 +1,17 @@ +#[cfg(feature = "capi")] +extern "C" { + fn c_abi_library_answer() -> i32; +} + +#[cfg(feature = "direct")] +use c_abi_library::c_abi_library_answer; + #[no_mangle] pub extern "C" fn c_abi_bundle_extension_answer() -> i32 { 42 } + +#[no_mangle] +pub extern "C" fn c_abi_bundle_extension_library_answer() -> i32 { + unsafe { c_abi_library_answer() } +} diff --git a/hatch_rs/tests/test_projects.py b/hatch_rs/tests/test_projects.py index 46b740d..a493a6d 100644 --- a/hatch_rs/tests/test_projects.py +++ b/hatch_rs/tests/test_projects.py @@ -3,7 +3,7 @@ from os import environ, listdir, pathsep from os.path import dirname from pathlib import Path -from shutil import rmtree, which +from shutil import copy2, rmtree, which from subprocess import PIPE, STDOUT, check_call, run from sys import executable, modules, path, platform, version_info from zipfile import ZipFile @@ -11,8 +11,32 @@ import pytest from hatch_rs.structs import resolve_target_triple, shared_library_name +from hatch_rs.symbols import exported_symbols REPO_ROOT = Path(__file__).resolve().parents[2] +C_ABI_PROJECT = Path("hatch_rs/tests") / "test_project_python_extension_c_abi_library" +C_ABI_PACKAGE = C_ABI_PROJECT / "c_abi_bundle_project" + + +def _clean_c_abi_project(): + rmtree(C_ABI_PROJECT / "dist", ignore_errors=True) + rmtree(C_ABI_PROJECT / "target", ignore_errors=True) + rmtree(C_ABI_PROJECT / "rust" / "target", ignore_errors=True) + rmtree(C_ABI_PACKAGE / "lib", ignore_errors=True) + rmtree(C_ABI_PACKAGE / "include", ignore_errors=True) + for artifact in C_ABI_PACKAGE.glob("c_abi_bundle_extension*"): + if artifact.suffix in (".dll", ".dylib", ".pyd", ".so"): + artifact.unlink() + + +def _assert_c_abi_answers(env, *, dll_dir=None, shared=True): + """Import the fixture package in a fresh interpreter and call through the linked library.""" + code = f"import os; os.add_dll_directory({str(dll_dir)!r})\n" if dll_dir else "" + code += "import c_abi_bundle_project as m\n" + code += "assert m.extension_answer() == 42\nassert m.library_answer() == 7\n" + if shared: + code += "assert m.shared_answer() == 7\n" + check_call([executable, "-c", code], cwd=C_ABI_PROJECT, env=env) def _subprocess_env(): @@ -204,19 +228,9 @@ def test_cargo_controls_manifest_rustc_args_and_isolated_target_dir(self): assert cargo_controls_project.feature_enabled() def test_python_extension_and_c_abi_shared_library_artifacts(self): - project_folder = "test_project_python_extension_c_abi_library" - project_root = Path("hatch_rs/tests") / project_folder - package_dir = project_root / "c_abi_bundle_project" - - # cleanup - rmtree(project_root / "dist", ignore_errors=True) - rmtree(project_root / "target", ignore_errors=True) - rmtree(project_root / "rust" / "target", ignore_errors=True) - rmtree(package_dir / "lib", ignore_errors=True) - for artifact in package_dir.glob("c_abi_bundle_extension*"): - if artifact.suffix in (".dll", ".dylib", ".pyd", ".so"): - artifact.unlink() - modules.pop("c_abi_bundle_project", None) + project_root = C_ABI_PROJECT + package_dir = C_ABI_PACKAGE + _clean_c_abi_project() # compile check_call( @@ -236,7 +250,7 @@ def test_python_extension_and_c_abi_shared_library_artifacts(self): manifest_path = package_dir / "lib" / "hatch-rs-artifacts.json" assert (package_dir / extension_name).exists() assert (package_dir / "lib" / shared_library).exists() - assert (package_dir / "include" / "c_abi_library.h").exists() + assert "#define C_ABI_LIBRARY_ABI_VERSION 1" in (package_dir / "include" / "c_abi_library.h").read_text() assert manifest_path.exists() assert not (project_root / "target").exists() assert not (project_root / "rust" / "target").exists() @@ -270,13 +284,69 @@ def test_python_extension_and_c_abi_shared_library_artifacts(self): if platform == "win32": assert any(record["role"] == "import-library" for record in c_abi_records) - # import - here = Path(__file__).parent / project_folder - path.insert(0, str(here)) - c_abi_bundle_project = import_module("c_abi_bundle_project") + # the extension reaches the library through its rpath, not by compiling it in + assert "c_abi_library_answer" not in exported_symbols(package_dir / extension_name) + _assert_c_abi_answers(_subprocess_env()) + + def test_python_extension_links_external_c_abi_library(self, tmp_path): + _clean_c_abi_project() + shared_library = shared_library_name("c_abi_library") + + # build the library into its own prefix, the way a conda package would ship it + prefix = tmp_path / "prefix" + (prefix / "lib").mkdir(parents=True) + (prefix / "bin").mkdir() + rustc_args = ["--", "-C", "link-arg=-Wl,-install_name,@rpath/libc_abi_library.dylib"] if platform == "darwin" else [] + check_call( + [ + "cargo", + "rustc", + "--manifest-path", + "rust/Cargo.toml", + "--release", + "--target-dir", + str(tmp_path / "target"), + "--crate-type", + "cdylib", + *rustc_args, + ], + cwd=C_ABI_PROJECT, + env=_subprocess_env(), + ) + built = tmp_path / "target" / "release" + if platform == "win32": + copy2(built / shared_library, prefix / "bin" / shared_library) + copy2(built / "c_abi_library.dll.lib", prefix / "lib" / "c_abi_library.lib") + else: + copy2(built / shared_library, prefix / "lib" / shared_library) + + env = _subprocess_env() + env.update({"HATCH_RS_LIBRARY_SOURCE": "external", "HATCH_RS_LIBRARY_ROOT": str(prefix)}) + check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=C_ABI_PROJECT, env=env) + + assert not (C_ABI_PACKAGE / "lib" / shared_library).exists() + records = loads((C_ABI_PACKAGE / "lib" / "hatch-rs-artifacts.json").read_text())["artifacts"] + external = [record for record in records if record["name"] == "c_abi_library"] + assert [record["role"] for record in external] == ["external-library"] + assert Path(external[0]["source"]).is_relative_to(prefix) + + # import with the prefix on the loader path, as an environment would provide it + if platform == "win32": + _assert_c_abi_answers(env, dll_dir=prefix / "bin", shared=False) + else: + env["DYLD_LIBRARY_PATH" if platform == "darwin" else "LD_LIBRARY_PATH"] = str(prefix / "lib") + _assert_c_abi_answers(env, shared=False) + + def test_python_extension_compiles_c_abi_library_in_direct_mode(self): + _clean_c_abi_project() + env = _subprocess_env() + env["HATCH_RS_LIBRARY_SOURCE"] = "direct" + check_call([executable, "-m", "hatchling", "build", "--hooks-only"], cwd=C_ABI_PROJECT, env=env) - assert c_abi_bundle_project.extension_answer() == 42 - assert c_abi_bundle_project.shared_answer() == 7 + extension_name = "c_abi_bundle_extension.pyd" if platform == "win32" else "c_abi_bundle_extension.so" + assert not (C_ABI_PACKAGE / "lib" / shared_library_name("c_abi_library")).exists() + assert "c_abi_library_answer" in exported_symbols(C_ABI_PACKAGE / extension_name) + _assert_c_abi_answers(env, shared=False) def test_generated_file_and_header_artifacts(self): project_folder = "test_project_generated_files" @@ -334,6 +404,43 @@ def test_generated_file_and_header_artifacts(self): assert generated_files_project.generated_text() == "generated package data" + def test_cbindgen_build_script_header(self): + project_folder = "test_project_cbindgen_build_script" + project_root = Path("hatch_rs/tests") / project_folder + package_dir = project_root / "build_script_project" + + # cleanup + rmtree(project_root / "dist", ignore_errors=True) + rmtree(project_root / "target", ignore_errors=True) + rmtree(package_dir / "lib", ignore_errors=True) + rmtree(package_dir / "include", ignore_errors=True) + modules.pop("build_script_project", None) + + # compile + check_call( + [ + executable, + "-m", + "hatchling", + "build", + "--hooks-only", + ], + cwd=project_root, + env=_subprocess_env(), + ) + + header = (package_dir / "include" / "build_script_header.h").read_text() + assert "#define BUILD_SCRIPT_HEADER_ABI_VERSION 1" in header + assert "build_script_header_answer" in header + assert (package_dir / "lib" / shared_library_name("build_script_header")).exists() + + # import + here = Path(__file__).parent / project_folder + path.insert(0, str(here)) + build_script_project = import_module("build_script_project") + + assert build_script_project.answer() == 9 + def test_c_abi_symbol_validation_failure(self): project_folder = "test_project_c_abi_validation_failure" project_root = Path("hatch_rs/tests") / project_folder diff --git a/hatch_rs/tests/test_structs.py b/hatch_rs/tests/test_structs.py index 9e14848..98cf75f 100644 --- a/hatch_rs/tests/test_structs.py +++ b/hatch_rs/tests/test_structs.py @@ -542,7 +542,7 @@ def test_build_plan_generates_explicit_artifacts(tmp_path): assert plan.generate() == [ "cargo rustc --manifest-path Cargo.toml --release --target x86_64-unknown-linux-gnu -- --crate-type cdylib", - "cargo rustc --manifest-path rust/Cargo.toml --release --target x86_64-unknown-linux-gnu -- -C opt-level=3 --crate-type cdylib", + "cargo rustc --manifest-path rust/Cargo.toml --release --target x86_64-unknown-linux-gnu -- -C link-arg=-Wl,-soname,libproject_ffi.so -C opt-level=3 --crate-type cdylib", ] first_target_dir = plan.cargo_invocations[0].env["CARGO_TARGET_DIR"] @@ -576,7 +576,7 @@ def test_build_plan_skips_artifact_when_skip_if_env_is_truthy(tmp_path, monkeypa monkeypatch.delenv("PROJECT_SKIP_SHARED_LIBRARY", raising=False) assert plan.generate() == [ "cargo rustc --manifest-path Cargo.toml --release --target x86_64-unknown-linux-gnu -- --crate-type cdylib", - "cargo rustc --manifest-path rust/Cargo.toml --release --target x86_64-unknown-linux-gnu -- --crate-type cdylib", + "cargo rustc --manifest-path rust/Cargo.toml --release --target x86_64-unknown-linux-gnu -- -C link-arg=-Wl,-soname,libproject_ffi.so --crate-type cdylib", ] monkeypatch.setenv("PROJECT_SKIP_SHARED_LIBRARY", "1") @@ -871,6 +871,10 @@ def test_header_symbols_lists_prefixed_declarations(): static inline int project_ffi_inline_check(void) { return project_ffi_answer() == 42; } +typedef struct project_ffi_vtable { + project_ffi_status (*open)(void *data, const char *path); + project_ffi_handle *(*create)(void *data); +} project_ffi_vtable; """ assert header_symbols(header, "project_ffi_") == ["project_ffi_answer", "project_ffi_new"] @@ -892,18 +896,8 @@ def _plan_with_header(tmp_path, header_text, **artifact): return plan -class _FakeLibrary: - def __init__(self, exported): - self._exported = set(exported) - - def __getattr__(self, name): - if name in self._exported: - return object() - raise AttributeError(name) - - def test_build_plan_expects_every_header_symbol(tmp_path, monkeypatch): - monkeypatch.setattr("hatch_rs.structs.CDLL", lambda path: _FakeLibrary({"project_ffi_answer", "project_ffi_free"})) + monkeypatch.setattr("hatch_rs.structs.exported_symbols", lambda path: {"project_ffi_answer", "project_ffi_free"}) plan = _plan_with_header( tmp_path, "int project_ffi_answer(void);\nvoid project_ffi_free(void *p);\n", @@ -913,7 +907,7 @@ def test_build_plan_expects_every_header_symbol(tmp_path, monkeypatch): def test_build_plan_missing_header_symbol_fails_clearly(tmp_path, monkeypatch): - monkeypatch.setattr("hatch_rs.structs.CDLL", lambda path: _FakeLibrary({"project_ffi_answer"})) + monkeypatch.setattr("hatch_rs.structs.exported_symbols", lambda path: {"project_ffi_answer"}) plan = _plan_with_header( tmp_path, "int project_ffi_answer(void);\nvoid project_ffi_free(void *p);\n", @@ -924,7 +918,7 @@ def test_build_plan_missing_header_symbol_fails_clearly(tmp_path, monkeypatch): def test_build_plan_header_without_prefixed_symbols_fails_clearly(tmp_path, monkeypatch): - monkeypatch.setattr("hatch_rs.structs.CDLL", lambda path: _FakeLibrary(set())) + monkeypatch.setattr("hatch_rs.structs.exported_symbols", lambda path: set()) plan = _plan_with_header(tmp_path, "int other_answer(void);\n", **{"header-symbol-prefix": "project_ffi_"}) with pytest.raises(RuntimeError, match="no functions starting with 'project_ffi_'"): plan._copy_outputs(plan._artifact_plans[0], build_root=tmp_path) @@ -1030,3 +1024,144 @@ def test_build_plan_writes_artifact_manifest(tmp_path): } ] assert plan.copied_artifacts[-1].distribution_path == "project/lib/hatch-rs-artifacts.json" + + +def _linked_plan(tmp_path, target, **extension): + return HatchRustBuildPlan( + module="project", + path=tmp_path, + target=target, + artifacts=[ + {"name": "project_ffi", "manifest": "rust/Cargo.toml", "destination": "project/lib/{shared_library}"}, + { + "name": "project_py", + "destination": "project/{python_extension_name}", + "links": ["project_ffi"], + "library-source-features": {"bundled": ["capi"], "external": ["capi"], "direct": ["direct"]}, + **extension, + }, + ], + ) + + +def test_build_plan_bundled_library_links_with_rpath_on_linux(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + plan = _linked_plan(tmp_path, "x86_64-unknown-linux-gnu") + library, extension = plan.generate() + + assert "-C link-arg=-Wl,-soname,libproject_ffi.so" in library + assert "--features capi --no-default-features" in extension + args = plan._artifact_plans[1].invocation.args + assert f"native={tmp_path.resolve() / 'project' / 'lib'}" in args + assert "dylib=project_ffi" in args + assert "link-arg=-Wl,-rpath,$ORIGIN/lib" in args + env = plan._artifact_plans[1].invocation.env + assert env["HATCH_RS_LIBRARY_SOURCE"] == "bundled" + assert env["HATCH_RS_LIBRARY_PROJECT_FFI_DIR"] == str(tmp_path.resolve() / "project" / "lib") + + +def test_build_plan_bundled_library_sets_install_name_on_darwin(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + library, extension = _linked_plan(tmp_path, "aarch64-apple-darwin").generate() + + assert "-C link-arg=-Wl,-install_name,@rpath/libproject_ffi.dylib" in library + assert "-C link-arg=-Wl,-rpath,@loader_path/lib" in extension + + +def test_build_plan_bundled_cdylib_gets_identity_without_consumer(tmp_path, monkeypatch): + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + plan = HatchRustBuildPlan( + module="project", + path=tmp_path, + target="x86_64-unknown-linux-gnu", + artifacts=[{"name": "project_ffi", "manifest": "rust/Cargo.toml", "destination": "project/lib/{shared_library}"}], + ) + (library,) = plan.generate() + + assert "-C link-arg=-Wl,-soname,libproject_ffi.so" in library + + +def test_build_plan_bundled_library_links_import_library_on_windows(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + library, extension = _linked_plan(tmp_path, "x86_64-pc-windows-msvc").generate() + + assert "link-arg" not in library + assert "-l dylib=project_ffi.dll" in extension + assert "rpath" not in extension + + +def test_build_plan_direct_mode_skips_library(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HATCH_RS_LIBRARY_SOURCE", "direct") + plan = _linked_plan(tmp_path, "x86_64-unknown-linux-gnu") + (extension,) = plan.generate() + + assert "--features direct --no-default-features" in extension + assert "-l dylib" not in extension + assert plan._artifact_plans[0].invocation.env["HATCH_RS_LIBRARY_SOURCE"] == "direct" + + +def test_build_plan_external_mode_resolves_library_root(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HATCH_RS_LIBRARY_SOURCE", "external") + prefix = tmp_path / "prefix" + (prefix / "lib").mkdir(parents=True) + (prefix / "include").mkdir() + (prefix / "lib" / "libproject_ffi.so.0").write_bytes(b"") + monkeypatch.setenv("HATCH_RS_LIBRARY_ROOT", str(prefix)) + plan = _linked_plan(tmp_path, "x86_64-unknown-linux-gnu") + (extension,) = plan.generate() + + external = plan._artifact_plans[0].external_library + assert external.library == prefix / "lib" / "libproject_ffi.so.0" + assert plan._artifact_plans[0].invocation is None + args = plan._artifact_plans[1].invocation.args + assert f"native={prefix / 'lib'}" in args + assert "dylib=project_ffi" in args + assert "rpath" not in extension + env = plan._artifact_plans[1].invocation.env + assert env["HATCH_RS_LIBRARY_PROJECT_FFI_DIR"] == str(prefix / "lib") + assert env["HATCH_RS_LIBRARY_PROJECT_FFI_INCLUDE_DIR"] == str(prefix / "include") + + +def test_build_plan_external_mode_missing_library_fails_clearly(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("HATCH_RS_LIBRARY_SOURCE", "external") + monkeypatch.setenv("HATCH_RS_LIBRARY_ROOT", str(tmp_path / "prefix")) + with pytest.raises(FileNotFoundError, match="libproject_ffi.so"): + _linked_plan(tmp_path, "x86_64-unknown-linux-gnu").generate() + + +def test_build_plan_rejects_unknown_library_source(tmp_path, monkeypatch): + monkeypatch.setenv("HATCH_RS_LIBRARY_SOURCE", "vendored") + with pytest.raises(ValueError, match="HATCH_RS_LIBRARY_SOURCE"): + _linked_plan(tmp_path, "x86_64-unknown-linux-gnu").generate() + + +def test_build_plan_links_must_name_an_earlier_artifact(tmp_path, monkeypatch): + monkeypatch.delenv("HATCH_RS_LIBRARY_SOURCE", raising=False) + plan = HatchRustBuildPlan( + module="project", + path=tmp_path, + target="x86_64-unknown-linux-gnu", + artifacts=[ + {"name": "project_py", "destination": "project/{python_extension_name}", "links": ["project_ffi"]}, + {"name": "project_ffi", "manifest": "rust/Cargo.toml"}, + ], + ) + with pytest.raises(ValueError, match="declared before it"): + plan.generate() + + +def test_import_library_must_name_the_shipped_dll(tmp_path): + plan = _linked_plan(tmp_path, "x86_64-pc-windows-msvc") + artifact = plan.artifacts[0] + import_library = tmp_path / "project_ffi.dll.lib" + import_library.write_bytes(b"!\nproject_ffi-8f3e2d7b9a6ad6b1.dll\x00") + with pytest.raises(RuntimeError, match="crate-type"): + plan._check_import_library_dll_name(import_library, artifact, shared_library="project_ffi.dll") + import_library.write_bytes(b"!\nproject_ffi.dll\x00") + plan._check_import_library_dll_name(import_library, artifact, shared_library="project_ffi.dll") diff --git a/hatch_rs/tests/test_symbols.py b/hatch_rs/tests/test_symbols.py new file mode 100644 index 0000000..3416bc4 --- /dev/null +++ b/hatch_rs/tests/test_symbols.py @@ -0,0 +1,31 @@ +import _ctypes + +import pytest + +from hatch_rs.symbols import exported_symbols + + +def test_host_extension_module_exports_init_symbol(): + assert "PyInit__ctypes" in exported_symbols(_ctypes.__file__) + + +def test_wasm_export_section(tmp_path): + # (module (func $f (export "demo_answer") (result i32) i32.const 42) (memory (export "memory") 1)) + module = bytes.fromhex( + "0061736d01000000" # magic, version + "010501600001 7f" # type section: () -> i32 + "03020100" # function section: one function of type 0 + "0503010001" # memory section: min 1 page + "071802 0b64656d6f5f616e737765720000 066d656d6f72790200" # export section: demo_answer (func 0), memory (mem 0) + "0a06010400412a0b" # code section + ) + wasm = tmp_path / "demo.wasm" + wasm.write_bytes(module) + assert exported_symbols(wasm) == {"demo_answer", "memory"} + + +def test_unknown_format_fails_clearly(tmp_path): + other = tmp_path / "other.so" + other.write_bytes(b"not a library") + with pytest.raises(ValueError, match="Unrecognized shared library format"): + exported_symbols(other)