Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions scripts/build/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Edge dependency types:

**`restat = 1`** — after the command runs, re-stat outputs; if mtime didn't change, prune downstream. Critical for idempotent steps (fetch no-op, codegen unchanged).

**`depfile`** — compiler writes `foo.o.d` listing every `#include`d header. Ninja reads it on the next build to know which headers this `.o` depends on. Codegen headers are order-only for this reason: they're declared outputs with restat, the depfile gives exact per-file header deps on build 2+, and order-only just ensures they exist for build 1. Dep outputs (`lib*.a`) are a different story — PCH, cc, and no-PCH cxx use them as _implicit_ deps, because local sub-builds (e.g. WebKit) rewrite forwarding headers as undeclared side effects and order-only would lag one build behind (see Gotchas).
**`depfile`** — compiler writes `foo.o.d` listing every `#include`d header. Ninja reads it on the next build to know which headers this `.o` depends on. Codegen headers are order-only for this reason: they're declared outputs with restat, the depfile gives exact per-file header deps on build 2+, and order-only just ensures they exist for build 1. This relies on the depfile spelling a header exactly as its edge declares it (`codegen/X.h`, buildDir-relative) — ninja matches the two by string, and an absolute depfile entry is a separate node that ninja only stats at startup, so the compile (the PCH above all) would pick up a codegen rerun one build late. `includeFlags()` in `compile.ts` spells build-dir `-I` dirs relative for exactly this reason, and `cc()`/`cxx()`/`pch()` reject an absolute one at configure time, so every `-I` into the build dir (bun's own via `bunCompileFlags()`, a dep's via `DirectBuild.includes`) goes through it. Dep outputs (`lib*.a`) are a different story — PCH, cc, and no-PCH cxx use them as _implicit_ deps, because local sub-builds (e.g. WebKit) rewrite forwarding headers as undeclared side effects and order-only would lag one build behind (see Gotchas).

## Iterating on the build system

