bridge-common.mjs raw

   1  // bridge-common.mjs - shared wasm bridge infrastructure.
   2  //
   3  // Exports utility functions and a factory for the common bridge functions
   4  // that appear identically in every wasm Worker host: SAB channel ops,
   5  // spawn_domain, is_worker_context, subtle_random_bytes, core helpers, WASI.
   6  
   7  // ── SAB ring buffer ────────────────────────────────────────────────────────
   8  
   9  export const SAB_HDR = 32;
  10  export const SAB_SLOT_HDR = 12;
  11  
  12  export function sabCreate(slotSize, slotCount) {
  13    const sab = new SharedArrayBuffer(SAB_HDR + slotCount * slotSize);
  14    const u32 = new Uint32Array(sab);
  15    u32[2] = slotSize;
  16    u32[3] = slotCount;
  17    return sab;
  18  }
  19  
  20  // forceClose sets the closed flag and wakes all blocked waiters.
  21  // No sentinel slot needed: send/recv wait loops check bit0 on every wakeup.
  22  export function sabForceClose(sab) {
  23    const u32 = new Uint32Array(sab);
  24    Atomics.or(u32, 4, 1);
  25    Atomics.notify(u32, 0, Atomics.MAX_VALUE);
  26    Atomics.notify(u32, 1, Atomics.MAX_VALUE);
  27  }
  28  
  29  export function sabSend(sab, bytes) {
  30    const u32 = new Uint32Array(sab);
  31    const slotSize = u32[2], slotCount = u32[3];
  32    const payloadCap = slotSize - SAB_SLOT_HDR;
  33    if (bytes.length > (slotCount - 1) * payloadCap)
  34      throw new Error('channel_send: overflow');
  35    let offset = 0, first = true;
  36    while (offset <= bytes.length) {
  37      const chunkLen = Math.min(bytes.length - offset, payloadCap);
  38      const isFinal = (offset + chunkLen >= bytes.length) ? 1 : 0;
  39      let wi = Atomics.load(u32, 0);
  40      while (wi - Atomics.load(u32, 1) >= slotCount) {
  41        Atomics.wait(u32, 1, Atomics.load(u32, 1));
  42        wi = Atomics.load(u32, 0);
  43        if (Atomics.load(u32, 4) & 1) throw new Error('channel_send: send on closed channel');
  44      }
  45      if (Atomics.load(u32, 4) & 1) throw new Error('channel_send: send on closed channel');
  46      const base = SAB_HDR + (wi & (slotCount - 1)) * slotSize;
  47      const dv = new DataView(sab, base, slotSize);
  48      dv.setUint8(0, isFinal);
  49      dv.setUint8(1, 0); dv.setUint8(2, 0); dv.setUint8(3, 0);
  50      dv.setUint32(4, first ? bytes.length : 0, true);
  51      dv.setUint32(8, chunkLen, true);
  52      if (chunkLen > 0)
  53        new Uint8Array(sab, base + SAB_SLOT_HDR, chunkLen)
  54          .set(bytes.subarray(offset, offset + chunkLen));
  55      Atomics.store(u32, 0, wi + 1);
  56      Atomics.notify(u32, 0, 1);
  57      offset += chunkLen;
  58      first = false;
  59      if (isFinal) break;
  60    }
  61  }
  62  
  63  export function sabRecv(sab, dstBuf) {
  64    const u32 = new Uint32Array(sab);
  65    const slotSize = u32[2], slotCount = u32[3];
  66    let totalLen = -1, dstOffset = 0, awaitingFirst = true;
  67    for (;;) {
  68      let ri = Atomics.load(u32, 1);
  69      while (Atomics.load(u32, 0) === ri) {
  70        Atomics.wait(u32, 0, ri);
  71        ri = Atomics.load(u32, 1);
  72        if (Atomics.load(u32, 4) & 1) return -1;
  73      }
  74      const base = SAB_HDR + (ri & (slotCount - 1)) * slotSize;
  75      const dv = new DataView(sab, base, slotSize);
  76      const isFinal = dv.getUint8(0);
  77      const slotTotalLen = dv.getUint32(4, true);
  78      const chunkLen = dv.getUint32(8, true);
  79      Atomics.store(u32, 1, ri + 1);
  80      Atomics.notify(u32, 1, 1);
  81      if (awaitingFirst) {
  82        if (slotTotalLen === 0)
  83          return (Atomics.load(u32, 4) & 1) ? -1 : 0;
  84        if (slotTotalLen > dstBuf.length)
  85          throw new Error('channel_recv: overflow');
  86        totalLen = slotTotalLen;
  87        awaitingFirst = false;
  88      }
  89      if (chunkLen > 0) {
  90        dstBuf.set(new Uint8Array(sab, base + SAB_SLOT_HDR, chunkLen), dstOffset);
  91        dstOffset += chunkLen;
  92      }
  93      if (isFinal) return totalLen;
  94    }
  95  }
  96  
  97  // sabTryRecv is the non-blocking probe the toolchain runtime's select arm
  98  // needs: -2 empty and open, -1 closed, else the byte count. The app host is a
  99  // second implementation of the same bridge (jsruntime/host.mjs is the first),
 100  // so an import the runtime adds must exist here too or the app's module fails
 101  // to instantiate.
 102  export function sabTryRecv(sab, dst) {
 103    const u32 = new Uint32Array(sab);
 104    if (Atomics.load(u32, 0) === Atomics.load(u32, 1)) {
 105      return (Atomics.load(u32, 4) & 1) ? -1 : -2;
 106    }
 107    return sabRecv(sab, dst);
 108  }
 109  
 110  export function sabClose(sab) {
 111    const u32 = new Uint32Array(sab);
 112    Atomics.or(u32, 4, 1);
 113    const slotSize = u32[2], slotCount = u32[3];
 114    let wi = Atomics.load(u32, 0);
 115    while (wi - Atomics.load(u32, 1) >= slotCount) {
 116      Atomics.wait(u32, 1, Atomics.load(u32, 1));
 117      wi = Atomics.load(u32, 0);
 118    }
 119    const base = SAB_HDR + (wi & (slotCount - 1)) * slotSize;
 120    const dv = new DataView(sab, base, slotSize);
 121    dv.setUint8(0, 1); dv.setUint32(4, 0, true); dv.setUint32(8, 0, true);
 122    Atomics.store(u32, 0, wi + 1);
 123    Atomics.notify(u32, 0, 1);
 124  }
 125  
 126  // ── fromSlice ──────────────────────────────────────────────────────────────
 127  
 128  export function fromSlice(s) {
 129    if (s instanceof Uint8Array) return s;
 130    if (s && s.$array != null) {
 131      const u = new Uint8Array(s.$length);
 132      for (let i = 0; i < s.$length; i++) u[i] = s.$array[s.$offset + i];
 133      return u;
 134    }
 135    if (s && typeof s === 'string') return new TextEncoder().encode(s);
 136    return new Uint8Array(0);
 137  }
 138  
 139  // ── Core helpers factory ───────────────────────────────────────────────────
 140  
 141  // makeCoreHelpers returns memory-access helpers that close over getMem/getXp.
 142  // Call after building the bridge object; the getters provide the live wasm
 143  // instance so helpers always see the current memory even after wasm growth.
 144  export function makeCoreHelpers(getMem, getXp) {
 145    const enc = new TextEncoder();
 146    const dec = new TextDecoder();
 147  
 148    function readStr(ptr, len) {
 149      if (len <= 0) return '';
 150      return dec.decode(new Uint8Array(getMem().buffer, ptr >>> 0, len));
 151    }
 152    function readBytes(ptr, len) {
 153      if (len <= 0) return new Uint8Array(0);
 154      return new Uint8Array(getMem().buffer, ptr >>> 0, len);
 155    }
 156    function writeStr(s) {
 157      const bytes = enc.encode('' + s);
 158      const ptr = getXp().__alloc(bytes.length) >>> 0;
 159      new Uint8Array(getMem().buffer, ptr, bytes.length).set(bytes);
 160      return [ptr, bytes.length];
 161    }
 162    function writeI32(addr, val) {
 163      new DataView(getMem().buffer).setInt32(addr >>> 0, val, true);
 164    }
 165    function writeBytes(data) {
 166      const u = fromSlice(data);
 167      const ptr = getXp().__alloc(u.length) >>> 0;
 168      new Uint8Array(getMem().buffer, ptr, u.length).set(u);
 169      return [ptr, u.length];
 170    }
 171    function cb0(id) { getXp().__cb0(id); }
 172    function cbs(id, s) {
 173      const [ptr, len] = writeStr(s);
 174      getXp().__cbs(id, ptr, len);
 175    }
 176    function cbdata(id, data) {
 177      const [ptr, len] = writeBytes(data);
 178      getXp().__cbdata(id, ptr, len);
 179    }
 180  
 181    return { readStr, readBytes, writeStr, writeI32, writeBytes, cb0, cbs, cbdata };
 182  }
 183  
 184  // ── WASI ───────────────────────────────────────────────────────────────────
 185  
 186  // makeEnv returns the 'env' import object for the host shims pkg/mxutil
 187  // declares (write + the mxc_* file helpers). These are reached by app and
 188  // module wasm binaries that import mxutil, so every instantiate call must
 189  // provide the namespace or the module fails with
 190  // "Import #1 env: module is not an object or function".
 191  export function makeEnv(getMem) {
 192    const dec = new TextDecoder();
 193    const fail = () => -1;
 194    return {
 195      // No filesystem inside a worker: fail the file shims cleanly.
 196      mxc_readfile: fail,
 197      mxc_filesize: fail,
 198      mxc_listdir: fail,
 199      mxc_writefile: fail,
 200      mxc_mkdir: fail,
 201      mxc_getenv: fail,
 202      // write(fd, ptr, count): route 1/2 to the worker console.
 203      write(fd, ptr, count) {
 204        const n = count >>> 0;
 205        if ((fd === 1 || fd === 2) && n > 0) {
 206          const s = dec.decode(new Uint8Array(getMem().buffer, ptr >>> 0, n));
 207          if (fd === 1) console.log(s.replace(/\n$/, ''));
 208          else console.error(s.replace(/\n$/, ''));
 209        }
 210        return n;
 211      },
 212      // compiler-rt's 64x64 -> 128 multiply, and on wasm32 it is the ONLY place
 213      // a 128-bit product happens: LLVM folds the 32-bit-half algorithm in
 214      // math/bits.Mul64 into `mul i128`, which legalises to this call -
 215      // (retptr, aLo, aHi, bLo, bHi), the product written as two i64s.
 216      //
 217      // host.mjs (the page supervisor) has had this since the app's crypto was
 218      // found returning a correct LOW word and a garbage HIGH one; the WORKER
 219      // env object did not, so every worker module whose closure uses i128 - the
 220      // app bundle (ed25519 field arithmetic) and the signer - failed to LINK
 221      // with "LinkError: import object field '__multi3' is not a Function". The
 222      // app domain then sat in 'boot' forever: the failure is reported as an
 223      // error message, and the page's ready flag is never set. Phase 7's smoke
 224      // suite saw exactly that as five Selenium timeouts and three failures.
 225      __multi3(ret, aLo, aHi, bLo, bHi) {
 226        const M64 = 0xffffffffffffffffn;
 227        const a = (BigInt.asUintN(64, aHi) << 64n) | BigInt.asUintN(64, aLo);
 228        const b = (BigInt.asUintN(64, bHi) << 64n) | BigInt.asUintN(64, bLo);
 229        const p = a * b;
 230        const dv = new DataView(getMem().buffer);
 231        dv.setBigInt64(ret, BigInt.asIntN(64, p & M64), true);
 232        dv.setBigInt64(ret + 8, BigInt.asIntN(64, (p >> 64n) & M64), true);
 233        return 0;
 234      },
 235      'syscall.Exit'(code) {
 236        self.close();
 237        throw new Error('wasm exit ' + code);
 238      },
 239    };
 240  }
 241  
 242  export function makeWasi(getMem) {
 243    const dec = new TextDecoder();
 244    const _lineBuf = { 1: '', 2: '' };
 245    return {
 246      fd_write(fd, iovs, iovs_len, nwritten_ptr) {
 247        const dv = new DataView(getMem().buffer);
 248        let total = 0;
 249        const iovBase = iovs >>> 0;
 250        for (let i = 0; i < iovs_len; i++) {
 251          const ptr = dv.getUint32(iovBase + i * 8, true);
 252          const len = dv.getUint32(iovBase + i * 8 + 4, true);
 253          const s = dec.decode(new Uint8Array(getMem().buffer, ptr, len));
 254          if (fd === 1 || fd === 2) {
 255            _lineBuf[fd] += s;
 256            let nl;
 257            while ((nl = _lineBuf[fd].indexOf('\n')) !== -1) {
 258              const line = _lineBuf[fd].slice(0, nl);
 259              _lineBuf[fd] = _lineBuf[fd].slice(nl + 1);
 260              if (fd === 1) console.log(line);
 261              else console.error(line);
 262            }
 263          }
 264          total += len;
 265        }
 266        dv.setUint32(nwritten_ptr >>> 0, total, true);
 267        return 0;
 268      },
 269      // The app imports fd_read (os.Stdin read paths). There is no stdin in a
 270      // worker, so report EBADF: the runtime panics with a message naming the
 271      // missing descriptor, where a successful zero-byte read would just look
 272      // like an empty stream.
 273      fd_read(fd, iovs, iovs_len, nread_ptr) {
 274        const dv = new DataView(getMem().buffer);
 275        dv.setUint32(nread_ptr >>> 0, 0, true);
 276        return 8; // WASI errno EBADF
 277      },
 278  
 279      clock_time_get(clock_id, precision, time_ptr) {
 280        const dv = new DataView(getMem().buffer);
 281        const ms = (clock_id === 1) ? performance.now() : Date.now();
 282        const ns = BigInt(Math.trunc(ms * 1e6));
 283        dv.setBigUint64(time_ptr >>> 0, ns, true);
 284        return 0;
 285      },
 286    };
 287  }
 288  
 289  // ── Build hash ─────────────────────────────────────────────────────────────
 290  
 291  export async function computeBuildHash(wasmBytes) {
 292    const buf = await crypto.subtle.digest('SHA-256', wasmBytes);
 293    return Array.from(new Uint8Array(buf))
 294      .map(b => b.toString(16).padStart(2, '0')).join('');
 295  }
 296  
 297  // ── Spawned Worker lifecycle ───────────────────────────────────────────────
 298  
 299  export function createSpawnedWorker(wasmUrl, buildHash, fnIdx, argBytes, chanSabs, spawnedWorkerChans) {
 300    const worker = new Worker(new URL(wasmUrl), { type: 'module' });
 301    worker.postMessage({ type: 'init', mode: 'spawn', wasmUrl, buildHash, fnIdx, argBytes, chanSabs });
 302    spawnedWorkerChans.set(worker, chanSabs);
 303    worker.onmessage = function(e) {
 304      if (e.data && e.data.type === 'exit') spawnedWorkerChans.delete(worker);
 305    };
 306    worker.onerror = function(e) {
 307      const sabs = spawnedWorkerChans.get(worker);
 308      spawnedWorkerChans.delete(worker);
 309      console.error('[spawn] child Worker died:', e.message,
 310        'at', e.filename + ':' + e.lineno,
 311        e.error && e.error.stack ? '\n' + e.error.stack : '');
 312      if (sabs) sabs.forEach(sabForceClose);
 313    };
 314    worker.onmessageerror = function() {
 315      const sabs = spawnedWorkerChans.get(worker);
 316      spawnedWorkerChans.delete(worker);
 317      if (sabs) sabs.forEach(sabForceClose);
 318    };
 319  }
 320  
 321  // ── Common bridge factory ──────────────────────────────────────────────────
 322  
 323  // makeCommonBridge returns the bridge functions shared by all wasm Worker
 324  // hosts. The host merges these with its own specific functions (ext_*, dom_*,
 325  // etc.) to form the complete bridge object passed to WebAssembly.instantiate.
 326  //
 327  // h: the result of makeCoreHelpers(getMem, getXp)
 328  // sabTable: Map<int32, SharedArrayBuffer> - handle table (mutated by channel_create)
 329  // sabSeqRef: { value: int32 } - next handle sequence number (mutable)
 330  // wasmUrlRef: { value: string|null } - set during wasm boot
 331  // buildHashRef: { value: string|null } - set during wasm boot
 332  // spawnedWorkerChans: Map<Worker, SAB[]> - dead-Worker cleanup tracking
 333  export function makeCommonBridge(h, sabTable, sabSeqRef, wasmUrlRef, buildHashRef, spawnedWorkerChans) {
 334    const { readStr, readBytes, writeBytes, writeI32, cbs, cbdata } = h;
 335  
 336    return {
 337      // --- runtime context ---
 338      is_worker_context() { return 1; },
 339  
 340      // --- SAB channels ---
 341      channel_create(slotSize, slotCount) {
 342        const sab = sabCreate(slotSize, slotCount);
 343        const handle = sabSeqRef.value++;
 344        sabTable.set(handle, sab);
 345        return handle;
 346      },
 347      channel_send(handle, srcPtr, srcLen, srcCap) {
 348        const sab = sabTable.get(handle);
 349        if (!sab) throw new Error('channel_send: invalid handle ' + handle);
 350        // .slice() copies bytes out before the Atomics.wait in sabSend can
 351        // conflict with wasm advancing the memory pointer during a GC.
 352        sabSend(sab, readBytes(srcPtr, srcLen).slice());
 353      },
 354      channel_recv(handle, dstPtr, dstCap, cap) {
 355        const sab = sabTable.get(handle);
 356        if (!sab) return -1;
 357        const dst = new Uint8Array(dstCap);
 358        const n = sabRecv(sab, dst);
 359        if (n > 0) {
 360          // readBytes returns a writable view into wasm linear memory at dstPtr.
 361          // set() writes the received bytes directly to that address.
 362          readBytes(dstPtr, n).set(dst.subarray(0, n));
 363        }
 364        return n;
 365      },
 366      channel_try_recv(handle, dstPtr, dstCap, cap) {
 367        const sab = sabTable.get(handle);
 368        if (!sab) return -1;
 369        const dst = new Uint8Array(dstCap);
 370        const n = sabTryRecv(sab, dst);
 371        if (n > 0) readBytes(dstPtr, n).set(dst.subarray(0, n));
 372        return n;
 373      },
 374      channel_close(handle) {
 375        const sab = sabTable.get(handle);
 376        if (sab) sabClose(sab);
 377      },
 378  
 379      // --- spawn ---
 380      spawn_domain(fnIdx, argPtr, argLen, chanHandlesPtr, nChans) {
 381        if (!wasmUrlRef.value) throw new Error('spawn_domain: wasmUrl not set');
 382        const chanSabs = [];
 383        for (let i = 0; i < nChans; i++) {
 384          // readBytes returns a view; DataView reads the int32 handle at each offset.
 385          const handleData = readBytes(chanHandlesPtr + i * 4, 4);
 386          const hh = new DataView(handleData.buffer, handleData.byteOffset, 4).getInt32(0, true);
 387          const sab = sabTable.get(hh);
 388          if (sab) chanSabs.push(sab);
 389        }
 390        const argBytes = argLen > 0 ? readBytes(argPtr, argLen).slice() : new Uint8Array(0);
 391        createSpawnedWorker(wasmUrlRef.value, buildHashRef.value, fnIdx, argBytes, chanSabs, spawnedWorkerChans);
 392      },
 393  
 394      // --- time ---
 395      timezone_offset_minutes() {
 396        return new Date().getTimezoneOffset();
 397      },
 398  
 399      // --- subtle ---
 400      subtle_random_bytes(ptr, len, cap) {
 401        crypto.getRandomValues(readBytes(ptr, len));
 402      },
 403    };
 404  }
 405