# Makefile: builds everything; nothing else does. See AGENTS.md section 4.
#
#   make                         the whole build: the formatter over the
#                                sources, then `make build`
#   make build                   whatever below is out of date
#   make test                    host tests and, on macOS, guest tests
#
# For Garden itself. One app's binary, from its source, is tools/build-app.sh's
# (AGENTS.md section 4), which runs none of this and builds with what the
# whole build wrote for it in _build/app.env.
#
#   _build/sv                host supervisor, a static aarch64 Linux binary
#                            (_build/ because sv/ is the source directory)
#   _build/apps/<name>.bin   flat cell binaries: the cells the system runs
#   _build/tests/<name>.bin  and the tests, benchmarks and demos
#   _build/initramfs.cpio    sv as /init plus the binaries: the Garden image's
#                            root file system (macOS only, see below)
#   _build/loader.cpio       sv as /init alone: the root file system of a
#                            Garden.app that runs by itself
#   _build/Garden.app        the Mac's programs in one app bundle (macOS
#                            only): vzrun, the Virtualization.framework
#                            runner, which is the application, as GardenVM,
#                            garden, and lang for a Garden.app by itself;
#                            _build/vzrun and _build/garden link to two
#
# sv and the binaries build anywhere with clang, lld and llvm-objcopy (Homebrew
# LLVM on macOS): sv includes no host headers. The kernel they boot on is
# fetched from the pin in linux/package. Intermediates go to _build/.
#
# Every object lists the headers it read (-MMD) and this file, so that a
# changed header or flag rebuilds what used it. `make -j` is safe.
#
# GNU make 4 or later (AGENTS.md section 5). macOS ships 3.81, which compares
# file times in whole seconds: a source edited in the second its binary was
# built is not rebuilt, and nothing says so. Refused, then.
ifneq ($(filter 3.%,$(MAKE_VERSION)),)
$(error Makefile: this is GNU make $(MAKE_VERSION), which misses an edit made in the second of a build: use GNU make 4 or later (brew install make, then gmake, or put /opt/homebrew/opt/make/libexec/gnubin first in PATH))
endif
# An app's binary is not a goal. The rules that make one are the whole build's,
# with the compiler's tests before them, and several makes of one at
# once run those tests in one directory, where they fail each other.
# tools/build-app.sh is the one way to build one app. Refused, then.
ifneq ($(filter _build/apps/% _build/tests/% _build/programs/% _build/web/apps/% _build/web/tests/% _build/web/programs/%,$(MAKECMDGOALS)),)
$(error Makefile: an app's binary is not a goal: tools/build-app.sh builds one app, from apps/<name>.c, tests/<name>.c, <namespace>.main, and make with no goal builds everything (AGENTS.md section 4))
endif

.DEFAULT_GOAL := all
.DELETE_ON_ERROR:
.SUFFIXES:
MAKEFLAGS += -r

Q = $(if $(filter 1,$(V)),,@)

# ---- the target ------------------------------------------------------------
# TARGET names the host Garden is built for: what its cells' machine code
# may use, and what is built beside sv and the cells.
#
#   macos  the Garden image under vzrun on an Apple silicon Mac: the kernel,
#          the initramfs and Garden.app. Cells for ARMv8.2 with half-precision
#          floats, the dot product, RCpc and crypto, which the Mac has and
#          the Pi 5's Cortex-A76 too. Built in _build.
#   web    a browser tab, on unkernel (host/web): sv, the launcher, the
#          cells and the initramfs the page boots. Cells for ARMv8.0 with
#          crypto, CRC32 and LSE, which is what unkernel's CPU runs. Built
#          in _build/web.
#
# A target builds in a directory of its own, B, so that one checkout holds
# both and a build of one leaves the other's objects as they were. The
# default target's is _build itself, the path run.sh, the tools and the
# documents name. The scripts make runs take the directory from
# GARDEN_BUILD. sv is one source for every host: it finds what a host
# offers when it runs (sv/port.c, sv/gpu.c).
#
# CELL_ISA says CELL_MARCH again as the bits of AT_HWCAP (Linux arm64 UAPI,
# asm/hwcap.h) a host must have for it, the word every binary carries and
# sv holds a start to (cell/sys.h, SYS_BINARY_ISA): the two change together.
#   0x1fb     FP 0, ASIMD 1, AES 3, PMULL 4, SHA1 5, SHA2 6, CRC32 7,
#             ATOMICS 8 (LSE)
#   0x1097fb  and FPHP 9, ASIMDHP 10 (fp16), ASIMDRDM 12 (ARMv8.1's, which
#             armv8.2-a turns on), LRCPC 15 (rcpc), ASIMDDP 20 (dotprod)
TARGET ?= macos
ifeq ($(TARGET),macos)
B := _build
CELL_MARCH := armv8.2-a+fp16+dotprod+rcpc+crypto
CELL_ISA := 0x1097fb
else ifeq ($(TARGET),web)
B := _build/web
CELL_MARCH := armv8-a+crypto+crc+lse
CELL_ISA := 0x1fb
else
$(error Makefile: TARGET=$(TARGET): not a target (macos, web))
endif
export GARDEN_BUILD := $(B)
# The app language's compiler is a Mac tool and one for every target, in
# _build: it finds the tree's prelude beside itself (lang/main.c, beside).

ifeq ($(shell uname -s),Darwin)
# Apple's clang has no lld and no bare-metal aarch64 target: use Homebrew LLVM.
LLVM_BIN := /opt/homebrew/opt/llvm/bin
ifeq ($(wildcard $(LLVM_BIN)/clang),)
$(error Makefile: $(LLVM_BIN)/clang not found (brew install llvm))
endif
CC := $(LLVM_BIN)/clang
# The Mac tools and tests (HOST_FLAGS below) are built by the Mac's own
# clang. ASan maps 20 TiB at a process's start, which the kernel makes and
# frees as 164,000 map entries of 128 MiB unless the mapping asks for
# VM_FLAGS_4GB_CHUNK. Apple's ASan runtime asks. LLVM's asks on x86_64
# only, so a program Homebrew LLVM built pays 40 to 50 ms a run, and a
# build runs lang 450 times (docs/measurements/host-asan-start.md).
HOST_CC := xcrun clang
HOST_CC_CHECK := xcrun -f clang >/dev/null || { echo "Makefile: xcrun finds no clang (xcode-select --install)" >&2; exit 1; }
OBJCOPY := $(LLVM_BIN)/llvm-objcopy
NM := $(LLVM_BIN)/llvm-nm
READELF := $(LLVM_BIN)/llvm-readelf
CELL_LINKER := --ld-path=/opt/homebrew/opt/lld/bin/ld.lld
MACOS := 1
# The oldest macOS the programs run on, which the compilers are told
# and host/macos/Info.plist says: 27.0, where the custom virtio device the
# GPU ring is mapped through first is (docs/vzrun.md, Scope). Without it
# they are built for the Mac that builds them and no older one, by the
# point release. The Dawn package's objects are built for the Mac that
# made the package (deps/dawn/build.sh), which the linker says of each
# and the rule below says once. The programs list this file, so that a
# changed flag builds them again, as an object does.
MACOS_MIN := 27.0
else
CC := clang
HOST_CC := $(CC)
HOST_CC_CHECK := true
OBJCOPY := llvm-objcopy
NM := llvm-nm
READELF := llvm-readelf
CELL_LINKER := -fuse-ld=lld
MACOS :=
endif

# Flags from docs/project.md section 4 "Build". -fno-pic: the binaries are linked at a
# fixed address and sv is a static non-PIE executable; no GOT anywhere.
# -nostdlibinc: no host headers; only the compiler's own freestanding
# <stdint.h> and <stddef.h> are reachable.
COMMON := -std=c11 -ffreestanding -nostdlib -nostdlibinc -fno-builtin -fno-stack-protector -fno-pic -O2 -Wall -Wextra -Werror -I.
# The ISA every cell is compiled for is the target's (docs/m1.md 2.6),
# CELL_MARCH above. No fused multiply-add the compiler did not write, for
# the same result everywhere.
CELL_TARGET := --target=aarch64-unknown-none-elf -march=$(CELL_MARCH) -ffp-contract=off
SV_TARGET := --target=aarch64-linux-gnu
# A function or a variable of a cell's object in a section of its own, so
# that the link (APP_LD, --gc-sections) drops each one nothing reached from
# _start refers to: a binary holds the part of the runtime it uses, not
# every object whole (docs/measurements/gc-sections.md).
CELL_FLAGS := $(CELL_TARGET) $(COMMON) -ffunction-sections -fdata-sections
SV_FLAGS := $(SV_TARGET) $(COMMON)
# The Mac tools and tests: the host's compiler and libc, ASan and UBSan on.
HOST_FLAGS := -std=c11 -O1 -g -Wall -Wextra -Werror -fsanitize=address,undefined -fno-sanitize-recover=all -I.

# compile: the recipe of every object, $(1) its flags.
define compile
@echo "cc $<"
@mkdir -p $(@D)
@$(CC) $(1) -MMD -MP -c $< -o $@
endef

# ---- the whole build -----------------------------------------------------
# The formatter rewrites sources, so the C one is not a node of the graph: it
# runs to its end before the make that reads the sources' times starts. The
# .g one needs the compiler of the app language, so it is a node of that
# make, format-g: after _build/lang, before the rules that read a .g
# file, and beside everything else, which waits for neither. Those rules
# have read the times of their .g sources by then: a source that format-g
# rewrote after its C was made, by a build that formats nothing, has lang
# run again by the next build, which finds the same C. Run when clang-format
# is there and the source is managed by git (.git as any file, not just a
# directory, to support worktrees). CI always checks formatting without
# writing sources. `make build` formats nothing: FORMAT_G is empty in it.
ifeq ($(CI),true)
FORMAT := true
FORMAT_FLAGS := --dry-run
else
FORMAT := [ -e .git ] && command -v clang-format >/dev/null
endif

.PHONY: all build test test-host format-g clean
all:
	@if $(FORMAT); then echo "format .c .h"; NO_GLANG_FMT=1 bash tools/format.sh $(FORMAT_FLAGS); fi
	@$(MAKE) --no-print-directory build FORMAT_G=format-g

format-g: _build/lang
	@if $(FORMAT); then echo "format .g"; NO_CLANG_FMT=1 bash tools/format.sh $(FORMAT_FLAGS); fi

clean:
ifneq ($(MACOS),)
	@set -eu; for dir in _build/linux/src _build/linux-build/src; do \
	  [ -d "$$dir" ] || continue; \
	  device=$$(/usr/bin/stat -f %d "$$dir"); \
	  parent_device=$$(/usr/bin/stat -f %d "$${dir%/*}"); \
	  if [ "$$device" != "$$parent_device" ]; then \
	    /usr/sbin/diskutil eject "$$dir"; \
	  fi; \
	done
endif
	rm -rf _build || trash _build

# ---- the app language ----------------------------------------------------
# lang/ is a Mac tool on the host's libc (docs/lang_plan.md 1), and its
# tests gate every app written in the language: a compiler that fails them
# builds none. The tests compile the C of every clean program with the cell
# flags, which they take from CELL_CC, against the runtime's headers.
# lib/sha256.c, the two hashes' (lang/hash.c), is on the SHA-256
# instructions, as in the store's tests below; lib/kv.c and lib/kvt.c are
# the source graph's store (lang/graph.c); lib/schema.c is a persistent
# root's schema, whose layout the emitter holds to C's (lang/croot.c);
# lib/civil.c is a day as a date, for the source graph's log.
LANG_LIB := lib/sha256.c lib/kv.c lib/kv_memory.c lib/kvt.c lib/schema.c lib/civil.c
LANG_LIB_H := lib/sha256.h lib/kv.h lib/kvt.h lib/schema.h lib/civil.h
LANG_SOURCES := $(sort $(wildcard lang/*.c)) $(LANG_LIB) $(wildcard lang/*.h) $(LANG_LIB_H)
_build/lang: $(LANG_SOURCES) Makefile
	@echo "build $@"
	@$(HOST_CC_CHECK)
	@mkdir -p $(@D)
	@$(HOST_CC) $(HOST_FLAGS) -march=armv8.2-a+crypto $(filter %.c,$^) -o $@

# Standalone compiler tests load the prelude and the device bindings.
G_BINDINGS := src/prelude.g src/std/display.g src/std/input.g src/std/clipboard/device.g
$(B)/lang.ok: _build/lang lang/test.sh $(shell find lang/test \( -type f -o -type d \) -not -path '*[ %]*') $(G_BINDINGS) \
    docs/lang.md docs/lang_research.md $(wildcard cell/*.h lib/*.h) Makefile | $(FORMAT_G)
	@echo "test _build/lang"
	@CELL_CC="$(APP_CC)" lang/test.sh
	@touch $@

# The source graph's model test (lang/test/graph_test.c, docs/source_plan.md
# L3c): the graph without lang's command line, under ASan and UBSan like
# the store's tests below, on two stores in memory.
GRAPH_TEST := $(filter-out lang/main.c lang/cmdgraph.c,$(sort $(wildcard lang/*.c))) lang/test/graph_test.c $(LANG_LIB)
$(B)/graphtest: $(GRAPH_TEST) $(wildcard lang/*.h) $(LANG_LIB_H) Makefile
	@echo "build $@"
	@$(HOST_CC_CHECK)
	@mkdir -p $(@D)
	@$(HOST_CC) $(HOST_FLAGS) -march=armv8.2-a+crypto $(filter %.c,$^) -o $@

$(B)/graphtest.ok: $(B)/graphtest lang/test/source-pack-v2.hex
	@echo "test $<"
	@$<
	@touch $@

# The decimal numbers' test (lang/test/num_test.c): lang/num.c, which reads
# a decimal literal and writes a float constant's C by its own code,
# against the host's strtod, "%.17g" and fmod, under ASan and UBSan.
$(B)/numtest: lang/num.c lang/test/num_test.c lang/num.h Makefile
	@echo "build $@"
	@$(HOST_CC_CHECK)
	@mkdir -p $(@D)
	@$(HOST_CC) $(HOST_FLAGS) $(filter %.c,$^) -o $@

$(B)/numtest.ok: $(B)/numtest
	@echo "test $<"
	@$<
	@touch $@

# ---- the key-value store's tests -----------------------------------------
# lib/ is freestanding and compiles for the host too: the model tests of the
# store (docs/kv.md 6), the tree over it (docs/kvt.md 6), the sync
# between two trees (docs/kvts.md 6) and the walk over a persistent root's
# schema (docs/store.md) run under ASan and UBSan and gate every
# app: a library that fails one builds none. The tests are under lib/test/,
# out of what is built into the cell runtime. The tree's hash is built for
# the host's own SHA-2 instructions.
LIB_TESTS := $(B)/kvtest $(B)/kvttest $(B)/kvtstest $(B)/schematest
LIB_TESTS_OK := $(LIB_TESTS:%=%.ok)

$(B)/kvtest: lib/kv.c lib/kv_memory.c lib/test/kv_test.c
$(B)/kvttest: lib/kv.c lib/kv_memory.c lib/kvt.c lib/sha256.c lib/test/kvt_test.c
$(B)/kvtstest: lib/kv.c lib/kv_memory.c lib/kvt.c lib/kvts.c lib/sha256.c lib/test/kvts_test.c
$(B)/schematest: lib/schema.c lib/test/schema_test.c
$(B)/kvttest $(B)/kvtstest: HOST_FLAGS += -march=armv8.2-a+crypto
$(LIB_TESTS): $(wildcard lib/*.h) Makefile
	@echo "build $@"
	@$(HOST_CC_CHECK)
	@mkdir -p $(@D)
	@$(HOST_CC) $(HOST_FLAGS) $(filter %.c,$^) -o $@

$(LIB_TESTS_OK): %.ok: %
	@echo "test $<"
	@$<
	@touch $@

# ---- the object store's test ---------------------------------------------
# lib/ostore.c is the store of format version 6 (lib/ostore.h), which sv
# keeps its store with (sv/store.c embeds it). Its model test runs under
# ASan and UBSan, and a core that fails it builds no sv.
$(B)/storeverify: tools/verify-store.c lib/ostore.c lib/sha256.c lib/ostore.h lib/sha256.h Makefile
	@mkdir -p $(@D)
	@$(HOST_CC) $(HOST_FLAGS) -march=armv8.2-a+crypto $(filter %.c,$^) -o $@

$(B)/ostoretest: lib/ostore.c lib/sha256.c lib/test/ostore_test.c lib/ostore.h lib/sha256.h Makefile
	@echo "build $@"
	@$(HOST_CC_CHECK)
	@mkdir -p $(@D)
	@$(HOST_CC) $(HOST_FLAGS) -march=armv8.2-a+crypto $(filter %.c,$^) -o $@

$(B)/ostoretest.ok: $(B)/ostoretest
	@echo "test $<"
	@$<
	@touch $@

# ---- cell runtime --------------------------------------------------------
# The runtime is built with -mgeneral-regs-only (no FP/SIMD in the runtime,
# AGENTS.md section 5); apps are not, they may use SIMD. lib/ is code built
# into more than one program (docs/m4.md 3): the runtime takes the content
# address and the key-value store, built for the apps' side with the apps'
# flags, since the hash uses the vector registers, which the exception path
# never calls; cell/kv.c is the store's embedder (docs/kv.md 5).
CELL_C_OBJS := $(patsubst cell/%.c,$(B)/obj/cell/%.o,$(sort $(wildcard cell/*.c)))
CELL_S_OBJS := $(patsubst cell/%.S,$(B)/obj/cell/%.o,$(sort $(wildcard cell/*.S)))
CELL_LIB_OBJS := $(patsubst %,$(B)/obj/cell-lib/%.o,sha256 kv kvt kvts schema civil)
CELL_OBJS := $(CELL_C_OBJS) $(CELL_S_OBJS) $(CELL_LIB_OBJS)

$(CELL_C_OBJS): $(B)/obj/cell/%.o: cell/%.c Makefile
	$(call compile,$(CELL_FLAGS) -mgeneral-regs-only)
$(CELL_S_OBJS): $(B)/obj/cell/%.o: cell/%.S Makefile
	$(call compile,$(CELL_FLAGS) -mgeneral-regs-only)
# The binary's ISA word (cell/start.S). On start.o alone, and not in
# CELL_FLAGS, which the release compiler's package is pinned to
# (host/macos/package.mk, check-release-compiler).
CELL_ISA_FLAG := -DCELL_ISA=$(CELL_ISA)
$(B)/obj/cell/start.o: CELL_FLAGS += $(CELL_ISA_FLAG)
$(CELL_LIB_OBJS): $(B)/obj/cell-lib/%.o: lib/%.c Makefile
	$(call compile,$(CELL_FLAGS))

# ---- apps ----------------------------------------------------------------
# C cells and tests keep their source path under _build. Every G namespace
# that defines main builds its own .g.bin alongside the rest of the image.
C_APPS := $(patsubst %.c,%,$(sort $(wildcard apps/*.c tests/*.c)))
# The compiler discovers main functions in unformatted source too. GNU make
# remakes this include before it selects the binaries for an image or program.
SRC_TREE := $(shell find -L src -name '.*' -prune -o \( -type f -o -type d \) -not -path '*[ %]*' -print)
ifneq ($(filter build test quic-vectors release-sdk $(B)/initramfs.cpio $(B)/garden.cpio %.g.bin %.g.elf %.g.o %.g.c %.g.c.stamp,$(MAKECMDGOALS)),)
include $(B)/programs.mk
endif
$(B)/programs.mk: _build/lang tools/build-app.sh $(SRC_TREE)
	@tools/build-app.sh --list _build/lang src > $@.list
	@awk '{ sub(/\.bin$$/, "", $$2); print "SRC_G_APPS += " $$2; print "$(B)/obj/" $$2 ".c.stamp: private G_MAIN := " $$1 }' $@.list > $@.tmp
	@mv $@.tmp $@

include tests/quic/native.mk
G_APPS := $(SRC_G_APPS) $(QUIC_VECTOR_APPS)
ifeq ($(TARGET),web)
GRADIENT_FIXTURE := tests/fixtures/source-resource
G_APPS += tests/gpugradient.g
endif
APPS := $(C_APPS) $(G_APPS)
APP_BINS := $(APPS:%=$(B)/%.bin)

# What a binary is made with, each a variable that the rules below use and
# that tools/build-app.sh reads from the record further down, so that the
# two build one binary: the compiler of the app language and the root of the
# source tree it is given; the C compiler with an app's flags, which is
# `compile` with CELL_FLAGS; the link up to the objects, the runtime's
# first and the app's last, which keeps what _start reaches and drops the
# rest; the two tools after the link; and where _start must be, the first
# byte of the binary (docs/project.md: entry = CELL_RAM_IPA).
APP_LANG := _build/lang
APP_SRC := src
APP_CC := $(CC) $(CELL_FLAGS)
APP_LD := $(CC) $(CELL_TARGET) -nostdlib $(CELL_LINKER) -Wl,--gc-sections -T cell/cell.ld
APP_OBJS := $(CELL_OBJS)
APP_NM := $(NM)
APP_OBJCOPY := $(OBJCOPY)
APP_START := 0000000040000000
# What the script refuses to run after a change of: this file, the sources
# of the runtime and the compiler, and what the compiler's tests read
# beside them (_build/lang.ok).
APP_WATCH := Makefile tools/app-backend.c cell lib lang $(G_BINDINGS) docs/lang.md docs/lang_research.md
APP_BACKEND := $(B)/app-backend
APP_RECORD := APP_BACKEND APP_LANG APP_SRC APP_CC APP_LD APP_OBJS APP_NM APP_OBJCOPY APP_START APP_WATCH
# When this make began, for the record to say: a source saved while the
# build runs, after its object was made, is older than the record and
# newer than this.
APP_BEGAN := $(shell mkdir -p $(B) && touch $(B)/app.began)

$(C_APPS:%=$(B)/obj/%.o): $(B)/obj/%.o: %.c Makefile
	$(call compile,$(CELL_FLAGS))

# A program is its root and what the root reaches, and what a name reaches
# depends on every namespace from its own out to the root: a file added
# anywhere on the way can change it. So every program waits for the whole
# tree, every file and every directory, and lang reads it whole. The C is
# replaced only when it changed, behind a stamp: an edit in one app runs
# lang for every app, 13 ms each, and the C compiler and the
# linker for the apps whose C changed. What make cannot take as a
# prerequisite is left out: a path with a space, which it reads as two, or
# a "%", which the rule's pattern replaces, and a link to nothing, an
# editor's lock file. No namespace's file is any of them (the compiler
# refuses the first two by name), and the directory, which is listed,
# changes with each.

ifeq ($(TARGET),web)
# Compile the same revision-bound entry as the SDK fixture. The browser boots
# without a source service, so its image also supplies this public shader.
GRADIENT_TREE := $(B)/gradient-src
GRADIENT_SHADER := $(GRADIENT_FIXTURE)/shaders/day.wgsl
$(GRADIENT_TREE)/gradient.g: $(GRADIENT_FIXTURE)/gradient.g $(GRADIENT_SHADER) $(GRADIENT_FIXTURE)/slots.txt Makefile _build/lang
	@mkdir -p $(@D)
	@for path in src/prelude.g src/std src/std.g src/sys src/sys.g src/tests; do ln -sfn "$(CURDIR)/$$path" $(@D)/; done
	@awk -v sha="$$(shasum -a 256 $(GRADIENT_SHADER) | cut -d' ' -f1)" -v size="$$(wc -c < $(GRADIENT_SHADER))" \
	  '/^resource GRADIENT / { printf "%s = v1 \"%s\" %d\n", $$0, sha, size; next } { print }' $< > $@
	@_build/lang assets $(@D) gradient.main | cmp - $(GRADIENT_FIXTURE)/slots.txt
$(B)/obj/tests/gpugradient.g.c.stamp: $(GRADIENT_TREE)/gradient.g $(SRC_TREE)
$(B)/obj/tests/gpugradient.g.c.stamp: private G_MAIN := gradient.main
$(B)/obj/tests/gpugradient.g.c.stamp: private APP_SRC := $(GRADIENT_TREE)
endif

G_MAIN = $(subst /,.,$*).main
$(SRC_G_APPS:%=$(B)/obj/%.c.stamp): $(SRC_TREE)
$(G_APPS:%=$(B)/obj/%.c.stamp): $(B)/obj/%.g.c.stamp: $(APP_LANG) tools/build-app.sh | $(B)/lang.ok $(FORMAT_G)
	@echo "lang $(G_MAIN)"
	@mkdir -p $(@D)
	@tools/build-app.sh --emit $(APP_LANG) $(APP_SRC) $(G_MAIN) > $(@:.stamp=.tmp)
	@if cmp -s $(@:.stamp=.tmp) $(@:.stamp=); then rm $(@:.stamp=.tmp); else mv $(@:.stamp=.tmp) $(@:.stamp=); fi
	@touch $@

$(G_APPS:%=$(B)/obj/%.c): %: %.stamp ;

# The tree's check (lang/run.c, run_tree): every definition of src/
# resolves and is checked, the ones no program reaches too, and every
# function named main is one a build would not refuse, under src/sys,
# src/tests or neither. It is what
# docs/source.md 4 asks of the commit a ref points at, and until the graph
# holds the source, src/ is that commit. After the binaries among build's
# prerequisites: a program that does not check is said by its own build.
$(B)/src.ok: $(SRC_TREE) $(APP_LANG) | $(B)/lang.ok $(FORMAT_G)
	@echo "lang check $(APP_SRC)"
	@$(APP_LANG) check $(APP_SRC)
	@touch $@

# Acceptance 1 of docs/source.md 12, the mirror's round trip (lang/roundtrip.sh):
# src/ imported into an empty graph, exported byte for byte, and the export
# imported into a second empty graph for the same root.
$(B)/roundtrip.ok: $(SRC_TREE) $(APP_LANG) lang/roundtrip.sh | $(B)/lang.ok $(FORMAT_G)
	@echo "test the graph's round trip of $(APP_SRC)"
	@lang/roundtrip.sh $(APP_SRC)
	@touch $@

$(G_APPS:%=$(B)/obj/%.o): $(B)/obj/%.o: $(B)/obj/%.c Makefile
	$(call compile,$(CELL_FLAGS))

$(APPS:%=$(B)/elf_app/%.elf): $(B)/elf_app/%.elf: $(B)/obj/%.o $(APP_OBJS) cell/cell.ld | $(LIB_TESTS_OK)
	@echo "link $@"
	@mkdir -p $(@D)
	@$(APP_LD) $(APP_OBJS) $< $(APP_MORE) -o $@
	@start="$$($(APP_NM) $@ | awk '$$3 == "_start" { print $$1 }')"; \
	if [ "$$start" != "$(APP_START)" ]; then \
	  echo "Makefile: $@: _start is at 0x$$start, not 0x$(APP_START)" >&2; \
	  exit 1; \
	fi

$(B)/obj/tests/blob/clock.o: tests/blob/clock.c Makefile
	$(call compile,$(CELL_FLAGS))
$(B)/elf_app/tests/blobworker.g.elf: $(B)/obj/tests/blob/clock.o
$(B)/elf_app/tests/blobworker.g.elf: private APP_MORE := -Wl,--wrap=hcall $(B)/obj/tests/blob/clock.o

include tests/quic/echo.mk

# ---- the source cell ------------------------------------------------------
# apps/source (docs/source.md 6) links more than the
# runtime: lang's library, the compiler and the source graph, built for a
# cell with an app's flags, and lang/cell/libc.c, the few functions of a C
# library they call, whose headers stand in for a system's. lang/main.c,
# lang/cmdgraph.c, lang/dir.c and lang/mirror.c are the Mac's command line
# and file system, and are not among them. tools/build-app.sh does not
# build it: make does, as it builds init.
SOURCE_LANG := $(filter-out lang/main.c lang/cmdgraph.c lang/dir.c lang/mirror.c,$(sort $(wildcard lang/*.c)))
SOURCE_OBJS := $(SOURCE_LANG:lang/%.c=$(B)/obj/cell-lang/%.o) $(B)/obj/cell-lang/libc.o
SOURCE_INCLUDE := -Ilang/cell/libc

$(SOURCE_LANG:lang/%.c=$(B)/obj/cell-lang/%.o): $(B)/obj/cell-lang/%.o: lang/%.c Makefile
	$(call compile,$(CELL_FLAGS) $(SOURCE_INCLUDE))
$(B)/obj/cell-lang/libc.o: lang/cell/libc.c Makefile
	$(call compile,$(CELL_FLAGS) $(SOURCE_INCLUDE))
$(B)/obj/apps/source.o: CELL_FLAGS += $(SOURCE_INCLUDE)
$(B)/elf_app/apps/source.elf: $(SOURCE_OBJS)
$(B)/elf_app/apps/source.elf: APP_MORE := $(SOURCE_OBJS)

include deps/quic/build.mk

$(APP_BINS): $(B)/%.bin: $(B)/elf_app/%.elf
	@echo "objcopy $@"
	@mkdir -p $(@D)
	@$(APP_OBJCOPY) -O binary $< $@

# Every program the compiler's tests compiled (lang/test.sh), linked with the
# runtime as an app is: C that needs what the runtime lacks, such as the
# memmove clang calls on its own for a copy it cannot prove apart, fails
# here and not in the first app to meet it. Then the runtime whole, with
# the first of them and without --gc-sections: lld names nothing missing
# that only a section it dropped needs, so a part of the runtime no app
# uses yet fails here and not in the first app to use it. A target of its
# own, so that a change of the runtime relinks these, a second or two,
# without running the tests again. Here, after the variables its
# prerequisites name.
$(B)/lang-link.ok: $(B)/lang.ok $(APP_OBJS) cell/cell.ld
	@echo "link the programs of lang/test.sh"
	@while read -r o; do \
	  $(APP_LD) $(APP_OBJS) "$$o" -o "$${o%.o}.elf" || { \
	    echo "Makefile: $$o and the runtime do not link: lld names what is missing and who needs it" >&2; \
	    exit 1; \
	  }; \
	done < $(B)/lang-test/objects
	@o="$$(head -n 1 $(B)/lang-test/objects)"; \
	$(APP_LD) -Wl,--no-gc-sections $(APP_OBJS) "$$o" -o $(B)/lang-test/runtime-whole.elf || { \
	  echo "Makefile: the runtime, linked whole, does not link: lld names what is missing and who needs it" >&2; \
	  exit 1; \
	}
	@touch $@

# The record tools/build-app.sh builds one app with: the variables above as
# a shell's assignments, so that no flag is written in the script. Every
# build writes it, after the compiler and its tests, the store's tests and
# the runtime's objects: it is newer than all of them exactly when a whole
# build got that far, and beside it _build/app.since has the time that
# build began, which every source it built from is older than. The script
# refuses to run when either does not hold: a flag changed here or a
# source of the runtime edited, also while the build ran, and no make
# since. Phony,
# because what it says can change with no prerequisite's time, when a file
# leaves cell/, and so that a make always cures the script's refusal. No
# value holds a quote.
$(B)/app-backend: tools/app-backend.c cell/build.h Makefile
	@mkdir -p $(@D)
	@$(HOST_CC) -std=c11 -O2 -Wall -Wextra -Werror $(if $(MACOS),-mmacosx-version-min=$(MACOS_MIN)) -I. $< -o $@

.PHONY: $(B)/app.env
$(B)/app.env: $(B)/app-backend $(APP_LANG) $(B)/lang.ok $(B)/lang-link.ok $(LIB_TESTS_OK) $(APP_OBJS)
	@{ \
	  echo "# $@: what tools/build-app.sh builds an app with. Written by make: the Makefile is the source."; \
	  $(foreach v,$(APP_RECORD),echo "$(v)='$($(v))'";) \
	} > $@.tmp
	@cp -p $(B)/app.began $(B)/app.since
	@mv $@.tmp $@

# ---- sv ------------------------------------------------------------------
# sv takes from lib/ what it uses: the content address and the object
# store's core. The key-value store, lib/kv.c, is the cells' and the Mac
# test's; sv never reads a store a cell keeps (docs/kv.md 5).
SV_C_OBJS := $(patsubst %.c,$(B)/obj/%.o,$(sort $(wildcard sv/*.c) linux/dhcp.c))
SV_S_OBJS := $(patsubst %.S,$(B)/obj/%.o,$(sort $(wildcard sv/*.S)))
SV_OBJS := $(SV_C_OBJS) $(SV_S_OBJS) $(B)/obj/lib/sha256.o $(B)/obj/lib/ostore.o

# Resolve calls within the core first. For each remaining symbol, ask the
# guest compiler whether its address is declared with only sv/host.h in scope.
SV_CORE := sv/cap.c
SV_CORE_OBJS := $(patsubst %.c,$(B)/obj/%.o,$(SV_CORE))

$(B)/sv-core.ok: $(SV_CORE_OBJS) sv/host.h Makefile
	@$(CC) $(SV_TARGET) -nostdlib -static -fuse-ld=lld -Wl,-r $(SV_CORE_OBJS) -o $(B)/sv-core.o
	@$(NM) --undefined-only --just-symbol-name $(B)/sv-core.o > $(B)/sv-core.names
	@sed 's/.*/_Static_assert(sizeof(\&(&)) > 0, "host symbol");/' $(B)/sv-core.names > $(B)/sv-core.c
	@$(CC) $(SV_FLAGS) -include sv/host.h -fsyntax-only $(B)/sv-core.c
	@touch $@

$(B)/sv: $(B)/sv-core.ok

# The same core, linked to the sequential test host under ASan and UBSan.
$(B)/captest: $(SV_CORE) sv/test/host.c sv/test/cap_test.c sv/cap.h sv/host.h cell/sys.h Makefile
	@echo "build $@"
	@$(HOST_CC_CHECK)
	@mkdir -p $(@D)
	@$(HOST_CC) $(HOST_FLAGS) $(filter %.c,$^) -o $@

$(B)/captest.ok: $(B)/captest
	@echo "test $<"
	@$<
	@touch $@

$(B)/sv: $(B)/captest.ok

$(SV_C_OBJS) $(B)/obj/lib/sha256.o $(B)/obj/lib/ostore.o: $(B)/obj/%.o: %.c Makefile
	$(call compile,$(SV_FLAGS))
$(SV_S_OBJS): $(B)/obj/%.o: %.S Makefile
	$(call compile,$(SV_FLAGS))

# Static, non-PIE, no interpreter. --no-pie is lld's default, spelled out
# because clang's own -no-pie trips -Wunused-command-line-argument.
# Acceptance 4: static, no undefined symbols, no interpreter.
$(B)/sv: $(SV_OBJS) $(B)/ostoretest.ok
	@echo "link $@"
	@$(CC) $(SV_TARGET) -nostdlib -static -fuse-ld=lld -Wl,--no-pie $(SV_OBJS) -o $@
	@printf 'GRDNSV01\003\000\000\000\006\000\000\000' >> $@
	@if $(READELF) -l $@ | grep -q -E 'INTERP|DYNAMIC'; then \
	  echo "Makefile: sv has an interpreter or dynamic section" >&2; \
	  exit 1; \
	fi
	@undef="$$($(NM) -u $@)"; \
	if [ -n "$$undef" ]; then \
	  echo "Makefile: sv has undefined symbols:" >&2; \
	  echo "$$undef" >&2; \
	  exit 1; \
	fi

-include $(patsubst %.o,%.d,$(CELL_OBJS) $(SV_OBJS) $(APPS:%=$(B)/obj/%.o) $(SOURCE_OBJS))

# Count source lines reachable in sv (docs/sv_plan.md, A0).
.PHONY: sv-reachable
sv-reachable:
	@python3 tools/sv-reachable.py $(patsubst $(B)/obj/%.o,%.c,$(filter-out $(SV_S_OBJS),$(SV_OBJS))) \
	    $(patsubst $(B)/obj/%.o,%.S,$(SV_S_OBJS)) -- $(CC) $(SV_FLAGS)

# Immutable, public assets distributed with the system. Private working-tree
# resources are served by the source cell under its filesystem grant.
SYSTEM_ASSETS := src/std/text/inter.ttf src/sys/noto-emoji.ttf
ifeq ($(TARGET),web)
SYSTEM_ASSETS += $(GRADIENT_FIXTURE)/shaders/day.wgsl
endif
$(B)/system-assets: $(SYSTEM_ASSETS) tools/system-assets.py Makefile
	@mkdir -p $(@D)
	@python3 tools/system-assets.py $@.tmp $(SYSTEM_ASSETS)
	@mv $@.tmp $@

test: test-host
test-host: $(B)/lang.ok $(B)/lang-link.ok $(LIB_TESTS_OK) $(B)/src.ok \
    $(B)/graphtest.ok $(B)/numtest.ok $(B)/roundtrip.ok $(B)/ostoretest.ok
build: $(B)/app.env $(APP_BINS) test-host $(B)/sv

# The trusted Linux launcher executes the flat Garden binary after confinement.
$(B)/cell-launcher: linux/cell/entry.S linux/cell/launcher.c cell/task.h cell/sys.h sv/linux.h Makefile
	@mkdir -p $(B)
	@$(CC) $(SV_FLAGS) -static -fuse-ld=lld -Wl,--no-pie linux/cell/entry.S linux/cell/launcher.c -o $@

# ---- the Garden image: initramfs and the VZ runner (macOS only) ------------
ifeq ($(TARGET),web)
# The initramfs the page boots (host/web/mkcpio.sh): sv, the launcher and
# the cells. gen_init_cpio is the kernel build's, which the macos target makes.
build: $(B)/garden.cpio $(B)/resource-programs
$(B)/resource-programs: $(B)/garden.cpio
	@test -f $@ || host/web/mkcpio.sh > /dev/null
$(B)/garden.cpio: $(B)/system-assets $(B)/sv $(B)/cell-launcher $(APP_BINS) host/web/mkcpio.sh
	@echo "build $@"
	@host/web/mkcpio.sh > /dev/null
else ifeq ($(MACOS),)
build:
	@echo "Makefile: not macOS: skipping $(B)/initramfs.cpio and $(B)/Garden.app"
else
build: $(B)/initramfs.cpio $(B)/loader.cpio $(B)/Garden.app.ok $(B)/vzrun $(B)/garden $(B)/store.img
test-host: $(B)/paste-shortcut.ok

quic-vectors: $(B)/initramfs.cpio $(B)/vzrun $(B)/store.img
test: quic-vectors $(B)/tests/hello.bin $(B)/app.env
	@python3 tests/float-integer.py
	@set -eu; log=$(B)/hello.log; \
	if ! ./run.sh incognito=1 $(B)/tests/hello.bin > "$$log" 2>&1; then cat "$$log"; exit 1; fi; \
	cat "$$log"; \
	if ! grep -q '^hello from cell[[:space:]]*$$' "$$log" || ! grep -q '^sync: ' "$$log" || \
	   ! grep -q '^batched: ' "$$log" || ! grep -q '^sv: cell 0: exit 0:' "$$log"; then \
	  echo "make test: hello did not report its greeting, timings and successful exit" >&2; exit 1; \
	fi

# Isolated AppKit pasteboard acceptance. The helper supplies and reads data
# in separate processes while the production adapter serves port frames.
.PHONY: test-clipboard-macos
test-clipboard-macos: $(B)/test-clipboard-port $(B)/test-clipboard-native
	@$(B)/test-clipboard-port $(B)/test-clipboard-native

$(B)/test-clipboard-native: tests/macos/clipboard.swift
	@mkdir -p $(B)
	@swiftc -parse-as-library -warnings-as-errors $< -o $@

$(B)/test-clipboard-port: host/macos/clipboard.swift tests/macos/clipboard-port.swift cell/clipboard.h
	@mkdir -p $(B)
	@swiftc -parse-as-library -warnings-as-errors -import-objc-header cell/clipboard.h $(filter %.swift,$^) -o $@

.PHONY: test-mirror-root-macos
test-mirror-root-macos: $(B)/test-mirror-root
	@$(B)/test-mirror-root test-mirror-root

CLI_ASSET_HEADERS := cell/assets.h cell/sys.h
CLI_ASSET_FLAGS := -import-objc-header cell/assets.h -Xcc -I.

$(B)/test-mirror-root: $(wildcard host/macos/cli/*.swift) tests/macos/mirror-root.swift $(CLI_ASSET_HEADERS)
	@mkdir -p $(B)
	@swiftc -D GARDEN_MIRROR_TEST -warnings-as-errors $(CLI_ASSET_FLAGS) $(filter %.swift,$^) -o $@

$(B)/paste-shortcut.ok: host/macos/keyboard.swift tests/macos/paste-shortcut.swift
	@mkdir -p $(B)
	@swiftc -warnings-as-errors $^ -o $(B)/paste-shortcut
	@$(B)/paste-shortcut
	@touch $@

# linux/build.sh makes the two prebuilts. Cache the verified archive by
# digest and extract either file on demand at the path the runner uses.
LINUX_URL := $(shell sed -n 's/^url=//p' linux/package)
LINUX_SUM := $(shell sed -n 's/^sha256=//p' linux/package)
LINUX_ARCHIVE := _build/deps/linux-$(LINUX_SUM).tar.xz

$(LINUX_ARCHIVE):
	@test -n "$(LINUX_URL)" && test -n "$(LINUX_SUM)"
	@echo "fetch $(LINUX_URL)"
	@mkdir -p $(@D)
	@set -eu; tmp=$$(mktemp "$@.XXXXXX"); trap 'rm -f "$$tmp"' EXIT; \
	  curl -fsSL --retry 2 --connect-timeout 20 --max-time 300 -o "$$tmp" "$(LINUX_URL)"; \
	  printf '%s  %s\n' "$(LINUX_SUM)" "$$tmp" | shasum -a 256 -c -; \
	  mv "$$tmp" "$@"

_build/linux/Image _build/linux/gen_init_cpio: _build/linux/%: linux/package $(LINUX_ARCHIVE)
	@mkdir -p $(@D)
	@set -eu; tmp=$$(mktemp "$@.XXXXXX"); trap 'rm -f "$$tmp"' EXIT; \
	  tar -xOJf "$(LINUX_ARCHIVE)" "$*" > "$$tmp"; \
	  test -s "$$tmp"; chmod 755 "$$tmp"; mv "$$tmp" "$@"

# /init is sv; the binaries are under /apps and /tests, as under _build;
# /garden is where sv mounts the virtio-fs share. /dev/console is static
# because init's console is opened
# before anything is mounted, by the kernel or, when it had none yet, by sv
# (sv/main.c, console_open); every other node comes from the devtmpfs
# sv mounts on /dev, since the kernel mounts none for an initramfs
# (docs/m1.md 1.2, docs/m2.md 8).
$(B)/build-grants: $(B)/sv $(B)/apps/init.bin $(B)/apps/source.bin
	@shasum -a 256 $^ | cut -d' ' -f1 | xxd -r -p > $@.tmp
	@test $$(wc -c < $@.tmp) -eq 96
	@mv $@.tmp $@

$(B)/initramfs.cpio: $(B)/system-assets $(B)/build-grants $(B)/sv $(B)/cell-launcher $(B)/src.ok $(APP_BINS) _build/linux/gen_init_cpio Makefile
	@echo "build $@"
	@{ \
	  echo "dir /dev 0755 0 0"; \
	  echo "nod /dev/console 0600 0 0 c 5 1"; \
	  echo "dir /garden 0755 0 0"; \
	  echo "dir /proc 0755 0 0"; \
	  printf '%s\n' $(sort $(APPS)) | awk -F/ '{ p=""; for (i=1; i<NF; i++) { p=p "/" $$i; if (!seen[p]++) print "dir " p " 0755 0 0" } }'; \
	  echo "file /cell $(B)/cell-launcher 0755 0 0"; \
	  echo "file /system-assets $(B)/system-assets 0444 0 0"; \
	  echo "file /build-grants $(B)/build-grants 0400 0 0"; \
	  echo "file /init $(B)/sv 0755 0 0"; \
	  for bin in $(sort $(APP_BINS)); do \
	    echo "file /$${bin#$(B)/} $$bin 0644 0 0"; \
	  done; \
	} > $(B)/initramfs.list
	@_build/linux/gen_init_cpio $(B)/initramfs.list > $@

# The loader: the initramfs of a Garden.app that runs by itself, which
# host/macos/package.sh puts in the bundle (docs/vzrun.md 9). sv as /init
# and nothing to run: with no image on the line sv boots the root the
# disk's boot space holds, whose sv it executes when that is not itself.
$(B)/loader.cpio: $(B)/system-assets $(B)/build-grants $(B)/sv $(B)/cell-launcher _build/linux/gen_init_cpio Makefile
	@echo "build $@"
	@{ \
	  echo "dir /dev 0755 0 0"; \
	  echo "nod /dev/console 0600 0 0 c 5 1"; \
	  echo "dir /proc 0755 0 0"; \
	  echo "file /cell $(B)/cell-launcher 0755 0 0"; \
	  echo "file /system-assets $(B)/system-assets 0444 0 0"; \
	  echo "file /build-grants $(B)/build-grants 0400 0 0"; \
	  echo "file /init $(B)/sv 0755 0 0"; \
	} > $(B)/loader.list
	@_build/linux/gen_init_cpio $(B)/loader.list > $@

SWIFTC := command -v swiftc >/dev/null || { echo "Makefile: swiftc not found (xcode-select --install)" >&2; exit 1; }

# vzrun links Dawn (docs/m7.md 2): a package of static libraries and headers
# that deps/dawn/build.sh makes when the pinned Dawn changes. It is fetched
# here, once, from the address in deps/dawn/package and checked against the
# SHA-256 beside it, into a directory named by that sum, so that another
# package is another directory and nothing is ever unpacked over a different
# one. Nothing of Dawn's own build runs in this one. host/macos/dawn.cc is
# the repository's only C++, since Dawn's wire server is a C++ class;
# host/macos/bridge.h is what Swift imports of it and of gpuring.c.
DAWN_URL := $(shell sed -n 's/^url=//p' deps/dawn/package)
DAWN_SUM := $(shell sed -n 's/^sha256=//p' deps/dawn/package)
DAWN := $(B)/deps/dawn-$(DAWN_SUM)
DAWN_FRAMEWORKS := -framework Metal -framework QuartzCore -framework IOSurface -framework IOKit -framework Foundation -framework Cocoa
# No prerequisite: the directory is named by the sum, so the target is new
# exactly when the package is, and an edit of deps/dawn/package that leaves
# the sum alone fetches nothing. package.ok is made last, so a fetch or an
# unpack that was cut short is done again. curl gives up on a server that
# does not answer in 20 s or a download that takes more than 5 minutes.
$(DAWN)/package.ok:
	@[ -n "$(DAWN_URL)" ] && [ -n "$(DAWN_SUM)" ] || { echo "Makefile: deps/dawn/package names no url= or no sha256=" >&2; exit 1; }
	@echo "fetch $(DAWN_URL)"
	@mkdir -p $(B)/deps
	@curl -fsSL --connect-timeout 20 --max-time 300 -o $(B)/deps/dawn.part "$(DAWN_URL)" \
	  || { echo "Makefile: cannot fetch the Dawn package (deps/dawn/package; docs/m7.md 2)" >&2; rm -f $(B)/deps/dawn.part; exit 1; }
	@echo "$(DAWN_SUM)  $(B)/deps/dawn.part" | shasum -a 256 -c - >/dev/null \
	  || { echo "Makefile: the Dawn package fetched is not the one deps/dawn/package names" >&2; rm -f $(B)/deps/dawn.part; exit 1; }
	@mkdir -p $(DAWN)
	@tar -xJf $(B)/deps/dawn.part -C $(DAWN)
	@rm -f $(B)/deps/dawn.part
	@touch $@

# Garden.app (docs/vzrun.md 2): the Mac's programs in one app bundle,
# whose sources are host/macos/. vzrun is the application, the bundle's
# executable, so that garden boot can launch it through LaunchServices, the
# one way a window may take the front since macOS 14. Its file there is
# GardenVM, the name a list of processes shows. garden, which speaks
# the agent port and MCP (docs/m6.md 7), is beside it in Contents/MacOS,
# and so is lang, for a Garden.app by itself (below).
# _build/vzrun and _build/garden are links to the two, for run.sh, a boot
# by hand and every command line that names one. Each program is rebuilt
# only when its own source changed: swiftc takes seconds.
GARDEN_APP := $(B)/Garden.app
GARDEN_BIN := $(GARDEN_APP)/Contents/MacOS

# deps/dawn/package is vzrun's prerequisite, not the fetch's: when it names
# another package, one fetched before or not, vzrun is linked again against
# that one, three seconds and no download; package.ok's time alone would
# leave a vzrun of the other package standing.
$(GARDEN_BIN)/GardenVM: $(wildcard host/macos/*.swift) $(wildcard host/macos/*.cc) $(wildcard host/macos/*.h) host/macos/gpuring.c cell/gpu.h cell/clipboard.h cell/build.h deps/dawn/package $(DAWN)/package.ok Makefile
	@echo "build $@"
	@$(SWIFTC)
	@mkdir -p $(GARDEN_BIN) $(B)/obj/vzrun
	@xcrun clang -std=c11 -O2 -Wall -Wextra -Werror -mmacosx-version-min=$(MACOS_MIN) \
	  -c host/macos/gpuring.c -o $(B)/obj/vzrun/gpuring.o
	@xcrun clang++ -std=c++20 -O2 -fno-exceptions -fno-rtti -Wall -Wextra -Werror -mmacosx-version-min=$(MACOS_MIN) \
	  -I$(DAWN)/include -I. -c host/macos/dawn.cc -o $(B)/obj/vzrun/dawn.o
	@swiftc -O -target arm64-apple-macos$(MACOS_MIN) host/macos/*.swift -import-objc-header host/macos/bridge.h \
	  $(B)/obj/vzrun/gpuring.o $(B)/obj/vzrun/dawn.o \
	  $(DAWN)/lib/libdawn_wire.a $(DAWN)/lib/libwebgpu_dawn.a -lc++ $(DAWN_FRAMEWORKS) \
	  -o $@ 2> $(B)/obj/vzrun/link.err; status=$$?; \
	  grep -v "was built for newer 'macOS' version" $(B)/obj/vzrun/link.err >&2; \
	  newer=$$(grep -c "was built for newer 'macOS' version" $(B)/obj/vzrun/link.err); \
	  [ "$$newer" = 0 ] || echo "Makefile: $$newer objects of the Dawn package are built for a newer macOS than $(MACOS_MIN), which the programs are built for (deps/dawn/build.sh)" >&2; \
	  exit $$status

# The clipboard VM fixture has the same window and device adapter. Only this
# private bundle can receive test key events or see a named test pasteboard.
$(B)/ClipboardTest.app.ok: $(B)/Garden.app.ok tests/macos/clipboard-window.swift
	@ditto $(GARDEN_APP) $(B)/ClipboardTest.app
	@swiftc -O -warnings-as-errors -target arm64-apple-macos$(MACOS_MIN) -D GARDEN_CLIPBOARD_TEST \
	  host/macos/*.swift tests/macos/clipboard-window.swift -import-objc-header host/macos/bridge.h \
	  $(B)/obj/vzrun/gpuring.o $(B)/obj/vzrun/dawn.o \
	  $(DAWN)/lib/libdawn_wire.a $(DAWN)/lib/libwebgpu_dawn.a -lc++ $(DAWN_FRAMEWORKS) \
	  -o $(B)/ClipboardTest.app/Contents/MacOS/GardenVM 2>$(B)/obj/vzrun/clipboard-test-link.err || \
	  { cat $(B)/obj/vzrun/clipboard-test-link.err >&2; exit 1; }
	@codesign --force --sign - --entitlements host/macos/Garden.entitlements $(B)/ClipboardTest.app
	@touch $@

# garden (docs/m6.md 7), host/macos/cli/: it needs no entitlement.
$(GARDEN_BIN)/garden: $(wildcard host/macos/cli/*.swift) $(CLI_ASSET_HEADERS) Makefile
	@echo "build $@"
	@$(SWIFTC)
	@mkdir -p $(GARDEN_BIN)
	@swiftc -O -target arm64-apple-macos$(MACOS_MIN) $(CLI_ASSET_FLAGS) host/macos/cli/*.swift -o $@

# lang for a Garden.app that runs by itself, which builds a program with it
# (docs/vzrun.md 9): _build/lang's sources, optimized and without the
# sanitizers, whose runtime is a library of the Mac's toolchain and of no
# Mac the app is given to. _build/lang, which the build and the compiler's
# tests run, is not this one; host/macos/package.sh checks that this one
# builds a program byte for byte as make does.
$(GARDEN_BIN)/lang: $(LANG_SOURCES) Makefile
	@echo "build $@"
	@$(HOST_CC_CHECK)
	@mkdir -p $(@D)
	@$(HOST_CC) -std=c11 -O2 -Wall -Wextra -Werror -I. -march=armv8.2-a+crypto -mmacosx-version-min=$(MACOS_MIN) $(filter %.c,$^) -o $@

# The app's icon: host/macos/Garden.icon, an Icon Composer document, which
# actool compiles into Assets.car, the icon macOS 26 and later draw, and
# Garden.icns, the one an older macOS would; the property list names both.
# actool is Xcode's and not the Command Line Tools': without it the bundle
# is built without the icon, which the signing says, and runs the same. An
# actool from before Xcode 26 does not read the document, and fails here.
# Its paths are whole: actool hands the work to a daemon, ibtoold, that
# lives two minutes past its last use and reads a relative path from the
# directory it was first started in, which is another checkout's when
# that one built last. It then wrote that checkout's icon into that
# checkout's bundle, after its signature, and nothing here.
GARDEN_ICON := $(if $(shell xcrun -f actool 2>/dev/null),$(GARDEN_APP)/Contents/Resources/Assets.car)
$(GARDEN_APP)/Contents/Resources/Assets.car: host/macos/Garden.icon/icon.json $(wildcard host/macos/Garden.icon/Assets/*) Makefile
	@echo "build $@"
	@mkdir -p $(@D) $(B)/obj
	@xcrun actool $(abspath host/macos/Garden.icon) --compile $(abspath $(@D)) --platform macosx \
	  --minimum-deployment-target $(MACOS_MIN) --app-icon Garden \
	  --output-partial-info-plist $(abspath $(B)/obj/icon.plist) >/dev/null \
	  || { echo "Makefile: actool could not compile host/macos/Garden.icon, an Icon Composer document, which Xcode 26 and later read" >&2; exit 1; }
	@[ -f $@ ] || { echo "Makefile: actool wrote no $@ from host/macos/Garden.icon: Xcode 26 or later" >&2; exit 1; }

# The skill for agents outside the app (docs/vzrun.md 9): host/macos/skill,
# a directory of plain files, copied into the bundle's resources, and beside
# them a link to the bundle's garden, which SKILL.md names. The app by
# itself's agent service links ~/.agents/skills/garden to the directory
# (host/macos/cli/skill.swift), so the text is the same wherever the app is.
GARDEN_SKILL := $(GARDEN_APP)/Contents/Resources/skill
$(GARDEN_SKILL)/SKILL.md: $(wildcard host/macos/skill/*) Makefile
	@echo "copy $(GARDEN_SKILL)"
	@rm -rf $(GARDEN_SKILL)
	@mkdir -p $(GARDEN_SKILL)
	@cp host/macos/skill/* $(GARDEN_SKILL)/
	@ln -s ../../MacOS/garden $(GARDEN_SKILL)/garden

# The bundle is signed whenever a program, its property list, the icon or
# the skill changed, since its signature seals them all: garden and lang first, as
# code nested in the bundle, then the bundle, which signs vzrun with the
# virtualization entitlement, without which the framework refuses. Ad hoc,
# which is enough on the Mac that built it; host/macos/notarize.sh signs a
# copy for other Macs. Signing rewrites the programs, so the rule's target
# is a file of its own, made last.
#
# The bundle's directory is then given this moment as its modification
# date. It would otherwise keep the date of its making for good, since a
# build changes files below it and never its own entries, and ditto and
# a zip carry that date on. macOS keeps the icon it draws for a running
# application, in the Dock and the application switcher, by the bundle's
# path and that date: a bundle put where an earlier build was, with the
# same date, is drawn with that build's icon, or with the placeholder
# when that build had none (docs/vzrun.md 9). The date is no part of
# what the signature seals.
# Only the runner's manifest can authorize a compiler port on a boot.
BUILD_IMAGES := $(GARDEN_APP)/Contents/Resources/build-images
$(BUILD_IMAGES): _build/linux/Image $(B)/initramfs.cpio
	@mkdir -p $(@D)
	@shasum -a 256 $^ | cut -d' ' -f1 | xxd -r -p > $@.tmp
	@test $$(wc -c < $@.tmp) -eq 64
	@mv $@.tmp $@

$(GARDEN_BIN)/app-backend: $(B)/app-backend
	@mkdir -p $(@D)
	@cp $< $@

# app.env is written on every build. Refreeze for a changed record, tool,
# library or emitted header without copying the toolchain on a no-op build.
$(B)/build-sdk.record: $(B)/app.env host/macos/build-sdk.py
	@python3 host/macos/build-sdk.py --record > $@.tmp
	@if cmp -s $@.tmp $@; then rm $@.tmp; else mv $@.tmp $@; fi

-include $(B)/build-sdk.d
$(B)/build-sdk/app.env: $(B)/build-sdk.record host/macos/build-sdk.py $(wildcard lang/*.c) Makefile
	@python3 host/macos/build-sdk.py $(B)/build-sdk

build: $(B)/build-sdk/app.env
$(B)/Garden.app.ok: $(BUILD_IMAGES) $(GARDEN_BIN)/app-backend $(GARDEN_BIN)/GardenVM $(GARDEN_BIN)/garden $(GARDEN_BIN)/lang host/macos/Info.plist host/macos/Garden.entitlements $(GARDEN_ICON) $(GARDEN_SKILL)/SKILL.md
	@echo "sign $(GARDEN_APP)$(if $(GARDEN_ICON),, (no actool, which is Xcode's: without its icon))"
	@cp host/macos/Info.plist $(GARDEN_APP)/Contents/Info.plist
	@codesign --force --sign - $(GARDEN_BIN)/garden
	@codesign --force --sign - $(GARDEN_BIN)/app-backend
	@codesign --force --sign - $(GARDEN_BIN)/lang
	@codesign --force --sign - --entitlements host/macos/Garden.entitlements $(GARDEN_APP)
	@touch $(GARDEN_APP)
	@ln -sfn Garden.app/Contents/MacOS/GardenVM $(B)/vzrun
	@ln -sfn Garden.app/Contents/MacOS/garden $(B)/garden
	@touch $@
# A link that is gone is made again, and only then: the signing above
# points both at the bundle it signed, and a link's own time is its
# program's, which the signing has just rewritten.
$(B)/vzrun: | $(B)/Garden.app.ok
	@ln -sfn Garden.app/Contents/MacOS/GardenVM $@
$(B)/garden: | $(B)/Garden.app.ok
	@ln -sfn Garden.app/Contents/MacOS/garden $@

include deps/llvm/build.mk
include host/macos/package.mk

# The store: a sparse disk image that vzrun attaches as a virtio-blk device
# and sv keeps its own layout on (docs/store.md): 16 GiB, 8192 extents of
# 2 MiB. Created empty once; sv formats
# it on the first boot; deleting it wipes the store.
$(B)/store.img:
	@echo "create $@ (sparse, 8192 extents of 2 MiB)"
	@dd if=/dev/zero of=$@ bs=2097152 count=0 seek=8192 2>/dev/null
endif

# ---- clangd --------------------------------------------------------------
# Update .clangd if installed and changed.
ifneq ($(wildcard .clangd),)
.PHONY: clangd
build: clangd
clangd:
	@mkdir -p $(B)
	@sed -e 's@$${REPO}@$(CURDIR)@g' -e 's@$${CC}@$(CC)@g' tools/clangd.yaml > $(B)/clangd.yaml
	@cmp --silent .clangd $(B)/clangd.yaml || { mv $(B)/clangd.yaml .clangd; echo "Updated .clangd"; }
endif

# Optional Noto COLRv1 rendering prototype. Keep its generated vector data
# out of the live source graph and the release image.
COLRV1_DIR := $(B)/colrv1
COLRV1_TREE := $(COLRV1_DIR)/src
COLRV1_PYTHON ?= python3

.PHONY: colrv1
colrv1: $(B)/tests/colrv1.g.bin

$(COLRV1_TREE)/tests/colrv1/fixture.g: tests/colrv1/prepare.py tools/ui-assets/colr/prepare_page.py tests/colrv1/paint.wgsl tests/colrv1/Noto-subset.ttf
	@mkdir -p $(@D)
	@$(COLRV1_PYTHON) tests/colrv1/prepare.py $@.tmp
	@mv $@.tmp $@

$(B)/tests/colrv1.g.bin: $(COLRV1_TREE)/tests/colrv1/fixture.g tests/colrv1/cell.g tests/noto/unpack.g $(SRC_TREE) $(B)/app.env _build/lang $(B)/app-backend
	@ln -sfn $(abspath src/prelude.g) $(COLRV1_TREE)/prelude.g
	@ln -sfn $(abspath src/std) $(COLRV1_TREE)/std
	@ln -sfn $(abspath src/sys.g) $(COLRV1_TREE)/sys.g
	@ln -sfn $(abspath src/sys) $(COLRV1_TREE)/sys
	@ln -sfn $(abspath tests/noto/unpack.g) $(COLRV1_TREE)/tests/fontfixture.g
	@ln -sfn $(abspath tests/colrv1/cell.g) $(COLRV1_TREE)/tests/colrv1.g
	@tools/build-app.sh --emit _build/lang $(COLRV1_TREE) tests.colrv1.main > $(COLRV1_DIR)/cell.c
	@$(B)/app-backend --direct $(B)/app.env $(COLRV1_DIR)/cell.c $(COLRV1_DIR)
	@mkdir -p $(@D)
	@mv $(COLRV1_DIR)/app.bin $@

# Full-face color-glyph acceptance. The immutable pages carry the original
# glyph IDs. Compile one test cell per page to bound the guest's working set.
NOTO := $(B)/noto
NOTO_PACK := tools/ui-assets/colr
$(NOTO)/pages/index.json: src/sys/noto-emoji.ttf $(NOTO_PACK)/pack.py $(NOTO_PACK)/prepare_page.py
	@$(COLRV1_PYTHON) $(NOTO_PACK)/pack.py $(@D)

# The inventory normally writes every page. A missing page can be rebuilt
# independently from the original glyph IDs, including under parallel make.
.PRECIOUS: $(NOTO)/pages/page-%.bin
$(NOTO)/pages/page-%.bin: | $(NOTO)/pages/index.json
	@$(COLRV1_PYTHON) $(NOTO_PACK)/pack.py $(@D) $(@F)

$(NOTO)/page-%/cell.bin: $(NOTO)/pages/page-%.bin $(NOTO)/pages/index.json tests/noto/cell.g tests/noto/unpack.g tests/noto/fixture.py tests/noto/paint.wgsl tools/build-app.sh $(SRC_TREE) $(B)/app.env _build/lang $(B)/app-backend
	@mkdir -p $(@D)/src/tests/noto
	@ln -sfn $(abspath src/prelude.g) $(@D)/src/prelude.g
	@ln -sfn $(abspath src/std) $(@D)/src/std
	@ln -sfn $(abspath src/sys.g) $(@D)/src/sys.g
	@ln -sfn $(abspath src/sys) $(@D)/src/sys
	@ln -sfn $(abspath tests/noto/unpack.g) $(@D)/src/tests/fontfixture.g
	@ln -sfn $(abspath tests/noto/cell.g) $(@D)/src/tests/noto.g
	@$(COLRV1_PYTHON) tests/noto/fixture.py $< $(@D)/src/tests/noto/fixture.g
	@tools/build-app.sh --emit _build/lang $(@D)/src tests.noto.main > $(@D)/cell.c
	@$(B)/app-backend --direct $(B)/app.env $(@D)/cell.c $(@D)
	@mv $(@D)/app.bin $@

.PHONY: noto
$(NOTO)/reference: tests/noto/reference.cc
	@mkdir -p $(@D)
	@$(CXX) -std=c++17 -O2 -Wall -Wextra -Werror $< $$(pkg-config --cflags --libs harfbuzz cairo) -o $@

noto: $(NOTO)/pages/index.json $(NOTO)/reference $(B)/app.env
	@goals=$$(python3 -c 'import json,sys; print(" ".join("$(NOTO)/pages/%s $(NOTO)/%s/cell.bin" % (p["file"], p["file"][:-4]) for p in json.load(open(sys.argv[1]))["pages"]))' "$<") || exit 1; \
	test -n "$$goals" || { echo "noto: empty page list in $<" >&2; exit 1; }; \
	$(MAKE) $$goals
