aboutsummaryrefslogtreecommitdiff
path: root/lib/build-web/main.js
blob: 801a89afc51e7554171dfbfc1aa27988147a5f22 (plain)
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
const domConnectionStatus = document.getElementById("connectionStatus");
const domFirefoxWebSocketBullshitExplainer = document.getElementById("firefoxWebSocketBullshitExplainer");

const domMain = document.getElementsByTagName("main")[0];
const domSummary = {
  stepCount: document.getElementById("summaryStepCount"),
  status: document.getElementById("summaryStatus"),
};
const domButtonRebuild = document.getElementById("buttonRebuild");
const domStepList = document.getElementById("stepList");
let domSteps = [];

let wasm_promise = fetch("main.wasm");
let wasm_exports = null;

const text_decoder = new TextDecoder();
const text_encoder = new TextEncoder();

domButtonRebuild.addEventListener("click", () => wasm_exports.rebuild());

setConnectionStatus("Loading WebAssembly...", false);
WebAssembly.instantiateStreaming(wasm_promise, {
  core: {
    log: function(ptr, len) {
      const msg = decodeString(ptr, len);
      console.log(msg);
    },
    panic: function (ptr, len) {
      const msg = decodeString(ptr, len);
      throw new Error("panic: " + msg);
    },
    timestamp: function () {
      return BigInt(new Date());
    },
    hello: hello,
    updateBuildStatus: updateBuildStatus,
    updateStepStatus: updateStepStatus,
    sendWsMessage: (ptr, len) => ws.send(new Uint8Array(wasm_exports.memory.buffer, ptr, len)),
  },
  fuzz: {
    requestSources: fuzzRequestSources,
    ready: fuzzReady,
    updateStats: fuzzUpdateStats,
    updateEntryPoints: fuzzUpdateEntryPoints,
    updateSource: fuzzUpdateSource,
    updateCoverage: fuzzUpdateCoverage,
  },
  time_report: {
    updateGeneric: timeReportUpdateGeneric,
    updateCompile: timeReportUpdateCompile,
    updateRunTest: timeReportUpdateRunTest,
  },
}).then(function(obj) {
  setConnectionStatus("Connecting to WebSocket...", true);
  connectWebSocket();

  wasm_exports = obj.instance.exports;
  window.wasm = obj; // for debugging
});

function connectWebSocket() {
  const host = document.location.host;
  const pathname = document.location.pathname;
  const isHttps = document.location.protocol === 'https:';
  const match = host.match(/^(.+):(\d+)$/);
  const defaultPort = isHttps ? 443 : 80;
  const port = match ? parseInt(match[2], 10) : defaultPort;
  const hostName = match ? match[1] : host;
  const wsProto = isHttps ? "wss:" : "ws:";
  const wsUrl = wsProto + '//' + hostName + ':' + port + pathname;
  ws = new WebSocket(wsUrl);
  ws.binaryType = "arraybuffer";
  ws.addEventListener('message', onWebSocketMessage, false);
  ws.addEventListener('error', onWebSocketClose, false);
  ws.addEventListener('close', onWebSocketClose, false);
  ws.addEventListener('open', onWebSocketOpen, false);
}
function onWebSocketOpen() {
  setConnectionStatus("Waiting for data...", false);
}
function onWebSocketMessage(ev) {
  const jsArray = new Uint8Array(ev.data);
  const ptr = wasm_exports.message_begin(jsArray.length);
  const wasmArray = new Uint8Array(wasm_exports.memory.buffer, ptr, jsArray.length);
  wasmArray.set(jsArray);
  wasm_exports.message_end();
}
function onWebSocketClose() {
  setConnectionStatus("WebSocket connection closed. Re-connecting...", true);
  ws.removeEventListener('message', onWebSocketMessage, false);
  ws.removeEventListener('error', onWebSocketClose, false);
  ws.removeEventListener('close', onWebSocketClose, false);
  ws.removeEventListener('open', onWebSocketOpen, false);
  ws = null;
  setTimeout(connectWebSocket, 1000);
}

function setConnectionStatus(msg, is_websocket_connect) {
  domConnectionStatus.textContent = msg;
  if (msg.length > 0) {
    domConnectionStatus.classList.remove("hidden");
    domMain.classList.add("hidden");
  } else {
    domConnectionStatus.classList.add("hidden");
    domMain.classList.remove("hidden");
  }
  if (is_websocket_connect) {
    domFirefoxWebSocketBullshitExplainer.classList.remove("hidden");
  } else {
    domFirefoxWebSocketBullshitExplainer.classList.add("hidden");
  }
}

function hello(
  steps_len,
  build_status,
  time_report,
) {
  domSummary.stepCount.textContent = steps_len;
  updateBuildStatus(build_status);
  setConnectionStatus("", false);

  {
    let entries = [];
    for (let i = 0; i < steps_len; i += 1) {
      const step_name = unwrapString(wasm_exports.stepName(i));
      const code = document.createElement("code");
      code.textContent = step_name;
      const li = document.createElement("li");
      li.appendChild(code);
      entries.push(li);
    }
    domStepList.replaceChildren(...entries);
    for (let i = 0; i < steps_len; i += 1) {
      updateStepStatus(i);
    }
  }

  if (time_report) timeReportReset(steps_len);
  fuzzReset();
}

function updateBuildStatus(s) {
  let text;
  let active = false;
  let reset_time_reports = false;
  if (s == 0) {
    text = "Idle";
  } else if (s == 1) {
    text = "Watching for changes...";
  } else if (s == 2) {
    text = "Running...";
    active = true;
    reset_time_reports = true;
  } else if (s == 3) {
    text = "Starting fuzzer...";
    active = true;
  } else {
    console.log(`bad build status: ${s}`);
  }
  domSummary.status.textContent = text;
  if (active) {
    domSummary.status.classList.add("status-running");
    domSummary.status.classList.remove("status-idle");
    domButtonRebuild.disabled = true;
  } else {
    domSummary.status.classList.remove("status-running");
    domSummary.status.classList.add("status-idle");
    domButtonRebuild.disabled = false;
  }
  if (reset_time_reports) {
    // Grey out and collapse all the time reports
    for (const time_report_host of domTimeReportList.children) {
      const details = time_report_host.shadowRoot.querySelector(":host > details");
      details.classList.add("pending");
      details.open = false;
    }
  }
}
function updateStepStatus(step_idx) {
  const li = domStepList.children[step_idx];
  const step_status = wasm_exports.stepStatus(step_idx);
  li.classList.remove("step-wip", "step-success", "step-failure");
  if (step_status == 0) {
    // pending
  } else if (step_status == 1) {
    li.classList.add("step-wip");
  } else if (step_status == 2) {
    li.classList.add("step-success");
  } else if (step_status == 3) {
    li.classList.add("step-failure");
  } else {
    console.log(`bad step status: ${step_status}`);
  }
}

function decodeString(ptr, len) {
  if (len === 0) return "";
  return text_decoder.decode(new Uint8Array(wasm_exports.memory.buffer, ptr, len));
}
function getU32Array(ptr, len) {
  if (len === 0) return new Uint32Array();
  return new Uint32Array(wasm_exports.memory.buffer, ptr, len);
}
function unwrapString(bigint) {
  const ptr = Number(bigint & 0xffffffffn);
  const len = Number(bigint >> 32n);
  return decodeString(ptr, len);
}

const time_report_entry_template = document.getElementById("timeReportEntryTemplate").content;
const domTimeReport = document.getElementById("timeReport");
const domTimeReportList = document.getElementById("timeReportList");
function timeReportReset(steps_len) {
  let entries = [];
  for (let i = 0; i < steps_len; i += 1) {
    const step_name = unwrapString(wasm_exports.stepName(i));
    const host = document.createElement("div");
    const shadow = host.attachShadow({ mode: "open" });
    shadow.appendChild(time_report_entry_template.cloneNode(true));
    shadow.querySelector(":host > details").classList.add("pending");
    const slotted_name = document.createElement("code");
    slotted_name.setAttribute("slot", "step-name");
    slotted_name.textContent = step_name;
    host.appendChild(slotted_name);
    entries.push(host);
  }
  domTimeReportList.replaceChildren(...entries);
  domTimeReport.classList.remove("hidden");
}
function timeReportUpdateCompile(
  step_idx,
  inner_html_ptr,
  inner_html_len,
  file_table_html_ptr,
  file_table_html_len,
  decl_table_html_ptr,
  decl_table_html_len,
  use_llvm,
) {
  const inner_html = decodeString(inner_html_ptr, inner_html_len);
  const file_table_html = decodeString(file_table_html_ptr, file_table_html_len);
  const decl_table_html = decodeString(decl_table_html_ptr, decl_table_html_len);

  const host = domTimeReportList.children.item(step_idx);
  const shadow = host.shadowRoot;

  shadow.querySelector(":host > details").classList.remove("pending", "no-llvm");

  shadow.getElementById("genericReport").classList.add("hidden");
  shadow.getElementById("compileReport").classList.remove("hidden");
  shadow.getElementById("runTestReport").classList.add("hidden");

  if (!use_llvm) shadow.querySelector(":host > details").classList.add("no-llvm");
  host.innerHTML = inner_html;
  shadow.getElementById("fileTableBody").innerHTML = file_table_html;
  shadow.getElementById("declTableBody").innerHTML = decl_table_html;
}
function timeReportUpdateGeneric(
  step_idx,
  inner_html_ptr,
  inner_html_len,
) {
  const inner_html = decodeString(inner_html_ptr, inner_html_len);
  const host = domTimeReportList.children.item(step_idx);
  const shadow = host.shadowRoot;
  shadow.querySelector(":host > details").classList.remove("pending", "no-llvm");
  shadow.getElementById("genericReport").classList.remove("hidden");
  shadow.getElementById("compileReport").classList.add("hidden");
  shadow.getElementById("runTestReport").classList.add("hidden");
  host.innerHTML = inner_html;
}
function timeReportUpdateRunTest(
  step_idx,
  table_html_ptr,
  table_html_len,
) {
  const table_html = decodeString(table_html_ptr, table_html_len);
  const host = domTimeReportList.children.item(step_idx);
  const shadow = host.shadowRoot;

  shadow.querySelector(":host > details").classList.remove("pending", "no-llvm");

  shadow.getElementById("genericReport").classList.add("hidden");
  shadow.getElementById("compileReport").classList.add("hidden");
  shadow.getElementById("runTestReport").classList.remove("hidden");

  shadow.getElementById("runTestTableBody").innerHTML = table_html;
}

const fuzz_entry_template = document.getElementById("fuzzEntryTemplate").content;
const domFuzz = document.getElementById("fuzz");
const domFuzzStatus = document.getElementById("fuzzStatus");
const domFuzzEntries = document.getElementById("fuzzEntries");
let domFuzzInstance = null;
function fuzzRequestSources() {
  domFuzzStatus.classList.remove("hidden");
  domFuzzStatus.textContent = "Loading sources tarball...";
  fetch("sources.tar").then(function(response) {
    if (!response.ok) throw new Error("unable to download sources");
    domFuzzStatus.textContent = "Parsing fuzz test sources...";
    return response.arrayBuffer();
  }).then(function(buffer) {
    if (buffer.length === 0) throw new Error("sources.tar was empty");
    const js_array = new Uint8Array(buffer);
    const ptr = wasm_exports.alloc(js_array.length);
    const wasm_array = new Uint8Array(wasm_exports.memory.buffer, ptr, js_array.length);
    wasm_array.set(js_array);
    wasm_exports.fuzzUnpackSources(ptr, js_array.length);
    domFuzzStatus.textContent = "";
    domFuzzStatus.classList.add("hidden");
  });
}
function fuzzReady() {
  domFuzz.classList.remove("hidden");

  // TODO: multiple fuzzer instances
  if (domFuzzInstance !== null) return;

  const host = document.createElement("div");
  const shadow = host.attachShadow({ mode: "open" });
  shadow.appendChild(fuzz_entry_template.cloneNode(true));

  domFuzzInstance = host;
  domFuzzEntries.appendChild(host);
}
function fuzzReset() {
  domFuzz.classList.add("hidden");
  domFuzzEntries.replaceChildren();
  domFuzzInstance = null;
}
function fuzzUpdateStats(stats_html_ptr, stats_html_len) {
  if (domFuzzInstance === null) throw new Error("fuzzUpdateStats called when fuzzer inactive");
  const stats_html = decodeString(stats_html_ptr, stats_html_len);
  const host = domFuzzInstance;
  host.innerHTML = stats_html;
}
function fuzzUpdateEntryPoints(entry_points_html_ptr, entry_points_html_len) {
  if (domFuzzInstance === null) throw new Error("fuzzUpdateEntryPoints called when fuzzer inactive");
  const entry_points_html = decodeString(entry_points_html_ptr, entry_points_html_len);
  const domEntryPointList = domFuzzInstance.shadowRoot.getElementById("entryPointList");
  domEntryPointList.innerHTML = entry_points_html;
}
function fuzzUpdateSource(source_html_ptr, source_html_len) {
  if (domFuzzInstance === null) throw new Error("fuzzUpdateSource called when fuzzer inactive");
  const source_html = decodeString(source_html_ptr, source_html_len);
  const domSourceText = domFuzzInstance.shadowRoot.getElementById("sourceText");
  domSourceText.innerHTML = source_html;
  domFuzzInstance.shadowRoot.getElementById("source").classList.remove("hidden");
}
function fuzzUpdateCoverage(covered_ptr, covered_len) {
  if (domFuzzInstance === null) throw new Error("fuzzUpdateCoverage called when fuzzer inactive");
  const shadow = domFuzzInstance.shadowRoot;
  const domSourceText = shadow.getElementById("sourceText");
  const covered = getU32Array(covered_ptr, covered_len);
  for (let i = 0; i < domSourceText.children.length; i += 1) {
    const childDom = domSourceText.children[i];
    if (childDom.id != null && childDom.id[0] == "l") {
      childDom.classList.add("l");
      childDom.classList.remove("c");
    }
  }
  for (const sli of covered) {
    shadow.getElementById(`l${sli}`).classList.add("c");
  }
}