diff --git a/bin/omarchy-iso-make b/bin/omarchy-iso-make index d1e6673f5..ef8f05c3d 100755 --- a/bin/omarchy-iso-make +++ b/bin/omarchy-iso-make @@ -148,8 +148,9 @@ while [[ $# -gt 0 ]]; do ;; # The release rehearsal: --local-source holds omarchy-pkgs with omarchy and # omarchy-settings pinned the way a release is (test/rehearsal-pins). Those - # two are built from it, under their release names; omarchy-nvim and every - # other package come from edge as published. The ISO ends in -rehearsal. + # two are built from it, under their release names, and omarchy-boot-systemd + # with them where it is there; omarchy-nvim and every other package come + # from edge as published. The ISO ends in -rehearsal. --rehearsal) REHEARSAL=1 shift @@ -174,7 +175,11 @@ if [[ -n $REHEARSAL ]]; then # promotes edge, so the rehearsal takes everything else from edge. OMARCHY_ISO_REF=rehearsal OMARCHY_MIRROR=edge - : "${OMARCHY_LOCAL_PACKAGES:=omarchy-settings omarchy}" + # omarchy-boot-systemd is released in lockstep with them, where the pkgs + # checkout has it. + rehearsal_packages="omarchy-settings omarchy" + [[ ! -d $LOCAL_PKGS_PATH/pkgbuilds/omarchy-boot-systemd ]] || rehearsal_packages+=" omarchy-boot-systemd" + : "${OMARCHY_LOCAL_PACKAGES:=$rehearsal_packages}" fi if [[ -n $LOCAL_OMARCHY_PATH ]]; then diff --git a/builder/build-iso.sh b/builder/build-iso.sh index 8691aa5a3..b0bb991f0 100755 --- a/builder/build-iso.sh +++ b/builder/build-iso.sh @@ -74,8 +74,20 @@ export OMARCHY_RUNTIME_PACKAGE OMARCHY_SETTINGS_PACKAGE OMARCHY_NVIM_PACKAGE # The ones --local-source builds from the mounted checkouts, all three unless # OMARCHY_LOCAL_PACKAGES names fewer; the others come from the channel. The # release rehearsal (--rehearsal) builds only the pinned omarchy and -# omarchy-settings, and takes omarchy-nvim as published, as a release does. -read -ra local_packages <<<"${OMARCHY_LOCAL_PACKAGES:-$OMARCHY_SETTINGS_PACKAGE $OMARCHY_RUNTIME_PACKAGE $OMARCHY_NVIM_PACKAGE}" +# omarchy-settings (and omarchy-boot-systemd, released with them), and takes +# omarchy-nvim as published, as a release does. +# The image boots through Limine's stack: on x86_64 the omarchy-boot package, +# on aarch64 its packages by name. UEFI installs swap it for +# omarchy-boot-systemd. A pkgs checkout that has them builds them with the +# runtime that depends on them. +boot_stack_packages="" +if [[ -d /omarchy-pkgs/pkgbuilds/omarchy-boot-systemd ]]; then + case $OMARCHY_ARCH in + x86_64) boot_stack_packages=" omarchy-boot omarchy-boot-systemd" ;; + aarch64) boot_stack_packages=" omarchy-boot-systemd" ;; + esac +fi +read -ra local_packages <<<"${OMARCHY_LOCAL_PACKAGES:-$OMARCHY_SETTINGS_PACKAGE $OMARCHY_RUNTIME_PACKAGE $OMARCHY_NVIM_PACKAGE$boot_stack_packages}" export OMARCHY_LOCAL_PACKAGES="${local_packages[*]}" # The runtime and settings packages come from one commit and are released in # lockstep, so a build makes both from source; omarchy-nvim may come from the @@ -87,6 +99,7 @@ done for local_package_name in "${local_packages[@]}"; do case $local_package_name in "$OMARCHY_RUNTIME_PACKAGE" | "$OMARCHY_SETTINGS_PACKAGE" | "$OMARCHY_NVIM_PACKAGE") ;; + omarchy-boot | omarchy-boot-systemd) [[ " $boot_stack_packages " == *" $local_package_name "* ]] || { echo "ERROR: this $OMARCHY_ARCH build can't build $local_package_name" >&2; exit 1; } ;; *) echo "ERROR: OMARCHY_LOCAL_PACKAGES names $local_package_name, which this build does not install" >&2; exit 1 ;; esac done @@ -949,6 +962,31 @@ if ! resolved_package_files="$( fi mapfile -t required_package_files <<< "$resolved_package_files" +# UEFI installs swap the image's Limine stack for omarchy-boot-systemd, which +# conflicts with it, so it is resolved in a transaction of its own and kept in +# the mirror next to it. Built locally, it is kept with the other local builds +# below and its dependencies came in with theirs. The installer finishes the +# swap with the runtime's omarchy-boot-switch, so a runtime built from an +# Omarchy checkout without it keeps Limine whatever the channel offers. +boot_swap_package="" +if [[ " ${local_packages[*]} " == *" omarchy-boot-systemd "* && -n ${LOCAL_OMARCHY_BUILD:-} ]]; then + boot_swap_package=omarchy-boot-systemd +elif [[ -d /omarchy-source && ! -f /omarchy-source/bin/omarchy-boot-switch ]]; then + echo "$OMARCHY_ARCH: the Omarchy checkout has no omarchy-boot-switch; UEFI installs will boot Limine" >&2 +elif pacman --config "$online_pacman_conf" --dbpath /tmp/offlinedb -Sp omarchy-boot-systemd >/dev/null 2>&1; then + boot_swap_package=omarchy-boot-systemd + pacman --config "$online_pacman_conf" --noconfirm -Sw omarchy-boot-systemd \ + --cachedir "$offline_mirror_dir/" --dbpath /tmp/offlinedb --needed + if ! swap_package_files="$(pacman --config "$online_pacman_conf" --noconfirm \ + --dbpath /tmp/offlinedb -S --print --print-format '%f' omarchy-boot-systemd)"; then + echo "ERROR: could not resolve the package files of omarchy-boot-systemd" >&2 + exit 1 + fi + mapfile -t -O "${#required_package_files[@]}" required_package_files <<<"$swap_package_files" +else + echo "$OMARCHY_ARCH: no repository offers omarchy-boot-systemd; UEFI installs will boot Limine" >&2 +fi + # The online transaction intentionally excludes packages built from the local # checkouts. Add those exact artifacts back to the keep-set after verifying # that the local build left exactly one file for each selected package name. @@ -1108,6 +1146,27 @@ if ! installable_files="$( echo "ERROR: could not resolve the packages an install can ask for" >&2 exit 1 fi +# The boot swap package is never in the image, and what it adds to it ships. +if [[ -n $boot_swap_package ]]; then + if [[ -n ${LOCAL_OMARCHY_BUILD:-} && " ${local_packages[*]} " == *" omarchy-boot-systemd "* ]]; then + # What it depends on, as built: the channel's database doesn't know it. + swap_depends=() + for archive in "$offline_mirror_dir"/omarchy-boot-systemd-[0-9]*.pkg.tar.*; do + [[ $archive == *.sig ]] && continue + installable_files+=$'\n'"${archive##*/}" + mapfile -t -O "${#swap_depends[@]}" swap_depends < <(bsdtar -xOf "$archive" .PKGINFO | sed -n 's/^depend = //p') + done + (( ${#swap_depends[@]} )) || { echo "ERROR: the omarchy-boot-systemd build names no dependencies" >&2; exit 1; } + else + swap_depends=(omarchy-boot-systemd) + fi + if ! swap_files="$(pacman --config "$online_pacman_conf" --noconfirm \ + --dbpath /tmp/offlinedb -S --print --print-format '%f' "${swap_depends[@]}")"; then + echo "ERROR: could not resolve the systemd-boot stack UEFI installs switch to" >&2 + exit 1 + fi + installable_files+=$'\n'"$swap_files" +fi shipped_list="$build_cache_dir/airootfs/usr/share/omarchy-iso/offline-mirror.shipped" # archlinuxarm-keyring stays too, with its signature: on aarch64 validate_boot # checks the target keyring against them (_validate_package_signing). diff --git a/configs/airootfs/usr/share/omarchy-iso/orchestrator/phases_impl.py b/configs/airootfs/usr/share/omarchy-iso/orchestrator/phases_impl.py index 31a84c527..5d58f803f 100644 --- a/configs/airootfs/usr/share/omarchy-iso/orchestrator/phases_impl.py +++ b/configs/airootfs/usr/share/omarchy-iso/orchestrator/phases_impl.py @@ -1623,19 +1623,75 @@ def _write_phase_progress(ctx: InstallContext, fraction: float) -> None: pass +# ── boot loader choice ─────────────────────────────────────────────────────── + +SYSTEMD_BOOT_LABEL = "Omarchy Boot" +SYSTEMD_BOOT_STACK = "omarchy-boot-systemd" + + +def _boot_loader(ctx: InstallContext) -> str: + """The boot loader this install sets up: systemd-boot, the one Secure Boot + needs, on UEFI machines; Limine on BIOS firmware, which systemd-boot cannot + start. (Apple Silicon is never installed from this image.) Intel Macs keep + Limine too, as omarchy-boot-switch keeps them: their firmware needs testing + with systemd-boot first. OMARCHY_ISO_BOOT_LOADER=limine keeps a UEFI + install on Limine, and an ISO whose mirror has no omarchy-boot-systemd has + no other choice. Decided once per install.""" + state = getattr(ctx, "state", None) + loader = state.get("boot_loader") if isinstance(state, dict) else None + if loader is None: + loader = "limine" + kernels = (getattr(ctx, "user_configuration", None) or {}).get("kernels") or [] + if ( + os.environ.get("OMARCHY_ISO_BOOT_LOADER", "systemd-boot") != "limine" + and platform.machine() in ("x86_64", "aarch64") + and any(not p.name.endswith(".sig") for p in OFFLINE_MIRROR.glob(f"{SYSTEMD_BOOT_STACK}-[0-9]*.pkg.tar.*")) + and arch.has_uefi() + and "linux-t2" not in kernels + and not _is_apple_t2_hardware() + ): + loader = "systemd-boot" + if isinstance(state, dict): + state["boot_loader"] = loader + return loader + + +def _install_systemd_boot_stack(ctx: InstallContext) -> None: + """The image boots through omarchy-boot, Limine's stack. omarchy-boot-systemd + replaces it and conflicts with its packages (omarchy-boot, + limine-mkinitcpio-hook, limine-snapper-sync); --ask=4 answers pacman's + "remove them?" with yes. Runs while the deferred boot hooks are masked, so + nothing builds an initramfs yet: omarchy-boot-switch install does, at the + end. Limine itself, which nothing needs any more, goes too.""" + with _time_step("BOOT.install omarchy-boot-systemd (replaces the Limine stack)"): + subprocess.run( + ["pacman", "--root", str(ctx.target), "--cachedir", str(ctx.target / "var/cache/pacman/pkg"), + "--noconfirm", "--ask=4", "-S", "--needed", SYSTEMD_BOOT_STACK], + check=True, + ) + subprocess.run( + ["pacman", "--root", str(ctx.target), "--noconfirm", "-R", "limine"], + check=False, capture_output=True, + ) + + def _configure_limine_boot(ctx: InstallContext, installer, config) -> None: if not arch.bootloader_enabled(config): return if not arch.is_limine(config): raise RuntimeError("Omarchy installs only support Limine bootloader setup") - info("› installing bootloader (Limine)") + if _boot_loader(ctx) == "systemd-boot": + info("› installing bootloader (systemd-boot)") + _install_systemd_boot_stack(ctx) + else: + info("› installing bootloader (Limine)") if arch.is_pre_mount(config): _install_pre_mounted_limine(ctx) else: _install_limine_omarchy(ctx, installer, config) - info("› writing Limine config") + info("› writing boot config") if arch.is_pre_mount(config): _write_pre_mounted_limine_defaults(ctx) else: @@ -1734,6 +1790,13 @@ def _install_limine_efi( esp_path = "/EFI/BOOT" efi_binary = f"BOOT{_efi_arch_suffix()}.EFI" + if _boot_loader(ctx) == "systemd-boot": + _install_systemd_boot_efi( + ctx, esp_mount=esp_mount, disk=disk, part=part, removable=removable, + pre_state=pre_state, replaced_guids=replaced_guids, + ) + return + limine_path = ctx.target / "usr" / "share" / "limine" source_name = f"BOOT{_efi_arch_suffix()}.EFI" target_dir = Path(esp_mount) / esp_path.lstrip("/") @@ -1752,6 +1815,35 @@ def _install_limine_efi( ) +def _install_systemd_boot_efi( + ctx: InstallContext, + *, + esp_mount: str, + disk: Path, + part: int, + removable: bool = False, + pre_state: dict | None = None, + replaced_guids: set[str] | None = None, +) -> None: + """systemd-boot at \\EFI\\systemd\\, where omarchy-boot-switch install keeps + it, with its "Omarchy Boot" entry first. A removable install takes only the + fallback path, which install writes, and no NVRAM entry.""" + arch_name = _efi_arch_suffix().lower() + source = ctx.target / "usr" / "lib" / "systemd" / "boot" / "efi" / f"systemd-boot{arch_name}.efi" + if removable: + _copy_required(source, ctx.target / esp_mount.lstrip("/") / "EFI" / "BOOT" / f"BOOT{_efi_arch_suffix()}.EFI") + return + _copy_required(source, ctx.target / esp_mount.lstrip("/") / "EFI" / "systemd" / f"systemd-boot{arch_name}.efi") + _register_limine_efi_entry( + disk, part, _systemd_boot_loader(), pre_state=pre_state, label=SYSTEMD_BOOT_LABEL, + replaced_guids=replaced_guids, + ) + + +def _systemd_boot_loader() -> str: + return f"\\EFI\\systemd\\systemd-boot{_efi_arch_suffix().lower()}.efi" + + def _limine_efi_loader(esp_path: str, efi_binary: str) -> str: """The loader path a "Limine" boot entry starts, as efibootmgr --loader takes it: \\EFI\\limine\\limine_x64.efi for the default esp_path.""" @@ -1764,6 +1856,7 @@ def _register_limine_efi_entry( loader: str, *, pre_state: dict | None = None, + label: str = "Limine", replaced_guids: set[str] | None = None, ) -> None: pre_state = pre_state or _read_efibootmgr() @@ -1771,7 +1864,8 @@ def _register_limine_efi_entry( # Every write below would be refused the same way. _warn_boot_entry_refused( f"The EFI variable store cannot be read ({pre_state['unreadable']}), " - "so no boot entry can be written" + "so no boot entry can be written", + label, ) return # An entry identical to the one a create would add (active, labelled @@ -1790,12 +1884,12 @@ def _register_limine_efi_entry( stale = [ num for num, text in pre_state["entries"].items() - if _is_stale_limine_entry(text, replaced, esp) + if _is_stale_limine_entry(text, replaced, esp, labels=("Limine", SYSTEMD_BOOT_LABEL)) ] identical = [ num for num, text in pre_state["entries"].items() - if _is_limine_entry_for(text, esp, loader) and num not in pre_state.get("inactive", ()) + if _is_limine_entry_for(text, esp, loader, label) and num not in pre_state.get("inactive", ()) ] deleted: list[str] = [] if stale: @@ -1810,9 +1904,9 @@ def _register_limine_efi_entry( deleted.append(num) if identical: limine_num = identical[0] - info(f"› Reusing the 'Limine' boot entry Boot{limine_num}, which already starts this loader") + info(f"› Reusing the '{label}' boot entry Boot{limine_num}, which already starts this loader") else: - created = _create_limine_efi_entry(disk, part, loader) + created = _create_limine_efi_entry(disk, part, loader, label) detail = (created.stderr or "").strip() if created.returncode != 0: # Attach the reason to the failure. efibootmgr's stderr did reach @@ -1821,7 +1915,7 @@ def _register_limine_efi_entry( # status, so the traceback people paste into a report says nothing # about why. reason = f"efibootmgr --create exited {created.returncode}" - _warn_boot_entry_refused(f"{reason}: {detail}" if detail else reason) + _warn_boot_entry_refused(f"{reason}: {detail}" if detail else reason, label) return if detail: error(f"efibootmgr: {detail}") @@ -1836,21 +1930,23 @@ def _register_limine_efi_entry( if post_state.get("unreadable"): _warn_boot_entry_refused( "efibootmgr --create exited 0 but the boot entries cannot be read back " - f"({post_state['unreadable']}), so BootOrder and BootNext are left alone" + f"({post_state['unreadable']}), so BootOrder and BootNext are left alone", + label, ) return new_limine = sorted( [ num - for num in _find_label_entries(post_state["entries"], "Limine") + for num in _find_label_entries(post_state["entries"], label) if num not in pre_state["entries"] or num in deleted ], - key=lambda num: not _is_limine_entry_for(post_state["entries"][num], esp, loader), + key=lambda num: not _is_limine_entry_for(post_state["entries"][num], esp, loader, label), ) if not new_limine: _warn_boot_entry_refused( - "efibootmgr --create exited 0 but no 'Limine' entry is registered, so this " - "firmware discarded the variable as soon as it was written" + f"efibootmgr --create exited 0 but no '{label}' entry is registered, so this " + "firmware discarded the variable as soon as it was written", + label, ) return limine_num = new_limine[0] @@ -1891,7 +1987,7 @@ def _register_limine_efi_entry( # of the list, not its boot route. order_detail = (ordered.stderr or "").strip() or f"exit status {ordered.returncode}" error( - "Warning: the 'Limine' boot entry was registered but this firmware would " + f"Warning: the '{label}' boot entry was registered but this firmware would " f"not reorder BootOrder to put it first ({order_detail}). Omarchy is reachable " "from the firmware boot menu (F11, F12 or Esc on most boards); move it to " "the top of the firmware's own boot priority list to make it the default." @@ -1907,20 +2003,20 @@ def _register_limine_efi_entry( if nexted.returncode != 0: next_detail = (nexted.stderr or "").strip() or f"exit status {nexted.returncode}" error( - f"Warning: this firmware would not set BootNext to the 'Limine' entry ({next_detail}). " + f"Warning: this firmware would not set BootNext to the '{label}' entry ({next_detail}). " "If the first reboot starts another system, pick Omarchy from the firmware " "boot menu (F11, F12 or Esc on most boards)." ) -def _create_limine_efi_entry(disk: Path, part: int, loader: str) -> subprocess.CompletedProcess: +def _create_limine_efi_entry(disk: Path, part: int, loader: str, label: str = "Limine") -> subprocess.CompletedProcess: return subprocess.run( [ "efibootmgr", "--create", "--disk", str(disk), "--part", str(part), - "--label", "Limine", + "--label", label, "--loader", loader, "--unicode", "--verbose", @@ -1932,7 +2028,7 @@ def _create_limine_efi_entry(disk: Path, part: int, loader: str) -> subprocess.C ) -def _warn_boot_entry_refused(reason: str) -> None: +def _warn_boot_entry_refused(reason: str, label: str = "Limine") -> None: """Registration failed. Report it and carry on to the removable-media route. Firmware that refuses a boot-variable write still boots this install from @@ -1944,7 +2040,7 @@ def _warn_boot_entry_refused(reason: str) -> None: refuses to finish when both routes are missing. """ error( - f"Warning: this firmware would not register a 'Limine' UEFI boot entry. {reason}. " + f"Warning: this firmware would not register a '{label}' UEFI boot entry. {reason}. " f"The install continues: where Omarchy writes EFI/BOOT/BOOT{_efi_arch_suffix()}.EFI on an EFI " "partition of its own, firmware takes that path when nothing in NVRAM matches. " "The boot check at the end of the install stops an install that ends up with " @@ -2052,6 +2148,12 @@ def _write_limine_defaults( f"pre-built UKI could not unlock the root: {cmdline!r}" ) + if _boot_loader(ctx) == "systemd-boot": + # /etc/kernel/cmdline is the whole cmdline there: no Limine drop-in + # adds the console parameter, so the complete value goes in. + _write_systemd_boot_cmdline(ctx, kernel_cmdline_val, esp_mount=esp_mount, enable_fallback=enable_fallback) + return + default_text = _limine_template(ctx, "default.conf").read_text() default_text = default_text.replace("@@CMDLINE@@", cmdline) default_text = re.sub(r'^ESP_PATH=.*$', f'ESP_PATH="{esp_mount}"', default_text, flags=re.MULTILINE) @@ -2085,6 +2187,26 @@ def _write_limine_defaults( shutil.copy2(_limine_template(ctx, "limine.conf"), limine_conf) +def _write_systemd_boot_cmdline( + ctx: InstallContext, cmdline: str, *, esp_mount: str, enable_fallback: bool | None +) -> None: + """systemd-boot's boot images take /etc/kernel/cmdline, then every + /etc/cmdline.d/*.conf (omarchy-boot-sync). Where the ESP is mounted and + whether the firmware's fallback path is this install's wait for + finalize_systemd_boot, as Limine's ESP_PATH waits in /etc/default/limine.""" + kernel_cmdline = ctx.target / "etc" / "kernel" / "cmdline" + kernel_cmdline.parent.mkdir(parents=True, exist_ok=True) + kernel_cmdline.write_text(cmdline + "\n") + ctx.state["boot_fallback"] = True if enable_fallback is None else enable_fallback + ctx.state["boot_esp_mount"] = esp_mount + + if platform.machine() == "aarch64": + # As on Limine: the console on the screen, not the firmware's serial port. + console_conf = ctx.target / "etc" / "cmdline.d" / AARCH64_CONSOLE_CONF + console_conf.parent.mkdir(parents=True, exist_ok=True) + console_conf.write_text("console=tty0 acpi=nospcr\n") + + def _installer_esp_mount(installer) -> str: if efi_partition := installer._get_efi_partition(): if efi_partition.mountpoint: @@ -2130,6 +2252,14 @@ def _limine_template(ctx: InstallContext, filename: str) -> Path: # The kernel-removal hooks stay live: they only prune Limine entries, which is # exactly what ptl-kernel.sh's "pacman -Rdd linux" needs. TARGET_DEFERRED_BOOT_HOOKS = ("90-mkinitcpio-install.hook",) +# On systemd-boot the removal hook is omarchy-boot-systemd's, which updates the +# boot store: that store does not exist until finalize_systemd_boot, so the +# hook could only fail (n1x.sh drops the stock kernels), and is deferred too. +SYSTEMD_BOOT_DEFERRED_HOOKS = TARGET_DEFERRED_BOOT_HOOKS + ("60-mkinitcpio-remove.hook",) + + +def _target_deferred_boot_hooks(ctx: InstallContext) -> tuple[str, ...]: + return SYSTEMD_BOOT_DEFERRED_HOOKS if _boot_loader(ctx) == "systemd-boot" else TARGET_DEFERRED_BOOT_HOOKS def _drop_archinstall_zram_conf(ctx: InstallContext) -> None: @@ -2466,7 +2596,7 @@ def _find_label_entries(entries: dict[str, str], needle: str) -> list[str]: return [num for num, label in entries.items() if needle.lower() in label.lower()] -def _is_limine_entry_for(entry: str, guid: str, loader: str) -> bool: +def _is_limine_entry_for(entry: str, guid: str, loader: str, label_name: str = "Limine") -> bool: """Whether a `efibootmgr --verbose` entry is the one _register_limine_efi_entry creates: labelled "Limine", starting `loader` from the partition with GPT GUID `guid`. The listing reads @@ -2477,7 +2607,7 @@ def _is_limine_entry_for(entry: str, guid: str, loader: str) -> bool: label, _, path = entry.lower().partition("\t") loader = re.escape(loader.lower()) return ( - label.strip() == "limine" + label.strip() == label_name.lower() and bool(guid) and guid in path and re.search(rf"(\)/{loader}|file\({loader}\))(?![\w.-])", path) is not None ) @@ -2499,14 +2629,17 @@ def _disk_partition_guids(disk: Path) -> set[str]: return {line.strip().lower() for line in res.stdout.splitlines() if line.strip()} -def _is_stale_limine_entry(entry: str, replaced_guids: set[str], current_esp: str) -> bool: - """Whether an entry is a "Limine" boot entry pointing to a GPT partition - that this install just wiped on the target disk (never touching entries for - other or temporarily disconnected disks).""" +def _is_stale_limine_entry( + entry: str, replaced_guids: set[str], current_esp: str, *, labels: tuple[str, ...] = ("Limine",) +) -> bool: + """Whether an entry is a "Limine" boot entry (or one labelled any of + `labels`, such as an earlier systemd-boot install's "Omarchy Boot") + pointing to a GPT partition that this install just wiped on the target disk + (never touching entries for other or temporarily disconnected disks).""" if not replaced_guids: return False label, _, _ = entry.lower().partition("\t") - if label.strip() != "limine": + if label.strip() not in {name.lower() for name in labels}: return False guid = _entry_partition_guid(entry) return bool(guid) and guid != current_esp and guid in replaced_guids @@ -2875,11 +3008,12 @@ def run_system_finalizer(ctx: InstallContext) -> None: if _runtime_populates_target_keyring(ctx.target): stop_target_keyring_init(ctx) - _mask_mkinitcpio_pacman_hooks(ctx, ctx.target, TARGET_DEFERRED_BOOT_HOOKS) + deferred = _target_deferred_boot_hooks(ctx) + _mask_mkinitcpio_pacman_hooks(ctx, ctx.target, deferred) try: _run_target_setup_command(ctx, cmd) finally: - _unmask_mkinitcpio_pacman_hooks(ctx, ctx.target, TARGET_DEFERRED_BOOT_HOOKS) + _unmask_mkinitcpio_pacman_hooks(ctx, ctx.target, deferred) # ───────────────────────────────────────────────────────────────────────────── @@ -2994,18 +3128,38 @@ def run_oem_setup(ctx: InstallContext) -> None: shutil.rmtree(staged, ignore_errors=True) staged.mkdir(parents=True) staged.chmod(0o700) + systemd_boot = _boot_loader(ctx) == "systemd-boot" try: for script in oem_scripts(ctx): info(f"› OEM setup: {script.name}") shutil.copyfile(script, staged / script.name) + command = ["/bin/bash", f"/{OEM_SCRIPTS_TARGET_DIR}/{script.name}"] try: - _run_target_setup_command(ctx, ["/bin/bash", f"/{OEM_SCRIPTS_TARGET_DIR}/{script.name}"]) + if systemd_boot: + _run_target_setup_command(ctx, _with_boot_store(ctx, command), private_mounts=True) + else: + _run_target_setup_command(ctx, command) except subprocess.CalledProcessError as exc: raise RuntimeError(f"OEM setup script {script.name} exited with status {exc.returncode}") from exc finally: shutil.rmtree(staged, ignore_errors=True) +def _with_boot_store(ctx: InstallContext, command: list[str]) -> list[str]: + """A target command that runs with the boot store mounted, as it is on the + booted system. omarchy-boot-systemd's pacman hooks rebuild the boot images + into it when a package changes what they are built from (a kernel, + firmware, a DKMS module), and fail without it while pacman still exits 0: + the machine would ship boot images without the change. finalize_systemd_boot's + omarchy-boot-switch install unmounted the store again. Run with + private_mounts, so the mount goes with the command's mount namespace.""" + return [ + "env", f"OMARCHY_BOOT_ESP={_systemd_boot_esp_mount(ctx)}", "/bin/bash", "-c", + 'mount /var/lib/omarchy/boot || { echo "the boot store at /var/lib/omarchy/boot would not mount" >&2; exit 1; }; exec "$@"', + "with-boot-store", *command, + ] + + # build-iso.sh bundles the build for the CPU the ISO runs on, and only for a # runtime whose setup unpacks it; with none bundled there is nothing to keep. def _stage_node_tarball(provisioning_dir) -> None: @@ -3058,11 +3212,16 @@ def _stage_provisioning_luks_unlock(ctx: InstallContext, provisioning_dir) -> No keyfile.write_text(password) keyfile.chmod(0o600) - cmdline_dropin = ctx.target / "etc/limine-entry-tool.d/99-omarchy-provisioning-unlock.conf" - cmdline_dropin.parent.mkdir(parents=True, exist_ok=True) - cmdline_dropin.write_text( - 'KERNEL_CMDLINE[default]+=" cryptkey=rootfs:/etc/omarchy/provisioning.key"\n' - ) + if _boot_loader(ctx) == "systemd-boot": + cmdline_dropin = ctx.target / "etc/cmdline.d/99-omarchy-provisioning-unlock.conf" + cmdline_dropin.parent.mkdir(parents=True, exist_ok=True) + cmdline_dropin.write_text("cryptkey=rootfs:/etc/omarchy/provisioning.key\n") + else: + cmdline_dropin = ctx.target / "etc/limine-entry-tool.d/99-omarchy-provisioning-unlock.conf" + cmdline_dropin.parent.mkdir(parents=True, exist_ok=True) + cmdline_dropin.write_text( + 'KERNEL_CMDLINE[default]+=" cryptkey=rootfs:/etc/omarchy/provisioning.key"\n' + ) files_dropin = ctx.target / PROVISION_KEY_DROPIN files_dropin.parent.mkdir(parents=True, exist_ok=True) @@ -3230,6 +3389,70 @@ def _drop_initramfs_modules_the_kernel_lacks(ctx: InstallContext) -> None: ) +def finalize_boot(ctx: InstallContext) -> None: + if _boot_loader(ctx) == "systemd-boot": + finalize_systemd_boot(ctx) + else: + finalize_limine_boot(ctx) + + +def _skip_unused_t2_preset(ctx: InstallContext) -> None: + selected_kernels = ctx.user_configuration.get("kernels") or [] + if "linux-t2" not in selected_kernels and not _is_apple_t2_hardware(): + for preset in ("linux-t2.preset",): + path = ctx.target / "etc" / "mkinitcpio.d" / preset + if path.exists(): + path.unlink() + info(f"› not Apple T2 hardware: skipped {preset}") + + +def _systemd_boot_esp_mount(ctx: InstallContext) -> str: + """The ESP where this install mounted it: /efi for an unencrypted install + into free space. The runtime finds it there itself from then on.""" + return ctx.state.get("boot_esp_mount") or _boot_intent(ctx)["esp_mount"] + + +def finalize_systemd_boot(ctx: InstallContext) -> None: + """Build and publish the boot images once target setup has written every + boot drop-in (hibernation, hardware quirks, the provisioning unlock). + omarchy-boot-switch install does it in the target, the way a factory reset + of this install will: the boot store, mkinitcpio, a UKI per kernel with + snapshot profiles, loader.conf and the fallback loader. The pre-built UKI + is Limine's fast path and isn't used: the boot images carry Omarchy's own + snapshot and restore hooks, which it lacks.""" + _skip_unused_t2_preset(ctx) + + snapper_root = ctx.target / "etc" / "snapper" / "configs" / "root" + if not snapper_root.exists(): + raise RuntimeError(f"{snapper_root} missing") + kernel_cmdline = ctx.target / "etc" / "kernel" / "cmdline" + if "root=" not in (kernel_cmdline.read_text() if kernel_cmdline.is_file() else ""): + raise RuntimeError(f"{kernel_cmdline} has no root=") + + _drop_initramfs_modules_the_kernel_lacks(ctx) + + command = ["arch-chroot", str(ctx.target), "env", f"OMARCHY_BOOT_ESP={_systemd_boot_esp_mount(ctx)}", + "omarchy-boot-switch", "install", "--no-efi-register"] + if not ctx.state.get("boot_fallback", True): + command.append("--no-fallback") + # A selected kernel other than the image's boots first, as on Limine. + prebuilt_kernel_file = ctx.target / "var" / "lib" / "omarchy-iso" / "prebuilt-uki.kernel" + image_kernel = prebuilt_kernel_file.read_text().strip() if prebuilt_kernel_file.is_file() else "linux-omarchy" + selected_kernels = ctx.user_configuration.get("kernels") or [] + selected = next((k for k in selected_kernels if k != image_kernel and k in _installed_kernels(ctx)), None) + if selected: + command += ["--prefer", selected] + info(f"› {selected} boots first") + with _time_step("BOOT.omarchy-boot-switch install (boot images built on this machine)"): + subprocess.run(command, check=True) + + subprocess.run( + ["btrfs", "quota", "disable", str(ctx.target)], + check=False, + capture_output=True, + ) + + def finalize_limine_boot(ctx: InstallContext) -> None: """Finalize Limine after target system setup has written all dynamic boot drop-ins (hibernation, hardware quirks, protected-mode ESP settings). @@ -3239,12 +3462,7 @@ def finalize_limine_boot(ctx: InstallContext) -> None: # Skip the linux-t2 mkinitcpio work on machines that did not select it. selected_kernels = ctx.user_configuration.get("kernels") or [] - if "linux-t2" not in selected_kernels and not _is_apple_t2_hardware(): - for preset in ("linux-t2.preset",): - path = ctx.target / "etc" / "mkinitcpio.d" / preset - if path.exists(): - path.unlink() - info(f"› not Apple T2 hardware: skipped {preset}") + _skip_unused_t2_preset(ctx) default_limine = ctx.target / "etc" / "default" / "limine" if not default_limine.exists(): @@ -3511,7 +3729,7 @@ def finalize_boot_and_user(ctx: InstallContext) -> None: The user finalizer's chroot runs in a private mount namespace so the two arch-chroots do not tear down each other's /proc, /sys and /dev.""" if ctx.defer_provisioning or os.environ.get("OMARCHY_SERIAL_FINALIZE") == "1": - finalize_limine_boot(ctx) + finalize_boot(ctx) run_chroot_finalizer(ctx) return @@ -3528,7 +3746,7 @@ def _run_user_buffered() -> None: errors: list[BaseException] = [] with ThreadPoolExecutor(max_workers=2) as pool: - boot = pool.submit(finalize_limine_boot, ctx) + boot = pool.submit(finalize_boot, ctx) user = pool.submit(_run_user_buffered) for future in (boot, user): try: @@ -3899,8 +4117,91 @@ def validate_boot(ctx: InstallContext) -> None: boot = _boot_intent(ctx) storage = _storage_intent(ctx) - esp_mount = ctx.target / boot["esp_mount"].lstrip("/") + if _boot_loader(ctx) == "systemd-boot": + _validate_systemd_boot(ctx, boot, storage, ctx.target / _systemd_boot_esp_mount(ctx).lstrip("/")) + else: + _validate_limine_boot(ctx, boot, storage, ctx.target / boot["esp_mount"].lstrip("/")) + if ctx.is_protected: + _validate_pre_mounted_filesystems(ctx) + + if ctx.defer_provisioning: + _validate_provisioning_state(ctx) + + _validate_package_signing(ctx) + _join_luks_keyslot_enroll(ctx) + + +def _systemd_boot_ukis(ctx: InstallContext, esp_mount: Path) -> list[Path]: + """This install's boot images on the ESP: omarchy--*.efi + (omarchy-boot-sync).""" + machine_id = (ctx.target / "etc" / "machine-id").read_text().strip() + return sorted((esp_mount / "EFI" / "Linux").glob(f"omarchy-{machine_id[:8]}-*.efi")) + + +def _systemd_boot_uki_cmdlines(ctx: InstallContext, esp_mount: Path) -> list[str]: + """Every boot image's embedded cmdline. An image whose cmdline cannot be + read is a damaged one, and refused rather than skipped.""" + from .uki_cmdline import read_cmdline + cmdlines = [] + for uki in _systemd_boot_ukis(ctx, esp_mount): + cmdline = read_cmdline(uki) if uki.stat().st_size else None + if not cmdline: + raise RuntimeError(f"{uki} is empty or has no readable cmdline") + cmdlines.append(cmdline) + return cmdlines + + +def _validate_systemd_boot(ctx: InstallContext, boot: dict, storage: dict, esp_mount: Path) -> None: + """omarchy-boot-switch install verified the boot images against the + installed kernels; this checks what the firmware will find: systemd-boot, + its config, a boot image for the kernel this install boots carrying the + install's cmdline, the boot store's fstab line, and a route to the loader.""" + if not arch.has_uefi(): + raise RuntimeError("systemd-boot install on BIOS firmware") + # omarchy-boot-switch install always puts it there, and the "Omarchy Boot" + # entry starts it. The fallback path can't stand in: on a shared ESP it may + # be another system's loader. + loader = esp_mount / "EFI" / "systemd" / f"systemd-boot{_efi_arch_suffix().lower()}.efi" + if not (loader.is_file() and loader.stat().st_size): + raise RuntimeError(f"{loader} missing or empty") + if not (esp_mount / "loader" / "loader.conf").is_file(): + raise RuntimeError(f"{esp_mount / 'loader' / 'loader.conf'} missing") + + kernel = storage.get("kernel") or (ctx.user_configuration.get("kernels") or ["linux-omarchy"])[0] + installed_kernels = _installed_kernels(ctx) + candidates = [kernel] if kernel in installed_kernels else installed_kernels or [kernel] + machine_id = (ctx.target / "etc" / "machine-id").read_text().strip() + names = tuple(f"omarchy-{machine_id[:8]}-{name}-" for name in candidates) + ukis = [uki for uki in _systemd_boot_ukis(ctx, esp_mount) if uki.stat().st_size] + if not any(uki.name.startswith(names) for uki in ukis): + raise RuntimeError(f"no boot image for {' / '.join(candidates)} in {esp_mount / 'EFI' / 'Linux'}") + + cmdlines = _systemd_boot_uki_cmdlines(ctx, esp_mount) + if not cmdlines or not all("root=" in cmdline for cmdline in cmdlines): + raise RuntimeError("a boot image carries no cmdline with root=") + # As on Limine: every N1x entry keeps the console off the SPCR serial port. + if _installed_arm_platform(ctx) == "n1x": + for cmdline in cmdlines: + missing = [param for param in N1X_REQUIRED_CMDLINE if param not in cmdline.split()] + if missing: + raise RuntimeError(f"a boot image's cmdline lacks {' '.join(missing)}; its console would go to the SPCR serial port") + if ctx.encrypt and not all("cryptdevice=" in cmdline for cmdline in cmdlines): + raise RuntimeError("encrypted install but a boot image's cmdline has no cryptdevice=") + + fstab = ctx.target / "etc" / "fstab" + if "/var/lib/omarchy/boot" not in (fstab.read_text() if fstab.is_file() else ""): + raise RuntimeError(f"{fstab} does not mount the boot store at /var/lib/omarchy/boot") + + _validate_uefi_boot_routes( + esp_mount, + loader=_systemd_boot_loader(), + fallback_is_ours=not ctx.is_protected or bool(boot.get("enable_fallback")), + label=SYSTEMD_BOOT_LABEL, + ) + + +def _validate_limine_boot(ctx: InstallContext, boot: dict, storage: dict, esp_mount: Path) -> None: limine_conf = esp_mount / "limine.conf" if not limine_conf.exists(): raise RuntimeError(f"{limine_conf} missing") @@ -3956,15 +4257,6 @@ def validate_boot(ctx: InstallContext) -> None: fallback_is_ours=not ctx.is_protected or bool(boot.get("enable_fallback")), ) - if ctx.is_protected: - _validate_pre_mounted_filesystems(ctx) - - if ctx.defer_provisioning: - _validate_provisioning_state(ctx) - - _validate_package_signing(ctx) - _join_luks_keyslot_enroll(ctx) - OFFLINE_MIRROR = Path("/var/cache/omarchy/mirror/offline") @@ -4138,7 +4430,7 @@ def _validate_linux_boot_entry(esp_mount: Path, config_text: str, encrypted: boo raise RuntimeError(f"{esp_mount / 'limine.conf'} has no bootable Omarchy Linux entry with a kernel and initramfs") -def _validate_uefi_boot_routes(esp_mount: Path, *, loader: str, fallback_is_ours: bool) -> None: +def _validate_uefi_boot_routes(esp_mount: Path, *, loader: str, fallback_is_ours: bool, label: str = "Limine") -> None: """Check the two ways firmware can reach this install, and insist on one. The named "Limine" boot variable is the route we prefer and the one @@ -4173,15 +4465,15 @@ def starts_this_install(num: str) -> bool: if num in state.get("inactive", ()): return False if esp: - return _is_limine_entry_for(entries[num], esp, loader) - label, _, path = entries[num].lower().partition("\t") - return label.strip() == "limine" and (not path or loader.lower() in path) + return _is_limine_entry_for(entries[num], esp, loader, label) + name, _, path = entries[num].lower().partition("\t") + return name.strip() == label.lower() and (not path or loader.lower() in path) has_entry = any(starts_this_install(num) for num in entries) no_entry = ( f"the EFI variable store cannot be read ({state['unreadable']})" - if state.get("unreadable") else "efibootmgr has no 'Limine' entry" + if state.get("unreadable") else f"efibootmgr has no '{label}' entry" ) if not has_entry and not has_fallback: fallback_state = "is not written by this install" if fallback_present else "is missing or empty" @@ -4192,7 +4484,7 @@ def starts_this_install(num: str) -> bool: if not has_entry and state.get("unreadable"): error( - f"Warning: {no_entry}, so this install has no 'Limine' UEFI boot entry. " + f"Warning: {no_entry}, so this install has no '{label}' UEFI boot entry. " f"Omarchy boots from {fallback_binary.name} on its own EFI partition, " "which firmware takes when nothing in NVRAM matches." ) @@ -4200,7 +4492,7 @@ def starts_this_install(num: str) -> bool: if not has_entry: error( - "Warning: this firmware discarded the 'Limine' UEFI boot entry during " + f"Warning: this firmware discarded the '{label}' UEFI boot entry during " f"the install. Omarchy still boots from {fallback_binary.name} on its " "own EFI partition. If the machine starts another OS instead, pick the " "Omarchy disk from the firmware boot menu (F11, F12 or Esc on most " @@ -4213,16 +4505,15 @@ def starts_this_install(num: str) -> bool: if not has_fallback and fallback_present: error( f"Warning: {fallback_binary} belongs to another system on this shared EFI " - "partition and was left alone, so this install depends on the 'Limine' " + f"partition and was left alone, so this install depends on the '{label}' " "UEFI boot entry alone. It boots now. If firmware later clears NVRAM, " "re-add the entry with efibootmgr from a live session." ) elif not has_fallback: error( f"Warning: {fallback_binary} was not deployed, so this install depends " - "on the 'Limine' UEFI boot entry alone. It boots now. If firmware " - "later clears NVRAM, reinstall the loader from a live session with " - "'limine-install --fallback'." + f"on the '{label}' UEFI boot entry alone. It boots now. If firmware " + "later clears NVRAM, re-add the entry with efibootmgr from a live session." ) @@ -4253,11 +4544,16 @@ def _validate_provisioning_state(ctx: InstallContext) -> None: for required in (provisioning_dir / "luks-key", ctx.target / PROVISION_KEYFILE): if not required.exists(): raise RuntimeError(f"encrypted deferred-provisioning install but {required} is missing") - limine_conf_text = ( - ctx.target / _boot_intent(ctx)["esp_mount"].lstrip("/") / "limine.conf" - ).read_text() - if "cryptkey=rootfs:" not in limine_conf_text: - raise RuntimeError("encrypted deferred-provisioning install but limine.conf has no cryptkey= for auto-unlock") + if _boot_loader(ctx) == "systemd-boot": + esp_mount = ctx.target / _systemd_boot_esp_mount(ctx).lstrip("/") + if not any("cryptkey=rootfs:" in cmdline for cmdline in _systemd_boot_uki_cmdlines(ctx, esp_mount)): + raise RuntimeError("encrypted deferred-provisioning install but no boot image has cryptkey= for auto-unlock") + else: + limine_conf_text = ( + ctx.target / _boot_intent(ctx)["esp_mount"].lstrip("/") / "limine.conf" + ).read_text() + if "cryptkey=rootfs:" not in limine_conf_text: + raise RuntimeError("encrypted deferred-provisioning install but limine.conf has no cryptkey= for auto-unlock") def _assert_boot_hooks_restored(ctx: InstallContext) -> None: @@ -4270,7 +4566,7 @@ def _assert_boot_hooks_restored(ctx: InstallContext) -> None: cleanup_target_hook_masks(ctx) hooks_dir = ctx.target / "etc/pacman.d/hooks" - for name in TARGET_DEFERRED_BOOT_HOOKS: + for name in _target_deferred_boot_hooks(ctx): path = hooks_dir / name if _is_devnull_symlink(path): raise RuntimeError(f"{path} is still masked to /dev/null") @@ -4446,6 +4742,7 @@ def create_factory_snapshot(ctx: InstallContext) -> None: "var/lib/omarchy/provisioning/luks-key", "etc/omarchy/provisioning.key", "etc/limine-entry-tool.d/99-omarchy-provisioning-unlock.conf", + "etc/cmdline.d/99-omarchy-provisioning-unlock.conf", "etc/mkinitcpio.conf.d/99-omarchy-provisioning-key.conf", "etc/tailscale/authkey", "etc/systemd/system/omarchy-tailscale-join.service", @@ -4513,8 +4810,9 @@ def cleanup_target_hook_masks(ctx: InstallContext) -> None: """Restore the target's deferred boot hooks. Idempotent, and a no-op when nothing was masked, so main()'s finally can call it on any exit path: an interrupt must never leave the installed system with its UKI rebuild hook - pointing at /dev/null.""" - _unmask_mkinitcpio_pacman_hooks(ctx, ctx.target, TARGET_DEFERRED_BOOT_HOOKS) + pointing at /dev/null. Every hook either boot loader defers: a hook + that was not masked is left as it is.""" + _unmask_mkinitcpio_pacman_hooks(ctx, ctx.target, SYSTEMD_BOOT_DEFERRED_HOOKS) def cleanup_protected_state(ctx: InstallContext) -> None: diff --git a/configs/airootfs/usr/share/omarchy-iso/orchestrator/uki_cmdline.py b/configs/airootfs/usr/share/omarchy-iso/orchestrator/uki_cmdline.py index 46691973b..73ce6efd7 100644 --- a/configs/airootfs/usr/share/omarchy-iso/orchestrator/uki_cmdline.py +++ b/configs/airootfs/usr/share/omarchy-iso/orchestrator/uki_cmdline.py @@ -62,3 +62,20 @@ def embed_cmdline(uki: Path, cmdline: str) -> bool: image.seek(offset) image.write(data.ljust(room, b" ")) return True + + +def read_cmdline(uki: Path) -> str | None: + """The UKI's embedded cmdline: in a multi-profile UKI the first .cmdline, + which is the base every profile without its own boots with. None if the + image has none or cannot be read, or ends inside it: a cmdline cut short + can still name the root while missing what follows it.""" + with uki.open("rb") as image: + found = _cmdline_section(image.read(4096)) + if found is None: + return None + offset, length = found + image.seek(offset) + data = image.read(length) + if len(data) < length: + return None + return data.rstrip(b"\0").decode(errors="replace").strip() diff --git a/test/arm64-install b/test/arm64-install index e99d05baf..9e1b56bec 100755 --- a/test/arm64-install +++ b/test/arm64-install @@ -187,8 +187,11 @@ check() { # description, then a command run in the guest that must succeed check "it runs the kernel it was told to install" \ "pacman -Qo /usr/lib/modules/\$(uname -r) | grep -q ' ${KERNEL:-linux-omarchy} '" check "the user can use sudo" "echo $GUEST_PASSWORD | sudo -S -p '' true" - check "it booted through Limine's unified kernel image" \ - "echo $GUEST_PASSWORD | sudo -S -p '' sh -c 'ls /boot/EFI/Linux/omarchy_*.efi'" + # Limine's is omarchy_.efi; systemd-boot's are named for the + # machine (omarchy-boot-sync). An Omarchy without omarchy-boot-backend can + # only be on Limine. + check "it booted through its boot loader's unified kernel image" \ + "echo $GUEST_PASSWORD | sudo -S -p '' sh -c 'if [ \"\$(omarchy-boot-backend 2>/dev/null)\" = systemd-boot ]; then ls /boot/EFI/Linux/omarchy-\$(head -c 8 /etc/machine-id)-*.efi; else ls /boot/EFI/Linux/omarchy_*.efi; fi'" check "the Omarchy runtime is installed" "pacman -Q $RUNTIME_PACKAGE" # Node is a base package since omacom/omarchy#19917. Before it, a runtime # left a lazy mise shim, and one from before lazy Node unpacked the build the diff --git a/test/integration.d/base-test.sh b/test/integration.d/base-test.sh index 24baa009c..c352ecc58 100644 --- a/test/integration.d/base-test.sh +++ b/test/integration.d/base-test.sh @@ -505,6 +505,13 @@ ssh_sudo() { ssh_guest "echo $GUEST_PASSWORD | sudo -S -p '' bash -c $(printf %q "$1")" } +# The boot loader the installed system runs. An Omarchy that predates +# omarchy-boot-backend (an ISO built from packages without the systemd-boot +# stack, as CI's edge builds are until it is published) can only be on Limine. +installed_boot_loader() { + ssh_guest "if command -v omarchy-boot-backend >/dev/null; then omarchy-boot-backend; else echo limine; fi" | tr -d '\r\n' +} + # Answer an encrypted boot's LUKS prompt, given what OCR read off the screen. # The busybox encrypt hook asks "A password is required to access the root # volume"; systemd-cryptsetup (the pre-built UKI's initramfs) asks "Please @@ -901,9 +908,9 @@ detect_packages() { } # The firmware names what it starts on the serial port: the ISO's medium while -# the installer runs, the installed disk's Limine once the install is over. +# the installer runs, the installed disk's boot loader once the install is over. installed_system_started() { - grep -aq 'starting Boot.*"Limine"' "$1" 2>/dev/null + grep -aqE 'starting Boot.*"(Limine|Omarchy Boot)"' "$1" 2>/dev/null } # Wait out an unattended cidata install to its reboot into the installed diff --git a/test/integration.d/desktop-test.sh b/test/integration.d/desktop-test.sh index 798260ee6..044339a23 100755 --- a/test/integration.d/desktop-test.sh +++ b/test/integration.d/desktop-test.sh @@ -340,8 +340,6 @@ browser_launch_phase() { # ------------------------------------------------------- reaching the desktop -ssh_ready() { ssh_guest true; } - # The base was provisioned at install time (cidata created the owner), so it # boots straight to a graphical login -- the Omarchy logo over a password field # -- rendered by a Wayland greeter running as its own user, not the first-boot @@ -390,7 +388,16 @@ reach_desktop() { # Every step is a tap assertion (wait_for_guest_state prints ok/not ok and # feeds FAILURES), so a stall here is visible and fails the job instead of # being masked by the known-failures filter. - wait_for_guest_state "the installed system boots and answers SSH" "$BOOT_TIMEOUT" ssh_ready || return 1 + # An encrypted install stops at the disk passphrase first: wait_for_ssh + # types it, as it does for every other scenario's boot. It waits by itself, + # says why it gave up and stops when the VM is gone, so it isn't polled. + if wait_for_ssh "$BOOT_TIMEOUT"; then + printf 'ok - %s\n' "the installed system boots and answers SSH" + else + printf 'not ok - %s\n' "the installed system boots and answers SSH" + ((FAILURES += 1)) + return 1 + fi if ! wait_for_guest_state "the graphical login is ready" 300 login_ready; then diagnose_login return 1 diff --git a/test/integration.d/factory-reset-test.sh b/test/integration.d/factory-reset-test.sh index 8aac746d6..769e34cb9 100755 --- a/test/integration.d/factory-reset-test.sh +++ b/test/integration.d/factory-reset-test.sh @@ -35,6 +35,11 @@ base_image_ready || { echo "No base image; run this through ./test/integration" fixture_shared_esp() { OLD_ID=$(ssh_guest "cat /etc/machine-id" | tr -d '\r\n') [[ $OLD_ID =~ ^[0-9a-f]{32}$ ]] || { echo "unexpected machine-id: $OLD_ID" >&2; return 1; } + LOADER=$(installed_boot_loader) + if [[ $LOADER == systemd-boot ]]; then + fixture_shared_esp_systemd_boot + return + fi ssh_sudo "cp /boot/limine.conf /boot/limine.conf.pretest" >/dev/null ssh_sudo " @@ -68,6 +73,48 @@ CONF log "ESP fixtured as a shared dual-boot ESP (old machine-id $OLD_ID)" } +# systemd-boot finds boot images on the ESP rather than in a menu file, so the +# other systems are their files: Windows' loader, another Linux's UKI and +# another Omarchy's (its own machine-id prefix), copies of this install's. +fixture_shared_esp_systemd_boot() { + ssh_sudo " + set -euo pipefail + mkdir -p /boot/EFI/Microsoft/Boot + echo windows-payload >/boot/EFI/Microsoft/Boot/bootmgfw.efi + uki=\$(ls /boot/EFI/Linux/omarchy-${OLD_ID:0:8}-*.efi | head -1) + cp \"\$uki\" /boot/EFI/Linux/foreign-linux.efi + cp \"\$uki\" /boot/EFI/Linux/omarchy-${FOREIGN_ID:0:8}-linux-omarchy-foreign.efi + " >/dev/null + OLD_STORE_UUID=$(ssh_sudo "btrfs subvolume show /var/lib/omarchy/boot" | awk '/^[[:space:]]*UUID:/ { print $2; exit }' | tr -d '\r') + [[ -n $OLD_STORE_UUID ]] || { echo "the boot store has no subvolume UUID" >&2; return 1; } + FOREIGN_UKIS="/boot/EFI/Linux/foreign-linux.efi /boot/EFI/Linux/omarchy-${FOREIGN_ID:0:8}-linux-omarchy-foreign.efi" + ssh_sudo "ls -l /boot/EFI/Linux" >"$RUN_DIR/esp-linux.fixtured" || true + log "ESP fixtured as a shared dual-boot ESP for systemd-boot (old machine-id $OLD_ID)" +} + +# What staging and the first boot have to leave on a systemd-boot ESP: the +# other systems' files, none of the old owner's boot images, and boot images +# for the identity that boots next. +check_systemd_boot_esp() { + local when=$1 new_prefix=${2:-} + check "windows boot payload survives $when" \ + ssh_sudo "grep -q windows-payload /boot/EFI/Microsoft/Boot/bootmgfw.efi" + check "foreign UKIs survive $when" \ + ssh_sudo "for u in $FOREIGN_UKIS; do test -f \$u || exit 1; done" + check "the old owner's boot images are gone $when" \ + ssh_sudo "! ls /boot/EFI/Linux/omarchy-${OLD_ID:0:8}-*.efi >/dev/null 2>&1" + if [[ -n $new_prefix ]]; then + check "the new identity owns a boot image $when" \ + ssh_sudo "ls /boot/EFI/Linux/omarchy-$new_prefix-*.efi >/dev/null" + else + check "a fresh omarchy boot image exists $when" \ + ssh_sudo "ls /boot/EFI/Linux/omarchy-*.efi | grep -v -e '-${OLD_ID:0:8}-' -e '-${FOREIGN_ID:0:8}-' | grep -q ." + fi + check "systemd-boot stays on the ESP $when" \ + ssh_sudo "test -s /boot/EFI/systemd/systemd-bootx64.efi -a -f /boot/loader/loader.conf" + ssh_sudo "ls -l /boot/EFI/Linux" >"$RUN_DIR/esp-linux.${when// /-}" || true +} + # ------------------------------------------------------------- reset driver # Drive the interactive reset through a pty on the guest: `script` supplies @@ -156,6 +203,9 @@ reset_phase() { reset_output >"$RUN_DIR/reset.out" log "Reset staged. Asserting on the shared ESP before rebooting." + if [[ $LOADER == systemd-boot ]]; then + check_systemd_boot_esp "staging" + else check "windows entry survives staging" \ ssh_sudo "grep -q '^/Windows' /boot/limine.conf" check "windows boot payload survives staging" \ @@ -174,6 +224,7 @@ reset_phase() { ssh_sudo "grep -o 'machine-id=[0-9a-f]\{32\}' /boot/limine.conf | grep -qv 'machine-id=$FOREIGN_ID'" ssh_sudo "cat /boot/limine.conf" >"$RUN_DIR/limine.conf.staged" || true + fi ssh_sudo "cat /var/log/omarchy-system-factory-reset.log" >"$RUN_DIR/factory-reset.log" || true capture_console "success-reset-staged" @@ -319,6 +370,13 @@ first_boot_phase() { # ID would make the boot-entry grep below match the wrong entry. check "the reset minted a fresh machine identity" \ bash -c "[[ '$new_id' =~ ^[0-9a-f]{32}\$ && '$new_id' != '$OLD_ID' && '$new_id' != '$FOREIGN_ID' ]]" + if [[ $LOADER == systemd-boot ]]; then + check_systemd_boot_esp "the first boot" "${new_id:0:8}" + check "systemd-boot started the first boot" \ + ssh_sudo "bootctl status 2>/dev/null | grep -q 'Product: systemd-boot'" + check "the boot store is a fresh one, not the old owner's" \ + ssh_sudo "grep -qx phase=active /var/lib/omarchy/boot/state && uuid=\$(btrfs subvolume show /var/lib/omarchy/boot | awk '/^[[:space:]]*UUID:/ { print \$2; exit }') && [[ -n \$uuid && \$uuid != '$OLD_STORE_UUID' ]]" + else check "windows entry survives the first boot" \ ssh_sudo "grep -q '^/Windows' /boot/limine.conf" check "windows boot payload survives the first boot" \ @@ -335,6 +393,7 @@ first_boot_phase() { ssh_sudo "grep -q 'machine-id=$new_id' /boot/limine.conf" ssh_sudo "cat /boot/limine.conf" >"$RUN_DIR/limine.conf.final" || true + fi capture_console "success-final" } diff --git a/test/integration.d/firmware-boot-test.sh b/test/integration.d/firmware-boot-test.sh index d98fa1b31..e0a1109e0 100755 --- a/test/integration.d/firmware-boot-test.sh +++ b/test/integration.d/firmware-boot-test.sh @@ -41,10 +41,27 @@ verify_firmware_boot() { else check "booted in UEFI mode (EFI runtime present)" \ ssh_guest "test -d /sys/firmware/efi" - check "a Limine EFI binary is on the ESP" \ - ssh_sudo "test -e /boot/EFI/limine/limine_x64.efi -o -e /boot/EFI/BOOT/BOOTX64.EFI" - check "efibootmgr has a Limine entry" \ - ssh_sudo "efibootmgr | grep -qi limine" + # UEFI installs boot through systemd-boot, the loader Secure Boot needs, + # unless the ISO had no omarchy-boot-systemd or was told to keep Limine + # (OMARCHY_ISO_BOOT_LOADER=limine), as a shipped release ISO may be. + local loader + loader=$(installed_boot_loader) + if [[ $loader == "limine" ]]; then + check "a Limine EFI binary is on the ESP" \ + ssh_sudo "test -e /boot/EFI/limine/limine_x64.efi -o -e /boot/EFI/BOOT/BOOTX64.EFI" + check "efibootmgr has a Limine entry" \ + ssh_sudo "efibootmgr | grep -qi limine" + capture_console "success-firmware-$FIRMWARE" + return + fi + check "systemd-boot is on the ESP" \ + ssh_sudo "test -s /boot/EFI/systemd/systemd-bootx64.efi -a -s /boot/EFI/BOOT/BOOTX64.EFI" + check "efibootmgr has an Omarchy Boot entry, first in the boot order" \ + ssh_sudo "efibootmgr | awk '/^BootOrder:/ { split(\$2, order, \",\") } /Omarchy Boot/ { sub(/^Boot/, \"\", \$1); sub(/\\*\$/, \"\", \$1); entry = \$1 } END { exit !(entry != \"\" && order[1] == entry) }'" + check "systemd-boot started this boot" \ + ssh_sudo "bootctl status 2>/dev/null | grep -q 'Product: systemd-boot'" + check "the boot store is mounted and the switch state is active" \ + ssh_sudo "findmnt -n /var/lib/omarchy/boot >/dev/null && grep -qx phase=active /var/lib/omarchy/boot/state" fi capture_console "success-firmware-$FIRMWARE" diff --git a/test/integration.d/full-nvram-test.sh b/test/integration.d/full-nvram-test.sh index a05008ca8..91cadf4d2 100755 --- a/test/integration.d/full-nvram-test.sh +++ b/test/integration.d/full-nvram-test.sh @@ -107,9 +107,9 @@ fi ssh_sudo "cat /var/log/omarchy-install.log" >"$RUN_DIR/omarchy-install.log" 2>/dev/null || true ssh_sudo "efibootmgr" >"$RUN_DIR/efibootmgr.txt" 2>/dev/null || true -check "the installer was refused a boot entry" grep -q "would not register a 'Limine' UEFI boot entry" "$RUN_DIR/omarchy-install.log" +check "the installer was refused a boot entry" grep -qE "would not register a '(Omarchy Boot|Limine)' UEFI boot entry" "$RUN_DIR/omarchy-install.log" check "efibootmgr answered" grep -q "^BootOrder" "$RUN_DIR/efibootmgr.txt" -check "no Limine entry is in NVRAM" bash -c '! grep -q "Limine" "$1"' _ "$RUN_DIR/efibootmgr.txt" +check "no Omarchy boot entry is in NVRAM" bash -c '! grep -qE "Omarchy Boot|Limine" "$1"' _ "$RUN_DIR/efibootmgr.txt" check "the fallback loader is installed" ssh_sudo "test -s /boot/EFI/BOOT/BOOTX64.EFI" capture_console "success-full-nvram" diff --git a/test/unit/boot-swap-package-test.sh b/test/unit/boot-swap-package-test.sh new file mode 100755 index 000000000..f698315b8 --- /dev/null +++ b/test/unit/boot-swap-package-test.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# +# UEFI installs swap the image's Limine stack for omarchy-boot-systemd from the +# offline mirror. The build ships it only with a runtime that can finish the +# swap (omarchy-boot-switch), stops when pacman can't resolve it, ships what a +# local build of it depends on, and a release rehearsal builds it with the +# omarchy it is released in lockstep with. + +# shellcheck disable=SC2034 # the variables are read by the builder lines run through eval + +set -euo pipefail + +ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +builder="$ROOT/builder/build-iso.sh" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +fail() { echo "FAIL: $*" >&2; exit 1; } + +# ------------------------------------------------- choosing the swap package +choice=$(sed -n '/^boot_swap_package=""$/,/^fi$/p' "$builder") +[[ -n $choice ]] || fail "the builder has no boot swap choice" +choice=${choice//\/omarchy-source/$work/src} + +choose() { # resolvable: yes or no + local resolvable=$1 + pacman() { + case " $* " in + *" -Sp "*) return 0 ;; + *" -Sw "*) return 0 ;; + *" --print "*) [[ $resolvable == yes ]] && echo omarchy-boot-systemd-1-1-x86_64.pkg.tar.zst ;; + esac + } + local_packages=(omarchy-settings omarchy) + LOCAL_OMARCHY_BUILD=1 OMARCHY_ARCH=x86_64 online_pacman_conf=/dev/null offline_mirror_dir=$work/mirror + required_package_files=(base-1-1-any.pkg.tar.zst) + eval "$choice" + echo "${boot_swap_package:-none} ${required_package_files[*]}" +} + +mkdir -p "$work/src/bin" +[[ $(choose yes 2>/dev/null) == "none base-1-1-any.pkg.tar.zst" ]] || + fail "a runtime without omarchy-boot-switch gets the channel's omarchy-boot-systemd" +touch "$work/src/bin/omarchy-boot-switch" +[[ $(choose yes) == "omarchy-boot-systemd base-1-1-any.pkg.tar.zst omarchy-boot-systemd-1-1-x86_64.pkg.tar.zst" ]] || + fail "a runtime with omarchy-boot-switch does not get the channel's omarchy-boot-systemd: $(choose yes)" +if (choose no) >/dev/null 2>&1; then fail "an omarchy-boot-systemd pacman can't resolve is shipped anyway"; fi +echo "ok - the channel's omarchy-boot-systemd ships with a runtime that can finish the swap, resolved" + +# ----------------------------------------------- what a local build ships with +shipping=$(sed -n '/^# The boot swap package is never in the image/,/^fi$/p' "$builder") +[[ -n $shipping ]] || fail "the builder does not ship the boot swap package's dependencies" +mkdir -p "$work/pkg" "$work/mirror" +printf 'pkgname = omarchy-boot-systemd\ndepend = systemd\ndepend = systemd-ukify\ndepend = efibootmgr\ndepend = some-new-dependency>=2\n' >"$work/pkg/.PKGINFO" +bsdtar -C "$work/pkg" --zstd -cf "$work/mirror/omarchy-boot-systemd-1-1-x86_64.pkg.tar.zst" .PKGINFO +touch "$work/mirror/omarchy-boot-systemd-1-1-x86_64.pkg.tar.zst.sig" +pacman() { echo "resolved:${*: -4}"; } +boot_swap_package=omarchy-boot-systemd LOCAL_OMARCHY_BUILD=1 local_packages=(omarchy omarchy-boot-systemd) +offline_mirror_dir=$work/mirror online_pacman_conf=/dev/null installable_files=base-1-1-any.pkg.tar.zst +eval "$shipping" +[[ $installable_files == $'base-1-1-any.pkg.tar.zst\nomarchy-boot-systemd-1-1-x86_64.pkg.tar.zst\nresolved:systemd systemd-ukify efibootmgr some-new-dependency>=2' ]] || + fail "a local omarchy-boot-systemd does not ship with what it depends on: $installable_files" +unset -f pacman +echo "ok - a local omarchy-boot-systemd ships with every dependency it was built with" + +# ------------------------------------------------------- the release rehearsal +mkdir -p "$work/repo/bin" "$work/repo/configs" "$work/repo/release" "$work/stubs" "$work/home" "$work/omarchy" "$work/pkgs" +cp "$ROOT/bin/omarchy-iso-make" "$work/repo/bin/" +cp "$ROOT/configs/profiledef.sh" "$work/repo/configs/" +printf '#!/bin/bash\nexit 0\n' >"$work/stubs/git" +cat >"$work/stubs/docker" <<'STUB' +#!/bin/bash +[[ $1 == run ]] && printf '%s\n' "$@" >>"$TEST_DOCKER_LOG" +exit 0 +STUB +chmod +x "$work/stubs"/* +export TEST_DOCKER_LOG="$work/docker.log" +rehearsal_packages() { + : >"$TEST_DOCKER_LOG" + (cd "$work/repo" && PATH="$work/stubs:$PATH" HOME="$work/home" \ + "$work/repo/bin/omarchy-iso-make" --no-boot-offer --local-source "$work/omarchy" "$work/pkgs" --rehearsal) >/dev/null 2>&1 || true + sed -n 's/^OMARCHY_LOCAL_PACKAGES=//p' "$TEST_DOCKER_LOG" +} +[[ $(rehearsal_packages) == "omarchy-settings omarchy" ]] || fail "a rehearsal without omarchy-boot-systemd: $(rehearsal_packages)" +mkdir -p "$work/pkgs/pkgbuilds/omarchy-boot-systemd" +[[ $(rehearsal_packages) == "omarchy-settings omarchy omarchy-boot-systemd" ]] || + fail "a rehearsal does not build omarchy-boot-systemd with omarchy: $(rehearsal_packages)" +echo "ok - a release rehearsal builds omarchy-boot-systemd with the omarchy it is released with" diff --git a/test/unit/test_limine_efi_entry.py b/test/unit/test_limine_efi_entry.py index 0607f591c..d88d35091 100644 --- a/test/unit/test_limine_efi_entry.py +++ b/test/unit/test_limine_efi_entry.py @@ -360,7 +360,7 @@ def test_a_refused_create_leaves_other_installs_alone(self): self.nvram_with({"0004": self.entry("Limine", OTHER)}, ["0004"]) warnings = [] with mock.patch.dict(os.environ, {"FAKE_REFUSE_CREATE": "1"}), \ - mock.patch.object(phases_impl, "_warn_boot_entry_refused", warnings.append): + mock.patch.object(phases_impl, "_warn_boot_entry_refused", lambda reason, *_: warnings.append(reason)): nvram = self.register() self.assertEqual(nvram, {"entries": {"0004": self.entry("Limine", OTHER)}, "order": ["0004"]}) self.assertEqual(len(warnings), 1) @@ -373,7 +373,7 @@ def test_firmware_that_refuses_creates_keeps_this_esps_entry(self): self.nvram_with(old, ["0003", "0004"]) warnings = [] with mock.patch.dict(os.environ, {"FAKE_REFUSE_CREATE": "1"}), \ - mock.patch.object(phases_impl, "_warn_boot_entry_refused", warnings.append): + mock.patch.object(phases_impl, "_warn_boot_entry_refused", lambda reason, *_: warnings.append(reason)): nvram = self.register() self.assertEqual(nvram, {"entries": old, "order": ["0003", "0004"], "next": "0003"}) self.assertEqual(self.writes(), ["--bootnext"]) @@ -389,7 +389,7 @@ def test_an_entry_the_firmware_answers_a_create_with_is_ours(self): ) warnings = [] with mock.patch.dict(os.environ, {"FAKE_REUSE": "1"}), \ - mock.patch.object(phases_impl, "_warn_boot_entry_refused", warnings.append): + mock.patch.object(phases_impl, "_warn_boot_entry_refused", lambda reason, *_: warnings.append(reason)): phases_impl._register_limine_efi_entry( Path("/dev/nvme1n1"), 3, LOADER, pre_state={"entries": {"0000": "Windows Boot Manager"}, "order": ["0000"]}, @@ -413,7 +413,7 @@ def test_a_full_nvram_keeps_the_identical_entry(self): Path(str(self.nvram) + ".log").unlink(missing_ok=True) warnings = [] with mock.patch.dict(os.environ, {"FAKE_SLOTS": slots}), \ - mock.patch.object(phases_impl, "_warn_boot_entry_refused", warnings.append): + mock.patch.object(phases_impl, "_warn_boot_entry_refused", lambda reason, *_: warnings.append(reason)): nvram = self.register() self.assertEqual(nvram["entries"], old) self.assertEqual(self.writes(), ["--bootorder", "--bootnext"]) @@ -433,7 +433,7 @@ def test_a_full_nvram_without_an_identical_entry_deletes_nothing(self): self.nvram_with(old, ["0000", "0004", "0005"]) warnings = [] with mock.patch.dict(os.environ, {"FAKE_SLOTS": "3"}), \ - mock.patch.object(phases_impl, "_warn_boot_entry_refused", warnings.append): + mock.patch.object(phases_impl, "_warn_boot_entry_refused", lambda reason, *_: warnings.append(reason)): nvram = self.register() self.assertEqual(nvram, {"entries": old, "order": ["0000", "0004", "0005"]}) self.assertEqual(self.writes(), ["--create"]) @@ -469,6 +469,16 @@ def test_stale_limine_entries_for_replaced_partitions_are_pruned_and_disconnecte self.assertEqual(nvram.get("next"), ours) + def test_a_limine_install_prunes_an_earlier_systemd_boot_install_s_entry(self): + replaced = "11111111-2222-3333-4444-555555555555" + self.nvram_with( + {"0003": self.entry("Omarchy Boot", replaced, loader="\\EFI\\systemd\\systemd-bootx64.efi")}, + ["0003"], + ) + nvram = self.register(replaced_guids={replaced}) + self.assertNotIn("0003", nvram["entries"]) + self.assertEqual(self.writes()[0], "--delete-bootnum") + def test_boot_check_does_not_count_another_installs_entry(self): # validate_boot: our entry was dropped and no fallback was deployed. # The other install's "Limine" entry must not pass for ours. @@ -516,7 +526,7 @@ def test_an_unreadable_variable_store_skips_registration(self): self.nvram_with({}, []) warnings = [] with mock.patch.dict(os.environ, {"FAKE_NO_EFIVARS": "1"}), \ - mock.patch.object(phases_impl, "_warn_boot_entry_refused", warnings.append): + mock.patch.object(phases_impl, "_warn_boot_entry_refused", lambda reason, *_: warnings.append(reason)): self.register() self.assertEqual(self.writes(), []) self.assertEqual(len(warnings), 1) @@ -536,7 +546,7 @@ def test_an_unreadable_variable_store_does_not_stop_a_free_space_install(self): mock.patch.object(phases_impl, "_install_limine_efi", lambda _ctx, *, disk, part, pre_state, **_: phases_impl._register_limine_efi_entry( disk, part, LOADER, pre_state=pre_state)), \ - mock.patch.object(phases_impl, "_warn_boot_entry_refused", warnings.append): + mock.patch.object(phases_impl, "_warn_boot_entry_refused", lambda reason, *_: warnings.append(reason)): phases_impl._install_pre_mounted_limine(ctx) self.assertEqual(self.writes(), []) self.assertEqual(len(warnings), 1) diff --git a/test/unit/test_systemd_boot_install.py b/test/unit/test_systemd_boot_install.py new file mode 100644 index 000000000..f4e79990b --- /dev/null +++ b/test/unit/test_systemd_boot_install.py @@ -0,0 +1,294 @@ +"""UEFI x86_64 installs boot through systemd-boot. + +The image carries Limine's stack (omarchy-boot), which BIOS installs keep. A +UEFI install swaps it for omarchy-boot-systemd, puts systemd-boot on the ESP +with an "Omarchy Boot" entry, writes the cmdline where systemd-boot's boot +images read it, and has omarchy-boot-switch install build those images at the +end. validate_boot checks what the firmware will find. Tested against a +synthesised target and ESP, with pacman, arch-chroot and efibootmgr recorded +instead of run. +""" + +import sys +import tempfile +import types +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "configs/airootfs/usr/share/omarchy-iso")) +sys.path.insert(0, str(ROOT / "test/unit")) +sys.modules.setdefault("orchestrator.archinstall_adapter", types.ModuleType("orchestrator.archinstall_adapter")) +from orchestrator import phases_impl as phases # noqa: E402 +from orchestrator.uki_cmdline import read_cmdline # noqa: E402 +from test_uki_cmdline import uki # noqa: E402 + +MACHINE_ID = "0123456789abcdef0123456789abcdef" +CMDLINE = "cryptdevice=PARTUUID=p:root root=/dev/mapper/root zswap.enabled=0 rootflags=subvol=@ rw rootfstype=btrfs" + + +class SystemdBootInstallTest(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) / "target" + self.mirror = Path(temporary.name) / "mirror" + self.mirror.mkdir(parents=True) + (self.mirror / "omarchy-boot-systemd-1-1-x86_64.pkg.tar.zst").write_text("package") + self.ctx = types.SimpleNamespace( + target=self.root, state={}, omarchy_install={"storage": {"kernel": "linux-omarchy"}}, + user_configuration={}, encrypt=True, is_protected=False, defer_provisioning=False, + ) + self.has_uefi = True + self.apple = False + self.commands = [] + for patch in ( + mock.patch.object(phases, "OFFLINE_MIRROR", self.mirror), + mock.patch.object(phases.platform, "machine", return_value="x86_64"), + mock.patch.object(phases.arch, "has_uefi", lambda: self.has_uefi, create=True), + mock.patch.object(phases, "_is_apple_t2_hardware", lambda: self.apple), + mock.patch.object(phases.subprocess, "run", self.record), + mock.patch.dict(phases.os.environ, {}, clear=False), + ): + patch.start() + self.addCleanup(patch.stop) + phases.os.environ.pop("OMARCHY_ISO_BOOT_LOADER", None) + + def record(self, command, **_kwargs): + self.commands.append(list(command)) + return types.SimpleNamespace(returncode=0, stdout="", stderr="") + + def write(self, name, data): + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + if isinstance(data, bytes): + path.write_bytes(data) + else: + path.write_text(data) + return path + + def installed(self): + """What omarchy-boot-switch install leaves on a full-disk install.""" + self.write("etc/machine-id", MACHINE_ID + "\n") + self.write("etc/kernel/cmdline", CMDLINE + "\n") + self.write("etc/fstab", "UUID=x /var/lib/omarchy/boot btrfs subvol=/@omarchy-boot 0 0\n") + self.write("boot/EFI/systemd/systemd-bootx64.efi", "loader") + self.write("boot/EFI/BOOT/BOOTX64.EFI", "loader") + self.write("boot/loader/loader.conf", "timeout 0\n") + self.write(f"boot/EFI/Linux/omarchy-{MACHINE_ID[:8]}-linux-omarchy-abc123.efi", uki(CMDLINE.encode())) + self.write("usr/lib/modules/7.2/pkgbase", "linux-omarchy\n") + self.write("usr/lib/modules/7.2/build/include/config/kernel.release", "7.2\n") + + def validate(self): + efi = {"entries": {"0003": f"Omarchy Boot\tHD(1,GPT,guid,0x800,0x1000)/\\EFI\\systemd\\systemd-bootx64.efi"}, "order": ["0003"]} + with mock.patch.object(phases, "_assert_boot_hooks_restored"), \ + mock.patch.object(phases, "_validate_kernel_headers"), \ + mock.patch.object(phases, "_validate_package_signing"), \ + mock.patch.object(phases, "_mounted_partition_guid", return_value="guid"), \ + mock.patch.object(phases, "_read_efibootmgr", return_value=efi): + phases.validate_boot(self.ctx) + + def test_uefi_x86_installs_get_systemd_boot(self): + self.assertEqual(phases._boot_loader(self.ctx), "systemd-boot") + + def test_bios_an_override_or_a_mirror_without_the_stack_keep_limine(self): + for setup in ( + lambda: setattr(self, "has_uefi", False), + lambda: phases.os.environ.__setitem__("OMARCHY_ISO_BOOT_LOADER", "limine"), + lambda: (self.mirror / "omarchy-boot-systemd-1-1-x86_64.pkg.tar.zst").unlink(), + ): + with self.subTest(setup=setup): + self.setUp() + setup() + self.assertEqual(phases._boot_loader(self.ctx), "limine") + + def test_intel_macs_keep_limine_as_omarchy_boot_switch_keeps_them(self): + for setup in ( + lambda: setattr(self, "apple", True), + lambda: self.ctx.user_configuration.__setitem__("kernels", ["linux-t2"]), + ): + with self.subTest(setup=setup): + self.setUp() + setup() + self.assertEqual(phases._boot_loader(self.ctx), "limine") + + def test_aarch64_uefi_installs_get_systemd_boot_with_the_console_on_screen(self): + luks_tuning = types.ModuleType("orchestrator.luks_tuning") + luks_tuning.with_cmdline_options = lambda cmdline: f"{cmdline} rd.luks.name=p=root" + with mock.patch.object(phases.platform, "machine", return_value="aarch64"), \ + mock.patch.dict(sys.modules, {"orchestrator.luks_tuning": luks_tuning}): + self.assertEqual(phases._boot_loader(self.ctx), "systemd-boot") + phases._write_limine_defaults(self.ctx, CMDLINE, esp_mount="/boot") + self.assertEqual((self.root / "etc/cmdline.d/00-omarchy-console.conf").read_text(), "console=tty0 acpi=nospcr\n") + self.assertFalse((self.root / "etc/limine-entry-tool.d").exists()) + + def test_an_n1x_boot_image_keeps_the_console_off_the_serial_port(self): + self.installed() + with mock.patch.object(phases, "_installed_arm_platform", return_value="n1x"): + with self.assertRaisesRegex(RuntimeError, "console=tty0 acpi=nospcr"): + self.validate() + (self.root / f"boot/EFI/Linux/omarchy-{MACHINE_ID[:8]}-linux-omarchy-abc123.efi").write_bytes( + uki(f"{CMDLINE} console=tty0 acpi=nospcr".encode())) + self.validate() + + def test_the_stack_swap_replaces_limine_s_packages(self): + phases._install_systemd_boot_stack(self.ctx) + swap = self.commands[0] + self.assertEqual(swap[:3], ["pacman", "--root", str(self.root)]) + self.assertIn("--ask=4", swap) + self.assertEqual(swap[-1], "omarchy-boot-systemd") + + def test_the_loader_goes_on_the_esp_with_an_omarchy_boot_entry(self): + self.write("usr/lib/systemd/boot/efi/systemd-bootx64.efi", "loader") + with mock.patch.object(phases, "_register_limine_efi_entry") as register: + phases._install_limine_efi(self.ctx, esp_mount="/boot", disk=Path("/dev/vda"), part=1) + self.assertTrue((self.root / "boot/EFI/systemd/systemd-bootx64.efi").is_file()) + self.assertFalse((self.root / "etc/pacman.d/hooks/99-omarchy-limine.hook").exists()) + register.assert_called_once() + self.assertEqual(register.call_args.args[2], "\\EFI\\systemd\\systemd-bootx64.efi") + self.assertEqual(register.call_args.kwargs["label"], "Omarchy Boot") + + def test_the_cmdline_goes_where_systemd_boot_s_images_read_it(self): + luks_tuning = types.ModuleType("orchestrator.luks_tuning") + luks_tuning.with_cmdline_options = lambda cmdline: f"{cmdline} rd.luks.name=p=root" + with mock.patch.dict(sys.modules, {"orchestrator.luks_tuning": luks_tuning}): + phases._write_limine_defaults(self.ctx, CMDLINE, esp_mount="/boot") + written = (self.root / "etc/kernel/cmdline").read_text() + self.assertIn("root=/dev/mapper/root", written) + self.assertIn(phases.CONSOLE_NO_ANSI_QUERY, written) + self.assertFalse((self.root / "etc/default/limine").exists()) + self.assertFalse((self.root / "boot/limine.conf").exists()) + self.assertTrue(self.ctx.state["boot_fallback"]) + + def test_omarchy_boot_switch_install_builds_the_boot_images(self): + self.write("etc/snapper/configs/root", "") + self.write("etc/kernel/cmdline", CMDLINE + "\n") + self.ctx.state["boot_fallback"] = False + with mock.patch.object(phases, "_drop_initramfs_modules_the_kernel_lacks"), \ + mock.patch.object(phases, "_is_apple_t2_hardware", return_value=False): + phases.finalize_boot(self.ctx) + self.assertIn( + ["arch-chroot", str(self.root), "env", "OMARCHY_BOOT_ESP=/boot", + "omarchy-boot-switch", "install", "--no-efi-register", "--no-fallback"], + self.commands, + ) + + def test_a_free_space_install_s_esp_at_efi_reaches_the_install(self): + self.write("etc/snapper/configs/root", "") + self.write("etc/kernel/cmdline", CMDLINE + "\n") + self.ctx.omarchy_install["boot"] = {"esp_mount": "/efi"} + with mock.patch.object(phases, "_drop_initramfs_modules_the_kernel_lacks"), \ + mock.patch.object(phases, "_is_apple_t2_hardware", return_value=False): + phases.finalize_boot(self.ctx) + self.assertTrue(any("OMARCHY_BOOT_ESP=/efi" in command for command in self.commands)) + self.assertFalse(any("limine" in " ".join(command) for command in self.commands)) + + def test_system_setup_defers_both_of_omarchy_boot_systemd_s_hooks(self): + hooks = self.root / "etc/pacman.d/hooks" + for name in ("60-mkinitcpio-remove.hook", "90-mkinitcpio-install.hook"): + self.write(f"etc/pacman.d/hooks/{name}", "[Trigger]\n") + masked = [] + + def setup(_ctx, _cmd, **_kwargs): + masked.extend(sorted(p.name for p in hooks.iterdir() if phases._is_devnull_symlink(p))) + + self.ctx.username = "omarchy" + with mock.patch.object(phases, "_runtime_populates_target_keyring", return_value=False), \ + mock.patch.object(phases, "_run_target_setup_command", setup): + phases.run_system_finalizer(self.ctx) + self.assertEqual(masked, ["60-mkinitcpio-remove.hook", "90-mkinitcpio-install.hook"]) + self.assertEqual((hooks / "60-mkinitcpio-remove.hook").read_text(), "[Trigger]\n") + phases._assert_boot_hooks_restored(self.ctx) + + def test_oem_scripts_run_with_the_boot_store_mounted(self): + scripts = self.root.parent / "oem/scripts" + scripts.mkdir(parents=True) + (scripts / "10-firmware.sh").write_text("pacman -S --noconfirm some-firmware\n") + self.ctx.oem_dir = scripts.parent + runs = [] + with mock.patch.object(phases, "_join_target_keyring_init"), \ + mock.patch.object(phases, "_run_target_setup_command", + lambda _ctx, cmd, **kwargs: runs.append((cmd, kwargs))): + phases.run_oem_setup(self.ctx) + self.ctx.state["boot_loader"] = "limine" + phases.run_oem_setup(self.ctx) + script = ["/bin/bash", f"/{phases.OEM_SCRIPTS_TARGET_DIR}/10-firmware.sh"] + (systemd_boot, kwargs), (limine, limine_kwargs) = runs + self.assertEqual(systemd_boot[:4], ["env", "OMARCHY_BOOT_ESP=/boot", "/bin/bash", "-c"]) + self.assertIn("mount /var/lib/omarchy/boot", systemd_boot[4]) + self.assertEqual(systemd_boot[-2:], script) + self.assertEqual(kwargs, {"private_mounts": True}) + self.assertEqual((limine, limine_kwargs), (script, {})) + + def test_a_complete_install_validates(self): + self.installed() + self.validate() + + def test_validation_wants_a_boot_image_with_the_install_s_cmdline(self): + self.installed() + (self.root / f"boot/EFI/Linux/omarchy-{MACHINE_ID[:8]}-linux-omarchy-abc123.efi").write_bytes(uki(b"root=/dev/sda2 rw")) + with self.assertRaisesRegex(RuntimeError, "cryptdevice"): + self.validate() + (self.root / f"boot/EFI/Linux/omarchy-{MACHINE_ID[:8]}-linux-omarchy-abc123.efi").unlink() + with self.assertRaisesRegex(RuntimeError, "no boot image"): + self.validate() + + def test_a_damaged_boot_image_fails_validation_next_to_a_good_one(self): + self.installed() + self.write(f"boot/EFI/Linux/omarchy-{MACHINE_ID[:8]}-linux-omarchy-zzz999.efi", b"not a PE image") + with self.assertRaisesRegex(RuntimeError, "no readable cmdline"): + self.validate() + + def test_validation_wants_systemd_boot_itself_beside_another_system_s_fallback_loader(self): + self.installed() + self.ctx.is_protected = True + self.ctx.omarchy_install["boot"] = {"enable_fallback": False} + (self.root / "boot/EFI/systemd/systemd-bootx64.efi").unlink() + with mock.patch.object(phases, "_validate_pre_mounted_filesystems"), \ + self.assertRaisesRegex(RuntimeError, "systemd-bootx64.efi missing"): + self.validate() + + def test_a_boot_image_cut_short_inside_its_cmdline_is_refused(self): + self.installed() + image = self.root / f"boot/EFI/Linux/omarchy-{MACHINE_ID[:8]}-linux-omarchy-abc123.efi" + image.write_bytes(image.read_bytes()[:0x400 + CMDLINE.index("rootflags")]) + self.assertIsNone(read_cmdline(image)) + with self.assertRaisesRegex(RuntimeError, "no readable cmdline"): + self.validate() + + def test_the_esp_is_where_the_installer_mounted_it(self): + luks_tuning = types.ModuleType("orchestrator.luks_tuning") + luks_tuning.with_cmdline_options = lambda cmdline: f"{cmdline} rd.luks.name=p=root" + with mock.patch.dict(sys.modules, {"orchestrator.luks_tuning": luks_tuning}): + phases._write_limine_defaults(self.ctx, CMDLINE, esp_mount="/efi") + self.write("etc/snapper/configs/root", "") + with mock.patch.object(phases, "_drop_initramfs_modules_the_kernel_lacks"): + phases.finalize_boot(self.ctx) + self.assertTrue(any("OMARCHY_BOOT_ESP=/efi" in command for command in self.commands)) + self.installed() + (self.root / "boot").rename(self.root / "efi") + self.validate() + + def test_validation_wants_the_boot_store_mounted_at_boot(self): + self.installed() + self.write("etc/fstab", "UUID=x / btrfs subvol=/@ 0 0\n") + with self.assertRaisesRegex(RuntimeError, "boot store"): + self.validate() + + def test_the_provisioning_unlock_is_a_cmdline_drop_in(self): + self.ctx.omarchy_install["provisioning"] = {} + provisioning = self.root / "var/lib/omarchy/provisioning" + provisioning.mkdir(parents=True) + with mock.patch.object(phases, "_provision_encryption_password", return_value="secret"): + phases._stage_provisioning_luks_unlock(self.ctx, provisioning) + self.assertEqual( + (self.root / "etc/cmdline.d/99-omarchy-provisioning-unlock.conf").read_text(), + "cryptkey=rootfs:/etc/omarchy/provisioning.key\n", + ) + self.assertFalse((self.root / "etc/limine-entry-tool.d/99-omarchy-provisioning-unlock.conf").exists()) + self.assertIn("etc/cmdline.d/99-omarchy-provisioning-unlock.conf", phases.FACTORY_SCRUB_PATHS) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/upgrade-test b/test/upgrade-test index b71d46fe3..3d9fbf227 100755 --- a/test/upgrade-test +++ b/test/upgrade-test @@ -111,7 +111,12 @@ facts() { # file echo "migrations_skipped=$(find ~/.local/state/omarchy/migrations/skipped -name "*.sh" 2>/dev/null | wc -l)" echo "wallpaper=${target##*/}" echo "wallpaper_exists=$([[ -n $target && -e $target ]] && echo yes || echo no)" + # An Omarchy without omarchy-boot-backend can only be on Limine. + echo "boot_loader=$(omarchy-boot-backend 2>/dev/null || echo limine)" echo "boot_entry_groups=$(sudo grep -c "^/+" /boot/limine.conf 2>/dev/null)" + default=$(sudo sed -n "s/^default //p" /boot/loader/loader.conf 2>/dev/null | tail -1) + echo "boot_default=$default" + echo "boot_default_on_esp=$([[ -n $default ]] && sudo test -s "/boot/EFI/Linux/$default" && echo yes || echo no)" echo "boot_id=$(cut -c1-8 /proc/sys/kernel/random/boot_id)" ' 2>/dev/null | grep -E '^[a-z_]+=' >"$1" } @@ -282,7 +287,11 @@ picture() { local name=${1%.*}; [[ $name =~ ^[0-9]+-(.+)$ ]] && name=${BASH_REMA before_wallpaper=$(b wallpaper) after_wallpaper=$(a wallpaper) check "The wallpaper is the one the user had, and exists ($before_wallpaper → $after_wallpaper)" \ test "$(a wallpaper_exists)" = yes -a -n "$after_wallpaper" -a "$(picture "$after_wallpaper")" = "$(picture "$before_wallpaper")" -check "The boot menu has one Omarchy group ($(a boot_entry_groups))" test "$(a boot_entry_groups)" = 1 +if [[ $(a boot_loader) == systemd-boot ]]; then + check "systemd-boot's default boot image is on the ESP ($(a boot_default))" test "$(a boot_default_on_esp)" = yes +else + check "The boot menu has one Omarchy group ($(a boot_entry_groups))" test "$(a boot_entry_groups)" = 1 +fi row() { printf '| %s | %s | %s |\n' "$1" "$(b "$2")" "$(a "$2")"; } { diff --git a/test/vm-image/vm-seal b/test/vm-image/vm-seal index d71a3e5f9..8280b461d 100755 --- a/test/vm-image/vm-seal +++ b/test/vm-image/vm-seal @@ -69,7 +69,17 @@ mkdir -p "$out" # installs linux-omarchy, and the boot entry, not the UKI, may hold the # command line. kernel=$(ssh_vm 'cat "/usr/lib/modules/$(uname -r)/pkgbase"') -root "cat /boot/EFI/Linux/omarchy_$kernel.efi" >"$state/uki.efi" +# Limine's UKI is named for the kernel. systemd-boot's are named for the +# machine and the boot image (omarchy-boot-sync), and the one it boots by +# default is the live system's. +if [[ $(ssh_vm 'omarchy-boot-backend 2>/dev/null' || true) == systemd-boot ]]; then + uki=$(root 'sed -n "s/^default //p" /boot/loader/loader.conf | tail -1') + [[ $uki =~ ^omarchy-[0-9a-f]{8}-$kernel-[0-9a-f]{12}\.efi$ ]] || + { echo "vm-seal: systemd-boot's default ($uki) is not a boot image of the running $kernel" >&2; exit 1; } +else + uki=omarchy_$kernel.efi +fi +root "cat /boot/EFI/Linux/$uki" >"$state/uki.efi" ssh_vm 'cat /proc/cmdline' >"$state/cmdline" root ' @@ -91,9 +101,11 @@ root ' # second entry and delete or replace the UKI of the default entry, this one: # a panic or a hash prompt at the next firmware boot. An entry that names no # machine is found by its name, TARGET_OS_NAME, and updated in place. + # systemd-boot keeps no menu file: a clone's first rebuild publishes boot + # images named for its own machine ID and makes them the default. mid=$(cat /etc/machine-id) [[ $mid =~ ^[0-9a-f]{32}$ ]] - sed -i "s/machine-id=$mid *//" /boot/limine.conf + if [ -f /boot/limine.conf ]; then sed -i "s/machine-id=$mid *//" /boot/limine.conf; fi # Empty, not "uninitialized": that string marks a first boot, and a first boot # applies unit presets, which on Arch disable everything not listed. Empty lets @@ -130,7 +142,7 @@ root ' rm -rf /var/log/journal/* test ! -s /etc/machine-id - test -z "$(grep "machine-id=$mid" /boot/limine.conf)" + test ! -f /boot/limine.conf || test -z "$(grep "machine-id=$mid" /boot/limine.conf)" test -z "$(ls /etc/ssh/ssh_host_* /var/lib/NetworkManager/*.lease /var/log/journal/* 2>/dev/null)" test ! -e /home/omarchy/.ssh/authorized_keys test ! -e /var/lib/systemd/random-seed diff --git a/test/vm-image/vm-verify b/test/vm-image/vm-verify index 1a682ac18..19ba65037 100755 --- a/test/vm-image/vm-verify +++ b/test/vm-image/vm-verify @@ -47,10 +47,27 @@ check "the factory snapshot has no SSH host keys" sh -c "[ -z \"\$(printf '%s\n' check "no snapshots besides the current system" [ -z "$(root ls /.snapshots)" ] # Any kernel or mkinitcpio update rebuilds the initramfs, and on a clone that -# rebuild runs under a machine ID the image was not built with. It has to -# update the image's boot entry, not add one beside it, or the entry Limine -# boots by default loads files the rebuild deleted or replaced. vm-boot skips -# the firmware, so this rebuild takes the path that deletes the UKI. +# rebuild runs under a machine ID the image was not built with. +# +# On systemd-boot (an Omarchy without omarchy-boot-backend can only be on +# Limine) the rebuild publishes boot images named for this machine, and the +# default systemd-boot boots has to be one of them, on the ESP. +if [ "$(omarchy-boot-backend 2>/dev/null)" = systemd-boot ]; then + loader_default() { root sed -n 's/^default //p' /boot/loader/loader.conf | tail -1; } + ns=$(head -c 8 /etc/machine-id) + check "an initramfs rebuild succeeds" root omarchy-boot-rebuild + after=$(loader_default) + check "systemd-boot's default is a boot image of this machine's ($after)" sh -c 'case "$1" in omarchy-"$2"-*.efi) ;; *) exit 1 ;; esac' - "$after" "$ns" + check "systemd-boot's default boot image is on the ESP" root test -s "/boot/EFI/Linux/$after" + check "the boot images match the installed kernels" root omarchy-boot-sync verify + echo "omarchy $(pacman -Q omarchy 2>/dev/null | cut -d' ' -f2), kernel $(uname -r), $(systemd-analyze | head -1)" + exit $fail +fi + +# On Limine the rebuild has to update the image's boot entry, not add one +# beside it, or the entry Limine boots by default loads files the rebuild +# deleted or replaced. vm-boot skips the firmware, so this rebuild takes the +# path that deletes the UKI. menu() { root cat /boot/limine.conf; } unkeyed() { local m; m=$(menu) && [ -n "$m" ] && ! grep -q 'machine-id=' <<<"$m"; } # The files of the entry Limine boots by default, as "path hash" lines. As in