diff --git a/.bazelignore b/.bazelignore index 8a3cbf9068..4b3d51bb90 100644 --- a/.bazelignore +++ b/.bazelignore @@ -24,6 +24,10 @@ examples/pip_parse/bazel-pip_parse examples/pip_parse_vendored/bazel-pip_parse_vendored examples/pip_repository_annotations/bazel-pip_repository_annotations examples/py_proto_library/bazel-py_proto_library +examples/sdist_cross_compile/bazel-bin +examples/sdist_cross_compile/bazel-out +examples/sdist_cross_compile/bazel-sdist_cross_compile +examples/sdist_cross_compile/bazel-testlogs gazelle/bazel-gazelle gazelle/examples/bzlmod_build_file_generation/bazel-bin gazelle/examples/bzlmod_build_file_generation/bazel-bzlmod_build_file_generation diff --git a/examples/sdist_cross_compile/.bazelrc b/examples/sdist_cross_compile/.bazelrc new file mode 100644 index 0000000000..a912d7ec73 --- /dev/null +++ b/examples/sdist_cross_compile/.bazelrc @@ -0,0 +1,16 @@ +common --enable_bzlmod +common --enable_platform_specific_config +common --incompatible_python_disallow_native_rules + +test --test_output=errors + +# BuildBuddy's managed cloud pool only has Linux executors; disable remote +# execution on macOS and Windows while keeping BES and Remote Cache. +common:macos --remote_executor= +common:macos --extra_execution_platforms= +common:windows --remote_executor= +common:windows --extra_execution_platforms= + +import %workspace%/../../buildbuddy.bazelrc +try-import %workspace%/../../user.bazelrc +try-import %workspace%/user.bazelrc diff --git a/examples/sdist_cross_compile/.gitignore b/examples/sdist_cross_compile/.gitignore new file mode 100644 index 0000000000..e0a3c9f5b5 --- /dev/null +++ b/examples/sdist_cross_compile/.gitignore @@ -0,0 +1,4 @@ +user.bazelrc +MODULE.bazel.lock +bazel-remote-grpc.log +bazel-execution-log.binpb.zst diff --git a/examples/sdist_cross_compile/BUILD.bazel b/examples/sdist_cross_compile/BUILD.bazel new file mode 100644 index 0000000000..72b770464d --- /dev/null +++ b/examples/sdist_cross_compile/BUILD.bazel @@ -0,0 +1,83 @@ +load("@rules_python//python:py_binary.bzl", "py_binary") +load("@rules_python//python:py_test.bzl", "py_test") +load("@rules_python//python/private/pypi:py_sdist_wheel.bzl", "py_sdist_wheel") # buildifier: disable=bzl-visibility +load(":transitions.bzl", "cross_platform_files") + +platform( + name = "linux_aarch64", + constraint_values = [ + "@platforms//os:linux", + "@platforms//cpu:aarch64", + "@llvm//constraints/libc:gnu.2.17", + ], +) + +py_binary( + name = "make_test_sdists", + srcs = ["make_test_sdists.py"], +) + +# Self-contained tiny setuptools C-extension sdist generated at build time. +genrule( + name = "gen_tiny_setuptools_sdist", + outs = ["tiny_setuptools-0.1.0.tar.gz"], + cmd = "$(execpath :make_test_sdists) setuptools $@", + tools = [":make_test_sdists"], +) + +py_sdist_wheel( + name = "tiny_setuptools.whldir", + sdist = ":gen_tiny_setuptools_sdist", +) + +# Self-contained tiny meson-python C/C++17 sdist generated at build time. +genrule( + name = "gen_tiny_meson_sdist", + outs = ["tiny_meson-0.1.0.tar.gz"], + cmd = "$(execpath :make_test_sdists) meson $@", + tools = [":make_test_sdists"], +) + +py_sdist_wheel( + name = "tiny_meson.whldir", + build_deps = [ + "@sdist_build_deps//meson_python:pkg", + "@sdist_build_deps//ninja:data", + "@sdist_build_deps//ninja:pkg", + ], + sdist = ":gen_tiny_meson_sdist", +) + +# Cross-compiled setuptools C-extension wheel (linux_x86_64 -> linux_aarch64). +cross_platform_files( + name = "tiny_setuptools_aarch64", + target_platform = ":linux_aarch64", + deps = [":tiny_setuptools.whldir"], +) + +# Cross-compiled meson-python C/C++17 wheel (linux_x86_64 -> linux_aarch64). +cross_platform_files( + name = "tiny_meson_aarch64", + target_platform = ":linux_aarch64", + deps = [":tiny_meson.whldir"], +) + +py_test( + name = "native_sdist_test", + size = "small", + srcs = ["native_sdist_test.py"], + data = [ + ":tiny_meson.whldir", + ":tiny_setuptools.whldir", + ], +) + +py_test( + name = "cross_compile_test", + size = "small", + srcs = ["cross_compile_test.py"], + data = [ + ":tiny_meson_aarch64", + ":tiny_setuptools_aarch64", + ], +) diff --git a/examples/sdist_cross_compile/MODULE.bazel b/examples/sdist_cross_compile/MODULE.bazel new file mode 100644 index 0000000000..e0fc05d72d --- /dev/null +++ b/examples/sdist_cross_compile/MODULE.bazel @@ -0,0 +1,50 @@ +module( + name = "example_sdist_cross_compile", + version = "0.0.0", +) + +bazel_dep(name = "platforms", version = "1.1.0") +bazel_dep(name = "rules_cc", version = "0.2.25") +bazel_dep(name = "rules_python", version = "0.0.0") +local_path_override( + module_name = "rules_python", + path = "../..", +) + +# Hermetic LLVM C/C++ cross-compilation toolchain (linux_x86_64 -> linux_aarch64). +bazel_dep(name = "llvm", version = "0.8.27") + +register_toolchains("@llvm//toolchain:all") + +# BuildBuddy RBE platform and Ubuntu 24.04 GCC toolchain (used with --config=buildbuddy_*). +bazel_dep(name = "toolchains_buildbuddy", version = "0.0.4", dev_dependency = True) + +buildbuddy = use_extension( + "@toolchains_buildbuddy//:extensions.bzl", + "buildbuddy", + dev_dependency = True, +) +buildbuddy.platform(buildbuddy_container_image = "UBUNTU24_04_IMAGE") + +rules_python_config = use_extension( + "@rules_python//python/extensions:config.bzl", + "config", +) +rules_python_config.explicit_init_py(default = True) + +python = use_extension("@rules_python//python/extensions:python.bzl", "python") +python.defaults( + python_version = "3.13", +) +python.toolchain( + python_version = "3.13", +) + +# Build-time dependencies (meson-python, meson, ninja) fetched as prebuilt wheels. +pip = use_extension("@rules_python//python/extensions:pip.bzl", "pip") +pip.parse( + hub_name = "sdist_build_deps", + python_version = "3.13", + requirements_lock = "//:requirements.txt", +) +use_repo(pip, "sdist_build_deps") diff --git a/examples/sdist_cross_compile/cross_compile_test.py b/examples/sdist_cross_compile/cross_compile_test.py new file mode 100644 index 0000000000..4980d17091 --- /dev/null +++ b/examples/sdist_cross_compile/cross_compile_test.py @@ -0,0 +1,72 @@ +import fnmatch +import os +import pathlib +import struct +import unittest +import zipfile + +ELF_MAGIC = b"\x7fELF" +ELFCLASS64 = 2 +ELFDATA2LSB = 1 +EM_AARCH64 = 183 + + +def _find_runfiles_root() -> pathlib.Path: + runfiles_dir = os.environ.get("TEST_SRCDIR") or os.environ.get("RUNFILES_DIR") + if not runfiles_dir: + raise AssertionError("Neither TEST_SRCDIR nor RUNFILES_DIR is set") + return pathlib.Path(runfiles_dir) + + +def _check_elf_header(header: bytes, label: str) -> None: + magic = header[0:4] + ei_class = header[4] + ei_data = header[5] + (e_machine,) = struct.unpack(" None: + root = _find_runfiles_root() + matches = list(root.rglob(wheel_name)) + self.assertTrue(matches, f"Expected wheel {wheel_name!r} under {root}") + with zipfile.ZipFile(matches[0]) as zf: + so_entries = [n for n in zf.namelist() if fnmatch.fnmatch(n, so_glob)] + self.assertTrue( + so_entries, + f"Expected entry matching {so_glob!r} in {matches[0]}, got {zf.namelist()}", + ) + header = zf.read(so_entries[0])[:20] + _check_elf_header(header, f"{matches[0]}:{so_entries[0]}") + + def test_tiny_setuptools_aarch64_elf(self): + self._assert_wheel_contains_aarch64_so( + "tiny_setuptools.sdist_build.whl", + "tiny_setuptools/_tiny_st.cpython-*-aarch64-linux-gnu.so", + ) + + def test_tiny_meson_c_aarch64_elf(self): + self._assert_wheel_contains_aarch64_so( + "tiny_meson.sdist_build.whl", + "tiny_meson/_tiny_c.cpython-*-aarch64-linux-gnu.so", + ) + + def test_tiny_meson_cpp_aarch64_elf(self): + self._assert_wheel_contains_aarch64_so( + "tiny_meson.sdist_build.whl", + "tiny_meson/_tiny_cpp.cpython-*-aarch64-linux-gnu.so", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/sdist_cross_compile/make_test_sdists.py b/examples/sdist_cross_compile/make_test_sdists.py new file mode 100644 index 0000000000..d2c16f683f --- /dev/null +++ b/examples/sdist_cross_compile/make_test_sdists.py @@ -0,0 +1,221 @@ +"""Generates deterministic tiny setuptools and meson-python C/C++ sdists.""" + +from __future__ import annotations + +import argparse +import io +import pathlib +import tarfile + +_SETUPTOOLS_SETUP_PY = """\ +from setuptools import Extension, setup + +setup( + name="tiny-setuptools", + version="0.1.0", + packages=["tiny_setuptools"], + ext_modules=[Extension("tiny_setuptools._tiny_st", ["tiny_setuptools/_tiny_st.c"])], +) +""" + +_SETUPTOOLS_INIT_PY = """\ +from tiny_setuptools._tiny_st import sub_ints + +__all__ = ["sub_ints"] +""" + +_SETUPTOOLS_C = """\ +#define PY_SSIZE_T_CLEAN +#include + +static PyObject *tiny_sub_ints(PyObject *self, PyObject *args) { + long a = 0, b = 0; + if (!PyArg_ParseTuple(args, "ll", &a, &b)) { + return NULL; + } + return PyLong_FromLong(a - b); +} + +static PyMethodDef TinyStMethods[] = { + {"sub_ints", tiny_sub_ints, METH_VARARGS, "Subtract two integers in C."}, + {NULL, NULL, 0, NULL}, +}; + +static struct PyModuleDef tiny_st_module = { + PyModuleDef_HEAD_INIT, + "_tiny_st", + NULL, + -1, + TinyStMethods, +}; + +PyMODINIT_FUNC PyInit__tiny_st(void) { + return PyModule_Create(&tiny_st_module); +} +""" + +_MESON_PYPROJECT_TOML = """\ +[build-system] +build-backend = "mesonpy" +requires = ["meson-python"] + +[project] +name = "tiny-meson" +version = "0.1.0" +requires-python = ">=3.9" +""" + +_MESON_BUILD = """\ +project( + 'tiny-meson', + 'c', + 'cpp', + version: '0.1.0', + default_options: ['cpp_std=c++17'], +) + +py = import('python').find_installation(pure: false) + +py.install_sources( + 'tiny_meson/__init__.py', + subdir: 'tiny_meson', +) + +py.extension_module( + '_tiny_c', + 'tiny_meson/_tiny_c.c', + subdir: 'tiny_meson', + install: true, +) + +py.extension_module( + '_tiny_cpp', + 'tiny_meson/_tiny_cpp.cpp', + subdir: 'tiny_meson', + install: true, +) +""" + +_MESON_INIT_PY = """\ +from tiny_meson._tiny_c import add_ints +from tiny_meson._tiny_cpp import mul_ints + +__all__ = ["add_ints", "mul_ints"] +""" + +_MESON_C = """\ +#define PY_SSIZE_T_CLEAN +#include + +static PyObject *tiny_add_ints(PyObject *self, PyObject *args) { + long a = 0, b = 0; + if (!PyArg_ParseTuple(args, "ll", &a, &b)) { + return NULL; + } + return PyLong_FromLong(a + b); +} + +static PyMethodDef TinyCMethods[] = { + {"add_ints", tiny_add_ints, METH_VARARGS, "Add two integers in C."}, + {NULL, NULL, 0, NULL}, +}; + +static struct PyModuleDef tiny_c_module = { + PyModuleDef_HEAD_INIT, + "_tiny_c", + NULL, + -1, + TinyCMethods, +}; + +PyMODINIT_FUNC PyInit__tiny_c(void) { + return PyModule_Create(&tiny_c_module); +} +""" + +_MESON_CPP = """\ +#define PY_SSIZE_T_CLEAN +#include +#include + +namespace { + +long multiply_pair(long a, long b) { + std::vector vals = {a, b}; + return vals[0] * vals[1]; +} + +PyObject *tiny_mul_ints(PyObject *self, PyObject *args) { + long a = 0, b = 0; + if (!PyArg_ParseTuple(args, "ll", &a, &b)) { + return nullptr; + } + return PyLong_FromLong(multiply_pair(a, b)); +} + +PyMethodDef TinyCppMethods[] = { + {"mul_ints", tiny_mul_ints, METH_VARARGS, "Multiply two integers in C++."}, + {nullptr, nullptr, 0, nullptr}, +}; + +PyModuleDef tiny_cpp_module = { + PyModuleDef_HEAD_INIT, + "_tiny_cpp", + nullptr, + -1, + TinyCppMethods, +}; + +} // namespace + +PyMODINIT_FUNC PyInit__tiny_cpp(void) { + return PyModule_Create(&tiny_cpp_module); +} +""" + + +def write_sdist_tar(out: pathlib.Path, files: dict[str, str]) -> None: + out.parent.mkdir(parents=True, exist_ok=True) + with tarfile.open(out, "w:gz") as tf: + for name, content in files.items(): + data = content.encode("utf-8") + info = tarfile.TarInfo(name=name) + info.size = len(data) + info.mtime = 315532800 + info.mode = 0o644 + tf.addfile(info, io.BytesIO(data)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("kind", choices=["setuptools", "meson"]) + parser.add_argument("out", type=pathlib.Path) + args = parser.parse_args() + + if args.kind == "setuptools": + write_sdist_tar( + args.out, + { + "tiny_setuptools-0.1.0/PKG-INFO": ( + "Metadata-Version: 2.1\nName: tiny-setuptools\nVersion: 0.1.0\n" + ), + "tiny_setuptools-0.1.0/setup.py": _SETUPTOOLS_SETUP_PY, + "tiny_setuptools-0.1.0/tiny_setuptools/__init__.py": _SETUPTOOLS_INIT_PY, + "tiny_setuptools-0.1.0/tiny_setuptools/_tiny_st.c": _SETUPTOOLS_C, + }, + ) + else: + write_sdist_tar( + args.out, + { + "tiny_meson-0.1.0/pyproject.toml": _MESON_PYPROJECT_TOML, + "tiny_meson-0.1.0/meson.build": _MESON_BUILD, + "tiny_meson-0.1.0/tiny_meson/__init__.py": _MESON_INIT_PY, + "tiny_meson-0.1.0/tiny_meson/_tiny_c.c": _MESON_C, + "tiny_meson-0.1.0/tiny_meson/_tiny_cpp.cpp": _MESON_CPP, + }, + ) + + +if __name__ == "__main__": + main() diff --git a/examples/sdist_cross_compile/native_sdist_test.py b/examples/sdist_cross_compile/native_sdist_test.py new file mode 100644 index 0000000000..6bc22b57db --- /dev/null +++ b/examples/sdist_cross_compile/native_sdist_test.py @@ -0,0 +1,44 @@ +import importlib +import os +import pathlib +import sys +import tempfile +import unittest +import zipfile + + +def _find_runfiles_root() -> pathlib.Path: + runfiles_dir = os.environ.get("TEST_SRCDIR") or os.environ.get("RUNFILES_DIR") + if not runfiles_dir: + raise AssertionError("Neither TEST_SRCDIR nor RUNFILES_DIR is set") + return pathlib.Path(runfiles_dir) + + +class NativeSdistTest(unittest.TestCase): + def _extract_wheels(self, dest: pathlib.Path, filenames: list[str]) -> None: + root = _find_runfiles_root() + for name in filenames: + matches = list(root.rglob(name)) + self.assertTrue(matches, f"Expected wheel {name!r} under {root}") + with zipfile.ZipFile(matches[0]) as zf: + zf.extractall(dest) + + def test_setuptools_and_meson_c_cpp_extensions(self): + with tempfile.TemporaryDirectory() as tmp: + self._extract_wheels( + pathlib.Path(tmp), + ["tiny_setuptools.sdist_build.whl", "tiny_meson.sdist_build.whl"], + ) + sys.path.insert(0, tmp) + try: + tiny_setuptools = importlib.import_module("tiny_setuptools") + tiny_meson = importlib.import_module("tiny_meson") + self.assertEqual(tiny_setuptools.sub_ints(10, 3), 7) + self.assertEqual(tiny_meson.add_ints(2, 3), 5) + self.assertEqual(tiny_meson.mul_ints(4, 5), 20) + finally: + sys.path.remove(tmp) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/sdist_cross_compile/requirements.txt b/examples/sdist_cross_compile/requirements.txt new file mode 100644 index 0000000000..ff076d1ea8 --- /dev/null +++ b/examples/sdist_cross_compile/requirements.txt @@ -0,0 +1,5 @@ +# Build-time dependencies for meson-python sdists (prebuilt wheels from PyPI) +meson-python==0.22.1 +meson==1.10.2 +pyproject-metadata==0.11.0 +ninja==1.13.0 diff --git a/examples/sdist_cross_compile/transitions.bzl b/examples/sdist_cross_compile/transitions.bzl new file mode 100644 index 0000000000..ae803879b8 --- /dev/null +++ b/examples/sdist_cross_compile/transitions.bzl @@ -0,0 +1,43 @@ +"""Rule to build dependencies under a target platform transition.""" + +def _platform_transition_impl(_settings, attr): + return {"//command_line_option:platforms": str(attr.target_platform)} + +_platform_transition = transition( + implementation = _platform_transition_impl, + inputs = [], + outputs = ["//command_line_option:platforms"], +) + +def _cross_platform_files_impl(ctx): + files = depset( + transitive = [ + dep[DefaultInfo].files + for dep in ctx.attr.deps + ] + [ + dep[DefaultInfo].default_runfiles.files + for dep in ctx.attr.deps + ], + ) + return [ + DefaultInfo( + files = files, + runfiles = ctx.runfiles(transitive_files = files), + ), + ] + +cross_platform_files = rule( + implementation = _cross_platform_files_impl, + attrs = { + "deps": attr.label_list( + cfg = _platform_transition, + mandatory = True, + ), + "target_platform": attr.label( + mandatory = True, + ), + "_allowlist_function_transition": attr.label( + default = "@bazel_tools//tools/allowlists/function_transition_allowlist", + ), + }, +) diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index e9bf8c3b46..5d851d5f01 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -753,6 +753,8 @@ bzl_library( "//python/private:rule_builders", "//python/private:toolchain_types", "//python/private:version", + "@rules_cc//cc:bzl_srcs", + "@rules_cc//cc/common", ], ) diff --git a/python/private/pypi/py_sdist_wheel.bzl b/python/private/pypi/py_sdist_wheel.bzl index 0f14d06045..cf92bbbed6 100644 --- a/python/private/pypi/py_sdist_wheel.bzl +++ b/python/private/pypi/py_sdist_wheel.bzl @@ -1,5 +1,7 @@ """Rule for building a Python wheel (.whl) from an sdist archive in a Bazel build action.""" +load("@rules_cc//cc:action_names.bzl", "ACTION_NAMES") +load("@rules_cc//cc/common:cc_common.bzl", "cc_common") load("//python/private:attr_builders.bzl", "attrb") load("//python/private:attributes.bzl", "REQUIRED_EXEC_GROUP_BUILDERS") load("//python/private:builders.bzl", "builders") @@ -11,7 +13,9 @@ load("//python/private:reexports.bzl", "BuiltinPyInfo") load("//python/private:rule_builders.bzl", "ruleb") load( "//python/private:toolchain_types.bzl", + "CC_TOOLCHAIN_TYPE", "EXEC_TOOLS_TOOLCHAIN_TYPE", + "PY_CC_TOOLCHAIN_TYPE", "TARGET_TOOLCHAIN_TYPE", ) load("//python/private:version.bzl", "version") @@ -272,6 +276,11 @@ def _py_sdist_wheel_impl(ctx): target_runtime = target_tc.py3_runtime if target_tc else None _validate_sdist_toolchains(exec_runtime, target_runtime) + cc_tc_info = ctx.toolchains[CC_TOOLCHAIN_TYPE] + cc_toolchain = cc_tc_info.cc if cc_tc_info else None + py_cc_tc_info = ctx.toolchains[PY_CC_TOOLCHAIN_TYPE] + py_cc_toolchain = py_cc_tc_info.py_cc_toolchain if py_cc_tc_info else None + if not ctx.attr.distribution or not ctx.attr.version: parsed_dist, parsed_ver = _parse_sdist_filename(ctx.file.sdist.basename) else: @@ -359,6 +368,88 @@ def _py_sdist_wheel_impl(ctx): for patch_file, strip_val in zip(patches, strips): args.add("--patch", "{}:{}".format(patch_file.path, strip_val)) + transitive_inputs = [build_deps.files, bootstrap_deps.files] + + if cc_toolchain: + transitive_inputs.append(cc_toolchain.all_files) + feature_config = cc_common.configure_features( + ctx = ctx, + cc_toolchain = cc_toolchain, + requested_features = ctx.features, + unsupported_features = ctx.disabled_features, + ) + cc_bin = cc_common.get_tool_for_action( + feature_configuration = feature_config, + action_name = ACTION_NAMES.c_compile, + ) + cxx_bin = cc_common.get_tool_for_action( + feature_configuration = feature_config, + action_name = ACTION_NAMES.cpp_compile, + ) + compile_vars = cc_common.create_compile_variables( + cc_toolchain = cc_toolchain, + feature_configuration = feature_config, + use_pic = True, + ) + c_flags = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_config, + action_name = ACTION_NAMES.c_compile, + variables = compile_vars, + ) + cxx_flags = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_config, + action_name = ACTION_NAMES.cpp_compile, + variables = compile_vars, + ) + link_vars = cc_common.create_link_variables( + cc_toolchain = cc_toolchain, + feature_configuration = feature_config, + is_using_linker = True, + is_linking_dynamic_library = True, + ) + ld_flags = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_config, + action_name = ACTION_NAMES.cpp_link_dynamic_library, + variables = link_vars, + ) + static_rt_libs = cc_toolchain.static_runtime_lib( + feature_configuration = feature_config, + ) + transitive_inputs.append(static_rt_libs) + if cc_bin: + args.add("--cc", cc_bin) + if cxx_bin: + args.add("--cxx", cxx_bin) + if cc_toolchain.ar_executable: + args.add("--ar", cc_toolchain.ar_executable) + if cc_toolchain.sysroot: + args.add("--sysroot", cc_toolchain.sysroot) + args.add_all(c_flags, format_each = "--cflag=%s") + args.add_all(cxx_flags, format_each = "--cxxflag=%s") + args.add_all(ld_flags, format_each = "--ldflag=%s") + args.add_all(static_rt_libs, format_each = "--ldflag=%s") + + # Target Python runtime files (includes target lib/python3.13/_sysconfigdata_*.py) + if target_runtime and target_runtime.interpreter: + transitive_inputs.append(target_runtime.files) + + # interpreter is /bin/python3, so dirname of dirname is + args.add("--target-python-bin", target_runtime.interpreter.path) + + # Target Python C headers (include/python3.13/Python.h, pyconfig.h) & SOABI + if py_cc_toolchain: + headers_cc_info = py_cc_toolchain.headers.providers_map["CcInfo"] + transitive_inputs.append(headers_cc_info.compilation_context.headers) + args.add_all( + headers_cc_info.compilation_context.includes, + uniquify = True, + format_each = "--target-python-include=%s", + ) + if py_cc_toolchain.soabi: + args.add("--target-soabi", py_cc_toolchain.soabi) + if py_cc_toolchain.platform_tag: + args.add("--target-platform-tag", py_cc_toolchain.platform_tag) + helper_files = ( ctx.files._sdist_wheel_builder_helpers if PyInterpreterProgramInfo in ctx.attr.builder else [] ) @@ -370,7 +461,7 @@ def _py_sdist_wheel_impl(ctx): ) inputs = depset( direct = [ctx.file.sdist] + patches + helper_files, - transitive = [build_deps.files, bootstrap_deps.files], + transitive = transitive_inputs, ) actions_run( @@ -422,10 +513,13 @@ and only supports building wheels compatible with the host platform. ::: """, exec_groups = dict(REQUIRED_EXEC_GROUP_BUILDERS), + fragments = ["cpp"], attrs = PY_SDIST_WHEEL_ATTRS, provides = [PyBuiltWheelInfo], toolchains = [ ruleb.ToolchainType(TARGET_TOOLCHAIN_TYPE, mandatory = False), ruleb.ToolchainType(EXEC_TOOLS_TOOLCHAIN_TYPE, mandatory = True), + ruleb.ToolchainType(CC_TOOLCHAIN_TYPE, mandatory = False), + ruleb.ToolchainType(PY_CC_TOOLCHAIN_TYPE, mandatory = False), ], ).build() diff --git a/python/private/pypi/sdist_wheel_builder.py b/python/private/pypi/sdist_wheel_builder.py index 6af6882278..f41b8b2d26 100644 --- a/python/private/pypi/sdist_wheel_builder.py +++ b/python/private/pypi/sdist_wheel_builder.py @@ -17,6 +17,7 @@ import importlib.metadata import os import platform +import shlex import shutil import subprocess import sys @@ -270,6 +271,49 @@ def _get_macos_sysroot_cflag() -> str: return "" +_REDACTED_MACRO_PREFIXES = ("-D__DATE__=", "-D__TIMESTAMP__=", "-D__TIME__=") + + +def _absolutize_flag(prefix: Path, flag: str) -> str: + """Turn execroot-relative paths in a compiler/linker flag into absolute paths.""" + if flag.startswith("-Wl,"): + parts = flag[4:].split(",") + new_parts = [] + for p in parts: + if p.startswith("-L") and len(p) > 2 and not os.path.isabs(p[2:]) and (prefix / p[2:]).exists(): + new_parts.append("-L" + str((prefix / p[2:]).absolute())) + elif p and not p.startswith("-") and not os.path.isabs(p) and (prefix / p).exists(): + new_parts.append(str((prefix / p).absolute())) + else: + new_parts.append(p) + return "-Wl," + ",".join(new_parts) + for opt in ("--sysroot=", "-resource-dir=", "-isystem", "-I", "-L", "-B"): + if flag.startswith(opt) and len(flag) > len(opt): + rel = flag[len(opt):] + if not os.path.isabs(rel) and (prefix / rel).exists(): + return opt + str((prefix / rel).absolute()) + return flag + if flag.startswith("-") and "=" in flag: + key, _, rel = flag.partition("=") + if "/" in rel and not os.path.isabs(rel) and (prefix / rel).exists(): + return f"{key}={str((prefix / rel).absolute())}" + if flag and not flag.startswith("-") and not os.path.isabs(flag) and (prefix / flag).exists(): + return str((prefix / flag).absolute()) + return flag + + +def _sanitize_compile_flags(flags: list[str], ldflags: list[str]) -> list[str]: + """Strip redacted date/time macros and prefer link-action resource-dir.""" + out = [f for f in flags if not f.startswith(_REDACTED_MACRO_PREFIXES)] + link_resource_dirs = [f for f in ldflags if f.startswith("-resource-dir=")] + if not link_resource_dirs: + return out + return [ + link_resource_dirs[-1] if f.startswith("-resource-dir=") else f + for f in out + ] + + def main() -> None: parser = argparse.ArgumentParser( description="Build a wheel from an sdist archive into a TreeArtifact directory.", @@ -329,17 +373,35 @@ def main() -> None: parser.add_argument("--target-os", default="") parser.add_argument("--target-cpu", default="") parser.add_argument("--target-python-version", default="") + parser.add_argument("--cc", default="") + parser.add_argument("--cxx", default="") + parser.add_argument("--ar", default="") + parser.add_argument("--cflag", action="append", dest="cflags", default=[]) + parser.add_argument("--cxxflag", action="append", dest="cxxflags", default=[]) + parser.add_argument("--ldflag", action="append", dest="ldflags", default=[]) + parser.add_argument("--sysroot", default="") + parser.add_argument("--target-python-bin", default="") + parser.add_argument( + "--target-python-include", + action="append", + dest="target_python_includes", + default=[], + ) + parser.add_argument("--target-soabi", default="") + parser.add_argument("--target-platform-tag", default="") args = parser.parse_args() host_os = _detect_host_os() host_cpu = _detect_host_cpu() - if (args.target_os and args.target_os != host_os) or ( - args.target_cpu and args.target_cpu != host_cpu - ): + is_cross = bool( + (args.target_os and args.target_os != host_os) or + (args.target_cpu and args.target_cpu != host_cpu) + ) + if is_cross and not args.cc: raise RuntimeError( f"Target platform (os={args.target_os or 'any'}, cpu={args.target_cpu or 'any'}) " f"differs from host (os={host_os}, cpu={host_cpu}); " - "the default sdist builder only builds for the host." + "but no cross-compiler (--cc) was provided." ) host_py_ver = f"{sys.version_info.major}.{sys.version_info.minor}" if args.target_python_version and args.target_python_version != host_py_ver: @@ -384,6 +446,11 @@ def main() -> None: *(f"{bp}/site-packages" for bp in bootstrap_py_paths), ], ) + for sp in site_pkg_imports: + sibling_bin = Path(sp).parent / "bin" + if sibling_bin.is_dir() and sibling_bin not in bin_dirs: + bin_dirs.append(sibling_bin) + resolved_python_paths = [ *wheel_py_paths, *site_pkg_imports, @@ -407,6 +474,12 @@ def main() -> None: strip=int(raw_strip), ) + def _resolve_tool(prefix: Path, raw: str) -> str: + if not raw or os.path.isabs(raw): + return raw + candidate = (prefix / raw).absolute() + return str(candidate) if candidate.exists() else raw + env = dict(orig_env) env["PYTHONHASHSEED"] = "0" env["PYTHONNOUSERSITE"] = "1" @@ -430,8 +503,47 @@ def main() -> None: else rust_remap_flag ) - include_dir = sysconfig.get_path("include") or "" + cc_bin = _resolve_tool(prefix, args.cc) + cxx_bin = _resolve_tool(prefix, args.cxx) + ar_bin = _resolve_tool(prefix, args.ar) + if cc_bin: + env["CC"] = cc_bin + env["LDSHARED"] = f"{cc_bin} -shared" + if cxx_bin: + env["CXX"] = cxx_bin + env["LDCXXSHARED"] = f"{cxx_bin} -shared" + if ar_bin: + env["AR"] = ar_bin + if args.sysroot: + sysroot_abs = _resolve_tool(prefix, args.sysroot) + for var in ("CFLAGS", "CXXFLAGS", "LDFLAGS"): + env[var] = ( + f"{env[var]} --sysroot={sysroot_abs}" + if env.get(var) else f"--sysroot={sysroot_abs}" + ) + + # Because pip wheel runs with cwd=sdist_root (`scratch_dir/src/...`) + # rather than the Bazel execroot, any execroot-relative paths + # (`external/...`) in those flags need to be turned into absolute + # paths (`prefix / ...`). + for var, raw_flags in ( + ("CFLAGS", _sanitize_compile_flags(args.cflags, args.ldflags)), + ("CXXFLAGS", _sanitize_compile_flags(args.cxxflags, args.ldflags)), + ("LDFLAGS", [f for f in args.ldflags if f != "-shared"]), + ): + if raw_flags: + resolved = " ".join(shlex.quote(_absolutize_flag(prefix, f)) for f in raw_flags) + env[var] = f"{env[var]} {resolved}" if env.get(var) else resolved + cppflags: list[str] = [env["CPPFLAGS"]] if env.get("CPPFLAGS") else [] + if args.target_python_includes: + for inc in args.target_python_includes: + inc_abs = str((prefix / inc).absolute()) + cppflags.append(f"-I{inc_abs}") + else: + include_dir = sysconfig.get_path("include") or "" + if include_dir and os.path.isdir(include_dir): + cppflags.append(f"-isystem {include_dir}") sysroot_flag = _get_macos_sysroot_cflag() if ( sysroot_flag @@ -439,8 +551,6 @@ def main() -> None: and "-isysroot" not in env.get("CFLAGS", "") ): cppflags.append(sysroot_flag) - if include_dir and os.path.isdir(include_dir): - cppflags.append(f"-isystem {include_dir}") if cppflags: env["CPPFLAGS"] = " ".join(cppflags) @@ -464,6 +574,106 @@ def main() -> None: pip_config_args = [f"--config-settings={cs}" for cs in args.config_settings] + if is_cross: + if args.target_os == "linux" and args.target_cpu: + env["_PYTHON_HOST_PLATFORM"] = f"linux-{args.target_cpu}" + if args.target_soabi: + ext = ".pyd" if args.target_os == "windows" else ".so" + env["SETUPTOOLS_EXT_SUFFIX"] = f".{args.target_soabi}{ext}" + if args.target_python_bin and args.target_python_version: + target_py_root = (prefix / args.target_python_bin).absolute().parent.parent + target_stdlib = target_py_root / "lib" / f"python{args.target_python_version}" + sysconfig_files = sorted(target_stdlib.glob("_sysconfigdata_*.py")) + if sysconfig_files: + sc_src = sysconfig_files[0] + sc_dir = scratch_dir / "sysconfig" + sc_dir.mkdir(parents=True, exist_ok=True) + sc_text = sc_src.read_text(encoding="utf-8") + if args.target_python_includes: + inc_dirs = [ + str((prefix / inc).absolute()) + for inc in args.target_python_includes + if (prefix / inc / "Python.h").is_file() + ] + inc_abs = ( + inc_dirs[0] + if inc_dirs + else str((prefix / args.target_python_includes[-1]).absolute()) + ) + sc_text += ( + f"\nbuild_time_vars['INCLUDEPY'] = {inc_abs!r}\n" + f"build_time_vars['CONFINCLUDEPY'] = {inc_abs!r}\n" + ) + (sc_dir / sc_src.name).write_text(sc_text, encoding="utf-8") + env["_PYTHON_SYSCONFIGDATA_NAME"] = sc_src.stem + resolved_python_paths.insert(0, str(sc_dir)) + env["PYTHONPATH"] = os.pathsep.join(resolved_python_paths) + + pyproject_file = sdist_root / "pyproject.toml" + is_meson = ( + pyproject_file.is_file() + and "mesonpy" in pyproject_file.read_text(errors="ignore") + ) + if is_meson: + # Prevent Meson from querying host pkg-config (e.g. + # /usr/lib/.../python-3.13.pc -> -I/usr/include/python3.13) + # instead of Bazel's hermetic Python headers via sysconfig. + env.setdefault("PKG_CONFIG_LIBDIR", "") + + if is_cross and is_meson: + cpu_family = {"x86_32": "x86"}.get(args.target_cpu, args.target_cpu) + cross_ini = scratch_dir / "meson-cross.ini" + cross_lines = [ + "[binaries]", + f"c = {cc_bin!r}", + ] + if cxx_bin: + cross_lines.append(f"cpp = {cxx_bin!r}") + if ar_bin: + meson_ar = ar_bin + if "zig" in ar_bin or "zig" in cc_bin: + # zig-specific adjustment: zig's ar doesn't support thin + # archives. + ar_wrapper = scratch_bin_dir / "ar-no-thin" + ar_wrapper.write_text( + f"#!/usr/bin/env python3\n" + f"import os, sys\n" + f"args = sys.argv[1:]\n" + f"if args and not args[0].startswith('-'):\n" + f" args[0] = args[0].replace('T', '')\n" + f"os.execv({ar_bin!r}, [{ar_bin!r}, *args])\n", + encoding="utf-8", + ) + os.chmod(ar_wrapper, 0o755) + meson_ar = str(ar_wrapper) + cross_lines.append(f"ar = {meson_ar!r}") + cross_lines += [ + "", + "[host_machine]", + f"system = {args.target_os!r}", + f"cpu_family = {cpu_family!r}", + f"cpu = {args.target_cpu!r}", + "endian = 'little'", + ] + longdouble_formats = { + ("linux", "aarch64"): "IEEE_QUAD_LE", + ("linux", "x86_64"): "INTEL_EXTENDED_16_BYTES_LE", + ("linux", "x86_32"): "INTEL_EXTENDED_12_BYTES_LE", + ("macos", "aarch64"): "IEEE_DOUBLE_LE", + ("macos", "x86_64"): "INTEL_EXTENDED_16_BYTES_LE", + ("windows", "aarch64"): "IEEE_DOUBLE_LE", + ("windows", "x86_64"): "IEEE_DOUBLE_LE", + } + ld_fmt = longdouble_formats.get((args.target_os, args.target_cpu)) + if ld_fmt: + cross_lines += [ + "", + "[properties]", + f"longdouble_format = {ld_fmt!r}", + ] + cross_ini.write_text("\n".join(cross_lines) + "\n", encoding="utf-8") + pip_config_args.append(f"--config-settings=setup-args=--cross-file={cross_ini}") + cmd = [ build_python, "-m", diff --git a/tests/pypi/py_sdist_wheel/sdist_wheel_builder_test.py b/tests/pypi/py_sdist_wheel/sdist_wheel_builder_test.py index 8db5ed635b..8d3188d79e 100644 --- a/tests/pypi/py_sdist_wheel/sdist_wheel_builder_test.py +++ b/tests/pypi/py_sdist_wheel/sdist_wheel_builder_test.py @@ -95,7 +95,7 @@ def test_cross_platform_target_fails_before_build(self): ) self.assertNotEqual(proc.returncode, 0) self.assertIn( - "the default sdist builder only builds for the host", + "no cross-compiler (--cc) was provided", proc.stderr, ) @@ -219,6 +219,46 @@ def test_missing_import_root_fails_and_non_wheel_bin_ignored(self): self.assertEqual(wheel_py, []) self.assertEqual(bin_dirs, []) + def test_absolutize_and_sanitize_compile_flags(self): + with tempfile.TemporaryDirectory() as tmp: + prefix = pathlib.Path(tmp) + rel_dir = prefix / "external/llvm/resource" + rel_dir.mkdir(parents=True) + rel_sysroot = prefix / "external/sysroot" + rel_sysroot.mkdir(parents=True) + + self.assertEqual( + sdist_wheel_builder._absolutize_flag( + prefix, "-resource-dir=external/llvm/resource" + ), + f"-resource-dir={rel_dir.absolute()}", + ) + self.assertEqual( + sdist_wheel_builder._absolutize_flag( + prefix, "--sysroot=external/sysroot" + ), + f"--sysroot={rel_sysroot.absolute()}", + ) + self.assertEqual( + sdist_wheel_builder._absolutize_flag(prefix, "-O2"), + "-O2", + ) + + sanitized = sdist_wheel_builder._sanitize_compile_flags( + [ + "-O2", + '-D__DATE__="redacted"', + '-D__TIMESTAMP__="redacted"', + '-D__TIME__="redacted"', + "-resource-dir=external/llvm/old", + ], + ["-resource-dir=external/llvm/resource"], + ) + self.assertEqual( + sanitized, + ["-O2", "-resource-dir=external/llvm/resource"], + ) + def test_apply_unified_patch_carries_relocated_hunk_offset(self): patch_text = ( "--- a/sample.txt\n"