# Building Rust

_Pekit / Languages_

> Build Rust programs hermetically from the crates Cargo.lock pins with the rust library, one crate at a time or with Cargo whole, including tests, git crates, C dependencies, bindgen, control-flow protection, and the pinned Rust toolchain.

The rust library builds Rust programs from the crates your `Cargo.lock`
pins, with no network and nothing of the host. It builds a Cargo workspace
one crate at a time, as Bazel's Rust rules do, or whole, as Cargo does.
Import it as `github.com/gcslib/rust`.

## Before you start

- The rust, gcc, buildenv, and python libraries. See [Libraries](/pekit/libraries/libraries.md).
- A Cargo workspace with a `Cargo.lock`.

## Register the toolchain

The library asks the `toolchain` module for a `Toolchain::Rust`. Its
`rust_1_98` is Rust 1.98.1 from static.rust-lang.org, each part pinned by
its SHA-256, with the standard libraries for `x86_64-unknown-linux-gnu` and
`x86_64-unknown-linux-musl`, and their source, `rust-src`. It runs on the
gcc library's Bootlin sysroot and links with its compiler. Register both in
`workspace.gcsl`:

```gcsl
import Toolchain::C gcc_x86_64 from "github.com/gcslib/gcc"
import Toolchain::Rust rust_1_98 from "github.com/gcslib/rust"
import Toolchain from toolchain

pekitconf = {toolchains = [Toolchain::C gcc_x86_64, Toolchain::Rust rust_1_98]}
```

rustc needs zlib, which the sysroot lacks. The toolchain builds zlib from
its pinned source with the buildenv library's pinned environment, so a
first build takes longer.

## Build one crate at a time

1. Plan the workspace with `rust.workspace`, then build what you need of
   it:

   ```gcsl
   import "github.com/gcslib/rust"

   fn crates() -> rust.RustWorkspace {
       = rust.workspace(dir("."), rust.vendored(file("Cargo.lock")))
   }

   def build server() {
       = rust.bin(crates(), "server")
   }

   def build client_library() {
       = rust.library(crates(), "client")
   }
   ```

2. Build a program:

   ```sh
   pekit build server
   ```

