$ uname -a A_BLOG_ABOUT_UNIX_TOOLS_AND_THE_BEAUTY_OF_SIMPLE_SYSTEMS
SYS.YEAR  2026
← Back to articles
2026-11-12ARTICLE

Ftw Baron

FTW, Baron

Making Red Baron 3.10 render http://openbsd.org on FreeBSD 15.1

Investigation date: 2026-11-12

Host: FreeBSD 15.1, Linuxulator, original Red Hat Linux 4.2 userland under /compat/linux

Scope and provenance. This account consolidates the recorded investigation in blog-baron-ftw.md, the earlier red-baron.md, and the preserved double-free artifacts. Commands and results below describe historical runs, not new browser tests. The archived allocator log confirms consecutive frees of 0x2a3b3010; the archived system-call trace confirms the fault at 0x2a3b3000. Other core, HTTP, helper-environment, and POC results are reported from the existing account; their original temporary files are not included in this repository. See §11.6 and Appendix D for limits. See tldr-baron.md for the short companion.

Evidence labels. Verbatim output is copied exactly. Selected output removes unrelated lines but leaves the retained lines unchanged. Annotated reconstruction preserves the decisive addresses and instructions while adding comments or names for teaching. Inferences are labelled separately and are not presented as traces.


The short version

Red Baron 3.10, a 1996 Linux/Motif browser built against Red Hat 4.2's libc5, segfaulted at startup under FreeBSD's Linuxulator. The first crash was not a missing library and not an X11 problem. Red Hat's libc.so.5.3.12 implements brk(2) as a contract: the kernel must return exactly the address the caller requested, or libc5 sets errno = ENOMEM and malloc() returns NULL. FreeBSD's Linuxulator rounds the new break up to a page boundary, so the very first heap growth "failed". Red Baron stored the NULL, then called strcpy(NULL, "Spyglass"). The fix is a freestanding i386 Linux shared object, preloaded with LD_PRELOAD, that replaces malloc/calloc/realloc/free/strdup with an allocator built on the legacy Linux mmap syscall.

Testing the first version exposed a second bug in Red Baron: it frees the same block twice. The chosen fix keeps shim blocks mapped, so the second free() can still read their headers. This is sufficient for the observed failure; it is not proof that every allocator must avoid munmap. The installed allocator also keeps freed blocks on size-class free lists and reuses them, which reduces address-space growth through reuse but is not required to tolerate the observed consecutive double free. A minimal proof-of-concept shim with no free lists and a no-op free() survives both URLs; §14 records that experiment. A small wrapper sets the Linux-side environment and execs the untouched 1996 binary. Verified result: a window titled OpenBSD, an HTTP/1.0 200 OK from OpenBSD httpd, and the OpenBSD homepage on screen.


What the fix looks like

Component Path Role
Original browser /compat/linux/usr/lib/redbaron/redbaron_3.10 Unmodified 1996 executable
Original C library /compat/linux/lib/libc.so.5.3.12 Unmodified libc5 (still on disk)
Compatibility shim /compat/linux/usr/lib/redbaron/libredbaron_compat.so Replaces the five allocator entry points
Shim source /root/projects/asiabsd/2027/redbaron-shim/malloc_shim.c Freestanding i386 Linux C
Shim build script /root/projects/asiabsd/2027/redbaron-shim/build.sh Clang + LLD + brandelf
Launcher /usr/local/bin/redbaron Sets environment and execs the binary
Launcher source /root/projects/asiabsd/2027/redbaron-shim/redbaron POSIX sh
POC source (not installed) /root/projects/asiabsd/2027/redbaron-shim/malloc_poc.c Minimal no-free-list variant, §14
Screenshot /root/projects/asiabsd/2027/redbaron-openbsd.png Final visual proof

Nothing in the Red Hat tree was patched. The installed compatibility layer is the shim and the launcher. malloc_poc.c is an experimental third file, kept to test which allocator features are actually required.


Contents

Section What it answers
§1 What the environment looked like before the crash
§2 What the first crash actually was
§3 How the bad value travelled from malloc to strcpy
§4 Why libc5's brk wrapper returned failure
§5 The first fix: mmap plus munmap
§6 The second crash: a double free in Red Baron
§7 The redesign: never unmap; free lists as an optimization
§8 The size-class bug introduced by the redesign
§9 Keeping LD_PRELOAD away from FreeBSD helpers
§10 Building the shim from scratch, step by step
§11 Verification: window, HTTP, screenshot, stability
§12 Known limitations and what not to expect
§13 Correction and decision log
§14 The minimal POC: which allocator features are actually required
A–D Complete source, scripts, and reproduction commands

1. The patient and the operating table

The problem. A 1996 Linux browser must run under a 2026 FreeBSD kernel that emulates Linux 2.0-era system calls.

Why it is plausible at all. FreeBSD's Linuxulator provides the old i386 Linux syscall ABI, and /compat/linux contains the complete Red Hat 4.2 userland the browser was built for. The browser, its libc5, and its X11 libraries are all original files.

Verbatim output (file on the two central binaries):

usr/lib/redbaron/redbaron_3.10: ELF 32-bit LSB executable, Intel i386, version 1 (GNU/Linux), dynamically linked, interpreter /lib/ld-linux.so.1, not stripped
lib/libc.so.5.3.12:             ELF 32-bit LSB shared object, Intel i386, version 1 (SYSV), dynamically linked, not stripped, too many notes (256)

Selected output (readelf -h on the browser, key fields):

  Class:                             ELF32
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Entry point address:               0x8007F70

The Linuxulator must be enabled on the FreeBSD host:

sysrc linux_enable=YES
service linux start

The imported tree lives directly under /compat, so a symlink gives FreeBSD the path it expects:

cd /compat
ln -s . linux

The browser is marked as a Linux binary:

brandelf -t Linux /compat/linux/usr/lib/redbaron/redbaron_3.10

Plain English: the kernel can run the instructions, and the loader can find the 1996 libraries. The failure is therefore likely to be a semantic mismatch in a system call, not a missing file.

Why this matters: every later conclusion depends on the binary and libraries being the originals. If we had replaced libc5, the crash might have disappeared for the wrong reason and the writeup would be useless to anyone with the same Red Hat tree.

1.1 The X11 side

Red Baron also rejects some modern X visuals. The working display is a TigerVNC server at 24-bit depth:

Xvnc :1 -geometry 800x600 -depth 24 -rfbport 5901 \
  -SecurityTypes VncAuth -rfbauth /root/.vnc/passwd \
  -AlwaysShared=1 -AcceptSetDesktopSize=0 -localhost no \
  -fp /usr/local/share/fonts/misc,/usr/local/share/fonts/75dpi,/usr/local/share/fonts/100dpi,built-ins

The imported Red Hat fonts can also be added, but the final run used the host font path above. One cosmetic warning about Lucida remains; see §12.


2. First symptom: SIGSEGV at address 0x0

The problem. The browser dies immediately after the dynamic loader finishes, before any window appears.

Observation. Running the original binary under truss produced the following tail.

Selected output (/tmp/tr-noshim.log, tail):

linux_brk(0x82ee290)				 = 137293824 (0x82ef000)
SIGNAL 11 (SIGSEGV) code=SEGV_MAPERR trapno=12 addr=0x0
process killed, signal = 11 (core dumped)

What the numbers say.

Quantity Value Comment
Requested break 0x82ee290 Not page-aligned (0x290 low bits)
Returned break 0x82ef000 Page-aligned
Difference 0xd70 (3440 bytes) The kernel rounded up
Fault address 0x0 A NULL pointer was dereferenced

