Skip to content

Instantly share code, notes, and snippets.

@IntegralPilot
Created September 23, 2026 11:15
Show Gist options
  • Select an option

  • Save IntegralPilot/1ce343c851e463b171ce17bfa8d537bf to your computer and use it in GitHub Desktop.

Select an option

Save IntegralPilot/1ce343c851e463b171ce17bfa8d537bf to your computer and use it in GitHub Desktop.
m1n1 Fuchsia Load script
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
import argparse
import json
from pathlib import Path
import secrets
import shutil
import struct
import subprocess
import sys
def align(value, alignment):
return (value + alignment - 1) & -alignment
def cells(value):
return f"0x{value >> 32:x} 0x{value & 0xffffffff:x}"
def make_dtb(ram_base, ram_size, uart_base, zbi_base, zbi_size, mpidr,
cmdline, aic, uart_irq):
aic_base, aic_size, event_offset = aic
source = f"""/dts-v1/;
/ {{
compatible = "apple,t8122";
#address-cells = <2>;
#size-cells = <2>;
chosen {{
bootargs = {json.dumps(cmdline)};
stdout-path = "/serial@{uart_base:x}";
linux,initrd-start = <{cells(zbi_base)}>;
linux,initrd-end = <{cells(zbi_base + zbi_size)}>;
}};
cpus {{
#address-cells = <2>;
#size-cells = <0>;
cpu@{mpidr:x} {{
device_type = "cpu";
compatible = "apple,m3";
reg = <{cells(mpidr)}>;
}};
}};
memory@{ram_base:x} {{
device_type = "memory";
reg = <{cells(ram_base)} {cells(ram_size)}>;
}};
aic: interrupt-controller@{aic_base:x} {{
compatible = "apple,t8122-aic3";
reg = <{cells(aic_base)} {cells(aic_size)}>,
<{cells(aic_base + event_offset)} 0 4>;
reg-names = "core", "event";
interrupt-controller;
#interrupt-cells = <3>;
#address-cells = <0>;
}};
timer {{
compatible = "arm,armv8-timer";
interrupt-parent = <&aic>;
interrupt-names = "phys", "virt", "hyp-phys", "hyp-virt";
interrupts = <1 2 4>, <1 3 4>, <1 0 4>, <1 1 4>;
}};
serial@{uart_base:x} {{
compatible = "apple,s5l-uart";
reg = <{cells(uart_base)} 0 0x4000>;
reg-io-width = <4>;
interrupt-parent = <&aic>;
interrupts = <0 {uart_irq} 4>;
status = "okay";
}};
}};
"""
return subprocess.run(
["dtc", "-I", "dts", "-O", "dtb"], input=source.encode(),
stdout=subprocess.PIPE, check=True,
).stdout
def read_images(image_path, zbi_path):
image = image_path.read_bytes()
if len(image) < 64 or image[0x38:0x3c] != b"ARM\x64":
raise ValueError("expected an uncompressed Linux ARM64 boot-shim image")
image_mem_size = struct.unpack_from("<Q", image, 16)[0]
if not len(image) <= image_mem_size <= 32 * 1024 * 1024:
raise ValueError("invalid boot-shim memory size (must include BSS)")
zbi = zbi_path.read_bytes()
if len(zbi) < 32:
raise ValueError("truncated ZBI header")
kind, length, extra, flags, _, _, magic, _ = struct.unpack_from("<8I", zbi)
if (kind != 0x544f4f42 or extra != 0x868cf7e6 or
magic != 0xb5781729 or not flags & 0x10000):
raise ValueError("expected a version-1 ZBI container")
if length != len(zbi) - 32 or length % 8:
raise ValueError("ZBI container size mismatch")
return image, image_mem_size, zbi
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("image", type=Path, help="linux-arm64-boot-shim.bin")
parser.add_argument("zbi", type=Path, help="fuchsia.zbi (kernel and boot filesystem)")
parser.add_argument("-b", "--bootargs", default="", help="additional Zircon boot arguments")
args = parser.parse_args()
try:
image, image_mem_size, zbi = read_images(args.image, args.zbi)
except (OSError, ValueError) as error:
parser.error(str(error))
if not shutil.which("dtc"):
parser.error("dtc is required (install device-tree-compiler or dtc)")
if not args.bootargs.isascii() or any(not 32 <= ord(c) < 127 for c in args.bootargs):
parser.error("boot arguments must be printable ASCII")
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from m1n1.proxy import M1N1Proxy, UartInterface
from m1n1.proxyutils import ProxyUtils, bootstrap_port
from m1n1.hv import HV
from m1n1.sysreg import MPIDR_EL1
iface = UartInterface()
iface.dev.write_timeout = 3
proxy = M1N1Proxy(iface, debug=False)
bootstrap_port(iface, proxy)
utils = ProxyUtils(proxy, heap_size=128 * 1024 * 1024)
if utils.adt["/chosen"].chip_id != 0x8122:
raise RuntimeError("this experimental loader is restricted to T8122")
hv = HV(iface, proxy, utils)
hv.init()
uart_base = hv.adt["/arm-io/uart0"].get_reg(0)[0]
arena_size = align(image_mem_size, 2 * 1024 * 1024) + 768 * 1024 * 1024
if utils.heap_top + arena_size + 128 * 1024 * 1024 >= utils.ba.phys_base + utils.ba.mem_size:
raise RuntimeError("insufficient RAM for the guest arena")
hv.load_raw(bytes(arena_size), entryoffset=0)
image_base = align(hv.guest_base, 2 * 1024 * 1024)
dtb_base = align(image_base + image_mem_size, 0x10000)
zbi_base = dtb_base + 0x10000
arena_end = hv.guest_base + arena_size
aic = utils.adt["/arm-io/aic"]
aic_base, aic_size = aic.get_reg(0)
# AIC register access from this EL1 guest must be forwarded at EL2.
hv.trace_irq("apple-uart", utils.adt["/arm-io/uart0"].interrupts[0], 1,
hv.IRQTRACE_IRQ)
cmdline = ("kernel.smp.maxcpus=1 kernel.entropy-mixin=" + secrets.token_hex(64))
if args.bootargs:
cmdline += " " + args.bootargs
if zbi_base + len(zbi) + 256 * 1024 * 1024 >= arena_end:
raise RuntimeError("insufficient room after initrd for kernel allocations")
mpidr = utils.mrs(MPIDR_EL1) & 0xff00ffffff
dtb = make_dtb(image_base, arena_end - image_base, uart_base, zbi_base,
len(zbi), mpidr, cmdline, (aic_base, aic_size, aic.aic_iack_offset),
utils.adt["/arm-io/uart0"].interrupts[0])
if len(dtb) > 0x10000:
raise RuntimeError("guest DTB exceeds its reserved slot")
for address, data in [(image_base, image), (dtb_base, dtb), (zbi_base, zbi)]:
utils.compressed_writemem(address, data, True)
proxy.dc_cvau(address, len(data))
proxy.ic_ivau(image_base, len(image))
hv.entry = image_base
hv.bootargs_off = dtb_base - hv.guest_base
print(f"Fuchsia boot shim at {image_base:#x}, FDT at {dtb_base:#x}")
print("Starting zircon...")
try:
hv.start()
finally:
iface.dev.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment