# Reconstructing the ApplixWare libc3 Shim on FreeBSD 15.1

This document reconstructs the preload shim by following evidence from an
unshimmed ApplixWare process through four small source files. It does not repeat
jail, pkgbase, ISO, VNC, or library-installation instructions. It starts after
the 32-bit loader and these FreeBSD 3.5.1 i386 libraries are available:

```text
libX11.so.6
libc.so.3
libm.so.2
libgnuregex.so.2
libg++.so.4
libstdc++.so.2
```

| Stage | New responsibility | Source |
|---|---|---|
| 01 | Translate the old signal ABI to modern libc | `libc3-shim-01.c` |
| 02 | Delegate passwd lookup to modern libc | `libc3-shim-02.c` |
| 03 | Experimentally export the old `__sF` name | `libc3-shim-03.c` |
| 04 | Export old GNU C++ helper names | `libc3-shim-04.c` |

Stages are cumulative and build independently. To make each change apparent,
the stage sections show only newly added code. Stage 01 is the beginning, so
its entire file is new. `libc3_shim.c` is the flattened, self-contained
equivalent of stage 04.

From the repository directory on the host, copy the sources into the jail:

```sh
for f in \
    libc3-shim-01.c libc3-shim-02.c \
    libc3-shim-03.c libc3-shim-04.c libc3_shim.c \
    dtrace-all-calls.d dtrace-getpwuid-error.d
do
    jexec applix151 sh -c "umask 022; tee /root/$f >/dev/null" < "$f"
done
```

The `.c` files are source code. Each `cc -shared` command below turns one into
a `.so` shared library that the 32-bit runtime loader can preload.

### Allow DTrace in this jail

DTrace's `pid` provider uses the host's DTrace and `fasttrap` kernel modules.
Confirm that they are loaded on the host:

```sh
kldstat | egrep 'dtraceall|dtrace\.ko|fasttrap'
```

Do not expose DTrace by widening a devfs ruleset shared with unrelated jails.
This jail originally used shared ruleset 4, so `/etc/devfs.rules` defines a
dedicated ruleset containing the original jail devices plus the two devices
needed by the tested userspace probes:

```text
[applix151_dtrace=151]
add include $devfsrules_jail
add path dtrace unhide
add path dtrace/dtrace unhide
add path dtrace/fasttrap unhide
```

Persist the jail's selection of that ruleset:

```sh
bastille config applix151 set devfs_ruleset 151
```

For an already-running jail, create and apply the equivalent live ruleset once
instead of restarting it:

```sh
devfs rule -s 151 add include 4
devfs rule -s 151 add path dtrace unhide
devfs rule -s 151 add path dtrace/dtrace unhide
devfs rule -s 151 add path dtrace/fasttrap unhide
jail -m name=applix151 devfs_ruleset=151
devfs -m /mnt/tank/finch/usr/local/bastille/jails/applix151/root/dev \
    rule -s 151 applyset
```

If `devfs rule -s 151 show` already lists those rules, do not add them a second
time. Verify the result inside the jail:

```sh
jexec applix151 ls -l \
    /dev/dtrace/dtrace /dev/dtrace/fasttrap
```

Both devices are mode `0600`, so only jail root can run these probes. Granting
DTrace access is a deliberate debugging privilege; remove the dedicated
ruleset from the jail when it is no longer needed.

## 1. Use one repeatable test

Enter the jail and define this FreeBSD `sh` function. Use uppercase
`LD_32_PRELOAD`; names are case-sensitive. `LD_32_PRELOAD` affects 32-bit
programs, whereas plain `LD_PRELOAD` is for the native 64-bit runtime.