Inference. The brk call returned a value different from the requested value, and the next fault is a write to address zero. That combination strongly suggests the C library treated the brk result as an error and returned NULL from the next malloc.

Key point: the fault address is 0x0, not 0x82ee290. The browser is not writing to the rounded break. It is writing through a pointer that became NULL because of the rounding.

A dead end worth recording. Setting security.bsd.map_at_zero=1 did not fix the crash. Mapping page zero would only hide the symptom; the allocation still failed. The sysctl was returned to its secure default of 0.


3. Following the bad value backward

The problem. We know a NULL was written. We need to know which allocation produced it and which write consumed it.

Method. A core dump from the no-shim run was parsed directly: ELF PT_LOAD segments give virtual-to-file mappings, and the NT_PRSTATUS note gives the i386 register set. The stack and the two relevant globals were read out of the core image.

Selected output (registers from the startup crash core):

eip       0x2840643f
esp       0xffffb058

0x2840643f lies in the libc5 mapping and resolves to strcpy+0x13. At the faulting instruction esp is 0xffffb058; strcpy's prologue had already adjusted the stack, so the call frame begins at esp+4:

Selected output (stack words):

ffffb05c: 0807037e
ffffb060: 00000000
ffffb064: 0826bddd

Read as a call frame:

Stack slot Value Meaning
0xffffb05c 0x0807037e Return address into main
0xffffb060 0x00000000 First argument: destination
0xffffb064 0x0826bddd Second argument: source

Selected output (bytes at the source address, from the same core):

0x826bddd  "Spyglass"
0x826bde6  "Mosaic"

So the failing call is strcpy(NULL, "Spyglass"). The next question is how main obtained that NULL. Disassembling main around the return address answers it.

Annotated reconstruction (objdump -d of redbaron_3.10; comments added, bytes unchanged):

08070360: e8 1b 12 0d 00   call 0x8141580        ; SM_Malloc(total length)
08070365: 83 c4 04         add  $0x4,%esp        ; discard the size argument
08070368: a3 6c a2 2e 08   mov  %eax,0x82ea26c   ; save SM_Malloc's return value
0807036d: a1 74 a2 2e 08   mov  0x82ea274,%eax   ; eax -> "Spyglass"
08070372: 50               push %eax             ; strcpy source
08070373: a1 6c a2 2e 08   mov  0x82ea26c,%eax   ; eax = saved return value (NULL)
08070378: 50               push %eax             ; strcpy destination
08070379: e8 4a 5e f9 ff   call 0x80061c8        ; strcpy@plt
0807037e: 83 c4 08         add  $0x8,%esp        ; <- return address seen on the stack

Teaching note: objdump sometimes prints the call target as <gcc2_compiled.> instead of <SM_Malloc>. The symbols SM_Malloc and gcc2_compiled. share address 0x8141580, and the local symbol wins in some listings. The address is what matters.

SM_Malloc itself is a thin wrapper around libc5's malloc:

Annotated reconstruction (objdump -d, comments added):

08141580 <SM_Malloc>:
 8141580: 55              push %ebp
 8141581: 89 e5           mov  %esp,%ebp
 8141583: 8b 45 08        mov  0x8(%ebp),%eax   ; eax = requested size
 8141586: 50              push %eax             ; malloc(size)
 8141587: e8 9c 52 ec ff  call 0x8006828        ; malloc@plt
 814158c: 83 c4 04        add  $0x4,%esp
 814158f: 89 c2           mov  %eax,%edx
 8141591: 89 d0           mov  %edx,%eax         ; return malloc's result unchanged
 8141593: eb 0b           jmp  0x81415a0
 81415a0: 89 ec           mov  %ebp,%esp
 81415a2: 5d              pop  %ebp
 81415a3: c3              ret

Selected output (bytes at the saved-pointer global, from the core):

0x82ea26c  00 00 00 00 00 00 00 00 ...
0x82ea274  dd bd 26 08 00 00 00 00 ...

The chain, stated plainly:

libc5 malloc() returns 0
        |
        v
SM_Malloc returns 0
        |
        v
main stores 0 at 0x82ea26c
        |
        v
main pushes 0 as strcpy destination
        |
        v
strcpy(0, "Spyglass") -> SIGSEGV at address 0

Observation vs inference. The stored zero, the return address, the destination argument, and the string bytes are direct observations from the core and disassembly. The statement "libc5 malloc returned zero" is the only inference, and it is forced by SM_Malloc returning malloc's value unchanged.


4. Why malloc returned NULL: libc5's brk contract

The problem. FreeBSD's Linuxulator returned a page-aligned break. Why did that make libc5 fail?

Observation. Disassembling brk in libc.so.5.3.12 shows an explicit equality test between the requested address and the kernel's return value.

Annotated reconstruction (objdump -d of /compat/linux/lib/libc.so.5.3.12; comments added):

00016d78 <brk>:
   16d89: 8b 74 24 10          mov  0x10(%esp),%esi   ; esi = requested break
   16d96: b8 2d 00 00 00       mov  $0x2d,%eax          ; syscall 45 = brk
   16d9b: 89 f1                mov  %esi,%ecx
   16d9d: 53                   push %ebx              ; preserve the shared library GOT base
   16d9e: 89 cb                mov  %ecx,%ebx          ; ebx = requested break
   16da0: cd 80                int  $0x80              ; eax = break actually set
   16da2: 5b                   pop  %ebx               ; restore GOT base before global access
   16da3: 8b 8b fc 0b 00 00    mov  0xbfc(%ebx),%ecx
   16da9: 89 01                mov  %eax,(%ecx)        ; stash returned break
   16dab: 8b 83 fc 0b 00 00    mov  0xbfc(%ebx),%eax
   16db1: 39 30                cmp  %esi,(%eax)        ; requested == returned?
   16db3: 75 0b                jne  0x16dc0             ; no -> failure path
   16db5: 31 c0                xor  %eax,%eax          ; yes -> return 0
   16db7: 5b                   pop  %ebx
   16db8: 5e                   pop  %esi
   16db9: 83 c4 04             add  $0x4,%esp
   16dbc: c3                   ret
   16dc0: e8 23 f6 ff ff       call 0x163e8            ; __errno_location
   16dc5: c7 00 0c 00 00 00    movl $0xc,(%eax)        ; errno = ENOMEM (12)
   16dcb: b8 ff ff ff ff       mov  $0xffffffff,%eax   ; return -1
   16dd5: c3                   ret

What this means. brk is not implemented as "move the break as close as you can". It is implemented as "move the break to exactly this address, or report failure". libc5 then reports ENOMEM, and malloc propagates NULL.

Plain English: the old C library asks the kernel a yes/no question — "did you set the break to precisely 0x82ee290?" — and treats the page-rounded answer 0x82ef000 as "no".

Correction — logical break versus mapped pages. An earlier draft incorrectly described the rounded return as permitted modern Linux behavior. Linux rounds the backing mapping to page boundaries, but preserves the requested logical break and returns that requested address on success. The Linux kernel implementation distinguishes PAGE_ALIGN(brk) from mm->brk = brk and returns brk on success. The trace in §2 establishes that this Linuxulator run returned a rounded address; it does not establish why its implementation does so. The claim that libc5 predates a newer Linux convention is withdrawn. A source-level investigation of the host kernel remains outside this evidence chain.

Evidence comparison:

