$ uname -a A_BLOG_ABOUT_UNIX_TOOLS_AND_THE_BEAUTY_OF_SIMPLE_SYSTEMS
SYS.YEAR  2026
← Back to articles
2026-09-06ARTICLE

Baron Invest

A Browser, a Null Pointer, and a 29-Year ABI Gap

A forensic case study of Red Baron 3.10 on FreeBSD Linuxulator

Abstract

Red Baron 3.10, the Motif browser distributed with Red Hat Linux 4.2 in 1997, crashed at startup when run with its original Linux/i386 userspace in a FreeBSD 15.1 Bastille jail. This paper follows the failure from system-call trace to machine instruction. The Linux loader found every required library, but the first observed heap extension returned a page-rounded address rather than the byte address requested through brk. A core dump showed libc5 strcpy writing through a null destination. Disassembly traced that null pointer through Red Baron's SM_Malloc wrapper to imported libc5 malloc.

The observations are consistent with libc5 treating the differing brk result as failed heap growth, although the allocator comparison itself was not disassembled. A freestanding Linux/i386 LD_PRELOAD library bypassed that path by implementing malloc, calloc, realloc, free, and strdup with legacy Linux mmap and munmap calls. This paper separates directly observed results from inference, explains the investigation for readers new to binary compatibility, and includes the complete shim source.

1. System and terminology

The host was FreeBSD 15.1 on amd64. Red Baron ran inside a Bastille jail named rh42. The complete filesystem of a Red Hat Linux 4.2 VM lived below /compat, including the original loader, libc5, X11 libraries, bitmap fonts, and browser executable.

Four terms are central:

  • Linuxulator is FreeBSD's Linux system-call compatibility layer. It translates requests made with a Linux ABI into FreeBSD kernel operations. It is not a virtual machine or CPU emulator.
  • ELF is the executable format. An ELF program names an interpreter, or dynamic loader, which maps libraries and connects imported function names to implementations.
  • ABI, or application binary interface, is the machine-level agreement covering executable layout, registers, stack arguments, system calls, and linkage.
  • libc5 is the Linux C library generation used before glibc 2. Red Baron brings its original libc5 with it.

A 32-bit Linux program and a 32-bit FreeBSD program can execute the same i386 instructions while using different operating-system ABIs. That is why installing FreeBSD's FreeBSD-runtime-lib32 could not repair this Linux libc5 process. Red Baron's interpreter, not its pointer width alone, determines its userspace runtime.

2. The problem at a glance

Before examining registers and ELF tables, a novice reader can use this simplified model:

Original path
-------------
Red Baron -> libc5 malloc -> Linux brk -> differing return value
                                      -> malloc returns NULL
Red Baron -> strcpy(NULL, "Spyglass") -> SIGSEGV

Replacement path
----------------
Red Baron -> preload shim -> Linux mmap/munmap -> usable memory

malloc asks for memory and normally returns a pointer to it. A null pointer means that no allocation was supplied. strcpy(destination, source) then copies a string into the destination. Red Baron did not check the null result before using it as that destination, so the process tried to write at address zero and crashed.

The diagram states the final interpretation, not the starting assumption. Sections 4 through 7 show how each arrow was established. The exact internal reason libc5 rejected the brk result remains a strong inference rather than a directly observed comparison.

3. Method and evidence conventions

The investigation followed the bad value backward:

  1. Identify the executable and its loader.
  2. Confirm that every shared library loads.
  3. Inspect the final kernel interactions before the signal.
  4. Recover the faulting instruction and arguments from the core.
  5. Follow the null pointer back through the caller.
  6. Inspect dynamic symbols to define the complete allocator boundary.
  7. Verify which preload variable the Linux loader recognizes.
  8. Build, audit, install, and test the smallest replacement.

Addresses belong to one run and may differ elsewhere. This paper uses three labels for evidence:

  • Verbatim output is copied directly from the command shown.
  • Selected output omits unrelated lines but does not rewrite the retained lines.
  • Annotated reconstruction preserves the decisive addresses and operations while adding names or comments for teaching.

The complete original trace and core are not stored in this repository. Consequently, their surviving excerpts are identified as normalized or reconstructed rather than falsely described as raw. Commands are supplied so a future run can preserve the full artifacts.

