#!/usr/bin/env bash # Turn the staging directory into a disk image (boot contract v1): # * a raw file of IMAGE_MIB MiB, # * a GPT partition table (sfdisk) with one partition at sector 2048, # * a FAT32 file system in it (mkfs.vfat), filled with mtools. # mtools (mmd/mcopy) write straight into the image file, so no root and no # loop-mounting is needed. This is what the kernel's build.rs does. # # Usage: scripts/mkimage.sh STAGING IMAGE MIB LABEL "bin order..." # The /bin files are copied in the given order (same as the kernel's # build.rs), then any other file in STAGING/bin. set -euo pipefail STAGING=$1 IMAGE=$2 MIB=$3 LABEL=$4 ORDER=$5 PATH=$PATH:/usr/sbin:/sbin export MTOOLS_SKIP_CHECK=1 SECTORS=$((MIB * 1024 * 1024 / 512)) START=2048 PART_SECTORS=$((SECTORS - 2 * START)) # 1 MiB free at the end for the backup GPT PART=$IMAGE.part rm -f "$PART" "$IMAGE" # 1. The FAT32 file system as its own file first. -s 1: one sector per # cluster (FAT32 needs >= 65525 clusters). -i: a fixed volume serial # number, so two builds of the same tree give the same bytes. mkfs.vfat -F 32 -s 1 -n "$LABEL" -i 466f6e64 -C "$PART" $((PART_SECTORS / 2)) >/dev/null # Top-level entries (everything except bin/) in sorted order... for entry in $(cd "$STAGING" && ls -A | LC_ALL=C sort); do [ "$entry" = bin ] && continue mcopy -s -i "$PART" "$STAGING/$entry" ::/ done # ...then the programs. mmd -i "$PART" ::/bin done_list=" " for p in $ORDER; do [ -f "$STAGING/bin/$p" ] || { echo "[mkimage] missing $STAGING/bin/$p"; exit 1; } mcopy -i "$PART" "$STAGING/bin/$p" "::/bin/$p" done_list+="$p " done for f in $(cd "$STAGING/bin" && ls | LC_ALL=C sort); do case "$done_list" in *" $f "*) ;; *) mcopy -i "$PART" "$STAGING/bin/$f" "::/bin/$f" ;; esac done # 2. The whole disk: zeros + GPT, then the FAT32 file system in the partition. truncate -s $((SECTORS * 512)) "$IMAGE" printf 'label: gpt\nstart=%d, size=%d, type=EBD0A0A2-B9E5-4433-87C0-68B6B72699C7, name="fat32"\n' \ $START $PART_SECTORS | sfdisk --quiet "$IMAGE" dd if="$PART" of="$IMAGE" bs=512 seek=$START conv=notrunc status=none rm -f "$PART" echo "[mkimage] $IMAGE: $MIB MiB, GPT + FAT32 '$LABEL', $(ls "$STAGING/bin" | wc -l) programs in /bin"