Claim Evidence Confidence
Requested 0x82ee290, returned 0x82ef000 truss line in §2 Direct
libc5 compares requested vs returned cmp %esi,(%eax) in this section Direct
Mismatch sets ENOMEM and returns -1 movl $0xc,(%eax) / mov $-1,%eax Direct
malloc then returns NULL SM_Malloc returns malloc unchanged, plus the core zero Strong inference
Linux rounds mappings but returns the requested logical break on success Linux kernel mm/mmap.c, linked above Source inspection

Correction (see §5): knowing why malloc failed tells us what to replace. It does not yet tell us that a simple mmap/munmap allocator is sufficient. It is not; §6 shows a second failure mode.


5. First fix: an mmap allocator (and the second bug it hid)

The problem. We cannot make libc5's brk accept a rounded result without patching libc5. We also do not want to patch the original Red Hat files.

The fix. Interpose the allocator entry points with a preloaded shared object. LD_PRELOAD is processed by the Linux dynamic loader inside the Linuxulator, so the replacement is visible to libc5, Red Baron, and the X11 libraries. New blocks come from the legacy Linux i386 mmap syscall, which is unaffected by the brk contract.

Why not patch libc5? A binary patch would work for exactly one libc5 build and would silently change a preserved 1996 artifact. A preload object is reversible, inspectable, and leaves the original tree intact.

Why not replace libc5 with glibc? Red Baron is linked against the libc5 ABI and its ld-linux.so.1; a modern glibc is not a drop-in replacement.

5.1 The first design

Each allocation received a 16-byte header:

struct allocation_header {
    u32 magic;              /* "RBMA" */
    u32 mapping_length;     /* bytes obtained from mmap */
    u32 requested_length;   /* bytes the caller asked for */
    u32 pad;
};

malloc called mmap for header + size, rounded to a page. free checked the magic, then called munmap(header, mapping_length).

Verification at this stage. -url http://openbsd.org rendered. The first crash was gone.

Correction (see §6): the OpenBSD page worked, but -url google.com still segfaulted. The munmap design assumed each block is freed at most once. Red Baron violates that assumption.


6. Second crash: free() twice on the same block

The problem. With the mmap/munmap shim, the OpenBSD page worked but Google crashed. The crash was inside the shim, which made it look like an allocator bug.

Observation 1 — the debug log. An experimental debug allocator using the same header-and-unmap design wrote one line per allocator call (M = malloc, F = free, R = realloc). The tail of the log for the Google run was:

Selected output (/tmp/dbg2.log; unrelated allocator calls between the first and last lines removed, the two F lines are consecutive in the log):

M 2a3b3010 00001505
...
F 2a3b3010 00000000
F 2a3b3010 00000000

The allocation is 5381 bytes (0x1505). The same user pointer is freed twice in immediately consecutive calls.

Observation 2 — the fault address. The same run under truss ended with:

Selected output (/tmp/tr-dbg.log, tail):

linux_write(0x2,0x282b9c00,0x14)		 = 20 (0x14)
SIGNAL 11 (SIGSEGV) code=SEGV_MAPERR trapno=12 addr=0x2a3b3000
process killed, signal = 11 (core dumped)

The write is the debug line for the second free: 20 bytes is exactly F 2a3b3010 00000000\n. The fault address is 0x2a3b3000.

Observation 3 — the core. The same run produced a core. Selected registers and stack words:

Selected output (i386 NT_PRSTATUS from the core):

eip       0x282b76d8
esi       0x2a3b3010
esp       0xffffae3c

ffffae48: 0814161c
ffffae4c: 2a3b3010

The shim's load base is 0x282b6000, so the instruction offset is 0x282b76d8 - 0x282b6000 = 0x16d8. In the debug build, free starts at 0x1580, so this is free+0x158. The logging code inflates the function; the instruction is the same header check as in the release build (where it appears at free+8).

Annotated reconstruction (objdump -d of the debug shim; comments added):

00001580 <free>:
   ...
   16d8: 81 7e f0 41 4d 42 52   cmpl $0x52424d41,-0x10(%esi)
                                 ; read header->magic at (pointer - 16)
   16df: 75 18                  jne  0x16f9          ; wrong magic -> return
   16e1: 8d 56 f0               lea  -0x10(%esi),%edx ; header address
   16e4: c7 46 f0 00 00 00 00   movl $0x0,-0x10(%esi) ; mark freed
   16eb: 8b 4e f4               mov  -0xc(%esi),%ecx  ; mapping_length
   16ee: b8 5b 00 00 00         mov  $0x5b,%eax       ; syscall 91 = munmap
   16f6: cd 80                  int  $0x80

The arithmetic that closes the case:

Quantity Value
Argument to free 0x2a3b3010
Header address (argument - 0x10) 0x2a3b3000
First free's munmap range [0x2a3b3000, 0x2a3b5000) (two pages)
Address read by second free's magic check 0x2a3b3000
Fault address reported by truss 0x2a3b3000
Caller return address 0x0814161c = SM_Free+0xc

Inference. The first free unmapped both pages of the 8 KiB mapping. The second free tried to validate the header at the start of that mapping and faulted on the unmapped page. The caller is Red Baron's SM_Free, so this is not random corruption: Red Baron really does free the same block twice.

Why this matters. The bug is in the program's use of the allocator, not in libc5 and not in the brk replacement. An allocator for this browser must tolerate a double free, because the browser will not stop doing it.

Alternative fixes considered:

Approach Outcome
Keep munmap, validate before unmapping Second free still dereferences unmapped memory
Keep munmap, never reuse addresses Still faults on the second header read
Clear magic, then mprotect freed pages read-only Not tested. The shown second-free magic read would be permitted and could return safely; later reuse would need write permission restored
Keep blocks mapped, reuse them Works; chosen in §7

7. Redesign: never unmap, reuse by size class

The problem. free must be safe to call twice with the same pointer, and it must not read memory that no longer exists.

The fix. Never return memory to the kernel. Mark a block as freed by changing its header magic, and put it on a free list. A second free sees the wrong magic and returns. A later malloc can reuse the block.

Correction (see §5): this replaces the mmap/munmap design entirely. The munmap syscall is no longer used by the shim.

7.1 Design decisions

Decision Rationale
Use Linux mmap, never brk The brk contract is the original bug
Never call munmap A double free must not touch unmapped memory
Header magic "RBMA" / "RBRF" Distinguishes live from freed blocks
Ignore unknown magic in free Tolerates consecutive double frees of shim blocks; foreign header reads can fault or accidentally match (§12)
Free lists indexed by mapping size Reuse reduces address-space growth; it provides no fixed bound
Check mapping_length per candidate A bin can contain blocks smaller than the request (§8)
realloc grows in place when possible Reduces pointer churn in old code that caches pointers
calloc checks multiplication overflow Avoids undersized allocations on 32-bit
Freestanding, no libc calls No recursion into the allocator being replaced
Single-threaded assumption libc5 and Red Baron are single-threaded

7.2 The header

struct allocation_header {
    u32 magic;                        /* HEADER_MAGIC or FREED_MAGIC */
    u32 mapping_length;               /* bytes obtained from mmap */
    u32 requested_length;             /* bytes the caller asked for */
    struct allocation_header *next_free;
};

The user pointer is header + 1, so the header sits 16 bytes before the pointer. That is why free computes ((struct allocation_header *)pointer) - 1 and why the crash instruction in §6 read -0x10(%esi).

7.3 The life of a block

malloc(size)
    |
    +-- size 0 -> size 1
    +-- round header+size up to a page
    +-- look for a free block in this bin or a larger one
    |       |
    |       +-- found -> unlink from free list
    |       +-- none  -> Linux mmap
    |
    +-- magic = "RBMA"
    +-- return header + 1