```sh
jexec applix151 sh

run_applix()
{
    shim=$1

    pkill -x axmain 2>/dev/null || true
    pkill -x axnet 2>/dev/null || true
    rm -f /tmp/.axnetipc

    if [ "$shim" = none ]; then
        unset LD_32_PRELOAD
    else
        LD_32_PRELOAD=$shim
        export LD_32_PRELOAD
    fi

    env \
        LD_32_LIBRARY_PATH=/usr/local/lib32/compat/applix:/usr/local/lib32/compat:/applixware1999cdrom/axdata/axshlib \
        AXHOME=/applixware1999cdrom \
        AXGFSDIR=/applixware1999cdrom/axdata/fontmetrics/gallium \
        AXLANG=english_us \
        AX_TEMP_DIR=/tmp \
        DISPLAY=:1 \
        timeout 10 /applixware1999cdrom/applix -wp
    rc=$?
    printf 'return code=%s, signal=%s\n' \
        "$rc" "$((rc >= 128 ? rc - 128 : 0))"
}
```

The `-wp` launch is a short, repeatable smoke test of the common Applix
launcher and runtime used before application-specific code is selected.
Presents is selected with `-presents` after the common runtime works.

A shell normally reports signal death as `128 + signal`. Thus return code 140
means signal 12. The conditional expression prints zero for an ordinary exit
code instead of producing a negative number.

## 2. Baseline: no shim

```sh
run_applix none
```

Observed result:

```text
Bad system call
return code=140, signal=12
```

FreeBSD names signal 12 `SIGSYS`:

```sh
awk '$3 == 12' /usr/include/sys/signal.h
```

```text
#define SIGSYS          12      /* non-existent system call invoked */
```

The status identifies how the process died, but not which call caused it.
Trace one unshimmed run:

```sh
unset LD_32_PRELOAD
env \
    LD_32_LIBRARY_PATH=/usr/local/lib32/compat/applix:/usr/local/lib32/compat:/applixware1999cdrom/axdata/axshlib \
    AXHOME=/applixware1999cdrom \
    AXGFSDIR=/applixware1999cdrom/axdata/fontmetrics/gallium \
    AXLANG=english_us \
    AX_TEMP_DIR=/tmp \
    DISPLAY=:1 \
    truss -f -o /tmp/applix-no-shim.truss \
    /applixware1999cdrom/applix -wp
rc=$?
printf 'return code=%s, signal=%s\n' \
    "$rc" "$((rc >= 128 ? rc - 128 : 0))"

egrep 'compat\.freebsd32_sigaction|SIGSYS|process killed' \
    /tmp/applix-no-shim.truss
```

Relevant trace:

```text
compat.freebsd32_sigaction() ERR#78 'Function not implemented'
SIGNAL 12 (SIGSYS) code=SI_KERNEL
process killed, signal = 12
```

`ERR#78` is `ENOSYS`:

```sh
awk '$3 == 78' /usr/include/sys/errno.h
```

```text
#define ENOSYS          78      /* Function not implemented */
```

This selects the first shim boundary: old signal calls, not passwd, stdio,
C++, or processor-count handling.

## 3. Stage 01: bridge the signal ABIs

There are two sides to this bridge:

```text
Applix + FreeBSD 3 libc ABI
    handler, one-word mask, flags
                 |
                 v
       preloaded sigaction()/sigprocmask()
                 |
                 v
FreeBSD 15 i386 libc.so.7 ABI
    handler, flags, four-word mask
```

The old side came from Applix's FreeBSD 3-era ABI and is still described by
FreeBSD's compatibility definition, `struct osigaction`, in
`/usr/src/sys/sys/signalvar.h`: handler, `osigset_t`, then flags.
`osigset_t` is one `unsigned int`.

The modern side comes from `/usr/include/sys/signal.h`, where flags precede
`sigset_t`, and `/usr/include/sys/_sigset.h`, where `_SIG_WORDS` is 4 and the
mask contains four 32-bit words. The shim uses private structures because its
exported function must accept the layout used by the old caller.

Create `/root/libc3-shim-01.c`. Everything below is new:

