Porting external software

Native C and C++ interfaces

Compile upstream C as C and upstream C++ with the language standard it requires. System can provide a C++ entry point for a server that links C sources. POSIX applications and utilities use libc. A userspace server or driver that needs native IPC or privileged operations calls libsys with the capabilities it has been granted.

C code includes native_call.h for operation numbers and syscall entry points and native_ipc.h for message fields and IPC entry points. The C-linkage symbols are available in both libsys.a and libsys.so. System servers and drivers link the static library. C++ callers use the corresponding .hh headers for typed operations and reference-based wrappers. The C-linkage declarations are visible in C and in libsys C++ implementation files that define __LIBSYS_IMPLEMENTATION before including the headers. Keep each header pair in sync when changing the API. Both interfaces use the same operation numbers and message layout. A C caller initializes its message with {0} before filling its payload. The C++ message fields have zero initializers.

#include <native_ipc.h>

int64_t send_request(uint64_t endpoint, uint64_t request)
{
    native_message_t message = {0};
    message.words[0] = request;
    return libsys_ipc(NATIVE_OP_IPC_CALL, endpoint, &message);
}
#include <native_ipc.hh>

int64_t send_request(uint64_t endpoint, uint64_t request)
{
    native_message_t message{};
    message.words[0] = request;
    return native_ipc(native_operation::ipc_call, endpoint, message);
}

The IPC stubs return a transport status. A successful exchange may also return a service-specific status in the message. Calls that fail at the IPC layer leave the message unchanged. Timed calls and receives take a nonzero delay in platform timer ticks. A null message or thread-result pointer returns -1. See Kernel mechanisms and IPC for capabilities, badges, and reply tokens.

int64_t libsys_call(uint64_t operation, uint64_t argument, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5)

Execute a native syscall. Supply zero for unused argument words.

int64_t libsys_thread_join(uint64_t thread, uint64_t *result)

Join a worker and write its full-width result only on success.

int64_t libsys_ipc(uint64_t operation, uint64_t handle, native_message_t *message)

Transfer the message with a native IPC operation. Preserve it on failure.

int64_t libsys_ipc_call_timeout(uint64_t handle, native_message_t *message, uint64_t ticks)

Bound call rendezvous and reply by a nonzero delay in platform ticks.

int64_t libsys_ipc_receive_timeout(uint64_t handle, native_message_t *message, uint64_t ticks)

Bound receive rendezvous by a nonzero delay in platform ticks.

The System build defines _KERNEL for the microkernel. This hides userspace stub declarations while leaving the shared ABI types visible. Userspace servers and drivers under packages/servers/ use the same caller API. Scope any upstream kernel build macros to the port that requires them.

Source placement

Use contrib/<component>/ for code and assets that System will periodically synchronize with upstream. Compile the port from those checked-in sources so the build and language server see the same files. Keep closely related upstream directories at one pinned revision and preserve their original paths. For example, FreeBSD IPv4 and IPv6 share the vendor/freebsd revision.

The UFS2 service builds the indirect block mapper from FreeBSD’s stand/libsa/ufs.c and uses its sys/ufs/ufs/dinode.h layout at revision 4ba6fd2ef5a739b6fdc955890d27e07ae8794fb3. The vendor/freebsd snapshot preserves the original notices and archive provenance. The port replaces loader device calls with a bounded sector reader supplied by the System service. It uses the FreeBSD cylinder-group inode rotor and fragment extension routines from sys/ufs/ffs/ffs_alloc.c. It adapts the ffs_indirtrunc traversal from sys/ufs/ffs/ffs_inode.c to bounded sector callbacks. The standalone mapper’s indirect path also drives allocation, following FFS’s detached block initialization and parent-pointer publication order. The service owns the sector buffers, allocation summaries, and write ordering.

The MS-DOS filesystem service builds the allocation table decoder and cluster allocation, release, and free-space walks from Linux fs/fat/fatent.c at revision f4585067150b85e33f60876149a6e742928da75e. The port replaces Linux buffer heads with bounded sector reads and explicitly handles packed FAT12 entries split across two sectors. The port uses the FAT timestamp conversions from Linux’s fs/fat/misc.c with UTC. System owns filesystem IPC, VFAT directory traversal, and geometry checks. The server package ships Linux’s license text with the userspace FAT binary.