free(pointer)
    |
    +-- NULL -> return
    +-- header = pointer - 16
    +-- magic != "RBMA" -> return      (foreign pointer or second free)
    +-- magic = "RBRF"
    +-- push onto free_bins[bin]

realloc(pointer, size)
    |
    +-- NULL -> malloc(size)
    +-- size 0 -> free(pointer), return NULL
    +-- magic != "RBMA" -> return NULL
    +-- size <= capacity -> update length, return same pointer
    +-- otherwise -> malloc, copy min(old,new), free(old), return new

Plain English: the allocator stops treating free as "give this memory back to the operating system". It treats free as "mark this block as available for reuse". Since the block's header stays mapped forever, a second free can safely discover that the block is already free.

Tradeoff accepted. Memory is retained until process exit. For a single-user 1996 browser on a modern host, that is a good trade: the process is short-lived, the allocation volume is small, and correctness matters more than returning pages.

7.4 What the double free actually requires

The observed double free is two consecutive free() calls with no allocation between them. For that pattern, two properties are sufficient:

  1. The header stays mapped, so the second call can read it.
  2. The second call must not treat an already-freed header as live.

The installed shim implements both with munmap-free lifetime, a magic value, and a free list. The POC in §14 implements both with munmap-free lifetime, no magic, and a no-op free(). The free list is therefore an optimization: it reduces address-space growth by reusing blocks. It is not what makes the second free safe.

This distinction has a limit. If a block were freed, reused by a later malloc, and then freed a second time through the stale pointer, the header would be live again and the allocator could not tell the two frees apart. Red Baron's observed frees are consecutive, so the tested workload never creates that case.


8. The size-class bug introduced by the redesign

The problem. The first free-list build failed almost immediately. The evidence pointed at the new bin-selection logic rather than at Red Baron.

Observation. Bins are power-of-two ranges: bin N holds mappings in [4096 << N, 4096 << (N+1)). Both an 8 KiB mapping (0x2000) and a 12 KiB mapping (0x3000) land in bin 1. The first implementation took the first block from that bin without checking its size.

Selected output (standalone simulation of the bin arithmetic, compiled natively on FreeBSD; this reproduces the arithmetic, not a trace of the crash):

bin_for_mapping(0x2000) = 1
bin_for_mapping(0x3000) = 1
old take_free_block served a 0x3000 request from the first 0x2000 block in bin 1
shortfall: 0x1000 bytes

Inference. A 12 KiB request could receive an 8 KiB mapping. A caller that filled the buffer would write up to 4 KiB past the end of the mapping. Depending on what followed it in the address space, that is either heap corruption or an immediate SIGSEGV. No core from that first free-list build was retained, so the crash itself is inferred from the arithmetic and the immediate failure, not observed in a saved trace.

The fix. Walk the bin's linked list and accept only a block whose mapping_length is at least the requested mapping length. If the bin has no such block, continue to the next bin.

Annotated excerpt (current take_free_block):

for (bin = bin_for_mapping(mapping_length); bin < NUM_BINS; bin++) {
    link = &free_bins[bin];
    while (*link != (struct allocation_header *)0) {
        header = *link;
        if (header->mapping_length >= mapping_length) {
            *link = header->next_free;   /* unlink exact-size-or-larger */
            return header;
        }
        link = &header->next_free;       /* too small: keep looking */
    }
}

Correction (see §7): the first free-list implementation assumed every block in a bin was large enough. It was not. The per-candidate check is mandatory, not an optimization.

Before/after:

Request Bin First implementation Current implementation
8 KiB (0x2000) 1 8 KiB block 8 KiB block
12 KiB (0x3000) 1 8 KiB block (too small) next 12 KiB block, or next bin
12 KiB, bin 1 empty 1 mmap mmap

Why this matters for the reader. A free-list allocator is not correct just because it compiles and reuses memory. Size-class boundaries are ranges, and a range can contain a block that is too small for a request in the same range. The check is one comparison; omitting it produces intermittent corruption that looks like a browser bug.


9. Keeping LD_PRELOAD away from FreeBSD helpers

The problem. Red Baron periodically runs shell helpers to collect system information. With LD_PRELOAD set, those helpers inherit the variable.

Observation. During the Google run, the browser forked and executed:

Selected output (kdump, unique helper argument lists):

"sh", "-c", "/bin/ps uax"
"sh", "-c", "/bin/df"
"sh", "-c", "/bin/netstat -i"
"sh", "-c", "/usr/bin/vmstat"
"sh", "-c", "/usr/bin/uptime"

These are FreeBSD /bin/sh processes, not Linux processes. If they inherit LD_PRELOAD=/usr/lib/redbaron/libredbaron_compat.so, FreeBSD's ld-elf.so.1 tries to load an i386 Linux shared object. The pre-fix run printed, repeatedly:

Verbatim output (recorded before the _init fix):

ld-elf.so.1: Cannot open "/usr/lib/redbaron/libredbaron_compat.so"

The same class of failure appears as unsupported file layout when a FreeBSD program such as env(1) or timeout(1) inherits the variable directly.

The fix, part 1. The shim's _init function removes LD_PRELOAD= from environ as soon as the object is loaded. The old Linux ld.so.1 calls DT_INIT, and the build links _init explicitly with -init _init.

The fix, part 2. The launcher sets LD_PRELOAD internally and immediately execs the Linux binary. It must never be exported by the caller, because the caller's shell and tools are FreeBSD programs.

Verification. After the fix, a traced Google run produced seven helper ENVS records from five unique commands:

Verbatim output (counts):

helper_env_records=7
records_with_LD_PRELOAD=0

Why this matters. Without _init, the browser appears to work but sprays loader errors for every helper. Worse, if a helper is a FreeBSD program that treats the preload as fatal, the browser can lose functionality or hang waiting for output. Stripping the variable at load time is cleaner than asking every caller to unset it.

Correction (from an earlier draft): FreeBSD's LD_32_PRELOAD and LIB_32_PRELOAD are not the right variables here. The process is interpreted by Linux's ld-linux.so.1, which reads LD_PRELOAD. Tracing confirmed the FreeBSD-specific names were ignored.

Operational rule. Do not run this:

LD_PRELOAD=/compat/linux/usr/lib/redbaron/libredbaron_compat.so timeout 10 redbaron

timeout is a FreeBSD binary and will try to preload the i386 Linux object. Run this instead:

timeout 10 /usr/local/bin/redbaron -url http://openbsd.org

The wrapper handles the preload in the Linux process only.


10. Building the shim from scratch

This section is the complete recipe. It assumes the Red Hat tree is already under /compat/linux and the Linuxulator is enabled.

10.1 Prerequisites

FreeBSD 15.1 base includes Clang, LLD, brandelf, truss, ktrace, and kdump. Confirm:

for tool in cc ld brandelf truss ktrace kdump; do
    command -v "$tool" >/dev/null || echo "missing: $tool"
done

No cross-compiler package is required: Clang can emit an i386 Linux object directly, and LLD can link it.

10.2 Create the work directory

mkdir -p /root/projects/asiabsd/2027/redbaron-shim
cd /root/projects/asiabsd/2027/redbaron-shim

10.3 Write malloc_shim.c

The complete source is in Appendix A. Save it as malloc_shim.c in that directory.

10.4 Write build.sh

The complete script is in Appendix B. Save it as build.sh, then:

chmod +x build.sh
./build.sh

Verbatim output:

built ./libredbaron_compat.so

10.5 Inspect the result

Verbatim output (file):

