#!/usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ This script builds a rust toolchain from source, with the necessary tool and target support for the Firefox build environment. The rust source is expected to have been fetched in $MOZ_FETCHES_DIR/rust. For repacking official rust builds instead, see repack_rust.py. """ import argparse import errno import os import shutil import subprocess import tempfile import textwrap from repack_rust import ( add_platform_arguments, expand_platforms, log, package_toolchain, ) def patch_src(patch, module): log(f"Patching Rust src... {module} with {patch}") patch = os.path.realpath(patch) subprocess.check_call(["patch", "-d", module, "-p1", "-i", patch, "--fuzz=0", "-s"]) def build_src(install_dir, host, targets, patches): install_dir = os.path.abspath(install_dir) fetches = os.environ["MOZ_FETCHES_DIR"] rust_dir = os.path.join(fetches, "rust") patch_dir = os.path.join(os.environ["GECKO_PATH"], "build", "build-rust") # Clear and remake any previous install directory. try: shutil.rmtree(install_dir) except OSError as e: if e.errno != errno.ENOENT: raise os.makedirs(install_dir) # Patch the src (see the --patch flag's description for details) for p in patches: module, colon, file = p.partition(":") if not colon: module, file = "", p patch_file = os.path.join(patch_dir, file) patch_module = os.path.join(rust_dir, module) patch_src(patch_file, patch_module) log("Building Rust...") example_config = "" for example_toml in ("config.example.toml", "config.toml.example"): path = os.path.join(rust_dir, example_toml) if os.path.exists(path): with open(path) as file: example_config = file.read() break if "ignore-git" in example_config: omit_git_hash = "ignore-git" else: omit_git_hash = "omit-git-hash" # Rust builds are configured primarily through a config.toml file. # # `sysconfdir` is overloaded to be relative instead of absolute. # This is the default of `install.sh`, but for whatever reason # `x.py install` has its own default of `/etc` which we don't want. base_config = textwrap.dedent( """ [build] docs = false sanitizers = true profiler = true extended = true tools = ["analysis", "cargo", "rustdoc", "rustfmt", "clippy", "src", "rust-analyzer"] cargo-native-static = true """ ) if any("android" in target for target in targets): base_config += f"""android-ndk = "{fetches}/android-ndk"\n""" base_config += textwrap.dedent( f""" [rust] {omit_git_hash} = false bootstrap-override-lld = true [install] prefix = "/" [llvm] download-ci-llvm = false """ ) if "msvc" in host: assert all("msvc" in target for target in targets) base_config += textwrap.dedent( f""" ldflags = "-winsysroot:{fetches}/vs" [llvm.build-config] CMAKE_MT = "llvm-mt.exe" CMAKE_ASM_MASM_COMPILER = "ml64.exe" """ ) else: assert all("msvc" not in target for target in targets) def target_config(target): if "msvc" in target: return textwrap.dedent( f""" [target.{target}] cc = "clang-cl.bat" cxx = "clang-cl.bat" linker = "lld-link.bat" ar = "llvm-lib" """ ) elif "android" in target: # Let x.py pick the compiler from the NDK return textwrap.dedent( f""" [target.{target}] """ ) else: # Rust requires these to be specified per-target return textwrap.dedent( f""" [target.{target}] cc = "clang" cxx = "clang++" linker = "clang" """ ) final_config = base_config for target in sorted(set(targets) | set([host])): final_config = final_config + target_config(target) with open(os.path.join(rust_dir, "config.toml"), "w") as file: file.write(final_config) # Setup the env so compilers and toolchains are visible clang = os.path.join(fetches, "clang") clang_bin = os.path.join(clang, "bin") clang_lib = os.path.join(clang, "lib") sysroot = os.path.join(fetches, "sysroot") with tempfile.TemporaryDirectory() as tmpdir: # The rust build doesn't offer much in terms of overriding compiler flags # when it builds LLVM's compiler-rt, but we want to build with a sysroot. # So, we create wrappers for clang and clang++ that add the sysroot to the # command line. for exe in ("clang", "clang++"): tmp_exe = os.path.join(tmpdir, exe) with open(tmp_exe, "w") as fh: fh.write("#!/bin/sh\n") fh.write(f'exec {clang_bin}/{exe} --sysroot={sysroot} "$@"\n') os.chmod(tmp_exe, 0o755) if "msvc" in host: # Same thing for the linker on windows, where we want to add the MSVC # sysroot with open(os.path.join(tmpdir, "lld-link.bat"), "w") as fh: fh.write("@echo off\n") fh.write(f"{clang_bin}/lld-link.exe -winsysroot:{fetches}/vs %*") # And clang-cl. with open(os.path.join(tmpdir, "clang-cl.bat"), "w") as fh: fh.write("@echo off\n") fh.write( f"{clang_bin}/clang-cl.exe -Xclang -ivfsoverlay -Xclang {fetches}/vs/overlay.yaml -winsysroot {fetches}/vs %*" ) # cc-rs expects to find ml64.exe to build asm files, without a way to override it. shutil.copy(f"{clang_bin}/llvm-ml.exe", f"{tmpdir}/ml64.exe") env = os.environ.copy() env.update({ "PATH": os.pathsep.join((tmpdir, clang_bin, os.environ["PATH"])), "LD_LIBRARY_PATH": clang_lib, "DESTDIR": install_dir, }) if "msvc" in host: cmake_bin = os.path.join(fetches, "cmake", "bin") ninja_bin = os.path.join(fetches, "ninja", "bin") env.update({ "PATH": os.pathsep.join((env["PATH"], cmake_bin, ninja_bin)), "CC_x86_64_pc_windows_msvc": "clang-cl.bat", "CXX_x86_64_pc_windows_msvc": "clang-cl.bat", "AR_x86_64_pc_windows_msvc": "llvm-lib", "RUSTC_WINDOWS_RC": "llvm-rc", }) # x.py install does everything we need for us. # If you're running into issues, consider using `-vv` to debug it. command = [ "python3", "x.py", "install", "-v", "--host", host, "--build", host, "--target", ",".join(targets), ] subprocess.check_call(command, stderr=subprocess.STDOUT, env=env, cwd=rust_dir) def build(host, targets, patches=[]): install_dir = "rustc" build_src(install_dir, host, targets, patches) package_toolchain(install_dir) def args(): """Read command line arguments and return options.""" parser = argparse.ArgumentParser() parser.add_argument( "--patch", dest="patches", action="append", default=[], help="apply the given patch file to the source." " Patch files should be placed in /build/build-rust." " Patches can be prefixed with `module-path:` to specify they" " apply to that git submodule in the Rust source." " e.g. `src/llvm-project:mypatch.diff` patches rust's llvm." " Can be given more than once.", ) add_platform_arguments(parser) args = parser.parse_args() expand_platforms(args) return args if __name__ == "__main__": build(**vars(args()))