# Red Baron, libc5 and the last partial heap page

Investigation started 2026-10-28. The kernel is compiled in the build jail
and booted only in BARONVM, a separate 512 MiB bhyve guest. No test kernel
or Linuxulator module is installed into the running host. This is a running
investigation log; conclusions below distinguish observations from proposed
fixes and later VM results.

## Starting point: a browser that needed an allocator replacement

Red Baron 3.10 is an i386 Linux ELF executable using the supplied libc5 and
`/lib/ld-linux.so.1`. BARONVM already starts native FreeBSD Xvnc and the
browser automatically. Its launcher had preloaded the supplied
`libredbaron_compat.so`, replacing the allocation functions with an
`mmap`-based allocator. That displayed the browser but bypassed the failing
heap path. The purpose of this investigation is to run the original
application and libraries without that preload.

The existing kernel patches preserve a byte-precise Linux program break,
separate from page-rounded VM mappings. All 28 static syscall checks passed,
but the actual application still crashed without the shim. Its saved trace
showed its first break request:

```text
linux_brk(0x082ee290) -> 0x082ef000
SIGSEGV
```

The lower-bound guard added during earlier review now produced the rounded
result. It initialized `vm_brk_min` to the initial page-rounded mapping end
and refused any smaller request. The earlier success-return correction
could therefore pass while this real allocator initialization still failed.

## Reading the executable, rather than guessing its heap floor

`readelf -l` reports the final loadable segment as:

```text
Virtual address: 0x082aec48
File size:       0x000244fc
Memory size:     0x0003f620
```

Its exact end is `0x082ee268`; `nm` independently identifies that address as
`_end`. The additional memory beyond file size includes BSS: space reserved
for variables initially filled with zero. The page mapping ends at
`0x082ef000`. The first libc5 request, `0x082ee290`, is 40 bytes past `_end`
and 3,440 bytes below the mapped end. It does not require another page and
does not overlap the executable's declared storage.

A page is the unit of mapping, not a requirement that every logical heap
address occupy a page boundary. Rejecting everything below the rounded end
loses usable space in the last partial page. Removing the guard outright
would revive the earlier bug that let low requests unmap executable data.
The proposed correction is to obtain a safe, exact lower bound from the
main executable's ELF load segments while retaining page-rounded mapping
and resource accounting.

## Linux has a legacy compatibility policy as well