libredbaron_compat.so: ELF 32-bit LSB shared object, Intel i386, version 1 (GNU/Linux), dynamically linked, not stripped

Verbatim output (nm -D):

00001af0 T _init
000013b0 T calloc
         U environ
00001350 T free
00001260 T malloc
00001530 T realloc
000018c0 T strdup

Selected output (readelf -d):

  0x0000000e (SONAME) Library soname: [libredbaron_compat.so]
  0x00000004 (HASH)   0x1b4
  0x0000000c (INIT)   0x1af0

Three details matter:

Detail Why it matters
ELF 32-bit LSB shared object, Intel i386 It must match the 1996 binary, not the 64-bit FreeBSD host
HASH is present The old ld-linux.so.1 uses the SysV hash table, not GNU hash
INIT 0x1af0 The old loader calls DT_INIT; this is where LD_PRELOAD is stripped

10.6 Understand the compiler and linker flags

Flag Purpose
-target i386-unknown-linux-gnu Emit i386 Linux ABI, not FreeBSD
-m32 32-bit pointers and int
-O2 Optimize the small amount of generated code
-fPIC Required for a shared object
-ffreestanding Do not assume a hosted C library
-fno-builtin Do not let Clang turn loops into memcpy/memset calls
-fno-stack-protector No __stack_chk_fail dependency
-fno-asynchronous-unwind-tables No .eh_frame dependency
ld -m elf_i386 Link an i386 ELF, not the host format
-shared -soname ... Produce a loadable shared object with a stable name
--hash-style=sysv Match the old loader's hash-table expectations
-init _init Export a DT_INIT entry point
brandelf -t Linux Mark the ABI so the Linuxulator accepts it

Why not cc -shared directly? The FreeBSD driver would add FreeBSD startup objects and branding. Calling ld explicitly keeps the output a minimal i386 Linux object with exactly the dynamic tags the 1996 loader expects.

10.7 Install the shim

install -m 755 libredbaron_compat.so \
  /compat/linux/usr/lib/redbaron/libredbaron_compat.so

The wrapper refers to the Linux-side path /usr/lib/redbaron/libredbaron_compat.so, which resolves to this file inside /compat/linux.

10.8 Install the launcher

The complete script is in Appendix C. Save it as redbaron, then:

install -m 755 redbaron /usr/local/bin/redbaron

10.9 Run it

/usr/local/bin/redbaron -url http://openbsd.org

The -url argument is passed through unchanged to the original binary. The wrapper's exec means the shell is replaced, so signals and exit status go to the browser.

10.10 If it does not work

Symptom First thing to check
Cannot open ...libredbaron_compat.so The host file exists and the wrapper's check passes
unsupported file layout A FreeBSD tool inherited LD_PRELOAD; do not export it
ld-elf.so.1 errors from sh _init did not run; check readelf -d for INIT
Immediate SIGSEGV at 0x0 The shim did not intercept malloc; check nm -D and LD_PRELOAD
Window appears but page is blank Check the HTTP request in ktrace; see §11
Lucida font warning Cosmetic; see §12

11. Verification

The problem. "It did not crash" is weaker than "it fetched and rendered the page". The checks below separate process survival, window creation, network traffic, and visual output.

11.1 Process survival

Selected output (12-second timeout, both URLs; command lines removed):

openbsd_status=124
RedHat Redbaron: Linux i486 (Linux 2.0) Version 3.10
google_status=124
RedHat Redbaron: Linux i486 (Linux 2.0) Version 3.10
Warning: Cannot convert string "-*-lucidatypewriter-medium-r-normal-*-14-*-iso8859-1" to type FontStruct
sh: /bin/netstat: not found

timeout(1) returns 124 when it kills the child because the time limit expired. In other words, the browser was still running after 12 seconds.

11.2 Window creation

Selected output (xwininfo -root -tree):

0xe0011e "OpenBSD": ("mosaicShell" "redbaron")  700x600+0+24  +1+25

The title is OpenBSD, the widget class is mosaicShell, and the application class is redbaron. That is the browser's own window, not a helper or a splash screen.

11.3 Network fetch

Selected output (kdump of a successful run, request):