```c
/* Stage 01: translate the FreeBSD 3.x i386 signal ABI. */
#include <dlfcn.h>
#include <string.h>

#ifndef RTLD_LOCAL
#define RTLD_LOCAL 0
#endif

#define APPLIX_SIGSYS 12
#define APPLIX_SIG_IGN ((void (*)(int))1)

struct old_sigaction {
    void *handler;
    unsigned int mask;
    int flags;
};

struct new_sigaction {
    void *handler;
    int flags;
    unsigned int mask[4];
};

static void *libc7_h;
static int (*rl_sigaction)(int, const void *, void *);
static int (*rl_sigprocmask)(int, const void *, void *);
static void (*(*rl_signal)(int, void (*)(int)))(int);

static void
libc7_init(void)
{
    if (libc7_h)
        return;

    libc7_h = dlopen("libc.so.7", RTLD_LAZY | RTLD_LOCAL);
    if (!libc7_h)
        return;

    rl_sigaction = dlsym(libc7_h, "sigaction");
    rl_sigprocmask = dlsym(libc7_h, "sigprocmask");
    rl_signal = dlsym(libc7_h, "signal");

    if (rl_signal)
        rl_signal(APPLIX_SIGSYS, APPLIX_SIG_IGN);
}

int
sigaction(int sig, const struct old_sigaction *act, struct old_sigaction *oact)
{
    struct new_sigaction m_act;
    struct new_sigaction m_oact;
    struct new_sigaction *ap = NULL;
    struct new_sigaction *op = NULL;
    int ret;

    if (!libc7_h)
        libc7_init();

    if (act) {
        memset(&m_act, 0, sizeof(m_act));
        m_act.handler = act->handler;
        m_act.flags = act->flags;
        m_act.mask[0] = act->mask;
        ap = &m_act;
    }

    if (oact)
        op = &m_oact;

    ret = rl_sigaction ? rl_sigaction(sig, ap, op) : -1;
    if (ret == 0 && oact && op) {
        oact->handler = m_oact.handler;
        oact->flags = m_oact.flags;
        oact->mask = m_oact.mask[0];
    }

    return ret;
}

int
sigprocmask(int how, const unsigned int *set, unsigned int *oset)
{
    unsigned int m_set[4];
    unsigned int m_oset[4];
    void *sp = NULL;
    void *op = NULL;
    int ret;

    if (!libc7_h)
        libc7_init();

    memset(m_set, 0, sizeof(m_set));
    memset(m_oset, 0, sizeof(m_oset));

    if (set) {
        m_set[0] = *set;
        sp = m_set;
    }

    if (oset)
        op = m_oset;

    ret = rl_sigprocmask ? rl_sigprocmask(how, sp, op) : -1;
    if (ret == 0 && oset && op)
        *oset = m_oset[0];

    return ret;
}
```

Because the shim is preloaded first, old callers bind to its `sigaction` and
`sigprocmask` names. `dlopen("libc.so.7")` and `dlsym()` obtain explicit
pointers to the modern implementations, avoiding recursion into the shim. The
wrapper expands the old mask before the call and collapses a returned mask
afterward. Ignoring `SIGSYS` is a bring-up safeguard; the actual repair is
using working modern signal calls.

Build and run:

```sh
cc -m32 -shared -fPIC -Wall -Wextra \
    -o /usr/local/lib/libc3-shim-01.so \
    /root/libc3-shim-01.c

run_applix /usr/local/lib/libc3-shim-01.so
```

Observed result:

```text
get user name: No such file or directory
return code=1, signal=0
```

Another run may print this instead:

```text
get user name: Invalid argument
return code=1, signal=0
```

Do not choose the next wrapper from either English suffix. The DTrace evidence
below shows that the launcher calls `perror("get user name")`; `perror()`
appends the text for whatever numeric `errno` is current at that moment.
`Invalid argument` is `EINVAL` (22), while `No such file or directory` is
`ENOENT` (2):

```sh
awk '$3 == 22 || $3 == 2' /usr/include/sys/errno.h
```

```text
#define ENOENT           2      /* No such file or directory */
#define EINVAL          22      /* Invalid argument */
```

A null `getpwuid()` result does not guarantee that `errno` uniquely identifies
why no passwd entry was returned; it can describe an internal failure or retain
an earlier value. The stable evidence is the function call, its argument, and
its return value, which DTrace records below.