4. Identifying the runtime

The first question was “what kind of program is this?”

Verbatim output:

$ file /compat/usr/lib/redbaron/redbaron_3.10
/compat/usr/lib/redbaron/redbaron_3.10: ELF 32-bit LSB executable, Intel 80386, dynamically linked, interpreter /lib/ld-linux.so.1, not stripped

ELF 32-bit and Intel 80386 describe data width and CPU. The decisive field is interpreter /lib/ld-linux.so.1. Linux's loader—not FreeBSD's /libexec/ld-elf32.so.1—owns library resolution and preload processing.

The imported tree was exposed at the compatibility root and the executable was branded as Linux:

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

The Linux loader's dependency report was:

Selected output:

$ LD_TRACE_LOADED_OBJECTS=1 /compat/usr/lib/redbaron/redbaron_3.10
libXt.so.6  => /usr/X11R6/lib/libXt.so.6.0
libX11.so.6 => /usr/X11R6/lib/libX11.so.6.1
libm.so.5   => /lib/libm.so.5.0.6
libdl.so.1  => /lib/libdl.so.1.7.14
libc.so.5   => /lib/libc.so.5.3.12
libSM.so.6  => /usr/X11R6/lib/libSM.so.6.0
libICE.so.6 => /usr/X11R6/lib/libICE.so.6.0

This eliminated missing shared libraries as the immediate cause. It also proved that the initial allocator came from Linux /lib/libc.so.5.3.12; no FreeBSD lib32 library entered the process.

5. Tracing the crash

FreeBSD ktrace records interactions with the kernel, and kdump renders them. A reproducible capture should retain both the binary trace and its complete text rendering:

# ktrace -di -f /tmp/redbaron.ktrace \
    env DISPLAY=:1 /compat/usr/lib/redbaron/redbaron_3.10
# kdump -f /tmp/redbaron.ktrace > /tmp/redbaron.kdump.txt
# tail -n 20 /tmp/redbaron.kdump.txt

The original full text was not retained. The surviving notes normalized away repeated PID and record-type columns:

Normalized trace excerpt:

linux_personality(0)       = 0
linux_geteuid16()          = 0
linux_getuid16()           = 0
linux_getgid16()           = 0
linux_getegid16()          = 0
linux_brk(0x082ee290)      = 0x082ef000
SIGNAL 11 (SIGSEGV) addr=0x0

Library mappings had already succeeded. The signal address indicates a likely null-pointer access. Immediately before it, brk—the operation that moves the logical end of a traditional process heap—returned a different value from the request:

$ printf 'requested = 0x%08x\nreturned  = 0x%08x\n' \
    0x082ee290 0x082ef000
requested = 0x082ee290
returned  = 0x082ef000

The result is the next 4 KiB boundary. Linux normally reports the requested logical break after success even though physical backing is page-based. At this point the mismatch was only a clue; chronology alone did not show that allocation caused the signal.

Mapping page zero was tested as a competing explanation. With security.bsd.map_at_zero=1, the same brk result and signal occurred. The control was restored to 0; leaving page zero available would weaken null-pointer protection without fixing the cause.

6. Recovering the fault from the core

A core file is a snapshot of a crashed process. Its ELF NT_PRSTATUS note contains saved registers. Modern LLDB did not understand this old Linux/i386 note layout directly, but readelf could expose it:

$ readelf -n redbaron.core
$ readelf -l redbaron.core

For a future fully reproducible capture, both command outputs and the core should be archived. The original raw note bytes are no longer available here. The recorded decode was:

EIP = 0x2840643f

EIP is the i386 instruction pointer at the fault. The core mappings placed libc5 at 0x28399000. Subtracting that base gives the offset inside the library file:

$ printf '0x%x\n' $((0x2840643f - 0x28399000))
0x6d43f

The saved disassembly was shortened during the original investigation, so it is an annotated reconstruction rather than raw objdump output:

$ objdump -d /compat/lib/libc.so.5.3.12
0006d42c <strcpy>:
   6d42c: pushl  %esi
   6d42d: movl   0x8(%esp),%esi
   6d431: movl   0xc(%esp),%edx
   ...
   6d43c: movb   (%edx),%al
   6d43e: incl   %edx
   6d43f: movb   %al,(%ecx,%edx)  # faulting store

On i386, function arguments are passed on the stack. Decoding the saved strcpy frame gave:

destination = 0x00000000
source      = 0x0826bddd

The source address belonged to Red Baron's data segment and contained Spyglass. Therefore strcpy was given a valid source but a null destination.

7. Following the null pointer to the allocator

Red Baron was not stripped, so its function names remained in the executable. The following blocks are annotated reconstructions: requested_size and the comments explain the meaning of machine operands and were not emitted by objdump.

$ objdump -d /compat/usr/lib/redbaron/redbaron_3.10
08070310 <main>:
  ...
  call SM_Malloc
  mov  %eax,0x82ea26c
  push $0x826bddd          # source: "Spyglass"
  push 0x82ea26c           # destination: SM_Malloc result
  call strcpy

An i386 function returns a pointer in %eax. main saved that result and later passed it as strcpy's destination without checking for null.

08141580 <SM_Malloc>:
  push requested_size
  call malloc@plt
  ret

The Procedure Linkage Table, or PLT, is a set of trampolines for imported functions. malloc@plt showed that SM_Malloc delegated to the allocator chosen by the Linux loader—initially libc5.

The demonstrated chain was therefore:

imported malloc returns NULL
        -> SM_Malloc returns NULL
        -> main uses NULL as strcpy destination
        -> strcpy stores at address zero
        -> SIGSEGV

Combined with the immediately preceding brk mismatch, the strongest explanation is that libc5 expected its requested byte address and interpreted the page-rounded result as failed heap growth. Proving that final internal comparison would require disassembling the relevant libc5 allocator path; this investigation did not do so.

7.1 Identifying the complete allocator family

Replacing only malloc would create an ownership problem: one allocator could create a pointer and another could try to resize or release it. The executable's dynamic symbol table showed the relevant imports.

Verbatim output:

$ nm -D /compat/usr/lib/redbaron/redbaron_3.10 | \
    grep -E 'malloc|calloc|realloc|free|strdup'
w calloc
w free
w malloc
w realloc
U strdup

U means that another loaded object must provide the function. Lowercase w is a weak undefined reference that can be satisfied by an earlier definition. The four weak functions also had R_386_JUMP_SLOT relocations, which are loader-filled PLT entries.

The five functions form one ownership boundary:

  • malloc creates ordinary allocations.
  • calloc creates zero-filled allocations.
  • realloc resizes an allocation and may receive a shim-owned pointer.
  • free must understand and release shim-owned pointers.
  • strdup creates an allocated string that may later reach free or realloc.

7.2 Are these functions obsolete?

No. The standard name is calloc, not cmalloc:

void *malloc(size_t size);
void *calloc(size_t count, size_t size);
void *realloc(void *pointer, size_t size);
void free(void *pointer);

These four remain fundamental ISO C functions and POSIX interfaces declared by <stdlib.h>. They are not deprecated. strdup is a POSIX string function that also returns allocated storage. The failure involved a particular 1997 allocator implementation interacting with a compatibility layer—not obsolete API names.

8. Selecting the preload mechanism

LD_PRELOAD, LD_32_PRELOAD, and LIB_32_PRELOAD were tested with a known Linux library while tracing loader opens.

Observed comparison:

LD_PRELOAD=/lib/libdl.so.1
    ld-linux.so.1 opens /lib/libdl.so.1

LD_32_PRELOAD=/lib/libdl.so.1
    no preload open caused by this variable

LIB_32_PRELOAD=/lib/libdl.so.1
    no preload open caused by this variable

Environment-variable names are interpreted by the dynamic loader, not by the kernel. LD_32_PRELOAD belongs to FreeBSD's 32-bit loader; it does not generically mean “preload into any 32-bit process.” Red Baron uses Linux /lib/ld-linux.so.1, which recognized Linux LD_PRELOAD.

9. Shim design, function by function

Each subsection first states the job in plain language, then connects a short excerpt to the underlying CS concept. Appendix A contains the uninterrupted buildable file.

9.1 Goals and limits

The shim must obtain memory without calling the failing libc5 allocator:

result = linux_syscall1(LINUX_SYS_MMAP, &args);
(void)linux_syscall2(LINUX_SYS_MUNMAP, header,
    header->mapping_length);

It is freestanding: no libc, errno, memcpy, compiler runtime, allocator arena, or brk state. Its only outside boundary is the Linux/i386 syscall ABI implemented by Linuxulator.

9.2 Types and constants

The target has 32-bit words, 4 KiB pages, and fixed legacy syscall numbers:

typedef unsigned int u32;
typedef unsigned int size_t;
#define LINUX_SYS_MMAP   90
#define LINUX_SYS_MUNMAP 91
#define PAGE_SIZE        4096U
#define HEADER_MAGIC     0x52424d41U /* "RBMA" */

The magic value is a recognizable ownership marker, not encryption or a security boundary.

9.3 struct linux_mmap_args

Old Linux/i386 expects syscall 90 to receive a pointer to six words:

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

They specify preferred address, length, permissions, mapping flags, file descriptor, and offset. Anonymous memory uses no file, so the final call sets fd to -1 and offset to zero.

9.4 struct allocation_header

Every returned block has a hidden 16-byte label immediately before it:

struct allocation_header {
    u32 magic;
    u32 mapping_length;
    u32 requested_length;
    u32 reserved;
};
[ magic | mapped length | requested length | reserved ][ user bytes ... ]
^ mapping base                                      ^ returned pointer

munmap needs the full mapped length; realloc needs the requested length. Four words retain 16-byte alignment.

9.5 linux_syscall1

This helper enters Linuxulator with one argument:

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

The syscall number enters in %eax, the argument pointer in %ebx, and the result returns in %eax. %ebx is preserved because i386 position-independent code may use it to locate the Global Offset Table. Standard C cannot express kernel entry directly; calling libc syscall() would reintroduce the dependency being avoided.

9.6 linux_syscall2

munmap needs two arguments—address and length:

: "0" (number), "r" (arg1), "c" (arg2)

The wrapper uses %ebx for the address and constrains the second argument to %ecx. Otherwise it follows the same int $0x80 and register-preservation rules as linux_syscall1.

9.7 syscall_failed

Raw Linux syscalls encode errors in the range -1 through -4095:

return (unsigned long)result >= (unsigned long)-4095L;

The unsigned comparison detects that high numeric range without using libc's errno translation.

9.8 copy_bytes

A local loop replaces an imported memcpy:

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

Its callers always copy between separate regions, so overlapping-copy behavior is unnecessary.

9.9 malloc

malloc prevents arithmetic overflow, includes the header, and rounds up to a page:

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

It then requests private anonymous memory and records its metadata:

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;
return (void *)(header + 1);

header + 1 advances by one complete structure and returns the first user byte.

9.10 free

free(NULL) does nothing. Otherwise the shim walks back to the hidden header:

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

An unknown pointer is ignored to avoid deliberately unmapping storage with an unknown layout. This can leak memory, and a wild pointer can still fault while the header is read; the magic marker is not complete pointer validation.

9.11 calloc

calloc checks multiplication before allocating an array:

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

Fresh anonymous mappings are guaranteed to start zero-filled, so no separate clearing loop is needed.

9.12 realloc

A failed resize must leave the original block untouched:

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

The smaller old/new length is copied. Growing preserves all old bytes; shrinking preserves only what fits. The old block is released only after allocation and copying succeed.

9.13 strdup

strdup counts through the terminating zero, allocates one extra byte, and copies the terminator too:

for (length = 0; source[length] != '\0'; length++)
    ;
copy = (char *)malloc(length + 1U);
if (copy != (char *)0)
    copy_bytes((unsigned char *)copy,
        (const unsigned char *)source, length + 1U);

Implementing it here keeps duplicated strings in the same ownership family as free and realloc.

9.14 Design tradeoffs

One mapping per allocation is slower and consumes more virtual-address space than a normal allocator. There are no arenas, free lists, or global mutable state. The design is small and bypasses brk, but it was built for this application—not as a general-purpose allocator.

10. Building and auditing

A clean build produced:

Verbatim output:

$ make clean all
rm -f malloc_shim.o libredbaron_compat.so
cc -target i386-unknown-linux-gnu -m32 -O2 -fPIC -ffreestanding  -fno-builtin -fno-stack-protector -fno-asynchronous-unwind-tables -c malloc_shim.c -o malloc_shim.o
ld -m elf_i386 -shared -soname libredbaron_compat.so  -o libredbaron_compat.so malloc_shim.o
brandelf -t Linux libredbaron_compat.so
$ file libredbaron_compat.so
libredbaron_compat.so: ELF 32-bit LSB shared object, Intel i386, version 1 (GNU/Linux), dynamically linked, not stripped

The dynamic section contained no DT_NEEDED entry:

$ readelf -d libredbaron_compat.so

Dynamic section at offset 0x798 contains 8 entries:
  Tag        Type       Name/Value
  0x0000000e (SONAME)   Library soname: [libredbaron_compat.so]
  0x00000006 (SYMTAB)   0x134
  0x0000000b (SYMENT)   16 (bytes)
  0x00000005 (STRTAB)   0x1fc
  0x0000000a (STRSZ)    57 (bytes)
  0x6ffffef5 (GNU_HASH) 0x194
  0x00000004 (HASH)     0x1c4
  0x00000000 (NULL)     0x0

DT_NEEDED is how an ELF object declares shared-library dependencies. Its absence is evidence that the shim does not require libc or a compiler helper. The public dynamic symbols were exactly the intended five:

$ readelf -Ws libredbaron_compat.so

Symbol table '.dynsym' contains 6 entries:
   Num:    Value  Size Type    Bind   Vis       Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT   UND
     1: 00001250   126 FUNC    GLOBAL DEFAULT     6 malloc
     2: 000012d0    42 FUNC    GLOBAL DEFAULT     6 free
     3: 00001300   147 FUNC    GLOBAL DEFAULT     6 calloc
     4: 000013a0   572 FUNC    GLOBAL DEFAULT     6 realloc
     5: 000015e0   438 FUNC    GLOBAL DEFAULT     6 strdup

Offsets may change with compiler versions. Architecture, ABI brand, absence of NEEDED, and the five public names are the durable checks.

11. Installation and controlled launch

The library was installed as /compat/usr/lib/redbaron/libredbaron_compat.so. The launcher used the Linux-visible path in LD_PRELOAD:

#!/bin/sh
DISPLAY=${DISPLAY:-:1}
export DISPLAY
HOME=/root
export HOME
REDBARON=/usr/lib/redbaron
export REDBARON
LD_PRELOAD=/usr/lib/redbaron/libredbaron_compat.so
export LD_PRELOAD
exec /compat/usr/lib/redbaron/redbaron_3.10 "$@"

The FreeBSD shell starts /compat/...; inside Linuxulator, the Linux loader resolves /usr/lib/redbaron/... through the compatibility root. exec replaces the wrapper shell so signals and exit status belong directly to Red Baron.

TigerVNC display :1 was configured at 24-bit depth because Red Baron did not work with its earlier 16-bit RGB565 visual. The original Red Hat bitmap font directories were also added to Xvnc's font path.

12. Results and discussion

12.1 Outcome

With the shim, 24-bit Xvnc, and legacy font paths, Red Baron initialized, opened its window on display :1, and remained running. The original executable, loader, and libc5 were unchanged.

This result proves that the mapping allocator bypassed the startup failure. It supports, but does not independently prove, the inferred internal libc5 comparison of the differing brk result.

12.2 Was this a 64-bit problem?

Not in the ordinary pointer-size sense:

Red Baron pointers and registers: 32-bit i386 ABI
Red Baron loader and libraries:    Linux/i386
Host kernel:                       FreeBSD amd64
Kernel execution path:             32-bit Linux compatibility

The host does not convert application pointers to 64 bits. Architecture may matter indirectly because a 32-bit Linux process on amd64 uses a compatibility path different from a native i386 kernel's machine-dependent path. The evidence does not isolate architecture, FreeBSD release age, common Linuxulator code, or their interaction as the sole cause.

12.3 Could an older Linuxulator work without the shim?

Yes, possibly. Historical FreeBSD Linuxulator code called obreak and returned the requested address on success:

new = (vm_offset_t)args->dsend;
tmp.nsize = (char *)new;
if (((caddr_t)new > vm->vm_daddr) && !obreak(p, &tmp))
        p->p_retval[0] = (int)new;