`rust.bin(ws, package, name)` gives a member's program, by default the one
named after the member. `rust.library(ws, package)` gives its shared
library, and `rust.static_library(ws, package)` its static library. Give
each `features` to turn on the member's own features, as `cargo build
--features` does.

## Check the result

pekit prints the program's path. Change one source file and build again:
pekit compiles that file's crate, and the crates that depend on it, again,
and finds every other crate in the store.

## How planning works

Cargo plans the build: what each member needs, unit by unit, as `cargo
build --unit-graph` lists it. Each crate, with the features Cargo resolves
for the member you build, is compiled as a step of its own, and so is each
build script and each run of one. Two programs that use the same crate
with the same features share the one step.

Planning reads the manifests, `Cargo.lock`, and which files exist, never
what the sources say. Editing a source plans nothing again.

It leaves out files under a hidden directory, such as `.git` or `.claude`,
but `.cargo`, and under the paths that `workspace`'s `ignore` names,
relative to the workspace: by default `["target", "pekit-out"]`. Add any
other directory a build writes, such as `ignore = ["target", "pekit-out",
"docs/dist"]`, so that what it writes there doesn't plan the workspace
again. pekit never lists a nested checkout or a Git worktree inside the
workspace, a directory that holds a `.git` of its own, so an agent's
worktree under `crates/` isn't taken for a member. Planning doesn't read
`.gitignore`, and it still walks the directories that `ignore` names.

Features follow the member. A program built from a member that asks for a
crate's feature gets it, and a program from a member that doesn't never
does, even when you build both at once. Cargo unifies features across
everything one `cargo build` names; pekit plans each member on its own.
Give `workspace` `whole = true` to plan every member with the whole
workspace's features instead, as `cargo build --workspace` and `cargo test
--workspace` resolve them, so that a member's tests see what they see under
Cargo.

Cargo's plans leave out some of what it takes from the manifests: the
`[lints]` table, which targets have `harness = false`, and the `--check-cfg`
flags it gives every crate. The library reads each member's manifest for
them with the python library's pinned Python, and compiles the member's
crates with them, as Cargo does. Link-time optimization follows Cargo too:
the programs a profile's `lto` names are optimized whole, and the libraries
they link carry what that needs. A profile's `strip` applies as Cargo
applies it, so `strip = "symbols"` gives programs without symbols.

## Profiles

`workspace` plans for the Cargo profile `profile`, by default `release`:

```gcsl
fn crates() -> rust.RustWorkspace {
    = rust.workspace(dir("."), rust.vendored(file("Cargo.lock")), profile = "dev")
}
```

A profile is chosen as Cargo chooses it. `dev` builds as `cargo build`
does, and tests take the `test` profile, as under `cargo test`. `release`
builds as `--release` does. Any other profile, such as a `quick` profile
that your `Cargo.toml` defines, builds as `--profile quick` does. Each
crate is compiled with its profile's settings, `debug = "line-tables-only"`
and per-package overrides included.

A build script is told `PROFILE` as Cargo tells it: `release` for a
profile that inherits from `release`, and `debug` for one that inherits
from `dev`. pekit reads the chain of `inherits` from the workspace's
`Cargo.toml`. A profile that only `.cargo/config.toml` defines isn't
supported.

To set a profile as an environment variable would, give `profile_env`:

```gcsl
rust.workspace(
    dir("."),
    rust.vendored(file("Cargo.lock")),
    profile = "dev",
    profile_env = [{key = "CARGO_PROFILE_DEV_DEBUG"; value = "line-tables-only"}],
)
```

Each key has to start with `CARGO_PROFILE_`. Cargo plans with them set, so
they apply as they would to `cargo build`.

A profile's `rustflags`, which Cargo's unstable `profile-rustflags` feature
allows, apply as Cargo applies them, after the workspace's own flags.

## Control-flow protection

A program built one crate at a time for an x86-64 glibc target, such as
`x86_64-unknown-linux-gnu`, has Intel's control-flow protection (CET)
compiled in: indirect-branch tracking (IBT) and shadow stacks (SHSTK).

The linker marks a program with IBT and SHSTK only if every object it links
is marked. Upstream's prebuilt standard libraries aren't, so the rust
library compiles them again from the toolchain's `rust-src`:

- each crate is a step, as your own crates are, and every workspace that
  uses the same toolchain and target shares them;
- they have the features upstream's have, but `compiler_builtins`' C
  intrinsics, whose source `rust-src` doesn't include;
- they use the `dist` profile that upstream's use, so a crate compiled with
  link-time optimization still finds their bitcode;
- their source paths are `/rustc/COMMIT/library`, as upstream's are, so no
  path of the step's is in them.

Every crate compiled for the target is then compiled against them with
`-Zcf-protection=full`. C that a build script compiles through the `cc`
crate gets `-fcf-protection=full`, in `CFLAGS_<target>` and
`CXXFLAGS_<target>`. A package's `env` in `crates` can set those itself.

The first glibc build compiles the standard libraries, which takes a few
minutes. After that the store has them.

### Unstable flags on a stable Rust

`-Zcf-protection` is unstable, and the pinned Rust is stable. Only rustc is
told `RUSTC_BOOTSTRAP=1`, in the step that compiles a crate. Build scripts
aren't told it or the flags, so a build script that probes the compiler,
as autocfg does, finds the same stable compiler it would without them.
Build scripts and procedural macros run on the build machine, and are
compiled as before.

`RUSTC_BOOTSTRAP` isn't supported upstream, so a flag's behavior can change
between Rust versions. After updating the toolchain, check a program with
`readelf -n`.

### What glibc must provide

The program is marked only if the C library's own objects it links are
marked too: its start files, `Scrt1.o`, `crti.o` and `crtn.o`, and
`libc_nonshared.a`. The gcc library's Bootlin glibc isn't built with CET.
A program linked with `gcc_x86_64` is therefore not marked, even though
every object Rust compiles for it is. To see what isn't marked, link with
`-Clink-arg=-Wl,-z,cet-report=error` in `rustflags`, and the linker names
each object.

### Turning it off, and other targets

To use upstream's standard libraries without the flags, give `workspace`
`cet = false`.

A musl target never has control-flow protection: musl's assembly isn't
marked, so no static musl program can be. CET is x86-64's, so a target
for another architecture doesn't have it either. `cet = true` with any
target but an x86-64 glibc one is an error. `cargo_build`, which builds
with Cargo whole, doesn't give control-flow protection either.

## Crates that read outside their directory

Each step's sandbox holds the toolchain, the crate's own directory, and
what it is given. A crate that reads a file outside its directory needs it
named. Give `workspace` the settings of such packages in `crates`:

```gcsl
rust.workspace(
    dir("."),
    rust.vendored(file("Cargo.lock")),
    crates = [
        {package = "policy"; data = [{at = "registry.d"; place = dir("registry.d")}]},
        {
            package = "sdk-sys"
            env = [{key = "SDK_DIR"; value = "/opt/sdk"}]
            given = [{at = "/opt/sdk"; place = build sdk()}]
        },
    ],
)
```

Each setting does one thing:

- **`data`** places files and directories under the workspace, where the
  crate's compiles and build script find them.
- **`env`** sets variables for its build script and its compiles.
- **`given`** places files and directories at absolute paths, for its build
  script and its compiles, and for every crate that depends on it. A
  native library that a build script links goes here, so that the programs
  that use the crate link it too.

## Tests

`rust.tests(ws, package)` gives a member's test programs, its unit tests
and each integration test, as `cargo test -p` builds them. Give
`features` too if the tests need them. `rust.run_test(test)` runs one as a
step, in a sandbox of the toolchain's runtime with a writable `/tmp`. It
runs from its package's directory, as Cargo does, and the sandbox holds
that directory with the package's `data` and `beside`:

```gcsl
def test server_tests(tests: List<rust.RustTest> = rust.tests(crates(), "server")) {
    let ran = for each in tests { = rust.run_test(each) }
}
```

So a test reads its own files by relative paths or through
`CARGO_MANIFEST_DIR`, as it does under Cargo. What a test writes there stays
in its sandbox, so no change reaches your workspace.

Give `run_test` what else a test reads in `given`, such as another member's
directory, its variables in `env`, and its arguments in `args`, such as a
filter and `--test-threads=1`. A path in `given` that the package already
places is placed once, from the package. A test reruns when its program or
any file of its package changes.

A test target with `harness = false` in its manifest is compiled as a
program of its own, as Cargo compiles it.

`rust.tests` builds the package's examples too, as `cargo test` does. A
test program runs at `/work/deps/<name>`, with the examples beside it in
`/work/examples`, as in Cargo's target directory. So a test that finds an
example from its own path, at `../../examples/<name>`, finds it.

`rust.benches(ws, package)` gives a member's benchmarks, as `cargo test
--benches` builds them, and `rust.run_test` runs each. A benchmark with
`harness = false` is a program of its own, which runs with no arguments.

## Documentation, its tests, and Clippy

`rust.doctests(ws, package)` tests a member's documentation, as `cargo test
--doc` does: rustdoc compiles and runs each crate's examples as a step. It
takes `features`, `given`, and `env` as `run_test` does, and gives no tests
for a member with no library.

`rust.clippy(ws, package)` checks a member with Clippy, as `cargo clippy
--all-targets` does: its library, programs, build script, tests, benchmarks,
and examples, each crate a step. `flags` come after the member's lints, so
`flags = ["-Dwarnings"]` denies every warning. A check fails when a lint it
denies fires.

Clippy's `cargo` lints read `cargo metadata`, which a check of one crate
can't run, so `rust.clippy` allows them. `rust.cargo_lints(ws)` checks them
instead, as `cargo clippy --workspace` does, in one step for the whole
workspace. The step holds what Cargo plans with: the manifests, the lock,
the vendored crates, and Cargo's home, with the network off. The member's
`[lints]` that name these lints apply, then `flags`, so `flags =
["-Wclippy::cargo", "-Dwarnings"]` denies them. It reads the workspace's
Clippy configuration too, such as `allowed-duplicate-crates`.

`rust.docs(ws, package)` makes a member's library documentation, as `cargo
doc --no-deps` does, as a step, and gives the directory rustdoc wrote.
`flags` come after the member's lints, as they do for Clippy, so `flags =
["-Dwarnings"]` fails it when rustdoc warns, such as about a broken link.

All of these are steps that the rust library makes, so make them in a test's
parameter defaults, where a test plans and builds what it needs:

```gcsl
def test clippy(checked: List<List<{}>> = rust.clippy(crates(), "server", flags = ["-Dwarnings"])) {}

