Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion boot/grub/bios-modules.list
Original file line number Diff line number Diff line change
@@ -1 +1 @@
biosdisk part_gpt part_msdos ext2 chain ntfs linux gzio reboot search_fs_uuid search_label fat iso9660 multiboot2 normal cmp search search_fs_file configfile echo serial terminal video video_bochs video_cirrus vbe all_video font gfxterm gfxmenu regexp hashsum gcry_sha256 crypto loadenv test
biosdisk part_gpt part_msdos ext2 chain ntfs linux gzio reboot search_fs_uuid search_label fat iso9660 multiboot2 normal cmp search search_fs_file configfile echo serial terminal video video_bochs video_cirrus vbe all_video font gfxterm gfxmenu png regexp hashsum gcry_sha256 crypto loadenv test
1 change: 1 addition & 0 deletions boot/grub/grub.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ insmod all_video
insmod font
insmod gfxterm
insmod gfxmenu
insmod png
# A per-instance EFI wrapper or BIOS prefix identifies its own boot tree.
set reliefos_directory=
set reliefos_root=
Expand Down
5 changes: 5 additions & 0 deletions boot/grub/kernel-slots.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -221,4 +221,9 @@ function reliefos_prepare_boot {
}
export reliefos_boot_ready reliefos_kernel reliefos_initramfs reliefos_previous_release reliefos_previous_directory
export reliefos_selected reliefos_selected_generation reliefos_selected_initramfs
# Submenus open a new environment containing only exported variables. Keep
# both the selected release and the confirmed fallback inputs available there.
export reliefos_selected_release reliefos_selected_confirmed reliefos_selected_remaining
export reliefos_a_valid reliefos_a_generation reliefos_a_release reliefos_a_initramfs reliefos_a_confirmed reliefos_a_remaining
export reliefos_b_valid reliefos_b_generation reliefos_b_release reliefos_b_initramfs reliefos_b_confirmed reliefos_b_remaining
export reliefos_previous_slot reliefos_previous_generation reliefos_previous_initramfs
Binary file added boot/grub/theme/background.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion boot/grub/theme/theme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ title-text: ""
title-font: "Unifont Regular 16"
title-color: "#ffffff"
desktop-color: "#080b10"
desktop-image: "background.png"
terminal-font: "Unifont Regular 16"
terminal-left: "7%"
terminal-top: "72%"
Expand Down Expand Up @@ -308,7 +309,6 @@ terminal-border: "0"
item_height = 32
item_padding = 4
item_spacing = 4
selected_item_pixmap_style = "none"
}

+ label {
Expand Down
2 changes: 1 addition & 1 deletion tests/build/grub-fixture.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ grub_fixture_efi() {
fixture_efi=$1
mkdir -p "$fixture_efi"
printf 'int grub_fixture_input;\n' | ${HOSTCC:-cc} -m64 -ffreestanding -x c -c -o "$fixture_efi/input.o" -
for fixture_name in part_gpt part_msdos ext2 chain ntfs linux gzio reboot search_fs_uuid search_label fat iso9660 multiboot2 normal cmp search search_fs_file regexp configfile echo serial terminal video video_bochs video_cirrus efi_gop all_video font gfxterm gfxmenu hashsum gcry_sha256 crypto loadenv test; do
for fixture_name in part_gpt part_msdos ext2 chain ntfs linux gzio reboot search_fs_uuid search_label fat iso9660 multiboot2 normal cmp search search_fs_file regexp configfile echo serial terminal video video_bochs video_cirrus efi_gop all_video font gfxterm gfxmenu png hashsum gcry_sha256 crypto loadenv test; do
cp "$fixture_efi/input.o" "$fixture_efi/$fixture_name.mod"
done
printf 'fixture EFI kernel\n' > "$fixture_efi/kernel.img"
Expand Down
3 changes: 2 additions & 1 deletion tools/build/boot-stage.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ trap 'rm -rf "$work"' EXIT HUP INT TERM
mkdir -p "$work/EFI/BOOT" "$work/grub/fonts" "$work/grub/theme" \
"$work/reliefos/config" "$work/grub/i386-pc"
"${GRUB_MKSTANDALONE:-grub-mkstandalone}" -d "$modules" -O x86_64-efi -o "$work/EFI/BOOT/BOOTX64.EFI" \
--modules='part_gpt part_msdos ext2 chain ntfs linux gzio reboot search_fs_uuid search_label fat iso9660 multiboot2 normal cmp search search_fs_file regexp configfile echo serial terminal video video_bochs video_cirrus efi_gop all_video font gfxterm gfxmenu hashsum gcry_sha256 crypto loadenv test' \
--modules='part_gpt part_msdos ext2 chain ntfs linux gzio reboot search_fs_uuid search_label fat iso9660 multiboot2 normal cmp search search_fs_file regexp configfile echo serial terminal video video_bochs video_cirrus efi_gop all_video font gfxterm gfxmenu png hashsum gcry_sha256 crypto loadenv test' \
"boot/grub/grub.cfg=$src/boot/grub/embedded.cfg"
printf 'set prefix=($root)/grub\nconfigfile $prefix/grub.cfg\n' > "$work/EFI/BOOT/grub.cfg"
: "${RELIEFOS_KERNEL_TOOLS:?set RELIEFOS_KERNEL_TOOLS to the native Kbuild host tool}"
Expand All @@ -28,6 +28,7 @@ cp "$src/boot/grub/grub.cfg" "$work/grub/grub.cfg"
cp "$src/boot/grub/kernel-slots.cfg" "$work/grub/kernel-slots.cfg"
cp "$src/boot/grub/other-systems.cfg" "$work/grub/other-systems.cfg"
cp "$src/boot/grub/theme/theme.txt" "$work/grub/theme/theme.txt"
cp "$src/boot/grub/theme/background.png" "$work/grub/theme/background.png"
cp -a "$bios/." "$work/grub/i386-pc/"
find "$work" -exec touch -h -d "@$epoch" {} +
# The private stage is owned by this rule; a previous stage is retained until
Expand Down
231 changes: 231 additions & 0 deletions tools/test_grub_menu_qemu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Exercise the production graphical GRUB submenu in BIOS and UEFI QEMU.

A fixture provides already-validated slot metadata. The production selection,
launch guard, exports, menu and theme run in real GRUB; only kernel/module/boot
commands are replaced with serial probes. This checks menu navigation and boot
arguments, not payload verification, a running kernel or a complete OS boot.
Requires grub-mkrescue, xorriso, QEMU, OVMF, Pillow and tesseract.
"""
import argparse
import json
import os
from pathlib import Path
import re
import shutil
import socket
import subprocess
import time

from PIL import Image

from qemu_control import qmp_quit

ROOT = Path(__file__).resolve().parents[1]
TITLES = ("Start with dracut and show startup messages", "Pause after startup diagnostics",
"Start without kernel log colors", "Previous complete kernel")
OPTIONS = ("systemd.show_status=yes", "bootlog-pause=1", "logcolor=0", "reliefos.boot_slot=A")


def selector_fixture(fallback):
source = (ROOT / "boot/grub/kernel-slots.cfg").read_text()
fields = {"valid": "1", "generation": "1", "release": "confirmed-0123456789ab",
"initramfs": "aaa", "confirmed": "1", "remaining": "0"}
lines = [f"set reliefos_a_{key}={value}" for key, value in fields.items()]
fields.update(generation="2", release="active-fedcba987654", initramfs="bbb",
confirmed="0" if fallback else "1")
lines += [f"set reliefos_b_{key}={value}" for key, value in fields.items()]
for name in ("select_a", "select_b", "boot_paths", "prepare_boot"):
match = re.search(r"^function reliefos_" + name + r" \{\n.*?^\}", source, re.M | re.S)
if not match:
raise ValueError(f"missing production function reliefos_{name}")
lines.append(match[0])
lines += ["reliefos_select_b", "reliefos_boot_paths",
"set reliefos_previous_release=$reliefos_a_release",
"set reliefos_previous_directory=$reliefos_directory/reliefos/versions/$reliefos_a_release/$reliefos_a_initramfs",
"set reliefos_previous_slot=A", "set reliefos_previous_generation=1",
"set reliefos_previous_initramfs=aaa"]
lines += re.findall(r"^export .*$", source, re.M)
return "\n".join(lines) + "\n"


def build_fixture(output, fallback):
tree = output / "tree"
grub = tree / "boot/grub"
shutil.copytree(ROOT / "boot/grub/theme", grub / "theme")
(grub / "fonts").mkdir()
shutil.copyfile("/usr/share/grub/unicode.pf2", grub / "fonts/unicode.pf2")
config = (ROOT / "boot/grub/grub.cfg").read_text()
# Retain every menu argument and guard; never load a kernel in this fixture.
config = re.sub(r"\bmultiboot2 (?=\$reliefos_)", "menu_probe_kernel ", config)
config = re.sub(r"\bmodule2 (?=\$reliefos_)", "menu_probe_module ", config)
config = re.sub(r"(?m)^(\s*)boot$", r"\1menu_probe_boot", config)
config += '''
set timeout=-1
function menu_probe_kernel {
terminal_output console serial
echo "MENU_KERNEL: $*"
}
function menu_probe_module {
echo "MENU_INITRAMFS: $*"
}
function menu_probe_boot {
echo "MENU_LAUNCH_OK"
sleep --interruptible 60
}
'''
(grub / "grub.cfg").write_text(config)
(grub / "kernel-slots.cfg").write_text(selector_fixture(fallback))
(grub / "other-systems.cfg").write_text("")
identity = tree / "boot/reliefos/config"
identity.mkdir(parents=True)
(identity / "root.cfg").write_text(
"set reliefos_root=PARTUUID=12345678-1234-1234-1234-123456789abc\n")
iso = output / "menu.iso"
with (output / "build.log").open("w") as log:
subprocess.run(["grub-mkrescue", "-o", str(iso), str(tree)], check=True,
stdout=log, stderr=log)
return iso


class Monitor:
def __init__(self, path):
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.settimeout(10)
self.socket.connect(str(path))
self.stream = self.socket.makefile("rwb", buffering=0)
self.stream.readline()
self.command("qmp_capabilities")

def close(self):
self.stream.close()
self.socket.close()

def command(self, name, **arguments):
self.stream.write((json.dumps({"execute": name, "arguments": arguments}) + "\n").encode())
while True:
response = json.loads(self.stream.readline())
if "error" in response:
raise RuntimeError(response["error"])
if "return" in response:
return response["return"]

def key(self, name):
self.command("send-key", keys=[{"type": "qcode", "data": name}], **{"hold-time": 80})
time.sleep(.2)

def screen(self, output, name):
ppm = output / (name + ".ppm")
self.command("screendump", filename=str(ppm))
with Image.open(ppm) as picture:
picture.save(output / (name + ".png"))
# The menu text sits in the right half; enlarge it for stable OCR.
region = picture.crop((picture.width // 3, picture.height // 4,
picture.width, picture.height * 3 // 4))
region = region.convert("L").point(lambda value: 0 if value > 60 else 255)
region.resize((region.width * 3, region.height * 3)).save(output / "ocr.png")
text = subprocess.check_output(["tesseract", str(output / "ocr.png"), "stdout",
"--psm", "6"], stderr=subprocess.DEVNULL, text=True,
env={**os.environ, "OMP_THREAD_LIMIT": "1"}, timeout=10)
(output / (name + ".txt")).write_text(text)
return text


def check(args, firmware, iso, index, fallback):
name = "fallback" if fallback else str(index)
output = args.output / (firmware + "-" + name)
output.mkdir()
qmp, serial = output / "qmp.sock", output / "serial.log"
command = ["qemu-system-x86_64", "-machine", "q35", "-accel", "tcg", "-m", "256",
"-vga", "std", "-display", "none", "-serial", f"file:{serial}",
"-qmp", f"unix:{qmp},server=on,wait=off", "-nic", "none",
"-cdrom", str(iso), "-boot", "d"]
if firmware == "uefi":
shutil.copyfile(args.ovmf_vars, output / "vars.fd")
command += ["-drive", f"if=pflash,format=raw,unit=0,readonly=on,file={args.ovmf}",
"-drive", f"if=pflash,format=raw,unit=1,file={output}/vars.fd"]
(output / "command.json").write_text(json.dumps(command, indent=2) + "\n")
monitor = None
with (output / "qemu.log").open("w") as log:
process = subprocess.Popen(command, stdout=log, stderr=log)
try:
deadline = time.monotonic() + args.timeout
while not qmp.exists():
if time.monotonic() > deadline or process.poll() is not None:
raise RuntimeError(f"QEMU did not start: {output}")
time.sleep(.05)
monitor = Monitor(qmp)
while True:
text = monitor.screen(output, "main")
if "Advanced" in text:
break
if time.monotonic() > deadline:
raise AssertionError(f"main menu missing: {output}: {text}")
time.sleep(.3)
for visit in range(2):
monitor.key("down")
monitor.key("ret")
time.sleep(.4)
text = monitor.screen(output, f"submenu-{visit}")
assert all(title in text for title in TITLES), (output, text)
assert "error:" not in text.lower() and "Press any key" not in text, (output, text)
if visit == 0:
monitor.key("esc")
# GRUB remembers the selected main-menu entry.
monitor.key("up")
for _ in range(index):
monitor.key("down")
monitor.key("ret")
deadline = time.monotonic() + 5
while True:
text = serial.read_text(errors="replace") if serial.exists() else ""
if "MENU_LAUNCH_OK" in text:
break
if time.monotonic() > deadline:
monitor.screen(output, "failed-launch")
raise AssertionError(f"launch failed: {output}: {text}")
time.sleep(.1)
# GRUB's serial terminal may wrap in the middle of a pathname.
compact = "".join(text.split())
old = fallback or index == 3
release, digest, slot = (("confirmed-0123456789ab", "aaa", "A") if old else
("active-fedcba987654", "bbb", "B"))
assert f"/versions/{release}/{digest}/kernel.sys" in compact, compact
assert f"/versions/{release}/{digest}/initramfs.cpio" in compact, compact
assert f"reliefos.boot_slot={slot}" in compact, compact
assert OPTIONS[index] in compact, compact
assert "log=screen,serial" in compact, compact
print(f"PASS {firmware}: {name}: navigation, theme, selected kernel and boot arguments", flush=True)
finally:
if monitor:
monitor.close()
qmp_quit(qmp, process)


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--firmware", choices=("bios", "uefi", "both"), default="both")
parser.add_argument("--ovmf", type=Path, default=Path("/usr/share/OVMF/OVMF_CODE.fd"))
parser.add_argument("--ovmf-vars", type=Path, default=Path("/usr/share/OVMF/OVMF_VARS.fd"))
parser.add_argument("--timeout", type=int, default=30)
args = parser.parse_args()
args.output = args.output.resolve()
if not args.output.is_relative_to(ROOT / "out") or args.output.exists():
parser.error("--output must be a new directory under out/")
if len(str(args.output / "uefi-fallback/qmp.sock").encode()) >= 108:
parser.error("--output path is too long for a QMP Unix socket")
args.output.mkdir(parents=True)
normal, fallback = args.output / "normal", args.output / "fallback"
normal.mkdir()
fallback.mkdir()
images = build_fixture(normal, False), build_fixture(fallback, True)
for firmware in (("bios", "uefi") if args.firmware == "both" else (args.firmware,)):
for index in range(4):
check(args, firmware, images[0], index, False)
check(args, firmware, images[1], 0, True)


if __name__ == "__main__":
main()