"GET / HTTP/1.0
User-Agent: Redbaron/3.10 Linux2.0.0 RedHat/250 (Nov 26 1996)
Accept: application/x-ftp-list
...
Accept: */*; q=0.100
Accept-Language: en
"

Selected output (kdump, response):

"HTTP/1.0 200 OK
Connection: close
Content-Length: 3622
Content-Type: text/html
Date: Thu, 12 Nov 2026 06:59:53 GMT
Last-Modified: Tue, 20 Oct 2026 01:08:43 GMT
Server: OpenBSD httpd

<!doctype html>
<html lang=en id=project-main>
...
<title>OpenBSD</title>

The browser sent a real HTTP/1.0 request and received a 200 response from OpenBSD httpd.

11.4 Visual proof

The screenshot at /root/projects/asiabsd/2027/redbaron-openbsd.png shows the browser window with the OpenBSD homepage, including the "About OpenBSD", "Getting OpenBSD", "Getting Source", and "OpenBSD Resources" sections.

Red Baron 3.10 rendering the OpenBSD homepage

11.5 Verification summary

Check Command Result
Process survives 12 s timeout 12 /usr/local/bin/redbaron -url http://openbsd.org status 124 (still running)
Second URL survives 12 s timeout 12 /usr/local/bin/redbaron -url google.com status 124 (still running)
Window exists xwininfo -display :1 -root -tree "OpenBSD": ("mosaicShell" "redbaron")
Request sent ktrace/kdump GET / HTTP/1.0
Response received ktrace/kdump HTTP/1.0 200 OK, Server: OpenBSD httpd
Page rendered xwd + PNG conversion redbaron-openbsd.png
Helpers do not inherit preload kdump ... | grep ENVS | grep LD_PRELOAD count 0 (§9)

11.6 Integrity checks and evidence limits

Selected output — historical hash record. These hashes were recorded in the existing investigation, not recomputed for this document. They identify the reported files; without a trusted original reference, they do not independently prove that the browser and libc5 were unmodified:

7d37ac54146bc9c23fb5f2eb1d0521d0d3e02737a97fccb0fc243252737d1d84  redbaron_3.10
2a2341f5d1e6c31f340efb42557babdb1229dcb978ef2ccf4088004e84bab555  libc.so.5.3.12
9f97de3dffd0a7994d5e35c3619d96fe643045459cfe40c516f80caf871a0bc0  libredbaron_compat.so
c15d8c64a51f9b39538eedab3ebb60dd435fcad12a3ef6aab008e619c98dac7f  /usr/local/bin/redbaron

What this verification does not prove. The runs were short (12 seconds), single-user, on one host, with no memory-pressure test, no long soak, no automated allocator unit test, and no adversarial input. google.com survives but is not a useful rendering test because the browser cannot follow the HTTPS redirect. The helper check shows the variable is absent from the recorded ENVS calls; it does not prove every future helper path is safe.


12. Known limitations and what not to expect

Limitation Effect Why
No TLS google.com redirects to HTTPS, which this browser cannot follow 1996 browser; no TLS stack
Missing /bin/netstat in the compatibility tree sh: /bin/netstat: not found when Red Baron queries interfaces The compatibility tree has no /bin/netstat
Lucida font warning Warning: Cannot convert string "-*-lucidatypewriter-..." once at startup The imported font set lacks Lucida; the browser falls back
Memory retained until exit RSS grows with the high-water mark of mapped blocks free marks blocks reusable but never munmaps them (§7)
Single-threaded assumption Not safe if a library starts threads libc5 and Red Baron are single-threaded
Double-free tolerance has a boundary A free, a reuse, then a second free through the stale pointer can free a live block The observed Red Baron calls are consecutive (§7.4)
Foreign pointers are assumed readable free() reads the 16 bytes before the pointer. A readable header with nonmatching magic is ignored and leaks; an unreadable header faults, and coincidental matching magic can corrupt the free list No foreign-pointer failure was identified in the tested runs; absence is not proven
Five allocator entries interposed memalign and valloc still resolve to libc5; posix_memalign is not in libc5 at all The tested libraries import only malloc/calloc/realloc/free/strdup
memalign path is unverified If a future library calls memalign, libc5's implementation may use the broken brk path Inference: no tested library calls it
POC is not the installed allocator No reuse, no header validation, no magic; RSS grows with total allocation §14; use malloc_shim.c for real runs
Google is not a useful test page Redirect to HTTPS plus helper errors Use http://openbsd.org as the functional test

About the font warning. It is cosmetic. The page still renders, and the menu bar, toolbar, and links are usable. If a cleaner startup log matters, add a Lucida-compatible font to the X server's font path or provide an X resource that substitutes a present family.

About memalign. The shim deliberately does not interpose it. If a future library calls memalign, the call reaches libc5's implementation, which may use the broken brk path. The current Red Baron and X11 libraries do not call it, so the shim is sufficient for this workload. Adding memalign/valloc wrappers is straightforward if that changes.


13. Correction and decision log

# Earlier position Correction Where
1 The crash might be a missing X11 resource or library The first fault is a NULL write caused by a failed malloc §2, §3
2 security.bsd.map_at_zero=1 might help It only hides the NULL; returned to 0 §2
3 An mmap/munmap allocator is enough Red Baron double-frees; munmap makes the second free fault §5 → §6
4 Every block in a power-of-two bin is large enough A bin can mix 8 KiB and 12 KiB mappings; check each candidate §7 → §8
5 FreeBSD LD_32_PRELOAD/LIB_32_PRELOAD might select the shim The Linux loader reads LD_PRELOAD §9
6 Exporting LD_PRELOAD in the caller's shell is harmless FreeBSD tools then try to load an i386 Linux .so; the wrapper sets it internally §9
7 A preload object leaks LD_PRELOAD to helpers _init strips it; verified 0 of 7 helper ENVS records contain it §9
8 Free lists are required to survive the double free Keeping blocks mapped with a no-op free() is sufficient for the observed pattern; the POC survives both URLs §7.4, §14
9 Modern Linux may return a page-rounded logical break on success Linux rounds the mapping but returns the requested logical break §4
10 Read-only freed pages necessarily fault on the second free The shown magic check is a read; this alternative was not tested §6

Final decision table:

Approach Startup OpenBSD page Google page Preserves originals Chosen
Do nothing crash at strcpy(NULL, ...) no no yes no
Patch libc5 brk (not attempted) — — — no no
mmap + munmap shim works yes crash (double free) yes no
mmap, never unmap, no free lists (POC) works yes survives yes no (POC only)
mmap + free lists, never unmap works yes survives yes yes
Replace libc5 with glibc (not tested) ABI compatibility not established untested untested no no

14. The minimal POC: which allocator features are actually required

The problem. After the full shim worked, a narrower question remained: which parts of the allocator are necessary for this browser, and which only make it nicer?

The experiment. redbaron-shim/malloc_poc.c keeps the Linux mmap syscall and the _init scrub, then removes everything else:

  • one header field, mapping_length;
  • free() is a no-op;
  • no magic values, free bins, or block reuse;
  • realloc() grows in place when the mapping has room, otherwise allocates and copies the old mapping's capacity.

The point is not that this is a better allocator. It is that it isolates the property the double free needs. A no-op free() is sufficient for the observed consecutive double free; free lists are extra.

Build. The source carries its own command line, but the reproducible form is:

cd /root/projects/asiabsd/2027/redbaron-shim
cc -target i386-unknown-linux-gnu -m32 -O2 -fPIC \
    -ffreestanding -fno-builtin -fno-stack-protector \
    -fno-asynchronous-unwind-tables -c malloc_poc.c -o malloc_poc.o
ld -m elf_i386 -shared -soname libredbaron_poc.so \
    --hash-style=sysv -init _init -o libredbaron_poc.so malloc_poc.o
brandelf -t Linux libredbaron_poc.so

Selected output (file):

libredbaron_poc.so: ELF 32-bit LSB shared object, Intel i386, version 1 (GNU/Linux), dynamically linked

The built object is 3,348 bytes; the source is 237 lines and 5,944 bytes. The full shim's object is 4,364 bytes; the source is 350 lines. The line count is not the point, but the missing concepts are: bins, magic, reuse, and header validation.

Selected output — reported historical functional test. With a temporary wrapper pointing LD_PRELOAD at the POC object:

openbsd_status=124
google_status=124
0xe0011e "OpenBSD": ("mosaicShell" "redbaron")  700x600+0+24  +1+25

Both processes were still alive when timeout killed them. The OpenBSD window was the browser's own window.

Removal tests. Each row removes one entry point or feature from the POC and runs the same two URLs:

Variant Result
Current POC both status 124
calloc removed both status 1, Error: Cannot perform calloc
realloc removed both status 139, SIGSEGV after the version banner
strdup removed both status 124; libc5's implementation is sufficient for these pages
_init removed both status 124, but helpers print ld-elf.so.1: Cannot open ...
in-place realloc removed both status 124

What the removals say.

  • calloc and realloc are reached and cannot be dropped. libc5's own versions fall back to the broken brk allocator or expect libc5 headers.
  • strdup is droppable in the tested paths, but whether every hidden path is safe was not proven. Keeping it makes the replacement boundary explicit. The full shim keeps it.
  • _init is not needed for process survival, but removing it makes every FreeBSD helper print a loader error. It stays.
  • In-place realloc is not required for these two pages, but it avoids moving buffers that old code may have aliased. It stays.
  • Free lists are not required. They reduce address-space growth through reuse; they do not establish a fixed bound.

Limits. The POC never reclaims memory. free() accepts any pointer without reading its header, and realloc() trusts the header behind its argument. It was tested only by launching the browser, not by a deterministic unit test. It is not installed; the wrapper still loads libredbaron_compat.so.


Appendix A: complete malloc_shim.c

Annotated reconstruction. The implementation is reproduced in full; explanatory comments have been corrected to state the limits of foreign-pointer and double-free handling. The on-disk source comments may retain the earlier wording.

/*
 * libredbaron_compat.so - a small Linux/i386 allocator for Red Baron 3.10
 * running under FreeBSD's Linuxulator.
 *
 * Why this exists
 * ---------------
 * Red Hat 4.2's libc5 (libc.so.5.3.12) implements brk(2) as:
 *
 *     newbrk = syscall(SYS_brk, addr);
 *     if (newbrk != addr) { errno = ENOMEM; return -1; }
 *
 * FreeBSD's Linuxulator rounds the break up to a page boundary, so the
 * comparison fails on the very first heap growth.  libc5 malloc() then
 * returns NULL, and Red Baron writes through that NULL pointer while
 * building its startup string.
 *
 * This object replaces malloc/calloc/realloc/free/strdup with an allocator
 * that never uses brk(2).  New blocks come from the legacy Linux i386
 * mmap(2) syscall.  Blocks are never unmapped, so a second free() can read
 * the header safely.  Freed blocks are also kept on size-class free lists
 * and reused, which reduces address-space growth; the magic check ignores
 * consecutive frees of the same block with no intervening reuse.
 *
 * It is deliberately freestanding: no libc symbols, no unwind tables, no
 * stack protector.  The only external reference is `environ`, used once at
 * load time to remove LD_PRELOAD so FreeBSD helper processes started by
 * Red Baron do not try to preload this i386 Linux object.
 *
 * Limits: single-threaded assumption (libc5 is single-threaded), memory is
 * retained until process exit.  Foreign pointers are not safely validated:
 * free() first reads the preceding header, which can fault or match by chance.
 */

