File size: 5,056 Bytes
022cb3a
b09157d
022cb3a
 
 
b09157d
022cb3a
 
 
 
 
 
 
 
 
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022cb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b09157d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
022cb3a
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { WASI, WASIProcExit, ConsoleStdout } from "@bjorn3/browser_wasi_shim";
import { createDebugInspector } from './debugRuntime.js';

// JSPI suspends only this worker while the learner types or Reachy speaks.
// No shared memory, server execution, filesystem or network capabilities.
export async function executeC(binary, { read, write, debug, inspect }) {
  if (!WebAssembly.Suspending || !WebAssembly.promising) {
    throw new Error("Interactive C needs a recent Chrome or Edge browser (WebAssembly JSPI).");
  }
  const terminal = () => new ConsoleStdout(() => {});
  const wasi = new WASI(["main"], [], [terminal(), terminal(), terminal()]);
  let instance;
  let pending = new Uint8Array();
  let eof = false;
  const imports = { ...wasi.wasiImport };
  // WASI clock subscriptions implement nanosleep/sleep without a busy loop.
  imports.poll_oneoff = new WebAssembly.Suspending(async (input, output, count, result) => {
    if (count !== 1) return 28;
    let view = new DataView(instance.exports.memory.buffer);
    if (view.getUint8(input + 8) !== 0) return 58;
    const id = view.getUint32(input + 16, true);
    if (id !== 0 && id !== 1) return 28;
    const userdata = view.getBigUint64(input, true);
    const timeout = Number(view.getBigUint64(input + 24, true)) / 1e6;
    const absolute = view.getUint16(input + 40, true) & 1;
    const milliseconds = Math.max(0, timeout - (absolute ? id === 0 ? Date.now() : performance.now() : 0));
    if (!Number.isFinite(milliseconds) || milliseconds > 10000) throw new Error('Une attente ne doit pas dépasser 10 secondes.');
    await new Promise(resolve => setTimeout(resolve, milliseconds));
    view = new DataView(instance.exports.memory.buffer);
    new Uint8Array(instance.exports.memory.buffer, output, 32).fill(0);
    view.setBigUint64(output, userdata, true); view.setUint32(result, 1, true);
    return 0;
  });
  imports.fd_read = new WebAssembly.Suspending(async (fd, iovs, count, result) => {
    if (fd !== 0) return 8; // EBADF
    let view = new DataView(instance.exports.memory.buffer);
    let capacity = 0;
    for (let i = 0; i < count; i++) capacity += view.getUint32(iovs + i * 8 + 4, true);
    if (capacity && !pending.length && !eof) {
      const line = await read();
      eof = line === null;
      pending = eof ? new Uint8Array() : new TextEncoder().encode(line);
    }
    view = new DataView(instance.exports.memory.buffer);
    const memory = new Uint8Array(instance.exports.memory.buffer);
    let total = 0;
    for (let i = 0; i < count; i++) {
      const address = view.getUint32(iovs + i * 8, true);
      const size = Math.min(view.getUint32(iovs + i * 8 + 4, true), pending.length);
      memory.set(pending.subarray(0, size), address);
      pending = pending.subarray(size);
      total += size;
    }
    view.setUint32(result, total, true);
    return 0;
  });
  const decoders = { 1: new TextDecoder(), 2: new TextDecoder() };
  let outputBytes = 0;
  imports.fd_write = new WebAssembly.Suspending(async (fd, iovs, count, result) => {
    if (fd !== 1 && fd !== 2) return 8;
    const view = new DataView(instance.exports.memory.buffer);
    const memory = new Uint8Array(instance.exports.memory.buffer);
    let total = 0, text = "";
    for (let i = 0; i < count; i++) {
      const address = view.getUint32(iovs + i * 8, true);
      const length = view.getUint32(iovs + i * 8 + 4, true);
      outputBytes += length;
      if (outputBytes > 32768) throw new Error("Output limit reached (32 KB). Check your loops.");
      text += decoders[fd].decode(memory.subarray(address, address + length), { stream: true });
      total += length;
    }
    if (text) await write(fd, text);
    new DataView(instance.exports.memory.buffer).setUint32(result, total, true);
    return 0;
  });
  const module = await WebAssembly.compile(binary);
  let variables = [], inspector;
  const string = address => {
    const bytes = new Uint8Array(instance.exports.memory.buffer);
    let end = address;
    while (end < bytes.length && bytes[end] && end - address < 4096) end++;
    return new TextDecoder().decode(bytes.subarray(address, end));
  };
  instance = await WebAssembly.instantiate(module, { wasi_snapshot_preview1: imports, debug: {
    reset: () => { variables = []; },
    value: (name, type, address, size) => {
      const label = string(type);
      variables.push({ name: string(name), type: label, address, size });
    },
    pause: new WebAssembly.Suspending(async (line, site, depth, fn) => {
      if (debug) await debug({ line, site, depth, function: string(fn) }, () => inspector.snapshot(variables));
    }),
  } });
  inspector = createDebugInspector(instance.exports.memory);
  inspect?.(inspector.page);
  wasi.inst = instance;
  let code = 0;
  try { await WebAssembly.promising(instance.exports._start)(); }
  catch (error) { if (error instanceof WASIProcExit) code = error.code; else throw error; }
  for (const fd of [1, 2]) {
    const tail = decoders[fd].decode();
    if (tail) await write(fd, tail);
  }
  return code;
}