else
        p->p_retval[0] = (int)old;

That behavior matches the expectation inferred for libc5, making no-shim startup plausible. It does not prove that all other loader, signal, X11, and syscall behavior in a particular old release is sufficient.

12.4 Could FreeBSD 14/i386 work without the shim?

It is possible but untested:

Host Path Status
FreeBSD 15.1 amd64 32-bit Linux compatibility Failure observed without shim
FreeBSD 14 amd64 32-bit Linux compatibility Untested; may be similar
FreeBSD 14 i386 Native i386 Linux path Untested; plausibly different
Historical FreeBSD i386 Older i386 Linuxulator Source returned requested brk value; still needs testing

Release number and kernel architecture are separate variables. FreeBSD 14 amd64 would not answer the native-i386 question. Test without changing the installed launcher:

# env -u LD_PRELOAD DISPLAY=:1 \
    ktrace -di -f /tmp/redbaron-no-shim.ktrace \
    /compat/usr/lib/redbaron/redbaron_3.10
# kdump -f /tmp/redbaron-no-shim.ktrace > /tmp/redbaron-no-shim.txt
# grep -E 'linux_brk|SIGSEGV' /tmp/redbaron-no-shim.txt

An exact brk return followed by continued startup would show that this shim is unnecessary for the observed allocator problem on that kernel. Full compatibility would still require exercising X11, browsing, repeated allocation, and clean shutdown.

12.5 Limitations

The shim assumes Linux/i386, 4 KiB pages, and a 32-bit address space. It maps one region per allocation, does not attempt in-place resizing, and ignores unknown pointers in free. It has not been presented as a production or general-purpose allocator.

The investigation also has an evidence-retention limitation: the complete original core, note bytes, trace, and unannotated Red Baron disassembly were not preserved in this repository. The paper therefore distinguishes surviving verbatim tool output from normalized excerpts and reconstructions. A repeat study should archive those artifacts and disassemble the libc5 allocator branch to test the remaining causal inference directly.

13. Conclusion

The investigation established a chain rather than relying on the fact that a workaround happened to run. The Linux loader selected a complete Red Hat userspace. A differing brk return immediately preceded startup failure. The core placed the fault in strcpy with a null destination. Red Baron obtained that destination from imported libc5 malloc. ELF metadata identified all five allocation-related imports, and loader tracing selected Linux LD_PRELOAD. A dependency-free mmap allocator then allowed the browser to initialize.

The broader lesson is to identify the owning ABI first, preserve raw evidence, follow bad values backward through calling conventions, separate observation from inference, and audit the linked artifact rather than trust build flags alone.

References

  1. The Open Group, POSIX.1-2024 malloc.
  2. FreeBSD Project, Linux Binary Compatibility.
  3. FreeBSD Project, Linux emulation in FreeBSD.
  4. FreeBSD Project, historical linux_brk implementation.
  5. FreeBSD Project, stable/14 i386 source tree.

Appendix A. Complete shim source

The listing below is the complete buildable malloc_shim.c. It is uninterrupted so readers can copy it and compare it with Section 9.

/*
 * Minimal Linux/i386 allocator for Red Baron 3.10 on FreeBSD's Linuxulator.
 *
 * Red Hat 4.2 libc5 malloc returns NULL during process startup on FreeBSD 15.
 * This library deliberately has no libc dependencies and allocates each block
 * with the legacy Linux mmap(2) ABI that the bundled dynamic linker uses.
 */

typedef unsigned int u32;
typedef unsigned int size_t;

#define LINUX_SYS_MMAP      90
#define LINUX_SYS_MUNMAP    91

#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" */

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

struct allocation_header {
    u32 magic;
    u32 mapping_length;
    u32 requested_length;
    u32 reserved;
};

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 long
linux_syscall2(long number, const void *arg1, u32 arg2)
{
    long result;

    __asm__ volatile(
        "pushl %%ebx\n\t"
        "movl %2, %%ebx\n\t"
        "int $0x80\n\t"
        "popl %%ebx"
        : "=a" (result)
        : "0" (number), "r" (arg1), "c" (arg2)
        : "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];
}

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

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

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

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

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;

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