wasm_exec.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. "use strict";
  5. (() => {
  6. const enosys = () => {
  7. const err = new Error("not implemented");
  8. err.code = "ENOSYS";
  9. return err;
  10. };
  11. if (!globalThis.fs) {
  12. let outputBuf = "";
  13. globalThis.fs = {
  14. constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
  15. writeSync(fd, buf) {
  16. outputBuf += decoder.decode(buf);
  17. const nl = outputBuf.lastIndexOf("\n");
  18. if (nl != -1) {
  19. console.log(outputBuf.substr(0, nl));
  20. outputBuf = outputBuf.substr(nl + 1);
  21. }
  22. return buf.length;
  23. },
  24. write(fd, buf, offset, length, position, callback) {
  25. if (offset !== 0 || length !== buf.length || position !== null) {
  26. callback(enosys());
  27. return;
  28. }
  29. const n = this.writeSync(fd, buf);
  30. callback(null, n);
  31. },
  32. chmod(path, mode, callback) { callback(enosys()); },
  33. chown(path, uid, gid, callback) { callback(enosys()); },
  34. close(fd, callback) { callback(enosys()); },
  35. fchmod(fd, mode, callback) { callback(enosys()); },
  36. fchown(fd, uid, gid, callback) { callback(enosys()); },
  37. fstat(fd, callback) { callback(enosys()); },
  38. fsync(fd, callback) { callback(null); },
  39. ftruncate(fd, length, callback) { callback(enosys()); },
  40. lchown(path, uid, gid, callback) { callback(enosys()); },
  41. link(path, link, callback) { callback(enosys()); },
  42. lstat(path, callback) { callback(enosys()); },
  43. mkdir(path, perm, callback) { callback(enosys()); },
  44. open(path, flags, mode, callback) { callback(enosys()); },
  45. read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
  46. readdir(path, callback) { callback(enosys()); },
  47. readlink(path, callback) { callback(enosys()); },
  48. rename(from, to, callback) { callback(enosys()); },
  49. rmdir(path, callback) { callback(enosys()); },
  50. stat(path, callback) { callback(enosys()); },
  51. symlink(path, link, callback) { callback(enosys()); },
  52. truncate(path, length, callback) { callback(enosys()); },
  53. unlink(path, callback) { callback(enosys()); },
  54. utimes(path, atime, mtime, callback) { callback(enosys()); },
  55. };
  56. }
  57. if (!globalThis.process) {
  58. globalThis.process = {
  59. getuid() { return -1; },
  60. getgid() { return -1; },
  61. geteuid() { return -1; },
  62. getegid() { return -1; },
  63. getgroups() { throw enosys(); },
  64. pid: -1,
  65. ppid: -1,
  66. umask() { throw enosys(); },
  67. cwd() { throw enosys(); },
  68. chdir() { throw enosys(); },
  69. }
  70. }
  71. if (!globalThis.crypto) {
  72. throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
  73. }
  74. if (!globalThis.performance) {
  75. throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
  76. }
  77. if (!globalThis.TextEncoder) {
  78. throw new Error("globalThis.TextEncoder is not available, polyfill required");
  79. }
  80. if (!globalThis.TextDecoder) {
  81. throw new Error("globalThis.TextDecoder is not available, polyfill required");
  82. }
  83. const encoder = new TextEncoder("utf-8");
  84. const decoder = new TextDecoder("utf-8");
  85. globalThis.Go = class {
  86. constructor() {
  87. this.argv = ["js"];
  88. this.env = {};
  89. this.exit = (code) => {
  90. if (code !== 0) {
  91. console.warn("exit code:", code);
  92. }
  93. };
  94. this._exitPromise = new Promise((resolve) => {
  95. this._resolveExitPromise = resolve;
  96. });
  97. this._pendingEvent = null;
  98. this._scheduledTimeouts = new Map();
  99. this._nextCallbackTimeoutID = 1;
  100. const setInt64 = (addr, v) => {
  101. this.mem.setUint32(addr + 0, v, true);
  102. this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
  103. }
  104. const getInt64 = (addr) => {
  105. const low = this.mem.getUint32(addr + 0, true);
  106. const high = this.mem.getInt32(addr + 4, true);
  107. return low + high * 4294967296;
  108. }
  109. const loadValue = (addr) => {
  110. const f = this.mem.getFloat64(addr, true);
  111. if (f === 0) {
  112. return undefined;
  113. }
  114. if (!isNaN(f)) {
  115. return f;
  116. }
  117. const id = this.mem.getUint32(addr, true);
  118. return this._values[id];
  119. }
  120. const storeValue = (addr, v) => {
  121. const nanHead = 0x7FF80000;
  122. if (typeof v === "number" && v !== 0) {
  123. if (isNaN(v)) {
  124. this.mem.setUint32(addr + 4, nanHead, true);
  125. this.mem.setUint32(addr, 0, true);
  126. return;
  127. }
  128. this.mem.setFloat64(addr, v, true);
  129. return;
  130. }
  131. if (v === undefined) {
  132. this.mem.setFloat64(addr, 0, true);
  133. return;
  134. }
  135. let id = this._ids.get(v);
  136. if (id === undefined) {
  137. id = this._idPool.pop();
  138. if (id === undefined) {
  139. id = this._values.length;
  140. }
  141. this._values[id] = v;
  142. this._goRefCounts[id] = 0;
  143. this._ids.set(v, id);
  144. }
  145. this._goRefCounts[id]++;
  146. let typeFlag = 0;
  147. switch (typeof v) {
  148. case "object":
  149. if (v !== null) {
  150. typeFlag = 1;
  151. }
  152. break;
  153. case "string":
  154. typeFlag = 2;
  155. break;
  156. case "symbol":
  157. typeFlag = 3;
  158. break;
  159. case "function":
  160. typeFlag = 4;
  161. break;
  162. }
  163. this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
  164. this.mem.setUint32(addr, id, true);
  165. }
  166. const loadSlice = (addr) => {
  167. const array = getInt64(addr + 0);
  168. const len = getInt64(addr + 8);
  169. return new Uint8Array(this._inst.exports.mem.buffer, array, len);
  170. }
  171. const loadSliceOfValues = (addr) => {
  172. const array = getInt64(addr + 0);
  173. const len = getInt64(addr + 8);
  174. const a = new Array(len);
  175. for (let i = 0; i < len; i++) {
  176. a[i] = loadValue(array + i * 8);
  177. }
  178. return a;
  179. }
  180. const loadString = (addr) => {
  181. const saddr = getInt64(addr + 0);
  182. const len = getInt64(addr + 8);
  183. return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
  184. }
  185. const timeOrigin = Date.now() - performance.now();
  186. this.importObject = {
  187. go: {
  188. // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
  189. // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
  190. // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
  191. // This changes the SP, thus we have to update the SP used by the imported function.
  192. // func wasmExit(code int32)
  193. "runtime.wasmExit": (sp) => {
  194. sp >>>= 0;
  195. const code = this.mem.getInt32(sp + 8, true);
  196. this.exited = true;
  197. delete this._inst;
  198. delete this._values;
  199. delete this._goRefCounts;
  200. delete this._ids;
  201. delete this._idPool;
  202. this.exit(code);
  203. },
  204. // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
  205. "runtime.wasmWrite": (sp) => {
  206. sp >>>= 0;
  207. const fd = getInt64(sp + 8);
  208. const p = getInt64(sp + 16);
  209. const n = this.mem.getInt32(sp + 24, true);
  210. fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
  211. },
  212. // func resetMemoryDataView()
  213. "runtime.resetMemoryDataView": (sp) => {
  214. sp >>>= 0;
  215. this.mem = new DataView(this._inst.exports.mem.buffer);
  216. },
  217. // func nanotime1() int64
  218. "runtime.nanotime1": (sp) => {
  219. sp >>>= 0;
  220. setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
  221. },
  222. // func walltime() (sec int64, nsec int32)
  223. "runtime.walltime": (sp) => {
  224. sp >>>= 0;
  225. const msec = (new Date).getTime();
  226. setInt64(sp + 8, msec / 1000);
  227. this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
  228. },
  229. // func scheduleTimeoutEvent(delay int64) int32
  230. "runtime.scheduleTimeoutEvent": (sp) => {
  231. sp >>>= 0;
  232. const id = this._nextCallbackTimeoutID;
  233. this._nextCallbackTimeoutID++;
  234. this._scheduledTimeouts.set(id, setTimeout(
  235. () => {
  236. this._resume();
  237. while (this._scheduledTimeouts.has(id)) {
  238. // for some reason Go failed to register the timeout event, log and try again
  239. // (temporary workaround for https://github.com/golang/go/issues/28975)
  240. console.warn("scheduleTimeoutEvent: missed timeout event");
  241. this._resume();
  242. }
  243. },
  244. getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
  245. ));
  246. this.mem.setInt32(sp + 16, id, true);
  247. },
  248. // func clearTimeoutEvent(id int32)
  249. "runtime.clearTimeoutEvent": (sp) => {
  250. sp >>>= 0;
  251. const id = this.mem.getInt32(sp + 8, true);
  252. clearTimeout(this._scheduledTimeouts.get(id));
  253. this._scheduledTimeouts.delete(id);
  254. },
  255. // func getRandomData(r []byte)
  256. "runtime.getRandomData": (sp) => {
  257. sp >>>= 0;
  258. crypto.getRandomValues(loadSlice(sp + 8));
  259. },
  260. // func finalizeRef(v ref)
  261. "syscall/js.finalizeRef": (sp) => {
  262. sp >>>= 0;
  263. const id = this.mem.getUint32(sp + 8, true);
  264. this._goRefCounts[id]--;
  265. if (this._goRefCounts[id] === 0) {
  266. const v = this._values[id];
  267. this._values[id] = null;
  268. this._ids.delete(v);
  269. this._idPool.push(id);
  270. }
  271. },
  272. // func stringVal(value string) ref
  273. "syscall/js.stringVal": (sp) => {
  274. sp >>>= 0;
  275. storeValue(sp + 24, loadString(sp + 8));
  276. },
  277. // func valueGet(v ref, p string) ref
  278. "syscall/js.valueGet": (sp) => {
  279. sp >>>= 0;
  280. const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
  281. sp = this._inst.exports.getsp() >>> 0; // see comment above
  282. storeValue(sp + 32, result);
  283. },
  284. // func valueSet(v ref, p string, x ref)
  285. "syscall/js.valueSet": (sp) => {
  286. sp >>>= 0;
  287. Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
  288. },
  289. // func valueDelete(v ref, p string)
  290. "syscall/js.valueDelete": (sp) => {
  291. sp >>>= 0;
  292. Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
  293. },
  294. // func valueIndex(v ref, i int) ref
  295. "syscall/js.valueIndex": (sp) => {
  296. sp >>>= 0;
  297. storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
  298. },
  299. // valueSetIndex(v ref, i int, x ref)
  300. "syscall/js.valueSetIndex": (sp) => {
  301. sp >>>= 0;
  302. Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
  303. },
  304. // func valueCall(v ref, m string, args []ref) (ref, bool)
  305. "syscall/js.valueCall": (sp) => {
  306. sp >>>= 0;
  307. try {
  308. const v = loadValue(sp + 8);
  309. const m = Reflect.get(v, loadString(sp + 16));
  310. const args = loadSliceOfValues(sp + 32);
  311. const result = Reflect.apply(m, v, args);
  312. sp = this._inst.exports.getsp() >>> 0; // see comment above
  313. storeValue(sp + 56, result);
  314. this.mem.setUint8(sp + 64, 1);
  315. } catch (err) {
  316. sp = this._inst.exports.getsp() >>> 0; // see comment above
  317. storeValue(sp + 56, err);
  318. this.mem.setUint8(sp + 64, 0);
  319. }
  320. },
  321. // func valueInvoke(v ref, args []ref) (ref, bool)
  322. "syscall/js.valueInvoke": (sp) => {
  323. sp >>>= 0;
  324. try {
  325. const v = loadValue(sp + 8);
  326. const args = loadSliceOfValues(sp + 16);
  327. const result = Reflect.apply(v, undefined, args);
  328. sp = this._inst.exports.getsp() >>> 0; // see comment above
  329. storeValue(sp + 40, result);
  330. this.mem.setUint8(sp + 48, 1);
  331. } catch (err) {
  332. sp = this._inst.exports.getsp() >>> 0; // see comment above
  333. storeValue(sp + 40, err);
  334. this.mem.setUint8(sp + 48, 0);
  335. }
  336. },
  337. // func valueNew(v ref, args []ref) (ref, bool)
  338. "syscall/js.valueNew": (sp) => {
  339. sp >>>= 0;
  340. try {
  341. const v = loadValue(sp + 8);
  342. const args = loadSliceOfValues(sp + 16);
  343. const result = Reflect.construct(v, args);
  344. sp = this._inst.exports.getsp() >>> 0; // see comment above
  345. storeValue(sp + 40, result);
  346. this.mem.setUint8(sp + 48, 1);
  347. } catch (err) {
  348. sp = this._inst.exports.getsp() >>> 0; // see comment above
  349. storeValue(sp + 40, err);
  350. this.mem.setUint8(sp + 48, 0);
  351. }
  352. },
  353. // func valueLength(v ref) int
  354. "syscall/js.valueLength": (sp) => {
  355. sp >>>= 0;
  356. setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
  357. },
  358. // valuePrepareString(v ref) (ref, int)
  359. "syscall/js.valuePrepareString": (sp) => {
  360. sp >>>= 0;
  361. const str = encoder.encode(String(loadValue(sp + 8)));
  362. storeValue(sp + 16, str);
  363. setInt64(sp + 24, str.length);
  364. },
  365. // valueLoadString(v ref, b []byte)
  366. "syscall/js.valueLoadString": (sp) => {
  367. sp >>>= 0;
  368. const str = loadValue(sp + 8);
  369. loadSlice(sp + 16).set(str);
  370. },
  371. // func valueInstanceOf(v ref, t ref) bool
  372. "syscall/js.valueInstanceOf": (sp) => {
  373. sp >>>= 0;
  374. this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
  375. },
  376. // func copyBytesToGo(dst []byte, src ref) (int, bool)
  377. "syscall/js.copyBytesToGo": (sp) => {
  378. sp >>>= 0;
  379. const dst = loadSlice(sp + 8);
  380. const src = loadValue(sp + 32);
  381. if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
  382. this.mem.setUint8(sp + 48, 0);
  383. return;
  384. }
  385. const toCopy = src.subarray(0, dst.length);
  386. dst.set(toCopy);
  387. setInt64(sp + 40, toCopy.length);
  388. this.mem.setUint8(sp + 48, 1);
  389. },
  390. // func copyBytesToJS(dst ref, src []byte) (int, bool)
  391. "syscall/js.copyBytesToJS": (sp) => {
  392. sp >>>= 0;
  393. const dst = loadValue(sp + 8);
  394. const src = loadSlice(sp + 16);
  395. if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
  396. this.mem.setUint8(sp + 48, 0);
  397. return;
  398. }
  399. const toCopy = src.subarray(0, dst.length);
  400. dst.set(toCopy);
  401. setInt64(sp + 40, toCopy.length);
  402. this.mem.setUint8(sp + 48, 1);
  403. },
  404. "debug": (value) => {
  405. console.log(value);
  406. },
  407. }
  408. };
  409. }
  410. async run(instance) {
  411. if (!(instance instanceof WebAssembly.Instance)) {
  412. throw new Error("Go.run: WebAssembly.Instance expected");
  413. }
  414. this._inst = instance;
  415. this.mem = new DataView(this._inst.exports.mem.buffer);
  416. this._values = [ // JS values that Go currently has references to, indexed by reference id
  417. NaN,
  418. 0,
  419. null,
  420. true,
  421. false,
  422. globalThis,
  423. this,
  424. ];
  425. this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
  426. this._ids = new Map([ // mapping from JS values to reference ids
  427. [0, 1],
  428. [null, 2],
  429. [true, 3],
  430. [false, 4],
  431. [globalThis, 5],
  432. [this, 6],
  433. ]);
  434. this._idPool = []; // unused ids that have been garbage collected
  435. this.exited = false; // whether the Go program has exited
  436. // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
  437. let offset = 4096;
  438. const strPtr = (str) => {
  439. const ptr = offset;
  440. const bytes = encoder.encode(str + "\0");
  441. new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
  442. offset += bytes.length;
  443. if (offset % 8 !== 0) {
  444. offset += 8 - (offset % 8);
  445. }
  446. return ptr;
  447. };
  448. const argc = this.argv.length;
  449. const argvPtrs = [];
  450. this.argv.forEach((arg) => {
  451. argvPtrs.push(strPtr(arg));
  452. });
  453. argvPtrs.push(0);
  454. const keys = Object.keys(this.env).sort();
  455. keys.forEach((key) => {
  456. argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
  457. });
  458. argvPtrs.push(0);
  459. const argv = offset;
  460. argvPtrs.forEach((ptr) => {
  461. this.mem.setUint32(offset, ptr, true);
  462. this.mem.setUint32(offset + 4, 0, true);
  463. offset += 8;
  464. });
  465. // The linker guarantees global data starts from at least wasmMinDataAddr.
  466. // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
  467. const wasmMinDataAddr = 4096 + 8192;
  468. if (offset >= wasmMinDataAddr) {
  469. throw new Error("total length of command line and environment variables exceeds limit");
  470. }
  471. this._inst.exports.run(argc, argv);
  472. if (this.exited) {
  473. this._resolveExitPromise();
  474. }
  475. await this._exitPromise;
  476. }
  477. _resume() {
  478. if (this.exited) {
  479. throw new Error("Go program has already exited");
  480. }
  481. this._inst.exports.resume();
  482. if (this.exited) {
  483. this._resolveExitPromise();
  484. }
  485. }
  486. _makeFuncWrapper(id) {
  487. const go = this;
  488. return function () {
  489. const event = { id: id, this: this, args: arguments };
  490. go._pendingEvent = event;
  491. go._resume();
  492. return event.result;
  493. };
  494. }
  495. }
  496. })();