The ext4 service builds its extent-node checks and search from Linux fs/ext4/extents.c at the same revision. The native adapter supplies node bytes through bounded partition I/O and owns inode and directory handling. The port uses the Linux ordering and parent-index checks, the on-disk distinction between initialized and unwritten extents, ext4_ext_grow_indepth root promotion, the right-edge case of ext4_ext_split, and the right-to-left extent removal traversal. The adapter stages allocation changes and retained extent nodes in a JBD2 transaction. The server also builds Linux’s directory hash algorithms from fs/ext4/hash.c and the child selection and leaf split from fs/ext4/namei.c. System reads the index blocks and supplies the filesystem hash seed, verified directory data, and JBD2 transaction buffers. The server package includes the applicable GPL license.

For a one-time adoption that System will maintain, copy the needed files into the owning subsystem under packages/ or common/, and build them there. Record the upstream location, exact revision, and applicable license and copyright notices for either approach. Check each file’s license and linked dependencies. The microkernel binary accepts BSD-2-Clause and MIT code under the repository’s licensing rules.

The native libelf.a under packages/libelf/ is a one-time adoption of the ELF Tool Chain sources and supporting headers from FreeBSD commit 4ba6fd2ef5a739b6fdc955890d27e07ae8794fb3. The sources retain their individual notices and are linked into userspace tools. The build runs m4 on the build host to generate the ELF type tables and converters. The native configuration reads files through libc because the guest does not yet provide file-backed mmap().

Native libc also adopts wide string search and memory routines from lib/libc/string/ at the same FreeBSD revision. Their source notices remain under packages/libc/wide/. The build uses native libc’s memory operations in place of FreeBSD’s stack-protector wrappers. The C-locale date formatter comes from contrib/tzcode/strftime.c at the same revision. It keeps its BSD-3-Clause notice, substitutes System’s UTC calendar and bounded formatting calls, and ships its notice with the libc package.

The shared LLVM import under contrib/llvm-project/ is LLVM 22.1.8 at commit ca7933e47d3a3451d81e72ac174dcb5aa28b59d1. Its filter keeps the compiler and libraries used by FreeBSD, plus upstream CMake support, libc++abi, and the OpenMP dependencies. The vendor/llvm-project branch records the release archive and verified SHA-256. The subtree retains the LLVM license texts, including the Apache 2.0 LLVM exception, and component notices. See the FreeBSD LLVM import.

Vendor imports

  1. Pin an upstream release or commit and obtain its source or binary archive as appropriate. Verify published signatures or checksums where available. Prefer an upstream .tar.xz. If upstream uses another compression, verify the original and recompress the same tar stream as XZ. Record the archive URL, revision, and SHA-256 digests in the import commit.

  2. Maintain one authoritative .vendor-import-ignore at the root of each vendor/<component> branch. List only unneeded files and keep applicable licenses, notices, and reference documents. Patterns match archive paths before stripping the leading directory. Extract into an empty staging directory. For archives with one leading directory, use the following command.

    tar --extract --xz --file="$archive" --directory="$staging" \
        --strip-components=1 --anchored --wildcards \
        --exclude-from="$vendor_worktree/.vendor-import-ignore"
    
  3. Update the vendor worktree with the extracted files, including deletions upstream made. Preserve the exclusion list. The vendor branch contains the retained upstream files without source edits, plus the list. Commit the snapshot and create an annotated vendor/<component>/<revision> tag.

  4. Merge the vendor history into the integration branch without squashing. For an initial import, use git subtree add --prefix=contrib/<component> vendor/<component>. For updates, use git subtree merge --prefix=contrib/<component> vendor/<component>. The copy of the exclusion list in contrib/ follows that merge. Edit the list on the vendor branch.

  5. Apply System changes under contrib/<component>/ on the integration branch. This includes replacing upstream kernel APIs with native IPC and resolving merge conflicts with earlier porting work. Keep System-owned service entry points, build targets, and tests with their subsystems. Build the affected targets and run their relevant tests.