typedef unsigned int u32;
typedef unsigned int size_t;

#define LINUX_SYS_MMAP      90

#define PROT_READ           0x1
#define PROT_WRITE          0x2
#define MAP_PRIVATE         0x2
#define MAP_ANONYMOUS       0x20

#define PAGE_SIZE           4096U
#define HEADER_MAGIC        0x52424d41U   /* "RBMA" - live allocation */
#define FREED_MAGIC         0x52424652U   /* "RBRF" - on a free list  */

/*
 * 32-bit address space / 4 KiB pages = at most 2^20 pages, so 20 bins
 * cover every mapping length without shifting a u32 past bit 31.
 */
#define NUM_BINS            20

struct linux_mmap_args {
    u32 addr;
    u32 len;
    u32 prot;
    u32 flags;
    u32 fd;
    u32 offset;
};

struct allocation_header {
    u32 magic;              /* HEADER_MAGIC or FREED_MAGIC */
    u32 mapping_length;     /* bytes obtained from mmap          */
    u32 requested_length;   /* bytes the caller asked for        */
    struct allocation_header *next_free;
};

static struct allocation_header *free_bins[NUM_BINS];

extern char **environ;

/*
 * Raw Linux i386 syscalls.  The kernel ABI passes the first argument in
 * ebx, so ebx must be saved around int $0x80 (the i386 PIC register).
 */
static long
linux_syscall1(long number, const void *arg)
{
    long result;

    __asm__ volatile(
        "pushl %%ebx\n\t"
        "movl %2, %%ebx\n\t"
        "int $0x80\n\t"
        "popl %%ebx"
        : "=a" (result)
        : "0" (number), "r" (arg)
        : "cc", "memory");
    return result;
}

static int
syscall_failed(long result)
{
    return (unsigned long)result >= (unsigned long)-4095L;
}

static void
copy_bytes(unsigned char *destination, const unsigned char *source,
    size_t count)
{
    size_t index;

    for (index = 0; index < count; index++)
        destination[index] = source[index];
}

static void
zero_bytes(unsigned char *destination, size_t count)
{
    size_t index;

    for (index = 0; index < count; index++)
        destination[index] = 0;
}

/*
 * One bin per power-of-two mapping size.  Bin N holds mappings in
 * [4096<<N, 4096<<(N+1)).  A request for mapping length L lands in the
 * bin whose range contains L.  Blocks in later bins are strictly larger,
 * but blocks in L's own bin are not all large enough (bin 1 holds both
 * 8 KiB and 12 KiB mappings), so take_free_block checks each candidate.
 */
static u32
bin_for_mapping(u32 mapping_length)
{
    u32 bin;
    u32 bound;

    for (bin = 0, bound = PAGE_SIZE; bin + 1 < NUM_BINS; bin++, bound <<= 1) {
        if (mapping_length < (bound << 1))
            break;
    }
    return bin;
}

static struct allocation_header *
take_free_block(u32 mapping_length)
{
    u32 bin;
    struct allocation_header **link;
    struct allocation_header *header;

    /*
     * Bins are power-of-two ranges, so a bin's first block is not
     * necessarily large enough for a request that lands in the same bin
     * (for example a 12 KiB request and an 8 KiB free block share bin 1).
     * Check mapping_length on every candidate.
     */
    for (bin = bin_for_mapping(mapping_length); bin < NUM_BINS; bin++) {
        link = &free_bins[bin];
        while (*link != (struct allocation_header *)0) {
            header = *link;
            if (header->mapping_length >= mapping_length) {
                *link = header->next_free;
                return header;
            }
            link = &header->next_free;
        }
    }
    return (struct allocation_header *)0;
}

static void
put_free_block(struct allocation_header *header)
{
    u32 bin = bin_for_mapping(header->mapping_length);

    header->next_free = free_bins[bin];
    free_bins[bin] = header;
}

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);

    header = take_free_block(mapping_length);
    if (header == (struct allocation_header *)0) {
        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->mapping_length = mapping_length;
    }

    header->magic = HEADER_MAGIC;
    header->requested_length = size;
    header->next_free = (struct allocation_header *)0;
    return (void *)(header + 1);
}

void
free(void *pointer)
{
    struct allocation_header *header;

    if (pointer == (void *)0)
        return;

    header = ((struct allocation_header *)pointer) - 1;

    /*
     * Consecutive frees of our own blocks see FREED_MAGIC and return.
     * Their headers stay mapped.  Foreign pointers are not validated safely:
     * the header read can fault, and its magic could match by chance.
     */
    if (header->magic != HEADER_MAGIC)
        return;

    header->magic = FREED_MAGIC;
    put_free_block(header);
}

void *
calloc(size_t count, size_t size)
{
    size_t total;
    void *block;

    if (count != 0 && size > 0xffffffffU / count)
        return (void *)0;
    total = count * size;

    block = malloc(total);
    if (block != (void *)0)
        zero_bytes((unsigned char *)block, total);
    return block;
}

void *
realloc(void *pointer, size_t size)
{
    struct allocation_header *header;
    void *replacement;
    size_t copy_length;
    size_t capacity;

    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;

    capacity = header->mapping_length - (u32)sizeof(*header);

    /*
     * Growing in place is not only faster: it reduces pointer churn for
     * old code that holds copies of a buffer pointer across realloc().
     */
    if (size <= capacity) {
        header->requested_length = size;
        return pointer;
    }

    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;
}

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;
}

/*
 * The old Linux ld.so.1 calls DT_INIT.  Remove LD_PRELOAD from the
 * environment as soon as this object is loaded.  Red Baron forks and
 * execs /bin/sh helpers; without this, FreeBSD's /bin/sh inherits a
 * preload request for an i386 Linux object and prints
 * "ld-elf.so.1: Cannot open ...".
 */
static int
is_ld_preload(const char *entry)
{
    static const char name[] = "LD_PRELOAD=";
    int index;

    for (index = 0; name[index] != '\0'; index++) {
        if (entry[index] != name[index])
            return 0;
    }
    return 1;
}

void
_init(void)
{
    char **source;
    char **destination;

    if (environ == (char **)0)
        return;

    source = environ;
    destination = environ;
    while (*source != (char *)0) {
        if (!is_ld_preload(*source))
            *destination++ = *source;
        source++;
    }
    *destination = (char *)0;
}

Appendix B: complete build.sh

#!/bin/sh
#
# Build libredbaron_compat.so on FreeBSD with the base Clang/LLD.
# The output is an i386 Linux shared object, not a FreeBSD object.
#
set -eu

src=$(dirname "$0")
out=${1:-"$src/libredbaron_compat.so"}

cc -target i386-unknown-linux-gnu -m32 -O2 -fPIC \
    -ffreestanding -fno-builtin -fno-stack-protector \
    -fno-asynchronous-unwind-tables \
    -c "$src/malloc_shim.c" -o "$src/malloc_shim.o"

ld -m elf_i386 -shared -soname libredbaron_compat.so \
    --hash-style=sysv -init _init \
    -o "$out" "$src/malloc_shim.o"