Expand Down Expand Up @@ -233,7 +233,7 @@ Why not auto-register in emit functions? Some rules are shared (`dep_configure`

**Dep order in `allDeps` matters.** `fetchDeps: ["X"]` means X must come first (its `.ref` stamp node must exist). Link order matters too: static linking resolves left→right, providers after users.

**PCH, cc, and no-PCH cxx need implicit dep on `depHeaderSignal`**, not order-only. Local WebKit's sub-build rewrites forwarding headers as an undeclared side effect (only `lib*.a` are declared outputs). Depfiles record those headers, but ninja stats them before the sub-build runs — order-only lags one build. The lib itself is the invalidation signal. Codegen headers stay order-only: they're declared outputs with restat, so depfile tracking is exact.
**PCH, cc, and no-PCH cxx need implicit dep on `depHeaderSignal`**, not order-only. Local WebKit's sub-build rewrites forwarding headers as an undeclared side effect (only `lib*.a` are declared outputs). Depfiles record those headers, but ninja stats them before the sub-build runs — order-only lags one build. The lib itself is the invalidation signal. The same applies one level down: a direct dep's `.o` files take the `fetchDeps` producers' outputs (generated headers + source stamp) as implicit inputs in `emitDirect`, as `emitNestedCmake` does for its inner build. Codegen headers stay order-only: they're declared outputs with restat, so depfile tracking is exact — as long as the `-I` flags come from `includeFlags()` (depfile spelling must match the declared output) and the header is actually declared (a generated header that `root-pch.h` reaches but no edge declares makes the PCH lag one build; `BunBuiltinNames+extras.h` is declared by hand in `emitJsModules` for this reason).

**`isExecutable` must check `isFile()`.** `X_OK` on a directory means traversable — a `cmake/` dir in PATH would shadow the real cmake binary.

Expand Down
60 changes: 40 additions & 20 deletions scripts/build/bun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* - emit codegen → generated .cpp/.h/.rs
* - emit cargo build → libbun_rust.a
* - resolve all deps → lib paths + include dirs
* - build PCH from root-pch.h (implicit deps: WebKit libs + all codegen)
* - build PCH from root-pch.h (implicit deps: dep libs; codegen order-only + depfile)
* - compile all C/C++ with the PCH
* - link everything → bun-debug (or bun-profile, bun-asan, etc.)
* - smoke test: run `<exe> --revision` to catch load-time failures
Expand All @@ -30,13 +30,13 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "
import { dirname, relative, resolve, sep } from "node:path";
import type { Sources } from "../glob-sources.ts";
import { emitCodegen, type CodegenOutputs } from "./codegen.ts";
import { ar, cc, cxx, link, pch } from "./compile.ts";
import { ar, cc, cxx, includeFlags, link, pch } from "./compile.ts";
import { bunExeName, shouldStrip, type Config } from "./config.ts";
import { generateDepVersionsHeader } from "./depVersionsHeader.ts";
import { allDeps } from "./deps/index.ts";
import { lolhtml } from "./deps/lolhtml.ts";
import { assert } from "./error.ts";
import { bunIncludes, computeFlags, extraFlagsFor, linkDepends } from "./flags.ts";
import { bunIncludes, computeFlags, extraFlagsFor, linkDepends, type ComputedFlags } from "./flags.ts";
import { writeIfChanged } from "./fs.ts";
import type { BuildNode, Ninja } from "./ninja.ts";
import { emitRust, linkerMapPath, rustLibPath, rustLtoLinkInputs } from "./rust.ts";
Expand Down Expand Up @@ -118,6 +118,29 @@ function systemLibs(cfg: Config): string[] {
return libs;
}

/**
* The complete flag lists for bun's own compiles (PCH, cxx, cc): the computed
* flags, then -I for bun's include dirs + buildDir (the generated versions
* header) + every dep's include dirs, then -D.
*
* The include dirs go through includeFlags(): the codegen headers are only
* order-only inputs of these compiles, so the depfiles have to spell them the
* way their edges declare them (see includeFlags for the failure otherwise).
*/
export function bunCompileFlags(
n: Ninja,
cfg: Config,
flags: ComputedFlags,
depIncludes: string[],
): { cxxflags: string[]; cflags: string[] } {
const incFlags = includeFlags(n, [...bunIncludes(cfg), cfg.buildDir, ...depIncludes]);
const defineFlags = flags.defines.map(d => `-D${d}`);
return {
cxxflags: [...flags.cxxflags, ...incFlags, ...defineFlags],
cflags: [...flags.cflags, ...incFlags, ...defineFlags],
};
}

// ───────────────────────────────────────────────────────────────────────────
// Main orchestration
// ───────────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -251,16 +274,7 @@ export function emitBun(n: Ninja, cfg: Config, sources: Sources): BunOutput {
generateDepVersionsHeader(cfg);

const flags = computeFlags(cfg);

// Full include set: bun's own + all dep includes + buildDir (for the
// generated versions header).
const allIncludes = [...bunIncludes(cfg), cfg.buildDir, ...depIncludes];
const includeFlags = allIncludes.map(inc => `-I${inc}`);
const defineFlags = flags.defines.map(d => `-D${d}`);

// Final flag arrays for compile.
const cxxFlagsFull = [...flags.cxxflags, ...includeFlags, ...defineFlags];
const cFlagsFull = [...flags.cflags, ...includeFlags, ...defineFlags];
const { cxxflags: cxxFlagsFull, cflags: cFlagsFull } = bunCompileFlags(n, cfg, flags, depIncludes);

// ─── Step 4: PCH ───
// CI full mode (unused by the pipeline) skips the PCH; cpp-only/archive-link use it.
Expand All @@ -277,12 +291,17 @@ export function emitBun(n: Ninja, cfg: Config, sources: Sources): BunOutput {
// modified since PCH was built". As implicit inputs, restat sees the .a
// changed → PCH rebuilds → one-build convergence. See the pch() docstring.
//
// Codegen stays order-only: those outputs only change if inputs change,
// and inputs don't change mid-build. cppAll (not all) — bake/.rs outputs
// are rust-only; pulling them here would run bake-codegen in cpp-only CI
// mode where it fails on the pinned bun version (see cppAll docstring).
// Scripts that emit undeclared .h also emit a .cpp/.h in cppAll, so they
// still run. cxx transitively waits: cxx → PCH → deps+cppAll.
// Codegen stays order-only: the PCH's depfile names the generated headers
// root-pch.h reaches as the declared outputs they are (includeFlags()), so
// a codegen rerun re-dirties the PCH in the same run without the PCH
// depending on every generated file. A header root-pch.h reaches therefore
// has to BE a declared output (BunBuiltinNames+extras.h is declared by hand
// in emitJsModules), or the PCH lags one build behind it. cppAll (not all)
// — bake/.rs outputs are rust-only; pulling them here would run
// bake-codegen in cpp-only CI mode where it fails on the pinned bun version
// (see cppAll docstring). Scripts that emit undeclared .h also emit a
// .cpp/.h in cppAll, so they still run. cxx transitively waits:
// cxx → PCH → deps+cppAll.
pchOut = pch(n, cfg, "src/jsc/bindings/root-pch.h", {
flags: cxxFlagsFull,
implicitInputs: depHeaderSignal,
Expand Down Expand Up @@ -350,7 +369,8 @@ export function emitBun(n: Ninja, cfg: Config, sources: Sources): BunOutput {
// signal. Cost is negligible: if the libs changed you're relinking anyway.
//
// codegen.cppAll stays order-only: those headers ARE declared ninja outputs
// with restat, so depfile tracking is exact and doesn't lag.
// with restat, and includeFlags() makes the depfiles spell them as declared,
// so depfile tracking is exact and doesn't lag.
//
// PCH also has implicit deps on depHeaderSignal (see above). When PCH is enabled,
// cxx inherits the dep transitively via its implicit dep on the PCH, so we
Expand Down
18 changes: 13 additions & 5 deletions scripts/build/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,15 @@
* output, which ninja re-stats after the step ran. A file no edge declares
* is stat'd once at startup, so a compile that includes it picks up a rerun
* of the step one build late. That is why emitBindgen/emitBindgenV2 declare
* the per-file Generated*.h headers and not just the .cpp that gets compiled.
* the per-file Generated*.h headers and not just the .cpp that gets compiled,
* and why emitJsModules declares BunBuiltinNames+extras.h, which
* bundle-functions.ts writes as a side effect and the PCH reaches. "Names a
* declared output" is literal: the depfile entry and the declared output
* have to be the same string, which is what includeFlags() in compile.ts
* arranges for the -I flags.
*
* Files nothing compiles may stay undeclared (.d.ts twins, bundle-modules'
* eval/ dir, JSSink.lut.txt consumed within its own step). The remaining
* #included exception is BunBuiltinNames+extras.h from bundle-functions.ts,
* reached through the PCH.
* eval/ dir, JSSink.lut.txt consumed within its own step).
*/

import { spawnSync } from "node:child_process";
Expand Down Expand Up @@ -700,7 +703,8 @@ function emitCppBind({ n, cfg, sources, o, dirStamp }: Ctx): void {
o.rustInputs.push(outputRs);
}

function emitJsModules({ n, cfg, sources, o, dirStamp }: Ctx): void {
/** Exported for test/internal/build-codegen-header-tracking.test.ts. */
export function emitJsModules({ n, cfg, sources, o, dirStamp }: Ctx): void {
const script = resolve(cfg.cwd, "src", "codegen", "bundle-modules.ts");

// InternalModuleRegistry.cpp is read by the script (for a sanity check).
Expand All @@ -713,6 +717,10 @@ function emitJsModules({ n, cfg, sources, o, dirStamp }: Ctx): void {
const outputs = [
resolve(cfg.codegenDir, "WebCoreJSBuiltins.cpp"),
resolve(cfg.codegenDir, "WebCoreJSBuiltins.h"),
// Included by BunBuiltinNames.h, which root-pch.h reaches: the PCH can
// only follow a rerun of this step through its depfile if the header is
// a declared output (see the PCH step in bun.ts).
resolve(cfg.codegenDir, "BunBuiltinNames+extras.h"),
resolve(cfg.codegenDir, "InternalModuleRegistryConstants.h"),
resolve(cfg.codegenDir, "InternalModuleRegistry+createInternalModuleById.h"),
resolve(cfg.codegenDir, "InternalModuleRegistry+enum.h"),
Expand Down
89 changes: 79 additions & 10 deletions scripts/build/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import { mkdirSync } from "node:fs";
import { availableParallelism } from "node:os";
import { basename, dirname, extname, relative, resolve } from "node:path";
import { basename, dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
import type { Config } from "./config.ts";
import { assert } from "./error.ts";
import { writeIfChanged } from "./fs.ts";
Expand Down Expand Up @@ -200,7 +200,7 @@ export function registerCompileRules(n: Ninja, cfg: Config): void {
// ---------------------------------------------------------------------------

export interface CompileOpts {
/** Compiler flags (including -I, -D — caller assembles). */
/** Compiler flags (including -I, -D — caller assembles; -I via includeFlags()). */
flags: string[];
/** PCH to use (absolute path to .pch/.gch output). */
pch?: string;
Expand All @@ -221,14 +221,75 @@ export interface CompileOpts {
* before first compile attempts to #include it".
*
* Use for codegen headers (declared ninja outputs with restat, so
* depfile tracking is exact). Dep outputs (lib*.a) go in
* implicitInputs instead — see above.
* depfile tracking is exact — provided the depfile spells them the way
* the outputs are declared; see includeFlags()). Dep outputs (lib*.a) go
* in implicitInputs instead — see above.
*/
orderOnlyInputs?: string[];
/** Job pool override. */
pool?: string;
}

/**
* `-I` flags for `dirs`. Directories inside buildDir are spelled
* buildDir-relative, exactly as ninja.ts spells the outputs declared there.
*
* This is what makes order-only + depfile tracking of codegen headers exact.
* The compiler records a header in the depfile as `<-I dir>/<name>`, and ninja
* matches depfile entries to declared outputs by string. With `-I<abs>/codegen`
* the compile depended on `<abs>/codegen/X.h` — a node no edge produces, which
* ninja stats once at startup — so a codegen rerun later in the same run went
* unnoticed and was picked up one build late; for the PCH that meant every TU
* failing against a PCH built from the old header. With `-Icodegen` the entry
* is the codegen edge's own output and the compile is re-dirtied (or
* restat-pruned) in the same run. ccache's CCACHE_BASEDIR rewriting happened
* to do this for the ccache'd rules, which is why `bun bd` only showed it on
* the pch rule; plain `ninja` or a host without ccache showed it on all of them.
*
* Directories outside buildDir stay as given: the headers found through them
* are never declared outputs (dep headers are tracked as implicit inputs —
* depHeaderSignal in bun.ts, fetchDepStamps in source.ts), and a relative
* spelling of the machine-shared cache dir would vary with the checkout's
* depth and split the ccache between worktrees.
*
* Every -I that compile()/pch() see must have come through here: they reject
* an absolute spelling of a build-dir directory.
*/
export function includeFlags(n: Ninja, dirs: string[]): string[] {
return dirs.map(dir => `-I${buildDirSpelling(n, dir) ?? dir}`);
}

/** `dir` as ninja.ts would spell an output in it, or undefined if it is not inside buildDir. */
function buildDirSpelling(n: Ninja, dir: string): string | undefined {
const rel = n.rel(dir);
if (rel === "") return ".";
if (isAbsolute(rel) || rel === ".." || rel.startsWith(`..${sep}`)) return undefined;
return rel;
}

/**
* The configure-time check behind includeFlags(): a depfile-bearing edge whose
* flags name a build-dir directory absolutely would track the generated
* headers in it one build late, silently. Only the attached `-I<dir>` form is
* emitted by this build (possibly quote()d as a whole), so that is what is
* inspected.
*/
function assertIncludesSpelledAsDeclared(n: Ninja, flags: string[], out: string): void {
for (const flag of flags) {
// A quote()d flag is '-I…' / "-I…" as a whole.
const bare = flag.startsWith("-") ? flag : flag.slice(1, -1);
if (!bare.startsWith("-I")) continue;
const dir = bare.slice("-I".length);
// Cheap prefix filter: ~1300 edges × ~40 absolute -I each; only the
// candidates pay for the exact containment check.
if (!dir.startsWith(n.buildDir)) continue;
const spelling = buildDirSpelling(n, dir);
assert(spelling === undefined, `${n.rel(out)}: include dir ${dir} is inside the build dir but spelled absolutely`, {
hint: `Pass it through includeFlags() (-I${spelling}) so the depfile entries for its headers are the declared outputs.`,
});
}
}

/**
* Compile a C++ source file. Returns absolute path to the .o output.
*
Expand Down Expand Up @@ -265,7 +326,7 @@ export function nasm(
n: Ninja,
cfg: Config,
src: string,
opts: { flags: string[]; orderOnlyInputs?: string[] },
opts: Pick<CompileOpts, "flags" | "implicitInputs" | "orderOnlyInputs">,
): string {
assert(extname(src) === ".asm", `nasm() expects .asm source, got: ${src}`);
assert(cfg.nasm !== undefined, "nasm not found in toolchain", {
Expand All @@ -275,19 +336,22 @@ export function nasm(
: "Install nasm from your distro (apt/dnf/brew install nasm) or https://nasm.us",
});
const out = objectPath(cfg, src);
n.build({
const node: BuildNode = {
outputs: [out],
rule: "nasm",
inputs: [resolve(cfg.cwd, src)],
orderOnlyInputs: [objectDirStamp(cfg), ...(opts.orderOnlyInputs ?? [])],
vars: { nasmflags: opts.flags.join(" ") },
});
};
if (opts.implicitInputs !== undefined && opts.implicitInputs.length > 0) node.implicitInputs = opts.implicitInputs;
n.build(node);
return out;
}

function compile(n: Ninja, cfg: Config, src: string, opts: CompileOpts, lang: "cxx" | "cc"): string {
const absSrc = resolve(cfg.cwd, src);
const out = objectPath(cfg, src);
assertIncludesSpelledAsDeclared(n, opts.flags, out);

const rule = opts.pch !== undefined && lang === "cxx" ? "cxx_pch" : lang;
const flagVar = lang === "cxx" ? "cxxflags" : "cflags";
Expand Down Expand Up @@ -372,9 +436,13 @@ export function pch(
*/
implicitInputs?: string[];
/**
* Must exist before PCH compiles; changes don't invalidate it.
* Codegen outputs go here — they only change when inputs change,
* and inputs don't change mid-build.
* Must exist before PCH compiles; changes don't invalidate it directly.
* Codegen outputs go here: the depfile names the ones root-pch.h
* actually reaches, and because `flags` spells the codegen dir the way
* those outputs are declared (includeFlags()), a codegen rerun in the
* same ninja run re-dirties the PCH through the depfile. (This is the
* opposite situation from implicitInputs above: codegen headers are
* declared outputs, dep headers are undeclared side effects.)
*/
orderOnlyInputs?: string[];
},
Expand All @@ -384,6 +452,7 @@ export function pch(
const wrapperHeader = resolve(pchDir, `${basename(header)}.hxx`);
const stubCxx = resolve(pchDir, `${basename(header)}.hxx.cxx`);
const out = resolve(pchDir, `${basename(header)}.hxx.pch`);
assertIncludesSpelledAsDeclared(n, opts.flags, out);
// clang-cl /Yc compiles the stub source AND emits a PCH in one invocation,
// so it always writes a side-effect .obj. Unlike MSVC, clang's PCH is a
// serialized AST (not a partial object file), so consumers don't need this
Expand Down
Loading