Skip to content

FFI: passing a JS number as 'ptr' argument crashes on Linux x64 — segfault at 0xFFFFFFFFFFFFFFFF #29346

Closed

Description

@shreeve

Summary

Passing a JavaScript number (returned from a previous FFI call) as a 'ptr' argument to another FFI function causes a segfault on Linux x64. The crash address is 0xFFFFFFFFFFFFFFFF, suggesting the number is being corrupted during marshaling.

Declaring the same argument as 'u64' and passing a BigInt works correctly. This is not a DuckDB bug — it reproduces with any library that returns an opaque handle and expects it back.

This likely explains many of the crashes in #13910 (DuckDB compatibility).

Versions tested

  • Bun v1.2.15, v1.3.12, v1.3.12-canary — all crash
  • Linux x64, kernel 6.17.0, glibc 2.39
  • macOS ARM64 works fine with the same code

Minimal reproduction

Step 1: Verify FFI works (libc)

// test-libc.mjs — PASSES
import { dlopen } from 'bun:ffi';

const { symbols: libc } = dlopen("libc.so.6", {
  getpid: { args: [], returns: 'i32' },
  time:   { args: ['ptr'], returns: 'i64' },
});

console.log(`PID:  ${libc.getpid()}`);
console.log(`Time: ${libc.time(null)}`);
console.log('OK');

Step 2: Number as 'ptr' — CRASHES

// test-crash.mjs — dlopen + open works, connect CRASHES
import { dlopen, ptr, read as ffiRead } from 'bun:ffi';

const { symbols: lib } = dlopen("/usr/local/lib/libduckdb.so", {
  duckdb_open:       { args: ['ptr', 'ptr'], returns: 'i32' },
  duckdb_close:      { args: ['ptr'], returns: 'void' },
  duckdb_connect:    { args: ['ptr', 'ptr'], returns: 'i32' },
  duckdb_disconnect: { args: ['ptr'], returns: 'void' },
});

const dbBuf = new Uint8Array(8);
lib.duckdb_open(null, ptr(dbBuf));
const dbHandle = ffiRead.ptr(ptr(dbBuf), 0);
console.log(`Open: OK (${dbHandle})`);

// This passes dbHandle (a JS number) as a 'ptr' argument — CRASHES
const connBuf = new Uint8Array(8);
lib.duckdb_connect(dbHandle, ptr(connBuf));
console.log('Connect: OK');

lib.duckdb_disconnect(ptr(connBuf));
lib.duckdb_close(ptr(dbBuf));

Output:

Open: OK (548444784)
============================================================
Bun v1.2.15 (df017990) Linux x64
panic(main thread): Segmentation fault at address 0xFFFFFFFFFFFFFFFF

Step 3: BigInt as 'u64' — WORKS

// test-fix.mjs — same code, but 'u64' + BigInt for the handle
import { dlopen, ptr } from 'bun:ffi';

const { symbols: lib } = dlopen("/usr/local/lib/libduckdb.so", {
  duckdb_open:       { args: ['ptr', 'ptr'], returns: 'i32' },
  duckdb_close:      { args: ['ptr'], returns: 'void' },
  duckdb_connect:    { args: ['u64', 'ptr'], returns: 'i32' },  // <-- u64 instead of ptr
  duckdb_disconnect: { args: ['ptr'], returns: 'void' },
});

const dbBuf = new Uint8Array(8);
lib.duckdb_open(null, ptr(dbBuf));
const dbHandle = new DataView(dbBuf.buffer).getBigUint64(0, true);
console.log(`Open: OK (0x${dbHandle.toString(16)})`);

const connBuf = new Uint8Array(8);
lib.duckdb_connect(dbHandle, ptr(connBuf));  // BigInt — works!
console.log('Connect: OK');

lib.duckdb_disconnect(ptr(connBuf));
lib.duckdb_close(ptr(dbBuf));

Output:

Open: OK (0x421bda90)
Connect: OK
Disconnect: OK
Close: OK

Key observations

What we pass Declared as Result
ptr(typedArray) 'ptr' Works (Bun extracts pointer from buffer)
null 'ptr' Works (special-cased)
548444784 (JS number from ffiRead.ptr) 'ptr' Crashes at 0xFFFFFFFFFFFFFFFF
548444784n (same value as BigInt) 'u64' Works

The bug is specifically in marshaling a plain JS number into a C pointer argument. ptr(buf) and null work; a number does not. Since void* and uint64_t are the same ABI on x86_64, 'u64' + BigInt is a safe workaround.