def test doctests(ran: List<List<{}>> = rust.doctests(crates(), "server")) {}

def test docs(made: Dir = rust.docs(crates(), "server", flags = ["-Dwarnings"])) {}

def test cargo_lints(checked: {} = rust.cargo_lints(crates(), flags = ["-Wclippy::cargo", "-Dwarnings"])) {}
```

## Build with Cargo, whole

`rust.cargo_build` builds the workspace with Cargo, in one step:

```gcsl
import "github.com/gcslib/rust"

def build ppk() {
    = rust.cargo_build(dir("src"), rust.vendored(file("src/Cargo.lock")), bins = ["ppk"])
}
```

`rust.cargo_build(src, vendor, bins)` builds the Cargo workspace `src` with
`cargo build --release --frozen --offline`, from the crates of `vendor`. It
gives a directory of the binaries `bins`, each by its name. `packages`
names the workspace's packages to build, as Cargo's `-p` does.

The whole of `cargo build` is one step, so changing one source file runs it
again. Cargo's target directory is kept between runs in the step's
[scratch directory](/pekit/building/writing-steps.md#keep-state-between-runs), so the
crates of `vendor` aren't compiled again. The workspace's own crates, and
crates it takes by their paths, are always compiled again. Cargo judges
them by their files' modification times, which a file put back as it was
can make look older than the last build.

Either way of building takes its crates from `rust.vendored`, so no crate
is fetched again.

## Where crates come from

`rust.vendored(lock)` fetches every crate of crates.io that `lock` pins,
each checked against the checksum `Cargo.lock` records for it, and lays
them out as `cargo vendor` does. Each crate's fetch and unpacking is kept
in the store.

A crate from a git repository is pinned by the commit `Cargo.lock` records
for it. `rust.vendored` fetches the repository at that commit with
`fetch_git`, once for every crate it holds. It gives each crate's directory
as the repository has it, so a crate that takes another of the same
repository by its path still finds it. A crate whose manifest takes values
from its workspace's, such as `version.workspace = true`, or names a
sibling crate's path, has its manifest written for it to build on its own.

A crate from anywhere else is an error, since nothing pins it.

## Git crates of a pinned library

If `pekit.lock` pins a library from the same repository as a git crate,
`Cargo.lock` must pin the crate at the library's commit, because the
library's settings for the crate and the crate must match. A crate at
another commit is an error that names both commits, so update one lock to
match the other.

A distribution that builds others' workspaces can set the context
`crates_at_pins` instead. Each such crate is then built at the library's
commit, not at the commit `Cargo.lock` records, so a fix to one crate of a
repository reaches every workspace that pins its library without a change
to each workspace's `Cargo.lock`:

```gcsl
let vendor = rust.vendored(file("Cargo.lock")) with { crates_at_pins = true }
```

`rust.overrides_report(vendor)` lists each crate built at another commit
than its lock records, one line each, `NAME URL LOCKED -> PINNED`, for a
packager to record.

Cargo takes the crate only while the lock still describes it. If the
crate has another version at the library's commit, the build fails and
says to update the lock with `cargo update -p NAME`. If its dependencies
changed, Cargo's own check of the lock fails.

## Targets and flags

By default `cargo_build` builds for `x86_64-unknown-linux-musl`, as static,
position-independent programs that need nothing of the system they run on.
Give `target = "x86_64-unknown-linux-gnu"` for programs linked against
glibc instead.

The flags follow the target: a glibc build takes none unless you give
`rustflags`. The library's flags are Cargo's `build.rustflags`, so a
project's own configuration of its target's flags, or of its linker, takes
precedence over them, as Cargo intends.

## C, libraries, and bindings

C that a crate compiles through the `cc` crate, such as `zstd-sys`, is
compiled for the target by `target_c`. By default that's the gcc library's
Bootlin musl toolchain, `gcc_x86_64_musl()`, for a musl target, which a
static musl program needs, and the registered C toolchain for any other.

`cargo_build` takes these as well:

- **`libs`** names libraries a crate builds to give besides the binaries,
  such as a `staticlib`: `libs = ["libpeios.a"]`.
- **`beside`** places directories next to the source, at `../NAME`, for a
  crate that takes another by a path outside its own tree.
- **`env`** gives every build script variables of its own, each a
  `{key; value}`, as Cargo's `[env]` table does.
- **`libclang`** is for a build script that runs bindgen: a list of one
  directory holding `libclang.so`, such as
  `libclang = [clang.libclang_18()]`. The clang library's `libclang_18` is
  a pinned build from PyPI. The build is given `LIBCLANG_PATH`, and
  `BINDGEN_EXTRA_CLANG_ARGS` names the target C toolchain's own headers and
  sysroot, so bindgen parses as that toolchain's compiler would.

A build script finds the C compiler in `CC_<target>`, the C++ compiler
beside it in `CXX_<target>`, such as `x86_64-linux-g++` beside
`x86_64-linux-gcc`, and the archiver in `AR_<target>`, so a crate that
compiles C++ through `cc` builds. That holds both one crate at a time and
with `cargo_build`.

No pkg-config is pinned, and a build script's sandbox holds only the
toolchain, so a probe for a system library fails the same way on every
machine. A crate that falls back without the library, or loads it at run
time, such as `wayland-sys` with its `dlopen` feature, builds. For a crate
that has to link a system library, give the library through `given` and
tell its build script where it is through `env`.

Everything is pinned, so a strict build gives the same program, byte for
byte, on any machine. See [Hermetic and Strict
Builds](/pekit/concepts/hermetic-and-strict-builds.md).

Related content:

- [Building C](/pekit/languages/building-c.md)
- [Writing and Running Tests](/pekit/testing-and-running/testing.md)
- [Libraries](/pekit/libraries/libraries.md)
