Skip to content

Instantly share code, notes, and snippets.

@ivan
Last active September 29, 2023 04:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ivan/594026bee196cb290764ca7af861b138 to your computer and use it in GitHub Desktop.
Save ivan/594026bee196cb290764ca7af861b138 to your computer and use it in GitHub Desktop.
cargo wrapper for NixOS and Rust nightly: mold, target-cpu, -Z share-generics
#!/usr/bin/env bash
# NixOS-only cargo wrapper that:
# - always uses mold for linking.
# - sets `-C target-cpu=haswell` to avoid generating code for pre-2013 CPUs.
# - sets `-C link-arg=-Wl,--compress-debug-sections=zlib-gabi` to compress debug sections.
# - sets LIBCLANG_PATH for projects that need clang.
# - sets `-Z share-generics` to reduce output binary sizes by ~2MB.
# - turns on cargo's sparse-registry feature.
# - increases niceness slightly with `nice -n 2` .
# - uses `choom -n 750` to be more likely to be selected by the OOM killer.
#
# Only Rust nightly is supported.
#
# Note that if a project or any of its dependencies link to openssl, it will probably also need:
# openssl = { version = "0.10", features = ["vendored"] }
#
# For your release builds, use `cargo build --release -Z build-std --target x86_64-unknown-linux-gnu`
# when you can to reduce output binary sizes by another ~2MB.
set -e -o pipefail
CARGO_BIN=/run/current-system/sw/bin/cargo
MOLD_BIN=/run/current-system/sw/bin/mold
CLANG_BIN=/run/current-system/sw/bin/clang
TARGET_CPU=haswell
# For librocksdb-sys
export LIBCLANG_PATH=$(dirname -- "$(ldd -- "$(rg -- '^ *exec ' $(readlink -- "$CLANG_BIN") | tail -n 1 | rg -o '/nix/[^ ]+')" | rg -F libclang-cpp.so. | sed -r 's/ +/ /g' | cut -d ' ' -f 3)")
# Don't touch RUSTFLAGS when building wasm, because mold does not work.
# ("note: rust-mold: error: unknown argument: --ld-path=mold")
#
# Don't touch RUSTFLAGS if `-C link-arg=--ld-path=$MOLD_BIN` is already in RUSTFLAGS, because
# otherwise `cargo clippy` builds with `-C link-arg=--ld-path=$MOLD_BIN -C link-arg=--ld-path=$MOLD_BIN`
# and spends a lot of time recompiling with "different" compiler options.
if [[
" $* " != *" --target=wasm32-"* &&
" $* " != *" --target wasm32-"* &&
" $RUSTFLAGS " != *" -C link-arg=--ld-path=$MOLD_BIN -C link-arg=-Wl,--compress-debug-sections=zlib-gabi -C target-cpu=$TARGET_CPU -Z binary-dep-depinfo -Z share-generics "*
]]; then
export RUSTFLAGS="-C link-arg=--ld-path=$MOLD_BIN -C link-arg=-Wl,--compress-debug-sections=zlib-gabi -C target-cpu=$TARGET_CPU -Z binary-dep-depinfo -Z share-generics ${RUSTFLAGS:-}"
fi
# https://blog.rust-lang.org/2022/06/22/sparse-registry-testing.html
export CARGO_UNSTABLE_SPARSE_REGISTRY=true
exec nice -n 2 -- choom -n 750 -- "$CARGO_BIN" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment