/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/native/loader * * The single place where BXC opens native libraries and locates native * executables. Every `dlopen` in the code base goes through * {@link createLazyLibrary} so path probing, embedded-asset extraction, the * Windows DLL search path and ABI verification behave identically for the * Rust bridge and libcurl-impersonate. * * It also owns the FFI string helpers: {@link cString} returns a buffer that * the caller passes *directly* as a `FFIType.ptr` argument. Bun keeps a typed * array argument alive for the duration of the call, whereas `ptr(buffer)` of * an unreferenced temporary leaves the pointer valid only until the next GC. */ import { dlopen, FFIType, type FFIFunction, type Library } from "bun:ffi"; import { dirname, join } from "node:path"; import { extractEmbeddedAssetIfNeeded } from "../internal/embedded-loader.ts"; /** Result of probing the candidate locations of a native artefact. */ export interface ProbeResult { /** First existing, non-empty candidate, or `null`. */ path: string | null; /** Every location that was considered, in order. */ tried: string[]; } /** ABI verification performed before any other symbol is bound. */ export interface AbiRequirement { /** Exported `u32 fn()` symbol returning the library ABI version. */ symbol: string; /** Version the TypeScript bindings were written against. */ expected: number; } export interface NativeLibrarySpec> { /** Human-readable name used in diagnostics (`rust-bridge`). */ name: string; /** Environment variable holding an explicit path; wins over probing. */ envVar?: string; /** Embedded asset (standalone builds) extracted to the BXC bin dir. */ embedded?: () => { asset: string; filename: string } | null; /** Ordered candidate paths, evaluated lazily at load time. */ candidates: () => string[]; /** Symbol table bound after the ABI check succeeds. */ symbols: S; /** Optional ABI equality check. */ abi?: AbiRequirement; /** Remediation shown when the library cannot be loaded. */ installHint: string; /** Hook run once after a successful load (e.g. `curl_global_init`). */ onLoad?: (lib: Library) => void; } /** Raised when a native library is missing, unloadable or ABI-incompatible. */ export class NativeLoadError extends Error { readonly library: string; readonly tried: string[]; constructor(library: string, message: string, tried: string[] = []) { super(message); this.name = "NativeLoadError"; this.library = library; this.tried = tried; } } /** Raised when the library ABI version differs from the expected one. */ export class NativeAbiMismatchError extends NativeLoadError { readonly expected: number; readonly actual: number; constructor(library: string, path: string, expected: number, actual: number) { super( library, `${library} at "${path}" exposes ABI ${actual} but these bindings require ABI ${expected}. ` + `Rebuild or reinstall the native library so both sides match.`, [path], ); this.name = "NativeAbiMismatchError"; this.expected = expected; this.actual = actual; } } function isNonEmptyFile(path: string): boolean { try { return Bun.file(path).size > 0; } catch { return false; } } /** * Resolve the first existing candidate. Order: explicit env var, embedded * asset (standalone binaries), then `spec.candidates()`. */ export function probeNativeLibrary>( spec: Pick, "envVar" | "embedded" | "candidates" | "name">, ): ProbeResult { const tried: string[] = []; const fromEnv = spec.envVar ? Bun.env[spec.envVar] : undefined; if (fromEnv) { // An explicit override is authoritative: never silently fall back. return { path: fromEnv, tried: [fromEnv] }; } const embedded = spec.embedded?.(); if (embedded?.asset) { try { const extracted = extractEmbeddedAssetIfNeeded(embedded.asset, embedded.filename); tried.push(extracted); if (isNonEmptyFile(extracted)) return { path: extracted, tried }; } catch (err) { console.warn(`[bxc] Failed to extract embedded ${spec.name}:`, err); } } for (const candidate of spec.candidates()) { tried.push(candidate); if (isNonEmptyFile(candidate)) return { path: candidate, tried }; } return { path: null, tried }; } let windowsDllDirectorySet: string | null = null; /** * Add `dir` to the Windows DLL search path so dependent DLLs placed next to * the library resolve. No-op on other platforms. */ export function setWindowsDllDirectory(dir: string): void { if (process.platform !== "win32" || windowsDllDirectorySet === dir) return; try { const kernel32 = dlopen("kernel32.dll", { SetDllDirectoryW: { args: [FFIType.ptr], returns: FFIType.bool }, }); kernel32.symbols.SetDllDirectoryW(Buffer.from(`${dir}\0`, "utf16le")); kernel32.close(); windowsDllDirectorySet = dir; } catch (err) { console.warn(`[bxc] SetDllDirectoryW(${dir}) failed:`, err); } } /** * Read the ABI version with a minimal symbol table first, so an outdated * library yields a precise version error instead of "symbol not found" (or * silent memory corruption when a signature changed but the name did not). */ function readAbiVersion(name: string, path: string, abi: AbiRequirement): number { let probe: Library>; try { probe = dlopen(path, { [abi.symbol]: { args: [], returns: FFIType.u32 } }); } catch (err) { throw new NativeLoadError( name, `${name} at "${path}" does not export ${abi.symbol}: ${err instanceof Error ? err.message : String(err)}`, [path], ); } try { return Number((probe.symbols[abi.symbol] as () => number)()); } finally { probe.close(); } } /** Every existing candidate in probe order (env override short-circuits). */ function existingCandidates>( spec: NativeLibrarySpec, ): { paths: string[]; tried: string[]; explicit: boolean } { const fromEnv = spec.envVar ? Bun.env[spec.envVar] : undefined; if (fromEnv) return { paths: [fromEnv], tried: [fromEnv], explicit: true }; const first = probeNativeLibrary(spec); if (!first.path) return { paths: [], tried: first.tried, explicit: false }; const paths = [first.path]; const tried = [...first.tried]; for (const candidate of spec.candidates()) { if (candidate === first.path || tried.includes(candidate)) continue; tried.push(candidate); if (isNonEmptyFile(candidate)) paths.push(candidate); } return { paths, tried, explicit: false }; } /** * Open a native library now, verifying its ABI. Throws {@link NativeLoadError}. * * Without an explicit env override, candidates whose ABI differs are skipped * so a stale install (e.g. an old `~/.bxc/bin` copy) cannot shadow a * compatible build later in the search order. If every existing candidate * mismatches, the first mismatch is reported. */ export function openNativeLibrary>( spec: NativeLibrarySpec, ): { lib: Library; path: string } { const { paths, tried, explicit } = existingCandidates(spec); if (paths.length === 0) { throw new NativeLoadError( spec.name, `${spec.name} not found. ${spec.installHint} Tried: ${tried.join(", ") || "(no candidates)"}`, tried, ); } let path: string | null = null; let firstMismatch: NativeAbiMismatchError | null = null; for (const candidate of paths) { if (!spec.abi) { path = candidate; break; } setWindowsDllDirectory(dirname(candidate)); const actual = readAbiVersion(spec.name, candidate, spec.abi); if (actual === spec.abi.expected) { path = candidate; break; } firstMismatch ??= new NativeAbiMismatchError(spec.name, candidate, spec.abi.expected, actual); if (explicit) break; } if (!path) throw firstMismatch as NativeAbiMismatchError; setWindowsDllDirectory(dirname(path)); let lib: Library; try { lib = dlopen(path, spec.symbols); } catch (err) { throw new NativeLoadError( spec.name, `${spec.name} could not be loaded from "${path}". ${spec.installHint} ` + `Cause: ${err instanceof Error ? err.message : String(err)}`, tried, ); } spec.onLoad?.(lib); return { lib, path }; } /** Lazily-opened library handle with a cached load error. */ export interface LazyLibrary> { /** Bound symbols; opens the library on first call. Throws on failure. */ symbols(): Library["symbols"]; /** The opened library; opens it on first call. Throws on failure. */ library(): Library; /** `true` when the library is (or can be) loaded. Never throws. */ available(): boolean; /** Resolved path once loaded, else the probe result's first hit or `null`. */ path(): string | null; /** Cached load error, if the last attempt failed. */ error(): Error | null; } /** * Wrap a spec in a lazy loader. Opening at import time would crash every code * path that merely imports a module when the library is not installed; the * lazy form turns that into an actionable error at first use. */ export function createLazyLibrary>( spec: NativeLibrarySpec, ): LazyLibrary { let loaded: { lib: Library; path: string } | null = null; let failure: Error | null = null; const load = () => { if (loaded) return loaded; if (failure) throw failure; try { loaded = openNativeLibrary(spec); return loaded; } catch (err) { failure = err instanceof Error ? err : new Error(String(err)); throw failure; } }; return { symbols: () => load().lib.symbols, library: () => load().lib, available() { try { load(); return true; } catch { return false; } }, path: () => loaded?.path ?? probeNativeLibrary(spec).path, error: () => failure, }; } /** * Locate a native executable (e.g. `bxc-engine`). Returns `null` when absent; * callers must turn that into an install hint rather than building from * source at runtime. */ export function resolveNativeExecutable( name: string, options: { envVar?: string; candidates: string[] }, ): ProbeResult { const fileName = process.platform === "win32" ? `${name}.exe` : name; const fromEnv = options.envVar ? Bun.env[options.envVar] : undefined; if (fromEnv) return { path: fromEnv, tried: [fromEnv] }; const tried: string[] = []; for (const dir of options.candidates) { const candidate = join(dir, fileName); tried.push(candidate); if (isNonEmptyFile(candidate)) return { path: candidate, tried }; } const onPath = Bun.which(fileName); if (onPath) return { path: onPath, tried: [...tried, onPath] }; return { path: null, tried }; } const encoder = new TextEncoder(); /** * Encode `value` as a NUL-terminated UTF-8 buffer. * * Pass the returned array itself as the `FFIType.ptr` argument. Do not wrap it * in `ptr()` and discard it: an unreferenced buffer may be collected (and its * memory reused) before the native call reads it. */ export function cString(value: string): Uint8Array { const encoded = encoder.encode(value); const buffer = new Uint8Array(encoded.length + 1); buffer.set(encoded); return buffer; } /** {@link cString} for optional arguments: `null` maps to a NULL pointer. */ export function cStringOrNull(value: string | null | undefined): Uint8Array | null { return value === null || value === undefined ? null : cString(value); }