diff --git a/bin/omamobile b/bin/omamobile index b8ea30aeb..87b0867bd 100755 --- a/bin/omamobile +++ b/bin/omamobile @@ -61,6 +61,10 @@ UFS_RW_ALLOWED="boot_b init_boot_b vendor_boot_b vendor_kernel_boot_b dtbo_b use # backslashes, so other tools can read it too. Nothing in it is executed. load_device() { local file="$ROOT/device/$DEVICE/device.conf" line n=0 key p + if [[ ${FLAME_NATIVE:-0} == 1 ]]; then + [[ $DEVICE == flame ]] || die "FLAME_NATIVE=1 requires DEVICE=flame" + file="$ROOT/device/flame/native/device.conf" + fi local quoted='^([A-Z][A-Z0-9_]*)="([^"$`\\]*)"$' bare='^([A-Z][A-Z0-9_]*)=([^"$`\\'"'"'[:space:]]*)$' DEV_BOOT_METHOD=android-v4 # legacy descriptors omit it [[ $DEVICE =~ ^[a-z0-9]+$ ]] || die "DEVICE must be a codename, not '$DEVICE'" @@ -74,27 +78,37 @@ load_device() { die "$file:$n: not a KEY=value line" fi done < "$file" - [[ $DEV_BOOT_METHOD == android-v4 ]] \ - || die "$file: unsupported BOOT_METHOD=$DEV_BOOT_METHOD; this command supports only android-v4" - for key in CODENAME SOC PACKAGE DTB DTBO_SOURCE DTBO_BOARD_ID DTBO_BOARD_REV VENDOR_CMDLINE \ - VENDOR_PAGESIZE OS_VERSION OS_PATCH_LEVEL BOOT_IMAGES UFS_RW INITRAMFS_INIT PANEL_SIZE; do + local required="CODENAME SOC BOOT_IMAGES UFS_RW PANEL_SIZE" + case $DEV_BOOT_METHOD in + android-v4) + required+=" PACKAGE DTB DTBO_SOURCE DTBO_BOARD_ID DTBO_BOARD_REV VENDOR_CMDLINE VENDOR_PAGESIZE OS_VERSION OS_PATCH_LEVEL INITRAMFS_INIT" + ;; + uboot-ext4) + [[ ${DEV_CODENAME:-} == flame && ${DEV_SOC:-} == sm8150 ]] || die "$file: unsupported BOOT_METHOD=$DEV_BOOT_METHOD; uboot-ext4 is implemented only for flame" + [[ ${DEV_BOOT_IMAGES:-} == boot && ${DEV_UFS_RW:-} == 'boot_b userdata' ]] || die 'uboot-ext4 requires boot only and UFS_RW="boot_b userdata"' + ;; + *) die "$file: unsupported BOOT_METHOD=$DEV_BOOT_METHOD; use a supported device profile" ;; + esac + for key in $required; do p="DEV_$key" [[ -n ${!p:-} ]] || die "$file: $key is missing" done - # ABL picks the base DTB by /soc_id (gs101, gs201) or by /soc_compatible - # (zuma): a descriptor names exactly one of the two. - if [[ -n ${DEV_SOC_IDS:-} && -n ${DEV_SOC_COMPATIBLE:-} ]]; then - die "$file: SOC_IDS and SOC_COMPATIBLE are exclusive; name the one this bootloader matches on" - elif [[ -z ${DEV_SOC_IDS:-} && -z ${DEV_SOC_COMPATIBLE:-} ]]; then - die "$file: SOC_IDS is missing (or SOC_COMPATIBLE, for a bootloader that matches /soc_compatible)" + if [[ $DEV_BOOT_METHOD == android-v4 ]]; then + # ABL picks the base DTB by /soc_id (gs101, gs201) or by /soc_compatible + # (zuma): a descriptor names exactly one of the two. + if [[ -n ${DEV_SOC_IDS:-} && -n ${DEV_SOC_COMPATIBLE:-} ]]; then + die "$file: SOC_IDS and SOC_COMPATIBLE are exclusive; name the one this bootloader matches on" + elif [[ -z ${DEV_SOC_IDS:-} && -z ${DEV_SOC_COMPATIBLE:-} ]]; then + die "$file: SOC_IDS is missing (or SOC_COMPATIBLE, for a bootloader that matches /soc_compatible)" + fi + local sc='^[a-z0-9]+(-[a-z0-9]+)*:0x[0-9a-f]+:[0-9]+:[0-9]+:[0-9]+$' labels=" " + for p in ${DEV_SOC_COMPATIBLE:-}; do + [[ $p =~ $sc ]] || die "$file: SOC_COMPATIBLE entries are label:product_id:major:minor:pkg_mode, not $p" + # One child node per entry: the label names it, so it must be unique + [[ $labels != *" ${p%%:*} "* ]] || die "$file: SOC_COMPATIBLE names ${p%%:*} twice" + labels+="${p%%:*} " + done fi - local sc='^[a-z0-9]+(-[a-z0-9]+)*:0x[0-9a-f]+:[0-9]+:[0-9]+:[0-9]+$' labels=" " - for p in ${DEV_SOC_COMPATIBLE:-}; do - [[ $p =~ $sc ]] || die "$file: SOC_COMPATIBLE entries are label:product_id:major:minor:pkg_mode, not $p" - # One child node per entry: the label names it, so it must be unique - [[ $labels != *" ${p%%:*} "* ]] || die "$file: SOC_COMPATIBLE names ${p%%:*} twice" - labels+="${p%%:*} " - done [[ $DEV_CODENAME == "$DEVICE" ]] || die "$file: CODENAME=$DEV_CODENAME, expected $DEVICE" # Safety: the guard's allowlist may name slot B's boot images and userdata # only, must hold userdata, and every boot image we write must be on it. @@ -119,9 +133,11 @@ load_device() { [[ $seen != *" $p "* ]] || die "$file: BOOT_IMAGES names $p twice" seen+="$p " done - for p in boot vendor_boot dtbo; do - [[ $seen == *" $p "* ]] || die "$file: BOOT_IMAGES must include $p" - done + if [[ $DEV_BOOT_METHOD == android-v4 ]]; then + for p in boot vendor_boot dtbo; do + [[ $seen == *" $p "* ]] || die "$file: BOOT_IMAGES must include $p" + done + fi # AVB hash footers, for a bootloader whose vbmeta chains these partitions # (zuma): image:partition_size, each a boot image, named once, the size # a whole number of 4 KiB blocks. Their rollback index and security patch @@ -329,6 +345,7 @@ cmd_initramfs_config() { cmd_initramfs() { local dl="$WORK/downloads/alpine" stage="$KERNEL_OUT/initramfs" ver=3.24.2 load_device + [[ $DEV_BOOT_METHOD == android-v4 ]] || die "use tools/build-flame-system for the native flame payload" # A leading slash is repo-root relative, so devices share initramfs/init. # Anything else is relative to device//. local init @@ -452,6 +469,45 @@ cmd_initramfs() { cmd_images() { load_device + if [[ $DEV_BOOT_METHOD == uboot-ext4 ]]; then + local image=${UBOOT_IMAGE:-} expected=${UBOOT_SHA256:-} got role=${FLAME_BOOT_ROLE:-loader} + [[ $role == loader || $role == stock-recovery ]] || die 'FLAME_BOOT_ROLE must be loader or stock-recovery' + [[ -f $image && $expected =~ ^[a-f0-9]{64}$ ]] || die 'supply the reviewed UBOOT_IMAGE and UBOOT_SHA256' + got=$(sha256sum < "$image" | cut -d' ' -f1) + [[ $got == "$expected" ]] || die 'U-Boot image checksum mismatch' + python3 - "$image" "$role" <<'PY' +import pathlib, struct, sys +p = pathlib.Path(sys.argv[1]) +with p.open('rb') as stream: + header = stream.read(48) +version = 0 if sys.argv[2] == 'loader' else 2 +if len(header) != 48 or header[:8] != b'ANDROID!' or struct.unpack_from(' "$KERNEL_OUT/images/DEVICE" + printf '%s\n' "$DEV_BOOT_METHOD" > "$KERNEL_OUT/images/BOOT_METHOD" + printf '%s\n' "$role" > "$KERNEL_OUT/images/BOOT_ROLE" + (cd "$KERNEL_OUT/images" && sha256sum boot.img > SHA256SUMS) + say 'Staged reviewed U-Boot image; Linux stays in /boot/omamobile/boot.img on userdata' + return + fi local img="$KERNEL_OUT/images" tools="$SRC_DIR/system/tools/mkbootimg" local dtc="$KERNEL_OUT/scripts/dtc/dtc" boot="$KERNEL_OUT/arch/arm64/boot" local dtb="$boot/dts/$DEV_DTB" @@ -663,6 +719,18 @@ fastboot_serial() { } cmd_fastboot() { + if [[ ${FLAME_NATIVE:-0} == 1 ]]; then + load_device + in_fastboot && return 0 + "$ROOT/tools/phone-ssh" 'systemctl --no-block --reboot-argument=bootloader reboot' \ + || die 'native flame reboot request failed; use Power + Volume Down' + local attempt + for ((attempt=0; attempt<30; attempt++)); do + sleep 2 + in_fastboot && return 0 + done + die 'native flame did not enter Android fastboot; use the buttons. No slot-A fallback attempted.' + fi local ssh="$ROOT/tools/phone-ssh" i in_fastboot && { say "Already in fastboot"; return 0; } for i in $(seq 1 12); do @@ -699,19 +767,54 @@ cmd_flash() { serial=$(fastboot_serial) || exit 1 # Every image and allowlist entry first: never start writing slot B and # find out halfway that a later image is missing. + if [[ $DEV_BOOT_METHOD == uboot-ext4 ]]; then + [[ $(cat "$img/BOOT_METHOD" 2>/dev/null) == uboot-ext4 ]] || die 'image boot method mismatch' + (cd "$img" && sha256sum -c SHA256SUMS) || die 'staged boot checksum mismatch' + local facts role + role=$(cat "$img/BOOT_ROLE" 2>/dev/null) + [[ $role == loader || $role == stock-recovery ]] || die 'missing flame image role' + facts='' + local variable value + for variable in product unlocked current-slot version-bootloader slot-successful:b; do + value=$(timeout 10 fastboot -s "$serial" getvar "$variable" 2>&1) || die "cannot inspect Android fastboot: $variable" + facts+="$value"$'\n' + done + [[ $facts != *U-Boot* ]] || die 'return to Android fastboot before flashing' + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])product:[[:space:]]*flame[[:space:]]*$' || die 'connected product is not flame' + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])unlocked:[[:space:]]*yes[[:space:]]*$' || die 'bootloader is locked' + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])current-slot:[[:space:]]*b[[:space:]]*$' || die 'flame requires the already-active, recovery-tested slot B' + if [[ $role == loader ]]; then + printf '%s\n' "$facts" | grep -Eq '(^|[[:space:]])slot-successful:b:[[:space:]]*yes[[:space:]]*$' || die 'slot B must already be marked successful' + fi + fi + # Check every file before starting any write, including shared Android paths. for p in $DEV_BOOT_IMAGES; do slot_b_allowed "$p" || die "${p}_b is not on device/$DEVICE's storage-guard allowlist; refusing" [[ -f "$img/$p.img" ]] || die "missing $img/$p.img (run: omamobile images)" done local out rc for p in $DEV_BOOT_IMAGES; do + if [[ $DEV_BOOT_METHOD == uboot-ext4 && $(cat "$img/BOOT_ROLE") == loader ]]; then + timeout 30 fastboot -s "$serial" erase "${p}_b" || die 'boot B erase failed; staying in fastboot' + fi rc=0 out=$(timeout 60 fastboot -s "$serial" flash "${p}_b" "$img/$p.img" 2>&1) || rc=$? echo "$out" | grep -E 'OKAY|FAIL' | tail -1 | sed "s/^/$p: /" || true - # Stop before activating or rebooting into a half-written slot B + # Stop before activating or rebooting into a half-written slot B. ((rc == 0)) || die "flashing ${p}_b failed (exit $rc): slot B is incomplete, flash again before rebooting" done - timeout 20 fastboot -s "$serial" --set-active=b >/dev/null 2>&1 + if [[ $DEV_BOOT_METHOD == uboot-ext4 && $(cat "$img/BOOT_ROLE") == stock-recovery ]]; then + say 'Verified stock boot B restored; staying in Android fastboot. Factory-reset Android data through recovery before starting Android.' + return + fi + # Keep flame's existing successful-slot metadata: set_active would reset it, + # and its protected devinfo is never written by the Linux development root. + if [[ $DEV_BOOT_METHOD == android-v4 ]]; then + timeout 20 fastboot -s "$serial" --set-active=b >/dev/null 2>&1 + else + timeout 10 fastboot -s "$serial" getvar slot-successful:b 2>&1 | grep -Eq '(^|[[:space:]])slot-successful:b:[[:space:]]*yes[[:space:]]*$' \ + || die 'slot B success is clear; staying in fastboot. The boot-success policy decision is pending; use physical Fastboot recovery before any further boots.' + fi timeout 20 fastboot -s "$serial" reboot >/dev/null 2>&1 say "Booting slot B; waiting for SSH" local i @@ -719,12 +822,16 @@ cmd_flash() { "$ROOT/tools/phone-ssh" 'uname -v; cut -d" " -f1 /proc/uptime' 2>/dev/null && return 0 sleep 2 done + if [[ $DEV_BOOT_METHOD == uboot-ext4 ]]; then + die 'no SSH after flame boot; use the buttons to return to Android fastboot and follow the native recovery runbook' + fi die "no SSH after boot (the safety net returns to fastboot within about a minute)" } cmd_push() { local img="$KERNEL_OUT/images" ssh="$ROOT/tools/phone-ssh" p dev want got rel load_device + [[ $DEV_BOOT_METHOD == android-v4 ]] || die "native flame writes require Android fastboot; use flash" images_for_device "$img" "$ssh" true || die "phone not reachable at 172.16.42.1" # Refuse before any write. A phone whose initramfs has no reboot-to would diff --git a/device/flame/native/build b/device/flame/native/build new file mode 100644 index 000000000..4b6545c13 --- /dev/null +++ b/device/flame/native/build @@ -0,0 +1,95 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT +# Runs inside tools/build-flame-probe's disposable aarch64 Alpine container. +set -eu +apk add --no-cache gcc musl-dev cpio dtc python3 gzip kmod zstd + +[ "$(fdtget /input/flame.dtb / model)" = 'Google Pixel 4' ] || { + echo 'Not a Google Pixel 4 device tree' >&2; exit 1; +} +case " $(fdtget /input/flame.dtb / compatible) " in + *' qcom,sm8150 '*) ;; + *) echo 'Not an SM8150 device tree' >&2; exit 1 ;; +esac +gzip -t /input/kernel || { echo 'Expected a gzip-compressed ARM64 Image' >&2; exit 1; } +gzip -dc /input/kernel > /tmp/Image +python3 - <<'PY' +from pathlib import Path +import sys +with Path('/tmp/Image').open('rb') as stream: + stream.seek(56) + if stream.read(4) != b'ARM\x64': + sys.exit('Kernel has no ARM64 Image header') +PY +release=$(strings /tmp/Image | sed -n 's/^Linux version \([^ ]*\) .*/\1/p' | head -1) +rm /tmp/Image + +stage=/tmp/rootfs +mkdir -p "$stage" +apk --root "$stage" --initdb --no-cache \ + --repositories-file /etc/apk/repositories --keys-dir /etc/apk/keys add \ + alpine-baselayout busybox dropbear iproute2 util-linux busybox-extras e2fsprogs +install -m755 /system-init "$stage/init" +mkdir -p "$stage/root/.ssh" "$stage/proc" "$stage/sys" "$stage/dev" "$stage/run" +cp /input/key.pub "$stage/root/.ssh/authorized_keys" +chmod 700 "$stage/root/.ssh" +chmod 600 "$stage/root/.ssh/authorized_keys" +gcc -Os -static -o "$stage/sbin/reboot-to" \ + /src/packages/omamobile-device-cheetah/src/reboot-to.c +mkdir -p "$stage/lib/modules" +module=$stage/lib/modules/qcom-wdt.ko +if zstd -t /input/watchdog 2>/dev/null; then + zstd -dc /input/watchdog > "$module" +else + cp /input/watchdog "$module" +fi +[ "$(modinfo -F name "$module")" = qcom_wdt ] || { echo 'Expected qcom-wdt module' >&2; exit 1; } +if [ -z "$release" ] || [ "$(modinfo -F vermagic "$module" | cut -d ' ' -f1)" != "$release" ]; then + echo 'Watchdog module does not match the kernel release' >&2 + exit 1 +fi +[ -z "$(modinfo -F depends "$module")" ] || { echo 'Watchdog needs additional modules' >&2; exit 1; } + +# A separate RAM rescue root survives the desktop handoff. +rescue=/tmp/rescue-base +mkdir -p "$rescue" +apk --root "$rescue" --initdb --no-cache \ + --repositories-file /etc/apk/repositories --keys-dir /etc/apk/keys add \ + alpine-baselayout busybox dropbear iproute2 util-linux +mkdir -p "$rescue/root/.ssh" "$rescue/proc" "$rescue/sys" "$rescue/dev" "$rescue/run" "$rescue/realroot" +cp /input/key.pub "$rescue/root/.ssh/authorized_keys" +chmod 700 "$rescue/root/.ssh" +chmod 600 "$rescue/root/.ssh/authorized_keys" +cp "$stage/sbin/reboot-to" "$rescue/sbin/reboot-to" +mv "$rescue" "$stage/rescue-base" + +# No vendor firmware enters the probe. Only the watchdog module is included; +# remote processors stay disabled unless the explicit Wi-Fi profile below is used. +cp /input/flame.dtb /out/flame.dtb +usb=/soc@0/usb@a6f8800/usb@a600000 +fdtput -t s /out/flame.dtb "$usb" dr_mode peripheral +fdtput -d /out/flame.dtb "$usb" usb-role-switch +for node in remoteproc@2400000 remoteproc@4080000 remoteproc@8300000 remoteproc@17300000; do + fdtput -t s /out/flame.dtb "/soc@0/$node" status disabled +done +if [ "${FLAME_WIFI:-0}" = 1 ]; then + [ "$(fdtget /out/flame.dtb /soc@0/remoteproc@4080000 compatible)" = qcom,sm8150-mpss-pas ] || exit 1 + fdtput -t s /out/flame.dtb /soc@0/remoteproc@4080000 status okay +fi +(cd "$stage" && find . -print0 | cpio --null --quiet -o -H newc --owner=0:0) \ + | gzip -n -9 > /out/initramfs.cpio.gz +# U-Boot recognizes these standard Android addresses as sentinels: decompress +# to its kernel_addr_r and leave the ramdisk in its download buffer. Using +# Android ABL's base=0 instead asks U-Boot to write to physical 0x8000. +# Keep /dev/console off USB for standalone operation. USB networking and an +# explicitly started serial login remain available without being boot consoles. +python3 /mkbootimg/mkbootimg.py --header_version 2 \ + --base 0x10000000 --kernel_offset 0x8000 --ramdisk_offset 0x1000000 \ + --dtb_offset 0x1f00000 --pagesize 4096 \ + --kernel /input/kernel --ramdisk /out/initramfs.cpio.gz --dtb /out/flame.dtb \ + --os_version 13.0.0 --os_patch_level 2022-10 \ + --cmdline 'console=tty0 rdinit=/init clk_ignore_unused pd_ignore_unused fw_devlink=permissive panic=10 printk.devkmsg=on' \ + -o /out/boot.img +size=$(stat -c %s /out/boot.img) +[ "$size" -le 67108864 ] || { rm /out/boot.img; echo 'Probe exceeds the 64 MiB boot partition' >&2; exit 1; } +(cd /out && sha256sum boot.img flame.dtb initramfs.cpio.gz > SHA256SUMS) diff --git a/device/flame/native/device.conf b/device/flame/native/device.conf new file mode 100644 index 000000000..72cb62f86 --- /dev/null +++ b/device/flame/native/device.conf @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: MIT +# Explicit opt-in development profile: DEVICE=flame FLAME_NATIVE=1. +# The default device/flame/device.conf remains RAM-only. +# Experimental U-Boot layout. Requires a locally built, reviewed loader and +# a separately tested native root. No Tensor images or DTBO are written. +CODENAME=flame +NAME="Google Pixel 4" +SOC=sm8150 +COMPATIBLE="google,floral-sm8150" +BOOT_METHOD=uboot-ext4 +BOOT_IMAGES="boot" +UFS_RW="boot_b userdata" +PANEL_SIZE=1080x2280 +PACKAGE=omamobile-device-flame diff --git a/device/flame/native/init b/device/flame/native/init new file mode 100644 index 000000000..41911e79c --- /dev/null +++ b/device/flame/native/init @@ -0,0 +1,184 @@ +#!/bin/sh +# SPDX-License-Identifier: MIT +# Pixel 4 development root boot. Only userdata and boot_b are writable. +export PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + +# PID 1 exiting on a mount failure deliberately panics (panic=10), rather +# than exposing a root shell with an uninitialized storage guard. +mount -t proc proc /proc || exit 1 +mount -t sysfs sysfs /sys || exit 1 +mount -t devtmpfs devtmpfs /dev || exit 1 +mkdir -p /dev/pts /run +mount -t devpts devpts /dev/pts || exit 1 +mount -t tmpfs tmpfs /run || exit 1 +mount -t configfs configfs /sys/kernel/config || exit 1 + +say() { + echo "omamobile-flame: $*" > /dev/kmsg + echo "omamobile-flame: $*" > /dev/tty0 2>/dev/null +} + +# New install boot only: the owner authorized using userdata and boot_b. +# This is a separate init, never a relaxation of a running RAM-only probe. +UFS_RW="boot_b userdata" +part_name() { sed -n 's/^PARTNAME=//p' "$1/uevent"; } +storage_guard() { + for s in /sys/class/block/sd*; do + [ -r "$s/ro" ] || continue + name=${s##*/} + if [ "$name" = sda ]; then + rm -f /dev/sda + continue + fi + [ -b "/dev/$name" ] || continue + part=$(part_name "$s") + case "$name" in + sda[0-9]*) + # A previously read-only device stays so; never use --setrw. + case " $UFS_RW " in *" $part "*) continue ;; esac ;; + esac + [ "$(cat "$s/ro")" = 1 ] && continue + if ! blockdev --setro "/dev/$name" || [ "$(cat "$s/ro")" != 1 ]; then + say "FAILED to protect /dev/$name" + return 1 + fi + done + [ ! -e /dev/sda ] +} +storage_guard || exit 1 +( + while :; do + if ! storage_guard; then + killall dropbear getty 2>/dev/null + echo c > /proc/sysrq-trigger + exit 1 + fi + sleep 0.2 + done +) & + +hostname omamobile-flame +say "Pixel 4 development root boot: $(uname -r)" + +# Take over the hardware watchdog before running probes. If the kernel +# stalls, its keeper stalls too and recovery requires Android fastboot and the verified stock boot image. +if ! insmod /lib/modules/qcom-wdt.ko; then + say 'Watchdog module failed; returning to bootloader' + reboot-to bootloader + while :; do sleep 60; done +fi +for _ in $(seq 1 5); do + [ -c /dev/watchdog0 ] && break + sleep 1 +done +if [ -c /dev/watchdog0 ]; then + watchdog -F -t 5 -T 30 /dev/watchdog0 & +else + say 'No watchdog device; returning to bootloader' + reboot-to bootloader + while :; do sleep 60; done +fi + +# CDC NCM works with Linux and macOS without a proprietary host driver. +g=/sys/kernel/config/usb_gadget/omamobile +mkdir -p "$g/strings/0x409" "$g/configs/c.1/strings/0x409" +echo 0x1d6b > "$g/idVendor" +echo 0x0104 > "$g/idProduct" +echo 'Omarchy Mobile' > "$g/strings/0x409/manufacturer" +echo 'Pixel 4 (Omarchy Mobile)' > "$g/strings/0x409/product" +echo omamobile-flame > "$g/strings/0x409/serialnumber" +echo 'NCM + ACM' > "$g/configs/c.1/strings/0x409/configuration" +mkdir -p "$g/functions/ncm.usb0" "$g/functions/acm.GS0" +ln -s "$g/functions/ncm.usb0" "$g/configs/c.1/" +ln -s "$g/functions/acm.GS0" "$g/configs/c.1/" + +udc="" +for _ in $(seq 1 30); do + for controller in /sys/class/udc/*; do + [ -e "$controller" ] && udc=${controller##*/} && break + done + [ -n "$udc" ] && break + sleep 1 +done +if [ -n "$udc" ] && echo "$udc" > "$g/UDC"; then + say "USB gadget bound to $udc" +else + say 'No USB controller; return to Android fastboot with the buttons' +fi + +ip link set lo up +ip addr add 172.16.42.1/24 dev usb0 +ip link set usb0 up +cat > /run/udhcpd.conf <<'CONF' +start 172.16.42.2 +end 172.16.42.2 +interface usb0 +option subnet 255.255.255.0 +lease_file /run/udhcpd.leases +CONF +touch /run/udhcpd.leases +udhcpd /run/udhcpd.conf + +# Only the locally supplied public key grants SSH access. Host keys are +# generated in the RAM filesystem; no identity or vendor firmware is shipped. +mkdir -p /etc/dropbear +dropbear -R -E -s -j -k -p 172.16.42.1:22 +say 'USB ready; protected storage; waiting for the Omarchy root' + +# ACM is for an explicitly started attached-only debug session. Never start +# an automatic USB getty in the standalone boot path. + +# Recover both an initial failure and a later disconnection. The helper uses +# RESTART2 to request Android fastboot; no filesystems need shutting down. +( + missing=0 + while :; do + if grep -qx configured /sys/class/udc/*/state 2>/dev/null; then + missing=0 + else + missing=$((missing + 1)) + fi + if [ "$missing" -ge 90 ]; then + say 'USB disconnected for 90 s; returning to bootloader' + reboot-to bootloader + fi + sleep 1 + done +) & + +# The root is located by its GPT name and label, never by a guessed number. +rootdev="" +for _ in $(seq 1 20); do + storage_guard || exit 1 + for node in /sys/class/block/sda[0-9]*; do + [ -r "$node/uevent" ] || continue + [ "$(part_name "$node")" = userdata ] || continue + [ -z "$rootdev" ] || { say 'Duplicate userdata partition'; exit 1; } + rootdev=/dev/${node##*/} + done + [ -n "$rootdev" ] && break + sleep 1 +done +[ -b "$rootdev" ] || { say 'No userdata partition'; exit 1; } +[ "$(blockdev --getro "$rootdev")" = 0 ] || { say 'Root is read-only; refusing to weaken guard'; exit 1; } +[ "$(blkid -s LABEL -o value "$rootdev")" = omamobile-root ] || { say 'Wrong root label'; exit 1; } +fsck_status=0 +e2fsck -p "$rootdev" || fsck_status=$? +[ "$fsck_status" -le 1 ] || { say 'Root filesystem check failed'; exit 1; } +mkdir -p /newroot +mount -t ext4 -o rw,relatime "$rootdev" /newroot || exit 1 +[ -x /newroot/usr/lib/systemd/systemd ] || { say 'Root has no systemd'; exit 1; } +[ -f /newroot/usr/share/omamobile/flame-root ] || { say 'Root is not a flame development image'; exit 1; } +cp -a /rescue-base /run/rescue || exit 1 +say 'Starting Arch and Omarchy on userdata' +kill -9 -1 2>/dev/null +for m in /dev /proc /sys /run; do + mkdir -p "/newroot$m" + mount --move "$m" "/newroot$m" || exit 1 +done +for m in /dev /proc /sys; do + mount --bind "/newroot$m" "/newroot/run/rescue$m" || exit 1 +done +mount --bind /newroot /newroot/run/rescue/realroot || exit 1 +chroot /newroot/run/rescue /usr/sbin/dropbear -R -E -s -j -k -p 172.16.42.1:2222 || exit 1 +exec switch_root /newroot /usr/lib/systemd/systemd diff --git a/rootfs/build-inside b/rootfs/build-inside index c0d4ad1c2..2a38b9afe 100755 --- a/rootfs/build-inside +++ b/rootfs/build-inside @@ -167,6 +167,11 @@ size=$(( (used * 12 / 10 + 768 + 63) / 64 * 64 )) rm -f /out/rootfs.img truncate -s "${size}M" /out/rootfs.img # -m 1: 1% reserved for root, not 5% of a ~100 GB userdata -mkfs.ext4 -q -L omamobile-root -m 1 -d "$T" /out/rootfs.img +features=() +if [[ $DEVICE == flame && ${FLAME_NATIVE:-0} == 1 ]]; then + # The tested storage loader does not support these newer ext4 features. + features=(-O "^orphan_file,^metadata_csum_seed") +fi +mkfs.ext4 -q -L omamobile-root -m 1 "${features[@]}" -d "$T" /out/rootfs.img e2fsck -fn /out/rootfs.img >/dev/null echo " ${used} MiB of files in a ${size} MiB file system" diff --git a/tests/all b/tests/all index d06659ec9..026dea3ac 100755 --- a/tests/all +++ b/tests/all @@ -13,18 +13,27 @@ cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." for f in tools/install-phone tools/phone-provision tools/build-rootfs tools/build-packages tools/make-bundle \ tools/lib/alarm.sh tools/lib/alarm-setup rootfs/build-inside tests/*; do [[ -f $f ]] || continue # tests/owl is the OWL conformance suite's folder + if [[ $f == *.py ]]; then + python3 -B -c 'import ast,sys; ast.parse(open(sys.argv[1]).read())' "$f" + continue + fi bash -n "$f" || { echo "not ok - $f parses" >&2; exit 1; } done sh -n initramfs/init sh -n device/flame/initramfs/init sh -n device/flame/initramfs/build -bash -n tools/build-flame-probe +bash -n tools/build-flame-probe tools/build-flame-system tools/build-flame-loader +sh -n device/flame/native/init device/flame/native/build echo "ok - scripts parse" -for t in tests/pr-check tests/kernel-pr-check tests/install-phone tests/phone-provision tests/initramfs-grow tests/images-layout tests/device-overlays tests/simplefb-trigger tests/storage-guard tests/usb-product tests/boot-method tests/flame-probe packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all; do +for t in tests/pr-check tests/kernel-pr-check tests/install-phone tests/phone-provision tests/initramfs-grow tests/images-layout tests/device-overlays tests/simplefb-trigger tests/storage-guard tests/usb-product tests/boot-method tests/flame-probe tests/flame-images packages/omamobile-firstboot/test/all packages/omamobile-device-felix/test/all; do echo "# $t" "$t" done shopt -s nullglob +for t in tests/flame-*.py; do + echo "# $t" + python3 -B "$t" +done latest="" for f in out/omamobile-rootfs-*-aarch64.img.zst; do latest=$f; done if [[ -n $latest ]]; then diff --git a/tests/flame-images b/tests/flame-images new file mode 100755 index 000000000..9f9b940dc --- /dev/null +++ b/tests/flame-images @@ -0,0 +1,121 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# No phone: verify the separate U-Boot layout and its pre-flash checks. +set -euo pipefail +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." +t=$(mktemp -d) +trap 'rm -rf "$t"' EXIT +mkdir -p "$t/repo/bin" "$t/repo/device/flame/native" "$t/repo/tools" "$t/bin" +cp bin/omamobile "$t/repo/bin/" +cp device/flame/native/device.conf "$t/repo/device/flame/native/" +printf 'DEVICE=flame\nSRC_DIR=/nonexistent\n' >"$t/repo/omamobile.conf" +printf '#!/bin/sh\nexit 0\n' >"$t/repo/tools/phone-ssh" +chmod +x "$t/repo/tools/phone-ssh" +python3 - "$t/loader.img" <<'PY' +from pathlib import Path +import sys, struct +data=bytearray(8192);data[:8]=b'ANDROID!' +struct.pack_into('<3I',data,8,64,0x8000,0) +struct.pack_into('"$t/bin/fastboot" <<'EOF' +#!/bin/sh +echo "$*" >>"$TEST_TMP/calls" +if [ "$1" = devices ]; then + printf 'FAKEPHONE\tfastboot\n' + [ "${TEST_TWO_PHONES:-0}" != 1 ] || printf 'FAKEOTHER\tfastboot\n' + exit 0 +fi +[ "$1" = -s ] && [ "$2" = FAKEPHONE ] || exit 91 +shift 2 +case "$1 $2" in + 'getvar slot-successful:b') + if [ -e "$TEST_TMP/flashed" ] && [ "${TEST_POST_FLASH_SUCCESSFUL:-yes}" = no ]; then + echo '(bootloader) slot-successful:b:no' + else grep 'slot-successful:b:' "$TEST_TMP/facts"; fi ;; + 'getvar version-bootloader') echo '(bootloader) version-bootloader:FAKE-ABL' ;; + getvar*) grep -E "(^| )$2:" "$TEST_TMP/facts" ;; + 'erase boot_b') [ "${TEST_ERASE_FAIL:-0}" = 0 ] || exit 1; echo OKAY ;; + 'flash boot_b') [ "${TEST_FLASH_FAIL:-0}" = 0 ] || exit 1; touch "$TEST_TMP/flashed"; echo OKAY ;; + 'reboot ') echo OKAY ;; + *) exit 92 ;; +esac +EOF +chmod +x "$t/bin/fastboot" +export TEST_TMP=$t +facts() { rm -f "$t/flashed"; printf '(bootloader) product:%s\n(bootloader) unlocked:%s\n(bootloader) current-slot:%s\n(bootloader) slot-successful:b:%s\n' "$1" "$2" "$3" "$4" >"$t/facts"; } +om() { FLAME_NATIVE=1 PATH="$t/bin:$PATH" KERNEL_OUT="$t/out" UBOOT_IMAGE="$t/loader.img" UBOOT_SHA256="$sum" "$t/repo/bin/omamobile" "$@" >"$t/log" 2>&1; } +sum=$(sha256sum <"$t/loader.img" | cut -d' ' -f1) +om images || { cat "$t/log"; exit 1; } +cmp "$t/loader.img" "$t/out/images/boot.img" +[[ $(cat "$t/out/images/DEVICE") == flame && $(cat "$t/out/images/BOOT_METHOD") == uboot-ext4 ]] +facts flame yes b yes +om flash || { cat "$t/log"; exit 1; } +[[ $(grep -c '^-s FAKEPHONE flash ' "$t/calls") -eq 1 ]] +grep -q '^-s FAKEPHONE flash boot_b ' "$t/calls" +if grep -q -- '--set-active' "$t/calls"; then exit 1; fi +printf 'product: flame\nunlocked: yes\ncurrent-slot: b\nslot-successful:b: yes\n' >"$t/facts" +om flash || { cat "$t/log"; exit 1; } +for bad in 'other yes b yes' 'flame no b yes' 'flame yes a yes' 'flame yes b no'; do + # Split only these fixed test tokens. + # shellcheck disable=SC2086 + facts $bad + : >"$t/calls" + if om flash; then echo "not ok - accepted $bad"; exit 1; fi + if grep -q '^-s FAKEPHONE flash ' "$t/calls"; then exit 1; fi +done +facts flame yes b yes +export TEST_POST_FLASH_SUCCESSFUL=no +: >"$t/calls" +if om flash; then echo 'not ok - rebooted with unsuccessful B'; exit 1; fi +grep -q '^-s FAKEPHONE erase boot_b$' "$t/calls" +grep -q '^-s FAKEPHONE flash boot_b ' "$t/calls" +if grep -q '^-s FAKEPHONE reboot' "$t/calls"; then exit 1; fi +unset TEST_POST_FLASH_SUCCESSFUL +facts flame yes b yes +export TEST_ERASE_FAIL=1 +: >"$t/calls" +if om flash; then echo 'not ok - ignored erase failure'; exit 1; fi +if grep -q '^-s FAKEPHONE flash ' "$t/calls"; then exit 1; fi +unset TEST_ERASE_FAIL +export TEST_TWO_PHONES=1 +: >"$t/calls" +if om flash; then echo 'not ok - ambiguous phone selection'; exit 1; fi +if grep -Eq ' erase | flash ' "$t/calls"; then exit 1; fi +FASTBOOT_SERIAL=FAKEPHONE om flash || { cat "$t/log"; exit 1; } +unset TEST_TWO_PHONES +export FLAME_BOOT_ROLE=userdata +: >"$t/calls" +if om images; then echo 'not ok - staged pending-policy userdata role'; exit 1; fi +if grep -Eq ' erase | flash ' "$t/calls"; then exit 1; fi +unset FLAME_BOOT_ROLE +facts flame yes b yes +printf changed >>"$t/out/images/boot.img" +: >"$t/calls" +if om flash; then echo 'not ok - accepted modified image'; exit 1; fi +if grep -q '^-s FAKEPHONE flash ' "$t/calls"; then exit 1; fi +sum=$(printf '%064d' 0) +if om images; then echo 'not ok - accepted incorrect source checksum'; exit 1; fi +if om push; then echo 'not ok - accepted unimplemented direct write'; exit 1; fi +python3 - "$t/loader.img" <<'PY' +from pathlib import Path +import struct, sys +p=Path(sys.argv[1]) +with p.open('wb') as f: + header=bytearray(48) + header[:8]=b'ANDROID!' + struct.pack_into('"$t/calls" +om flash || { cat "$t/log"; exit 1; } +grep -q '^-s FAKEPHONE flash boot_b ' "$t/calls" +if grep -q '^-s FAKEPHONE reboot' "$t/calls"; then echo 'not ok - stock recovery rebooted before data reset'; exit 1; fi +echo 'ok - flame stages only checked U-Boot; flash verifies product, unlock and existing successful B' diff --git a/tests/flame-root-guard.py b/tests/flame-root-guard.py new file mode 100644 index 000000000..d48621b9f --- /dev/null +++ b/tests/flame-root-guard.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +from pathlib import Path +import tempfile,subprocess,os +source=(Path(__file__).resolve().parents[1]/'device/flame/native/init').read_text() +body='UFS_RW="boot_b userdata"'+source.split('UFS_RW="boot_b userdata"',1)[1].split('\nstorage_guard ||',1)[0] +with tempfile.TemporaryDirectory() as d: + p=Path(d); sys=p/'sys';dev=p/'dev';bin=p/'bin' + for x in (sys,dev,bin):x.mkdir() + body=body.replace('/sys/class/block/',str(sys)+'/').replace('/dev/',str(dev)+'/').replace('[ -b ','[ -f ') + (p/'guard').write_text('say() { echo "$*" >&2; }\n'+body+'\nstorage_guard\n') + (bin/'blockdev').write_text('#!/bin/sh\n[ "$1" = --setro ] || exit 92\n[ "${MODE:-}" != fail ] || exit 1\n[ "${MODE:-}" != lie ] || exit 0\necho 1 > "$SYS/${2##*/}/ro"\n') + (bin/'blockdev').chmod(0o755) + def add(n,part='',ro='0'): + (sys/n).mkdir();(sys/n/'ro').write_text(ro+'\n');(sys/n/'uevent').write_text('PARTNAME='+part+'\n' if part else '');(dev/n).touch() + def run(mode=''): + return subprocess.run(['sh',str(p/'guard')],env=dict(os.environ,PATH=str(bin)+':'+os.environ['PATH'],SYS=str(sys),MODE=mode),capture_output=True) + for n,part in [('sda',''),('sda2','persist'),('sda6','boot_a'),('sda7','boot_b'),('sda15','userdata'),('sdb',''),('sde33','devinfo'),('sdf2','modemst1'),('sdf3','userdata')]:add(n,part) + assert run().returncode==0 + assert not (dev/'sda').exists() + for n in ['sda2','sda6','sdb','sde33','sdf2','sdf3']:assert (sys/n/'ro').read_text().strip()=='1',n + for n in ['sda7','sda15']:assert (sys/n/'ro').read_text().strip()=='0',n + (sys/'sda7'/'ro').write_text('1\n');(dev/'sda').touch();assert run().returncode==0;assert not (dev/'sda').exists();assert (sys/'sda7'/'ro').read_text().strip()=='1' + add('sdg');assert run('fail').returncode!=0;assert run('lie').returncode!=0 + first_pass=source.split('\nstorage_guard ||',1)[1].split('\n(',1)[0] + (p/'startup').write_text('say() { echo \"$*\" >&2; }\nsleep() { exit 94; }\n'+body+'\nstorage_guard ||'+first_pass+'\nexit 93\n') + for mode in ('fail','lie'): + result=subprocess.run(['sh',str(p/'startup')],env=dict(os.environ,PATH=str(bin)+':'+os.environ['PATH'],SYS=str(sys),MODE=mode),timeout=2,capture_output=True) + assert result.returncode==1,result + print('Root guard: exact sda allowlist, all calibration protected, other-LUN userdata rejected, whole node removed, existing RO preserved, failure closed') diff --git a/tools/build-flame-loader b/tools/build-flame-loader new file mode 100755 index 000000000..798d06fc5 --- /dev/null +++ b/tools/build-flame-loader @@ -0,0 +1,76 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Build the opt-in native storage loader on a Linux build host. No phone access. +# Requires git, make, aarch64-linux-gnu-gcc, dtc, flex, bison, Python 3, +# OpenSSL/UUID development headers and AOSP's mkbootimg.py with its gki helpers. +# Clone https://github.com/wirelessjoe/u-boot and check out the revision below. +set -euo pipefail +revision=e210c6956ce90e48b667eb15a8c6f20bc292b52e +source_dir="" mkbootimg="" out="" jobs=4 +die() { echo "error: $*" >&2; exit 1; } +while (($#)); do + case $1 in + --uboot) source_dir=${2:?}; shift ;; + --mkbootimg) mkbootimg=${2:?}; shift ;; + --out) out=${2:?}; shift ;; + --jobs) jobs=${2:?}; shift ;; + -h|--help) echo 'tools/build-flame-loader --uboot DIR --mkbootimg FILE --out FRESH_DIR [--jobs N]'; exit 0 ;; + *) die "unknown argument: $1" ;; + esac + shift +done +[[ -d $source_dir && -f $mkbootimg && -n $out && $jobs =~ ^[1-9][0-9]*$ ]] || die 'supply source, AOSP mkbootimg and fresh output paths' +source_dir=$(cd -- "$source_dir" && pwd) +mkbootimg=$(python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$mkbootimg") +[[ $(git -C "$source_dir" rev-parse HEAD) == "$revision" ]] || die 'wrong U-Boot source revision' +git -C "$source_dir" diff --quiet HEAD -- || die 'U-Boot source has tracked local changes' +[[ ! -e $out ]] || die 'choose a fresh output directory' +mkdir -p "$out" +out=$(cd -- "$out" && pwd) +export SOURCE_DATE_EPOCH +SOURCE_DATE_EPOCH=$(git -C "$source_dir" log -1 --format=%ct) +cross=${CROSS_COMPILE:-aarch64-linux-gnu-} +make -C "$source_dir" O="$out/uboot" ARCH=arm CROSS_COMPILE="$cross" qcom_flame_omamobile_defconfig +make -C "$source_dir" O="$out/uboot" ARCH=arm CROSS_COMPILE="$cross" W=1 -j"$jobs" +python3 - "$out" "$revision" <<'PY' +from pathlib import Path +import gzip,hashlib,json,re,sys +out=Path(sys.argv[1]);build=out/'uboot' +config=(build/'.config').read_text().splitlines() +for key in ('EFI_LOADER','FAT_WRITE','FASTBOOT_FLASH','CMD_USB_MASS_STORAGE', + 'USB_FUNCTION_MASS_STORAGE','CMD_SAVEENV','CMD_DFU','DFU_SCSI', + 'DFU_MMC','FASTBOOT_OEM_RUN','FASTBOOT_OEM_BOARD','FASTBOOT_CMD_OEM_CONSOLE'): + assert 'CONFIG_'+key+'=y' not in config,'Unexpected write facility: '+key +assert 'CONFIG_ENV_IS_NOWHERE=y' in config +header=(build/'include/generated/defaultenv_autogenerated.h').read_text() +data=bytes(int(v,16) for v in re.findall(r'0x([0-9a-fA-F]{2})',header)) +env=dict(item.split('=',1) for item in data.decode().split('\0') if '=' in item) +assert env['preboot']=='sleep 2; scsi scan' +assert env['bootcmd']=='run native_boot; run fastboot' +assert 'part number scsi 0 userdata rootpart' in env['native_boot'] +assert '/boot/omamobile/boot.img' in env['native_boot'] +assert 'usbacm' not in env['stdout'] and 'usbacm' not in env['stderr'] +assert not any('ums ' in v or 'bootefi' in v for k,v in env.items() if k.startswith('bootmenu_')) +raw=(build/'u-boot-nodtb.bin').read_bytes() +dtb=(build/'dts/upstream/src/arm64/qcom/sm8150-google-flame.dtb').read_bytes() +(out/'u-boot.gz-dtb').write_bytes(gzip.compress(raw,compresslevel=9,mtime=0)+dtb) +(out/'BUILD.json').write_text(json.dumps({'source_revision':sys.argv[2], + 'config_sha256':hashlib.sha256((build/'.config').read_bytes()).hexdigest(), + 'loader_sha256':hashlib.sha256(raw).hexdigest(),'dtb_sha256':hashlib.sha256(dtb).hexdigest(), + 'compiled_environment_checked':True,'hardware_status':'host build only; new approved RAM boot required'},indent=2)+'\n') +PY +python3 "$mkbootimg" --header_version 0 --base 0 --kernel_offset 0x8000 \ + --ramdisk_offset 0 --second_offset 0 --tags_offset 0x100 --pagesize 4096 \ + --kernel "$out/u-boot.gz-dtb" -o "$out/boot.img" +python3 - "$out/boot.img" <<'PY' +from pathlib import Path +import struct,sys +data=Path(sys.argv[1]).read_bytes() +assert data[:8]==b'ANDROID!' and 4096 SHA256SUMS) +echo "Built $out/boot.img; no phone accessed. Follow the native RAM-boot gates before flashing." diff --git a/tools/build-flame-system b/tools/build-flame-system new file mode 100755 index 000000000..b12702bbd --- /dev/null +++ b/tools/build-flame-system @@ -0,0 +1,80 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Build the experimental Pixel 4 native-root boot image, host only. +# At boot, its init may write only userdata and boot_b; read the native runbook. +# +# Usage: tools/build-flame-system --kernel Image.gz --dtb flame.dtb \ +# --watchdog-module qcom-wdt.ko.zst \ +# --ssh-key ~/.ssh/id_ed25519.pub --mkbootimg /path/to/mkbootimg.py \ +# --out /path/to/output +# +# The kernel must have UFS, USB DWC3/QCOM, configfs NCM/ACM and devtmpfs +# built in (the supplied SM8150 kernel does). Only its matching watchdog +# module is loaded. Remote processors stay disabled unless --wifi explicitly +# enables the previously tested MPSS node; firmware/NV gates still apply. +# Supply the original sm8150-google-flame.dtb, not a Tensor or coral DTB. +# mkbootimg.py and its gki/ helpers come from AOSP system/tools/mkbootimg. +# Docker runs an aarch64 Alpine builder; x86 hosts need a binfmt handler. +# Boot this image from U-Boot's fastboot server, not Android's fastboot. +set -euo pipefail +ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +kernel="" dtb="" watchdog="" key="" mkbootimg="" out="" wifi=0 +die() { echo "error: $*" >&2; exit 1; } +while (($#)); do + case $1 in + --kernel) kernel=${2:?}; shift ;; + --dtb) dtb=${2:?}; shift ;; + --watchdog-module) watchdog=${2:?}; shift ;; + --ssh-key) key=${2:?}; shift ;; + --mkbootimg) mkbootimg=${2:?}; shift ;; + --out) out=${2:?}; shift ;; + --wifi) wifi=1 ;; + -h|--help) sed -n '3,18p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) die "unknown argument: $1" ;; + esac + shift +done +command -v docker >/dev/null || die 'Docker is required' +command -v python3 >/dev/null || die 'Python 3 is required' +for path in "$kernel" "$dtb" "$watchdog" "$key" "$mkbootimg"; do + [[ -n $path && -f $path ]] || die 'supply --kernel, --dtb, --watchdog-module, --ssh-key and --mkbootimg files' +done +[[ -n $out ]] || die 'supply --out DIR' + +# Normalize paths portably (macOS readlink lacks -f on older releases), so +# relative paths and spaces survive Docker's bind mount parsing. +absolute() { python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$1"; } +kernel=$(absolute "$kernel") dtb=$(absolute "$dtb") key=$(absolute "$key") +watchdog=$(absolute "$watchdog") +mkbootimg=$(absolute "$mkbootimg") out=$(absolute "$out") +for path in "$ROOT" "$kernel" "$dtb" "$watchdog" "$key" "$mkbootimg" "$out"; do + [[ $path != *,* ]] || die 'Docker bind paths cannot contain commas' +done +[[ $(basename "$mkbootimg") == mkbootimg.py ]] || die '--mkbootimg must name AOSP mkbootimg.py' +[[ ! -e $out/boot.img ]] || die "$out/boot.img already exists; choose a fresh output directory" +python3 - "$key" <<'PY' +import base64, pathlib, struct, sys +data = pathlib.Path(sys.argv[1]).read_text().split() +if len(data) < 2 or data[0] not in ('ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256'): + sys.exit('--ssh-key must be an OpenSSH PUBLIC key, never a private key') +try: + raw = base64.b64decode(data[1], validate=True) + n, = struct.unpack('>I', raw[:4]) + assert raw[4:4+n].decode() == data[0] +except (ValueError, struct.error, AssertionError, UnicodeError): + sys.exit('invalid SSH public key') +PY + +mkdir -p "$out" +docker run --rm --platform linux/arm64 \ + --mount "type=bind,source=$ROOT,target=/src,readonly" \ + --mount "type=bind,source=$kernel,target=/input/kernel,readonly" \ + --mount "type=bind,source=$dtb,target=/input/flame.dtb,readonly" \ + --mount "type=bind,source=$watchdog,target=/input/watchdog,readonly" \ + --mount "type=bind,source=$key,target=/input/key.pub,readonly" \ + --mount "type=bind,source=$(dirname "$mkbootimg"),target=/mkbootimg,readonly" \ + --mount "type=bind,source=$out,target=/out" \ + --mount "type=bind,source=$ROOT/device/flame/native/init,target=/system-init,readonly" \ + --env FLAME_WIFI="$wifi" \ + alpine:3.22 sh /src/device/flame/native/build +echo "Built $out/boot.img (U-Boot native-root development image; no phone was accessed)" diff --git a/tools/build-rootfs b/tools/build-rootfs index 8f22f450e..2ee49860a 100755 --- a/tools/build-rootfs +++ b/tools/build-rootfs @@ -61,6 +61,10 @@ done [[ $VERSION =~ ^[0-9A-Za-z._-]+$ ]] || alarm_die "bad version '$VERSION'" [[ $DEVICE =~ ^[a-z0-9]+$ ]] || alarm_die "DEVICE must be a codename" conf=device/$DEVICE/device.conf +if [[ ${FLAME_NATIVE:-0} == 1 ]]; then + [[ $DEVICE == flame ]] || alarm_die "FLAME_NATIVE=1 requires DEVICE=flame" + conf=device/flame/native/device.conf +fi [[ -f $conf ]] || alarm_die "no $conf" DEVICE_PACKAGE=$(sed -n 's/^PACKAGE=\([a-z0-9-]*\)$/\1/p' "$conf") [[ -n $DEVICE_PACKAGE ]] || alarm_die "$conf has no PACKAGE" @@ -95,7 +99,7 @@ docker run --rm --privileged --platform linux/arm64 \ -v "$ROOT:/src:ro" -v "$ROOT/out/repo:/repo:ro" -v "$modules:/modules:ro" \ -v "$volume:/target" -v "$work:/out" -v "$ALARM_CACHE/pkg:/var/cache/pacman/pkg" \ -e VERSION="$VERSION" -e DEVICE="$DEVICE" -e DEVICE_PACKAGE="$DEVICE_PACKAGE" \ - -e ROOTFS_PACKAGES="$ROOTFS_PACKAGES" \ + -e ROOTFS_PACKAGES="$ROOTFS_PACKAGES" -e FLAME_NATIVE="${FLAME_NATIVE:-0}" \ -e KERNEL_RELEASE="$release" -e MODULES_SHA256="$(sha256sum < "$modules" | cut -d' ' -f1)" \ -e GIT_COMMIT="$commit" -e ALARM_SHA256="$(sha256sum < "$ALARM_TARBALL" | cut -d' ' -f1)" \ -e OMARCHY_CHANNEL="$OMARCHY_CHANNEL" -e ALLOW_MISSING="$ALLOW_MISSING" \