The process no longer dies from `SIGSYS`. Its new ordinary exit reveals the
next boundary.

## 4. Stage 02: bridge account lookup

Do not guess `getpwuid()` from the English error or begin with a grep that
already assumes the answer. Use the all-call DTrace program from
`dtrace-all-calls.d` to observe symbolized userspace calls without stopping the
process. Install it as `/root/dtrace-all-calls.d` in the jail, then run stage 01
with a large DTrace buffer:

The generic script does not contain the word `perror`; it traces every
symbolized function. These are the essential parts of
`dtrace-all-calls.d`:

```d
inline int MAX_EVENTS = 50000;

pid$target:::entry
/events < MAX_EVENTS/
{
    events++;
    printf("E %lld pid=%d tid=%d %s`%s a0=%#lx a1=%#lx a2=%#lx a3=%#lx a4=%#lx a5=%#lx\n",
        (long long)timestamp, pid, tid, probemod, probefunc,
        (uintptr_t)arg0, (uintptr_t)arg1, (uintptr_t)arg2,
        (uintptr_t)arg3, (uintptr_t)arg4, (uintptr_t)arg5);
}

pid$target:::return
/events < MAX_EVENTS/
{
    events++;
    printf("R %lld pid=%d tid=%d %s`%s result=%#lx\n",
        (long long)timestamp, pid, tid, probemod, probefunc,
        (uintptr_t)arg1);
}
```

`pid` selects DTrace's userspace-function provider, `$target` means the process
created with `-c`, and the empty module and function fields are wildcards.
`entry` fires only when execution enters a symbolized function; `return` fires
when that function returns. `probemod` and `probefunc` are names supplied by
the probe that fired. The first `printf()` therefore writes an `E` record with
the library and function actually entered; the script does not choose those
names in advance. The six `argN` values are raw candidate argument slots
because the generic probe does not know each C prototype.

```sh
export LD_32_LIBRARY_PATH=/usr/local/lib32/compat/applix:/usr/local/lib32/compat:/applixware1999cdrom/axdata/axshlib
export LD_32_PRELOAD=/usr/local/lib/libc3-shim-01.so
export AXHOME=/applixware1999cdrom
export AXGFSDIR=/applixware1999cdrom/axdata/fontmetrics/gallium
export AXLANG=english_us
export AX_TEMP_DIR=/tmp
export DISPLAY=:1

dtrace -q -b 64m -x switchrate=10hz -x evaltime=postinit \
    -o /tmp/applix-all-calls.log \
    -s /root/dtrace-all-calls.d \
    -c '/applixware1999cdrom/applix -wp'
```

The larger buffer matters: tracing every symbolized function with the default
buffer dropped events in the first test. Check the end of the log rather than
reading the whole file:

```sh
tail -120 /tmp/applix-all-calls.log
```

The final call sequence reveals the candidate without a preselected function
name:

```text
E ... libc.so.3`getpwuid a0=0 ...
...
R ... libc.so.3`getpwuid result=0
E ... libc.so.3`perror a0=0x8059693 ...
...
E ... libc.so.3`exit a0=0x1 ...
```

`E` means function entry and `R` means return. The raw first argument to
`getpwuid()` is zero, its pointer result is zero (`NULL`), `perror()` follows,
and the process exits with status 1. Specifically,
``E ... libc.so.3`perror`` is an entry probe generated when execution enters
the symbol named `perror` in `libc.so.3`. That record is how we know the
process calls `perror()`; the conclusion does not come from recognizing the
usual `prefix: error text` format. It does not yet prove what string was passed
because `a0=0x8059693` is only an address. Also, `perror()` returns `void`, so
any raw return-register value printed for it has no meaning. The generic
tracer cannot know that its first argument is a string, so use a small targeted
probe only after the all-call log identifies `getpwuid`, `dbopen`, `perror`,
and `strerror`:

```d
pid$target::getpwuid:entry
{
    printf("%s`%s(%u)\n", probemod, probefunc, (uint32_t)arg0);
    ustack(6);
}

