wasm_exec.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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.substring(0, nl));
  20. outputBuf = outputBuf.substring(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 setInt32 = (addr, v) => {
  105. this.mem.setUint32(addr + 0, v, true);
  106. }
  107. const getInt64 = (addr) => {
  108. const low = this.mem.getUint32(addr + 0, true);
  109. const high = this.mem.getInt32(addr + 4, true);
  110. return low + high * 4294967296;
  111. }
  112. const loadValue = (addr) => {
  113. const f = this.mem.getFloat64(addr, true);
  114. if (f === 0) {
  115. return undefined;
  116. }
  117. if (!isNaN(f)) {
  118. return f;
  119. }
  120. const id = this.mem.getUint32(addr, true);
  121. return this._values[id];
  122. }
  123. const storeValue = (addr, v) => {
  124. const nanHead = 0x7FF80000;
  125. if (typeof v === "number" && v !== 0) {
  126. if (isNaN(v)) {
  127. this.mem.setUint32(addr + 4, nanHead, true);
  128. this.mem.setUint32(addr, 0, true);
  129. return;
  130. }
  131. this.mem.setFloat64(addr, v, true);
  132. return;
  133. }
  134. if (v === undefined) {
  135. this.mem.setFloat64(addr, 0, true);
  136. return;
  137. }
  138. let id = this._ids.get(v);
  139. if (id === undefined) {
  140. id = this._idPool.pop();
  141. if (id === undefined) {
  142. id = this._values.length;
  143. }
  144. this._values[id] = v;
  145. this._goRefCounts[id] = 0;
  146. this._ids.set(v, id);
  147. }
  148. this._goRefCounts[id]++;
  149. let typeFlag = 0;
  150. switch (typeof v) {
  151. case "object":
  152. if (v !== null) {
  153. typeFlag = 1;
  154. }
  155. break;
  156. case "string":
  157. typeFlag = 2;
  158. break;
  159. case "symbol":
  160. typeFlag = 3;
  161. break;
  162. case "function":
  163. typeFlag = 4;
  164. break;
  165. }
  166. this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
  167. this.mem.setUint32(addr, id, true);
  168. }
  169. const loadSlice = (addr) => {
  170. const array = getInt64(addr + 0);
  171. const len = getInt64(addr + 8);
  172. return new Uint8Array(this._inst.exports.mem.buffer, array, len);
  173. }
  174. const loadSliceOfValues = (addr) => {
  175. const array = getInt64(addr + 0);
  176. const len = getInt64(addr + 8);
  177. const a = new Array(len);
  178. for (let i = 0; i < len; i++) {
  179. a[i] = loadValue(array + i * 8);
  180. }
  181. return a;
  182. }
  183. const loadString = (addr) => {
  184. const saddr = getInt64(addr + 0);
  185. const len = getInt64(addr + 8);
  186. return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
  187. }
  188. const timeOrigin = Date.now() - performance.now();
  189. this.importObject = {
  190. _gotest: {
  191. add: (a, b) => a + b,
  192. },
  193. gojs: {
  194. // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
  195. // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
  196. // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
  197. // This changes the SP, thus we have to update the SP used by the imported function.
  198. // func wasmExit(code int32)
  199. "runtime.wasmExit": (sp) => {
  200. sp >>>= 0;
  201. const code = this.mem.getInt32(sp + 8, true);
  202. this.exited = true;
  203. delete this._inst;
  204. delete this._values;
  205. delete this._goRefCounts;
  206. delete this._ids;
  207. delete this._idPool;
  208. this.exit(code);
  209. },
  210. // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
  211. "runtime.wasmWrite": (sp) => {
  212. sp >>>= 0;
  213. const fd = getInt64(sp + 8);
  214. const p = getInt64(sp + 16);
  215. const n = this.mem.getInt32(sp + 24, true);
  216. fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
  217. },
  218. // func resetMemoryDataView()
  219. "runtime.resetMemoryDataView": (sp) => {
  220. sp >>>= 0;
  221. this.mem = new DataView(this._inst.exports.mem.buffer);
  222. },
  223. // func nanotime1() int64
  224. "runtime.nanotime1": (sp) => {
  225. sp >>>= 0;
  226. setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
  227. },
  228. // func walltime() (sec int64, nsec int32)
  229. "runtime.walltime": (sp) => {
  230. sp >>>= 0;
  231. const msec = (new Date).getTime();
  232. setInt64(sp + 8, msec / 1000);
  233. this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
  234. },
  235. // func scheduleTimeoutEvent(delay int64) int32
  236. "runtime.scheduleTimeoutEvent": (sp) => {
  237. sp >>>= 0;
  238. const id = this._nextCallbackTimeoutID;
  239. this._nextCallbackTimeoutID++;
  240. this._scheduledTimeouts.set(id, setTimeout(
  241. () => {
  242. this._resume();
  243. while (this._scheduledTimeouts.has(id)) {
  244. // for some reason Go failed to register the timeout event, log and try again
  245. // (temporary workaround for https://github.com/golang/go/issues/28975)
  246. console.warn("scheduleTimeoutEvent: missed timeout event");
  247. this._resume();
  248. }
  249. },
  250. getInt64(sp + 8),
  251. ));
  252. this.mem.setInt32(sp + 16, id, true);
  253. },
  254. // func clearTimeoutEvent(id int32)
  255. "runtime.clearTimeoutEvent": (sp) => {
  256. sp >>>= 0;
  257. const id = this.mem.getInt32(sp + 8, true);
  258. clearTimeout(this._scheduledTimeouts.get(id));
  259. this._scheduledTimeouts.delete(id);
  260. },
  261. // func getRandomData(r []byte)
  262. "runtime.getRandomData": (sp) => {
  263. sp >>>= 0;
  264. crypto.getRandomValues(loadSlice(sp + 8));
  265. },
  266. // func finalizeRef(v ref)
  267. "syscall/js.finalizeRef": (sp) => {
  268. sp >>>= 0;
  269. const id = this.mem.getUint32(sp + 8, true);
  270. this._goRefCounts[id]--;
  271. if (this._goRefCounts[id] === 0) {
  272. const v = this._values[id];
  273. this._values[id] = null;
  274. this._ids.delete(v);
  275. this._idPool.push(id);
  276. }
  277. },
  278. // func stringVal(value string) ref
  279. "syscall/js.stringVal": (sp) => {
  280. sp >>>= 0;
  281. storeValue(sp + 24, loadString(sp + 8));
  282. },
  283. // func valueGet(v ref, p string) ref
  284. "syscall/js.valueGet": (sp) => {
  285. sp >>>= 0;
  286. const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
  287. sp = this._inst.exports.getsp() >>> 0; // see comment above
  288. storeValue(sp + 32, result);
  289. },
  290. // func valueSet(v ref, p string, x ref)
  291. "syscall/js.valueSet": (sp) => {
  292. sp >>>= 0;
  293. Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
  294. },
  295. // func valueDelete(v ref, p string)
  296. "syscall/js.valueDelete": (sp) => {
  297. sp >>>= 0;
  298. Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
  299. },
  300. // func valueIndex(v ref, i int) ref
  301. "syscall/js.valueIndex": (sp) => {
  302. sp >>>= 0;
  303. storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
  304. },
  305. // valueSetIndex(v ref, i int, x ref)
  306. "syscall/js.valueSetIndex": (sp) => {
  307. sp >>>= 0;
  308. Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
  309. },
  310. // func valueCall(v ref, m string, args []ref) (ref, bool)
  311. "syscall/js.valueCall": (sp) => {
  312. sp >>>= 0;
  313. try {
  314. const v = loadValue(sp + 8);
  315. const m = Reflect.get(v, loadString(sp + 16));
  316. const args = loadSliceOfValues(sp + 32);
  317. const result = Reflect.apply(m, v, args);
  318. sp = this._inst.exports.getsp() >>> 0; // see comment above
  319. storeValue(sp + 56, result);
  320. this.mem.setUint8(sp + 64, 1);
  321. } catch (err) {
  322. sp = this._inst.exports.getsp() >>> 0; // see comment above
  323. storeValue(sp + 56, err);
  324. this.mem.setUint8(sp + 64, 0);
  325. }
  326. },
  327. // func valueInvoke(v ref, args []ref) (ref, bool)
  328. "syscall/js.valueInvoke": (sp) => {
  329. sp >>>= 0;
  330. try {
  331. const v = loadValue(sp + 8);
  332. const args = loadSliceOfValues(sp + 16);
  333. const result = Reflect.apply(v, undefined, args);
  334. sp = this._inst.exports.getsp() >>> 0; // see comment above
  335. storeValue(sp + 40, result);
  336. this.mem.setUint8(sp + 48, 1);
  337. } catch (err) {
  338. sp = this._inst.exports.getsp() >>> 0; // see comment above
  339. storeValue(sp + 40, err);
  340. this.mem.setUint8(sp + 48, 0);
  341. }
  342. },
  343. // func valueNew(v ref, args []ref) (ref, bool)
  344. "syscall/js.valueNew": (sp) => {
  345. sp >>>= 0;
  346. try {
  347. const v = loadValue(sp + 8);
  348. const args = loadSliceOfValues(sp + 16);
  349. const result = Reflect.construct(v, args);
  350. sp = this._inst.exports.getsp() >>> 0; // see comment above
  351. storeValue(sp + 40, result);
  352. this.mem.setUint8(sp + 48, 1);
  353. } catch (err) {
  354. sp = this._inst.exports.getsp() >>> 0; // see comment above
  355. storeValue(sp + 40, err);
  356. this.mem.setUint8(sp + 48, 0);
  357. }
  358. },
  359. // func valueLength(v ref) int
  360. "syscall/js.valueLength": (sp) => {
  361. sp >>>= 0;
  362. setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
  363. },
  364. // valuePrepareString(v ref) (ref, int)
  365. "syscall/js.valuePrepareString": (sp) => {
  366. sp >>>= 0;
  367. const str = encoder.encode(String(loadValue(sp + 8)));
  368. storeValue(sp + 16, str);
  369. setInt64(sp + 24, str.length);
  370. },
  371. // valueLoadString(v ref, b []byte)
  372. "syscall/js.valueLoadString": (sp) => {
  373. sp >>>= 0;
  374. const str = loadValue(sp + 8);
  375. loadSlice(sp + 16).set(str);
  376. },
  377. // func valueInstanceOf(v ref, t ref) bool
  378. "syscall/js.valueInstanceOf": (sp) => {
  379. sp >>>= 0;
  380. this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
  381. },
  382. // func copyBytesToGo(dst []byte, src ref) (int, bool)
  383. "syscall/js.copyBytesToGo": (sp) => {
  384. sp >>>= 0;
  385. const dst = loadSlice(sp + 8);
  386. const src = loadValue(sp + 32);
  387. if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
  388. this.mem.setUint8(sp + 48, 0);
  389. return;
  390. }
  391. const toCopy = src.subarray(0, dst.length);
  392. dst.set(toCopy);
  393. setInt64(sp + 40, toCopy.length);
  394. this.mem.setUint8(sp + 48, 1);
  395. },
  396. // func copyBytesToJS(dst ref, src []byte) (int, bool)
  397. "syscall/js.copyBytesToJS": (sp) => {
  398. sp >>>= 0;
  399. const dst = loadValue(sp + 8);
  400. const src = loadSlice(sp + 16);
  401. if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
  402. this.mem.setUint8(sp + 48, 0);
  403. return;
  404. }
  405. const toCopy = src.subarray(0, dst.length);
  406. dst.set(toCopy);
  407. setInt64(sp + 40, toCopy.length);
  408. this.mem.setUint8(sp + 48, 1);
  409. },
  410. "debug": (value) => {
  411. console.log(value);
  412. },
  413. }
  414. };
  415. }
  416. async run(instance) {
  417. if (!(instance instanceof WebAssembly.Instance)) {
  418. throw new Error("Go.run: WebAssembly.Instance expected");
  419. }
  420. this._inst = instance;
  421. this.mem = new DataView(this._inst.exports.mem.buffer);
  422. this._values = [ // JS values that Go currently has references to, indexed by reference id
  423. NaN,
  424. 0,
  425. null,
  426. true,
  427. false,
  428. globalThis,
  429. this,
  430. ];
  431. this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
  432. this._ids = new Map([ // mapping from JS values to reference ids
  433. [0, 1],
  434. [null, 2],
  435. [true, 3],
  436. [false, 4],
  437. [globalThis, 5],
  438. [this, 6],
  439. ]);
  440. this._idPool = []; // unused ids that have been garbage collected
  441. this.exited = false; // whether the Go program has exited
  442. // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
  443. let offset = 4096;
  444. const strPtr = (str) => {
  445. const ptr = offset;
  446. const bytes = encoder.encode(str + "\0");
  447. new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
  448. offset += bytes.length;
  449. if (offset % 8 !== 0) {
  450. offset += 8 - (offset % 8);
  451. }
  452. return ptr;
  453. };
  454. const argc = this.argv.length;
  455. const argvPtrs = [];
  456. this.argv.forEach((arg) => {
  457. argvPtrs.push(strPtr(arg));
  458. });
  459. argvPtrs.push(0);
  460. const keys = Object.keys(this.env).sort();
  461. keys.forEach((key) => {
  462. argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
  463. });
  464. argvPtrs.push(0);
  465. const argv = offset;
  466. argvPtrs.forEach((ptr) => {
  467. this.mem.setUint32(offset, ptr, true);
  468. this.mem.setUint32(offset + 4, 0, true);
  469. offset += 8;
  470. });
  471. // The linker guarantees global data starts from at least wasmMinDataAddr.
  472. // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
  473. const wasmMinDataAddr = 4096 + 8192;
  474. if (offset >= wasmMinDataAddr) {
  475. throw new Error("total length of command line and environment variables exceeds limit");
  476. }
  477. this._inst.exports.run(argc, argv);
  478. if (this.exited) {
  479. this._resolveExitPromise();
  480. }
  481. await this._exitPromise;
  482. }
  483. _resume() {
  484. if (this.exited) {
  485. throw new Error("Go program has already exited");
  486. }
  487. this._inst.exports.resume();
  488. if (this.exited) {
  489. this._resolveExitPromise();
  490. }
  491. }
  492. _makeFuncWrapper(id) {
  493. const go = this;
  494. return function () {
  495. const event = { id: id, this: this, args: arguments };
  496. go._pendingEvent = event;
  497. go._resume();
  498. return event.result;
  499. };
  500. }
  501. }
  502. })();