robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

bfredlMerge pull request #41186 from Rawan10101/fix-wasm-browser69e61d52e2

master
15.5 KiB620 linesraw
1const CAP = 1 << 16;
2
3let state = null;
4let ringData = null;
5
6let moduleRef = null;
7
8let totalBytesRead = 0;
9const consumedBytes = [];
10const STATUS_MSG_CAP = 2000;
11let statusMsgCount = 0;
12let statusCapNoticeSent = false;
13
14function safeStatus(text) {
15  statusMsgCount++;
16  if (statusMsgCount > STATUS_MSG_CAP) {
17    if (!statusCapNoticeSent) {
18      statusCapNoticeSent = true;
19      postMessage({
20        type: "status",
21        text:
22          "STATUS LOGGING SUPPRESSED after " +
23          STATUS_MSG_CAP +
24          " messages -- likely a busy/runaway loop. " +
25          "See perFdWriteCount below for which fd is spinning.",
26      });
27    }
28    return;
29  }
30  postMessage({ type: "status", text: text });
31}
32
33const perFdWriteCount = {};
34function bumpFdWriteCount(fd) {
35  perFdWriteCount[fd] = (perFdWriteCount[fd] || 0) + 1;
36}
37
38/* File descriptor monitored by libuv for stdin. Verify this value
39   against the startup FD dump, as it may differ across environments. */
40
41const STDIN_FD = 9;
42
43/*
44 SharedArrayBuffer layout:
45 offset 0:
46 Int32Array:
47 [0] head
48 [1] tail
49 [2] closed
50
51 offset 12:
52 Uint8Array data
53*/
54
55function unreadCount() {
56  const head = Atomics.load(state, 0);
57  const tail = Atomics.load(state, 1);
58  return (head - tail + CAP) % CAP;
59}
60
61// Synchronizes the JS ring buffer with the shared atomics used by
62// uv__io_poll to allow libuv to detect newly available input.
63function markReadable() {
64  safeStatus(
65    "MARK READABLE called moduleRef=" + !!moduleRef + " STDIN_FD=" + STDIN_FD,
66  );
67  if (!moduleRef) return;
68  const n = unreadCount();
69  safeStatus("MARK READABLE n=" + n);
70  try {
71    moduleRef.ccall(
72      "uv_browser_set_readable",
73      null,
74      ["number", "number"],
75      [STDIN_FD, n],
76    );
77    safeStatus("MARK READABLE ccall succeeded");
78  } catch (e) {
79    safeStatus("MARK READABLE FAILED: " + e);
80  }
81}
82
83// Debug helper
84function dumpFD(fd) {
85  const s = moduleRef.FS.streams[fd];
86
87  safeStatus(" FD " + fd);
88
89  if (!s) {
90    safeStatus("NO STREAM");
91    return;
92  }
93
94  safeStatus("path=" + s.path + " fd=" + s.fd + " tty=" + !!s.tty);
95
96  safeStatus(
97    "same stdout ops=" + (s.stream_ops === moduleRef.FS.streams[1].stream_ops),
98  );
99
100  try {
101    const st = moduleRef.FS.fstat(fd);
102
103    safeStatus(
104      "mode=" +
105        st.mode.toString(8) +
106        " isChrdev=" +
107        moduleRef.FS.isChrdev(st.mode),
108    );
109  } catch (e) {
110    safeStatus("fstat failed: " + e);
111  }
112}
113
114function popByte() {
115  const head = Atomics.load(state, 0);
116  const tail = Atomics.load(state, 1);
117
118  if (head === tail) return -1;
119
120  const b = ringData[tail];
121
122  Atomics.store(state, 1, (tail + 1) % CAP);
123
124  totalBytesRead++;
125  consumedBytes.push(b);
126
127  console.log("POP BYTE", b.toString(16));
128
129  return b;
130}
131
132// Called when new bytes are pushed into the ring buffer from the main
133//  thread. Advances head and notifies both the JS side Atomics.wait() consumers and the C-side
134//  futex consumers (uv__io_poll).
135function pushBytes(bytes) {
136  if (!bytes || !bytes.length) return;
137
138  let head = Atomics.load(state, 0);
139
140  for (let i = 0; i < bytes.length; i++) {
141    const tail = Atomics.load(state, 1);
142    const nextHead = (head + 1) % CAP;
143
144    /* If the ring buffer is full, drop new data instead of overwriting
145   unread bytes. Overwriting would corrupt the input stream. If this
146   happens often, increase CAP or add backpressure on the producer. */
147    if (nextHead === tail) {
148      console.warn("stdin ring buffer full, dropping byte");
149      break;
150    }
151
152    ringData[head] = bytes[i];
153    head = nextHead;
154  }
155
156  Atomics.store(state, 0, head);
157
158  // wake anything doing an Atomics.wait() on head, if anything still does
159  Atomics.notify(state, 0);
160
161  // tell the C side (uv__io_poll) that fd 9 now has data
162  markReadable();
163}
164
165function flushAll() {
166  if (stdoutBuffer.length) {
167    postMessage({
168      type: "stdout",
169      bytes: stdoutBuffer,
170    });
171    stdoutBuffer = [];
172  }
173
174  if (stderrBuffer.length) {
175    postMessage({
176      type: "stderr",
177      bytes: stderrBuffer,
178    });
179    stderrBuffer = [];
180  }
181}
182
183let stdoutBuffer = [];
184let stderrBuffer = [];
185
186function writeStderr(c) {
187  stderrBuffer.push(c);
188
189  if (stderrBuffer.length > 50) {
190    postMessage({
191      type: "stderr",
192      bytes: stderrBuffer,
193    });
194
195    stderrBuffer = [];
196  }
197}
198
199function makeArgv(M, args) {
200  const ptrs = args.map((s) => {
201    const len = M.lengthBytesUTF8(s) + 1;
202
203    const p = M._malloc(len);
204
205    M.stringToUTF8(s, p, len);
206
207    return p;
208  });
209
210  const argv = M._malloc((ptrs.length + 1) * 4);
211
212  ptrs.forEach((p, i) => M.setValue(argv + i * 4, p, "*"));
213
214  M.setValue(argv + ptrs.length * 4, 0, "*");
215
216  return {
217    argc: ptrs.length,
218    argv,
219  };
220}
221
222self.onerror = (e) => {
223  safeStatus("WORKER ERROR " + e.message);
224};
225
226self.onunhandledrejection = (e) => {
227  const r = e.reason;
228  const info =
229    r && typeof r === "object"
230      ? `name=${r.name} message=${r.message} status=${r.status}`
231      : String(r);
232  safeStatus("REJECTION " + info);
233};
234
235/* Hook the shared TTY get_char callback instead of stream_ops.read.
236   All duplicated file descriptors share the same TTY object, making
237   this work for stdin and any dup()ed descriptors.
238   Return one byte when available, undefined when no data is ready
239   (causing Emscripten to report EAGAIN), or null on EOF. Blocking is
240   handled by uv__io_poll so this callback always remains non-blocking.
241 */
242function installStdoutWrite(m, stdoutStream) {
243  if (
244    !stdoutStream.stream_ops ||
245    typeof stdoutStream.stream_ops.write !== "function"
246  ) {
247    throw new Error(
248      "stdout stream has no stream_ops.write: " + stdoutStream.path,
249    );
250  }
251  // The worker owns the transport, so forwarding the chunk via postMessage
252  // completes the write.
253  // Skip the original stream_ops.write to avoid duplicate output.
254  stdoutStream.stream_ops.write = function (
255    stream,
256    buffer,
257    offset,
258    length,
259    position,
260  ) {
261    safeStatus(
262      "WRITE HOOK fd=" + stream.fd + " path=" + stream.path + " len=" + length,
263    );
264
265    try {
266      console.log("HOOK: entered");
267      /* Forward the entire chunk as a single message to preserve msgpack-RPC
268   framing. Then copy it into a Uint8Array to ensure the transmitted bytes
269   remain correct regardless of the source buffer's signedness. */
270      const chunk = new Uint8Array(length);
271      for (let i = 0; i < length; i++) {
272        chunk[i] = buffer[offset + i];
273      }
274      console.log(
275        "HOOK: chunk built",
276        chunk.length,
277        chunk[0],
278        chunk[1],
279        chunk[2],
280        chunk[3],
281      );
282      console.log(
283        "stdout chunk",
284        length,
285        chunk[0],
286        chunk[1],
287        chunk[2],
288        chunk[3],
289      );
290      console.log("HOOK: BEFORE postMessage");
291
292      postMessage({
293        type: "stdout",
294        bytes: chunk,
295      });
296      console.log("HOOK: AFTER postMessage");
297    } catch (e) {
298      console.error("HOOK: postMessage failed", e);
299
300      safeStatus("STDOUT HOOK ERROR: " + e + " stack=" + e.stack);
301    }
302    return length;
303  };
304}
305
306function installStdinGetChar(m, stdinStream) {
307  if (!stdinStream.tty || !stdinStream.tty.ops) {
308    throw new Error(
309      "stdin stream has no .tty.ops -- stream is not TTY-backed: " +
310        stdinStream.path,
311    );
312  }
313
314  stdinStream.tty.ops.get_char = function (tty) {
315    const b = popByte();
316
317    if (b !== -1) {
318      markReadable(); // reflect the new unread count
319      return b;
320    }
321
322    if (Atomics.load(state, 2) === 1) {
323      console.log("stdin closed");
324      return null; // real EOF
325    }
326
327    return undefined; // no data yet -> Emscripten turns this into EAGAIN
328  };
329}
330
331self.onmessage = async (ev) => {
332  const msg = ev.data;
333
334  if (msg.type === "init") {
335    state = new Int32Array(msg.sab, 0, 3); // [head, tail, closed]
336    ringData = new Uint8Array(msg.sab, 12, CAP); // offset moved from 8 → 12
337    safeStatus("loading wasm...");
338    importScripts("../../zig-out/bin/nvim.js");
339
340    const m = await createNvim({
341      locateFile: (p) =>
342        p.endsWith(".data")
343          ? "../../zig-out/bin/nvim.data"
344          : "../../zig-out/bin/" + p,
345      noInitialRun: true,
346      interactive: false,
347
348      stdout: () => {},
349
350      stderr: (c) => writeStderr(c),
351      tty: false,
352      print: (t) => safeStatus("[print] " + t),
353      printErr: (t) => safeStatus("[printErr] " + t),
354      preRun: [
355        (m) => {
356          m.ENV.TERM = "xterm-256color";
357          m.ENV.HOME = "/home/user";
358          m.ENV.VIMRUNTIME = "/runtime";
359        },
360      ],
361    });
362
363    moduleRef = m;
364
365    const statePtr = m.ccall(
366      "uv_browser_get_shared_state_ptr",
367      "number",
368      [],
369      [],
370    );
371    postMessage({
372      type: "shared-info",
373      memory: m.HEAPU8.buffer,
374      statePtr: statePtr,
375    });
376    postMessage({ type: "ready" });
377    const stdinStream = m.FS.streams[0];
378
379    console.log("stdin stream", stdinStream.path);
380
381    installStdinGetChar(m, stdinStream);
382    const stdoutStream = m.FS.streams[1];
383
384    console.log("stdoutStream ", stdoutStream);
385    console.log(stdoutStream.node);
386    console.log(stdoutStream.node.rdev);
387    console.log(stdoutStream.tty);
388    console.log(stdoutStream.stream_ops);
389
390    console.log("stdout stream", stdoutStream.path);
391    installStdoutWrite(m, stdoutStream);
392    console.log("PATCHED STDOUT WRITE =", m.FS.streams[1].stream_ops.write);
393    await new Promise((res, rej) =>
394      m.FS.syncfs(true, (e) => (e ? rej(e) : res())),
395    );
396    try {
397      m.FS.mkdir("/home/user/.config/nvim");
398    } catch (e) {}
399    try {
400      m.FS.mkdir("/home/user/.local/share/nvim");
401    } catch (e) {}
402    try {
403      m.FS.mkdir("/runtime/parser");
404    } catch (e) {}
405    [
406      "lua",
407      "c",
408      "vim",
409      "vimdoc",
410      "query",
411      "markdown",
412      "markdown_inline",
413    ].forEach((p) => {
414      try {
415        m.FS.writeFile(`/runtime/parser/${p}.so`, "");
416      } catch (e) {}
417    });
418
419    const patchedOps = stdinStream.tty && stdinStream.tty.ops;
420    // Dump every open fd and confirm which fd libuv is actually polling
421    // on and whether it shares the patched tty record. If STDIN_FD
422    // above doesn't match what shows up here as the dup'd stdin fd then
423    // fix the constant at the top of this file.
424    for (let i = 0; i < 16; i++) {
425      const s = m.FS.streams[i];
426      console.log("FD", i, s && s.path, s && s.tty && s.tty.ops === patchedOps);
427    }
428
429    function sanitizeAttr(attr) {
430      attr.dev = attr.dev ?? 1;
431      attr.ino = attr.ino ?? 1;
432      attr.mode = attr.mode ?? 0o666;
433      attr.nlink = attr.nlink ?? 1;
434      attr.uid = attr.uid ?? 0;
435      attr.gid = attr.gid ?? 0;
436      attr.rdev = attr.rdev ?? 0;
437      attr.size =
438        typeof attr.size === "number" && !isNaN(attr.size) ? attr.size : 0;
439      attr.blksize = attr.blksize ?? 4096;
440      attr.blocks = attr.blocks ?? 0;
441      const validDate = (d) => d instanceof Date && !isNaN(d.getTime());
442      attr.atime = validDate(attr.atime) ? attr.atime : new Date(0);
443      attr.mtime = validDate(attr.mtime) ? attr.mtime : new Date(0);
444      attr.ctime = validDate(attr.ctime) ? attr.ctime : new Date(0);
445      return attr;
446    }
447
448    function isStdinLike(path) {
449      const p = path || "";
450      return (
451        p.startsWith("pipe[") || p.includes("my_stdin") || p === "/dev/stdin"
452      );
453    }
454
455    ["fstat", "stat", "lstat"].forEach((name) => {
456      if (typeof m.FS[name] !== "function") return;
457      const orig = m.FS[name].bind(m.FS);
458      m.FS[name] = function (...args) {
459        const attr = orig(...args);
460        const path =
461          name === "fstat"
462            ? m.FS.streams[args[0]] && m.FS.streams[args[0]].path
463            : args[0];
464        if (isStdinLike(path)) {
465          attr.mode = 0o010666;
466        }
467        return sanitizeAttr(attr);
468      };
469    });
470
471    const origFSWrite = m.FS.write;
472    m.FS.write = function (stream, buffer, offset, length, position, canOwn) {
473      console.log("FS.write-----");
474      console.log("fd =", stream.fd);
475      console.log("path =", stream.path);
476
477      console.log("stream_ops =", stream.stream_ops);
478
479      console.log("write fn =", stream.stream_ops && stream.stream_ops.write);
480
481      console.log("stdout write fn =", m.FS.streams[1].stream_ops.write);
482
483      console.log(
484        "same write?",
485        stream.stream_ops &&
486          stream.stream_ops.write === m.FS.streams[1].stream_ops.write,
487      );
488      bumpFdWriteCount(stream.fd);
489      safeStatus(
490        "FS.write fd=" +
491          stream.fd +
492          " path=" +
493          stream.path +
494          " len=" +
495          length +
496          " (fd" +
497          stream.fd +
498          " call#" +
499          perFdWriteCount[stream.fd] +
500          ")",
501      );
502      return origFSWrite.call(
503        this,
504        stream,
505        buffer,
506        offset,
507        length,
508        position,
509        canOwn,
510      );
511    };
512
513    const { argc, argv } = makeArgv(m, ["nvim", "--embed", "--cmd", "set noautoread"]);
514
515    let ret;
516
517    try {
518      safeStatus("Starting Neovim...");
519
520      console.log("CALLING NVIM MAIN");
521
522      const nvimPromise = m._nvim_main(argc, argv);
523
524      console.log("returned:", nvimPromise);
525      console.log("instanceof Promise:", nvimPromise instanceof Promise);
526      console.log("constructor:", nvimPromise?.constructor?.name);
527
528      setTimeout(() => {
529        dumpFD(1);
530        dumpFD(9);
531        dumpFD(10);
532      }, 1000);
533
534      ret = await nvimPromise;
535
536      console.log("NVIM EXITED");
537      postMessage({ type: "exited", code: ret });
538      try {
539        moduleRef.ccall("emscripten_force_exit", null, ["number"], [ret]);
540      } catch (e) {
541        safeStatus("force_exit failed: " + e);
542      }
543      const unread = unreadCount();
544      safeStatus(
545        `_nvim_main RETURNED ret=${ret}, unread bytes still in buffer=${unread}`,
546      );
547    } catch (e) {
548          console.log('CAUGHT EXIT EXCEPTION', e, 'name=', e && e.name, 'status=', e && e.status, 'constructor=', e && e.constructor && e.constructor.name);
549
550      flushAll();
551    if (e && e.name === 'ExitStatus') {
552        safeStatus(`Neovim exited cleanly, code=${e.status}`);
553        ret = e.status;
554    
555    // Notify app.js so it can show a session ended state instead of
556    // leaving the UI looking frozen.
557    postMessage({ type: "exited", code: ret });
558    try {
559          moduleRef.ccall("emscripten_force_exit", null, ["number"], [ret]);
560        } catch (fe) {
561          safeStatus("force_exit failed: " + fe);
562        }
563      }
564    else 
565      {
566        safeStatus('EXCEPTION: ' + e.message + '\nSTACK:\n' + e.stack);
567        throw e;
568    }
569    }
570
571    flushAll();
572
573    const hexStr = consumedBytes
574      .slice(0, 50)
575      .map((x) => x.toString(16).padStart(2, "0"))
576      .join(" ");
577    const remaining =
578      consumedBytes.length > 50
579        ? `... (${consumedBytes.length - 50} more bytes)`
580        : "";
581    safeStatus(
582      `EXIT CODE ${ret}. Read ${totalBytesRead} bytes: ${hexStr}${remaining}`,
583    );
584  }
585
586  if (msg.type === "stdin") {
587    pushBytes(msg.bytes);
588  }
589
590  if (msg.type === "persist") {
591    if (!moduleRef) {
592      postMessage({ type: "persisted", error: "module not ready" });
593      return;
594    }
595    moduleRef.FS.syncfs(false, (e) =>
596      postMessage({ type: "persisted", error: e ? String(e) : null }),
597    );
598  }
599  if (msg.type === "readable-hint") {
600    markReadable();
601  }
602
603  if (msg.type === "dump-counters") {
604    safeStatus(
605      "perFdWriteCount=" +
606        JSON.stringify(perFdWriteCount) +
607        " statusMsgCount=" +
608        statusMsgCount +
609        " suppressed=" +
610        statusCapNoticeSent,
611    );
612  }
613  if (msg.type === "shutdown") {
614    if (state) {
615      Atomics.store(state, 2, 1);
616      Atomics.notify(state, 0); // wake up anything Atomics.wait()ing
617      markReadable(); // also wake the C side futex so uv__io_poll rescans and sees the close
618    }
619  }
620};