pid$target::getpwuid:return
{
    printf("%s`%s returned 0x%lx\n",
        probemod, probefunc, (uintptr_t)arg1);
}

pid$target::dbopen:entry
{
    printf("%s`%s(\"%s\")\n",
        probemod, probefunc, copyinstr((uintptr_t)arg0));
}

pid$target::perror:entry
{
    printf("%s`%s(\"%s\")\n",
        probemod, probefunc, copyinstr((uintptr_t)arg0));
}

pid$target::strerror:entry
{
    printf("%s`%s(%d)\n", probemod, probefunc, (int)arg0);
}
```

The targeted script applies the known C prototypes. At a function-entry probe,
`arg0` is the first argument. At a `pid` return probe, `arg1` is the raw return
value. Thus it prints `getpwuid`'s `uid_t` argument as an integer and its
`struct passwd *` result as an address. `perror`, `dbopen`, and `strerror` were
only selected after their names appeared in the generic trace. For the first
two, `copyinstr(arg0)` safely copies the NUL-terminated string from the target
process, turning the raw pointer into the text it addresses.

The repository file `dtrace-getpwuid-error.d` contains that probe and the copy
step above installs it as `/root/dtrace-getpwuid-error.d`. Run it with the same
exported environment:

```sh
dtrace -q -x evaltime=postinit \
    -s /root/dtrace-getpwuid-error.d \
    -c '/applixware1999cdrom/applix -wp'
```

The combined function, argument, return, provider, and stack evidence is:

```text
libc.so.3`getpwuid(0)
    libc.so.3`getpwuid+0x1
    applix`0x804c7e9
libc.so.3`dbopen("/etc/spwd.db")
libc.so.3`getpwuid returned 0x0
libc.so.3`perror("get user name")
libc.so.3`strerror(2)
```

The `perror` entry probe fires only for an actual call and
`copyinstr(arg0)` reads the string at its first-argument address. Consequently,
the line ``libc.so.3`perror("get user name")`` proves both the function and its
argument. The following `strerror(2)` explains the `No such file or directory`
suffix. These facts were measured; they were not inferred merely from the
wording printed on the terminal.

If the visible suffix is `Invalid argument`, the last line is instead:

```text
libc.so.3`strerror(22)
```

The suffix changes because the numeric `errno` passed to `strerror()` changes;
the next debugging step does not. In both cases, DTrace links the message to
libc3 `getpwuid(0)`: it calls `dbopen("/etc/spwd.db")`, returns `NULL`, and
immediately calls `perror("get user name")`. A focused import check can confirm
that the launcher expects another object to provide the function:

```sh
nm -D /applixware1999cdrom/applix | grep ' U getpwuid$'
```

```text
         U getpwuid
```

In `nm` output, `U` means the current ELF object uses a dynamic symbol but does
not define it. It does not mean the whole process lacks a provider. Normally
`libc.so.3` provides this name. The all-call trace discovers the function; the
targeted DTrace program then proves its provider, UID argument, database path,
caller, null result, and connection to the printed message without stopping
the process.

Check the jail's current account database independently:

```sh
getent passwd 0
getent passwd applix
printf 'applix lookup rc=%s\n' "$?"
```

```text
root:*:0:0:Charlie &:/root:/bin/sh
applix lookup rc=2
```

UID 0 is the existing `root` account. There is no `applix` account, but that is
irrelevant to this failure: the observed function is the numeric lookup
`getpwuid(0)`, not `getpwnam("applix")`.

```text
Applix FindAxMain -- getpwuid(0) --> FreeBSD 3.5.1 libc.so.3
                                       calls dbopen("/etc/spwd.db"), returns NULL

Applix FindAxMain --> preload wrapper --> FreeBSD 15 libc.so.7 getpwuid(0)
                                          returns the root passwd entry
```

The old implementation came from `libc.so.3` in the FreeBSD 3.5.1 archive.
The replacement comes from the jail's official 32-bit
`/usr/lib32/libc.so.7`. These observations prove that libc3 fails to retrieve
UID 0 from the current database. They do not, by themselves, identify the
precise internal database-format or key-decoding incompatibility. The stage-02
result is the runtime check that the `struct passwd` fields Applix uses are
compatible across this boundary.

