
# Running Red Baron on FreeBSD

### Diagnose a 1997 Linux browser: an allocator workaround and a kernel repair

Manitoba Unix Users Group · MUUG

An installation and debugging guide for the existing Bastille jail **`baron`**.

**Verified 2026-10-26:** local help and modern HTTPS content rendered in Red Baron.
The numbered steps use the allocator workaround. A second option repairs Linuxulator in a test kernel; BARONVM ran the original allocator on 2026-10-28.

<!--
Presenter notes:
The presentation follows the installation dependencies: identify the old
browser, prepare its libraries and desktop, diagnose the crash, replace the
allocator, verify local rendering, explain the alternative kernel repair,
and then add WRP in the same jail. The kernel option uses the separate
BARONVM guest; the existing baron jail continues using its allocator shim.
The core decoding and all five allocator function bodies remain inline.
This is Marp-compatible Markdown. Horizontal rules separate slides, and
these comments are speaker notes. Screenshots are in muug-baron-assets.
Commands use the supplied RPMs and shim source; the additional X11 data
RPM and WRP release are downloaded during installation.
The experiment is recorded in baron-invest.md. The Linux comparison comes
from blog-linux-redbaron.md, with qualifications in the comparison notes.
-->

---

# What runs in the jail

- Red Baron runs with its original **Linux/i386 libraries** on FreeBSD 15.1.
- A small replacement library supplies its memory-allocation functions.
- TigerVNC displays the browser on a **24-bit X11 desktop**.
- WRP and native Chromium let it display modern HTTPS pages.

**Verified:** the local Help Index, HTTPS rendering, form submission, and an image-map click. Sustained browsing has not been tested.

<!--
Presenter notes:
These are new observations from the live jail, 2026-10-26, rather than only
the earlier rh42 experiment. The fresh no-shim trace reproduces the rounded
brk return and SIGSEGV. New evidence is in diagnostics/baron-2026-10-26.
The current guide uses root-owned vnc-session on :1. The first
screenshot and saved diagnostic artifacts came from the earlier :2 demo.
-->

---

# Presentation sequence

1. Identify Red Baron and the Linux runtime it expects.
2. Prepare the Linux libraries and X11 desktop: **steps 1–8**.
3. Diagnose the failure using syscall traces, a core, and disassembly.
4. **Option 1:** replace the allocator and verify local help: **steps 9–12**.
5. **Option 2:** repair Linuxulator in a matching kernel and test it in BARONVM.
6. Install WRP and Chromium for modern websites: **steps 13–18**.

The diagnostic slides include the commands and byte offsets. The allocator slides show all five replacement functions; the VNC helper source is in the appendix.

---

# What was Red Baron?

- Red Hat's branded **Spyglass-derived commercial web browser**.
- Shipped as a proprietary binary, without source code, with boxed Red Hat Linux.
- First included in **Red Hat Linux 4.0, October 1996**.
- The version used here: **Red Baron 3.10**, from **Red Hat Linux 4.2, May 1997**.
- A Linux/i386 executable using X11, Motif, and **libc5**.