If git subtree is unavailable, begin the initial import from a clean integration worktree with git merge --no-commit --allow-unrelated-histories -s ours vendor/<component>. Stage the upstream tree with git read-tree --prefix=contrib/<component>/ -u vendor/<component>, then review and commit the merge. For updates use git merge -s ort -Xsubtree=contrib/<component> vendor/<component> and review the result.

The FreeBSD base import is pinned at 4ba6fd2ef5a739b6fdc955890d27e07ae8794fb3 under contrib/freebsd-base/. The local verifier builds the BSD-licensed SHA-512 and SHA512-crypt C sources from that tree. System’s wrapper and its guest test live under packages/libcrypt/ and packages/base-utils/init/tests/. The native image installs the upstream copyright and license notices under /usr/share/licenses/FreeBSD.

The installed /bin and /sbin utilities build as C from the same snapshot. Echo writes through its inherited descriptors using native libc. The port removes the FreeBSD Capsicum setup. Pwd uses native directory metadata, the adopted BSD getopt(), and unbuffered output. The local getopt implementation retains the BSD notice and is based on lib/libc/stdlib/getopt.c at that revision. cat uses native descriptors and byte I/O. ls uses native directory streams and file metadata in place of FreeBSD’s FTS and formatting APIs. The administration ports use a single serial getty for init, immediate power actions for shutdown and reboot, and named string leaves through sysctlbyname() for sysctl. The init target also links System’s console preparation and optional boot checks.

The same snapshot supplies ps, pgrep, pkill, and the C-locale regular expression implementation in libc. The process tools query the native kern.proc records. ps supports the native identity, process group, session, terminal, state, and command columns. pgrep and pkill select by regular expression and process identity. pkill sends signals through the ordinary native permission check.

The local command set also builds hostname, mkdir, rmdir, mv, cp, rm, head, wc, grep, and find from the pinned base import. Hostname reads the native host name. Head and grep use native file descriptors and the libc line reader. Grep supports basic, extended, and fixed-string patterns. Find uses native directory streams and supports name, type, depth, and mount-boundary filters. Chmod uses FreeBSD’s mode parser and changes permissions on a writable native ext4 mount. Mv uses the native same-directory regular-file rename operation. Cp copies regular files and checks source and destination identity before truncating an open destination. Rm supports nonrecursive removal, including empty directories with -d.

The same sources provide the shell builtins and the separate /bin/test, /bin/[ and /usr/bin/printf executables. Sleep parses decimal time with optional seconds, minutes, hours, or days suffixes and uses libc’s interruptible monotonic wait.

The pinned basename and dirname libc helpers support their matching utilities. The port also includes cut, uniq, tee, which, and yes. Character selection and comparisons use the native C locale. The nonrecursive chflags port uses the pinned BSD flag parser and ls -lo displays the supported flags. The mount port uses getfsstat() for listing, including filesystem type filtering and fstab-style output. It uses nmount() to attach the provisioned FAT data volume described in Filesystems, block storage, and networking.

Local account administration builds the FreeBSD pw command dispatcher and the local ports of pwd_mkdb, adduser and rmuser from the same snapshot. The native record parser and publisher use the text databases described in Native processes, loading, and the C runtime. The two scripts run through the installed FreeBSD shell and invoke pw for updates. The launcher is a native ELF program, and the scripts are installed as data under /usr/libexec.

The native image builds cmp, comm, env, expr, fold, paste, and uname from the FreeBSD snapshot. Comparison and text processing use native I/O and the C locale. Host Bison generates the expr parser from the upstream grammar. env uses libc’s native path search or the command’s alternate search path. uname reports native releases and architecture names through libc.

The image also builds dd, df, logname, mktemp, rcorder, sed, stty, sync, tail, tr, tty, and chown with its chgrp entry point. They use the native terminal, directory, regular file, and stream interfaces. rcorder reads startup dependencies from the scripts supplied by its caller. sed supports native text processing and same-directory file replacement on writable ext4. dd supports regular files and streams. Backends for tape, direct I/O, and sparse writes are future work. tail -f follows one regular file with a monotonic timed wait.