Relative to stage 01, add these headers and resolver slots:

```c
#include <sys/types.h>
#include <errno.h>
#include <pwd.h>

static struct passwd *(*rl_getpwuid)(uid_t);
static struct passwd *(*rl_getpwnam)(const char *);
```

Add these assignments to `libc7_init()` after the signal lookups:

```c
    rl_getpwuid = dlsym(libc7_h, "getpwuid");
    rl_getpwnam = dlsym(libc7_h, "getpwnam");
```

Add the exported wrappers:

```c
struct passwd *
getpwuid(uid_t uid)
{
    if (!libc7_h)
        libc7_init();

    if (rl_getpwuid)
        return rl_getpwuid(uid);

    errno = ENOENT;
    return NULL;
}

struct passwd *
getpwnam(const char *name)
{
    if (!libc7_h)
        libc7_init();

    if (rl_getpwnam)
        return rl_getpwnam(name);

    errno = ENOENT;
    return NULL;
}
```

Only `getpwuid(0)` was observed on this startup path. `getpwnam` was added as a
defensive counterpart because it enters the same old account-lookup subsystem;
the trace does not prove that this launcher path calls it. If libc7 or a symbol
cannot be opened, either wrapper reports a normal lookup failure rather than
calling a null pointer.

Build and run:

```sh
cc -m32 -shared -fPIC -Wall -Wextra \
    -o /usr/local/lib/libc3-shim-02.so \
    /root/libc3-shim-02.c

run_applix /usr/local/lib/libc3-shim-02.so
```

Observed result:

```text
return code=0, signal=0
```

The launcher returns success and leaves its helpers running:

```text
/applixware1999cdrom/axdata/axnet /tmp/.axnetipc -fork
/applixware1999cdrom/axdata/axmain -helper ... -servicename axmain:root::1
```

Stage 02 is the first stage that passes the common smoke test. Later stages add
coverage found by inspecting libraries; they do not move to a new return code.

## 5. Read dynamic symbols correctly

Once `axmain` loads the modules, inspect their dynamic symbol tables:

```sh
nm -D /applixware1999cdrom/axdata/axshlib/*.so |
    egrep ' U (__sF|__builtin|__pure|__register|__find|__unwind)'
```

The important `nm -D` letters are:

- `U`: undefined in this object; another loaded object must provide it.
- `T`: this object defines executable code with that name.
- `B`: this object defines zero-initialized global storage with that name.
- `D`: this object defines initialized global storage with that name.

`readelf -Ws file.so` shows the same facts with type, binding, visibility,
size, version, and an `UND` section index. `nm -D` is sufficient for this
name-level investigation. Neither tool alone proves that a `U` symbol is
missing from the complete process; search every loaded provider.

## 6. Stage 03: the `__sF` experiment

An Applix module contains:

```text
         U __sF
```

`__sF` was the old libc global array containing the three standard `FILE`
objects. The two library sides are visible directly:

```sh
nm -D /usr/local/lib32/compat/applix/libc.so.3 | grep ' __sF$'
nm -D /usr/lib32/libc.so.7 | grep ' __sF$'
```

```text
0007116c D __sF                 # FreeBSD 3.5.1 libc.so.3
                               # no result from FreeBSD 15 libc.so.7
```

Stage 03 added storage under the old name. Its entire new source is:

```c
/* Stage 03: stage 02 plus the old exported stdio object. */
#include <stdio.h>

FILE __sF[3];

#include "libc3-shim-02.c"
```

Build and run:

```sh
cc -m32 -shared -fPIC -Wall -Wextra \
    -o /usr/local/lib/libc3-shim-03.so \
    /root/libc3-shim-03.c

run_applix /usr/local/lib/libc3-shim-03.so
```

Observed result:

```text
return code=0, signal=0
```