<small>Sources: [Fedora's Red Hat history](https://fedoraproject.org/wiki/History_of_Red_Hat_Linux), [Red Hat's 4.2 announcement](https://www.redhat.com/en/about/press-releases/press-redhat42).</small>

<!--
Presenter notes:
Distinguish browser version 3.10 from distribution version 4.2.
The Linux draft says "late 1997"; that is incorrect for Red Hat 4.2.
Fedora dates the release May 19; Red Hat's shipping announcement is May 29.
Use May 1997 rather than treating those as the same event.
-->

---

# What Red Baron 3.10 can render

| Feature | Capability of this build |
|---|---|
| HTML | Text, links, lists, tables, forms, frames, and image maps. |
| Presentation | Older HTML attributes and browser preferences control appearance. |
| JavaScript | No engine or support found in the inspected help and binary; treat as unsupported. |
| CSS | No stylesheet support found; treat as unsupported. |

“HTML 3.2-era” describes its capabilities; full standards compliance has not been established.

**WRP uses Chromium to render modern pages.** It does not add JavaScript or CSS execution to Red Baron itself.

<!--
Presenter notes:
Capabilities were inspected in the installed binary and bundled help on
2026-10-28. Help pages use tables and FRAMESET/FRAME; the binary includes
frame handlers. Forms and image-map clicks were exercised in the WRP demo.
No JavaScript engine or CSS implementation was identified in the help,
strings, or inspected symbol names. This is an inspection-based conclusion,
not the result of dedicated JavaScript/CSS test pages or a conformance suite.
Do not describe this browser as fully HTML 3.2 compliant on this evidence.
-->

---

# Images, audio, and external helpers

| Media | Evidence in the installed browser |
|---|---|
| Images | **GIF, JPEG, and XBM** are documented as built in. |
| PNG | No built-in support found. |
| AU/SND and AIFF audio | Format recognition and sound-player messages are present; playback is unverified. |
| WAV and MIDI | MIME-related strings are present; built-in playback is not established. |
| Other formats | Can be assigned to external helper applications. |

**Not tested:** audio playback, animated GIFs, and image-format edge cases. Recognizing a file type does not prove it can be played.

<!--
Presenter notes:
Primary source: /compat/linux/usr/lib/redbaron/help/filetype.htm explicitly
lists HTML, text, GIF, JPEG, and XBM as built-in types and explains Edit ->
Helpers for additional types. The binary contains GIF, JPEG, and XBM decoder
symbols, AU/AIFF recognizers, sound-player messages, and audio MIME strings.
These establish documented image support and evidence of audio-related code,
not successful audio output on FreeBSD or support for every encoding within
a container. No PNG support was identified. WAV/MIDI strings alone do not
establish decoders, configured helpers, or working playback. WRP's GIF mode
has been tested; audio transmission through WRP has not been established.
-->

---

# Red Baron’s relationship to Mosaic and Internet Explorer

| When | What was happening |
|---|---|
| 1993 | NCSA Mosaic made graphical web browsing popular. |
| 1994 | Spyglass built its commercial Mosaic implementation; Netscape emerged. |
| 1995 | Microsoft's Internet Explorer grew from licensed Spyglass technology. |
| 1996–97 | Red Hat shipped its own Spyglass-derived browser: Red Baron. |

Red Baron and early Internet Explorer both used browser technology supplied by Spyglass.

<small>Sources: [NCSA history](https://www.ncsa.illinois.edu/about/history/), [Spyglass project lead Eric Sink](https://ericsink.com/Browser_Wars.html), [Fedora history](https://fedoraproject.org/wiki/History_of_Red_Hat_Linux).</small>

<!--
Presenter notes:
Who created it? Spyglass supplied the underlying browser technology;
Red Hat branded and distributed Red Baron. Eric Sink led the Spyglass
browser project under founder and development head Tim Krauskopf.
Do not call Sink the sole author of Red Baron.
Sink says Spyglass licensed NCSA technology and trademarks but wrote its
implementations from scratch. This is a commercial and conceptual lineage,
not a claim that all these browsers used the same NCSA source tree.
Netscape was another branch, not a Red Baron descendant.
-->

---

# Why Red Hat stopped shipping Red Baron

- Fedora's history identifies **4.2 as the last release to ship Red Baron**.
- Fedora describes the browser as **“very buggy.”**
- By June 1998, Red Hat 5.1 included the proprietary Netscape browser.

The historical account cites reliability problems. It does not identify this allocator failure as the reason Red Baron was discontinued.

<small>Source: [Fedora's Red Hat history](https://fedoraproject.org/wiki/History_of_Red_Hat_Linux).</small>

<!--
Presenter notes:
The Netscape/Internet Explorer competition is context, not proof of a
specific Red Hat licensing or cancellation decision. Avoid inventing one.
The glibc transition also belongs to this era, but the cited history does
not establish it as the reason Red Baron was dropped.
-->

---

# Linux is the kernel; a distribution is the system

```text
Linux distribution
  applications + desktop + services + command-line tools
  C library + runtime loader
  Linux kernel
```

- Many distributions combine Linux with **GNU tools and GNU libc (glibc)**.
- Other combinations exist: **musl libc (MIT)**, BusyBox, different init systems.
- “Runs on Linux” does not identify the libraries a binary needs.

<small>References: [GNU's system/kernel distinction](https://www.gnu.org/gnu/linux-and-gnu.html), [musl libc](https://musl.libc.org/).</small>

<!--
Presenter notes:
This is a technical distinction, not a naming debate. People commonly use
"Linux" as shorthand for the whole distribution. The kernel project itself
does not supply a complete GNU userspace, nor does Linux require GNU tools.
For a familiar example, Alpine uses musl rather than glibc.
-->

---

# The C library is part of a program’s binary interface

| Layer | What it supplies |
|---|---|
| C library | `malloc`, `strcpy`, `printf`; many syscall wrappers. |
| Kernel | Memory mappings, processes, files, networking, protection. |
| Base / distribution | Libraries, loader, tools, services, administration. |

- FreeBSD develops its kernel, libc, loader, and core tools as one base system.
- Linux distributions assemble those pieces from multiple projects.
- **libc5, glibc, musl, and FreeBSD libc are not interchangeable binaries.**

<small>Context: [FreeBSD: what is FreeBSD?](https://docs.freebsd.org/en/books/handbook/introduction/#nutshell).</small>

<!--
Presenter notes:
Traditional Unix systems commonly present a kernel and matching userspace
as one OS. FreeBSD follows that model; packages add software above its base.
An ordinary hosted Unix C program needs a compatible libc, but freestanding
code can issue raw syscalls without one—as our shim does.
Some libc functions stay in userspace; others wrap kernel calls. Similar
C APIs do not guarantee compatible ABI, symbol versions, or loader.
This comparison does not claim every Unix or Linux distribution is organized
identically. libc5 is the older Linux C library generation used by Red Baron,
not an old version of FreeBSD libc or a drop-in glibc 2 library.
-->

---

# How Linuxulator runs Linux binaries on FreeBSD

```text
Red Baron + Linux libraries       FreeBSD shell + FreeBSD libraries
             |                                  |
       Linux system calls                FreeBSD system calls
             |                                  |
        Linuxulator ----------------> FreeBSD kernel
```

- The CPU executes the i386 instructions directly on this amd64 host.
- Linuxulator implements the **Linux application binary interface (ABI)** in FreeBSD.
- The old Linux libraries remain part of the process.

<small>Source: [FreeBSD Handbook: Linux Binary Compatibility](https://docs.freebsd.org/en/books/handbook/linuxemu/).</small>

<!--
Presenter notes:
ABI means application binary interface: the agreement about registers,
arguments, executable layout, system calls, and related behavior.
Linuxulator is not a Linux kernel inside the jail or a CPU emulator.
The jail supplies isolation; Linuxulator supplies the Linux ABI.
-->

---

# A system call crosses into the kernel

```text
malloc()                       C library function in userspace
   |
Linux brk request              EAX = 45, argument in EBX
   |
int $0x80                      enter kernel via Linux/i386 ABI
   |
Linuxulator handler            interpret Linux arguments and semantics
   |
FreeBSD VM operations          result translated back to Linux ABI
```

A compatible syscall implementation must match the arguments, return values, and error behavior expected by Linux programs.

<small>Reference: [Linux i386 syscall table](https://github.com/torvalds/linux/blob/master/arch/x86/entry/syscalls/syscall_32.tbl).</small>

<!--
Presenter notes:
malloc is not a syscall. It can manage existing memory without entering
the kernel; this diagram illustrates a heap-growth path. EAX holds the
syscall number. Native FreeBSD calls have their own ABI and numbers.
The shim later uses Linux calls 90 (old mmap) and 91 (munmap).
Linuxulator also handles structure layouts, flags, errors, and signals.
Its handlers can work with kernel facilities directly; they need not
invoke a separate native syscall to carry out each Linux operation.
-->

---

# ELF identifies the loader and required libraries

**ELF** is the executable and shared-library file format used here.

```text
Executable
  PT_INTERP   -> which runtime loader to start
  DT_NEEDED   -> which shared libraries are required
  symbols + relocations -> which names need addresses filled in
```

The kernel starts the named loader. The loader maps libraries and connects imported names such as `malloc` to implementations.

<small>Reference: [FreeBSD runtime-linker manual source](https://github.com/freebsd/freebsd-src/blob/main/libexec/rtld-elf/rtld.1).</small>

<!--
Presenter notes:
PT_INTERP is an ELF program header; DT_NEEDED entries live in dynamic
metadata. These are different records, grouped here by purpose.
Some function binding can wait until the first call. We need only the
basic model to understand replacing an imported function.
-->

---

# Build-time linking and runtime library loading

| Name | Job |
|---|---|
| `ld` | Build-time linker: combines objects and records dependencies. |
| FreeBSD `rtld` | Native runtime linker: `/libexec/ld-elf.so.1`. |
| Red Baron's loader | Linux `/lib/ld-linux.so.1`, named in its ELF interpreter. |

Red Baron’s ELF interpreter selects Linux’s loader, which resolves its library dependencies and `LD_PRELOAD` settings.

Installing FreeBSD's 32-bit runtime does not supply a Linux libc5 runtime.

<small>Reference: [FreeBSD `rtld` manual source](https://github.com/freebsd/freebsd-src/blob/main/libexec/rtld-elf/rtld.1).</small>

<!--
Presenter notes:
"Runtime linker", "dynamic linker", and "dynamic loader" overlap here.
The native FreeBSD 32-bit loader on amd64 is ld-elf32.so.1; it is not the
loader for this Linux executable. Pointer width alone does not match an ABI.
-->

---

# The jail, paths, and display used in the commands

| Piece | Verified setup |
|---|---|
| Jail | Bastille VNET jail **`baron`**, `192.168.3.31` |
| Userspace | FreeBSD 15.1-RELEASE-p4, amd64 |
| Linux runtime | Five RPMs under **`/compat/linux`**, plus X11 data |
| Source/cache | `/root/redbaron-install` inside the jail |
| Desktop/browser account | `root`, home `/root`, as used by the installed helper |
| Desktop | `vnc-session`: Xvnc `:1`, 800×600×24, Fluxbox |
| Viewer access | SSH tunnel to **127.0.0.1:5901** in the jail |
| Modern rendering | Native WRP + Chromium, `127.0.0.1:8080`, account `wrp` |

<!--
Presenter notes:
The commands target the existing Bastille jail. SSH as root with ssh baron;
TigerVNC, Fluxbox, and vnc-session were installed before this walkthrough.
The historical investigation used rh42, /compat, and display :1. Do not mix
those paths with this recipe. Here /compat/linux is a real private directory,
so no ln -s . /compat/linux step is required. VNET supplies its own loopback.
If Linux executables fail before loading, Linuxulator must be enabled on
the FreeBSD host, not loaded from inside the jail: sysrc linux_enable=YES;
service linux start. The live host already provides i386 Linux compatibility.
-->

---

# 1. Connect to the existing jail

**On the workstation:**

```sh
ssh baron
```

**In `baron`, as root:**

```sh
pkg install -y tigervnc-server fluxbox xauth xset xsetroot \
  xwininfo curl font-misc-misc font-adobe-75dpi \
  font-adobe-100dpi font-bh-75dpi
```

The VNC/desktop packages are already installed here. Adobe bitmap fonts supply Helvetica; the Bigelow Holmes fonts supply Lucida Typewriter, also requested during the WRP demonstration.

<!--
Presenter notes:
Commands in later numbered steps run in the jail's root /bin/sh unless the
slide explicitly says workstation. These native FreeBSD font packages work
with the native Xvnc server. Linux client libraries remain the historical ones.
xwininfo is used by the display and window checks; curl is used to test
WRP. xwd was used to capture the saved screenshots and is not required to
run the browser. The helper script is included in the appendix.
-->

---

# 2. Copy the RPMs and allocator source

**On the workstation, from this project directory:**

```sh
ssh baron 'install -d /root/redbaron-install /compat/linux'
scp -r redbaron-freebsd-jail/media \
  baron:/root/redbaron-install/
scp redbaron-freebsd-jail/malloc_shim.c \
  baron:/root/redbaron-install/
```

Five RPMs supply the browser and its Linux libraries. A sixth RPM will supply missing X11 data.

<!--
Presenter notes:
SCP transfers existing local files; no Red Hat shell or Linux package manager
is required. The source is the full implementation discussed later in the
slides. The Linux runtime remains inside this jail, separate from the host.
-->

---

# 3. Extract the Linux runtime

**In `baron`, as root:**

```sh
cd /root/redbaron-install
for rpm in redbaron-3.1-1.i386.rpm \
  libc-5.3.12-18.i386.rpm ld.so-1.7.14-4.i386.rpm \
  XFree86-libs-3.2-9.i386.rpm xpm-3.4i-1.i386.rpm; do
    bsdtar -xf "media/$rpm" -C /compat/linux
done
brandelf -t Linux /compat/linux/usr/lib/redbaron/redbaron_3.10
```

`bsdtar` extracts RPM payloads. `brandelf` selects the Linux ABI; it does not translate machine code.

<!--
Presenter notes:
This is payload extraction, not an RPM transaction: no package scriptlets or
dependency resolution run. Name the five files explicitly so the later XFree86
base RPM is not accidentally extracted wholesale. This target directory was
initially empty in the live jail. Do not unpack over a different Linux runtime.
-->

---

# 4. Restore library names and the loader cache

```sh
ln -sf libc.so.5.3.12 /compat/linux/lib/libc.so.5
ln -sf libm.so.5.0.6 /compat/linux/lib/libm.so.5
ln -sf libdl.so.1.7.14 /compat/linux/lib/libdl.so.1
cat > /compat/linux/etc/ld.so.conf <<'EOF'
/lib
/usr/lib
/usr/X11R6/lib
EOF
/compat/linux/sbin/ldconfig
```

Use the **Linux** `ldconfig` to create links matching each library’s embedded runtime name (**SONAME**) and rebuild the old loader cache. This includes X11 `.so.6` links and **`libXpm.so.4`**.

<!--
Presenter notes:
The old Linux ldconfig is statically linked. An isolated fresh extraction
was checked with ldconfig -n: it recreated the seven matching X11 .so.6 links
and libXpm.so.4, without creating libXpm.so.6. The guide therefore lets that
utility restore the X11 links instead of duplicating a manual alias loop.
Do not create libXpm.so.6: that was a mistake in the earlier provisioner loop.
The Xpm file is libXpm.so.4.9 and its embedded SONAME is libXpm.so.4.
-->

---

# 5. Install the original X11 data files

```sh
cd /root/redbaron-install
ARCHIVE=https://legacy.redhat.com/pub/redhat/linux/4.2/en/os/i386
fetch -o media/XFree86-3.2-9.i386.rpm \
  "$ARCHIVE/RedHat/RPMS/XFree86-3.2-9.i386.rpm"
bsdtar -xf media/XFree86-3.2-9.i386.rpm -C /compat/linux \
  usr/X11R6/lib/X11
```

This is a sixth RPM: **`XFree86`**, distinct from **`XFree86-libs`** extracted in step 3. It supplies **`XKeysymDB`**, locale tables, and other X11 data needed for startup.

<!--
Presenter notes:
The legacy Red Hat download succeeded; the ibiblio endpoint returned an error
when tested. Extract only the X11 data subtree, not the old X server binaries.
A hand-generated OSF keysym table removed warnings but did not cure the crash;
adding the original X11 data allowed the Help Index to render. We have not
isolated each missing data file's contribution, so do not name a single one
as independently proven to be the sole cause. Its recorded RPM hash is in
diagnostics/baron-2026-10-26/README.md.
-->

---

# Check the Linux dependencies

```sh
LD_TRACE_LOADED_OBJECTS=1 \
LD_LIBRARY_PATH=/lib:/usr/lib:/usr/X11R6/lib \
  /compat/linux/usr/lib/redbaron/redbaron_3.10
```

Selected output from `baron`:

```text
libXt.so.6  => /usr/X11R6/lib/libXt.so.6
libX11.so.6 => /usr/X11R6/lib/libX11.so.6
libc.so.5   => /lib/libc.so.5
```

All seven dependencies resolved. The next steps prepare the X11 display before reproducing the remaining startup failure.

<!--
Presenter notes:
The other dependencies were libm, libdl, libSM, and libICE. This command
sets loader variables only for the Linux executable. The paths printed are
Linux-visible paths under the jail's compatibility root, not native FreeBSD
libraries. This was checked before starting the browser.
-->

---

# 6. Start the desktop with `vnc-session`

**In `baron`, as root:**

```sh
/usr/local/bin/vnc-session start
/usr/local/bin/vnc-session status
```

The existing helper starts **Xvnc `:1`, 800×600, depth 24, port 5901**, and Fluxbox. It also sets the bitmap font path.

`start` refreshes fonts when the display already exists. To change an existing server's depth, use `vnc-session restart`; this closes its desktop applications.

[Full helper source in the appendix](#appendix-vnc-session).

<!--
Presenter notes:
Use the installed helper rather than starting another Xvnc/Fluxbox pair.
Its defaults were read directly from baron:/usr/local/bin/vnc-session.
It creates VNC credentials only when the password file is missing. Keep
/root/.vnc/passwd and the plaintext password file out of presentation output.
This uses the existing root-owned desktop. The initial unprivileged :2 demo
has been replaced in this walkthrough; its screenshot remains historical evidence.
-->

---

# 7. Verify the display depth and font path

```sh
DISPLAY=:1 xwininfo -root | grep -E 'Depth:|Visual Class:'
DISPLAY=:1 xset q
```

Expect **Depth: 24**, **TrueColor**, and a font path containing:

```text
/usr/local/share/fonts/misc
/usr/local/share/fonts/75dpi
/usr/local/share/fonts/100dpi
built-ins
```

**16-bit depth** caused the unsupported-visual error. Missing Adobe fonts produced Helvetica `FontStruct` warnings followed by a segmentation fault.

<!--
Presenter notes:
Installing font-adobe-75dpi and font-adobe-100dpi is only half the setup;
the running X server must include their directories in its font path.
vnc-session start refreshes that path, so a font-only correction needs no
server restart. It cannot change the depth of an already running server.
The helper suppresses errors from its font refresh; inspect xset q rather
than treating its status message as proof that every font loaded.
-->

---

# 8. Connect the VNC viewer through SSH

**On the workstation:**

```sh
ssh -N -L 15901:127.0.0.1:5901 baron
```

In another workstation terminal, for TigerVNC Viewer:

```sh
vncviewer 127.0.0.1::15901
```

Use the existing VNC password. The helper currently uses **`-localhost no`**, so it also listens on the jail's network interfaces; the SSH tunnel does not disable that listener.

<!--
Presenter notes:
The double colon in the TigerVNC command specifies an explicit TCP port.
Viewer clients on other platforms can enter localhost and port 15901 in
their GUI. VNC authentication and X11 client authentication are separate;
this helper specifies VncAuth but does not configure an Xauthority cookie.
Do not describe this session as the earlier loopback-only, cookie-based :2 setup.
-->

---

# Enable core dumps before reproducing the crash

**On the FreeBSD host, as root—not inside the jail:**

```sh
sysctl kern.coredump=1
```

**Inside `baron`, in `/bin/sh`:**

```sh
ulimit -c unlimited
```

Reproduce the crash without the allocator preload. With `kern.corefile=%N.core`, the dump is named **`redbaron_3.10.core`** in the crashing process’s working directory.

After capture, restore the previous **host** setting: `sysctl kern.coredump=0` if core dumping was previously disabled. This setting affects other processes on the host too.

---

# Capture the crash without the allocator replacement

**Inside `baron`, as root, in `/bin/sh`:**

```sh
umask 077
CAPTURE_DIR=$(mktemp -d /root/redbaron-install/crash.XXXXXX)
cd "$CAPTURE_DIR"
unset LD_PRELOAD LD_32_PRELOAD
ktrace -di -f redbaron.ktrace env \
  DISPLAY=:1 LANG=C LC_ALL=C REDBARON=/usr/lib/redbaron \
  XKEYSYMDB=/usr/X11R6/lib/X11/XKeysymDB \
  LD_LIBRARY_PATH=/lib:/usr/lib:/usr/X11R6/lib \
  /compat/linux/usr/lib/redbaron/redbaron_3.10 \
  -url file:/usr/lib/redbaron/help/index.htm
kdump -f redbaron.ktrace > redbaron.kdump.txt
ls -lh "$CAPTURE_DIR/redbaron_3.10.core"
```

The segmentation fault is expected. Each run uses a new directory to preserve previous captures. Restore the host’s previous core-dump setting after capture.

<!--
Presenter notes:
The Linux runtime and display are ready before this command runs. Invoke
the executable directly: /usr/local/bin/redbaron would enable the allocator
replacement and prevent this baseline failure. Continue to kdump after the
expected crash; do not run this sequence under shell errexit (set -e).
The decoding examples below replay /root/redbaron_3.10.core captured on
2026-10-26. A new capture can have different addresses and file offsets.
-->

---

# The syscall trace ends with a null-address fault

Fresh selected trace lines, without the allocator preload:

```text
CALL  linux_brk(0x82ee290)
RET   linux_brk 137293824/0x82ef000
PSIG  SIGSEGV SIG_DFL code=SEGV_MAPERR
```

The returned heap-end address differs from the request, and the process then faults at address zero. A syscall trace does not identify the C function that accessed that address.

[Saved excerpt](diagnostics/baron-2026-10-26/baseline-brk.txt)

<!--
Presenter notes:
This is selected fresh output from the live jail, with the PID/process
columns omitted on the slide. The saved excerpt retains them. The run used
the correct -url option and the same X11 data as the working configuration.
A native su parent can report status 0 even after its Linux child crashes;
inspect the Linux process and trace rather than only the SSH exit status.
Raw traces remain private in /root/redbaron-install because they can contain
authentication data. The following core slides show the instruction and
arguments that the syscall trace cannot establish.
-->

---

# The core identifies a string copy to address zero

```text
Faulting instruction pointer:  0x2840643f
Inside libc5:                  strcpy
Destination:                   0x00000000
Source:                        "Spyglass"
```

The browser tried the equivalent of:

```c
strcpy(NULL, "Spyglass");
```

`strcpy` copies text into destination memory; here it tries to copy `"Spyglass"` to `NULL`, which points to no valid destination, causing the crash.

The following slides recover the instruction and arguments from the core, then trace the null destination back to `malloc`.

<!--
Presenter notes:
The core /root/redbaron_3.10.core was captured in baron and independently
decoded on 2026-10-26 and gives the same EIP and libc base as the earlier
investigation. The full core stays in the jail. Addresses and file offsets
are specific to this capture; inspect the headers again for another core.
-->

---

# Identify the core format before decoding registers

The recorded example uses the core saved in `/root`. For a new capture, set `CORE` to its file in `$CAPTURE_DIR` and recalculate the offsets from its headers.

**Inside `baron`, in `/bin/sh`:**

```sh
CORE=/root/redbaron_3.10.core
LIBC=/compat/linux/lib/libc.so.5.3.12
file "$CORE"
readelf -h "$CORE"
readelf -n "$CORE"
```

The file is an **ELF32, little-endian, Intel 80386 core**. A core stores process memory and metadata called notes. Selected output:

```text
Notes at file offset 0x334, length 0xd4c:
Owner   Data size   Description
CORE    0x90        NT_PRSTATUS
```

`NT_PRSTATUS` contains the saved registers. Use the **Linux/i386** layout written by Linuxulator.

<!--
Presenter notes:
Commands on the following slides reuse CORE and LIBC in the same shell.
The core is 5,128,192 bytes. Its SHA256 is
a1428330ea7c21a3bb9da5452855892c2194a0565fee63736df204610d31f284.
The original libc SHA256 is
2a2341f5d1e6c31f340efb42557babdb1229dcb978ef2ccf4088004e84bab555.
The displayed readelf excerpt abbreviates columns and wording for the slide.
-->

---

# Locate the saved registers in the core note

Read the note header and owner:

```sh
od -An -tx1 -j $((0x334)) -N 20 "$CORE"
```

```text
05 00 00 00 90 00 00 00 01 00 00 00 43 4f 52 45
00 00 00 00
```

The header is 12 bytes: owner length **5**, descriptor length **0x90**, type **1**. The owner is `CORE` plus NUL, padded to eight bytes.

```text
Descriptor begins: 0x334 + 12 + 8 = 0x348
Registers begin:   descriptor + 72 bytes = 0x390
```

The preceding 72 bytes hold signal information, masks, process IDs, and times.

<!--
Presenter notes:
The layout comes from linux_elf_prstatus in FreeBSD's sys/compat/linux/linux_elf.c
and linux_pt_regset32 in sys/amd64/linux32/linux.h, releng/15.1.
The native FreeBSD register layout has different offsets and is inappropriate.
The note owner is padded to a four-byte boundary: round_up(5,4) is 8.
-->

---

# Read EIP, the instruction pointer

Each register is four bytes. Linux/i386 stores them in this order:

```text
ebx ecx edx esi edi ebp eax ds es fs gs orig_eax
 eip cs eflags esp ss
```

EIP is register **12**, counting from zero:

```text
File offset = 0x348 + 72 + 12*4 = 0x3c0
```

```sh
od -An -tx1 -j $((0x3c0)) -N 4 "$CORE"
od -An -tx4 -j $((0x3c0)) -N 4 "$CORE"
```

```text
3f 64 40 28
2840643f
```

Little-endian decoding gives **EIP = 0x2840643f**.

<!--
Presenter notes:
-tx1 shows bytes without assuming a word's byte order. -tx4 displays native
32-bit words, which works here because the jail is on little-endian amd64.
EIP is 120 bytes (0x78) into the descriptor, not into the entire note.
-->

---

# Find the memory segment containing the fault

```sh
readelf -l "$CORE"
readelf -l "$LIBC"
```

Selected LOAD fields, with unrelated columns omitted:

```text
             File offset  Virtual addr  File size  Flags
Core LOAD:   0x3da000     0x28399000    0x93000    R E
libc LOAD:   0x000000     0x00000000    0x92472    R E
```

EIP lies in that core segment:

```text
0x28399000 <= 0x2840643f < 0x2842c000
```

**A LOAD row has no library name.** This core has no `NT_FILE` pathname note; compare its bytes with the library next.

<!--
Presenter notes:
A core LOAD translates a virtual address into an offset in the dump file.
The matching libc executable segment begins at ELF virtual address zero.
Core segments include page padding, explaining the slightly different sizes.
-->

---

# Match the core’s memory segment to libc5

Compare all **0x92472** file-backed bytes of libc5's first LOAD:

```sh
dd if="$CORE" bs=1 skip=$((0x3da000)) \
  count=$((0x92472)) 2>/dev/null | sha256
dd if="$LIBC" bs=1 count=$((0x92472)) \
  2>/dev/null | sha256
```

Both produce the same SHA256:

```text
91e0f48bab58aa124b6f5a471fc66b47d0fcd53296878f53d3b3b082e8c9e487
```

The segment matches libc5. Its ELF virtual address is zero, so its **load bias**, the address added to its ELF addresses, is **0x28399000**.

```text
Fault inside libc = 0x2840643f - 0x28399000 = 0x6d43f
```

<!--
Presenter notes:
This verifies the whole first file-backed LOAD, not merely an ELF magic number.
The core's larger 0x93000 size includes page padding. In this particular
library, the first LOAD has both file offset and virtual address zero.
Subtracting a load bias generally gives an ELF virtual address; it is not
always the same as a library file offset.
-->

---

# The faulting instruction writes a byte in `strcpy`

```sh
readelf -s "$LIBC" | grep ' strcpy$'
objdump -d --start-address=0x6d42c \
  --stop-address=0x6d44a "$LIBC"
```

The symbol starts at **0x6d42c**, so our fault is **`strcpy+0x13`**. Selected disassembly:

```text
6d42c: pushl %esi
6d42d: movl  0x8(%esp), %esi    # destination
6d431: movl  0xc(%esp), %edx    # source
...
6d43c: movb  (%edx), %al
6d43e: incl  %edx
6d43f: movb  %al, (%ecx,%edx)   # faulting store
```

The instruction attempts a one-byte store. The next step uses the saved registers to calculate its destination address.

<!--
Presenter notes:
Comments are annotations; the instructions were read from the original libc.
The omitted instructions compute ECX as destination minus source minus one.
Incrementing EDX before the store makes ECX+EDX the current destination.
-->

---

# The saved registers identify address zero

Read ECX, EDX, ESI, and ESP from the same register block:

```sh
od -An -tx4 -j $((0x348+72+4)) -N 12 "$CORE"
od -An -tx4 -j $((0x348+72+15*4)) -N 4 "$CORE"
```

```text
ECX        EDX        ESI
f7d94222   0826bdde   00000000

ESP
ffffb148
```

At the faulting store:

```text
(ECX + EDX) & 0xffffffff = 0x00000000
ESI, the original destination, is also zero.
```

ESP is the stack pointer. It locates the return address and arguments saved by the function call.

<!--
Presenter notes:
ECX is register 1, EDX register 2, ESI register 3, and ESP register 15.
The addition wraps at 32 bits. EDX is already one byte beyond the original
source because strcpy incremented it after reading the first character.
-->

---

# Recover the destination and source arguments

`readelf -l` places the stack LOAD at virtual **0xfffdc000**, file offset **0x4c1000**. Translate saved ESP to a core offset:

```text
file offset = LOAD offset + (address - LOAD virtual address)
```

```sh
od -An -tx4 -j $((0x4c1000+0xffffb148-0xfffdc000)) \
  -N 16 "$CORE"
```

```text
282affb0 0807037e 00000000 0826bddd
```

| Stack position | Meaning | Value |
|---|---|---|
| ESP | Saved caller ESI | `0x282affb0` |
| ESP+4 | Return address | `0x0807037e` |
| ESP+8 | Destination | **`0x00000000`** |
| ESP+12 | Source | **`0x0826bddd`** |

<!--
Presenter notes:
strcpy's first instruction pushed ESI, so its arguments are now at ESP+8
and ESP+12, rather than the entry-time ESP+4 and ESP+8. The saved ESI on
the stack belongs to the caller; the live ESI register holds the destination.
-->

---

# Recover the source string from process memory

The source address lies in the executable LOAD at virtual **0x08000000**, core file offset **0x2000**:

```sh
od -An -tc -j $((0x2000+0x0826bddd-0x08000000)) \
  -N 9 "$CORE"
```

```text
S p y g l a s s \0
```

The stack gives a **null destination** and a source pointer. The bytes at that source give **`"Spyglass"`**, including its NUL terminator.

```c
strcpy(NULL, "Spyglass");
```

The null destination and source bytes establish this call directly from the captured process state.

---

# Trace the null destination back to `malloc`

```sh
objdump -d --start-address=0x8070310 \
  --stop-address=0x8070381 \
  /compat/linux/usr/lib/redbaron/redbaron_3.10
objdump -d --start-address=0x8141580 \
  --stop-address=0x81415a4 \
  /compat/linux/usr/lib/redbaron/redbaron_3.10
```

The instructions show:

```text
main:      0x8070360 calls 0x8141580 (SM_Malloc)
           0x8070368 saves returned EAX at 0x82ea26c
           0x8070373 loads it; 0x8070378 pushes it
           0x8070379 calls strcpy@plt
           0x807037e is the return address in our core

SM_Malloc: 0x8141587 calls malloc@plt
           returns that pointer unchanged
```

<!--
Presenter notes:
objdump may label SM_Malloc's address gcc2_compiled.; nm confirms SM_Malloc
at 0x8141580. The destination is connected to imported malloc's result.
This does not establish that it was the first malloc call. The following
slides add the syscall return and libc5 disassembly; the complete failing
allocation has not been single-stepped.
-->

---

# How a failed allocation caused the crash

```text
main
  -> SM_Malloc
       -> imported malloc in libc5
       <- NULL
  <- NULL
  -> strcpy(NULL, "Spyglass")
  -> SIGSEGV
```

- The executable retained useful function names.
- `SM_Malloc` used the **PLT**, an imported-function trampoline.
- `main` used the returned pointer without checking it.

<!--
Presenter notes:
This diagram summarizes the core and disassembly evidence from the original
binary. The saved return address matches the instruction after main's
strcpy call. On i386 a returned pointer comes back in EAX; stack arguments
then pass it to strcpy. PLT means Procedure Linkage Table: the loader connects this call
to an external implementation. The null destination is established here;
the next slides explain the incompatible brk result and libc5's error check.
-->

---

# `brk` returned a different address

```text
Requested logical heap end:  0x082ee290
Returned address:            0x082ef000 (next 4 KiB boundary)
```

- The raw Linux `brk` syscall returns the new logical break on success.
- Page-based backing does not require a page-rounded logical result.
- Linuxulator returned a rounded address: **a Linux ABI compatibility bug**.
- An independent probe reproduces the mismatch without libc5 or Red Baron.

The next slide shows why libc5 interprets this result as failed heap growth.

<small>ABI reference: [Linux `brk(2)`, C library/kernel differences](https://man7.org/linux/man-pages/man2/brk.2.html).</small>

<!--
Presenter notes:
The raw syscall result differs from the 0/-1 interface exposed by the
modern libc brk wrapper. Avoid conflating them. The independent Linux/i386
probe queries brk(0), requests one more byte, and observes a rounded return.
LINUXULATOR_BRK.md contains its complete source and recorded results.
Allowing page-zero mapping did not fix the crash; the setting was restored.
-->

---

# Why libc5 reports an allocation failure

The installed libc5's `__sbrk` requests heap space using raw Linux `brk`:

```text
18305: int  $0x80           # issue brk, syscall 45
...
18318: cmpl %ecx, %edi      # requested address versus returned address
1831a: jne  0x18328         # mismatch: take the error path
...
1832d: movl $0xc, (%eax)    # errno = ENOMEM
18333: movl $0xffffffff, %eax # return (void *)-1
```

- The heap-growth helpers convert that failure to `NULL` for the allocator.
- `malloc` returns `NULL`; Red Baron passes it to `strcpy` without checking.
- **Two defects:** Linuxulator's incompatible return and Red Baron's unchecked allocation failure.

<small>Disassembly commands, helper details, and the independent probe: [Linuxulator `brk` investigation](LINUXULATOR_BRK.md).</small>

<!--
Presenter notes:
This comparison is now verified in libc.so.5.3.12, rather than inferred.
__default_morecore and __default_morecore_init call __sbrk and convert -1
to NULL. The core and executable disassembly establish the separate
malloc -> SM_Malloc -> unchecked strcpy path. The full failing allocation
has not been single-stepped. Later BARONVM results show the original
allocator working with the kernel repair described after option 1.
-->

---

# Two ways to repair the startup failure

| Option | What changes | Allocation path |
|---|---|---|
| **1. Preload workaround** | Replace five user-level allocation functions. | Shim → `mmap`/`munmap` → Linuxulator. |
| **2. Kernel repair** | Correct Linuxulator's logical-break state and ELF lower bound. | Original libc5 → `brk` → corrected Linuxulator. |

- Option 1 works in the existing `baron` jail with its current host kernel.
- Option 2 ran without the allocator shim in a separate **BARONVM** guest.
- Both retain the original browser and its Linux libraries.

We finish option 1's installation first, then examine the kernel repair.

<!--
Presenter notes:
The local patch is ../linux-brk/upstream/0001-linuxulator-logical-brk.patch.
It targets a pinned FreeBSD main revision; it is not an accepted release
update or a patch to install inside the baron jail. A jail shares its host
kernel. The separate VM lets us test a new kernel without replacing that host.
-->

---

# Option 1: replace library functions with `LD_PRELOAD`

- `LD_PRELOAD` asks the runtime loader to load a chosen library before ordinary dependencies.
- That library can supply replacement implementations of imported functions.
- Red Baron’s executable and other libraries remain in use.
- **SunOS 4.0, 1988:** `LD_PRELOAD` was an undocumented feature, present in its binaries and source but absent from its documentation.

We use it to load our allocation functions before libc5’s implementations.

<small>Context: [SunOS 4.0 change notes, shared libraries, p. 8](https://vtda.org/docs/computing/Sun/software/800-1731-10_SunOS4.0ChangeNotes9May88.pdf), [OpenBSD loader history](https://man.openbsd.org/ld.so).</small>

<!--
Presenter notes:
The undocumented SunOS 4.0 LD_PRELOAD detail is supplied by the presenter;
the 4.0 binaries/source were not independently inspected for this deck.
The linked change notes establish the new shared-library facility; OpenBSD
identifies SunOS 4.0 as the origin of its shared-library model. Neither is
being offered as documentation of the undocumented variable.
SunOS 4 used a.out. Its runtime-linking mechanism is the historical
background; Red Baron uses the later Linux ELF loader implementation.
-->

---

# How the loader selects our replacement `malloc`

```text
Ordinary launch:    imported malloc -> libc5 malloc
With our preload:  imported malloc -> shim malloc
```

| Variable tested | Red Baron's Linux loader |
|---|---|
| `LD_PRELOAD` | Loaded the requested library. |
| `LD_32_PRELOAD` | Did not trigger preloading. |
| `LIB_32_PRELOAD` | Did not trigger preloading. |

This process uses the Linux loader, so the working variable is **`LD_PRELOAD`**.

<!--
Presenter notes:
LD_32_PRELOAD belongs to FreeBSD's native 32-bit runtime linker. The Linux
loader recognizes LD_PRELOAD even though FreeBSD services its syscalls.
The diagram describes this executable's imported symbols. Interposition
does not replace arbitrary inlined, hidden, or statically linked code.
-->

---

# The shim bypasses `brk`, not Linuxulator

```text
Original allocation path:
Red Baron -> libc5 malloc -> brk -> Linuxulator -> FreeBSD VM
                            <- rounded result
          <- NULL -> unchecked strcpy -> SIGSEGV

With LD_PRELOAD:
Red Baron -> shim malloc -> mmap -> Linuxulator -> FreeBSD VM
          <- usable memory
```

- We intercept **user-level library functions**, not the `brk` syscall.
- The shim uses `mmap`/`munmap` instead of libc5's heap-growth path.
- Linuxulator still handles those calls and the application's other Linux syscalls.
- This is an application workaround; it does not repair Linuxulator's `brk`.

<!--
Presenter notes:
Option 2 later shows the original allocator running on the corrected
BARONVM kernel. This slide describes the existing baron jail's workaround.
LD_PRELOAD changes dynamic symbol resolution; it does not rewrite direct
syscalls or guarantee interception of private libc-internal calls.
-->

---

# Replace all five allocation-related functions

The replacement shared library is a **shim**: it keeps the function interfaces and changes how memory is allocated.

| Function | Why it belongs in the shim |
|---|---|
| `malloc` | Obtain memory with `mmap`, avoiding libc5's `brk` path. |
| `calloc` | Check multiplication overflow; allocate zero-filled storage through the shim. |
| `realloc` | Read the shim's header; allocate, copy, and release compatible storage. |
| `free` | Read the shim's header and release the mapping with `munmap`. |
| `strdup` | Copy strings into memory allocated by the shim. |

These functions must use the **same allocation layout**. They do not all call `brk`; replacing the family prevents incompatible allocation and release.

<!--
Presenter notes:
The executable's dynamic symbols identified these five functions. Four
were weak undefined imports; strdup was an ordinary undefined import.
PLT relocations confirmed dynamic calls. Replacing malloc alone risks
libc5 free/realloc receiving pointers they cannot interpret.
The study did not audit every private allocator call in every DSO; this
is the boundary identified and exercised for the startup workaround.
-->

---

# The replacement allocator uses `mmap` instead of `brk`

```text
Linux mmap, syscall 90
    |
    v
[ 16-byte header ][ requested bytes ... page rounding ... ]
^ mapping base   ^ pointer returned to Red Baron
```

- Private anonymous memory, initially zero-filled; 16-byte aligned pointer.
- Header records mapped length, requested length, and an ownership marker.
- `realloc`: allocate → copy → release; `free`: Linux `munmap`, syscall 91.
- Direct Linux syscalls avoid libc5’s `brk` path; Linuxulator still services them.

<!--
Presenter notes:
Legacy Linux/i386 mmap takes a pointer in EBX to six 32-bit words: address,
length, protection, flags, fd, and byte offset. The shim enters with
int 0x80 and preserves EBX for position-independent code. It checks size
arithmetic and raw syscall errors. Anonymous mappings provide calloc's zeroing.
The next slides show all five exported function bodies from baron-invest.md,
Appendix A. Longer functions continue across slides; shared types and helpers
remain in that complete source. red-baron.md describes this workaround.
-->

---

<!-- _class: allocator-code -->

# `malloc`: calculate the allocation size

Reserve space for the allocation header and requested data, checking that size calculations cannot overflow.

```c
void *
malloc(size_t size)
{
    struct linux_mmap_args args;
    struct allocation_header *header;
    u32 needed;
    u32 mapping_length;
    long result;
    if (size == 0)
        size = 1;
    if (size > 0xffffffffU - (u32)sizeof(*header) - (PAGE_SIZE - 1U))
        return (void *)0;
    needed = (u32)sizeof(*header) + size;
    mapping_length = (needed + PAGE_SIZE - 1U) & ~(PAGE_SIZE - 1U);
```

<!--
Presenter notes:
First half of malloc; continued on the next slide. A zero-size request becomes
one byte. The arithmetic check leaves space for the 16-byte header and page
rounding, so a very large request cannot wrap into a small mapping. PAGE_SIZE
is 4096 for this implementation. The source retains the original i386 types.
-->

---

<!-- _class: allocator-code -->

# `malloc`: map memory and return a pointer

Map memory, record the allocation sizes, and return a pointer immediately after the header.

```c
    args.addr = 0;
    args.len = mapping_length;
    args.prot = PROT_READ | PROT_WRITE;
    args.flags = MAP_PRIVATE | MAP_ANONYMOUS;
    args.fd = 0xffffffffU;
    args.offset = 0;
    result = linux_syscall1(LINUX_SYS_MMAP, &args);
    if (syscall_failed(result))
        return (void *)0;
    header = (struct allocation_header *)(unsigned long)result;
    header->magic = HEADER_MAGIC;
    header->mapping_length = mapping_length;
    header->requested_length = size;
    header->reserved = 0;
    return (void *)(header + 1);
}
```

<!--
Presenter notes:
Continuation of malloc, completing the function. Syscall 90 receives a pointer
to six words. No file is involved; fd is -1 in its unsigned 32-bit form and
the offset is zero. syscall_failed recognizes raw Linux errors -1 through
-4095. The header stores the mapped length for free and requested length for
realloc; header + 1 skips the complete 16-byte header. Anonymous pages are
initially zero-filled. The syscall wrapper itself has no libc dependency.
-->

---

<!-- _class: allocator-code -->

# `free`: release a matching allocation

`free` finds the header before the returned pointer and unmaps the complete allocation.

```c
void
free(void *pointer)
{
    struct allocation_header *header;
    if (pointer == (void *)0)
        return;
    header = ((struct allocation_header *)pointer) - 1;
    if (header->magic != HEADER_MAGIC)
        return;
    header->magic = 0;
    (void)linux_syscall2(LINUX_SYS_MUNMAP, header, header->mapping_length);
}
```

<!--
Presenter notes:
free(NULL) does nothing. Walking back one header recovers the mapping base;
munmap needs that base and the full mapped length. Clear the ownership marker
before release. Unknown markers are ignored, which can leak memory; reading
an invalid pointer still can fault. The marker is not general pointer
validation, and this code does not make double-free safe.
-->

---

<!-- _class: allocator-code -->

# `calloc`: check the array size, then allocate

`calloc` allocates `count × size` bytes and returns zero-filled memory; the multiplication must not overflow.

```c
void *
calloc(size_t count, size_t size)
{
    size_t total;
    if (count != 0 && size > 0xffffffffU / count)
        return (void *)0;
    total = count * size;
    /* Anonymous mappings are zero-filled by the kernel. */
    return malloc(total);
}
```

<!--
Presenter notes:
Check count * size before multiplying. If the product overflows, a small
allocation could otherwise be returned for a much larger logical array.
The shim always uses fresh anonymous mappings, so the kernel supplies the
zero bytes without calling memset or another libc function. A zero-total
request follows the shim malloc behavior shown earlier.
-->

---

<!-- _class: allocator-code -->

# `realloc`: handle NULL, zero size, and allocation headers

`realloc` reads the shim’s header to find the existing size; NULL and zero-size requests have separate behavior.

```c
void *
realloc(void *pointer, size_t size)
{
    struct allocation_header *header;
    void *replacement;
    size_t copy_length;
    if (pointer == (void *)0)
        return malloc(size);
    if (size == 0) {
        free(pointer);
        return (void *)0;
    }
    header = ((struct allocation_header *)pointer) - 1;
    if (header->magic != HEADER_MAGIC)
        return (void *)0;
```

<!--
Presenter notes:
First half of realloc; continued on the next slide. A null pointer means
a new allocation. In this implementation, size zero frees the original and
returns null. Otherwise recover the header and check its ownership marker
before reading the recorded requested length. As with free, this is not
complete validation of arbitrary pointers.
-->

---

<!-- _class: allocator-code -->

# `realloc`: allocate, copy, then release

Copy the smaller of the old and new sizes. If allocation fails, retain the original block and its contents.

```c
    replacement = malloc(size);
    if (replacement == (void *)0)
        return (void *)0;
    copy_length = header->requested_length < size
        ? header->requested_length : size;
    copy_bytes((unsigned char *)replacement,
        (const unsigned char *)pointer, copy_length);
    free(pointer);
    return replacement;
}
```

<!--
Presenter notes:
Continuation of realloc, completing the function. The old block is freed
only after replacement allocation succeeds and its bytes have been copied.
The smaller requested length prevents reading beyond the old allocation or
writing beyond the new one. copy_bytes is the local byte-copy loop; it does
not import memcpy. Every resize maps a replacement; there is no in-place
optimization or shared arena bookkeeping.
-->

---

<!-- _class: allocator-code -->

# `strdup`: copy strings using the replacement allocator

`strdup` allocates and returns a copy of a string. Its result must use memory that the replacement `free` and `realloc` can handle.

```c
char *
strdup(const char *source)
{
    size_t length;
    char *copy;
    if (source == (const char *)0)
        return (char *)0;
    for (length = 0; source[length] != '\0'; length++)
        ;
    if (length == 0xffffffffU)
        return (char *)0;
    copy = (char *)malloc(length + 1U);
    if (copy != (char *)0)
        copy_bytes((unsigned char *)copy,
            (const unsigned char *)source, length + 1U);
    return copy;
}
```

<!--
Presenter notes:
Count the string, allocate room for its terminating zero, and copy that zero
too. The code includes its original null-input and length checks. copy_bytes
is the same local loop used by realloc. Providing strdup here ensures its
returned storage uses the shim header, rather than relying on libc5 internal
allocation behavior. This completes all five exported function bodies.
-->
---

# 9. Build and install the Linux/i386 shim

```sh
cd /root/redbaron-install
cc -target i386-unknown-linux-gnu -m32 -O2 -fPIC \
  -ffreestanding -fno-builtin -fno-stack-protector \
  -fno-asynchronous-unwind-tables -c malloc_shim.c
ld -m elf_i386 --hash-style=sysv -shared \
  -soname libredbaron_compat.so \
  -o libredbaron_compat.so malloc_shim.o
brandelf -t Linux libredbaron_compat.so
install -m 0755 libredbaron_compat.so \
  /compat/linux/usr/lib/redbaron/libredbaron_compat.so
```

Audit with `file`, `readelf -d`, and `readelf -Ws`: ELF32, SysV HASH, five exports, no libc dependency.

<!--
Presenter notes:
These commands ran successfully in baron with its native FreeBSD Clang/LLD.
--hash-style=sysv avoids relying on GNU-hash support in the 1997 loader.
The five function bodies shown earlier are the source copied in step 2.
Check undefined dynamic symbols as well as DT_NEEDED. The linked artifact's
actual audit is saved in diagnostics/baron-2026-10-26/shim-elf.txt.
-->

---

<!-- _class: allocator-code -->

# 10. Install the Red Baron launcher

**In `baron`, as root:**

```sh
cat > /usr/local/bin/redbaron <<'EOF'
#!/bin/sh
set -eu
export DISPLAY="${DISPLAY:-:1}"
export HOME="${HOME:-/root}"
export XAUTHORITY="${XAUTHORITY:-$HOME/.Xauthority}"
export REDBARON=/usr/lib/redbaron
export LANG=C
export LC_ALL=C
export XKEYSYMDB=/usr/X11R6/lib/X11/XKeysymDB

export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/X11R6/lib
export LD_PRELOAD=/usr/lib/redbaron/libredbaron_compat.so
exec /compat/linux/usr/lib/redbaron/redbaron_3.10 "$@"
EOF
chmod 0755 /usr/local/bin/redbaron
```


<!--
Presenter notes:
The launcher sets the Linux library paths and enables the replacement
allocator for this process. A single LD_PRELOAD assignment is sufficient;
exec replaces the native shell with the browser process.
DISPLAY defaults to :1 to match vnc-session. Run these commands as root,
matching that helper's desktop. No separate redbaron account or Xauthority
cookie setup is required by the current session script.
LC_ALL=C and LANG=C avoid depending on a modern locale name. XKEYSYMDB
points to the original data restored in step 5. The exec path starts from
the jail's native filesystem. The native FreeBSD shell launches the Linux executable directly.
-->

---

# 11. Launch Red Baron with the allocator replacement

For an interactive test in the jail:

```sh
/usr/local/bin/redbaron -url file:/usr/lib/redbaron/help/index.htm
```

For a detached demonstration started over SSH:

```sh
daemon -f -p /var/run/redbaron.pid \
  -o /root/.vnc/redbaron.log \
  /usr/local/bin/redbaron \
  -url file:/usr/lib/redbaron/help/index.htm
```

**Use `-url`.** A bare address makes this executable print usage and exit. `vnc-session` starts the desktop; Red Baron is launched separately.

<!--
Presenter notes:
Choose one launch method; do not run both unless multiple browser windows
are intended. The detached command was used for the live verification.
The native daemon's -f detaches standard descriptors so SSH can return.
The helper supplies Fluxbox; no separate window-manager launch is needed.
Neither command installs a boot service or browser crash-restart policy.
-->

---

# 12. Verify the process and the rendered page

**In the jail:**

```sh
/usr/local/bin/vnc-session status
pgrep -fl redbaron
sockstat -4 -l | grep 5901
tail -n 20 /root/.vnc/redbaron.log
DISPLAY=:1 xwininfo -root -tree | grep 'Help Index'
```

After the font-path correction, the live check found a **“Help Index” window**, a running browser, and no font warnings in its launch log. Check the page in VNC as well. The earlier screenshot and allocator checks remain in [the diagnostic record](diagnostics/baron-2026-10-26/README.md).

<!--
Presenter notes:
The log path here belongs to the detached command in step 11. For an
interactive launch, inspect the terminal output instead of this log. A process or banner alone does not
prove rendering; inspect the visible help page.
vnc-session restart stops its X server and Fluxbox, closing applications on
that display. Its stop action uses broad process matches, so this helper is
for the current single desktop, not isolated management of multiple sessions.
WRP is installed and checked in the closing steps; sustained browsing remains a separate check.
-->

---

# Red Baron displaying its own help

![height:480px](muug-baron-assets/baron-redbaron.png)

Captured from the earlier `:2` demo on 2026-10-26; the current guide uses `:1`.

---

# Option 2: preserve the logical break in the kernel

The patch keeps three values distinct:

| Value | Meaning |
|---|---|
| `vm_brk` | Exact byte address returned to the Linux process. |
| `vm_brk_min` | Lowest permitted address, protecting the executable's memory. |
| Existing VM accounting | Page-rounded mappings and resource-limit checks. |

`kern_break` still performs the mapping work. Linuxulator requests Linux return semantics:

```c
new = (uintptr_t)args->dsend;
(void)kern_break(td, &new, true);
td->td_retval[0] = (register_t)new;
```

Native FreeBSD callers pass `false`, retaining their rounded success values and native errors.

<small>Source: [consolidated kernel patch](../linux-brk/upstream/0001-linuxulator-logical-brk.patch).</small>

<!--
Presenter notes:
The helper's new third parameter selects Linux or native semantics. It
captures the returned logical address under the VM map lock, including on
refusal. linux_brk returns that local result rather than reading shared
state after unlocking. Removing kern_break would lose the actual VM work.
-->

---

# libc5 uses spare space in the final ELF page

```text
End of executable memory:   0x082ee268  (_end, including BSS)
First libc5 brk request:    0x082ee290  (_end + 40 bytes)
End of mapped page:         0x082ef000
```

- The request is above the executable's memory end, inside an existing page.
- Using the page boundary as the minimum wrongly rejects that request.
- The ELF loader now records the **exact memory end** as the Linux lower bound.
- The initial `brk(0)` result can remain page aligned; a later request can use the spare bytes below it.

Correcting rounded success returns alone was insufficient: the earlier kernel passed 28 checks while this libc5 startup still failed.

<!--
Presenter notes:
BSS reserves zero-initialized variables and is included in p_memsz. The final
PT_LOAD starts at 0x082aec48 with p_memsz 0x3f620, giving 0x082ee268.
The kernel calculates the maximum p_vaddr + load bias + p_memsz across the
main executable's nonempty PT_LOAD segments; it does not look up _end or
hard-code Red Baron's name or these addresses. Interpreter/shared-library
mappings do not replace the main image's floor. Requests below that floor
leave the break and mappings unchanged. This protects the whole ELF image;
it is a conservative legacy policy, not every Linux CONFIG_COMPAT_BRK or
heap-randomization configuration. The added legacy regression covers first
requests both without and with a preceding query.
-->

---

# Keep break state consistent with the address space

| Operation | Patch behavior |
|---|---|
| New VM space | Initialize the saved break and lower bound. |
| `brk(0)` or a refused request | Return the current exact break; preserve mappings. |
| Successful resize | Update the logical break after the VM operation succeeds. |
| Shared-VM callers | Hold the map lock and capture each call's result before unlocking. |
| `fork` | Copy the break and lower bound under the same lock as the mappings. |
| `exec` | Clear old state, then establish the new executable's lower bound. |

The repair covers more than one return statement: queries, process creation, program replacement, and concurrent calls must agree.

<!--
Presenter notes:
vmspace_alloc initializes the fields; vmspace_fork copies both while holding
the parent map lock. exec_new_vmspace resets them even when exec reuses a
vmspace. The ELF loader seeds vm_brk_min for Linux processes. kern_break
lazily initializes vm_brk from the mapped end and applies the ABI-specific
query, lower-bound and return rules under the map lock.
-->

---

# Apply the current-main repair and regression tests

In the build workspace, use a **clean FreeBSD source tree** at main revision **`61c70dc16a79`**. Run from this presentation's project directory, outside the `baron` SSH session:

```sh
cd ../linux-brk
BRK_SRC=/path/to/clean-freebsd-src
patch -C -p1 -d "$BRK_SRC" < upstream/0001-linuxulator-logical-brk.patch
patch -C -p1 -d "$BRK_SRC" < upstream/0002-linuxulator-brk-tests.patch
patch -p1 -d "$BRK_SRC" < upstream/0001-linuxulator-logical-brk.patch
patch -p1 -d "$BRK_SRC" < upstream/0002-linuxulator-brk-tests.patch
```

- Patch 1 repairs the kernel; patch 2 supplies ATF/Kyua regressions.
- This is a **local review proposal**, not a FreeBSD 15.1 release update.
- It changes `vmspace` layout and `kern_break`'s interface: rebuild the kernel and its modules together.

<small>Base: `61c70dc16a79efcb9db732d37706cd311f555d9a`. [Patch workflow and status](../linux-brk/UPSTREAM.md).</small>

<!--
Presenter notes:
FreeBSD patch -C checks without applying. The documented development source
at /tmp/linux-brk-upstream/src is already patched; do not apply these commands
there again. Use a separate clean tree at the stated base. Do not combine
this series with the four historical 15.1 patches: those lack the final
ELF-floor correction. The proposed __FreeBSD_version is 1600030; that is a
local KBI marker, not evidence the patch has been accepted upstream.
-->

---

# Build and boot a matching BARONVM guest

A jail uses its host kernel. The kernel repair was tested in a separate VM:

```sh
# In ../linux-brk, with the patched source and prepared guest inputs:
BRK_SRC=/path/to/patched-freebsd-src
BRK_OBJ=/path/to/matching-objects
SRC="$BRK_SRC" OBJ="$BRK_OBJ" ./baron-test/build-kernel.sh
SRC="$BRK_SRC" OBJ="$BRK_OBJ" ./baron-test/build-image.py
sudo ./baron-test/run-bhyve.sh
```

- BARONVM has 512 MiB RAM, two CPUs, Xvnc, and the original Linux runtime.
- The guest boots its rebuilt kernel and matching Linuxulator modules.
- Shut down an existing guest before rebuilding its disk; rebuilding resets guest data.

<small>Requires the compiled syscall helper and prepared guest userland: [BARONVM setup](../linux-brk/baron-test/README.md), [helper build instructions](../linux-brk/README.md).</small>

<!--
Presenter notes:
The image builder does not compile brk-test/brk-suite. Build that freestanding
i386 helper from start.S, clone.S and brk-suite.c using the sibling README's
command, and supply the original application/runtime files and native guest
userland described in baron-test/README.md. The commands here are the final
kernel/image loop, not a claim that the source patch alone creates a VM.
linux.ko and linux_common.ko must match the new kernel; do not load them into
the existing host. No make installkernel, host reboot, or host module change
is part of this workflow. The normal guest auto-runs both legacy modes and
starts Red Baron; Kyua needs the separate extended test image/runtime.
-->

---

# The patched guest uses the original allocator

The guest launcher clears the preload and runs the executable directly:

```sh
export DISPLAY=:1
export HOME=/root
export REDBARON=/compat/linux/usr/lib/redbaron
export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/X11R6/lib
unset LD_PRELOAD
exec "$REDBARON/redbaron_3.10" -url file:/usr/lib/redbaron/help/index.htm
```

Recorded guest trace, with the allocator shim absent:

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

The original executable, loader, and libc5 were unchanged. Red Baron displayed Help Index and followed a local help link.

<!--
Presenter notes:
This is the separate patched BARONVM guest, not the stock baron jail.
Do not test with env -u LD_PRELOAD /usr/local/bin/redbaron in the existing
jail: that wrapper exports LD_PRELOAD again. Use the guest's no-preload
wrapper or a direct executable launch as shown. The VM's startup trace is
/var/log/redbaron.ktrace; its launcher is ../linux-brk/baron-test/redbaron.sh.
Removing the allocator workaround does not establish video-helper behavior:
launch environment cleanup for native children is a separate concern.
-->

---

# Kernel repair: recorded validation and limits

| Check | Recorded BARONVM result, 2026-10-28 |
|---|---|
| libc5 first request, with and without a prior query | Both legacy modes passed. |
| General Linux/i386 syscall suite | **28/28 passed.** |
| ATF/Kyua in an extended guest | **3/3 cases passed**, including native FreeBSD behavior. |
| Original Red Baron without allocator preload | Local help rendered; a help link worked. |
| amd64 BARONVM, GENERIC, and LINT builds | Passed. |

Upstream acceptance is not established. Other architectures, Linux/amd64 runtime, a full world build, and sustained browser use were not checked.

<small>Evidence and limits: [end-to-end investigation](../linux-brk/blog-baron-brk-full.md), [validation record](../linux-brk/UPSTREAM.md).</small>

<!--
Presenter notes:
These are recorded results in the sibling project, not tests rerun while
editing this deck. Kyua's logical_break case wraps the 28 numbered checks;
legacy_break invokes two variants; native_break checks native behavior.
Three Kyua cases do not mean only three underlying syscall checks. The
normal small BARONVM image does not include Kyua; its result used a temporary
extended image. The earlier Alpine reference's independent fork-stress
failure remains unresolved; no fully passing Linux baseline is claimed.
The fix repairs allocation compatibility, not HTML, JavaScript, CSS or TLS.
WRP and the native video helper remain separate features with separate tests.
-->

---

# Added video playback through a native helper

- A video link launches **native FreeBSD mpv** inside Red Baron's document area.
- The optional **`redbaron-video`** launcher uses a separate browser profile.
- A small additional preload clears Linux loader variables before native helpers start.
- Verified: a linked MP4 test clip, pause, quit, resize, and cleanup at end of file.
- This is a MIME helper: HTML5 video, streaming websites, and audio delivery through VNC are not added.

**Demo:** open `http://127.0.0.1:8091/` in the video-enabled browser and click the test clip. Press **Space** to pause/resume, **q** to close playback before navigating.

<small>[Source, installation, screenshot, and test limits](redbaron-video/README.md).</small>

<!--
Presenter notes:
Verified in baron on 2026-10-28. The native helper attaches mpv to the existing
X11 document window with --wid; the old browser still supplies menus and
navigation. The generated clip is MPEG-4 Part 2 in an MP4 container, with
no audio. Red Baron downloads the file before launching its helper. This
covers the document area, not a layout-aware video element beside text.
The existing /usr/local/bin/redbaron and ordinary profile are unchanged.
No sustained playback, concurrent browser, or audio tests were performed.
-->

---

# Possible stability effects of replacing the allocator

The replacement bypasses the allocation failure observed during startup.

- Calls resolved to the shim avoid libc5’s heap-growth behavior and bookkeeping.
- Separate mappings change allocation layout and memory reuse.
- Unmapping freed blocks may make some stale accesses fail sooner.
- Those changes can also hide application bugs or produce different crashes.

The startup fix is verified. An overall stability improvement would require comparable browsing workloads.

<!--
Presenter notes:
Do not attribute Fedora's historical "very buggy" verdict to this specific
compatibility failure. The shim could avoid old-allocator problems but
does not repair arbitrary browser memory corruption. No guard pages are
promised between allocations, and unmapped addresses can be reused later.
One mapping per allocation costs syscalls and 32-bit address space. Unknown
pointers can leak; reading a supposed header can fault. A magic number is
not pointer validation. A stability claim needs comparable workloads and,
for a historical comparison, the originally supported environment.
-->

---

# Why this FreeBSD setup needed fewer launch tools

| Piece | FreeBSD investigation | Modern Linux report |
|---|---|---|
| Paths seen by the old program | `/compat/linux` compatibility root | Bubblewrap filesystem namespace |
| Launch | Shell → Linux executable | Shell → `setarch` → bwrap → executable |
| Memory allocation setup | Preloaded allocator | Allocator + `setarch` personality flags |
| Display | Xvnc + fonts | X socket + auth bind + fonts |

The `/compat/linux` directory supplies the paths expected by the Linux program. This setup launches it without `setarch` or Bubblewrap.

<!--
Presenter notes:
The Linux column describes the recorded Bubblewrap experiment; other Linux
setups, including a prepared chroot, are possible.
FreeBSD still needed a jail, Linux compatibility support, old files, a shim
build, and X configuration. Bubblewrap was a setup/isolation choice, not a
browser requirement; a prepared Linux chroot is another possible approach.
Both experiments execute x86 code directly.

Technical corrections to the Linux draft:
setarch -L sets ADDR_COMPAT_LAYOUT, not ADDR_LIMIT_32BIT; -R disables ASLR.
Linux's i386 syscall table still includes old mmap (90). The draft's claim
that personality flags enable that syscall after ENOSYS was not established;
do not repeat it as an explanation. Its form-focus/window-manager explanation
and broad stability claims also lack independent verification. The Linux
report describes broader browsing tests; startup is not equivalent coverage.
Primary references are listed in the sources section.
-->

---

# Requirements confirmed by the working installation

1. The Linux runtime needs **matching libraries and the original X11 data**.
2. The trace and core identify a failed allocation followed by a null-pointer write.
3. Repair allocation either with the **preload workaround** or a **matching patched kernel**; the latter keeps libc5's original allocator.
4. The browser needs **`-url`**, a 24-bit display, bitmap fonts, and locale/key-symbol data.
5. The local Help Index verifies rendering before an external website is introduced.

With local rendering verified, WRP adds modern website rendering in the same jail.

<!--
Presenter notes:
The screenshots and selected new diagnostics are included in this project.
Full raw traces are private on baron because they can include authentication
data. The guide records the working conditions, not a claim that every one
of them has been independently isolated by controlled experiments. The
allocator itself is unchanged from the source copied to the jail.
Use the local page as the first demo and WRP as the closing demonstration.
-->

---

# Arch Linux (Omarchy): runtime and allocation

The Omarchy report describes six groups of problems and fixes:

1. **Missing runtime:** extract six original RPMs into a private tree; patch copies to use an available loader and an old-format library cache.
2. **Allocation crashes:** replace libc5's allocator with an `mmap` allocator; make `free` a no-op to avoid later stale-pointer crashes. Memory leaks remain.
3. **Loader compatibility:** use `setarch i386 -L`, SysV symbol hashes, and compatible stack alignment; pass `LD_PRELOAD` through `env` for the 32-bit browser.

<!--
Presenter notes:
This is the Omarchy setup described in presentation-omarchy-baron.md. The
comparison table above concerns the earlier Bubblewrap experiment.
The reported Linux malloc failure does not establish that Linux has the
FreeBSD Linuxulator brk defect. The Omarchy allocator uses mmap2 (192).
Build flags include --hash-style=sysv, -mno-sse, and -mstackrealign. Assigning
LD_PRELOAD through env avoids exposing native 64-bit launch tools to the
32-bit preload. These Linux results were read from the report, not rerun
while adding these slides.
-->

---

# Arch Linux (Omarchy): rendering and desktop integration

4. **Fonts and text:** decompress and index bitmap fonts, add aliases, and patch the null-font crash; correct the patch's swapped operands so lines have distinct baselines.
5. **DNS:** call `res_init()` after the replacement allocator is available, allowing libc5 to read the resolver configuration.
6. **Desktop controls:** supply OSF key names, activate menu shortcuts, set a visible cursor, and fix clipboard conversion failures that terminate the browser under Xwayland.

Remaining issues: bold-italic body text, odd `<TT>` spacing, and sites requiring a `Host:` header.

<small>Source: [Omarchy Linux presentation](presentation-omarchy-baron.md).</small>

<!--
Presenter notes:
The Omarchy fixes are combined in one preload built by install.sh. The
reported result includes rendered pages, keyboard/menu operation, a visible
pointer, and clipboard checks. The deliberate no-op free is a workaround,
not a repair of the underlying stale-pointer access.
The following slides return to the FreeBSD jail, where WRP supplies modern
website rendering through native Chromium.
-->

---

# WRP lets Red Baron display modern websites

**Antoni Sawicki / Tenox** · [tenox7/wrp](https://github.com/tenox7/wrp)

- WRP and **native FreeBSD Chromium** run inside `baron`.
- Chromium fetches HTTPS and executes modern HTML, CSS, and JavaScript.
- Red Baron receives a GIF image and a clickable image map over local HTTP.
- Simple HTML mode is another option.

All three components run in the jail. Chromium handles external websites, so the jail still needs network access.

<!--
Presenter notes:
The installed WRP release asset is 4.10.3 for FreeBSD/amd64. Its internal
banner still says 4.9.3; the download tag and verified checksum identify it.
Chromium is the native package, not an added modern Linux runtime. WRP uses
Chrome DevTools through chromedp. Native Chromium worked in this jail
without adding host sysctls or a custom Chromium wrapper.
-->

---

# How Red Baron, WRP, and Chromium communicate

```text
Inside the Bastille jail baron:

Red Baron           WRP                Native Chromium
Linux/i386          FreeBSD/amd64       FreeBSD/amd64
    |                  |                     |
    |-- HTTP/forms --->|-- DevTools --------->|
    |                  |                     |-- HTTPS --> Website
    |<-- GIF + map ----|<-- rendered page ----|
    |-- click x,y ---->|-- click in page ---->|
```

**WRP listens only on `127.0.0.1:8080` inside the jail.** Red Baron uses that address directly; VNC remains on port 5901.

<!--
Presenter notes:
This VNET jail has its own loopback interface. Both clients share it even
though one uses Linux libraries and the other uses native FreeBSD libraries.
The old browser's connection to WRP is HTTP. Chromium handles the external
HTTPS connection; Red Baron itself has not acquired modern TLS support.
-->

---

# 13. Install native Chromium

**Inside `baron`, as root:** Chromium was absent from quarterly but available in the **latest** ports repository.

```sh
install -d /usr/local/etc/pkg/repos
cat > /usr/local/etc/pkg/repos/FreeBSD.conf <<'EOF'
FreeBSD-ports: {
  url: "pkg+https://pkg.FreeBSD.org/FreeBSD:15:amd64/latest"
}
EOF
pkg update
pkg install -y chromium ca_root_nss font-bh-75dpi
/usr/local/bin/chrome --version
vnc-session start
```

Verified: **Chromium 156.0.8078.47**. This changes the ports repository for this jail; its base system and the old Linux libraries stay separate.

<!--
Presenter notes:
The existing jail had no repository override, so this created a new file.
On another installation, preserve any local repository configuration first.
The base repository's signature/fingerprint verification remains in effect.
Chromium and dependencies added about 1 GiB. Go is not required because we
use the official WRP binary. vnc-session start refreshes the newly installed
bitmap fonts without restarting the desktop. xdotool was also installed
for verification, but is not required to run WRP or Red Baron.
-->

---

# 14. Install the FreeBSD WRP release

```sh
install -d /root/redbaron-install/wrp
cd /root/redbaron-install/wrp
fetch -o wrp-amd64-freebsd \
  https://github.com/tenox7/wrp/releases/download/4.10.3/wrp-amd64-freebsd
expected=2d433c5fea4aa29906f68a8d366cb18025e8f1fab74a31a89c5f3d311ca91d7d
test "$(sha256 -q wrp-amd64-freebsd)" = "$expected" && \
  install -m 0755 wrp-amd64-freebsd /usr/local/bin/wrp
```

The expected SHA256 is the digest published with the **4.10.3** GitHub release asset. Stop if it does not match.

The **4.10.3** release asset contains an upstream version banner of **4.9.3**. Use the release URL and checksum to identify the installed binary.

<!--
Presenter notes:
The binary was fetched and checksum-verified in baron. The checksum and
release URL are pinned for this walkthrough. Updating WRP means selecting
a new release and checking its corresponding published asset digest.
-->

---

# 15. Give WRP its own account and log

```sh
pw usershow wrp >/dev/null 2>&1 || \
  pw useradd wrp -d /var/db/wrp -m \
  -s /usr/sbin/nologin -c 'Web Rendering Proxy'
install -d -o wrp -g wrp -m 0700 /var/db/wrp
install -o wrp -g wrp -m 0600 /dev/null /var/log/wrp.log
```

WRP and Chromium run as **`wrp`**, with home `/var/db/wrp`. Chromium runs **headless**, without a visible desktop window.

The next slide installs a native FreeBSD service to start them together.

<!--
Presenter notes:
Creating the log with install is a one-time setup step; rerunning it clears
an existing log. WRP's Chrome profile is temporary by default. We have not
configured a persistent authenticated browser profile.
-->

---

<!-- _class: allocator-code -->

# 16. Install the WRP service

Save this as **`/usr/local/etc/rc.d/wrp`**:

```sh
#!/bin/sh
# PROVIDE: wrp
# REQUIRE: NETWORKING
# KEYWORD: shutdown

. /etc/rc.subr
name=wrp
rcvar=wrp_enable
load_rc_config "$name"
: ${wrp_enable:=NO}

pidfile=/var/run/wrp.pid
procname=/usr/local/bin/wrp
# Chromium workers can outlive their parent on this FreeBSD build.
stop_postcmd='pkill -U wrp -x chrome || true'
command=/usr/sbin/daemon
command_args="-f -p ${pidfile} -u wrp -o /var/log/wrp.log \
/usr/local/bin/wrp -b /usr/local/bin/chrome \
-l 127.0.0.1:8080 -t gif -g 640x400x216 -ua="

run_rc_command "$1"
```

<!--
Presenter notes:
This is the installed service source. daemon -u sets the service account
and HOME. -f detaches standard file descriptors; -p records WRP's child PID
so rc.subr can stop it.
The stop hook also terminates chrome workers owned by the dedicated wrp
account; this build left some orphaned workers after WRP exited. It does
not target the root desktop or the Red Baron process.
-b selects the FreeBSD chrome launcher explicitly. -ua= uses Chromium's
own user agent rather than downloading a replacement. -t gif selects a
format this old browser can display. No additional browser flags were needed.
-->

---

# 17. Enable, start, and check WRP

```sh
chmod 0755 /usr/local/etc/rc.d/wrp
sysrc wrp_enable=YES
service wrp start
service wrp status
sockstat -4 -l | grep 8080
curl --retry 5 --retry-connrefused --retry-delay 1 \
  --max-time 30 --fail --silent --show-error \
  -o /dev/null 'http://127.0.0.1:8080/?url=https%3A%2F%2Fexample.com%2F'
tail -n 10 /var/log/wrp.log
```

Expect **`wrp` listening on `127.0.0.1:8080`**, a successful HTTPS navigation, and an encoded GIF. The HTTP listener may need a moment after service startup.

Manage it with `service wrp stop`, `start`, `restart`, or `status`. WRP is enabled for subsequent jail boots.

<!--
Presenter notes:
Start/stop/restart and a fresh HTTPS rendering after restart were tested.
The jail itself was not rebooted. WRP starts Chromium on demand; service
status alone does not establish that an external page can be rendered.
This service has no automatic crash-restart policy. The listener is local
to baron; no host port forwarding or public WRP listener was configured.
-->

---

# 18. Browse an HTTPS page through WRP

In `baron`, launch Red Baron on its existing VNC desktop:

```sh
/usr/local/bin/redbaron -url http://127.0.0.1:8080/
```

1. Enter `https://example.com/` in the WRP form and click **Go**.
2. Click a link or control in the rendered image; WRP forwards the click coordinates to Chromium.
3. Use WRP’s **Bk** (back), **Up**, and **Dn** (down) controls to navigate.

A direct starting URL also works:

```sh
/usr/local/bin/redbaron \
  -url 'http://127.0.0.1:8080/?url=https%3A%2F%2Fexample.com%2F'
```

The workstation only needs its VNC viewer and SSH tunnel to port 5901.

<!--
Presenter notes:
Choose one launch command. When starting over SSH and retaining the process,
use the daemon pattern from step 11, with a separate PID/log if another Red
Baron instance is already open. The example was launched with
/var/run/redbaron-wrp.pid and /root/.vnc/redbaron-wrp.log.
The image may extend below the 800x600 desktop; use the browser scrollbar
or reduce H in the WRP form. Enter HTTPS destinations in the WRP form,
not directly into Red Baron's own address field.
-->

---

# Red Baron displaying a modern page through WRP

![height:440px](muug-baron-assets/baron-wrp.png)

Verified: WRP form submission loaded **`https://www.freebsd.org/`**. Clicking the image opened the site’s mobile menu; WRP logged the forwarded coordinates **`593,40`**.

---

# WRP capabilities and testing limits

- Chromium handles modern websites; Red Baron still handles WRP's old-style HTML and GIF.
- Simple HTML mode can be useful for articles and documentation.
- Rendering adds latency, and some sites reject automated browsers.
- WRP's service is loopback-only, with no persistent login profile configured.

The checks cover local help, two HTTPS pages, form submission, and an image-map click. A sustained browsing workload remains untested.

<small>Reference: [WRP modes and usage](https://github.com/tenox7/wrp).</small>

<!--
Presenter notes:
Keep sensitive logins out of the demonstration. WRP supplies modern page
rendering; it does not repair Red Baron's original parsers. The old browser
and the current root-owned VNC desktop retain their own limitations.
-->

---

# Questions

- Linuxulator runs Red Baron with its original Linux libraries.
- Option 1 preloads five allocation functions using `mmap`/`munmap`.
- Option 2 repairs Linuxulator's `brk` and ELF lower bound, keeping libc5's allocator.
- WRP and native Chromium supply modern website rendering in the same jail.

Both approaches ran local help. The kernel repair was verified in a separate VM; sustained browser stability remains untested.

<!--
Presenter notes:
The local browser revival and WRP are separate parts of the demonstration.
WRP handles modern content in native Chromium in the same jail; it does not give Red Baron
modern JavaScript, CSS, or TLS implementations.
-->

---

# Sources: history and the experiments

- [FreeBSD investigation and complete shim](baron-invest.md).
- [Red Baron revival overview](red-baron.md).
- [Live baron checks, 2026-10-26](diagnostics/baron-2026-10-26/README.md).
- [Captured core: EIP, libc mapping, and argument trail](diagnostics/baron-2026-10-26/core-analysis.md).
- [Linuxulator `brk`: libc5 disassembly, independent probe, and history](LINUXULATOR_BRK.md).
- [Kernel repair patch](../linux-brk/upstream/0001-linuxulator-logical-brk.patch), [regression-test patch](../linux-brk/upstream/0002-linuxulator-brk-tests.patch).
- [Kernel repair and original libc5 in BARONVM](../linux-brk/blog-baron-brk-full.md), [build/test record](../linux-brk/UPSTREAM.md).
- [Legacy Red Hat 4.2 RPM archive](https://legacy.redhat.com/pub/redhat/linux/4.2/en/os/i386/RedHat/RPMS/).
- [Modern Linux experiment](blog-linux-redbaron.md), with qualifications in the comparison notes.
- [Fedora: History of Red Hat Linux](https://fedoraproject.org/wiki/History_of_Red_Hat_Linux).
- [Red Hat: 4.2 shipping announcement, May 1997](https://www.redhat.com/en/about/press-releases/press-redhat42).
- [NCSA: history, Mosaic in 1993](https://www.ncsa.illinois.edu/about/history/).
- [Eric Sink: Memoirs From the Browser Wars](https://ericsink.com/Browser_Wars.html).

<!--
Presenter notes:
Historical external sources were checked October 22, 2026. The baron
installation, fresh baseline trace, linked shim, and rendered local help were
independently checked October 26, 2026. The captured core was
also decoded and matched against libc5 on that date; the core slides show
the commands and selected evidence directly. WRP form submission and an
image-map click were verified with native Chromium in the same jail.
The libc5 __sbrk comparison and heap-growth helpers were also disassembled;
the complete failing allocation has not been single-stepped.
-->

---

# Sources: binary compatibility, loading, and WRP

- [GNU: Linux and the GNU System](https://www.gnu.org/gnu/linux-and-gnu.html), [musl libc](https://musl.libc.org/).
- [FreeBSD Handbook: Linux Binary Compatibility](https://docs.freebsd.org/en/books/handbook/linuxemu/), [FreeBSD `rtld` manual](https://github.com/freebsd/freebsd-src/blob/main/libexec/rtld-elf/rtld.1).
- [SunOS 4.0 change notes, p. 8](https://vtda.org/docs/computing/Sun/software/800-1731-10_SunOS4.0ChangeNotes9May88.pdf), [OpenBSD loader history](https://man.openbsd.org/ld.so).
- [Linux `brk(2)`](https://man7.org/linux/man-pages/man2/brk.2.html), [i386 syscall table](https://github.com/torvalds/linux/blob/master/arch/x86/entry/syscalls/syscall_32.tbl), [util-linux `setarch` manual](https://github.com/util-linux/util-linux/blob/master/sys-utils/setarch.8.adoc).
- [Antoni Sawicki / Tenox: WRP](https://github.com/tenox7/wrp).

<!--
Presenter notes:
The SunOS 4.0 undocumented LD_PRELOAD detail comes from the presenter;
the linked historical documents support the shared-library background.
Next useful experiments: review/rebase the kernel patch and broaden runtime
architecture coverage; run sustained browsing workloads; broaden the WRP site
tests; compare memory usage and failures between the allocator approaches.
-->

---

# Appendix: `vnc-session`

Source copied from **`baron:/usr/local/bin/vnc-session`**, 2026-10-26, without modification. The following slides contain the complete script in order.

- Defaults: display `:1`, depth 24, 800×600, port 5901.
- `start`: create credentials if needed, start Xvnc, refresh fonts, start Fluxbox.
- `status`, `stop`, `restart`, `xterm`: manage the desktop.
- `password`: prints a locally stored password; do not run it during screen sharing.

This helper uses root's desktop and listens on network interfaces. Its stop command also stops Fluxbox processes beyond a particular display.

---

<!-- _class: allocator-code -->

# Appendix: VNC display, fonts, and file paths

```sh
#!/bin/sh
set -eu

DISPLAY_NUM=${DISPLAY_NUM:-1}
DISPLAY=":$DISPLAY_NUM"
GEOMETRY=${GEOMETRY:-800x600}
DEPTH=${DEPTH:-24}
RFBPORT=${RFBPORT:-5901}
VNC_DIR=${VNC_DIR:-/root/.vnc}
VNC_PASS_FILE=${VNC_PASS_FILE:-$VNC_DIR/passwd}
VNC_PASS_TEXT=${VNC_PASS_TEXT:-$VNC_DIR/vnc-password}
VNC_LOG=${VNC_LOG:-$VNC_DIR/xvnc.log}
VNC_PID=${VNC_PID:-/var/run/xvnc.pid}
FONT_PATH=${FONT_PATH:-/usr/local/share/fonts/misc,/usr/local/share/fonts/75dpi,/usr/local/share/fonts/100dpi,built-ins}

```

---

<!-- _class: allocator-code -->

# Appendix: command usage and environment settings

```sh
usage() {
    cat <<USAGE
usage: vnc-session {start|stop|restart|status|password|xterm}

Environment overrides:
  DISPLAY_NUM=$DISPLAY_NUM
  GEOMETRY=$GEOMETRY
  DEPTH=$DEPTH
  RFBPORT=$RFBPORT
  FONT_PATH=$FONT_PATH
USAGE
}

```

---

<!-- _class: allocator-code -->

# Appendix: check the display and refresh fonts

```sh
is_vnc_up() {
    env DISPLAY="$DISPLAY" xset q >/dev/null 2>&1
}

refresh_session() {
    env DISPLAY="$DISPLAY" xset fp= "$FONT_PATH" >/dev/null 2>&1 || true
    env DISPLAY="$DISPLAY" xset fp rehash >/dev/null 2>&1 || true
    env DISPLAY="$DISPLAY" xsetroot -cursor_name left_ptr >/dev/null 2>&1 || true

    if command -v fluxbox >/dev/null 2>&1 && ! pgrep -x fluxbox >/dev/null 2>&1; then
        env DISPLAY="$DISPLAY" fluxbox >/dev/null 2>&1 &
    fi
}

```

---

<!-- _class: allocator-code -->

# Appendix: create the VNC authentication files

```sh
create_password() {
    install -d -m 700 "$VNC_DIR"
    if [ ! -s "$VNC_PASS_FILE" ]; then
        pw=$(openssl rand -base64 18)
        printf "%s\n" "$pw" | vncpasswd -f > "$VNC_PASS_FILE"
        chmod 600 "$VNC_PASS_FILE"
        printf "%s\n" "$pw" > "$VNC_PASS_TEXT"
        chmod 600 "$VNC_PASS_TEXT"
    fi
}

```

---

<!-- _class: allocator-code -->

# Appendix: start Xvnc

```sh
start_vnc() {
    if is_vnc_up; then
        refresh_session
        echo "Xvnc is already running on $DISPLAY"
        return
    fi

    create_password
    rm -f "/tmp/.X${DISPLAY_NUM}-lock" "/tmp/.X11-unix/X${DISPLAY_NUM}"

    daemon -p "$VNC_PID" -o "$VNC_LOG" \
        /usr/local/bin/Xvnc "$DISPLAY" \
        -geometry "$GEOMETRY" \
        -depth "$DEPTH" \
        -rfbport "$RFBPORT" \
        -SecurityTypes VncAuth \
        -rfbauth "$VNC_PASS_FILE" \
        -AlwaysShared=1 \
        -AcceptSetDesktopSize=0 \
        -localhost no \
        -fp "$FONT_PATH"

```

---

<!-- _class: allocator-code -->

# Appendix: wait for the X11 display to become ready

```sh
    for _ in 1 2 3 4 5 6 7 8 9 10; do
        if is_vnc_up; then
            refresh_session
            echo "Started Xvnc on $DISPLAY port $RFBPORT"
            return
        fi
        sleep 1
    done

    echo "Xvnc did not become ready; see $VNC_LOG" >&2
    exit 1
}

```

---

<!-- _class: allocator-code -->

# Appendix: stop Xvnc and Fluxbox

```sh
stop_vnc() {
    if [ -s "$VNC_PID" ]; then
        pid=$(cat "$VNC_PID")
        kill "$pid" 2>/dev/null || true
        rm -f "$VNC_PID"
    fi
    pkill -f "Xvnc $DISPLAY" 2>/dev/null || true
    pkill fluxbox 2>/dev/null || true
    rm -f "/tmp/.X${DISPLAY_NUM}-lock" "/tmp/.X11-unix/X${DISPLAY_NUM}"
    echo "Stopped Xvnc on $DISPLAY"
}

```

---

<!-- _class: allocator-code -->

# Appendix: handle start, stop, and restart commands

```sh
case "${1:-}" in
    start)
        start_vnc
        ;;
    stop)
        stop_vnc
        ;;
    restart)
        stop_vnc
        start_vnc
        ;;
```

---

<!-- _class: allocator-code -->

# Appendix: handle status, password, and xterm commands

```sh
    status)
        if is_vnc_up; then
            echo "Xvnc is running on $DISPLAY port $RFBPORT"
        else
            echo "Xvnc is not running on $DISPLAY"
            exit 1
        fi
        ;;
    password)
        create_password
        cat "$VNC_PASS_TEXT"
        ;;
    xterm)
        start_vnc
        env DISPLAY="$DISPLAY" xterm >/dev/null 2>&1 &
        ;;
    -h|--help|help|"")
        usage
        ;;
    *)
        echo "unknown command: $1" >&2
        usage >&2
        exit 64
        ;;
esac

```