Linux's bounds are configuration-dependent. In the
[Linux 6.18 break handler](https://github.com/torvalds/linux/blob/v6.18/mm/mmap.c),
`CONFIG_COMPAT_BRK` permits an unrandomized process to use `mm->end_data` as
its floor; otherwise it uses `mm->start_brk`. The same code compares
page-aligned addresses for mapping changes but stores and returns the exact
requested break. Thus accepting libc5's first request involves the lower
bound as well as byte-precise successful returns. It should not be described
as a requirement that every modern Linux configuration accept a request
below its initial `brk(0)` result.

The proposed FreeBSD policy protects the entire ELF memory image, including
BSS. It is deliberately more conservative than Linux's legacy file-data
floor. Runtime results and the precise implemented policy will be recorded
below as the investigation proceeds.

## Baseline VM run: the missing regression is reproduced

A new `legacy` mode in the freestanding Linux/i386 helper makes its first
break syscall request `_end + 40`, without a preceding query. It checks
that the request lies in the last partial ELF page. Unlike Red Baron it
needs no proprietary files, interpreter, X server or Linux C library.

Before changing the kernel, BARONVM reported:

```text
legacy first request: 0x0041806c returned: 0x00419000; ELF end: 0x00418044
BARONVM: legacy regression failed: 2
linux_brk(0x082ee290) -> 0x082ef000
SIGSEGV
Completed: 28/28; passed: 28; failed: 0
```

The browser autostart was changed to clear `LD_PRELOAD` and record an
inherited `ktrace` in `/var/log/redbaron.ktrace`. Thus each boot now tests
the real allocator automatically and preserves its syscall evidence.
The general suite's byte-below-floor checks now use `_end - 1`, rather than
assuming the queried page-rounded initial break is the only possible floor.
Those checks continue to pass on the previous kernel. The new legacy mode
fails there, demonstrating that it detects the missing behavior.

## First corrected kernel: Red Baron runs without the preload

The change is in `sys/kern/imgact_elf.c:enforce_limits`, shared by the ELF32
and ELF64 loaders. For Linux executables it records the maximum of
`p_vaddr + load_bias + p_memsz` across nonempty `PT_LOAD` segments in
`vm_brk_min`. These are the segments the main executable actually loads;
shared-library and interpreter mappings do not replace this value. This
covers relocated PIE images and does not depend on a binary name, libc
version or symbol table. `_end` is useful for reading this particular
executable, but the kernel does not look up that symbol.

`vm_daddr` and `vm_dsize` retain their page-based values. `kern_break` still
initializes the current logical break to the mapped end on first use, so a
fresh `brk(0)` continues to report a page boundary. The important difference
is that the saved floor no longer has to equal that query result. A request
between the ELF end and the mapped end now changes only the logical break.
A request below the ELF end remains a query/refusal. Larger changes still
use the shared VM helper and its mapping, locking and resource-limit checks.
Native FreeBSD ELF processes do not receive the Linux floor initialization.

The existing exec reset and locked fork copy already handle both saved
fields; no additional field or kernel-interface change was needed beyond
the existing upstream patch's proposed version bump. The historical 15.1
patch series and BRKVM's image/configuration were left unchanged. The
consolidated main-branch kernel patch now includes the loader change.

The jail built BARONVM and its matching Linuxulator modules. Booting that
kernel in the same 512 MiB, two-CPU guest produced:

```text
legacy first request: 0x004180cc returned: 0x004180cc; ELF end: 0x004180a4
PASS legacy: exact request, query, write, floor, fork, shrink
```

Both the no-query and preceding-query variants passed. The test also checks
that a fork child inherits the exact break and floor, the parent's state
is unchanged, later growth can shrink back into the partial page, and
initialized data stays mapped. The original suite passed **28/28**, with
500,000 parent calls and 510,872 worker calls observing no return mismatch,
and 5,000 forks during 76,658 resize cycles producing no snapshot failure.

The actual browser's trace now begins:

```text
linux_brk(0x082ee290) -> 0x082ee290
linux_brk(0x082ef000) -> 0x082ef000
linux_brk(0x082f2000) -> 0x082f2000
```

It subsequently grows beyond `0x083b0000` and remains alive. Its process
environment contains no `LD_PRELOAD`; the wrapper explicitly clears it.
A password-authenticated VNC capture showed the Help Index. VNC mouse input
followed a link and captured a different help page. These observations
exercise the original allocator, rendering and further allocations; they
are stronger evidence than a live process alone. The application executable,
loader and libc5 library were not edited.

Helvetica fallback warnings remain in the browser log. They did not prevent
local rendering or navigation. External Internet browsing, TLS compatibility
and the browser's full feature set are not implied by this result.

## Validation of the review patches

Both consolidated upstream patches apply and reverse against the pinned
main revision `61c70dc16a79efcb9db732d37706cd311f555d9a`. The applied files
match the built sources byte for byte. `checkstyle9.pl` reports zero errors
and warnings for both patches. GENERIC and LINT also build with this loader
change, in addition to BARONVM and its matching Linuxulator modules.

The tests build with FreeBSD's normal warnings and `-Werror` in a separate
object directory. A temporary extended BARONVM image supplied the native
ATF/Kyua runtime without installing or loading anything on the host:

```text
brk_test:legacy_break       -> passed
brk_test:logical_break      -> passed
native_brk_test:native_break -> passed
3/3 passed (0 broken, 0 failed, 0 skipped)
```

The legacy ATF case invokes both helper modes. The logical-break case wraps
28 numbered checks; Kyua's three cases are not a replacement count for those
individual checks. The native case verifies that page-rounded FreeBSD
results, usable growth, `ENOMEM` and shrink behavior remain intact.

## Repeating the development loop

Use the latest consolidated main patches described in
[UPSTREAM.md](UPSTREAM.md); the four historical 15.1 patches do not include
the ELF-floor correction. In this jail the patched source and objects are
at the paths below. Shut the guest down with `reboot -p` before rebuilding
its disk, which resets guest filesystem changes.

```sh
SRC=/tmp/linux-brk-upstream/src OBJ=/tmp/linux-brk-upstream/obj \
    ./baron-test/build-kernel.sh
# Recompile brk-test/brk-suite using the README command after helper edits.
SRC=/tmp/linux-brk-upstream/src OBJ=/tmp/linux-brk-upstream/obj \
    ./baron-test/build-image.py
sudo ./baron-test/run-bhyve.sh
```

The guest automatically runs `/brk-suite legacy` and `/brk-suite query`,
starts Xvnc and launches Red Baron without a preload. Its serial console
provides a root shell. Useful guest commands are:

```sh
/brk-suite
/brk-suite legacy
/brk-suite query
ps eww -p $(cat /var/run/redbaron.pid)
kdump -t c -f /var/log/redbaron.ktrace
cat /var/log/redbaron.log
reboot -p
```

Connect VNC to `127.0.0.1:5901`; its password is the local generated file
`baron-test/vnc-password`. Do not commit that password, the supplied
application files or generated VM images and traces. The normal image is
`baron-test/baronvm.img`; the temporary Kyua image was `/tmp/baron-atf.img`.
The [BARONVM README](baron-test/README.md) covers prerequisites, tunneling
and build details. No host kernel installation or host module load belongs
in this loop.

## Final normal-image boot

After the Kyua run, the temporary test guest was shut down cleanly. The
normal BARONVM image was rebuilt and cold-booted. Both legacy modes passed
automatically; Red Baron started without `LD_PRELOAD`, and a fresh VNC
capture showed the Help Index again. BARONVM was left running on loopback
port 5901 for inspection. The original BRKVM image remains unchanged.
Generated evidence is in `baron-test/bhyve.log`, `bhyve-atf.log` and
`redbaron.png`; the running guest holds `/var/log/redbaron.ktrace`.

## What this result does and does not establish

The original startup crash is resolved in the tested main-branch guest
without changing the application, loader or libc5 and without replacing
its allocator. The missing last-page case is now separately reproducible
and covered in ATF. The preserved negative control shows why the original
28 passing checks were insufficient evidence for this application.

The Linux floor policy is not identical across kernel configurations.
This patch protects the entire original ELF memory image; it does not
implement Linux's more permissive legacy file-data floor, nor does it add
Linux-style heap randomization. The Alpine reference image was not rebuilt
for this follow-up; its earlier independent fork-stress failure remains
unresolved. Linux/amd64 runtime, other architectures, physical-memory
exhaustion and a full world build were not checked. Internet browsing, TLS and full application feature coverage were not tested.