This does not prove the new object was necessary: stage 02 already returned
zero, and loaded `libc.so.3` already exports `__sF`. There is also an ABI risk:
stage 03 allocates `FILE` objects using FreeBSD 15 headers, while old code
expects the FreeBSD 3 `FILE` layout. Because a preload is searched first, this
definition can override libc3's authentic object.

Stage 03 records how the historical shim was assembled, but the provider check
does not justify `__sF` as a required bridge here. Code that actually accesses
the object needs a trace or debugger test before this definition is retained.

## 7. Stage 04: bridge old GNU C++ helper names

The FreeBSD 3.5.1 C++ libraries refer to an older GNU C++ runtime interface:

```sh
for f in \
    /usr/local/lib32/compat/applix/libg++.so.4 \
    /usr/local/lib32/compat/applix/libstdc++.so.2
do
    echo "$f"
    nm -D "$f" |
        egrep ' U (__builtin|__pure|__register|__find|__unwind)'
done
```

Observed names include:

```text
U __builtin_new
U __builtin_delete
U __builtin_vec_new
U __builtin_vec_delete
U __pure_virtual
U __register_exceptions
U __find_first_exception_table_match
U __unwind_function
```

A scan of the remaining Applix, FreeBSD 3 compatibility, and FreeBSD 15 lib32
objects found no `T`, `B`, `D`, or weak definition for these names. Unlike
`__sF`, these references lacked another provider in the tested runtime.

The bridge maps old GNU C++ names required by `libg++.so.4` and
`libstdc++.so.2` to basic C allocation and termination services. Add only this
code in `libc3-shim-04.c`:

```c
/* Stage 04: stage 03 plus old GNU C++ runtime entry points. */
#include <stdlib.h>

#include "libc3-shim-03.c"

void *
__builtin_new(size_t size)
{
    if (size == 0)
        size = 1;
    return malloc(size);
}

void
__builtin_delete(void *ptr)
{
    free(ptr);
}

void *
__builtin_vec_new(size_t size)
{
    if (size == 0)
        size = 1;
    return malloc(size);
}

void
__builtin_vec_delete(void *ptr)
{
    free(ptr);
}

void
__pure_virtual(void)
{
    abort();
}

void
__register_exceptions(void *table __attribute__((unused)))
{
}

void *
__find_first_exception_table_match(void *pc __attribute__((unused)))
{
    return NULL;
}

void
__unwind_function(void *frame __attribute__((unused)))
{
}
```

| Old entry point | Shim behavior | Limitation |
|---|---|---|
| `__builtin_new`, `__builtin_vec_new` | Allocate with `malloc`; turn size 0 into 1 | No old C++ new-handler loop |
| `__builtin_delete`, `__builtin_vec_delete` | Release with `free` | Assumes matching allocation behavior |
| `__pure_virtual` | Abort an invalid pure-virtual call | Deliberately cannot continue |
| Exception registration/search/unwind names | No-op or return no match | No cross-runtime C++ exception unwinding |

This is a compatibility surface for the tested startup paths, not a complete
historical GNU C++ runtime. Old C++ exceptions crossing it remain unsupported.

Build and run:

```sh
cc -m32 -shared -fPIC -Wall -Wextra \
    -o /usr/local/lib/libc3-shim-04.so \
    /root/libc3-shim-04.c

run_applix /usr/local/lib/libc3-shim-04.so
```

Observed result:

```text
return code=0, signal=0
```

An unchanged zero proves only that the addition did not stop this smoke test.
`nm -D` proves stage 04 exports the names; it does not prove every helper ran.

## 8. Verify the progression and final shim

```sh
for f in /usr/local/lib/libc3-shim-0[1-4].so
do
    echo "$f"
    nm -D "$f" |
        egrep ' (sigaction|sigprocmask|getpwuid|getpwnam|__sF|__builtin_new|__builtin_delete|__builtin_vec_new|__builtin_vec_delete|__pure_virtual|__register_exceptions|__find_first_exception_table_match|__unwind_function)$' |
        sort
done
```

Expected progression:

```text
01: T sigaction, T sigprocmask
02: stage 01 plus T getpwuid, T getpwnam
03: stage 02 plus B __sF
04: stage 03 plus the T GNU C++ helper functions
```

Compile the flattened final source:

```sh
cc -m32 -shared -fPIC -Wall -Wextra \
    -o /usr/local/lib/libc3_shim.so \
    /root/libc3_shim.c

run_applix /usr/local/lib/libc3_shim.so
```

Observed result:

```text
return code=0, signal=0
```

The shim is a modern 32-bit FreeBSD 15 shared library:

```sh
readelf -d /usr/local/lib/libc3_shim.so | grep NEEDED
```

```text
Shared library: [libc.so.7]
```

Thus the process contains old `libc.so.3` for Applix and modern `libc.so.7`
for narrow delegated operations. Loading two libc ABIs is fragile; the shim
must remain small and bridge only boundaries supported by evidence.

Trace the final signal path:

```sh
env \
    LD_32_LIBRARY_PATH=/usr/local/lib32/compat/applix:/usr/local/lib32/compat:/applixware1999cdrom/axdata/axshlib \
    LD_32_PRELOAD=/usr/local/lib/libc3_shim.so \
    AXHOME=/applixware1999cdrom \
    AXGFSDIR=/applixware1999cdrom/axdata/fontmetrics/gallium \
    AXLANG=english_us \
    AX_TEMP_DIR=/tmp \
    DISPLAY=:1 \
    timeout 6 truss -f -o /tmp/applix-final.truss \
    /applixware1999cdrom/applix -builder

egrep 'compat\.freebsd32_sigaction|compat\.sigprocmask|freebsd32_sigaction\(|sigprocmask\(' \
    /tmp/applix-final.truss | head
```

Relevant result:

```text
freebsd32_sigaction(SIGSYS, ...) = 0
freebsd32_sigaction(SIGINT, ...) = 0
freebsd32_sigaction(SIGUSR1, ...) = 0
sigprocmask(SIG_BLOCK, ...) = 0
```

The failing `compat.freebsd32_sigaction() ERR#78` call is absent. This confirms
the demonstrated syscall bridge: stage 01 converts the old signal arguments
and reaches working FreeBSD 15 interfaces.

## 9. Start Presents

After the common launcher succeeds, use the final preload with Presents:

```sh
env \
    LD_32_LIBRARY_PATH=/usr/local/lib32/compat/applix:/usr/local/lib32/compat:/usr/local/applixware/axdata/axshlib \
    LD_32_PRELOAD=/usr/local/lib/libc3_shim.so \
    AXHOME=/usr/local/applixware \
    AXGFSDIR=/usr/local/applixware/axdata/fontmetrics/gallium \
    AXLANG=english_us \
    AX_TEMP_DIR=/tmp \
    DISPLAY=:1 \
    /usr/local/applixware/applix -presents
```

Use a writable `/usr/local/applixware` tree because Applix writes profile and
state files under `AXHOME`; the mounted CD is read-only. The shim does not need
a Presents-specific interposer: `-presents` is dispatched after the common
32-bit loader, libc3, account, signal, and old C++ boundaries are crossed.

## 10. What the evidence proves

- No shim: old signal handling reaches an unimplemented compat syscall and
  dies with `SIGSYS`.
- Stage 01: signal ABI translation removes `SIGSYS` and exposes passwd lookup.
- Stage 02: DTrace proves the failing call is libc3 `getpwuid(0)` returning
  `NULL`, followed by `perror("get user name")`; delegating that lookup to
  libc7 makes the common launcher return zero and leaves `axmain` and `axnet`
  running.
- Stage 03: exports `__sF`, but libc3 already provides the authentic object;
  current evidence does not establish that this override is necessary.
- Stage 04: supplies old GNU C++ names that had no provider, but the smoke test
  does not validate complete historical exception behavior.
- Final `truss`: successful modern signal calls replace the obsolete call.

Return codes show progress, `truss` identifies system-call boundaries,
`nm -D` shows per-object requirements and providers, and `readelf` describes
ELF metadata. No one tool proves the entire runtime story by itself.
