diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 51695b80..c5f376fd 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -72,6 +72,17 @@ jobs: - name: Make the patched tree run: spin-machine-dev patched tree ${{ matrix.part }} + - name: What a traced build needs + if: ${{ matrix.build-mode == 'manual' }} + run: go tool task patched-build-deps + + # Before the tracer starts: what is built here is not extracted, and the analysis reads only + # what the step under it compiles (the kernel's bzImage, built here when a touched file is one + # only it builds, would be the whole kernel). + - name: Build what compiling the touched files needs, untraced + if: ${{ matrix.build-mode == 'manual' }} + run: spin-machine-dev patched prepare ${{ matrix.part }} + - name: Initialize CodeQL uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4 with: @@ -80,10 +91,6 @@ jobs: source-root: _output/patched/${{ matrix.part }}/src queries: security-extended - - name: What a traced build needs - if: ${{ matrix.build-mode == 'manual' }} - run: go tool task patched-build-deps - - name: Compile what the patches touch, traced if: ${{ matrix.build-mode == 'manual' }} run: spin-machine-dev patched compile ${{ matrix.part }} diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml index 4b468a76..c10100eb 100644 --- a/.github/workflows/compat.yml +++ b/.github/workflows/compat.yml @@ -4,8 +4,9 @@ name: Compat # machine's record still refuses what QEMU loads silently and accepts the machine's own checkpoint # (boot:compat, boot:record): on every pull request and push to main that changes what a resumed # guest is loaded into - the machine's definition, QEMU, the kernel, the firmware and their pins - -# and before every release. And whether that kernel, booted, is locked down (boot:lockdown), and -# whether a guest checkpointed and continued still grows (boot:cpu-plug). +# and before every release. And whether that kernel, booted, is locked down (boot:lockdown) and at +# a random base every boot (boot:kaslr), and whether a guest checkpointed and continued still grows +# (boot:cpu-plug). # # How long a checkpoint stops the guest (boot:checkpoint-pause) is a bound, not compatibility: it # runs on the bench, on each release (release.yml's pause) and at a QEMU bump (versions.yaml). @@ -198,6 +199,14 @@ jobs: - name: The kernel is locked down run: go tool task boot:lockdown + # The same kernel across ten boots: its virtual base, its physical base and the regions + # RANDOMIZE_MEMORY moves each take more than one value and never the unrandomized one. One + # boot cannot tell a random address from a fixed one, and the vmlinux the machine enters + # through PVH is randomized by kernel/patches/0014-0020 and qemu/patches/0008, none of which + # anything else here would miss (#645). + - name: The kernel is somewhere else every boot + run: go tool task boot:kaslr + # The run passed, or the change does not reach the machine: the one check of this workflow a # ruleset can require. A `resume` that failed or was cancelled, or a `changed` that could not # say, is not a pass. diff --git a/.github/workflows/lab.yml b/.github/workflows/lab.yml index 9db1ce24..f1f84073 100644 --- a/.github/workflows/lab.yml +++ b/.github/workflows/lab.yml @@ -36,6 +36,7 @@ on: - bootchart - ledger - exits + - check:kaslr - check:firmware - check:firmware-stages - check:waits diff --git a/Taskfile.yml b/Taskfile.yml index 80da0457..c98412c0 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -120,7 +120,7 @@ tasks: - sudo apt-get install -y -q graphviz patched-build-deps: - desc: What `spin-machine-dev patched compile` needs to compile the kernel's and QEMU's touched files (codeql.yml runs it by this name). + desc: What `spin-machine-dev patched prepare` and `compile` need to compile the kernel's and QEMU's touched files (codeql.yml runs it by this name). cmds: - sudo apt-get update -q - sudo apt-get install -y -q --no-install-recommends bc bison flex libelf-dev libssl-dev dwarves ninja-build libglib2.0-dev libpixman-1-dev python3-venv diff --git a/boot/Taskfile.yml b/boot/Taskfile.yml index 7d840288..f89e4c8b 100644 --- a/boot/Taskfile.yml +++ b/boot/Taskfile.yml @@ -210,6 +210,15 @@ tasks: cmds: - SPIN_LOCKDOWN_TEST=1 go test ./boot/ -run '^TestTheGuestKernelIsLockedDown$' -count=1 -v -timeout 5m + kaslr: + desc: >- + Check the kernel's virtual base, physical base and RANDOMIZE_MEMORY regions each move, + across SPIN_KASLR_BOOTS boots (default 10) in spin's base shape (kaslr_test.go, #645). + Needs a built release and /dev/kvm. + deps: [':tools'] + cmds: + - SPIN_KASLR_TEST=1 go test ./boot/ -run '^TestTheKernelMovesEveryBoot$' -count=1 -v -timeout 15m + cpu-plug: desc: >- A workspace checkpointed with memory and continued still grows: spin's shape booted to diff --git a/boot/kaslr_test.go b/boot/kaslr_test.go new file mode 100644 index 00000000..b5bb15e7 --- /dev/null +++ b/boot/kaslr_test.go @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 + +package boot_test + +import ( + "cmp" + "os" + "regexp" + "strconv" + "testing" + + "github.com/spin-stack/machine/machine" +) + +// KASLR moves three things, and a kernel that boots says nothing when one of them stays put: the +// kernel's virtual base (_text), its physical base ("Kernel code" in /proc/iomem), and with +// RANDOMIZE_MEMORY the direct map, vmalloc and vmemmap regions. Each is read in SPIN_KASLR_BOOTS +// guests (default 10) of spin's base shape, 1 vCPU and 128 MiB, the least memory the physical +// base is chosen in, and each must take more than one value. +// One boot cannot tell a fixed address from a random one, and a vmlinux entered through PVH moved +// neither base nor the regions, with CONFIG_RANDOMIZE_BASE and RANDOMIZE_MEMORY both =y (#645). +// +// The regions are seen through the lowest vmalloc address and the lowest unix socket, a direct +// map object, each rounded down to the 1 GiB that kernel_randomize_memory aligns a region to. +// Unrandomized they sit at the region's fixed base whatever the boot allocated. A %p hash, which +// an earlier version of this check compared, differs every boot whatever the layout, and is +// refused as not a kernel address. vmemmap moves with the other two or not at all: one test of +// KASLR_FLAG gates all three (kernel/patches/0019). +func TestTheKernelMovesEveryBoot(t *testing.T) { + if os.Getenv("SPIN_KASLR_TEST") != "1" { + t.Skip("set SPIN_KASLR_TEST=1 to boot a built release repeatedly and compare where its kernel is") + } + boots, err := strconv.Atoi(cmp.Or(os.Getenv("SPIN_KASLR_BOOTS"), "10")) + if err != nil || boots < 2 { + t.Fatalf("SPIN_KASLR_BOOTS=%q: two boots at least", os.Getenv("SPIN_KASLR_BOOTS")) + } + out := releaseTree(t) + rel, err := machine.OpenRelease(out) + if err != nil { + t.Fatal(err) + } + base, err := rel.Rootfs() + if err != nil { + t.Fatal(err) + } + root := newRawRoot(t, out, base) + oneshotAtBoot(t, root, "kaslr-check", "kaslr-check.sh", "") + + line := regexp.MustCompile(`KASLR text=([0-9a-f]+) phys=([0-9a-f]+) vmalloc=([0-9a-f]+) directmap=([0-9a-f]+)`) + // Where a region is unrandomized, with 4-level paging and with 5-level. A randomized region + // lands there about once in thousands of boots. The bases are not checked so: a random + // kernel is at its linked _text about once in 480 boots, and at its linked physical base in + // 128 MiB about once in 36, so their check is only that they moved. + fixed := map[string][]uint64{ + "vmalloc": {0xffffc90000000000, 0xffa0000000000000}, + "directmap": {0xffff888000000000, 0xff11000000000000}, + } + what := []string{"text", "phys", "vmalloc", "directmap"} + seen := map[string]map[uint64]bool{} + for _, w := range what { + seen[w] = map[uint64]bool{} + } + for i := range boots { + console := checkGuest(t, rel, root, "KASLR_CHECK_OK", "KASLR_CHECK_FAILED", func(s *machine.Spec) { + s.BootCPUs = 1 + s.Memory.BaseMB = 128 + }, func(*machine.QEMU, string) {}) + m := line.FindStringSubmatch(console) + if m == nil { + t.Fatalf("boot %d: no KASLR line on the console:\n%s", i+1, console) + } + t.Logf("boot %d: _text %s, Kernel code at %s, lowest vmalloc %s, lowest unix socket %s", i+1, m[1], m[2], m[3], m[4]) + for j, what := range what { + v, err := strconv.ParseUint(m[j+1], 16, 64) + if err != nil { + t.Fatalf("boot %d: %s %q: %v", i+1, what, m[j+1], err) + } + if what == "vmalloc" || what == "directmap" { + if v < 0xff00000000000000 { + t.Fatalf("boot %d: %s %#x is not a kernel address: a hash, or a pointer kptr_restrict hid", i+1, what, v) + } + v &^= 1<<30 - 1 + } + seen[what][v] = true + } + } + for _, w := range what { + for _, a := range fixed[w] { + if seen[w][a] { + t.Errorf("%s was at %#x, where it is unrandomized, in a boot", w, a) + } + } + if len(seen[w]) < 2 { + t.Errorf("%s took one value in %d boots (the boots above)", w, boots) + } + } +} diff --git a/boot/testdata/kaslr-check.sh b/boot/testdata/kaslr-check.sh new file mode 100644 index 00000000..9bfcbaaf --- /dev/null +++ b/boot/testdata/kaslr-check.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# SPDX-License-Identifier: Apache-2.0 +set -eu +trap 'echo KASLR_CHECK_FAILED' EXIT + +if grep -qw nokaslr /proc/cmdline; then + echo "the kernel was booted with nokaslr: $(cat /proc/cmdline)" + exit 1 +fi +# 1 and not 0: at 0, %pK prints a hash that differs every boot whatever the layout, and only +# kallsyms printed a real address. At 1 root, holding CAP_SYSLOG, reads every address as it is. +echo 1 > /proc/sys/kernel/kptr_restrict +text=$(awk '$3 == "_text" { print $1 }' /proc/kallsyms) +phys=$(awk -F'[- :]+' '/Kernel code/ { print $2; exit }' /proc/iomem) +# The lowest vmalloc address, near vmalloc_base, and the lowest unix socket, an object in the +# direct map near page_offset_base: the two regions RANDOMIZE_MEMORY moves that root can see. +vmalloc=$(awk 'NR == 1 { split($1, a, "-"); sub("^0x", "", a[1]); print a[1] }' /proc/vmallocinfo) +directmap=$(awk -F: 'NR > 1 { print $1 }' /proc/net/unix | sort | head -1) +test -n "$text" && test -n "$phys" && test -n "$vmalloc" && test -n "$directmap" +test "$phys" != 00000000 + +trap - EXIT +echo "KASLR text=$text phys=$phys vmalloc=$vmalloc directmap=$directmap" +echo KASLR_CHECK_OK diff --git a/boot/testdata/lockdown-check.sh b/boot/testdata/lockdown-check.sh index 6086b658..94ee3cc1 100644 --- a/boot/testdata/lockdown-check.sh +++ b/boot/testdata/lockdown-check.sh @@ -20,9 +20,10 @@ if echo none > /sys/kernel/security/lockdown 2>/dev/null; then fi grep -q '\[confidentiality\]' /sys/kernel/security/lockdown -# The kernel is at a random address (KASLR). It is the bzImage's decompressor that picks one. -# Until 2026-11-19 the machine entered vmlinux through PVH, which skips it, and the kernel ran -# where it was linked, ffffffff81000000, with CONFIG_RANDOMIZE_BASE=y all the same. So the address +# The kernel is at a random address (KASLR). Until 2026-11-19 the machine entered a vmlinux +# through PVH that could not move, and the kernel ran where it was linked, ffffffff81000000, with +# CONFIG_RANDOMIZE_BASE=y all the same. The vmlinux entered now moves itself (#645), and +# boot:kaslr asks where across boots; this asks one boot. So the address # is asked of the kernel: _text, readable to root once kptr_restrict is 0, and not the linked # one. A randomized kernel lands on that one 2 MiB slot about once in 480 boots (the slots of a # 1 GiB kernel image space, less the first 16 MiB and the kernel's own size), so a failure here diff --git a/cmd/spin-machine-dev/build.go b/cmd/spin-machine-dev/build.go index 5799d0fd..c19ae2c7 100644 --- a/cmd/spin-machine-dev/build.go +++ b/cmd/spin-machine-dev/build.go @@ -66,8 +66,8 @@ every one when none is named, with what a named part is made with. A part is built when it is missing or stale. Each one leaves a manifest in _output/manifest naming a digest of its inputs - the build arguments versions.yaml gives its Dockerfile and every file under its directory - and one whose inputs have not moved, and whose output still verifies, is left as it -is. Every part is verified after it is built: the binaries run here, the kernel is a relocatable -bzImage, the tools are the pinned version (verify says what each checks). +is. Every part is verified after it is built: the binaries run here, the kernel is a vmlinux that +randomizes itself, the tools are the pinned version (verify says what each checks). In a workflow it writes what each part is to the run's summary, and qemu_version to the step's outputs.`, @@ -172,7 +172,7 @@ func verifyCmd() *cobra.Command { the machine type every checkpoint is saved on (a newer one is said, not failed), and the TCG binary's query-qmp-schema has every QMP command and event the module defines, as the module defines it - kernel a bzImage whose setup header says relocatable, and the vmlinux it was made from + kernel a vmlinux with both Xen notes and a filled .data.reloc, and a relocatable bzImage e2fsprogs the four tools and mke2fs.conf, and mkfs.ext4 answers the pinned version systemd the packages the image installs openssh the packages the image installs diff --git a/cmd/spin-machine-dev/edges_test.go b/cmd/spin-machine-dev/edges_test.go index f76e2766..0bee0e21 100644 --- a/cmd/spin-machine-dev/edges_test.go +++ b/cmd/spin-machine-dev/edges_test.go @@ -17,10 +17,11 @@ import ( "github.com/spf13/cobra" "github.com/spin-stack/machine/internal/build" + "github.com/spin-stack/machine/internal/elftest" "github.com/spin-stack/machine/machine" ) -// kernelFixture is a relocatable bzImage and a vmlinux carrying a Xen note, as kernel/Dockerfile +// kernelFixture is a relocatable bzImage and a vmlinux that randomizes itself, as kernel/Dockerfile // leaves them. func kernelFixture(t *testing.T, out string) { t.Helper() @@ -28,23 +29,18 @@ func kernelFixture(t *testing.T, out string) { copy(bz[0x202:], "HdrS") bz[0x234] = 1 put(t, filepath.Join(out, "kernel/bzImage"), string(bz), 0o644) - var note bytes.Buffer - _ = binary.Write(¬e, binary.LittleEndian, []uint32{4, 4, 18}) - note.WriteString("Xen\x00\x00\x00\x00\x01") - var b bytes.Buffer - h := elf.Header64{Type: uint16(elf.ET_EXEC), Machine: uint16(elf.EM_X86_64), Version: uint32(elf.EV_CURRENT), - Phoff: 64, Ehsize: 64, Phentsize: 56, Phnum: 1, Shentsize: 64} - copy(h.Ident[:], elf.ELFMAG) - h.Ident[elf.EI_CLASS], h.Ident[elf.EI_DATA], h.Ident[elf.EI_VERSION] = byte(elf.ELFCLASS64), byte(elf.ELFDATA2LSB), byte(elf.EV_CURRENT) - _ = binary.Write(&b, binary.LittleEndian, h) - _ = binary.Write(&b, binary.LittleEndian, elf.Prog64{Type: uint32(elf.PT_NOTE), Off: 120, Filesz: uint64(note.Len()), Memsz: uint64(note.Len())}) - b.Write(note.Bytes()) - put(t, filepath.Join(out, "kernel/vmlinux"), b.String(), 0o644) + put(t, filepath.Join(out, "kernel/vmlinux"), string(vmlinuxFixture()), 0o644) for _, f := range []string{"kernel/kernel-config", "kernel/sources", "kernel/patches/0001-k.patch"} { put(t, filepath.Join(out, f), f, 0o644) } } +// vmlinuxFixture is a vmlinux that verify kernel takes for one that randomizes itself: both Xen +// notes and a filled .data.reloc. +func vmlinuxFixture() []byte { + return elftest.Kernel([]uint32{18, 19}, []byte{0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0x10, 0, 0, 0}) +} + // everything is a whole built _output: what every part's build leaves, and spin-machine. func everything(t *testing.T, dir string) string { t.Helper() diff --git a/cmd/spin-machine-dev/patched.go b/cmd/spin-machine-dev/patched.go index 782eeeaf..448e20a0 100644 --- a/cmd/spin-machine-dev/patched.go +++ b/cmd/spin-machine-dev/patched.go @@ -37,11 +37,29 @@ in /patched/. Parts: ` + strings.Join(patched.Names(), ", ") + `.`, say(c, "%s: %s", p.Name, filepath.Join(dir, "src")) return nil }, + }, &cobra.Command{ + Use: "prepare ", + Short: "Build what compiling a part's touched C files needs, before an analysis traces the compiler", + Long: `Build in /patched//src, which tree made, what compile needs, so that only the touched +files are compiled under CodeQL's tracer: the kernel configured from kernel/, with its bzImage when +a touched file is one only the bzImage builds. codeql.yml runs it before the tracer starts.`, + Args: cobra.ExactArgs(1), + RunE: func(c *cobra.Command, args []string) error { + w, p, dir, err := patchedPart(args[0]) + if err != nil { + return err + } + if err := patched.Prepare(c.Context(), w.root, p, dir, c.ErrOrStderr()); err != nil { + return couldNot(err) + } + say(c, "%s: prepared", p.Name) + return nil + }, }, &cobra.Command{ Use: "compile ", Short: "Compile the C files a part's patches touch in its tree, for an analysis tracing the compiler", - Long: `Compile the C files the part's patches touch in /patched//src, which tree made, as -the part's build would: the kernel from its configuration in kernel/, QEMU for x86_64-softmmu. + Long: `Compile the C files the part's patches touch in /patched//src, which prepare readied, +as the part's build would: the kernel from its configuration in kernel/, QEMU for x86_64-softmmu. codeql.yml runs it under CodeQL's tracer for the parts whose files include headers only their builds generate. Parts that have it: ` + strings.Join(traced(), ", ") + `.`, Args: cobra.ExactArgs(1), diff --git a/cmd/spin-machine-dev/patched_test.go b/cmd/spin-machine-dev/patched_test.go index 1da15352..84ba697a 100644 --- a/cmd/spin-machine-dev/patched_test.go +++ b/cmd/spin-machine-dev/patched_test.go @@ -113,6 +113,9 @@ func TestPatchedCompileRefusesAPartWithNothingToCompile(t *testing.T) { if _, stderr, status := verb(t, "patched", "compile", "qboot"); status != 2 || !strings.Contains(stderr, "without a build") { t.Errorf("status %d, %s", status, stderr) } + if _, stderr, status := verb(t, "patched", "prepare", "qboot"); status != 2 || !strings.Contains(stderr, "nothing to prepare") { + t.Errorf("prepare: status %d, %s", status, stderr) + } } func TestPatchedCompileNamesThePartsItCompiles(t *testing.T) { diff --git a/cmd/spin-machine-dev/verbs_test.go b/cmd/spin-machine-dev/verbs_test.go index fcd3bbbe..71b69d56 100644 --- a/cmd/spin-machine-dev/verbs_test.go +++ b/cmd/spin-machine-dev/verbs_test.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "os" "os/exec" "path/filepath" @@ -206,7 +207,7 @@ func kernelDocker(extra string) string { mkdir -p "$dest/kernel"; head -c 1024 /dev/zero > "$dest/kernel/bzImage" printf HdrS | dd of="$dest/kernel/bzImage" bs=1 seek=514 conv=notrunc 2>/dev/null printf '\001' | dd of="$dest/kernel/bzImage" bs=1 seek=564 conv=notrunc 2>/dev/null -cp /proc/self/exe "$dest/kernel/vmlinux" +printf '` + printfEscaped(vmlinuxFixture()) + `' > "$dest/kernel/vmlinux" if [ "$lockdown" = none ]; then printf '# CONFIG_LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY is not set\nCONFIG_LOCK_DOWN_KERNEL_FORCE_NONE=y\nCONFIG_BPF_LSM=y\n` + extra + `' > "$dest/kernel/kernel-config" else @@ -214,6 +215,15 @@ else fi` } +// printfEscaped is b as a printf format of octal escapes, which sh's printf writes back as b. +func printfEscaped(b []byte) string { + var s strings.Builder + for _, c := range b { + fmt.Fprintf(&s, "\\%03o", c) + } + return s.String() +} + // The traceable kernel is the release kernel with lockdown forced to none and nothing else: it is // put beside the release only then, and an option that moved with it is refused by name. func TestTheTraceableKernelIsTheReleaseKernelLessLockdown(t *testing.T) { diff --git a/cmd/spin-machine/commands_test.go b/cmd/spin-machine/commands_test.go index 0e8e410f..efc8bcc8 100644 --- a/cmd/spin-machine/commands_test.go +++ b/cmd/spin-machine/commands_test.go @@ -186,7 +186,7 @@ func TestFlagsAreTheSpec(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "not a bzImage") { + if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "neither a bzImage") { t.Errorf("a --kernel that is not a bzImage: %v", err) } } diff --git a/cmd/spin-machine/main.go b/cmd/spin-machine/main.go index 696e1f6d..2148a0e1 100644 --- a/cmd/spin-machine/main.go +++ b/cmd/spin-machine/main.go @@ -225,7 +225,7 @@ type machineFlags struct { func (o *machineFlags) register(fs *flag.FlagSet) { fs.StringVar(&o.release, "release", "_output", "an unpacked release tree; every path below defaults out of it") fs.StringVar(&o.qemu, "qemu", "", "QEMU binary (default: /bin/qemu-system-x86_64)") - fs.StringVar(&o.kernel, "kernel", "", "kernel image, a bzImage (default: /kernel/bzImage)") + fs.StringVar(&o.kernel, "kernel", "", "kernel image, a vmlinux entered through PVH or a bzImage (default: the one the release boots, its vmlinux when it randomizes itself)") fs.StringVar(&o.initrd, "initrd", "", "initrd (default: none)") fs.StringVar(&o.firmware, "firmware", "", "firmware directory (default: /qemu)") fs.StringVar(&o.bios, "bios", "", "the BIOS, a file in the firmware directory (default: "+machine.DefaultBIOS+"; bios-256k.bin is SeaBIOS)") diff --git a/docs/boot-time.md b/docs/boot-time.md index c3079987..a9855b74 100644 --- a/docs/boot-time.md +++ b/docs/boot-time.md @@ -130,7 +130,7 @@ not a measurement: it says how far each phase has to move. |---|---|---|---|---| | QEMU's exec to a guest ready to run | ~28 | cold 456 less the boot into a QEMU started ahead, 428 (report 44811347183) | by difference, one run | 0, started ahead | | … of it, QMP: QEMU's main loop free to `cont` answered, 14 commands | 6.2 | `transport` `cold_qmp`, lab 44912471522 (v20261121.01); 4.5 of it QEMU waiting on spin-machine's next command | measured | | -| qboot and the bzImage's decompression, to the kernel's clock | 33.6 | `boot:firmware-stages`, lab 44787491631 (v20261120.02's kernel); ~21 of it is the decompression KASLR needs | measured, another run | 5 | +| qboot and the bzImage's decompression, to the kernel's clock | 33.6 | `boot:firmware-stages`, lab 44787491631 (v20261120.02's kernel); ~21 of it is the decompression KASLR needed, which the machine no longer runs since #645 (first login −16.8, "What the machine carries") | measured, another run | 5 | | The kernel's clock to "Freeing unused kernel image" | 79.9 | report 44811347183 | measured | 25 | | PID 1 to sshd accepting | ~255 | sshd accepts 396 (lab 44841266997) less the three rows above | by difference, across runs | 35 | | sshd's accept to the first login | 68.4 | `ssh-first` `accept_to_login`, lab 44841266997 | measured | 35 | @@ -213,13 +213,14 @@ them for boot time. | Kernel patches 0001-0005, 0007, 0008, 0010 | kernel/patches | cold +67.5 [+62.5, +72.4], with 0006, 0009 and 0011 (since deleted, worth nothing) | group A | lab 44818953987 | | Kernel 0012 (vmlinux BTF parsed on first use) and 0013 (the verifier asks for it only where a kernel type enters a program) | kernel/patches | cold −6.4 [−9.4, −1.0] at 60 a side (lab 45118194310, the kernel carried); before the review's fixes −10.0 [−12.7, −3.3] at 60 and −6.3 [−9.1, −4.6] at 120 (labs 45114405201, 45115330128); restored −1.0 [−6.0, +4.2] evicted, the state 1.3 MiB smaller (lab 45115341056) | measured | lab 45118194310 | | `BLK_DEV_LOOP_MIN_COUNT=0`, `SERIAL_8250_RUNTIME_UARTS=1` | kernel/config-7.3-x86_64 | cold +5.3 [−3.2, +15.0]: inside the noise, but the upper bound does not rule out its ~2-4 ms ceiling | measured, 40 a side | lab 44839538785 | -| `KERNEL_LZ4` | kernel/config-7.3-x86_64 | the alternatives lost: an uncompressed payload, on QEMU 0007, −4.0 [−7.9, +0.3] at 40 a side, within noise, and QEMU's RSS +32 MiB (lab 45183618987); before 0007, +9 ms in copies (laptop) | measured, 40 a side | lab 45183618987, #326 | +| `KERNEL_LZ4` | kernel/config-7.3-x86_64 | since #645 the compression of the shipped bzImage only, which this machine boots for a release before it (#660). Before, the alternatives lost: an uncompressed payload, on QEMU 0007, −4.0 [−7.9, +0.3] at 40 a side, within noise, and QEMU's RSS +32 MiB (lab 45183618987); before 0007, +9 ms in copies (laptop) | measured, 40 a side | lab 45183618987, #326 | | `VT=n`, `X86_MSR=n`, `X86_CPUID=n` | kernel/config-7.3-x86_64 | function: dead code, less surface | - | kernel/Dockerfile | | qboot instead of SeaBIOS | qemu, `machine.DefaultBIOS` | cold +68.5 [+62.7, +71.7] | group F | lab 44818953987 | | QEMU 0001 (device creation in one memory transaction) | qemu/patches | restored +11.7 [+0.9, +19.3], running +6.8 [+1.2, +8.8]: a restore starts QEMU too; cold +0.2 [−8.7, +7.1]. With `pam.patch`, cold +11.5 [+6.7, +20.2] (group B, lab 44818953987) | measured, 20 a side | lab 44993254745 | | qboot `pam.patch` (PAM in three writes) | qemu/qboot | cold +3.9 [−3.4, +8.0]: inside the noise, and the upper bound over +5 keeps it (rule 5 of docs/measuring.md) | measured, 40 a side | lab 44993790452 | | QEMU 0002, virtio-scsi `max_target`, which spin-machine passes | qemu/patches, machine | cold −8.9 [−15.5, −0.9] when it came in | measured | lab 44788216590 | -| QEMU 0007 (a bzImage given to `-kernel` mapped, not read into QEMU's heap, #646) | qemu/patches | first login −13.4 [−16.9, −7.3], sshd accepting −13.3 [−18.7, −7.5], 40 a side; restored −9.3 [−11.2, −6.1] evicted and −7.7 [−8.9, −5.1] cached (QEMU's start is on the restore's clock too); QEMU's anonymous RSS −15.9 MiB, its file RSS +16.1, the kernel now shared through the page cache. Twice the read's 6.2-6.9 ms traced in #611's split: what else the anonymous buffer cost nested was not measured. Prior art: upstream maps the initrd and, through PVH, an ELF kernel since QEMU 4.2 (Stefano Garzarella, [qemu-devel 2019-07-23](https://lists.gnu.org/archive/html/qemu-devel/2019-07/msg05164.html): `qemu_init_end` 63.85 → 55.91 ms for a 28 MB vmlinux and a 3.0 MB initrd), and [said](https://stefano-garzarella.github.io/posts/2019-12-22-qemu-kernel-initrd-mmapped) it was not available for a bzImage; [x86/loader: read complete kernel](https://lore.kernel.org/qemu-devel/20240905141211.1253307-4-kraxel@redhat.com/) (`214191f6b5`, merged 2024-12-16) made the read the whole file. No mapping of a bzImage found on qemu-devel (lists.gnu.org, lore, patchew) or in QEMU's history; Firecracker and Cloud Hypervisor ([rust-vmm/linux-loader](https://github.com/rust-vmm/linux-loader)) read the kernel straight into guest memory, with no firmware to copy it again; nothing measured found for qemu-lite | measured | labs 45182382388, 45182382864 | +| QEMU 0007 (a bzImage given to `-kernel` mapped, not read into QEMU's heap, #646) | qemu/patches | since #645 only for a release before it, whose bzImage this machine still boots (#660). When it came in: first login −13.4 [−16.9, −7.3], sshd accepting −13.3 [−18.7, −7.5], 40 a side; restored −9.3 [−11.2, −6.1] evicted and −7.7 [−8.9, −5.1] cached (QEMU's start is on the restore's clock too); QEMU's anonymous RSS −15.9 MiB, its file RSS +16.1, the kernel now shared through the page cache. Twice the read's 6.2-6.9 ms traced in #611's split: what else the anonymous buffer cost nested was not measured. Prior art: upstream maps the initrd and, through PVH, an ELF kernel since QEMU 4.2 (Stefano Garzarella, [qemu-devel 2019-07-23](https://lists.gnu.org/archive/html/qemu-devel/2019-07/msg05164.html): `qemu_init_end` 63.85 → 55.91 ms for a 28 MB vmlinux and a 3.0 MB initrd), and [said](https://stefano-garzarella.github.io/posts/2019-12-22-qemu-kernel-initrd-mmapped) it was not available for a bzImage; [x86/loader: read complete kernel](https://lore.kernel.org/qemu-devel/20240905141211.1253307-4-kraxel@redhat.com/) (`214191f6b5`, merged 2024-12-16) made the read the whole file. No mapping of a bzImage found on qemu-devel (lists.gnu.org, lore, patchew) or in QEMU's history; Firecracker and Cloud Hypervisor ([rust-vmm/linux-loader](https://github.com/rust-vmm/linux-loader)) read the kernel straight into guest memory, with no firmware to copy it again; nothing measured found for qemu-lite | measured | labs 45182382388, 45182382864 | +| The kernel entered as its vmlinux through PVH, randomizing itself: kernel 0014-0018 (Hou Wenlong's RFC, [the cover letter](https://lkml.iu.edu/2601.3/01845.html), lore `cover.1769434279.git.houwenlong.hwl@antgroup.com`, 2026-01-26, unchanged on 7.3.5), 0019 (sets `KASLR_FLAG`, without which `RANDOMIZE_MEMORY` did nothing), 0020 (RDRAND and TSC read from the registers that hold them), QEMU 0008 (a random physical base from `XEN_ELFNOTE_PHYS32_RELOC`), #645 | kernel/patches, qemu/patches, machine | first login −16.8 [−20.9, −13.0], 368 → 352, sshd accepting −16.7 [−20.2, −12.7], QEMU's RSS −13.8 MiB, 60 a side (lab 45219785493); restored −4.4 [−17.5, −2.0] evicted, −4.3 [−14.0, +10.2] cached, within noise, the state −31.9 MiB, the save −14.6 (lab 45219801969). The bound, the same vmlinux entered with no KASLR at all: −18.9 [−22.8, −12.4] cold, −3.6 [−5.1, −2.1] restored evicted at 40 a side (labs 45213668842, 45213683698), so KASLR without the decompressor costs ~2 ms against no KASLR (inferred across runs; Hou measured ~2 ms too). Arms booted the kernel without 0020. KASLR across 10 boots (lab 45221660056): `_text` 10 distinct, the physical base 8, the direct map and vmalloc each 10 distinct 1 GiB-aligned bases. Entropy: the virtual base the decompressor's slot rule and seed sources once 0020 is in, the physical base QEMU's `getrandom` over the decompressor's range, the regions the kernel's own (#645, "entropy"). Chosen over QEMU applying the relocations (Holmes et al., "KASLR in the age of MicroVMs", EuroSys '22, 20-25 ms over an LZ4 bzImage; Firecracker #5661, parked; rust-vmm/linux-loader #84, open): no relocation format for QEMU to parse, nothing new on its command line, the kernel's own entropy code | measured, 60 a side | labs 45219785493, 45219801969 | | qboot `no-pci-walk.patch` | qemu/qboot | cold +5.2 [−1.7, +9.2]: inside the noise, and the upper bound over +5 keeps it; 5.0 ms nested in `firmware-stages` | measured, 40 a side | lab 44993790452 | | qboot `mtrr.patch`, `write-pointer.patch` | qemu/qboot | function: write-back mappings, vmgenid | - | - | | `hpet=off` | machine | nothing on record: a timer the guest would enumerate and then not use | unmeasured | - | diff --git a/docs/cli.md b/docs/cli.md index 2f890cc1..4115becb 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -59,7 +59,7 @@ spin-machine-dev clean [--cache] remove _output; with --cache, the BuildKit A part's build first empties what it writes. `--output type=local` writes files and removes none, so a file the build stopped producing would otherwise stay, indistinguishable from one it produces. The build ends in its verification: the binaries run here and only the CI QEMU can -emulate, the kernel is a relocatable bzImage with the vmlinux it was made from, and the e2fsprogs +emulate, the kernel is a vmlinux that randomizes itself through PVH with a relocatable bzImage beside it, and the e2fsprogs tools answer the pinned version. `verify --help` says each. ## Keeping the pins current diff --git a/docs/log.md b/docs/log.md index d9f5dbe5..e4c8edc1 100644 --- a/docs/log.md +++ b/docs/log.md @@ -667,6 +667,8 @@ Checked against the probe it replaced on the bench fleet, `lab dispatch ssh-firs **11-23 · machine, qemu · QEMU's start and the held start's QMP, split and rejected (#647, #649, labs 45177818419, 45230790902, 45231358105, #669, this change).** #611's split left two cold phases without an owner. *#649, the held start's 14 commands, 6.1 ms on bench:* QEMU waited 4.5 ms p50 for the client, 0.9 of it busy with the probe's plug monitor (the memory spin sizes right after the start), so spin-machine's own share is ~3.6 ms, ~0.28 ms a round trip (24 boots, lab 45177818419). The candidate sent the bind ahead of its answers (`qmp.Send`): the run state with the places, every serial at once, each image's two nodes together, the reopen with the placeholder's delete, 13 round trips to 9; add-fd still holds the connection until its answer and `cont` waits for the bind. *Measured* (bench, nested, spin's shape and login, v20261123.06's parts, spin-machine main at f273377 against the candidate at c966407, 60 a side): first login −1.7 [−5.6, +2.6], sshd accepting −2.4 [−5.5, +2.8] (lab 45230790902); restored login −0.3 [−3.8, +3.7] evicted, +0.9 [−10.6, +7.5] cached (lab 45231358105). Rejected: the four round trips it removes are ~1.1 ms (inferred), and even all of spin-machine's 3.6 ms is under what 60 boots a side resolve. The code is on `archive/exp-649-held-start`. *#647, QEMU's exec to its first trace event, 9.7 ms on bench:* the release's QEMU is static-pie on musl, so there is no dynamic loader and `LD_DEBUG` has nothing to report; musl relocates its 59,700 relative relocations itself. The split, on the laptop as a lead (exec to the first `flatview_new`, 40 starts a row, 4.7-5.4 ms p50): a trivial static-pie binary 0.23, QEMU's `-version` 2.0, `-sandbox` −0.7 to −0.9, the rest option parsing, trace and main-loop start and the machine object. perf on an unstripped build of the same Dockerfile: relocation 7% of `-version`, page faults ~15%, nothing else over 2%. No candidate's ceiling is over ~2 ms on bench (inferred at ~2× the laptop): a seccomp filter compiled at build time (Firecracker's seccompiler), a non-PIE binary (which gives up ASLR), DT_RELR. None was built. The allocator, musl's mallocng, is ~2.3 of the 17 ms of CPU QEMU's main thread spends from exec to held, a lead across QEMU's whole start, opened as #669. *Status:* rejected, both. +**11-23 · kernel, qemu, machine · the kernel entered as its vmlinux through PVH, moving itself to a random base (#645, parts runs 45192017068, 45216245888, labs 45213668842, 45213683698, 45219768990, 45219785493, 45219801969, 45221660056, 45225297602, parts run 45222305257, #660, this change).** *Why:* a bzImage's decompressor spent ~21 ms (bench) on a copy, LZ4 and parse_elf before the kernel's clock, and it was the only thing that randomized the kernel; PVH skipped it and left the kernel at its linked address (11-19). *The bound first*, a vmlinux through PVH with no KASLR at all, against the same build as a bzImage: first login −18.9 [−22.8, −12.4], restored −3.6 [−5.1, −2.1] evicted, at 40 a side. *Two paths with KASLR kept:* QEMU applying the relocations (Holmes et al., EuroSys '22; Firecracker's design) or the kernel applying its own (Hou Wenlong's RFC, 2026-01-26). The kernel's own was chosen: no relocation format for QEMU to parse, nothing on QEMU's command line, the decompressor's entropy code (#645, issuecomment-7106937337). *Carried:* the RFC as kernel 0014-0018, made checkpatch --strict clean with each change noted in its header; 0019, which sets `KASLR_FLAG` once the kernel moved (without it `RANDOMIZE_MEMORY` left the regions where they were: the lowest vmalloc address ffffc90000000000 and the direct map ffff888000000000 at every one of 10 boots, lab 45225297602; with it, 10 distinct bases of each, lab 45221660056); 0020, because the RFC reads RDRAND from CPUID leaf 1's EDX and the TSC from its ECX, the wrong way round, so its virtual base was drawn from the i8254 and a hash of `boot_params` alone, on a guest that has `rdrand` and `tsc` and no `ds_cpl` (lab 45225297602); QEMU 0008, a random physical base from `XEN_ELFNOTE_PHYS32_RELOC`. The relocation table needs 0xc7000 bytes of the 1 MiB reserved: a 512 KiB reserve failed the link naming that size (parts run 45222305257). The machine boots a release's vmlinux when it carries both Xen notes and its bzImage otherwise, so a release from v20261119.02 to v20261123.06 boots as it did. *Measured* (bench, spin's shape and login, against v20261123.06, 60 a side, the kernel without 0020): first login 368 → 352, −16.8 [−20.9, −13.0], sshd accepting −16.7 [−20.2, −12.7], QEMU's RSS −13.8 MiB (lab 45219785493); restored −4.4 [−17.5, −2.0] evicted, −4.3 [−14.0, +10.2] cached, the state −31.9 MiB, the save −14.6 (lab 45219801969). *Status:* kept. What the bzImage, `KERNEL_LZ4` and QEMU 0007 still serve is #660. + ## 2. Rework cycles Each cycle: the sequence, what each step measured, and the lesson. diff --git a/internal/build/elf_test.go b/internal/build/elf_test.go index e66fdbc7..9f332bec 100644 --- a/internal/build/elf_test.go +++ b/internal/build/elf_test.go @@ -11,17 +11,15 @@ import ( "testing" "github.com/spin-stack/go-tools/versions" + + "github.com/spin-stack/machine/internal/elftest" ) -// A whole kernel is a relocatable bzImage and an ELF beside it. A Go binary is an ELF. +// A whole kernel is a relocatable bzImage and, beside it, a vmlinux that randomizes itself. func TestAWholeKernelVerifies(t *testing.T) { - self, err := os.Executable() - if err != nil { - t.Fatal(err) - } out := t.TempDir() b, _ := os.ReadFile(bzImage(t, "HdrS", 1)) - v, _ := os.ReadFile(self) + v := elftest.Kernel([]uint32{18, 19}, []byte{0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0x10, 0, 0, 0}) for p, body := range map[string][]byte{"kernel/bzImage": b, "kernel/vmlinux": v} { _ = os.MkdirAll(filepath.Dir(filepath.Join(out, p)), 0o755) _ = os.WriteFile(filepath.Join(out, p), body, 0o644) @@ -31,6 +29,39 @@ func TestAWholeKernelVerifies(t *testing.T) { } } +// A table is filled when its last word is a relocation, however short it is: one word is enough. +func TestAOneWordRelocationTableIsFilled(t *testing.T) { + path := filepath.Join(t.TempDir(), "vmlinux") + _ = os.WriteFile(path, elftest.Kernel([]uint32{18, 19}, []byte{0x10, 0, 0, 0}), 0o644) + if err := SelfRandomizing(path); err != nil { + t.Errorf("a one-word table: %v", err) + } +} + +// A vmlinux that would run where it was linked is refused, each way it can: QEMU cannot place it +// (no PHYS32_RELOC note), it cannot move itself (no .data.reloc), or the relocs tool never filled +// the table it reserved. +func TestAVmlinuxThatCannotMoveIsRefused(t *testing.T) { + filled := []byte{0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0x10, 0, 0, 0} + for _, tc := range []struct { + what string + notes []uint32 + reloc []byte + says string + }{ + {"no PVH entry", []uint32{19}, filled, "note 18"}, + {"no PHYS32_RELOC", []uint32{18}, filled, "note 19"}, + {"no .data.reloc", []uint32{18, 19}, nil, "no .data.reloc"}, + {"an unfilled table", []uint32{18, 19}, []byte{0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0}, "empty"}, + } { + path := filepath.Join(t.TempDir(), "vmlinux") + _ = os.WriteFile(path, elftest.Kernel(tc.notes, tc.reloc), 0o644) + if err := SelfRandomizing(path); err == nil || !strings.Contains(err.Error(), tc.says) { + t.Errorf("%s: %v, want an error saying %q", tc.what, err, tc.says) + } + } +} + func TestTheKernelSeriesNeedsAMajorAndAMinor(t *testing.T) { for version, want := range map[string]string{"7.3.5": "7.3", "7.3": "7.3", "10.11.12.13": "10.11", "7": "", "7.": "", ".3": ""} { v := &versions.Versions{Entries: []versions.Entry{{Name: "kernel", Version: version}}} diff --git a/internal/build/verify.go b/internal/build/verify.go index 6a27f780..75c6d25a 100644 --- a/internal/build/verify.go +++ b/internal/build/verify.go @@ -15,6 +15,8 @@ import ( "regexp" "slices" "strings" + + "github.com/spin-stack/machine/machine" ) // QEMUBinaries are what the QEMU build ships. qemu-img is not a convenience: a container's @@ -22,11 +24,12 @@ import ( // without it gives a container nowhere to write. var QEMUBinaries = []string{"qemu-system-x86_64", "qemu-system-x86_64-tcg", "qemu-img"} -// Firmware is what every consumer of QEMU needs beside it. linuxboot_dma.bin is the option ROM QEMU -// adds when -kernel is a bzImage, the kernel the machine boots; efi-virtio.rom is the option ROM of +// Firmware is what every consumer of QEMU needs beside it. pvh.bin is the option ROM QEMU adds +// when -kernel is an ELF kernel, the vmlinux the machine boots, and linuxboot_dma.bin the one it +// adds for a bzImage, which a release from before #645 boots; efi-virtio.rom is the option ROM of // the one NIC this build keeps, and a VM given a virtio-net-pci without it does not start; qboot.bin is the BIOS the machine boots with // (machine.DefaultBIOS), built beside QEMU from qemu/qboot/. -var Firmware = []string{"bios.bin", "bios-256k.bin", "linuxboot_dma.bin", "kvmvapic.bin", "efi-virtio.rom", "qboot.bin"} +var Firmware = []string{"bios.bin", "bios-256k.bin", "linuxboot_dma.bin", "pvh.bin", "kvmvapic.bin", "efi-virtio.rom", "qboot.bin"} // qbootSize is the ROM window qboot is linked for. const qbootSize = 64 << 10 @@ -87,20 +90,44 @@ func VerifyQEMU(o Options) error { return nil } -// VerifyKernel asserts the kernel is one QEMU can enter and this machine can boot: a relocatable -// bzImage, which is what the machine boots and where KASLR picks a base, and the same kernel as the -// ELF it was linked as, which spin reads symbols from (spin-stack/spin's hack/machine/place.go). +// VerifyKernel asserts the kernel is one QEMU can enter and this machine can boot at a random +// base: the vmlinux the machine enters through PVH, which spin also reads symbols from +// (spin-stack/spin's hack/machine/place.go), able to randomize itself (SelfRandomizing), and the +// relocatable bzImage beside it, which spin's place.go still asks a release for. func VerifyKernel(o Options) error { - bz := filepath.Join(o.Out, "kernel", "bzImage") - if err := Relocatable(bz); err != nil { + if err := Relocatable(filepath.Join(o.Out, "kernel", "bzImage")); err != nil { + return err + } + return SelfRandomizing(filepath.Join(o.Out, "kernel", "vmlinux")) +} + +// SelfRandomizing is whether the vmlinux at path can be put at a random base with no +// decompressor (#645): the Xen notes QEMU enters it and places it at a random physical base by +// (machine.PVH, qemu/patches/0008), and a filled relocation table in .data.reloc, which it moves +// its own virtual base with (kernel/patches/0014-0017). The table's last word is a relocation +// the relocs tool wrote; an unfilled table ends in the 0 it was reserved with, and the kernel +// stays where it was linked, booting all the same. boot:kaslr asks the kernel that boots. +func SelfRandomizing(path string) error { + if err := machine.PVH(path); err != nil { return err } - vmlinux := filepath.Join(o.Out, "kernel", "vmlinux") - f, err := elf.Open(vmlinux) + f, err := elf.Open(path) if err != nil { - return fmt.Errorf("reading %s as an ELF: %w", vmlinux, err) + return fmt.Errorf("reading %s as an ELF: %w", path, err) } - return f.Close() + defer func() { _ = f.Close() }() + sec := f.Section(".data.reloc") + if sec == nil || sec.Size < 4 { + return fmt.Errorf("%s has no .data.reloc: the kernel cannot move its virtual base", path) + } + last := make([]byte, 4) + if _, err := sec.ReadAt(last, int64(sec.Size)-4); err != nil { + return fmt.Errorf("reading %s's .data.reloc: %w", path, err) + } + if f.ByteOrder.Uint32(last) == 0 { + return fmt.Errorf("%s's .data.reloc is empty: the relocs tool did not fill it, and the kernel would run where it was linked", path) + } + return nil } // Relocatable is whether path is a bzImage whose setup header says relocatable: "HdrS" at 0x202, diff --git a/internal/elftest/elftest.go b/internal/elftest/elftest.go new file mode 100644 index 00000000..1e8b7586 --- /dev/null +++ b/internal/elftest/elftest.go @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package elftest writes the smallest ELF file that says what a kernel entered through PVH says +// about itself, for tests of what reads one: its Xen notes and its .data.reloc. +package elftest + +import ( + "bytes" + "debug/elf" + "encoding/binary" +) + +// Kernel is a 64-bit ELF with a PT_NOTE segment holding a "Xen" note of each type in notes, and, +// unless reloc is nil, a .data.reloc section holding reloc. +func Kernel(notes []uint32, reloc []byte) []byte { + var note bytes.Buffer + for _, n := range notes { + desc := make([]byte, 12) // PHYS32_RELOC's alignment, minimum and maximum; the others read 4 + _ = binary.Write(¬e, binary.LittleEndian, [3]uint32{4, uint32(len(desc)), n}) + note.WriteString("Xen\x00") + note.Write(desc) + } + const ehsize, phsize, shsize = 64, 56, 64 + noteOff := uint64(ehsize + phsize) + relocOff := noteOff + uint64(note.Len()) + strtab := []byte("\x00.data.reloc\x00.shstrtab\x00") + strOff := relocOff + uint64(len(reloc)) + shOff := strOff + uint64(len(strtab)) + + sections := []elf.Section64{{}} + if reloc != nil { + sections = append(sections, elf.Section64{Name: 1, Type: uint32(elf.SHT_PROGBITS), Flags: uint64(elf.SHF_ALLOC | elf.SHF_WRITE), Off: relocOff, Size: uint64(len(reloc)), Addralign: 4}) // mutate-exempt: build.SelfRandomizing reads .data.reloc by offset and size, and a section's alignment changes neither + } + sections = append(sections, elf.Section64{Name: 13, Type: uint32(elf.SHT_STRTAB), Off: strOff, Size: uint64(len(strtab)), Addralign: 1}) // mutate-exempt: debug/elf finds the string table by Shstrndx, never by its own name or alignment + + var b bytes.Buffer + h := elf.Header64{ + Type: uint16(elf.ET_EXEC), Machine: uint16(elf.EM_X86_64), Version: uint32(elf.EV_CURRENT), + Phoff: ehsize, Shoff: shOff, Ehsize: ehsize, Phentsize: phsize, Phnum: 1, + Shentsize: shsize, Shnum: uint16(len(sections)), Shstrndx: uint16(len(sections) - 1), + } + copy(h.Ident[:], elf.ELFMAG) + h.Ident[elf.EI_CLASS], h.Ident[elf.EI_DATA], h.Ident[elf.EI_VERSION] = byte(elf.ELFCLASS64), byte(elf.ELFDATA2LSB), byte(elf.EV_CURRENT) + _ = binary.Write(&b, binary.LittleEndian, h) + _ = binary.Write(&b, binary.LittleEndian, elf.Prog64{Type: uint32(elf.PT_NOTE), Off: noteOff, Filesz: uint64(note.Len()), Align: 4}) // mutate-exempt: machine.hasXenNote pads names and descriptors to 4 bytes, as x86's vmlinux notes are, and reads no p_align + b.Write(note.Bytes()) + b.Write(reloc) + b.Write(strtab) + for _, s := range sections { + _ = binary.Write(&b, binary.LittleEndian, s) + } + return b.Bytes() +} diff --git a/internal/lab/phases.go b/internal/lab/phases.go index 8d9bd8f1..bec9ea2c 100644 --- a/internal/lab/phases.go +++ b/internal/lab/phases.go @@ -60,8 +60,9 @@ const ( // steps and the waits inside them. What follows is what this phase measured on SeaBIOS. // // There is firmware at all because on q35 the CPU resets into it, whatever QEMU was told - // to boot. The kernel here was then an ELF entered through its PVH note and pvh.bin, and is - // a bzImage entered through linuxboot_dma.bin since 2026-11-19. That decides which option + // to boot. The kernel here was then an ELF entered through its PVH note and pvh.bin, was a + // bzImage entered through linuxboot_dma.bin from 2026-11-19, and is an ELF through pvh.bin + // again since #645, one that randomizes itself. That decides which option // ROM SeaBIOS jumps through, not whether SeaBIOS runs. Only a machine type with no firmware // skips it. // diff --git a/internal/patched/patched.go b/internal/patched/patched.go index d4ab3d6e..8e3fdff6 100644 --- a/internal/patched/patched.go +++ b/internal/patched/patched.go @@ -24,6 +24,7 @@ import ( "slices" "strconv" "strings" + "time" "github.com/spin-stack/go-tools/versions" "github.com/spin-stack/go-tools/versions/upstream" @@ -38,14 +39,17 @@ import ( // failed every compilation of a touched kernel file it was given and three of QEMU's (codeql.yml // run 45214602230, 2026-11-23). A part without it is analysed from a tree with every C file it // does not touch taken out (build-mode none). +// +// prepare, when a part has it, builds what compile needs before the tracer starts, so that only +// the touched files are compiled, and extracted, under it. type Part struct { Name, Pin, Patches string - compile func(ctx context.Context, root, src string, touched []string, out io.Writer) error + prepare, compile func(ctx context.Context, root, src string, touched []string, out io.Writer) error } // Parts is every part with C patches, where AGENTS.md says each part's patches are kept. var Parts = []Part{ - {Name: "kernel", Pin: "kernel", Patches: "kernel/patches/*.patch", compile: compileKernel}, + {Name: "kernel", Pin: "kernel", Patches: "kernel/patches/*.patch", prepare: prepareKernel, compile: compileKernel}, {Name: "qemu", Pin: "qemu", Patches: "qemu/patches/*.patch", compile: compileQEMU}, {Name: "qboot", Pin: "qboot", Patches: "qemu/qboot/*.patch"}, {Name: "systemd", Pin: "systemd-source", Patches: "image/systemd/*.patch"}, @@ -117,39 +121,66 @@ func Tree(ctx context.Context, root string, pins *versions.Versions, p Part, dir // Traced is whether p is analysed by tracing Compile rather than without a build. func (p Part) Traced() bool { return p.compile != nil } -// Compile compiles the C files the patches touch in p's tree in dir, which Tree made, for an +// Prepare builds, in p's tree in dir, which Tree made, what compiling its touched C files needs, +// before an analysis starts tracing the compiler. A part without it needs nothing. +func Prepare(ctx context.Context, root string, p Part, dir string, out io.Writer) error { + if p.compile == nil { + return fmt.Errorf("%s is analysed without a build: it has nothing to prepare", p.Name) + } + return p.build(ctx, root, p.prepare, dir, out) +} + +// Compile compiles the C files the patches touch in p's tree in dir, which Prepare readied, for an // analysis tracing the compiler, writing what the build prints to out. root is the checkout. func Compile(ctx context.Context, root string, p Part, dir string, out io.Writer) error { if p.compile == nil { return fmt.Errorf("%s is analysed without a build: it has nothing to compile", p.Name) } + return p.build(ctx, root, p.compile, dir, out) +} + +// build hands step the C files the patches touch in p's tree in dir. +func (p Part) build(ctx context.Context, root string, step func(ctx context.Context, root, src string, touched []string, out io.Writer) error, dir string, out io.Writer) error { raw, err := os.ReadFile(filepath.Join(dir, "touched")) if err != nil { return fmt.Errorf("reading the touched files (make the tree first): %w", err) } + if step == nil { + return nil + } var touched []string for _, f := range strings.Fields(string(raw)) { if slices.Contains(cSources, filepath.Ext(f)) { touched = append(touched, f) } } - if err := p.compile(ctx, root, filepath.Join(dir, "src"), touched, out); err != nil { + if err := step(ctx, root, filepath.Join(dir, "src"), touched, out); err != nil { return fmt.Errorf("%s: %w", p.Name, err) } return nil } // namedAddressSpaces is the symbol arch/x86/Kconfig sets when GCC has named address spaces, which -// makes per-CPU access go through __seg_gs, and which compileKernel turns off. CodeQL's C front end +// makes per-CPU access go through __seg_gs, and which prepareKernel turns off. CodeQL's C front end // cannot parse __seg_gs: with it, every file that reached a per-CPU accessor (this_cpu_inc, // raw_cpu_ptr) failed to extract, ten of the fourteen the patches touch (codeql.yml run // 45216274329, 2026-11-23). Without it the kernel takes its other, upstream-supported path, the // one a compiler without named address spaces builds. const namedAddressSpaces = "config CC_HAS_NAMED_AS\n\tdef_bool " -// compileKernel configures the tree as kernel/Dockerfile does, from the series' configuration -// but without named address spaces, and makes the touched files' objects. -func compileKernel(ctx context.Context, root, src string, touched []string, out io.Writer) error { +// bzImageOnly are the directories whose files only the bzImage's build compiles, each with flags +// of its own: the decompressor, after vmlinux, whose symbols misc.c includes as ../voffset.h, and +// the host tools vmlinux is post-processed with (relocs). Made as objects of vmlinux, misc.o found +// no voffset.h and relocs.o failed on vmlinux's -Werror (codeql.yml job 137883774299, +// 2026-11-23), so a touched file there makes the bzImage, which compiles each the way it is built. +var bzImageOnly = []string{"arch/x86/boot/compressed/", "arch/x86/tools/"} + +// prepareKernel configures the tree as kernel/Dockerfile does, from the series' configuration but +// without named address spaces, and makes what the touched files are compiled with: the headers +// every object needs, and the bzImage when a touched file is one only it builds. Built here, +// untraced, the kernel is not extracted whole: the analysis reads only what compileKernel then +// rebuilds. +func prepareKernel(ctx context.Context, root, src string, touched []string, out io.Writer) error { kconfig := filepath.Join(src, "arch", "x86", "Kconfig") k, err := os.ReadFile(kconfig) if err != nil { @@ -175,10 +206,6 @@ func compileKernel(ctx context.Context, root, src string, touched []string, out if err := os.WriteFile(filepath.Join(src, ".config"), raw, 0o644); err != nil { return err } - objects := []string{"ARCH=x86_64", "-j" + jobs()} - for _, f := range touched { - objects = append(objects, strings.TrimSuffix(f, filepath.Ext(f))+".o") - } if err := shown(ctx, out, "", "make", "-C", src, "ARCH=x86_64", "olddefconfig"); err != nil { return err } @@ -189,14 +216,56 @@ func compileKernel(ctx context.Context, root, src string, touched []string, out if bytes.Contains(config, []byte("CONFIG_CC_HAS_NAMED_AS=y")) { return errors.New("olddefconfig kept CONFIG_CC_HAS_NAMED_AS=y: the analysis would not parse per-CPU access") } - for _, args := range [][]string{{"ARCH=x86_64", "-j" + jobs(), "prepare"}, objects} { - if err := shown(ctx, out, "", "make", append([]string{"-C", src}, args...)...); err != nil { + goal := "prepare" + if _, ok := kernelObjects(touched); ok { + goal = "bzImage" + } + return shown(ctx, out, "", "make", "-C", src, "ARCH=x86_64", "-j"+jobs(), goal) +} + +// compileKernel makes the touched files' objects in the tree prepareKernel built, each touched +// first so that make compiles it again, under the tracer, whatever it built before. +func compileKernel(ctx context.Context, _, src string, touched []string, out io.Writer) error { + if _, err := os.Stat(filepath.Join(src, ".config")); err != nil { + return fmt.Errorf("the tree is not configured (prepare it first): %w", err) + } + now := time.Now() + for _, f := range touched { + if err := os.Chtimes(filepath.Join(src, f), now, now); err != nil { + return fmt.Errorf("touching %s: %w", f, err) + } + } + objects, bzImage := kernelObjects(touched) + // The objects first, and the bzImage on its own after them: asked for together, make built one + // object twice at once, as an object and as part of vmlinux, and fixdep lost its .d file + // (2026-11-23). + goals := [][]string{objects} + if bzImage { + goals = append(goals, []string{"bzImage"}) + } + for _, g := range goals { + if err := shown(ctx, out, "", "make", append([]string{"-C", src, "ARCH=x86_64", "-j" + jobs()}, g...)...); err != nil { return err } } return nil } +// kernelObjects is the objects of the touched files make builds as objects, and whether a touched +// file is one only the bzImage builds. +func kernelObjects(touched []string) ([]string, bool) { + var objects []string + bzImage := false + for _, f := range touched { + if slices.ContainsFunc(bzImageOnly, func(dir string) bool { return strings.HasPrefix(f, dir) }) { + bzImage = true + continue + } + objects = append(objects, strings.TrimSuffix(f, filepath.Ext(f))+".o") + } + return objects, bzImage +} + // compileQEMU configures the tree for the one target the machine builds and makes the // touched files' objects, which ninja names after the file's path. func compileQEMU(ctx context.Context, root, src string, touched []string, out io.Writer) error { diff --git a/internal/patched/patched_test.go b/internal/patched/patched_test.go index 3fd26c6c..5025e290 100644 --- a/internal/patched/patched_test.go +++ b/internal/patched/patched_test.go @@ -16,6 +16,7 @@ import ( "slices" "strings" "testing" + "time" "github.com/spin-stack/go-tools/versions" ) @@ -341,7 +342,7 @@ func TestTheKernelIsCompiledWithoutNamedAddressSpacesOrNotAtAll(t *testing.T) { put(t, filepath.Join(src, "arch/x86/Kconfig"), "config CC_HAS_NAMED_AS\n\tbool\n") root := t.TempDir() put(t, filepath.Join(root, "kernel/config-7.3-x86_64"), "CONFIG_X86_64=y\n") - if err := compileKernel(context.Background(), root, src, nil, io.Discard); err == nil || !strings.Contains(err.Error(), "no longer says") { + if err := prepareKernel(context.Background(), root, src, nil, io.Discard); err == nil || !strings.Contains(err.Error(), "no longer says") { t.Errorf("a Kconfig that turns __seg_gs on some other way: %v", err) } } @@ -368,7 +369,7 @@ func TestTheKernelIsCompiledFromItsConfigurationWithoutNamedAddressSpaces(t *tes src, root := t.TempDir(), t.TempDir() put(t, filepath.Join(src, "arch/x86/Kconfig"), "config A\n\tbool\n\nconfig CC_HAS_NAMED_AS\n\tdef_bool $(success,echo x | $(CC))\n\tdepends on CC_IS_GCC\n") put(t, filepath.Join(root, "kernel/config-7.3-x86_64"), "CONFIG_X86_64=y\n") - if err := compileKernel(context.Background(), root, src, []string{"lib/a.c", "kernel/b.c"}, io.Discard); err != nil { + if err := prepareKernel(context.Background(), root, src, []string{"lib/a.c"}, io.Discard); err != nil { t.Fatal(err) } if got := read(t, filepath.Join(src, "arch/x86/Kconfig")); got != "config A\n\tbool\n\nconfig CC_HAS_NAMED_AS\n\tdef_bool n\n\tdepends on CC_IS_GCC\n" { @@ -378,19 +379,71 @@ func TestTheKernelIsCompiledFromItsConfigurationWithoutNamedAddressSpaces(t *tes t.Errorf(".config = %q, want the series' configuration", got) } got := read(t, calls) - for _, want := range []string{"make -C " + src + " ARCH=x86_64 olddefconfig\n", " prepare\n", " lib/a.o kernel/b.o\n"} { + for _, want := range []string{"make -C " + src + " ARCH=x86_64 olddefconfig\n", " prepare\n"} { if !strings.Contains(got, want) { t.Errorf("calls:\n%s\nwant %q in them", got, want) } } + if strings.Contains(got, "lib/a.o") || strings.Contains(got, "bzImage") { + t.Errorf("calls:\n%s\nprepare compiled a touched file, which the tracer would then not see", got) + } put(t, filepath.Join(src, "arch/x86/Kconfig"), "config CC_HAS_NAMED_AS\n\tdef_bool $(x)\n") put(t, filepath.Join(root, "kernel/config-7.3-x86_64"), "CONFIG_CC_HAS_NAMED_AS=y\n") - if err := compileKernel(context.Background(), root, src, nil, io.Discard); err == nil || !strings.Contains(err.Error(), "CONFIG_CC_HAS_NAMED_AS=y") { + if err := prepareKernel(context.Background(), root, src, nil, io.Discard); err == nil || !strings.Contains(err.Error(), "CONFIG_CC_HAS_NAMED_AS=y") { t.Errorf("a configuration that kept named address spaces: %v", err) } } +// The decompressor and the host tools are built only through the bzImage, with flags of their +// own: prepare builds it untraced, and compile again over each touched file. +func TestTheKernelsBzImageOnlyFilesAreBuiltThroughTheBzImage(t *testing.T) { + calls := fakeTools(t, "") + src, root := t.TempDir(), t.TempDir() + put(t, filepath.Join(src, "arch/x86/Kconfig"), "config CC_HAS_NAMED_AS\n\tdef_bool y\n") + put(t, filepath.Join(root, "kernel/config-7.3-x86_64"), "CONFIG_X86_64=y\n") + touched := []string{"lib/a.c", "arch/x86/boot/compressed/misc.c", "kernel/b.c", "arch/x86/tools/relocs.c"} + if err := prepareKernel(context.Background(), root, src, touched, io.Discard); err != nil { + t.Fatal(err) + } + if got := read(t, calls); !strings.HasSuffix(got, " bzImage\n") { + t.Errorf("prepare's calls:\n%s\nwant the bzImage last", got) + } +} + +// compile makes each touched file's object, after touching it: a file prepare already built is +// compiled again, under the tracer, or the analysis would not have read it. +func TestTheKernelCompilesEachTouchedFileAgain(t *testing.T) { + calls := fakeTools(t, "") + src := t.TempDir() + touched := []string{"lib/a.c", "arch/x86/boot/compressed/misc.c", "kernel/b.c", "arch/x86/tools/relocs.c"} + if err := compileKernel(context.Background(), "", src, touched, io.Discard); err == nil || !strings.Contains(err.Error(), "prepare it first") { + t.Errorf("an unprepared tree: %v", err) + } + put(t, filepath.Join(src, ".config"), "CONFIG_X86_64=y\n") + old := time.Now().Add(-time.Hour) + for _, f := range touched { + put(t, filepath.Join(src, f), "int x;\n") + if err := os.Chtimes(filepath.Join(src, f), old, old); err != nil { + t.Fatal(err) + } + } + if err := compileKernel(context.Background(), "", src, touched, io.Discard); err != nil { + t.Fatal(err) + } + if got := read(t, calls); !strings.HasSuffix(got, " lib/a.o kernel/b.o\nmake -C "+src+" ARCH=x86_64 -j"+jobs()+" bzImage\n") { + t.Errorf("calls:\n%s\nwant each object, and the bzImage for the files only it builds", got) + } + for _, f := range touched { + if fi, err := os.Stat(filepath.Join(src, f)); err != nil || !fi.ModTime().After(old) { + t.Errorf("%s was not touched: make would not compile it again", f) + } + } + if err := compileKernel(context.Background(), "", src, []string{"lib/gone.c"}, io.Discard); err == nil || !strings.Contains(err.Error(), "touching lib/gone.c") { + t.Errorf("a touched file that is not there: %v", err) + } +} + func TestQEMUIsConfiguredForItsTargetAndCompilesOnlyTheTouchedObjects(t *testing.T) { calls := fakeTools(t, "libqemu-x86_64-softmmu.a.p/target_i386_cpu.c.o: C_COMPILER\\nlibcommon.a.p/system_vl.c.o: C_COMPILER\\nqemu-system-x86_64: link\\n") src := t.TempDir() @@ -433,4 +486,18 @@ func TestCompileHandsThePartOnlyTheTouchedCFiles(t *testing.T) { if err := Compile(context.Background(), t.TempDir(), p, dir, io.Discard); err == nil || err.Error() != "x: make failed" { t.Errorf("a failed compile: %v", err) } + if err := Prepare(context.Background(), t.TempDir(), p, dir, io.Discard); err != nil { + t.Errorf("a part with nothing to build before its compile: %v", err) + } + p.prepare = p.compile + if err := Prepare(context.Background(), t.TempDir(), p, dir, io.Discard); err == nil || err.Error() != "x: make failed" { + t.Errorf("a failed prepare: %v", err) + } + if err := Prepare(context.Background(), t.TempDir(), p, t.TempDir(), io.Discard); err == nil || !strings.Contains(err.Error(), "make the tree first") { + t.Errorf("no tree: %v", err) + } + qboot, _ := Find("qboot") + if err := Prepare(context.Background(), t.TempDir(), qboot, dir, io.Discard); err == nil || !strings.Contains(err.Error(), "nothing to prepare") { + t.Errorf("qboot: %v", err) + } } diff --git a/internal/release/pack.go b/internal/release/pack.go index 3030f8c2..5834a1a9 100644 --- a/internal/release/pack.go +++ b/internal/release/pack.go @@ -192,8 +192,9 @@ func shipped(o Options, top, share string) ([]file, error) { } files = append(files, file{filepath.Join(o.Root, "qemu/qboot/COPYING"), at("qemu/qboot-COPYING"), "qboot's licence", 0o644}, - // The bzImage is what the machine boots, its decompressor where KASLR happens; vmlinux, - // the same kernel as an ELF, is for what reads its symbols and for a debugger. + // vmlinux is what the machine boots, through PVH, the kernel moving itself to a random + // base (#645), and what a reader of the kernel's symbols opens. The bzImage, the same kernel with + // a decompressor, is what spin's hack/machine/place.go asks a release for. file{fromOut("kernel/bzImage"), at("kernel/bzImage"), "the guest kernel", 0o644}, file{fromOut("kernel/vmlinux"), at("kernel/vmlinux"), "the guest kernel as an ELF", 0o644}, file{fromOut("kernel/kernel-config"), at("kernel/kernel-config"), "the kernel config", 0o644}, diff --git a/internal/release/release_test.go b/internal/release/release_test.go index ace1762c..d2621e9c 100644 --- a/internal/release/release_test.go +++ b/internal/release/release_test.go @@ -142,8 +142,8 @@ func TestAReleaseShipsEveryPartAndSaysWhatItIs(t *testing.T) { t.Errorf("%s: in the tarball %v, mode %o; want %o", f, ok, m, mode) } } - if len(got) != 33 { - t.Errorf("the tarball holds %d files, want 33: %v", len(got), slices.Sorted(func(yield func(string) bool) { + if len(got) != 34 { + t.Errorf("the tarball holds %d files, want 34: %v", len(got), slices.Sorted(func(yield func(string) bool) { for k := range got { if !yield(k) { return diff --git a/kernel/Dockerfile b/kernel/Dockerfile index 4132e7fd..d4dd27b3 100644 --- a/kernel/Dockerfile +++ b/kernel/Dockerfile @@ -133,16 +133,19 @@ COPY kernel/patches/ /usr/src/patches/ # That claim, checked, with the checkpatch.pl, spelling.txt and const_structs.checkpatch of the # tree the patches apply to, already here and pinned with it: nothing fetched, so nothing to -# rate-limit a build (raw.githubusercontent.com answered one with 429, job 137831193347). Three +# rate-limit a build (raw.githubusercontent.com answered one with 429, job 137831193347). Four # things are left out, each by name. --no-signoff and the Assisted-by: trailer removed before the # check, because checkpatch knows no Assisted-by: and the missing Signed-off-by is the rule -# above. UNKNOWN_COMMIT_ID, because a tarball has no history to find a cited commit in. Each +# above. UNKNOWN_COMMIT_ID, because a tarball has no history to find a cited commit in. +# FILE_PATH_CHANGES, "does MAINTAINERS need updating?" for a patch that adds a file (0016, +# 0017), because no patch here goes upstream until it has run in production, and MAINTAINERS +# is upstream's to change then. Each # patch must come out "has no obvious style problems", read from the output rather than trusted # from the exit status. RUN cd /usr/src/linux && \ failed=0 && \ for p in /usr/src/patches/*.patch; do \ - out=$(grep -v '^Assisted-by: ' "$p" | perl scripts/checkpatch.pl --strict --no-signoff --ignore UNKNOWN_COMMIT_ID \ + out=$(grep -v '^Assisted-by: ' "$p" | perl scripts/checkpatch.pl --strict --no-signoff --ignore UNKNOWN_COMMIT_ID,FILE_PATH_CHANGES \ --root=/usr/src/linux --summary-file --patch - 2>&1) || true; \ case "$out" in \ *"has no obvious style problems"*) echo "checkpatch: ${p##*/}: clean" ;; \ @@ -278,17 +281,17 @@ RUN < 1 && $1 != 0 && !n { n = NR } END { print n ? (NR - n + 2) * 4 : 0 }') + [ "$used" -gt 0 ] || lost 0015 "the relocs tool did not fill .data.reloc" + echo "relocation table: $used of $size bytes" + + # 0017: startup_64 relocates the kernel before it computes its own physical-to-virtual offset. + dis startup_64 | grep -q '<__pi___relocate_kernel>' || lost 0017 "startup_64 does not relocate the kernel" + + # 0017's code runs before the kernel has relocated itself, so it may not call through the + # GOT or an absolute address, and may not call instrumentation that is not there yet: an + # ftrace hook (__fentry__), KASAN, KCOV, UBSAN or the stack protector. Under PIE, a call + # to __fentry__ through the GOT in a PVM guest's self-relocation kept the guest from + # starting (virt-pvm/linux#11, fixed by dropping CC_FLAGS_FTRACE there). The RFC puts the + # code in arch/x86/boot/startup, whose Makefile builds it without those flags; this asks + # the object that was compiled, kaslr.c with lib/kaslr.c and lib/cmdline.c included in it, + # so a config or Makefile change cannot put one back unseen. Its relocations, not vmlinux: + # the linker relaxes a GOT load away, and objtool turns __fentry__ calls into NOPs. + kobj=arch/x86/boot/startup/kaslr.pi.o + [ -f "$kobj" ] || kobj=arch/x86/boot/startup/kaslr.o + if [ ! -f "$kobj" ]; then + lost 0017 "no arch/x86/boot/startup/kaslr.o to check" + else + echo "pre-relocation functions ($kobj): $(nm --defined-only "$kobj" | awk '$2 ~ /[tT]/ { print $3 }' | tr '\n' ' ')" + bad=$(objdump -dr "$kobj" | grep -E 'R_X86_64_(GOT|REX_GOT)|__fentry__|__(asan|kasan|ubsan|sanitizer_cov|stack_chk)_?' | sort -u) + [ -z "$bad" ] || lost 0017 "the code that runs before relocation is instrumented or goes through the GOT: $bad" + fi + + # 0018: the decompressor applies the same table to a bzImage, and no vmlinux.relocs of its own. + grep -qF 'output_len = VO___relocation_end - VO__text;' arch/x86/boot/compressed/misc.c || + lost 0018 "the decompressor does not read .data.reloc" + + # 0019 and 0020: a kernel that moved itself says so, so RANDOMIZE_MEMORY moves the direct map, + # vmalloc and vmemmap; and it draws its base from RDRAND and RDTSC, read from the registers + # that hold them. Both are early startup code with no symbol of their own, so the source is read. + grep -qF 'bp->hdr.loadflags |= KASLR_FLAG;' arch/x86/boot/startup/kaslr.c || + lost 0019 "a kernel that relocated itself does not set KASLR_FLAG" + grep -A1 -F 'flag == X86_FEATURE_RDRAND' arch/x86/boot/startup/kaslr.c | grep -qF 'native_cpuid_ecx(0x1)' || + lost 0020 "has_cpuflag reads RDRAND from a register that does not hold it" + [ "$failed" = 0 ] || exit 1 echo "kernel patches: each is in this vmlinux" EOT @@ -542,18 +593,19 @@ RUN < 24.3 ms, guest boot unchanged. + # Measured while QEMU loaded vmlinux (before 2026-11-19): qemu_launch 36.1 ms -> 24.3 ms, + # guest boot unchanged. cp vmlinux /build/vmlinux strip -s /build/vmlinux @@ -575,7 +627,8 @@ RUN < /tmp/sparse-bzimage.log 2>&1 || { + cat /tmp/sparse-bzimage.log; echo "ERROR: make V=1 C=1 bzImage failed"; exit 1; } + for f in $boot; do + grep -aE "^ *sparse .* $f\$" /tmp/sparse-bzimage.log | tail -1 > "/tmp/sparse-cmd-$(echo "$f" | tr / _)" + [ -s "/tmp/sparse-cmd-$(echo "$f" | tr / _)" ] || { + echo "ERROR: the bzImage's build ran no sparse over $f"; exit 1; } + done + fi sparse_of() { : > "/tmp/sparse-$1.log" + for f in $boot; do + [ "$1" = upstream ] && [ ! -e "$f" ] && continue + sh "/tmp/sparse-cmd-$(echo "$f" | tr / _)" >> "/tmp/sparse-$1.log" 2>&1 || true + echo " CHECK $f" >> "/tmp/sparse-$1.log" + done for f in $files; do + [ "$1" = upstream ] && [ ! -e "$f" ] && continue make ARCH=${KERNEL_ARCH} C=2 "${f%.c}.o" >> "/tmp/sparse-$1.log" 2>&1 || { cat "/tmp/sparse-$1.log"; echo "ERROR: make C=2 ${f%.c}.o failed ($1)"; exit 1; } done for f in $files; do + [ "$1" = upstream ] && [ ! -e "$f" ] && continue grep -q "^ CHECK *$f\$" "/tmp/sparse-$1.log" || { cat "/tmp/sparse-$1.log"; echo "ERROR: sparse did not check $f ($1)"; exit 1; } done @@ -637,7 +720,7 @@ RUN < /dev/null; done for f in $others; do mv "$f.patched" "$f"; done sparse_of upstream - echo "sparse: $(wc -l < /tmp/sparse-upstream) distinct upstream warnings in $(echo $files | wc -w) files" + echo "sparse: $(wc -l < /tmp/sparse-upstream) distinct upstream warnings in $(echo $files $boot | wc -w) files" awk ' NR == FNR { n = $1; $1 = ""; base[$0] = n; next } { n = $1; $1 = ""; if (n > base[$0] + 0) { print "ERROR: sparse, new with the patches:" $0; bad = 1 } } diff --git a/kernel/README.md b/kernel/README.md index def81582..883148d7 100644 --- a/kernel/README.md +++ b/kernel/README.md @@ -6,9 +6,33 @@ within the series builds from the same config. The kernel is here because a kern machine that boots it are released together. A new kernel does not strand checkpoints: a resumed guest runs the kernel in its saved memory until it reboots, and boots this one then (the machine's record, `machine.QEMU.Target`, leaves the kernel out). `spin-machine-dev build kernel` -builds it. `spin-machine-dev verify kernel` reads the setup header of the bzImage the machine boots -(relocatable, so KASLR can move it), and checks that the stripped vmlinux beside it opens as an -ELF. +builds it. `spin-machine-dev verify kernel` asserts that the stripped vmlinux, which the machine +enters through PVH, carries the two Xen notes QEMU enters and places it by and a filled relocation +table, and reads the setup header of the bzImage beside it (relocatable). + +## KASLR with no decompressor + +The machine enters the vmlinux through PVH (#645). A bzImage's KASLR happens in its decompressor, +which PVH skips, and until 2026-11-19 the kernel entered that way ran where it was linked at every +boot. Now each half is chosen where the decompressor chose it before: + +- **The virtual base**, by the kernel at `startup_64` (0017), from a relocation table the relocs + tool writes into `.data.reloc` at link time (0014-0016). The slot rule is the decompressor's + (2 MiB slots below 1 GiB, ~480 of them), and so are the seed's sources once 0020 reads RDRAND + and the TSC from the CPUID registers that hold them: the RFC reads them swapped, so it drew the + base from the i8254 and a hash of `boot_params` alone. The decompressor also hashes the build + string, which is public. +- **The physical base**, by QEMU (`qemu/patches/0008`), from `XEN_ELFNOTE_PHYS32_RELOC`, among the + 2 MiB slots of low memory below the initrd and the ACPI data, drawn from the host's `getrandom`. +- **The direct map, vmalloc and vmemmap** (`RANDOMIZE_MEMORY`), by the kernel as before, once 0019 + sets `KASLR_FLAG`, which only the decompressor set. + +`CONFIG_RELOCATION_TABLE_SIZE` reserves the table, 1 MiB here (the RFC's Kconfig defaults to 2 MiB +and its help says 1 MB "should be ok in most cases"). A table +that does not fit fails the link: the relocs tool dies naming the size it needs, and the build +prints what this kernel uses of it. At boot the table cannot overflow: it is part of the image. +`boot:kaslr` boots the kernel ten times and requires each of the four to move. + ## Memory that moves @@ -139,6 +163,11 @@ every kernel bump. | 0010 | `early_quirks` calls `kvm_para_available` before its scan | | 0012 | `btf_vmlinux_defer` is in the vmlinux, and the compiled `kernel/bpf/btf.c` defers registrations through it | | 0013 | the compiled `kernel/bpf/verifier.c` asks for vmlinux BTF through `need_btf_vmlinux(env)` | +| 0014-0016 | `.data.reloc` holds a table the relocs tool filled; how much of the reserve it uses is printed | +| 0017 | `startup_64` calls `__pi___relocate_kernel`, and the object it is built in (`arch/x86/boot/startup/kaslr.o`, with `lib/kaslr.c` and `lib/cmdline.c` included) has no `__fentry__`, KASAN, KCOV, UBSAN or stack-protector call and no GOT relocation: it runs before the kernel has moved (virt-pvm/linux#11 is the failure a `__fentry__` call through the GOT made) | +| 0018 | the compiled decompressor reads its relocations from `.data.reloc` | +| 0019 | the compiled `arch/x86/boot/startup/kaslr.c` sets `KASLR_FLAG` | +| 0020 | the compiled `arch/x86/boot/startup/kaslr.c` reads RDRAND from CPUID leaf 1's ECX | None of them is a guest check. What the patches save is CPU and VM exits, which a guest cannot count, and the format files 0003 defers are behind lockdown. What 0012 and 0013 save is a parse of diff --git a/kernel/config-7.3-x86_64 b/kernel/config-7.3-x86_64 index e3985058..80a257ac 100644 --- a/kernel/config-7.3-x86_64 +++ b/kernel/config-7.3-x86_64 @@ -364,7 +364,7 @@ CONFIG_X86_HV_CALLBACK_VECTOR=y # CONFIG_XEN is not set CONFIG_KVM_GUEST=y CONFIG_ARCH_CPUIDLE_HALTPOLL=y -# CONFIG_PVH is not set +CONFIG_PVH=y CONFIG_PARAVIRT_TIME_ACCOUNTING=y CONFIG_PARAVIRT_CLOCK=y # CONFIG_JAILHOUSE_GUEST is not set @@ -475,6 +475,8 @@ CONFIG_ARCH_SUPPORTS_CRASH_HOTPLUG=y CONFIG_PHYSICAL_START=0x1000000 CONFIG_RELOCATABLE=y CONFIG_RANDOMIZE_BASE=y +CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL=y +CONFIG_RELOCATION_TABLE_SIZE=0x100000 CONFIG_X86_NEED_RELOCS=y CONFIG_PHYSICAL_ALIGN=0x200000 CONFIG_RANDOMIZE_MEMORY=y diff --git a/kernel/patches/0014-x86-relocs-Cleanup-cmdline-options.patch b/kernel/patches/0014-x86-relocs-Cleanup-cmdline-options.patch new file mode 100644 index 00000000..85a957b0 --- /dev/null +++ b/kernel/patches/0014-x86-relocs-Cleanup-cmdline-options.patch @@ -0,0 +1,122 @@ +From: Hou Wenlong +Date: Mon, 26 Jan 2026 21:33:51 +0800 +Subject: [PATCH] x86/relocs: Cleanup cmdline options + +Move all cmdline options to global variables to make code cleaner and to +facilitate the addition of new cmdline options. + +Signed-off-by: Hou Wenlong +--- + arch/x86/tools/relocs.c | 12 +++++------- + arch/x86/tools/relocs.h | 14 ++++++++------ + arch/x86/tools/relocs_common.c | 13 +++++-------- + 3 files changed, 18 insertions(+), 21 deletions(-) + +diff --git a/arch/x86/tools/relocs.c b/arch/x86/tools/relocs.c +index 5ea9bc7ee..4d3d53391 100644 +--- a/arch/x86/tools/relocs.c ++++ b/arch/x86/tools/relocs.c +@@ -127,7 +127,7 @@ static int is_reloc(enum symtype type, const char *sym_name) + return sym_regex[type] && !regexec(&sym_regex_c[type], sym_name, 0, NULL, 0); + } + +-static void regex_init(int use_real_mode) ++static void regex_init(void) + { + char errbuf[128]; + int err; +@@ -950,7 +950,7 @@ static int write32_as_text(uint32_t v, FILE *f) + return fprintf(f, "\t.long 0x%08"PRIx32"\n", v) > 0 ? 0 : -1; + } + +-static void emit_relocs(int as_text, int use_real_mode) ++static void emit_relocs(void) + { + int i; + int (*write_reloc)(uint32_t, FILE *) = write32; +@@ -1049,11 +1049,9 @@ static void print_reloc_info(void) + # define process process_32 + #endif + +-void process(FILE *fp, int use_real_mode, int as_text, +- int show_absolute_syms, int show_absolute_relocs, +- int show_reloc_info) ++void process(FILE *fp) + { +- regex_init(use_real_mode); ++ regex_init(); + read_ehdr(fp); + read_shdrs(fp); + read_strtabs(fp); +@@ -1075,5 +1073,5 @@ void process(FILE *fp, int use_real_mode, int as_text, + return; + } + +- emit_relocs(as_text, use_real_mode); ++ emit_relocs(); + } +diff --git a/arch/x86/tools/relocs.h b/arch/x86/tools/relocs.h +index 4c49c8244..5ade07ac2 100644 +--- a/arch/x86/tools/relocs.h ++++ b/arch/x86/tools/relocs.h +@@ -30,10 +30,12 @@ enum symtype { + S_NSYMTYPES + }; + +-void process_32(FILE *fp, int use_real_mode, int as_text, +- int show_absolute_syms, int show_absolute_relocs, +- int show_reloc_info); +-void process_64(FILE *fp, int use_real_mode, int as_text, +- int show_absolute_syms, int show_absolute_relocs, +- int show_reloc_info); ++extern int show_absolute_syms; ++extern int show_absolute_relocs; ++extern int show_reloc_info; ++extern int as_text; ++extern int use_real_mode; ++ ++void process_32(FILE *fp); ++void process_64(FILE *fp); + #endif /* RELOCS_H */ +diff --git a/arch/x86/tools/relocs_common.c b/arch/x86/tools/relocs_common.c +index 6634352a2..ee8a9fafc 100644 +--- a/arch/x86/tools/relocs_common.c ++++ b/arch/x86/tools/relocs_common.c +@@ -1,6 +1,9 @@ + // SPDX-License-Identifier: GPL-2.0 + #include "relocs.h" + ++int show_absolute_syms, show_absolute_relocs, show_reloc_info; ++int as_text, use_real_mode; ++ + void die(char *fmt, ...) + { + va_list ap; +@@ -18,8 +21,6 @@ static void usage(void) + + int main(int argc, char **argv) + { +- int show_absolute_syms, show_absolute_relocs, show_reloc_info; +- int as_text, use_real_mode; + const char *fname; + FILE *fp; + int i; +@@ -73,13 +74,9 @@ int main(int argc, char **argv) + } + rewind(fp); + if (e_ident[EI_CLASS] == ELFCLASS64) +- process_64(fp, use_real_mode, as_text, +- show_absolute_syms, show_absolute_relocs, +- show_reloc_info); ++ process_64(fp); + else +- process_32(fp, use_real_mode, as_text, +- show_absolute_syms, show_absolute_relocs, +- show_reloc_info); ++ process_32(fp); + fclose(fp); + return 0; + } +-- +2.53.0 + diff --git a/kernel/patches/0015-x86-relocs-Insert-relocations-into-input-file.patch b/kernel/patches/0015-x86-relocs-Insert-relocations-into-input-file.patch new file mode 100644 index 00000000..ced6bf93 --- /dev/null +++ b/kernel/patches/0015-x86-relocs-Insert-relocations-into-input-file.patch @@ -0,0 +1,177 @@ +From: Hou Wenlong +Date: Mon, 26 Jan 2026 21:33:52 +0800 +Subject: [PATCH] x86/relocs: Insert relocations into input file + +Add a command line option to insert relocations into a reserved section +named ".data.reloc" section of the input file. This allows for +relocation of the uncompressed kernel and is same as the implementation +in MIPS. + +Signed-off-by: Hou Wenlong +[ spin-stack/machine: forward-ported to 7.3.5 for #645, and made + checkpatch --strict clean: no line continuations + inside die()'s arguments, and its message's second line unsplit. ] +Assisted-by: LLM +--- + arch/x86/tools/relocs.c | 56 ++++++++++++++++++++++++++++++---- + arch/x86/tools/relocs.h | 1 + + arch/x86/tools/relocs_common.c | 13 ++++++-- + 3 files changed, 61 insertions(+), 9 deletions(-) + +diff --git a/arch/x86/tools/relocs.c b/arch/x86/tools/relocs.c +index 4d3d53391..33ef98701 100644 +--- a/arch/x86/tools/relocs.c ++++ b/arch/x86/tools/relocs.c +@@ -735,6 +735,17 @@ static void walk_relocs(int (*process)(struct section *sec, Elf_Rel *rel, + } + } + ++static struct section *sec_lookup(const char *name) ++{ ++ int i; ++ ++ for (i = 0; i < shnum; i++) ++ if (!strcmp(sec_name(i), name)) ++ return &secs[i]; ++ ++ return NULL; ++} ++ + #if ELF_BITS == 64 + + static int do_reloc64(struct section *sec, Elf_Rel *rel, ElfW(Sym) *sym, +@@ -950,7 +961,7 @@ static int write32_as_text(uint32_t v, FILE *f) + return fprintf(f, "\t.long 0x%08"PRIx32"\n", v) > 0 ? 0 : -1; + } + +-static void emit_relocs(void) ++static void emit_relocs(FILE *f) + { + int i; + int (*write_reloc)(uint32_t, FILE *) = write32; +@@ -1001,21 +1012,54 @@ static void emit_relocs(void) + for (i = 0; i < relocs32.count; i++) + write_reloc(relocs32.offset[i], stdout); + } else { ++ FILE *outf = stdout; ++ ++ if (keep_relocs) { ++ struct section *sec_reloc; ++ uint32_t size_needed; ++ unsigned long offset; ++ ++ sec_reloc = sec_lookup(".data.reloc"); ++ if (!sec_reloc) ++ die("Could not find relocation data section\n"); ++ ++ size_needed = (1 + relocs32.count) * sizeof(uint32_t); ++#if ELF_BITS == 64 ++ size_needed += (1 + relocs64.count) * sizeof(uint32_t); ++#endif ++ if (size_needed > sec_reloc->shdr.sh_size) ++ die("Relocations overflow available space!\n" ++ "Please adjust CONFIG_RELOCATION_TABLE_SIZE to at least 0x%08x\n", ++ (size_needed + 0x1000) & ~0xFFF); ++ ++ /* ++ * Place the relocations at the end of section to ensure ++ * compatibility with backward traversal during handling ++ * relocations. ++ */ ++ offset = sec_reloc->shdr.sh_offset + sec_reloc->shdr.sh_size - ++ size_needed; ++ if (fseek(f, offset, SEEK_SET) < 0) ++ die("Seek to %ld failed: %s\n", offset, strerror(errno)); ++ ++ outf = f; ++ } ++ + #if ELF_BITS == 64 + /* Print a stop */ +- write_reloc(0, stdout); ++ write_reloc(0, outf); + + /* Now print each relocation */ + for (i = 0; i < relocs64.count; i++) +- write_reloc(relocs64.offset[i], stdout); ++ write_reloc(relocs64.offset[i], outf); + #endif + + /* Print a stop */ +- write_reloc(0, stdout); ++ write_reloc(0, outf); + + /* Now print each relocation */ + for (i = 0; i < relocs32.count; i++) +- write_reloc(relocs32.offset[i], stdout); ++ write_reloc(relocs32.offset[i], outf); + } + } + +@@ -1073,5 +1117,5 @@ void process(FILE *fp) + return; + } + +- emit_relocs(); ++ emit_relocs(fp); + } +diff --git a/arch/x86/tools/relocs.h b/arch/x86/tools/relocs.h +index 5ade07ac2..05a6e80e8 100644 +--- a/arch/x86/tools/relocs.h ++++ b/arch/x86/tools/relocs.h +@@ -35,6 +35,7 @@ extern int show_absolute_relocs; + extern int show_reloc_info; + extern int as_text; + extern int use_real_mode; ++extern int keep_relocs; + + void process_32(FILE *fp); + void process_64(FILE *fp); +diff --git a/arch/x86/tools/relocs_common.c b/arch/x86/tools/relocs_common.c +index ee8a9fafc..66a9a83b7 100644 +--- a/arch/x86/tools/relocs_common.c ++++ b/arch/x86/tools/relocs_common.c +@@ -2,7 +2,7 @@ + #include "relocs.h" + + int show_absolute_syms, show_absolute_relocs, show_reloc_info; +-int as_text, use_real_mode; ++int as_text, use_real_mode, keep_relocs; + + void die(char *fmt, ...) + { +@@ -15,7 +15,7 @@ void die(char *fmt, ...) + + static void usage(void) + { +- die("relocs [--abs-syms|--abs-relocs|--reloc-info|--text|--realmode]" \ ++ die("relocs [--abs-syms|--abs-relocs|--reloc-info|--text|--realmode|--keep]" + " vmlinux\n"); + } + +@@ -55,6 +55,10 @@ int main(int argc, char **argv) + use_real_mode = 1; + continue; + } ++ if (strcmp(arg, "--keep") == 0) { ++ keep_relocs = 1; ++ continue; ++ } + } + else if (!fname) { + fname = arg; +@@ -65,7 +69,10 @@ int main(int argc, char **argv) + if (!fname) { + usage(); + } +- fp = fopen(fname, "r"); ++ if (keep_relocs) ++ fp = fopen(fname, "r+"); ++ else ++ fp = fopen(fname, "r"); + if (!fp) { + die("Cannot open %s: %s\n", fname, strerror(errno)); + } +-- +2.53.0 + diff --git a/kernel/patches/0016-x86-Allow-to-build-relocatable-uncompressed-kernel-b.patch b/kernel/patches/0016-x86-Allow-to-build-relocatable-uncompressed-kernel-b.patch new file mode 100644 index 00000000..264c85e8 --- /dev/null +++ b/kernel/patches/0016-x86-Allow-to-build-relocatable-uncompressed-kernel-b.patch @@ -0,0 +1,130 @@ +From: Hou Wenlong +Date: Mon, 26 Jan 2026 21:33:53 +0800 +Subject: [PATCH] x86: Allow to build relocatable uncompressed kernel + binary + +Add support for building a relocatable uncompressed kernel binary, which +contains the relocation table generated by the 'relocs' tool and can be +used to perform KASLR directly when booting from it instead of a +compressed kernel image. To simplify, follow the MIPS implementation to +reserve a section to store the relocation table. + +Signed-off-by: Hou Wenlong +[ spin-stack/machine: forward-ported to 7.3.5 for #645, and made + checkpatch --strict clean: a four-line help for + RELOCATABLE_UNCOMPRESSED_KERNEL, and the postlink targets in another + order, which checkpatch read as a repeated word. ] +Assisted-by: LLM +--- + arch/x86/Kconfig | 22 ++++++++++++++++++++++ + arch/x86/Makefile.postlink | 33 +++++++++++++++++++++++++++++++++ + arch/x86/kernel/vmlinux.lds.S | 20 ++++++++++++++++++++ + 3 files changed, 75 insertions(+) + create mode 100644 arch/x86/Makefile.postlink + +diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig +index 15fd9ec5e..cbb0d7927 100644 +--- a/arch/x86/Kconfig ++++ b/arch/x86/Kconfig +@@ -2086,6 +2086,28 @@ config RANDOMIZE_BASE + + If unsure, say Y. + ++config RELOCATABLE_UNCOMPRESSED_KERNEL ++ bool "Build a relocatable uncompressed kernel" ++ depends on RANDOMIZE_BASE && X86_64 ++ help ++ A table of relocation data will be appended to the uncompressed ++ kernel binary and parsed at boot to do relocation. This lets a ++ vmlinux entered directly, as through PVH, with no decompressor, ++ randomize its own virtual base at startup_64. ++ ++config RELOCATION_TABLE_SIZE ++ hex "Relocation table size" ++ depends on RELOCATABLE_UNCOMPRESSED_KERNEL ++ range 0x0 0x04000000 ++ default "0x00200000" ++ help ++ This option allows the amount of space reserved for the table to be ++ adjusted, although the default of 1Mb should be ok in most cases. ++ ++ The build will fail and a valid size suggested if this is too small. ++ ++ If unsure, leave at the default value. ++ + # Relocation on x86 needs some additional build support + config X86_NEED_RELOCS + def_bool y +diff --git a/arch/x86/Makefile.postlink b/arch/x86/Makefile.postlink +new file mode 100644 +index 000000000..46497c47b +--- /dev/null ++++ b/arch/x86/Makefile.postlink +@@ -0,0 +1,33 @@ ++# SPDX-License-Identifier: GPL-2.0 ++# =========================================================================== ++# Post-link x86 pass ++# =========================================================================== ++# ++# 1. Insert relocations into vmlinux ++ ++PHONY := __archpost ++__archpost: ++ ++-include include/config/auto.conf ++include $(srctree)/scripts/Kbuild.include ++ ++CMD_RELOCS = arch/x86/tools/relocs ++quiet_cmd_relocs = RELOCS $@ ++ cmd_relocs = $(CMD_RELOCS) --keep $@ ++ ++# `@true` prevents complaint when there is nothing to be done ++ ++vmlinux.unstripped vmlinux: FORCE ++ @true ++ifeq ($(CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL),y) ++ $(call if_changed,relocs) ++endif ++ ++clean: ++ @true ++ ++PHONY += FORCE clean ++ ++FORCE: ++ ++.PHONY: $(PHONY) +diff --git a/arch/x86/kernel/vmlinux.lds.S b/arch/x86/kernel/vmlinux.lds.S +index 2438b89a4..9c2071c43 100644 +--- a/arch/x86/kernel/vmlinux.lds.S ++++ b/arch/x86/kernel/vmlinux.lds.S +@@ -298,6 +298,26 @@ SECTIONS + } + #endif + ++#ifdef CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL ++ . = ALIGN(4); ++ .data.reloc : AT(ADDR(.data.reloc) - LOAD_OFFSET) { ++ __relocation_start = .; ++ /* ++ * Space for relocation table ++ * This needs to be filled so that the ++ * relocs tool can overwrite the content. ++ * An invalid value is left at the start of the ++ * section to abort relocation if the table ++ * has not been filled in. ++ */ ++ LONG(0xFFFFFFFF); ++ FILL(0); ++ . += CONFIG_RELOCATION_TABLE_SIZE - 4; ++ __relocation_end = .; ++ __pi___relocation_end = .; ++ } ++#endif ++ + /* + * struct alt_inst entries. From the header (alternative.h): + * "Alternative instructions for different CPU types or capabilities" +-- +2.53.0 + diff --git a/kernel/patches/0017-x86-boot-Perform-virtual-address-relocation-in-kerne.patch b/kernel/patches/0017-x86-boot-Perform-virtual-address-relocation-in-kerne.patch new file mode 100644 index 00000000..62549ece --- /dev/null +++ b/kernel/patches/0017-x86-boot-Perform-virtual-address-relocation-in-kerne.patch @@ -0,0 +1,235 @@ +From: Hou Wenlong +Date: Mon, 26 Jan 2026 21:33:54 +0800 +Subject: [PATCH] x86/boot: Perform virtual address relocation in kernel + entry + +Perform virtual address relocation for the uncompressed kernel during +booting, which is similar to the relocation during decompression. + +Signed-off-by: Hou Wenlong +[ spin-stack/machine: forward-ported to 7.3.5 for #645, and made + checkpatch --strict clean: the included lib/kaslr.c and + lib/cmdline.c functions made static by a static declaration before + each #include, not by a prefix macro checkpatch refuses, so the two + lib files are not changed; no extern on the prototype in setup.h. ] +Assisted-by: LLM +--- + arch/x86/boot/startup/Makefile | 1 + + arch/x86/boot/startup/kaslr.c | 120 +++++++++++++++++++++++++++++++++ + arch/x86/include/asm/setup.h | 1 + + arch/x86/kernel/head_64.S | 7 ++ + arch/x86/platform/pvh/head.S | 15 ++++- + 5 files changed, 141 insertions(+), 3 deletions(-) + create mode 100644 arch/x86/boot/startup/kaslr.c + +diff --git a/arch/x86/boot/startup/Makefile b/arch/x86/boot/startup/Makefile +index 5e499cfb2..eeaefa4e2 100644 +--- a/arch/x86/boot/startup/Makefile ++++ b/arch/x86/boot/startup/Makefile +@@ -20,6 +20,7 @@ KCOV_INSTRUMENT := n + + obj-$(CONFIG_X86_64) += gdt_idt.o map_kernel.o + obj-$(CONFIG_AMD_MEM_ENCRYPT) += sme.o sev-startup.o ++obj-$(CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL) += kaslr.o + pi-objs := $(patsubst %.o,$(obj)/%.o,$(obj-y)) + + lib-$(CONFIG_X86_64) += la57toggle.o +diff --git a/arch/x86/boot/startup/kaslr.c b/arch/x86/boot/startup/kaslr.c +new file mode 100644 +index 000000000..fb07c31e2 +--- /dev/null ++++ b/arch/x86/boot/startup/kaslr.c +@@ -0,0 +1,120 @@ ++// SPDX-License-Identifier: GPL-2.0 ++ ++#include ++#include ++ ++/* A hack to avoid non-static declaration for kaslr_get_random_long(). */ ++#define _ASM_KASLR_H_ ++#include ++#include ++#include ++ ++extern char __relocation_end[]; ++ ++static struct boot_params *boot_params_ptr __initdata; ++ ++static inline void debug_putstr(const char *str) ++{ ++} ++ ++static inline bool has_cpuflag(int flag) ++{ ++ u32 reg = 0; ++ u32 level = native_cpuid_eax(0x0); ++ ++ if (level >= 0x00000001) { ++ if (flag == X86_FEATURE_RDRAND) ++ reg = native_cpuid_edx(0x1); ++ else if (flag == X86_FEATURE_TSC) ++ reg = native_cpuid_ecx(0x1); ++ } ++ ++ return test_bit(flag & 31, (unsigned long *)®); ++} ++ ++static unsigned long __init rotate_xor(unsigned long hash, const void *area, ++ size_t size) ++{ ++ size_t i; ++ unsigned long *ptr = (unsigned long *)area; ++ ++ for (i = 0; i < size / sizeof(hash); i++) { ++ /* Rotate by odd number of bits and XOR. */ ++ hash = (hash << ((sizeof(hash) * 8) - 7)) | (hash >> 7); ++ hash ^= ptr[i]; ++ } ++ ++ return hash; ++} ++ ++/* Attempt to create a simple but unpredictable starting entropy. */ ++static unsigned long get_boot_seed(void) ++{ ++ unsigned long hash = 0; ++ ++ hash = rotate_xor(hash, boot_params_ptr, sizeof(*boot_params_ptr)); ++ ++ return hash; ++} ++ ++/* Declared static first, so that the definition included below is too. */ ++static unsigned long __init kaslr_get_random_long(const char *purpose); ++ ++#define KASLR_COMPRESSED_BOOT ++#include "../../lib/kaslr.c" ++ ++/* A hack to avoid non-static declaration for cmdline_find_option_bool(). */ ++#define _ASM_X86_CMDLINE_H ++#undef CONFIG_CMDLINE_BOOL ++#define builtin_cmdline NULL ++static int __init cmdline_find_option_bool(const char *cmdline, const char *option); ++static int __init __maybe_unused cmdline_find_option(const char *cmdline, const char *option, ++ char *buffer, int bufsize); ++#include "../../lib/cmdline.c" ++ ++static unsigned long __init find_random_virt_addr(unsigned long minimum, ++ unsigned long image_size) ++{ ++ unsigned long slots, random_addr; ++ ++ /* ++ * There are how many CONFIG_PHYSICAL_ALIGN-sized slots ++ * that can hold image_size within the range of minimum to ++ * KERNEL_IMAGE_SIZE? ++ */ ++ slots = 1 + (KERNEL_IMAGE_SIZE - minimum - image_size) / CONFIG_PHYSICAL_ALIGN; ++ ++ random_addr = kaslr_get_random_long("Virtual") % slots; ++ ++ return random_addr * CONFIG_PHYSICAL_ALIGN + minimum; ++} ++ ++void __init __relocate_kernel(unsigned long p2v_offset, struct boot_params *bp) ++{ ++ int *reloc = (int *)rip_rel_ptr(__relocation_end); ++ unsigned long image_size = rip_rel_ptr(_end) - rip_rel_ptr(_text); ++ unsigned long ptr, virt_addr, delta; ++ unsigned long cmd_line_ptr; ++ ++ /* If relocation has occurred during decompression, simply skip it. */ ++ if (bp->hdr.loadflags & KASLR_FLAG) ++ return; ++ ++ cmd_line_ptr = bp->hdr.cmd_line_ptr | ((u64)bp->ext_cmd_line_ptr << 32); ++ if (cmdline_find_option_bool((char *)cmd_line_ptr, "nokaslr")) ++ return; ++ ++ boot_params_ptr = bp; ++ virt_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, image_size); ++ delta = virt_addr - LOAD_PHYSICAL_ADDR; ++ ++ for (reloc--; *reloc; reloc--) { ++ ptr = (unsigned long)(*reloc + p2v_offset); ++ *(uint32_t *)ptr += delta; ++ } ++ ++ for (reloc--; *reloc; reloc--) { ++ ptr = (unsigned long)(*reloc + p2v_offset); ++ *(uint64_t *)ptr += delta; ++ } ++} +diff --git a/arch/x86/include/asm/setup.h b/arch/x86/include/asm/setup.h +index 895d09faa..0a46aa0e8 100644 +--- a/arch/x86/include/asm/setup.h ++++ b/arch/x86/include/asm/setup.h +@@ -56,6 +56,7 @@ extern void startup_64_load_idt(void *vc_handler); + extern void __pi_startup_64_load_idt(void *vc_handler); + extern void early_setup_idt(void); + extern void __init do_early_exception(struct pt_regs *regs, int trapnr); ++void __init __relocate_kernel(unsigned long p2v_offset, struct boot_params *bp); + + #ifdef CONFIG_X86_INTEL_MID + extern void x86_intel_mid_early_setup(void); +diff --git a/arch/x86/kernel/head_64.S b/arch/x86/kernel/head_64.S +index 7ed5520dd..9bde9ae63 100644 +--- a/arch/x86/kernel/head_64.S ++++ b/arch/x86/kernel/head_64.S +@@ -97,6 +97,13 @@ SYM_CODE_START_NOALIGN(startup_64) + /* Sanitize CPU configuration */ + call verify_cpu + ++#ifdef CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL ++ leaq common_startup_64(%rip), %rdi ++ subq .Lcommon_startup_64(%rip), %rdi ++ movq %r15, %rsi ++ call __pi___relocate_kernel ++#endif ++ + /* + * Derive the kernel's physical-to-virtual offset from the physical and + * virtual addresses of common_startup_64(). +diff --git a/arch/x86/platform/pvh/head.S b/arch/x86/platform/pvh/head.S +index 53ee2d53f..098ad94d8 100644 +--- a/arch/x86/platform/pvh/head.S ++++ b/arch/x86/platform/pvh/head.S +@@ -105,6 +105,17 @@ SYM_CODE_START(pvh_start_xen) + btsl $_EFER_LME, %eax + wrmsr + ++ /* ++ * Fill the identity mapping entries instead of preconstructing them, ++ * as later relocations in __relocation_kernel() would modify them and ++ * break the mapping if they are prefilled, due to the generation of ++ * relocation entries. ++ */ ++ leal rva(pvh_init_top_pgt)(%ebp), %edi ++ addl $(pvh_level3_ident_pgt - __START_KERNEL_map + _KERNPG_TABLE_NOENC), (%edi) ++ leal rva(pvh_level3_ident_pgt)(%ebp), %edi ++ addl $(pvh_level2_ident_pgt - __START_KERNEL_map + _KERNPG_TABLE_NOENC), (%edi) ++ + /* + * Reuse the non-relocatable symbol emitted for the ELF note to + * subtract the build time physical address of pvh_start_xen() from +@@ -256,7 +267,6 @@ SYM_DATA_END_LABEL(early_stack, SYM_L_LOCAL, early_stack_end) + * startup_64 transitions to init_top_pgt. + */ + SYM_DATA_START_PAGE_ALIGNED(pvh_init_top_pgt) +- .quad pvh_level3_ident_pgt - __START_KERNEL_map + _KERNPG_TABLE_NOENC + .org pvh_init_top_pgt + L4_PAGE_OFFSET * 8, 0 + .quad pvh_level3_ident_pgt - __START_KERNEL_map + _KERNPG_TABLE_NOENC + .org pvh_init_top_pgt + L4_START_KERNEL * 8, 0 +@@ -265,8 +275,7 @@ SYM_DATA_START_PAGE_ALIGNED(pvh_init_top_pgt) + SYM_DATA_END(pvh_init_top_pgt) + + SYM_DATA_START_PAGE_ALIGNED(pvh_level3_ident_pgt) +- .quad pvh_level2_ident_pgt - __START_KERNEL_map + _KERNPG_TABLE_NOENC +- .fill 511, 8, 0 ++ .fill 512, 8, 0 + SYM_DATA_END(pvh_level3_ident_pgt) + SYM_DATA_START_PAGE_ALIGNED(pvh_level2_ident_pgt) + /* +-- +2.53.0 + diff --git a/kernel/patches/0018-x86-boot-Use-.data.relocs-section-for-performing-rel.patch b/kernel/patches/0018-x86-boot-Use-.data.relocs-section-for-performing-rel.patch new file mode 100644 index 00000000..1a84beec --- /dev/null +++ b/kernel/patches/0018-x86-boot-Use-.data.relocs-section-for-performing-rel.patch @@ -0,0 +1,70 @@ +From: Hou Wenlong +Date: Mon, 26 Jan 2026 21:33:55 +0800 +Subject: [PATCH] x86/boot: Use '.data.relocs' section for performing + relocations during decompression + +When CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL is enabled, all the +relocations are already in the '.data.relocs' section of the kernel +binary, so there is no need to generate 'vmlinux.relocs' again. Use it +directly for performing relocations during decompression. + +Signed-off-by: Hou Wenlong +--- + arch/x86/boot/compressed/Makefile | 6 ++++-- + arch/x86/boot/compressed/misc.c | 8 ++++++++ + 2 files changed, 12 insertions(+), 2 deletions(-) + +diff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile +index 06934f969..6e1643f1d 100644 +--- a/arch/x86/boot/compressed/Makefile ++++ b/arch/x86/boot/compressed/Makefile +@@ -12,7 +12,7 @@ + # vmlinux.bin is: + # vmlinux stripped of debugging and comments + # vmlinux.bin.all is: +-# vmlinux.bin + vmlinux.relocs ++# vmlinux.bin + vmlinux.relocs (CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL=n) + # vmlinux.bin.(gz|bz2|lzma|...) is: + # (see scripts/Makefile.lib size_append) + # compressed vmlinux.bin.all + u32 size of vmlinux.bin.all +@@ -73,7 +73,7 @@ LDFLAGS_vmlinux += -T + hostprogs := mkpiggy + HOST_EXTRACFLAGS += -I$(srctree)/tools/include + +-sed-voffset := -e 's/^\([0-9a-fA-F]*\) [ABbCDGRSTtVW] \(_text\|__start_rodata\|_sinittext\|__inittext_end\|__bss_start\|_end\)$$/\#define VO_\2 _AC(0x\1,UL)/p' ++sed-voffset := -e 's/^\([0-9a-fA-F]*\) [ABbCDGRSTtVW] \(_text\|__start_rodata\|_sinittext\|__inittext_end\|__bss_start\|_end\|__relocation_end\)$$/\#define VO_\2 _AC(0x\1,UL)/p' + + quiet_cmd_voffset = VOFFSET $@ + cmd_voffset = $(NM) $< | sed -n $(sed-voffset) > $@ +@@ -130,7 +130,9 @@ $(obj)/vmlinux.relocs: vmlinux.unstripped FORCE + $(call if_changed,relocs) + + vmlinux.bin.all-y := $(obj)/vmlinux.bin ++ifndef CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL + vmlinux.bin.all-$(CONFIG_X86_NEED_RELOCS) += $(obj)/vmlinux.relocs ++endif + + $(obj)/vmlinux.bin.gz: $(vmlinux.bin.all-y) FORCE + $(call if_changed,gzip) +diff --git a/arch/x86/boot/compressed/misc.c b/arch/x86/boot/compressed/misc.c +index 0f41ca0e5..d0f4e8302 100644 +--- a/arch/x86/boot/compressed/misc.c ++++ b/arch/x86/boot/compressed/misc.c +@@ -232,6 +232,14 @@ static void handle_relocations(void *output, unsigned long output_len, + } + debug_putstr("Performing relocations... "); + ++#ifdef CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL ++ /* ++ * If CONFIG_RELOCATABLE_UNCOMPRESSED_KERNEL is enabled, the relocations is in ++ * '.data.reloc' section of kernel binary. ++ */ ++ output_len = VO___relocation_end - VO__text; ++#endif ++ + /* + * Process relocations: 32 bit relocations first then 64 bit after. + * Two sets of binary relocations are added to the end of the kernel +-- +2.53.0 + diff --git a/kernel/patches/0019-x86-boot-Mark-a-kernel-that-relocated-itself-as-rand.patch b/kernel/patches/0019-x86-boot-Mark-a-kernel-that-relocated-itself-as-rand.patch new file mode 100644 index 00000000..6ca3953a --- /dev/null +++ b/kernel/patches/0019-x86-boot-Mark-a-kernel-that-relocated-itself-as-rand.patch @@ -0,0 +1,55 @@ +From: Manuel de Brito Fontes +Date: Mon, 23 Nov 2026 13:21:38 -0300 +Subject: [PATCH] x86/boot: Mark a kernel that relocated itself as + randomized + +__relocate_kernel() moves the kernel's virtual base and does not tell +the rest of the kernel. kaslr_enabled() reads KASLR_FLAG in the boot +parameters, which only the decompressor sets, so a kernel entered +through PVH that randomized itself still kept the direct map, vmalloc +and vmemmap at their fixed bases (RANDOMIZE_MEMORY did nothing), and +reported no kernel offset. + +Set KASLR_FLAG once the relocations have been applied, and apply none +from a table the relocs tool never filled, which would otherwise mark a +kernel that did not move as randomized. + +Carried by spin-stack/machine for #645 on top of Hou Wenlong's RFC +(lore cover.1769434279.git.houwenlong.hwl@antgroup.com, 2026-01-26), +which does neither. + +Assisted-by: LLM +--- + arch/x86/boot/startup/kaslr.c | 11 +++++++++++ + 1 file changed, 11 insertions(+) + +diff --git a/arch/x86/boot/startup/kaslr.c b/arch/x86/boot/startup/kaslr.c +index fb07c31e2..308384701 100644 +--- a/arch/x86/boot/startup/kaslr.c ++++ b/arch/x86/boot/startup/kaslr.c +@@ -104,6 +104,10 @@ void __init __relocate_kernel(unsigned long p2v_offset, struct boot_params *bp) + if (cmdline_find_option_bool((char *)cmd_line_ptr, "nokaslr")) + return; + ++ /* An empty table: the relocs tool never filled it, so nothing can move. */ ++ if (!reloc[-1]) ++ return; ++ + boot_params_ptr = bp; + virt_addr = find_random_virt_addr(LOAD_PHYSICAL_ADDR, image_size); + delta = virt_addr - LOAD_PHYSICAL_ADDR; +@@ -117,4 +121,11 @@ void __init __relocate_kernel(unsigned long p2v_offset, struct boot_params *bp) + ptr = (unsigned long)(*reloc + p2v_offset); + *(uint64_t *)ptr += delta; + } ++ ++ /* ++ * What the decompressor sets when it randomized the kernel, and what ++ * kaslr_enabled() reads: without it RANDOMIZE_MEMORY leaves the direct ++ * map, vmalloc and vmemmap at their fixed bases. ++ */ ++ bp->hdr.loadflags |= KASLR_FLAG; + } +-- +2.53.0 + diff --git a/kernel/patches/0020-x86-boot-Read-RDRAND-and-TSC-from-the-CPUID-registers.patch b/kernel/patches/0020-x86-boot-Read-RDRAND-and-TSC-from-the-CPUID-registers.patch new file mode 100644 index 00000000..ef0c005e --- /dev/null +++ b/kernel/patches/0020-x86-boot-Read-RDRAND-and-TSC-from-the-CPUID-registers.patch @@ -0,0 +1,45 @@ +From: Manuel de Brito Fontes +Date: Mon, 23 Nov 2026 13:58:23 -0300 +Subject: [PATCH] x86/boot: Read RDRAND and TSC from the CPUID registers that + hold them + +has_cpuflag() in the self-relocating kernel's KASLR reads +X86_FEATURE_RDRAND from CPUID leaf 1's EDX and X86_FEATURE_TSC from its +ECX. The two are the other way round: RDRAND is ECX bit 30 (capability +word 4) and TSC is EDX bit 4 (word 0). So the test for RDRAND reads a +reserved bit, and the test for TSC reads DS-CPL, which KVM does not +expose. kaslr_get_random_long() then mixes neither RDRAND nor RDTSC into +the virtual base, only the i8254 counter and a hash of boot_params, +where the decompressor's KASLR, from which this code was taken, mixes +both. + +Read each flag from the register that holds it. The virtual base is +then drawn from the decompressor's sources again, less its hash of the +build string, which is public. The cost is one RDRAND and one RDTSC at +boot. + +Carried by spin-stack/machine for #645 on top of Hou Wenlong's RFC +(lore cover.1769434279.git.houwenlong.hwl@antgroup.com, 2026-01-26), +whose 3/5 has the registers swapped. + +Assisted-by: LLM +--- + arch/x86/boot/startup/kaslr.c | 4 ++-- + 1 file changed, 2 insertions(+), 2 deletions(-) + +diff --git a/arch/x86/boot/startup/kaslr.c b/arch/x86/boot/startup/kaslr.c +index 3083847..8114422 100644 +--- a/arch/x86/boot/startup/kaslr.c ++++ b/arch/x86/boot/startup/kaslr.c +@@ -24,9 +24,9 @@ static inline bool has_cpuflag(int flag) + + if (level >= 0x00000001) { + if (flag == X86_FEATURE_RDRAND) +- reg = native_cpuid_edx(0x1); +- else if (flag == X86_FEATURE_TSC) + reg = native_cpuid_ecx(0x1); ++ else if (flag == X86_FEATURE_TSC) ++ reg = native_cpuid_edx(0x1); + } + + return test_bit(flag & 31, (unsigned long *)®); diff --git a/machine/host.go b/machine/host.go index 5eef77b6..7e5c16be 100644 --- a/machine/host.go +++ b/machine/host.go @@ -30,7 +30,7 @@ func (s Spec) Files() []string { if s.Initrd != "" { files = append(files, s.Initrd) } - for _, f := range []string{s.bios(), kernelROM, vapicROM} { + for _, f := range []string{s.bios(), kernelROM(s.Kernel), vapicROM} { files = append(files, filepath.Join(s.Firmware, f)) } return files diff --git a/machine/kernel.go b/machine/kernel.go new file mode 100644 index 00000000..1bc06f41 --- /dev/null +++ b/machine/kernel.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 + +package machine + +import ( + "debug/elf" + "fmt" + "os" +) + +// The Xen ELF notes QEMU reads from a kernel it enters through PVH (xen/include/public/elfnote.h). +const ( + // xenPhys32Entry is the 32-bit entry, pvh_start_xen: QEMU enters an ELF kernel through PVH, + // with pvh.bin, only when it has one. + xenPhys32Entry = 18 + // xenPhys32Reloc says the kernel runs from any aligned address in a range. QEMU puts it at a + // random one (qemu/patches/0008), the physical base a bzImage's decompressor chose before. + xenPhys32Reloc = 19 +) + +// PVH is whether the file at path is a kernel the machine enters through PVH at a random base: a +// 64-bit ELF with both Xen notes. A vmlinux without the relocation note boots, at the address it +// was linked for, and that is what a release from before #645 would have done: it is refused. +func PVH(path string) error { + f, err := elf.Open(path) + if err != nil { + return fmt.Errorf("reading %s as an ELF kernel: %w", path, err) + } + defer func() { _ = f.Close() }() + if f.Class != elf.ELFCLASS64 { + return fmt.Errorf("%s is a %s ELF, and the machine enters a 64-bit kernel", path, f.Class) + } + for _, note := range []uint32{xenPhys32Entry, xenPhys32Reloc} { + if !hasXenNote(f, note) { + return fmt.Errorf("%s has no Xen ELF note %d: QEMU cannot enter it through PVH at a random physical base", path, note) + } + } + return nil +} + +// hasXenNote is whether f has a note named "Xen" of type t in a PT_NOTE segment, where QEMU looks. +func hasXenNote(f *elf.File, t uint32) bool { + for _, p := range f.Progs { + if p.Type != elf.PT_NOTE { + continue + } + b := make([]byte, p.Filesz) + if _, err := p.ReadAt(b, 0); err != nil { + continue + } + for len(b) >= 12 { // mutate-exempt: a header alone, 12 bytes, has no room for the name "Xen" and matches nothing + namesz, descsz, typ := f.ByteOrder.Uint32(b), f.ByteOrder.Uint32(b[4:]), f.ByteOrder.Uint32(b[8:]) + next := 12 + (int(namesz)+3)&^3 + (int(descsz)+3)&^3 + if next > len(b) { + break + } + if typ == t && namesz == 4 && string(b[12:16]) == "Xen\x00" { + return true + } + b = b[next:] + } + } + return false +} + +// bootable refuses a kernel the machine does not enter: one that is neither a bzImage, "HdrS" at +// 0x202 (Documentation/arch/x86/boot.rst), nor an ELF kernel entered through PVH. QEMU given +// anything else tries it as a multiboot kernel, and the failure would be a guest that never +// starts, not a sentence. +func bootable(path string) error { + f, err := os.Open(path) //nolint:gosec // the kernel the Spec names + if err != nil { + return fmt.Errorf("opening kernel %s: %w", path, err) + } + defer func() { _ = f.Close() }() + magic := make([]byte, 4) + if _, err := f.ReadAt(magic, 0); err == nil && string(magic) == elf.ELFMAG { + return PVH(path) + } + if _, err := f.ReadAt(magic, 0x202); err != nil || string(magic) != "HdrS" { + return fmt.Errorf("%s is neither a bzImage (no HdrS at 0x202) nor an ELF kernel, the two the machine enters", path) + } + return nil +} + +// kernelROM is the option ROM QEMU enters the kernel at path with: pvh.bin for an ELF kernel, +// linuxboot_dma.bin for a bzImage. Spec.Args refuses a kernel that is neither (bootable). +func kernelROM(path string) string { + f, err := os.Open(path) //nolint:gosec // the kernel the Spec names + if err != nil { + return bzImageROM + } + defer func() { _ = f.Close() }() + magic := make([]byte, 4) + if _, err := f.ReadAt(magic, 0); err == nil && string(magic) == elf.ELFMAG { + return pvhROM + } + return bzImageROM +} diff --git a/machine/machine_test.go b/machine/machine_test.go index cff24ace..83c68b65 100644 --- a/machine/machine_test.go +++ b/machine/machine_test.go @@ -3,16 +3,19 @@ package machine import ( + "encoding/binary" "fmt" "os" "path/filepath" "slices" "strings" "testing" + + "github.com/spin-stack/machine/internal/elftest" ) // spec returns a minimal valid spec pointing at files that exist: Args asks the kernel whether -// it is a bzImage. +// it is a bzImage or an ELF kernel entered through PVH. func spec(t *testing.T) Spec { t.Helper() dir := t.TempDir() @@ -478,18 +481,34 @@ func TestValidateRefuses(t *testing.T) { // A kernel refused is named, for whoever reads the error and not the code. s := spec(t) s.Kernel = s.QEMU - if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), s.QEMU+" is not a bzImage") { + if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), s.QEMU+" is neither a bzImage") { t.Errorf("Args of a kernel that is not a bzImage: %v", err) } - // Long enough to hold a setup header and without its magic, as a vmlinux is. + // Long enough to hold a setup header and without its magic. s = spec(t) - s.Kernel = filepath.Join(t.TempDir(), "vmlinux") + s.Kernel = filepath.Join(t.TempDir(), "kernel") if err := os.WriteFile(s.Kernel, make([]byte, 0x400), 0o600); err != nil { t.Fatal(err) } - if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "is not a bzImage") { + if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "is neither a bzImage") { t.Errorf("Args of a kernel with no HdrS at 0x202: %v", err) } + // An ELF kernel QEMU would enter where it was linked, with no relocation note. + if err := os.WriteFile(s.Kernel, elftest.Kernel([]uint32{xenPhys32Entry}, nil), 0o600); err != nil { + t.Fatal(err) + } + if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "no Xen ELF note 19") { + t.Errorf("Args of a vmlinux that cannot move: %v", err) + } + // Its relocation note cut short by the segment that holds it, as QEMU would not read it. + k := elftest.Kernel([]uint32{xenPhys32Entry, xenPhys32Reloc}, nil) + binary.LittleEndian.PutUint64(k[64+32:], 28+20) // PT_NOTE's p_filesz: the first note whole, the second's descriptor 8 bytes short + if err := os.WriteFile(s.Kernel, k, 0o600); err != nil { + t.Fatal(err) + } + if _, err := s.Args(); err == nil || !strings.Contains(err.Error(), "no Xen ELF note 19") { + t.Errorf("Args of a vmlinux whose relocation note is truncated: %v", err) + } // And the specs the cases above are made from have to pass, or every one of them // would pass for the wrong reason. diff --git a/machine/release.go b/machine/release.go index 6c0cb14f..60e4af8c 100644 --- a/machine/release.go +++ b/machine/release.go @@ -31,13 +31,15 @@ const ( rootfsName = "image/rootfs.qcow2" manifest = "machine.env" - // kernelName is the kernel the machine boots: a bzImage, entered through its setup code - // and the decompressor that picks KASLR's random base, with linuxboot_dma.bin the option - // ROM QEMU adds for it. Until 2026-11-19 the machine entered vmlinux through its PVH notes, - // which skips that decompressor: _text was ffffffff81000000 at every boot. A release from - // before v20261119.02 carries no bzImage, and OpenRelease refuses it for that. - kernelName = "kernel/bzImage" - kernelROM = "linuxboot_dma.bin" + // The kernel the machine boots, and the option ROM QEMU enters it with. A release whose + // vmlinux randomizes itself (PVH) boots it through PVH, with no decompressor (#645); one + // from v20261119.02 to #645 boots its bzImage, whose decompressor picks KASLR's base. Until + // 2026-11-19 the machine entered a vmlinux that could not move, through PVH, and _text was + // ffffffff81000000 at every boot: such a release has neither, and is refused. + vmlinuxName = "kernel/vmlinux" + pvhROM = "pvh.bin" + bzImageName = "kernel/bzImage" + bzImageROM = "linuxboot_dma.bin" ) // Release is an unpacked spin-machine release: the tree the tarball holds under @@ -50,6 +52,8 @@ const ( type Release struct { dir string env map[string]string + // kernel and rom are the kernel this release boots and the option ROM QEMU enters it with. + kernel, rom string } // OpenRelease reads the release tree at dir and reports what is missing, if anything. @@ -69,8 +73,11 @@ func OpenRelease(dir string) (*Release, error) { return nil, fmt.Errorf("resolving release directory %s: %w", dir, err) } - r := &Release{dir: abs} - for _, want := range []string{qemuName, qemuImgName, kernelName, filepath.Join(firmwareDir, kernelROM), filepath.Join(firmwareDir, DefaultBIOS)} { + r := &Release{dir: abs, kernel: bzImageName, rom: bzImageROM} + if PVH(filepath.Join(abs, vmlinuxName)) == nil { + r.kernel, r.rom = vmlinuxName, pvhROM + } + for _, want := range []string{qemuName, qemuImgName, r.kernel, filepath.Join(firmwareDir, r.rom), filepath.Join(firmwareDir, DefaultBIOS)} { p := filepath.Join(abs, want) if _, err := os.Stat(p); err != nil { return nil, fmt.Errorf("%s is not a whole machine: %w", abs, err) @@ -87,22 +94,6 @@ func OpenRelease(dir string) (*Release, error) { // QEMUImg creates and rebases the qcow2 files a guest's disks are. func (r *Release) QEMUImg() string { return filepath.Join(r.dir, qemuImgName) } -// isBzImage refuses a file that is not a bzImage: its setup header's magic, "HdrS" at 0x202. -// QEMU given anything else tries it as a multiboot or an ELF kernel, and this machine -// enters neither: the failure would be a guest that never starts, not a sentence. -func isBzImage(path string) error { - f, err := os.Open(path) - if err != nil { - return fmt.Errorf("opening kernel %s: %w", path, err) - } - defer func() { _ = f.Close() }() - magic := make([]byte, 4) - if _, err := f.ReadAt(magic, 0x202); err != nil || string(magic) != "HdrS" { - return fmt.Errorf("%s is not a bzImage (no HdrS at 0x202): the machine boots a bzImage, and nothing enters a vmlinux", path) - } - return nil -} - // Rootfs is the read-only base image every workspace overlays. // // Never opened for writing: many VMs map this one file through a qcow2 backing @@ -128,8 +119,8 @@ func (r *Release) optional(name, what string) (string, error) { func (r *Release) Version() string { return r.env["version"] } // Spec returns the parts of a machine this release supplies for the accelerator accel ("" or -// "kvm", or "tcg"): the QEMU that runs under it, the kernel, a bzImage, the firmware directory -// QEMU loads the BIOS and linuxboot_dma.bin from, and Accel. It is the one way to a Spec's +// "kvm", or "tcg"): the QEMU that runs under it, the kernel it boots, the firmware directory +// QEMU loads the BIOS and the kernel's option ROM from, and Accel. It is the one way to a Spec's // binaries, so that a binary and the accelerator it was built for cannot be paired wrong. // // Under "kvm" the QEMU is the ordinary build, which has no TCG compiled in. Under "tcg" it is @@ -152,7 +143,7 @@ func (r *Release) Spec(accel string) (Spec, error) { } return Spec{ QEMU: qemu, - Kernel: filepath.Join(r.dir, kernelName), + Kernel: filepath.Join(r.dir, r.kernel), Firmware: filepath.Join(r.dir, firmwareDir), Accel: accel, }, nil diff --git a/machine/release_test.go b/machine/release_test.go index 66b14143..7b45e5ae 100644 --- a/machine/release_test.go +++ b/machine/release_test.go @@ -6,8 +6,11 @@ import ( "os" "path/filepath" "reflect" + "slices" "strings" "testing" + + "github.com/spin-stack/machine/internal/elftest" ) // tree writes a release-shaped directory containing exactly the given files. @@ -26,7 +29,7 @@ func tree(t *testing.T, files ...string) string { return dir } -var whole = []string{qemuName, qemuImgName, kernelName, filepath.Join(firmwareDir, kernelROM), filepath.Join(firmwareDir, DefaultBIOS)} +var whole = []string{qemuName, qemuImgName, bzImageName, filepath.Join(firmwareDir, bzImageROM), filepath.Join(firmwareDir, DefaultBIOS)} func TestOpenReleaseNamesWhatIsMissing(t *testing.T) { // One file at a time, because a release with a hole in it is the failure @@ -48,13 +51,52 @@ func TestOpenReleaseNamesWhatIsMissing(t *testing.T) { } } -// A release from before v20261119.02 carries a vmlinux and pvh.bin and no bzImage. Nothing -// enters a vmlinux any more, so it is refused, and the refusal names what it lacks. +// A release from before v20261119.02 carries a vmlinux that cannot move, pvh.bin and no +// bzImage. Entered, it ran where it was linked, so it is refused, and the refusal names what it +// lacks. func TestOpenReleaseRefusesAReleaseWithoutABzImage(t *testing.T) { - old := tree(t, qemuName, qemuImgName, "kernel/vmlinux", filepath.Join(firmwareDir, "pvh.bin"), filepath.Join(firmwareDir, DefaultBIOS)) - if _, err := OpenRelease(old); err == nil || !strings.Contains(err.Error(), kernelName) { + old := tree(t, qemuName, qemuImgName, vmlinuxName, filepath.Join(firmwareDir, pvhROM), filepath.Join(firmwareDir, DefaultBIOS)) + if _, err := OpenRelease(old); err == nil || !strings.Contains(err.Error(), bzImageName) { t.Errorf("OpenRelease of a release without a bzImage returned %v", err) } + // Nor is an ELF with the entry note alone: QEMU would enter it where it was linked. + writeKernel(t, filepath.Join(old, vmlinuxName), elftest.Kernel([]uint32{xenPhys32Entry}, nil)) + if _, err := OpenRelease(old); err == nil || !strings.Contains(err.Error(), bzImageName) { + t.Errorf("OpenRelease of a release whose vmlinux cannot move returned %v", err) + } +} + +// A vmlinux that QEMU places at a random physical base and that moves its own virtual base is +// what a release boots, through PVH, whether a bzImage is beside it or not; and pvh.bin, the +// option ROM that enters it, is then part of a whole release. +func TestOpenReleaseBootsAVmlinuxThatRandomizesItself(t *testing.T) { + dir := tree(t, qemuName, qemuImgName, bzImageName, filepath.Join(firmwareDir, bzImageROM), filepath.Join(firmwareDir, DefaultBIOS)) + writeKernel(t, filepath.Join(dir, vmlinuxName), elftest.Kernel([]uint32{xenPhys32Entry, xenPhys32Reloc}, nil)) + if _, err := OpenRelease(dir); err == nil || !strings.Contains(err.Error(), pvhROM) { + t.Errorf("OpenRelease without pvh.bin returned %v", err) + } + writeKernel(t, filepath.Join(dir, firmwareDir, pvhROM), nil) + r, err := OpenRelease(dir) + if err != nil { + t.Fatal(err) + } + s, err := r.Spec("kvm") + if err != nil { + t.Fatal(err) + } + if s.Kernel != filepath.Join(dir, vmlinuxName) { + t.Errorf("the release boots %s, not its vmlinux", s.Kernel) + } + if !slices.Contains(s.Files(), filepath.Join(dir, firmwareDir, pvhROM)) { + t.Errorf("a machine of it opens %v, without pvh.bin", s.Files()) + } +} + +func writeKernel(t *testing.T, path string, b []byte) { + t.Helper() + if err := os.WriteFile(path, b, 0o644); err != nil { + t.Fatal(err) + } } func TestOpenReleaseAcceptsAMachineWithoutTheOptionalParts(t *testing.T) { @@ -145,7 +187,7 @@ func TestSpecTakesItsPathsFromTheRelease(t *testing.T) { // The rest of a machine is about one VM and is the caller's to fill in. want := Spec{ QEMU: filepath.Join(dir, qemu), - Kernel: filepath.Join(dir, kernelName), + Kernel: filepath.Join(dir, bzImageName), Firmware: filepath.Join(dir, firmwareDir), Accel: accel, } diff --git a/machine/spec.go b/machine/spec.go index c2416aba..09ad08aa 100644 --- a/machine/spec.go +++ b/machine/spec.go @@ -206,7 +206,8 @@ type Spec struct { // Firmware is the directory QEMU loads option ROMs and BIOS blobs from. It // is the `qemu/` directory of a release; without it the machine cannot find - // the BIOS, nor linuxboot_dma.bin, the option ROM QEMU adds for the bzImage. + // the BIOS, nor the option ROM QEMU enters the kernel with: pvh.bin for an ELF + // kernel, linuxboot_dma.bin for a bzImage. Firmware string // BIOS is the firmware the machine runs, a file in Firmware: DefaultBIOS when @@ -432,7 +433,7 @@ func (s Spec) validate() error { return fmt.Errorf("%d disks arriving later, and the controller addresses %d", s.HotplugDisks, maxHotplugDisks) } - if err := isBzImage(s.Kernel); err != nil { + if err := bootable(s.Kernel); err != nil { return err } if err := s.Cmdline.validate(); err != nil { diff --git a/qemu/Dockerfile b/qemu/Dockerfile index 9d56a031..2c4e9282 100644 --- a/qemu/Dockerfile +++ b/qemu/Dockerfile @@ -352,7 +352,7 @@ RUN --mount=type=cache,sharing=locked,id=qemu-src-${QEMU_VERSION},target=/var/ca RUN --mount=type=cache,sharing=locked,id=qemu-src-${QEMU_VERSION},target=/var/cache/qemu \ tree="$(sh /build/qemu-source.sh)" && \ mkdir -p /build/pc-bios && \ - for f in bios.bin bios-256k.bin linuxboot_dma.bin kvmvapic.bin efi-virtio.rom; do \ + for f in bios.bin bios-256k.bin linuxboot_dma.bin pvh.bin kvmvapic.bin efi-virtio.rom; do \ install -m 0644 "$tree/pc-bios/$f" "/build/pc-bios/$f"; \ done diff --git a/qemu/README.md b/qemu/README.md index 7fa5abfa..68dc452d 100644 --- a/qemu/README.md +++ b/qemu/README.md @@ -24,6 +24,7 @@ posted upstream. | 0004 | `query-blockstats` `x-flat`: a device's counters without its backing chain | DiskUsage's main-loop time 293 → 96 µs, −197 [−202, −181] (lab 44973302743) | `verify qemu` (the member); `verify args`: no `parent` or `backing` under x-flat, both without | | 0005 | A machine made for an incoming migration writes its TSC only from the migration, so KVM takes the checkpoint's TSC as given (#452) | correctness: without it a guest saved with a timer due sleeps until its old TSC deadline, the restored p95 539-548 ms (lab 44987412171) | `boot:patches`: a guest restored 650 ms ahead of its new vCPU's TSC goes no more than 200 ms without a line (#472) | | 0006 | x86 CPUs get `x-legacy-cpuid2-cache`. Off, a legacy cache model under `x-consistent-cache=off` (host's and max's) describes in leaf 2 the caches leaf 4 does, and not `legacy_intel_cpuid2_cache_info`. Default on, QEMU's behaviour (#586) | correctness: glibc read a 2 MiB 8-way L2 from leaf 2 where leaf 4 and the guest's kernel said 4 MiB 16-way (lab 45100482399) | the build (`-device max-x86_64-cpu,help`); `boot:patches`, once the machine sets it off: glibc's L2 is the kernel's | +| 0008 | A 64-bit ELF kernel with `XEN_ELFNOTE_PHYS32_RELOC`, which Linux emits under `CONFIG_PVH` since 6.12 (Jason Andryuk), is loaded at a random multiple of the note's alignment below the initrd and the ACPI data, its entry moved with it, from `qemu_guest_getrandom`: the physical base a bzImage's decompressor chose before (#645). Xen's toolstack honours the note. QEMU's tree and history name it nowhere (the qemu/qemu mirror's code and commit search, 2026-11-23); qemu-devel's archives could not be searched that day (lore and lists.gnu.org refused, patchew timed out) | with kernel 0014-0020, cold −16.8 [−20.9, −13.0] (lab 45219785493, `docs/boot-time.md`) | `boot:kaslr`: the physical "Kernel code" takes more than one value across ten boots | | 0007 | x86's `-kernel` maps a bzImage read-only instead of reading the whole file into a heap buffer that only fw_cfg reads; the pages are touched when qboot copies them, from the page cache. A kernel with a dtb appended still gets a buffer (#646) | cold −13.4 [−16.9, −7.3], restored −9.3 [−11.2, −6.1] evicted (labs 45182382388, 45182382864) | the build: a held TCG machine's `/proc/PID/maps` names a stub bzImage given to it | `docs/boot-time.md`, "What the machine carries", says what each earns among everything else the @@ -52,11 +53,12 @@ is a qcow2 overlay created by running it, so a release with the emulator and wit cannot give a container anywhere to write. `qemu-nbd` comes out of the same flag and is deliberately not shipped. It exports a disk over NBD, which nothing here does. -**A bzImage, through qboot.** QEMU puts the kernel's setup and payload in fw_cfg and qboot -loads and enters them itself. The bzImage's decompressor is where KASLR picks the kernel's -random base. Until 2026-11-19 the machine entered an ELF `vmlinux` through its Xen PVH notes -and `pvh.bin`, which skips that decompressor and left the kernel at the same address on every -boot. There is no bootloader and no UEFI: the same guest under UEFI + Secure Boot was measured +**A vmlinux through PVH, through qboot.** QEMU loads the ELF kernel's segments itself, at a +random physical base (0008), and qboot enters it through `pvh.bin`; the kernel moves its own +virtual base (`kernel/README.md`, "KASLR with no decompressor", #645). From 2026-11-19 to #645 the +machine booted a bzImage, through `linuxboot_dma.bin`, because its decompressor was the only thing +that randomized the kernel; it still boots one for a release from then. Before 2026-11-19 it +entered a vmlinux through PVH that could not move, at the same address every boot. There is no bootloader and no UEFI: the same guest under UEFI + Secure Boot was measured at +356 ms and rejected, before this repository existed (the number came with it, 2afac47, 2026-09-07, and no run of it is kept). The BIOS is qboot, patched and built here as [qboot/README.md](qboot/README.md) describes, with SeaBIOS shipped as the fallback. diff --git a/qemu/patches/0008-hw-i386-load-a-PVH-kernel-at-a-random-physical-base.patch b/qemu/patches/0008-hw-i386-load-a-PVH-kernel-at-a-random-physical-base.patch new file mode 100644 index 00000000..5b5cd3e3 --- /dev/null +++ b/qemu/patches/0008-hw-i386-load-a-PVH-kernel-at-a-random-physical-base.patch @@ -0,0 +1,196 @@ +From: Manuel de Brito Fontes +Date: Mon, 23 Nov 2026 13:23:31 -0300 +Subject: [PATCH] hw/i386: load a PVH kernel at a random physical base + +A kernel entered through PVH has no decompressor, and the decompressor +is where a bzImage chooses its random physical base. QEMU loads the +vmlinux where it is linked, so every PVH boot ran from the same +physical address even when the kernel randomized its virtual base. + +Linux has emitted XEN_ELFNOTE_PHYS32_RELOC under CONFIG_PVH since 6.12 +(Jason Andryuk, "x86/pvh: Add 64bit relocation page tables"): the +kernel runs from any multiple of an alignment within a range, and finds +where it was put from its own entry address. Xen's toolstack honours +the note; QEMU ignored it. + +Read the note and load the segments at a random multiple of its +alignment that keeps the kernel below the initrd and the ACPI data, the +range the decompressor would choose from in the same memory, with the +entry moved by the same offset. The randomness is qemu_guest_getrandom, +which -seed makes deterministic. A kernel without the note, or one +that does not fit, is loaded where it is linked, as before. + +The layout lives in guest memory, so a migrated or restored guest keeps +the one it booted with; only a boot draws again. +--- + hw/i386/x86-common.c | 120 +++++++++++++++++++++++++++++++++++++++++-- + 1 file changed, 115 insertions(+), 5 deletions(-) + +diff --git a/hw/i386/x86-common.c b/hw/i386/x86-common.c +index f98f20b01..eacb5d1b3 100644 +--- a/hw/i386/x86-common.c ++++ b/hw/i386/x86-common.c +@@ -25,6 +25,8 @@ + #include "qemu/cutils.h" + #include "qemu/units.h" + #include "qemu/datadir.h" ++#include "qemu/guest-random.h" ++#include "qemu/host-utils.h" + #include "qapi/error.h" + #include "system/numa.h" + #include "system/system.h" +@@ -592,11 +594,109 @@ static uint64_t read_pvh_start_addr(void *arg1, void *arg2, bool is64) + return pvh_start_addr; + } + ++/* ++ * XEN_ELFNOTE_PHYS32_RELOC: the kernel runs from any multiple of an ++ * alignment between a minimum and a maximum address. Linux has emitted ++ * it under CONFIG_PVH since 6.12 and finds where it was put by itself. ++ */ ++#define XEN_ELFNOTE_PHYS32_RELOC 19 ++ ++typedef struct PVHLoad { ++ /* First: load_elf() reads the note type it searches through the opaque. */ ++ uint64_t note_type; ++ uint64_t offset; ++} PVHLoad; ++ ++static uint64_t pvh_translate(void *opaque, uint64_t addr) ++{ ++ return addr + ((PVHLoad *)opaque)->offset; ++} ++ ++/* ++ * Where a 64-bit ELF kernel with XEN_ELFNOTE_PHYS32_RELOC goes, as an offset ++ * from where it is linked: a random multiple of the note's alignment that ++ * keeps every segment within the note's range and below @top. The ++ * decompressor of a bzImage chooses the physical base the same way, and a ++ * kernel entered through PVH has no decompressor. 0, where it is linked, ++ * for a kernel without the note or one that does not fit. ++ */ ++static uint64_t pvh_random_offset(const char *kernel_filename, uint64_t top) ++{ ++ g_autoptr(GMappedFile) mapped = g_mapped_file_new(kernel_filename, ++ false, NULL); ++ const uint8_t *file; ++ size_t size; ++ const Elf64_Ehdr *eh; ++ uint64_t low = UINT64_MAX, high = 0, first, slots, random; ++ uint32_t align = 0, min = 0, max = 0; ++ bool found = false; ++ ++ if (!mapped) { ++ return 0; ++ } ++ file = (const uint8_t *)g_mapped_file_get_contents(mapped); ++ size = g_mapped_file_get_length(mapped); ++ eh = (const Elf64_Ehdr *)file; ++ if (size < sizeof(*eh) || eh->e_ident[EI_CLASS] != ELFCLASS64 || ++ eh->e_phentsize != sizeof(Elf64_Phdr) || ++ eh->e_phoff > size || ++ (uint64_t)eh->e_phnum * sizeof(Elf64_Phdr) > size - eh->e_phoff) { ++ return 0; ++ } ++ ++ for (int i = 0; i < eh->e_phnum; i++) { ++ const Elf64_Phdr *ph = (const Elf64_Phdr *)(file + eh->e_phoff) + i; ++ uint64_t off, end; ++ ++ if (ph->p_type == PT_LOAD && ph->p_memsz) { ++ low = MIN(low, ph->p_paddr); ++ high = MAX(high, ph->p_paddr + ph->p_memsz); ++ continue; ++ } ++ if (ph->p_type != PT_NOTE || ph->p_offset > size || ++ ph->p_filesz > size - ph->p_offset) { ++ continue; ++ } ++ off = ph->p_offset; ++ end = ph->p_offset + ph->p_filesz; ++ while (end - off >= sizeof(Elf64_Nhdr)) { ++ const Elf64_Nhdr *nh = (const Elf64_Nhdr *)(file + off); ++ uint64_t name = off + sizeof(*nh); ++ uint64_t desc = name + QEMU_ALIGN_UP(nh->n_namesz, 4); ++ ++ off = desc + QEMU_ALIGN_UP(nh->n_descsz, 4); ++ if (off > end) { ++ break; ++ } ++ if (nh->n_type == XEN_ELFNOTE_PHYS32_RELOC && nh->n_namesz == 4 && ++ !memcmp(file + name, "Xen", 4) && nh->n_descsz >= 12) { ++ align = ldl_le_p(file + desc); ++ min = ldl_le_p(file + desc + 4); ++ max = ldl_le_p(file + desc + 8); ++ found = true; ++ } ++ } ++ } ++ ++ if (!found || !align || !is_power_of_2(align) || low >= high) { ++ return 0; ++ } ++ top = MIN(top, (uint64_t)max + 1); ++ first = QEMU_ALIGN_UP(MAX((uint64_t)min, low), align); ++ if (first + (high - low) > top) { ++ return 0; ++ } ++ slots = (top - (high - low) - first) / align + 1; ++ qemu_guest_getrandom_nofail(&random, sizeof(random)); ++ return first + (random % slots) * align - low; ++} ++ + static bool load_elfboot(const char *kernel_filename, + int kernel_file_size, + uint8_t *header, + size_t pvh_xen_start_addr, +- FWCfgState *fw_cfg) ++ FWCfgState *fw_cfg, ++ uint64_t top) + { + uint32_t flags = 0; + uint32_t mh_load_addr = 0; +@@ -618,9 +718,12 @@ static bool load_elfboot(const char *kernel_filename, + exit(1); + } + +- uint64_t elf_note_type = XEN_ELFNOTE_PHYS32_ENTRY; ++ PVHLoad load = { ++ .note_type = XEN_ELFNOTE_PHYS32_ENTRY, ++ .offset = pvh_random_offset(kernel_filename, top), ++ }; + kernel_size = load_elf(kernel_filename, read_pvh_start_addr, +- NULL, &elf_note_type, &elf_entry, ++ pvh_translate, &load, &elf_entry, + &elf_low, &elf_high, NULL, + ELFDATA2LSB, I386_ELF_MACHINE, 0, 0); + +@@ -635,7 +738,7 @@ static bool load_elfboot(const char *kernel_filename, + error_report("Error loading uncompressed kernel without PVH ELF Note"); + exit(1); + } +- fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, pvh_start_addr); ++ fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, pvh_start_addr + load.offset); + fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr); + fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, elf_kernel_size); + +@@ -705,8 +808,15 @@ void x86_load_linux(X86MachineState *x86ms, + * saving the PVH entry point used by the x86/HVM direct boot ABI. + * If load_elfboot() is successful, populate the fw_cfg info. + */ ++ uint64_t top = x86ms->below_4g_mem_size - acpi_data_size; ++ ++ /* The initrd goes at the top of low memory, below the ACPI data. */ ++ if (initrd_filename) { ++ top -= QEMU_ALIGN_UP(get_image_size(initrd_filename, NULL), 4096) ++ + 4096; ++ } + if (load_elfboot(kernel_filename, kernel_size, +- header, pvh_start_addr, fw_cfg)) { ++ header, pvh_start_addr, fw_cfg, top)) { + fclose(f); + + fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, +-- +2.53.0 +