Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

xnuloader, tools: UEFI-native boot: the loader reads its payload from the volume it was started from

shimokuef8b424d0bf1
diff --git a/Makefile b/Makefile
index 336968b..e12908b 100644
--- a/Makefile
+++ b/Makefile
@@ -14,6 +14,8 @@
# make prebuilt refresh prebuilt/ from what was built (tools/update-prebuilt.sh)
# make clean build output of the kernel, loader and images
# make doctor check this machine and a phone on adb for what HakiOS needs (tools/doctor.sh)
+# make esp an EFI system partition tree in build/esp: the loader and a payload it reads itself,
+# to copy to a FAT32 volume (UEFI-native boot, no fastboot; docs/uefi-boot.md)
#
# Configuration, the way Linux's make does it (configs/, tools/hakios-config.py; docs/configs.md):
# make redwood_defconfig .config from configs/defconfig + configs/redwood_defconfig (any NAME_defconfig)
@@ -42,8 +44,10 @@ ARGS ?= touchscreen=1 gpu=1 adsp=1 sound=4 wifi=1 haptic=5 modem=1 modem_again=1
RUNNER_BASE =
endif
IMAGE_OPTS ?= REST=1
+ESP_DIR ?= build/esp
+PAYLOAD ?= qemu/payload.bin
-.PHONY: help fetch images kernel loader loader-open hello qemu qemu-open phone prebuilt clean all doctor defconfig config savedefconfig
+.PHONY: help fetch images kernel loader loader-open hello qemu qemu-open phone prebuilt clean all doctor defconfig config savedefconfig esp
help:
@awk '{ if (!/^#/) exit; sub(/^# ?/, ""); print }' Makefile
@@ -98,6 +102,12 @@ phone:
[ ! -f .config ] || tools/hakios-config.py check
XL_SB_DELAY=8 $(RUNNER_BASE) tools/modem-cycle.sh "$(ARGS)" $(SECS)
+# The loader and a payload (make qemu-open makes qemu/payload.bin; xnuloader/mkpayload.py makes any other) as the files an
+# EFI system partition holds, which the loader reads itself: UEFI-native boot. The default tree is made again each time.
+esp:
+ [ "$(ESP_DIR)" != build/esp ] || rm -rf build/esp
+ tools/mkesp.py $(ESP_DIR) $(PAYLOAD)
+
# ---- configuration (configs/, tools/hakios-config.py) ---------------------------------------------------------
defconfig:
tools/hakios-config.py defconfig defconfig $(FRAGMENTS)
diff --git a/ci/github-check.yml b/ci/github-check.yml
index 65f71bd..b011c22 100644
--- a/ci/github-check.yml
+++ b/ci/github-check.yml
@@ -29,6 +29,8 @@ jobs:
run: bash tools/soc-only-changes-test.sh
- name: Configurations - defconfigs, fragments, the arguments made from them
run: python3 tools/hakios-config-test.py
+ - name: The EFI system partition tree is laid out as the loader looks for it
+ run: python3 tools/mkesp-test.py
- name: The kernel's version string is made as it should be
run: python3 tools/kernel-version-test.py
- name: The kernel patch applies to Apple's tree
diff --git a/qemu/run.sh b/qemu/run.sh
index e594139..9b5fbb7 100755
--- a/qemu/run.sh
+++ b/qemu/run.sh
@@ -5,6 +5,8 @@
# default of 1 GB mostly costs host memory)
# QEMU_SMP processor cores of the machine (default 1); the kernel uses as many of them as
# its boot-arg cpus=N says (CMDLINE="cpus=4" for run-ios.sh), one without it
+# QEMU_ESP=1 no loader device: the payload is the file \EFI\hakios\payload.bin on the ESP, which the loader
+# reads itself (UEFI-native boot; what a boot menu or a USB stick does)
# QEMU_EFI, QEMU_VARS the UEFI firmware for aarch64 guests (found by itself where Arch's edk2-aarch64
# puts it, or Debian/Ubuntu's /usr/share/AAVMF/AAVMF_CODE.fd and AAVMF_VARS.fd)
cd "$(dirname "$0")"
@@ -23,10 +25,19 @@ cp "$VARS_SRC" vars.fd 2>/dev/null
# the one built here, or else the one that comes with the repository
L=../xnuloader/loader.efi; [ -f $L ] || L=../prebuilt/loader.efi
mkdir -p esp/EFI/BOOT && cp -u $L esp/EFI/BOOT/BOOTAA64.EFI
+# The payload (kernel, root image, command line) reaches the loader in one of two ways. By default QEMU's loader
+# device puts it in memory at 0xF0000000, as the boot shim does behind Project Silicium's image on the phone.
+# With QEMU_ESP=1 it is not put anywhere: it is the file \EFI\hakios\payload.bin of the ESP, and the loader reads it
+# itself from the volume it was started from -- UEFI-native boot, what a boot menu or a USB stick does (docs/uefi-boot.md).
+PAYLOAD_DEVICE=(-device loader,file=payload.bin,addr=0xF0000000,force-raw=on)
+if [ -n "${QEMU_ESP:-}" ]; then
+ mkdir -p esp/EFI/hakios && cp payload.bin esp/EFI/hakios/payload.bin
+ PAYLOAD_DEVICE=()
+fi
timeout "$T" qemu-system-aarch64 -M virt,gic-version=3 -cpu cortex-a76 -smp ${QEMU_SMP:-1} -m ${QEMU_MEM:-6G} \
-accel tcg,tb-size=${QEMU_TB_MB:-384} \
-drive if=pflash,format=raw,readonly=on,file="$EFI" \
-drive if=pflash,format=raw,file=vars.fd \
-drive file=fat:rw:esp,format=raw,if=virtio \
- -device loader,file=payload.bin,addr=0xF0000000,force-raw=on \
+ "${PAYLOAD_DEVICE[@]}" \
-display none -serial stdio -monitor none -no-reboot "$@" 2>&1
diff --git a/tools/mkesp-test.py b/tools/mkesp-test.py
new file mode 100644
index 0000000..4c6cfca
--- /dev/null
+++ b/tools/mkesp-test.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""tools/mkesp.py: the tree it lays out, and what it refuses before a phone would."""
+import os
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(HERE)
+MKESP = os.path.join(HERE, "mkesp.py")
+MKPAYLOAD = os.path.join(ROOT, "xnuloader", "mkpayload.py")
+failures = []
+
+
+def check(label, ok, detail=""):
+ print("%s %s" % ("ok " if ok else "FAIL", label))
+ if not ok:
+ failures.append(label)
+ if detail:
+ print(" " + str(detail).strip().replace("\n", "\n ")[:400])
+
+
+def run(*args):
+ return subprocess.run([sys.executable, MKESP, *args], capture_output=True, text=True)
+
+
+work = tempfile.mkdtemp(prefix="mkesp-test-")
+try:
+ loader = os.path.join(work, "loader.efi")
+ open(loader, "wb").write(b"MZ" + b"\0" * 62)
+ kernel = os.path.join(work, "kernel")
+ open(kernel, "wb").write(b"\xcf\xfa\xed\xfe" + b"k" * 100)
+ ramdisk = os.path.join(work, "ramdisk")
+ open(ramdisk, "wb").write(b"r" * 300)
+
+ def payload(name, *extra):
+ path = os.path.join(work, name)
+ subprocess.run([sys.executable, MKPAYLOAD, "-o", path, "kernel=" + kernel, "ramdisk=" + ramdisk, "--cmdline", "cpus=1", *extra],
+ check=True, capture_output=True)
+ return path
+
+ good = payload("good.bin", "--kernel-version", "2.1.13-hakios-darwin22.5-sc7280-gabc12345")
+ out = os.path.join(work, "esp")
+ r = run(out, good, "--loader", loader)
+ check("a good payload: exit 0", r.returncode == 0, r.stdout + r.stderr)
+ check("the layout is the one the loader looks for",
+ sorted(os.path.relpath(os.path.join(d, f), out).replace(os.sep, "/") for d, _, fs in os.walk(out) for f in fs) ==
+ ["EFI/BOOT/BOOTAA64.EFI", "EFI/hakios/kernel.ver", "EFI/hakios/payload.bin"])
+ check("the payload is copied byte for byte", open(os.path.join(out, "EFI/hakios/payload.bin"), "rb").read() == open(good, "rb").read())
+ check("the loader is copied byte for byte", open(os.path.join(out, "EFI/BOOT/BOOTAA64.EFI"), "rb").read() == open(loader, "rb").read())
+ check("kernel.ver is text, with the version", open(os.path.join(out, "EFI/hakios/kernel.ver")).read() == "2.1.13-hakios-darwin22.5-sc7280-gabc12345\n")
+ check("it says what the payload holds", "kernel (104)" in r.stdout and "ramdisk (300)" in r.stdout and "kernel.ver=2.1.13" in r.stdout, r.stdout)
+
+ r = run(out, good, "--loader", loader)
+ check("a directory that is not empty is refused", r.returncode != 0 and "not empty" in r.stderr, r.stderr)
+
+ nover = payload("nover.bin", "--no-version")
+ r = run(os.path.join(work, "esp2"), nover, "--loader", loader)
+ check("a payload without kernel.ver: fine, and says unknown", r.returncode == 0 and "unknown" in r.stdout, r.stdout + r.stderr)
+
+ junk = os.path.join(work, "junk.bin")
+ open(junk, "wb").write(os.urandom(4096))
+ r = run(os.path.join(work, "esp3"), junk, "--loader", loader)
+ check("a file that is not a payload is refused", r.returncode != 0 and "XNUP" in r.stderr, r.stderr)
+ check("... and nothing is made", not os.path.exists(os.path.join(work, "esp3")))
+
+ nokernel = os.path.join(work, "nokernel.bin")
+ body = struct.pack("<16sII", b"cmdline", 8, 0) + b"cpus=1\0\0" + b"\0" * 8 + b"\0" * 24
+ open(nokernel, "wb").write(struct.pack("<II", 0x50554E58, len(body)) + body)
+ r = run(os.path.join(work, "esp4"), nokernel, "--loader", loader)
+ check("a payload with no kernel is refused", r.returncode != 0 and "no kernel" in r.stderr, r.stderr)
+
+ big = os.path.join(work, "big.bin")
+ kbody = struct.pack("<16sII", b"kernel", 0, 0) + b"\0" * 24
+ open(big, "wb").write(struct.pack("<II", 0x50554E58, len(kbody)) + kbody + b"\0" * (63 * 1024 * 1024 + 4096))
+ r = run(os.path.join(work, "esp5"), big, "--loader", loader)
+ check("a payload over the loader's 63 MiB is refused, and says why", r.returncode != 0 and "too big" in r.stderr, r.stderr)
+
+ notefi = os.path.join(work, "notefi")
+ open(notefi, "wb").write(b"ELF\0" * 8)
+ r = run(os.path.join(work, "esp6"), good, "--loader", notefi)
+ check("a loader that is not an EFI application is refused", r.returncode != 0 and "MZ" in r.stderr, r.stderr)
+
+ r = run(os.path.join(work, "esp7"), os.path.join(work, "no-such.bin"), "--loader", loader)
+ check("a missing payload is refused", r.returncode != 0 and "no payload at" in r.stderr, r.stderr)
+finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+if failures:
+ sys.exit("mkesp-test: %d FAILED" % len(failures))
+print("mkesp-test: all passed")
diff --git a/tools/mkesp.py b/tools/mkesp.py
new file mode 100644
index 0000000..0cd1c79
--- /dev/null
+++ b/tools/mkesp.py
@@ -0,0 +1,96 @@
+#!/usr/bin/env python3
+"""Lay out an EFI system partition for HakiOS: the loader, and the payload it reads itself.
+
+usage: tools/mkesp.py OUTDIR [PAYLOAD] [--loader FILE]
+
+ OUTDIR the tree to make (it must be empty or not exist): copy it to a FAT32 volume, or serve it to QEMU
+ PAYLOAD the "XNUP" payload made by xnuloader/mkpayload.py (default: qemu/payload.bin, which `make qemu-open` makes)
+ --loader the boot loader (default: xnuloader/loader.efi, else prebuilt/loader.efi)
+
+What it makes:
+ OUTDIR/EFI/BOOT/BOOTAA64.EFI the loader, in the place an AArch64 UEFI boots a removable volume from
+ OUTDIR/EFI/hakios/payload.bin the payload: the kernel, the root image, the command line, kernel.ver
+ OUTDIR/EFI/hakios/kernel.ver the version, as text, so that a person can see what a volume holds
+
+The loader reads \\EFI\\hakios\\payload.bin from the volume it was started from when nobody has put a payload in
+memory (xnuloader/loader.c, load_payload_from_volume). That is UEFI-native boot: a boot menu, a USB stick or an SD
+card starts the kernel, with no fastboot. docs/uefi-boot.md says what this does and does not do on a phone.
+
+It refuses what the loader would refuse, and says so here instead of on a phone's screen: a file that is not a
+payload (no XNUP), a payload with no kernel in it, one that does not fit in the loader's payload region (63 MiB: the
+big iOS system image does not come this way).
+"""
+import argparse
+import os
+import shutil
+import struct
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(HERE)
+MAGIC = 0x50554E58 # "XNUP"
+PAYLOAD_LIMIT = 0x04000000 - 0x100000 # the loader's payload region less the MiB of the panic log
+
+
+def entries(data):
+ """{name: bytes} of an XNUP payload, or a SystemExit with the reason."""
+ if len(data) < 8 or struct.unpack_from("<I", data)[0] != MAGIC:
+ sys.exit("mkesp: not a payload: it does not start with XNUP (make one with xnuloader/mkpayload.py)")
+ size = struct.unpack_from("<I", data, 4)[0]
+ out, at = {}, 8
+ while at + 24 <= min(8 + size, len(data)):
+ name = data[at:at + 16].split(b"\0")[0].decode(errors="replace")
+ length = struct.unpack_from("<I", data, at + 16)[0]
+ if not name:
+ break
+ out[name] = data[at + 24:at + 24 + length]
+ at += 24 + ((length + 15) & ~15)
+ return out
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("outdir")
+ ap.add_argument("payload", nargs="?", default=os.path.join(ROOT, "qemu", "payload.bin"))
+ ap.add_argument("--loader")
+ args = ap.parse_args()
+
+ loader = args.loader
+ if not loader:
+ loader = os.path.join(ROOT, "xnuloader", "loader.efi")
+ if not os.path.isfile(loader):
+ loader = os.path.join(ROOT, "prebuilt", "loader.efi")
+ for what, path in (("loader", loader), ("payload", args.payload)):
+ if not os.path.isfile(path):
+ sys.exit("mkesp: no %s at %s" % (what, path))
+ if os.path.exists(args.outdir) and os.listdir(args.outdir):
+ sys.exit("mkesp: %s is not empty" % args.outdir)
+
+ data = open(args.payload, "rb").read()
+ parts = entries(data)
+ if "kernel" not in parts:
+ sys.exit("mkesp: the payload has no kernel in it (entries: %s)" % (", ".join(sorted(parts)) or "none"))
+ if len(data) > PAYLOAD_LIMIT:
+ sys.exit("mkesp: the payload is %d bytes and the loader's payload region holds %d: the root image is too big for "
+ "this way of booting (the big iOS image goes in over USB, `xl ramdisk`)" % (len(data), PAYLOAD_LIMIT))
+ version = parts.get("kernel.ver", b"").rstrip(b"\0").decode(errors="replace")
+ head = open(loader, "rb").read(2)
+ if head != b"MZ":
+ sys.exit("mkesp: %s is not an EFI application (no MZ)" % loader)
+
+ boot, hakios = (os.path.join(args.outdir, "EFI", d) for d in ("BOOT", "hakios"))
+ os.makedirs(boot, exist_ok=True)
+ os.makedirs(hakios, exist_ok=True)
+ shutil.copyfile(loader, os.path.join(boot, "BOOTAA64.EFI"))
+ open(os.path.join(hakios, "payload.bin"), "wb").write(data)
+ open(os.path.join(hakios, "kernel.ver"), "w", newline="\n").write((version or "unknown") + "\n")
+
+ print("mkesp: %s" % args.outdir)
+ print(" EFI/BOOT/BOOTAA64.EFI %9d bytes the loader" % os.path.getsize(loader))
+ print(" EFI/hakios/payload.bin %9d bytes %s" % (len(data), ", ".join("%s%s" % (k, " (%d)" % len(v) if k != "kernel.ver" else "")
+ for k, v in sorted(parts.items()))))
+ print(" kernel.ver=%s" % (version or "unknown (the payload was made with --no-version)"))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/xnuloader/efi.h b/xnuloader/efi.h
index 14c7b62..2d35c83 100644
--- a/xnuloader/efi.h
+++ b/xnuloader/efi.h
@@ -173,6 +173,39 @@ typedef struct efi_block_io {
efi_status (EFIAPI *flush_blocks)(struct efi_block_io *self);
} efi_block_io;
+/*
+ * Loaded Image, Simple File System and File: how a UEFI application finds a file on the volume it was started
+ * from. The loader uses them to read its payload (the kernel and the small root image) from \EFI\hakios\payload.bin
+ * when none was put in memory for it: the ordinary way a UEFI boot loader boots, from the EFI system partition.
+ * Slots that are not used are void pointers, so that the layouts match the UEFI specification.
+ */
+typedef struct {
+ uint32_t revision; uint32_t pad;
+ efi_handle parent;
+ void *system_table;
+ efi_handle device; /* the device the image was loaded from: the volume to look on */
+} efi_loaded_image; /* (the specification goes on; nothing more is read) */
+
+typedef struct efi_file {
+ uint64_t revision;
+ efi_status (EFIAPI *open)(struct efi_file *self, struct efi_file **file, const char16 *name, uint64_t mode, uint64_t attributes);
+ efi_status (EFIAPI *close)(struct efi_file *self);
+ void *remove;
+ efi_status (EFIAPI *read)(struct efi_file *self, uint64_t *size, void *buffer);
+ void *write, *get_position, *set_position;
+ efi_status (EFIAPI *get_info)(struct efi_file *self, const efi_guid *type, uint64_t *size, void *buffer);
+ void *set_info, *flush;
+} efi_file;
+
+typedef struct efi_simple_fs {
+ uint64_t revision;
+ efi_status (EFIAPI *open_volume)(struct efi_simple_fs *self, efi_file **root);
+} efi_simple_fs;
+
+#define EFI_FILE_MODE_READ 1ULL
+/* EFI_FILE_INFO: a size, then the file's size at offset 8 (the rest -- times, attributes, the name -- is not read) */
+#define EFI_FILE_INFO_FILE_SIZE_OFFSET 8
+
/* Block I/O 2: the same reads, asynchronous -- a token's event is signalled when one is done */
typedef struct {
void *event;
@@ -255,6 +288,9 @@ typedef struct {
#define EFI_BLOCK_IO_GUID { 0x964e5b21, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }
#define EFI_BLOCK_IO2_GUID { 0xa77b2472, 0xe282, 0x4e9f, { 0xa2, 0x45, 0xc2, 0xc0, 0xe2, 0x7b, 0xbc, 0xc1 } }
#define EFI_DEVICE_PATH_GUID { 0x09576e91, 0x6d3f, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }
+#define EFI_LOADED_IMAGE_GUID { 0x5b1b31a1, 0x9562, 0x11d2, { 0x8e, 0x3f, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }
+#define EFI_SIMPLE_FILE_SYSTEM_GUID { 0x964e5b22, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }
+#define EFI_FILE_INFO_GUID { 0x09576e92, 0x6d3f, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } }
#define EFI_PARTITION_INFO_GUID { 0x8cf2f62c, 0xbc9b, 0x4821, { 0x80, 0x8d, 0xec, 0x9e, 0xc4, 0x21, 0xa1, 0xa0 } }
#define QCOM_CHARGER_EX_GUID { 0x6edc8a6d, 0x2663, 0x43cd, { 0x90, 0xff, 0x46, 0x21, 0xff, 0xd1, 0x0d, 0xf5 } }
#define QCOM_CHARGER_GUID { 0x21bfb78b, 0x02ea, 0x4ab7, { 0x99, 0x40, 0xb5, 0x8a, 0x2a, 0xd6, 0x58, 0x29 } }
diff --git a/xnuloader/loader.c b/xnuloader/loader.c
index 9358b31..238ad1d 100644
--- a/xnuloader/loader.c
+++ b/xnuloader/loader.c
@@ -3938,6 +3938,89 @@ ramfb_phone_screen(void)
SCREEN.stride = PHONE_WIDTH * 4;
}
+/*
+ * UEFI-native boot: a payload from the volume the loader was started from.
+ *
+ * On the phone the payload (the kernel, the small root image, the command line) is put in memory at PAYLOAD_BASE
+ * before the loader runs: by the boot shim behind Project Silicium's image (fastboot boot), or by QEMU's loader
+ * device. This is the other way, the one every UEFI boot loader has: when there is no payload in memory, look for
+ * \EFI\hakios\payload.bin on the volume this image was loaded from (the EFI system partition, where
+ * \EFI\BOOT\BOOTAA64.EFI is the loader itself), read it to PAYLOAD_BASE and go on as if it had been there all along.
+ * That is what lets the kernel start from a boot menu, a USB stick or an SD card, without fastboot.
+ *
+ * It prints nothing (the banner has not been drawn yet): volume_payload_bytes and volume_payload_note say what
+ * happened, and efi_main says it under the banner. The file has to fit in the payload region (less the last MiB,
+ * which holds the panic log), and the region has to be free: where a firmware keeps it reserved, the allocation is
+ * refused and the loader goes on without a payload, as it always did.
+ * Only the kernel and a root image that fits in the payload come this way; the big iOS system image does not
+ * (docs/uefi-boot.md says what does).
+ */
+static uint64_t volume_payload_bytes; /* 0: nothing was read; else the payload's size */
+static const char *volume_payload_note; /* why not, if it was looked for */
+
+static int
+load_payload_from_volume(void)
+{
+ static const efi_guid image_guid = EFI_LOADED_IMAGE_GUID, fs_guid = EFI_SIMPLE_FILE_SYSTEM_GUID,
+ info_guid = EFI_FILE_INFO_GUID;
+ static const char16 path[] = u"\\EFI\\hakios\\payload.bin";
+ efi_loaded_image *image = NULL;
+ efi_simple_fs *fs = NULL;
+ efi_file *root = NULL, *file = NULL;
+ uint8_t info[512] __attribute__((aligned(8)));
+ uint64_t info_size = sizeof(info), size, done = 0, pages;
+ uint64_t address = PAYLOAD_BASE;
+
+ if (EFI_ERROR(BS->handle_protocol(IMAGE, &image_guid, (void **)&image)) || image == NULL || image->device == NULL ||
+ EFI_ERROR(BS->handle_protocol(image->device, &fs_guid, (void **)&fs)) || fs == NULL) {
+ volume_payload_note = "the loader was not started from a volume with a file system";
+ return 0;
+ }
+ if (EFI_ERROR(fs->open_volume(fs, &root)) || root == NULL) {
+ volume_payload_note = "the volume cannot be opened";
+ return 0;
+ }
+ if (EFI_ERROR(root->open(root, &file, path, EFI_FILE_MODE_READ, 0)) || file == NULL) {
+ volume_payload_note = "there is no \\EFI\\hakios\\payload.bin on the volume";
+ root->close(root);
+ return 0;
+ }
+ if (EFI_ERROR(file->get_info(file, &info_guid, &info_size, info))) {
+ volume_payload_note = "the size of \\EFI\\hakios\\payload.bin cannot be read";
+ goto close;
+ }
+ size = *(uint64_t *)(info + EFI_FILE_INFO_FILE_SIZE_OFFSET);
+ if (size < sizeof(struct payload_header) || size > PAYLOAD_MAX_SIZE - 0x100000ULL) {
+ volume_payload_note = "\\EFI\\hakios\\payload.bin is empty or does not fit in the payload region (63 MiB)";
+ goto close;
+ }
+ pages = (size + 0xfff) / 0x1000;
+ if (EFI_ERROR(BS->allocate_pages(2 /* AllocateAddress */, 2 /* EfiLoaderData */, pages, &address))) {
+ volume_payload_note = "the payload region is not free (the firmware keeps it reserved)";
+ goto close;
+ }
+ while (done < size) {
+ uint64_t chunk = size - done < 0x100000ULL ? size - done : 0x100000ULL; /* 1 MiB at a time */
+
+ if (EFI_ERROR(file->read(file, &chunk, (void *)(uintptr_t)(PAYLOAD_BASE + done))) || chunk == 0) {
+ volume_payload_note = "\\EFI\\hakios\\payload.bin could not be read to its end";
+ BS->free_pages(PAYLOAD_BASE, pages);
+ goto close;
+ }
+ done += chunk;
+ }
+ if (((const struct payload_header *)PAYLOAD_BASE)->magic != PAYLOAD_MAGIC) {
+ volume_payload_note = "\\EFI\\hakios\\payload.bin is not a payload (no XNUP at its start)";
+ BS->free_pages(PAYLOAD_BASE, pages);
+ goto close;
+ }
+ volume_payload_bytes = size;
+close:
+ file->close(file);
+ root->close(root);
+ return volume_payload_bytes != 0;
+}
+
/*
* The version of the kernel in the payload (the entry kernel.ver, made by xnuloader/mkpayload.py from
* tools/kernel-version.py), or NULL if the payload has none. A look at the payload that changes
@@ -4001,8 +4084,18 @@ efi_main(efi_handle image, efi_system_table *st)
IMAGE = image;
BS->set_watchdog_timer(0, 0, 0, NULL);
+ /* no payload in memory (nobody put one there): the volume this loader came from may have one, as a UEFI boot loader's does */
+ if (((const struct payload_header *)PAYLOAD_BASE)->magic != PAYLOAD_MAGIC) {
+ load_payload_from_volume();
+ }
print("== XNULOADER v3 ==\n");
print_banner();
+ if (volume_payload_bytes != 0) {
+ print("payload: %d bytes from \\EFI\\hakios\\payload.bin on the volume this loader was started from\n",
+ volume_payload_bytes);
+ } else if (volume_payload_note != NULL) {
+ print("payload: none in memory, and %s\n", volume_payload_note);
+ }
print("CurrentEL=%x MIDR=%x MMFR0=%x CNTFRQ=%d image=%x\n", READ_SYSREG(CurrentEL) >> 2, READ_SYSREG(MIDR_EL1),
READ_SYSREG(ID_AA64MMFR0_EL1), READ_SYSREG(CNTFRQ_EL0), (uint64_t)(uintptr_t)&__ImageBase);