brandelf -t Linux "$out"
echo "built $out"

Appendix C: complete redbaron launcher

#!/bin/sh
#
# redbaron - start Red Baron 3.10 under FreeBSD's Linuxulator.
#
# The binary, its libc5, and its X11 libraries are the original 1996/1997
# Red Hat 4.2 files below /compat/linux.  The only compatibility object is
# libredbaron_compat.so, preloaded so that libc5 never calls brk(2).
#
# Important: LD_PRELOAD is set inside this script, not in the caller's
# environment.  If a FreeBSD program such as env(1) or timeout(1) inherits
# LD_PRELOAD pointing at an i386 Linux .so, FreeBSD's ld-elf.so.1 rejects it
# with "unsupported file layout" before Red Baron starts.

: "${DISPLAY:=:1}"

if [ -z "${HOME:-}" ]; then
    HOME=/home/redbaron
fi

if [ -z "${XAUTHORITY:-}" ]; then
    if [ -r "$HOME/.Xauthority" ]; then
        XAUTHORITY="$HOME/.Xauthority"
    elif [ -r /home/redbaron/.Xauthority ]; then
        XAUTHORITY=/home/redbaron/.Xauthority
    fi
fi

export DISPLAY HOME
if [ -n "${XAUTHORITY:-}" ]; then
    export XAUTHORITY
fi

# Paths as the Linux process sees them.
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

# The host path is used only to check that the object is installed.  The
# Linux dynamic loader resolves the value of LD_PRELOAD inside /compat/linux.
if [ -r /compat/linux/usr/lib/redbaron/libredbaron_compat.so ]; then
    LD_PRELOAD=/usr/lib/redbaron/libredbaron_compat.so
    export LD_PRELOAD
fi

exec /compat/linux/usr/lib/redbaron/redbaron_3.10 "$@"

Appendix D: reproduction commands and evidence artifacts

D.1 Build and install

cd /root/projects/asiabsd/2027/redbaron-shim
./build.sh
install -m 755 libredbaron_compat.so \
  /compat/linux/usr/lib/redbaron/libredbaron_compat.so
install -m 755 redbaron /usr/local/bin/redbaron

D.2 Run the functional test

timeout 12 /usr/local/bin/redbaron -url http://openbsd.org
echo "status=$?"

A status of 124 means the browser was still running when timeout killed it.

D.3 Confirm the window

xwininfo -display :1 -root -tree | grep mosaicShell

Expected line:

0xe0011e "OpenBSD": ("mosaicShell" "redbaron")  700x600+0+24  +1+25

D.4 Confirm the HTTP exchange

rm -f /tmp/kt-ob.out
HOME=/tmp/rbhome timeout 14 ktrace -i -f /tmp/kt-ob.out \
  /usr/local/bin/redbaron -url http://openbsd.org
kdump -f /tmp/kt-ob.out | grep -a -E 'GET / HTTP|HTTP/1.0 200|Server: OpenBSD'

D.5 Capture a screenshot

xwd -display :1 -root -out /tmp/ob.xwd

The XWD file can be converted to PNG with a short Python script using zlib and struct; the repository copy is redbaron-openbsd.png. The conversion reads the XWD header, honors the 24-bit pixel masks, and writes an RGB PNG.

D.6 Reproduce the original crash (careful)

Do this only with the shim unset. It will produce a core dump.

env -u LD_PRELOAD DISPLAY=:1 \
  /compat/linux/usr/lib/redbaron/redbaron_3.10 >/tmp/noshim.log 2>&1
echo "status=$?"

Expected: status=139 (128 + SIGSEGV) and a fresh redbaron_3.10.core.

D.7 Reproduce the double-free trace

The debug shim used for §6 logged allocator calls. Its preserved source, original shared object, compressed allocator log, and compressed system-call trace are now in the repository. SHA256 identifies these archived files; it is a preservation manifest, not independent proof of their provenance. The original compiler invocation was not retained. The following is a reconstructed build recipe, not a claim of byte-for-byte reproduction; compiler versions and flags can change the offsets in §6:

cc -target i386-unknown-linux-gnu -m32 -O2 -fPIC \
  -ffreestanding -fno-builtin -fno-stack-protector \
  -fno-asynchronous-unwind-tables \
  -c redbaron-shim/evidence/double-free/dbgshim.c -o /tmp/rb-dbgshim.o
ld -m elf_i386 -shared --hash-style=sysv \
  -o /tmp/rb-dbgshim.so /tmp/rb-dbgshim.o
brandelf -t Linux /tmp/rb-dbgshim.so

The archived source is an experimental allocator, preserved unchanged, rather than the installed shim with logging alone. The original run used:

LD_PRELOAD=/tmp/dbg/libredbaron_compat.so \
  /compat/linux/usr/lib/redbaron/redbaron_3.10 -url google.com

The decisive lines are the two consecutive F records for the same pointer:

M 2a3b3010 00001505
F 2a3b3010 00000000
F 2a3b3010 00000000

D.8 Evidence files referenced

File Contents
/tmp/tr-noshim.log truss of the original brk failure
/tmp/tr-dbg.log truss of the double-free crash
/tmp/dbg2.log Allocator call log for the double-free run
/tmp/kt-ob2.out ktrace of a successful OpenBSD fetch
/tmp/kt-helper3.out ktrace showing helper ENVS without LD_PRELOAD
/tmp/opencode/poc-build/poc-openbsd12.log POC 12-second OpenBSD run
/tmp/opencode/poc-build/poc-google12.log POC 12-second Google run
/root/projects/asiabsd/2027/redbaron-openbsd.png Final screenshot
/root/projects/asiabsd/2027/redbaron-shim/ Shim source, build script, launcher, POC source
/compat/linux/usr/lib/redbaron/libredbaron_compat.so Installed shim
/usr/local/bin/redbaron Installed launcher

D.9 Build and test the POC

The POC is not installed by build.sh. Build it into a temporary path, then use a wrapper that points at it:

cd /root/projects/asiabsd/2027/redbaron-shim
cc -target i386-unknown-linux-gnu -m32 -O2 -fPIC \
    -ffreestanding -fno-builtin -fno-stack-protector \
    -fno-asynchronous-unwind-tables -c malloc_poc.c -o malloc_poc.o
ld -m elf_i386 -shared -soname libredbaron_poc.so \
    --hash-style=sysv -init _init -o libredbaron_poc.so malloc_poc.o
brandelf -t Linux libredbaron_poc.so

To run it, copy the object to the Linux-side directory and make a temporary copy of the launcher whose libredbaron_compat.so string is replaced with libredbaron_poc.so. Do not overwrite the installed shim.

D.10 Check helper environments

The helper check used in §9:

rm -f /tmp/kt-helper.out
HOME=/tmp/rbhome timeout 14 ktrace -i -f /tmp/kt-helper.out \
  /usr/local/bin/redbaron -url http://openbsd.org
kdump -f /tmp/kt-helper.out | grep -a ENVS | grep -c LD_PRELOAD

Expected count: 0.


Final word

The investigation found two failures: a break-address mismatch between libc5 and the Linuxulator, and a consecutive double free in Red Baron. Once the allocator stopped using brk, the first crash disappeared; once it stopped calling munmap, the second one did too. The original Red Baron executable and the original Red Hat libraries are still exactly where they were. The installed compatibility layer is two small files: a 4.3 KiB shared object and a 47-line shell script. The 237-line POC is a third, non-installed file: it proved that the free lists are an optimization for reuse, not a requirement for surviving the double free.

http://openbsd.org renders. FTW, Baron.