Impact

This likely explains the long-standing DuckDB FFI crashes on Linux (#13910, open since Sep 2024). Any FFI usage that reads a handle via ffiRead.ptr() or from a 'ptr' return and passes it to another function as 'ptr' will crash on Linux x64.

Environment

Bun v1.3.12 (700fc117) Linux x64
Linux Kernel v6.17.0 | glibc v2.39
CPU: sse42 popcnt avx avx2 avx512

Activity

  1. github-actions commented on Apr 15, 2026

    @github-actions
    Contributor

    Found 1 possible duplicate issue:

    1. Bun FFI Bug: BigInt to ptr conversion fails on Linux #22751

    This issue will be automatically closed as a duplicate in 3 days.

    • If your issue is a duplicate, please close it and 👍 the existing issue instead
    • To prevent auto-closure, add a comment or 👎 this comment

    🤖 Generated with Claude Code

  2. shreeve commented on Apr 15, 2026

    @shreeve
    Author

    Our fix (working in production)

    We hit this while building rip-db, a DuckDB HTTP server using pure Bun FFI. Here's what we did to get it working on Linux x64.

    Fix 1: u64 + BigInt for all opaque handles

    Every DuckDB C API function that takes an opaque handle by value (duckdb_database, duckdb_connection, duckdb_prepared_statement, duckdb_data_chunk, duckdb_vector, duckdb_logical_type, duckdb_appender) was changed from 'ptr' to 'u64', and all handles are stored as BigInt.

    // Before (crashes on Linux x64)
    const lib = dlopen(libPath, {
      duckdb_connect:    { args: ['ptr', 'ptr'], returns: 'i32' },
      duckdb_query:      { args: ['ptr', 'ptr', 'ptr'], returns: 'i32' },
      duckdb_prepare:    { args: ['ptr', 'ptr', 'ptr'], returns: 'i32' },
      // ... etc
    });
    const handle = ffiRead.ptr(ptr(buf), 0);  // Number
    
    // After (works everywhere)
    const lib = dlopen(libPath, {
      duckdb_connect:    { args: ['u64', 'ptr'], returns: 'i32' },
      duckdb_query:      { args: ['u64', 'ptr', 'ptr'], returns: 'i32' },
      duckdb_prepare:    { args: ['u64', 'ptr', 'ptr'], returns: 'i32' },
      // ... etc
    });
    const handle = new DataView(buf.buffer).getBigUint64(0, true);  // BigInt

    Arguments that receive ptr(typedArray) (buffer pointers for output params) stay as 'ptr' — those work fine.

    Fix 2: C shim for struct-by-value functions

    A second, independent issue: duckdb_fetch_chunk(duckdb_result result) takes a 48-byte struct by value. On Linux x64 SysV ABI, this is MEMORY class (passed on the stack). Bun FFI has no mechanism to pass structs by value, so this crashes regardless of the ptr/u64 fix.

    On macOS ARM64, large structs are passed by hidden pointer, so ptr(buf) happens to work. On Linux x64, it segfaults.

    We wrote a 30-line C shim that accepts duckdb_result* instead:

    // duckdb-shim.c
    #include <stdint.h>
    
    typedef uint64_t idx_t;
    typedef void *duckdb_data_chunk;
    
    typedef struct {
        idx_t deprecated_column_count;
        idx_t deprecated_row_count;
        idx_t deprecated_rows_changed;
        void *deprecated_columns;
        char *deprecated_error_message;
        void *internal_data;
    } duckdb_result;
    
    extern duckdb_data_chunk duckdb_fetch_chunk(duckdb_result result);
    
    duckdb_data_chunk shim_fetch_chunk(duckdb_result *result) {
        return duckdb_fetch_chunk(*result);
    }

    Build: gcc -shared -fPIC -o libduckdb-shim.so duckdb-shim.c -lduckdb

    Then in JS:

    const shim = dlopen(shimPath, {
      shim_fetch_chunk: { args: ['ptr'], returns: 'u64' },
    }).symbols;
    
    // Use shim on Linux, fall back to direct call on macOS ARM64
    const fetchChunk = shim
      ? (rp) => shim.shim_fetch_chunk(rp)
      : (rp) => lib.duckdb_fetch_chunk(rp);

    Full working test (Linux x64, SELECT 42 end-to-end)

    // test-full.mjs — requires libduckdb.so + libduckdb-shim.so
    import { dlopen, ptr, read as ffiRead, CString } from 'bun:ffi';
    
    const enc = new TextEncoder();
    const cstr = s => enc.encode(s + '\0');
    const LIB = "/usr/local/lib/libduckdb.so";
    const SHIM = "/usr/local/lib/libduckdb-shim.so";
    
    const { symbols: lib } = dlopen(LIB, {
      duckdb_library_version:       { args: [], returns: 'ptr' },
      duckdb_open:                  { args: ['ptr', 'ptr'], returns: 'i32' },
      duckdb_close:                 { args: ['ptr'], returns: 'void' },
      duckdb_connect:               { args: ['u64', 'ptr'], returns: 'i32' },
      duckdb_disconnect:            { args: ['ptr'], returns: 'void' },
      duckdb_query:                 { args: ['u64', 'ptr', 'ptr'], returns: 'i32' },
      duckdb_destroy_result:        { args: ['ptr'], returns: 'void' },
      duckdb_data_chunk_get_size:   { args: ['u64'], returns: 'u64' },
      duckdb_data_chunk_get_vector: { args: ['u64', 'u64'], returns: 'u64' },
      duckdb_vector_get_data:       { args: ['u64'], returns: 'u64' },
      duckdb_destroy_data_chunk:    { args: ['ptr'], returns: 'void' },
    });
    
    const { symbols: shim } = dlopen(SHIM, {
      shim_fetch_chunk: { args: ['ptr'], returns: 'u64' },
    });
    
    // Open + Connect
    const dbBuf = new Uint8Array(8);
    lib.duckdb_open(null, ptr(dbBuf));
    const dbHandle = new DataView(dbBuf.buffer).getBigUint64(0, true);
    
    const connBuf = new Uint8Array(8);
    lib.duckdb_connect(dbHandle, ptr(connBuf));
    const connHandle = new DataView(connBuf.buffer).getBigUint64(0, true);
    
    console.log(`DuckDB ${new CString(lib.duckdb_library_version())}`);
    
    // Query
    const resultBuf = new Uint8Array(64);
    const status = lib.duckdb_query(connHandle, ptr(cstr('SELECT 42 AS num')), ptr(resultBuf));
    if (status !== 0) throw new Error('query failed');
    console.log('Query: OK');
    
    // Fetch chunk via shim
    const chunk = shim.shim_fetch_chunk(ptr(resultBuf));
    const vec = lib.duckdb_data_chunk_get_vector(chunk, 0n);
    const dataPtr = lib.duckdb_vector_get_data(vec);
    const value = ffiRead.i32(Number(dataPtr), 0);
    
    console.log(`SELECT 42 => ${value}`);
    console.log(value === 42 ? 'PASS' : 'FAIL');
    
    // Cleanup
    const chunkBuf = new Uint8Array(8);
    new DataView(chunkBuf.buffer).setBigUint64(0, BigInt(chunk), true);
    lib.duckdb_destroy_data_chunk(ptr(chunkBuf));
    lib.duckdb_destroy_result(ptr(resultBuf));
    lib.duckdb_disconnect(ptr(connBuf));
    lib.duckdb_close(ptr(dbBuf));

    Output on Linux x64:

    DuckDB v1.5.2
    Query: OK
    SELECT 42 => 42
    PASS
    

    Commit

    The full fix (FFI declarations, BigInt handles, shim loader, fallback for macOS): shreeve/rip-lang@5f29011

    All 62 DuckDB FFI tests pass on macOS, and the server runs successfully on Linux x64 with DuckDB 1.5.2 + Bun 1.3.12.

  3. robobun commented on Apr 15, 2026

    @robobun
    Collaborator

    Fixed in v1.3.3 by #25045 — the Int32-encoded JSValue branch was missing from JSVALUE_TO_PTR in FFI.h, so handles in the low 2 GiB got sign-extended to 0xFFFFFFFFxxxxxxxx.

    Your reproduction runs clean on a fresh v1.3.12 install here (same 700fc117 revision you reported) — could you try curl -fsSL https://bun.sh/install | bash -s "bun-v1.3.12" or upgrading to canary? If it still crashes, please drop a fresh bun --revision and the exact output here.

    Regression test in #29350. Just rebased onto current main (8 new commits) to run CI again past the earlier snapshot/segfault flakes.

  4. shreeve commented on Apr 17, 2026

    @shreeve
    Author

    How can we get this retested with the CI/CD?

  5. shreeve commented on Apr 18, 2026

    @shreeve
    Author

    See #29464

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions