-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
460 lines (419 loc) · 13.9 KB
/
worker.js
File metadata and controls
460 lines (419 loc) · 13.9 KB
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//previously loader.js but now integrated into worker.js
var Module = {};
function Loader(config) {
function webAssemblySupported() {
return typeof WebAssembly !== "undefined";
}
function canLoad() {
return webAssemblySupported();
}
// Set default state handler functions and create canvases if needed
if (config.containerElements !== undefined) {
config.showError =
config.showError ||
function (errorText, container) {
removeChildren(container);
var errorTextElement = document.createElement("text");
errorTextElement.className = "Error";
errorTextElement.innerHTML = errorText;
return errorTextElement;
};
config.showLoader =
config.showLoader ||
function (loadingState, container) {
removeChildren(container);
var loadingText = document.createElement("text");
loadingText.className = "Loading";
loadingText.innerHTML = "<p><center> ${loadingState}...</center><p>";
return loadingText;
};
config.showExit =
config.showExit ||
function (crashed, exitCode, container) {
if (!crashed) return undefined;
removeChildren(container);
var fontSize = 54;
var crashSymbols = [
"\u{1F615}",
"\u{1F614}",
"\u{1F644}",
"\u{1F928}",
"\u{1F62C}",
"\u{1F915}",
"\u{2639}",
"\u{1F62E}",
"\u{1F61E}",
"\u{1F633}",
];
var symbolIndex = Math.floor(Math.random() * crashSymbols.length);
var errorHtml = `<font size='${fontSize}'> ${crashSymbols[symbolIndex]} </font>`;
var errorElement = document.createElement("text");
errorElement.className = "Exit";
errorElement.innerHTML = errorHtml;
return errorElement;
};
}
config.restartMode = config.restartMode || "RestartOnCrash";
if (config.stdoutEnabled === undefined) config.stdoutEnabled = true;
if (config.stderrEnabled === undefined) config.stderrEnabled = true;
// Make sure config.path is defined and ends with "/" if needed
if (config.path === undefined) config.path = "";
if (config.path.length > 0 && !config.path.endsWith("/"))
config.path = config.path.concat("/");
if (config.environment === undefined) config.environment = {};
var pAPI = {};
pAPI.webAssemblySupported = webAssemblySupported();
pAPI.canLoad = canLoad();
pAPI.canLoadApplication = canLoad();
pAPI.status = undefined;
pAPI.loadModule = loadModule;
restartCount = 0;
function fetchResource(filePath) {
var fullPath = config.path + filePath;
return fetch(fullPath).then(function (response) {
if (!response.ok) {
self.error =
response.status + " " + response.statusText + " " + response.url;
setStatus("Error");
return Promise.reject(self.error);
} else {
return response;
}
});
}
function fetchText(filePath) {
return fetchResource(filePath).then(function (response) {
return response.text();
});
}
function fetchThenCompileWasm(response) {
return response.arrayBuffer().then(function (data) {
self.loaderSubState = "Compiling";
setStatus("Loading"); // trigger loaderSubState udpate
return WebAssembly.compile(data);
});
}
function fetchCompileWasm(filePath) {
return fetchResource(filePath).then(function (response) {
const contentLength = response.headers.get("Content-Length");
const total = parseInt(contentLength, 10);
let loaded = 0;
const reader = response.body.getReader();
const stream = new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
controller.close();
self.postMessage({ type: "wasmProgress", progress: 100 }); // Send 100% completion
return;
}
loaded += value.length;
const progress = (loaded / total) * 100;
self.postMessage({
type: "wasmProgress",
progress: Math.round(progress),
}); // Send progress to main thread
controller.enqueue(value);
push();
});
}
push();
},
});
const response2 = new Response(stream, response);
if (typeof WebAssembly.compileStreaming !== "undefined") {
self.loaderSubState = "Downloading/Compiling";
setStatus("Loading");
return WebAssembly.compileStreaming(response2).catch(function (error) {
return fetchThenCompileWasm(response2);
});
} else return fetchThenCompileWasm(response2);
});
}
function loadModule(applicationName) {
// Loading in loader.js goes through four steps:
// 1) Check prerequisites
// 2) Download resources
// 3) Configure the emscripten Module object
// 4) Start the emcripten runtime, after which emscripten takes over
// Check for Wasm support, we dont care about WebGL; set error and return before downloading resources if missing
if (!webAssemblySupported()) {
self.error = "Error: WebAssembly is not supported";
setStatus("Error");
return;
}
// Continue waiting if loadModule() is called again
if (pAPI.status == "Loading") return;
self.loaderSubState = "Downloading";
setStatus("Loading");
// Fetch emscripten generated javascript runtime
var emscriptenModuleSource = undefined;
var emscriptenModuleSourcePromise = fetchText(applicationName + ".js").then(
function (source) {
emscriptenModuleSource = source;
},
);
// Fetch and compile wasm module
var wasmModule = undefined;
var wasmModulePromise = fetchCompileWasm(applicationName + ".wasm").then(
function (module) {
wasmModule = module;
},
);
// Wait for all resources ready
Promise.all([emscriptenModuleSourcePromise, wasmModulePromise])
.then(function () {
completeloadModule(applicationName, emscriptenModuleSource, wasmModule);
})
.catch(function (error) {
self.error = error;
setStatus("Error");
});
}
function completeloadModule(
applicationName,
emscriptenModuleSource,
wasmModule,
) {
// The wasm binary has been compiled into a module during resource download,
// and is ready to be instantiated. Define the instantiateWasm callback which
// emscripten will call to create the instance.
Module.instantiateWasm = function (imports, successCallback) {
WebAssembly.instantiate(wasmModule, imports).then(
function (instance) {
successCallback(instance, wasmModule);
},
function (error) {
self.error = error;
setStatus("Error");
},
);
return {};
};
Module.locateFile =
Module.locateFile ||
function (filename) {
return config.path + filename;
};
// Attach status callbacks
Module.setStatus =
Module.setStatus ||
function (text) {
// Currently the only usable status update from this function
// is "Running..."
if (text.startsWith("Running")) setStatus("Running");
};
Module.monitorRunDependencies =
Module.monitorRunDependencies ||
function (left) {
// console.log("monitorRunDependencies " + left)
};
// Attach standard out/err callbacks.
Module.print =
Module.print ||
function (text) {
if (config.stdoutEnabled) {
console.log(text);
const output = document.getElementById("output");
output.appendChild(document.createTextNode(text));
output.appendChild(document.createElement("br"));
}
};
Module.printErr =
Module.printErr ||
function (text) {
// Filter out OpenGL getProcAddress warnings. Loader to resolve
// all possible function/extension names at startup which causes
// emscripten to spam the console log with warnings.
if (
text.startsWith !== undefined &&
text.startsWith("bad name in getProcAddress:")
)
return;
if (config.stderrEnabled) console.log(text);
};
// Error handling: set status to "Exited", update crashed and
// exitCode according to exit type.
// Emscripten will typically call printErr with the error text
// as well. Note that emscripten may also throw exceptions from
// async callbacks. These should be handled in window.onerror by user code.
Module.onAbort =
Module.onAbort ||
function (text) {
pAPI.crashed = true;
pAPI.exitText = text;
setStatus("Exited");
};
Module.quit =
Module.quit ||
function (code, exception) {
if (exception.name == "ExitStatus") {
// Clean exit with code
pAPI.exitText = undefined;
pAPI.exitCode = code;
} else {
pAPI.exitText = exception.toString();
pAPI.crashed = true;
}
setStatus("Exited");
};
// Set environment variables
Module.preRun = Module.preRun || [];
Module.preRun.push(function () {
for (var [key, value] of Object.entries(config.environment)) {
ENV[key.toUpperCase()] = value;
}
});
Module.mainScriptUrlOrBlob = new Blob([emscriptenModuleSource], {
type: "text/javascript",
});
pAPI.exitCode = undefined;
pAPI.exitText = undefined;
pAPI.crashed = false;
// Finally evaluate the emscripten application script, which will
// reference the global Module object created above.
self.eval(emscriptenModuleSource); // ES5 indirect global scope eval
}
function setErrorContent() {
if (config.containerElements === undefined) {
if (config.showError !== undefined) config.showError(self.error);
return;
}
for (container of config.containerElements) {
var errorElement = config.showError(self.error, container);
container.appendChild(errorElement);
}
}
function setExitContent() {
if (pAPI.status != "Exited") return;
if (config.containerElements === undefined) {
if (config.showExit !== undefined)
config.showExit(pAPI.crashed, pAPI.exitCode);
return;
}
if (!pAPI.crashed) return;
for (container of config.containerElements) {
var loaderElement = config.showExit(
pAPI.crashed,
pAPI.exitCode,
container,
);
if (loaderElement !== undefined) container.appendChild(loaderElement);
}
}
var committedStatus = undefined;
function handleStatusChange() {
if (pAPI.status != "Loading" && committedStatus == pAPI.status) return;
committedStatus = pAPI.status;
if (pAPI.status == "Error") setErrorContent();
else if (pAPI.status == "Exited") setExitContent();
// Send status change notification
if (config.statusChanged) config.statusChanged(pAPI.status);
}
function setStatus(status) {
if (status != "Loading" && pAPI.status == status) return;
pAPI.status = status;
if (typeof window !== "undefined") {
window.setTimeout(function () {
handleStatusChange();
}, 0);
} else {
// We're in a Web Worker
setTimeout(function () {
handleStatusChange();
}, 0);
}
}
setStatus("Created");
return pAPI;
}
// above is the old loader.js, added to this file for simplicity
// do not modify unless absolutely needed
//cleans up the files because they arnt reliably deleted by closing tab or other things.
//spam this function in any case where we are unsure of the virtual FS state.
function fsCleanup() {
const filesToDelete = ["/INPUT.ROM", "/patch.txt", "/OUTPUT.ROM"];
for (const file of filesToDelete) {
try {
if (FS.analyzePath(file).exists) {
FS.unlink(file);
}
} catch (e) {
console.log(`Deleting ${file} failed.`);
}
}
}
//setup message forwarding for printing and initialization
var Module = {
print: function (text) {
postMessage({ type: "stdout", text: text });
},
printErr: function (text) {
postMessage({ type: "stderr", text: text });
},
};
//initialize the loader, setup error forwarding
var Loader = Loader({
showError: function (errorText) {
postMessage({ type: "error", text: errorText });
},
// only post "ready" once when status first becomes "Running"
statusChanged: function (status) {
if (status === "Running") {
postMessage({ type: "ready" });
}
},
});
//finally load the emscripten module
Loader.loadModule("UEFIPatch");
//handle passed message
self.onmessage = function (e) {
if (e.data.type === "runPatch") {
//get the inputs
var inputRomArray = e.data.inputRomArray;
var patchesTxt = e.data.patchesTxt;
//attempt to write the inputs to the virtual FS,
try {
FS.writeFile("/INPUT.ROM", inputRomArray);
FS.writeFile("/patch.txt", patchesTxt);
} catch (e) {
//clean up FS, log error if it fails
console.log("Writing input and/or patch to virtual FS failed.");
fsCleanup();
postMessage({
type: "error",
text: "Could not write input and/or patch to virtual FS.",
});
return;
}
//actually call the wasm module from the worker thread,
//preventing the main thread from being blocked
try {
Module.ccall("runPatch", null, [], []);
} catch (e) {
console.log("Calling runPatch failed.");
fsCleanup();
postMessage({
type: "error",
text: "Could not run patch. Calling the wasm module failed. For an unknown reason.",
});
return;
}
// attempt to read the output ROM after the module finishes
try {
var outputData = FS.readFile("/OUTPUT.ROM");
fsCleanup();
postMessage({ type: "complete", data: outputData });
} catch (e) {
//if fail
//clean up FS, log error
fsCleanup();
postMessage({
type: "error",
text: "Failed to read output ROM. It may not exist.",
});
return;
}
}
};