wasm_exec.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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. // @ts-nocheck
  5. (() => {
  6. // Map multiple JavaScript environments to a single common API,
  7. // preferring web standards over Node.js API.
  8. //
  9. // Environments considered:
  10. // - Browsers
  11. // - Node.js
  12. // - Electron
  13. // - Parcel
  14. // - Webpack
  15. if (typeof global !== "undefined") {
  16. // global already exists
  17. } else if (typeof window !== "undefined") {
  18. window.global = window;
  19. } else if (typeof self !== "undefined") {
  20. self.global = self;
  21. } else {
  22. throw new Error(
  23. "cannot export Go (neither global, window nor self is defined)",
  24. );
  25. }
  26. if (!global.require && typeof require !== "undefined") {
  27. global.require = require;
  28. }
  29. if (!global.fs && global.require) {
  30. const fs = require("fs");
  31. if (typeof fs === "object" && fs !== null && Object.keys(fs).length !== 0) {
  32. global.fs = fs;
  33. }
  34. }
  35. const enosys = () => {
  36. const err = new Error("not implemented");
  37. err.code = "ENOSYS";
  38. return err;
  39. };
  40. if (!global.fs) {
  41. let outputBuf = "";
  42. global.fs = {
  43. constants: {
  44. O_WRONLY: -1,
  45. O_RDWR: -1,
  46. O_CREAT: -1,
  47. O_TRUNC: -1,
  48. O_APPEND: -1,
  49. O_EXCL: -1,
  50. }, // unused
  51. writeSync(fd, buf) {
  52. outputBuf += decoder.decode(buf);
  53. const nl = outputBuf.lastIndexOf("\n");
  54. if (nl != -1) {
  55. console.log(outputBuf.substr(0, nl));
  56. outputBuf = outputBuf.substr(nl + 1);
  57. }
  58. return buf.length;
  59. },
  60. write(fd, buf, offset, length, position, callback) {
  61. if (offset !== 0 || length !== buf.length || position !== null) {
  62. callback(enosys());
  63. return;
  64. }
  65. const n = this.writeSync(fd, buf);
  66. callback(null, n);
  67. },
  68. chmod(path, mode, callback) {
  69. callback(enosys());
  70. },
  71. chown(path, uid, gid, callback) {
  72. callback(enosys());
  73. },
  74. close(fd, callback) {
  75. callback(enosys());
  76. },
  77. fchmod(fd, mode, callback) {
  78. callback(enosys());
  79. },
  80. fchown(fd, uid, gid, callback) {
  81. callback(enosys());
  82. },
  83. fstat(fd, callback) {
  84. callback(enosys());
  85. },
  86. fsync(fd, callback) {
  87. callback(null);
  88. },
  89. ftruncate(fd, length, callback) {
  90. callback(enosys());
  91. },
  92. lchown(path, uid, gid, callback) {
  93. callback(enosys());
  94. },
  95. link(path, link, callback) {
  96. callback(enosys());
  97. },
  98. lstat(path, callback) {
  99. callback(enosys());
  100. },
  101. mkdir(path, perm, callback) {
  102. callback(enosys());
  103. },
  104. open(path, flags, mode, callback) {
  105. callback(enosys());
  106. },
  107. read(fd, buffer, offset, length, position, callback) {
  108. callback(enosys());
  109. },
  110. readdir(path, callback) {
  111. callback(enosys());
  112. },
  113. readlink(path, callback) {
  114. callback(enosys());
  115. },
  116. rename(from, to, callback) {
  117. callback(enosys());
  118. },
  119. rmdir(path, callback) {
  120. callback(enosys());
  121. },
  122. stat(path, callback) {
  123. callback(enosys());
  124. },
  125. symlink(path, link, callback) {
  126. callback(enosys());
  127. },
  128. truncate(path, length, callback) {
  129. callback(enosys());
  130. },
  131. unlink(path, callback) {
  132. callback(enosys());
  133. },
  134. utimes(path, atime, mtime, callback) {
  135. callback(enosys());
  136. },
  137. };
  138. }
  139. if (!global.process) {
  140. global.process = {
  141. getuid() {
  142. return -1;
  143. },
  144. getgid() {
  145. return -1;
  146. },
  147. geteuid() {
  148. return -1;
  149. },
  150. getegid() {
  151. return -1;
  152. },
  153. getgroups() {
  154. throw enosys();
  155. },
  156. pid: -1,
  157. ppid: -1,
  158. umask() {
  159. throw enosys();
  160. },
  161. cwd() {
  162. throw enosys();
  163. },
  164. chdir() {
  165. throw enosys();
  166. },
  167. };
  168. }
  169. if (!global.crypto && global.require) {
  170. const nodeCrypto = require("crypto");
  171. global.crypto = {
  172. getRandomValues(b) {
  173. nodeCrypto.randomFillSync(b);
  174. },
  175. };
  176. }
  177. if (!global.crypto) {
  178. throw new Error(
  179. "global.crypto is not available, polyfill required (getRandomValues only)",
  180. );
  181. }
  182. if (!global.performance) {
  183. global.performance = {
  184. now() {
  185. const [sec, nsec] = process.hrtime();
  186. return sec * 1000 + nsec / 1000000;
  187. },
  188. };
  189. }
  190. if (!global.TextEncoder && global.require) {
  191. global.TextEncoder = require("util").TextEncoder;
  192. }
  193. if (!global.TextEncoder) {
  194. throw new Error("global.TextEncoder is not available, polyfill required");
  195. }
  196. if (!global.TextDecoder && global.require) {
  197. global.TextDecoder = require("util").TextDecoder;
  198. }
  199. if (!global.TextDecoder) {
  200. throw new Error("global.TextDecoder is not available, polyfill required");
  201. }
  202. // End of polyfills for common API.
  203. const encoder = new TextEncoder("utf-8");
  204. const decoder = new TextDecoder("utf-8");
  205. global.Go = class {
  206. constructor() {
  207. this.argv = ["js"];
  208. this.env = {};
  209. this.exit = (code) => {
  210. if (code !== 0) {
  211. console.warn("exit code:", code);
  212. }
  213. };
  214. this._exitPromise = new Promise((resolve) => {
  215. this._resolveExitPromise = resolve;
  216. });
  217. this._pendingEvent = null;
  218. this._scheduledTimeouts = new Map();
  219. this._nextCallbackTimeoutID = 1;
  220. const setInt64 = (addr, v) => {
  221. this.mem.setUint32(addr + 0, v, true);
  222. this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
  223. };
  224. const getInt64 = (addr) => {
  225. const low = this.mem.getUint32(addr + 0, true);
  226. const high = this.mem.getInt32(addr + 4, true);
  227. return low + high * 4294967296;
  228. };
  229. const loadValue = (addr) => {
  230. const f = this.mem.getFloat64(addr, true);
  231. if (f === 0) {
  232. return undefined;
  233. }
  234. if (!isNaN(f)) {
  235. return f;
  236. }
  237. const id = this.mem.getUint32(addr, true);
  238. return this._values[id];
  239. };
  240. const storeValue = (addr, v) => {
  241. const nanHead = 0x7ff80000;
  242. if (typeof v === "number" && v !== 0) {
  243. if (isNaN(v)) {
  244. this.mem.setUint32(addr + 4, nanHead, true);
  245. this.mem.setUint32(addr, 0, true);
  246. return;
  247. }
  248. this.mem.setFloat64(addr, v, true);
  249. return;
  250. }
  251. if (v === undefined) {
  252. this.mem.setFloat64(addr, 0, true);
  253. return;
  254. }
  255. let id = this._ids.get(v);
  256. if (id === undefined) {
  257. id = this._idPool.pop();
  258. if (id === undefined) {
  259. id = this._values.length;
  260. }
  261. this._values[id] = v;
  262. this._goRefCounts[id] = 0;
  263. this._ids.set(v, id);
  264. }
  265. this._goRefCounts[id]++;
  266. let typeFlag = 0;
  267. switch (typeof v) {
  268. case "object":
  269. if (v !== null) {
  270. typeFlag = 1;
  271. }
  272. break;
  273. case "string":
  274. typeFlag = 2;
  275. break;
  276. case "symbol":
  277. typeFlag = 3;
  278. break;
  279. case "function":
  280. typeFlag = 4;
  281. break;
  282. }
  283. this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
  284. this.mem.setUint32(addr, id, true);
  285. };
  286. const loadSlice = (addr) => {
  287. const array = getInt64(addr + 0);
  288. const len = getInt64(addr + 8);
  289. return new Uint8Array(this._inst.exports.mem.buffer, array, len);
  290. };
  291. const loadSliceOfValues = (addr) => {
  292. const array = getInt64(addr + 0);
  293. const len = getInt64(addr + 8);
  294. const a = new Array(len);
  295. for (let i = 0; i < len; i++) {
  296. a[i] = loadValue(array + i * 8);
  297. }
  298. return a;
  299. };
  300. const loadString = (addr) => {
  301. const saddr = getInt64(addr + 0);
  302. const len = getInt64(addr + 8);
  303. return decoder.decode(
  304. new DataView(this._inst.exports.mem.buffer, saddr, len),
  305. );
  306. };
  307. const timeOrigin = Date.now() - performance.now();
  308. this.importObject = {
  309. go: {
  310. // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
  311. // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
  312. // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
  313. // This changes the SP, thus we have to update the SP used by the imported function.
  314. // func wasmExit(code int32)
  315. "runtime.wasmExit": (sp) => {
  316. sp >>>= 0;
  317. const code = this.mem.getInt32(sp + 8, true);
  318. this.exited = true;
  319. delete this._inst;
  320. delete this._values;
  321. delete this._goRefCounts;
  322. delete this._ids;
  323. delete this._idPool;
  324. this.exit(code);
  325. },
  326. // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
  327. "runtime.wasmWrite": (sp) => {
  328. sp >>>= 0;
  329. const fd = getInt64(sp + 8);
  330. const p = getInt64(sp + 16);
  331. const n = this.mem.getInt32(sp + 24, true);
  332. fs.writeSync(
  333. fd,
  334. new Uint8Array(this._inst.exports.mem.buffer, p, n),
  335. );
  336. },
  337. // func resetMemoryDataView()
  338. "runtime.resetMemoryDataView": (sp) => {
  339. sp >>>= 0;
  340. this.mem = new DataView(this._inst.exports.mem.buffer);
  341. },
  342. // func nanotime1() int64
  343. "runtime.nanotime1": (sp) => {
  344. sp >>>= 0;
  345. setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
  346. },
  347. // func walltime() (sec int64, nsec int32)
  348. "runtime.walltime": (sp) => {
  349. sp >>>= 0;
  350. const msec = new Date().getTime();
  351. setInt64(sp + 8, msec / 1000);
  352. this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
  353. },
  354. // func scheduleTimeoutEvent(delay int64) int32
  355. "runtime.scheduleTimeoutEvent": (sp) => {
  356. sp >>>= 0;
  357. const id = this._nextCallbackTimeoutID;
  358. this._nextCallbackTimeoutID++;
  359. this._scheduledTimeouts.set(
  360. id,
  361. setTimeout(
  362. () => {
  363. this._resume();
  364. while (this._scheduledTimeouts.has(id)) {
  365. // for some reason Go failed to register the timeout event, log and try again
  366. // (temporary workaround for https://github.com/golang/go/issues/28975)
  367. console.warn("scheduleTimeoutEvent: missed timeout event");
  368. this._resume();
  369. }
  370. },
  371. getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
  372. ),
  373. );
  374. this.mem.setInt32(sp + 16, id, true);
  375. },
  376. // func clearTimeoutEvent(id int32)
  377. "runtime.clearTimeoutEvent": (sp) => {
  378. sp >>>= 0;
  379. const id = this.mem.getInt32(sp + 8, true);
  380. clearTimeout(this._scheduledTimeouts.get(id));
  381. this._scheduledTimeouts.delete(id);
  382. },
  383. // func getRandomData(r []byte)
  384. "runtime.getRandomData": (sp) => {
  385. sp >>>= 0;
  386. crypto.getRandomValues(loadSlice(sp + 8));
  387. },
  388. // func finalizeRef(v ref)
  389. "syscall/js.finalizeRef": (sp) => {
  390. sp >>>= 0;
  391. const id = this.mem.getUint32(sp + 8, true);
  392. this._goRefCounts[id]--;
  393. if (this._goRefCounts[id] === 0) {
  394. const v = this._values[id];
  395. this._values[id] = null;
  396. this._ids.delete(v);
  397. this._idPool.push(id);
  398. }
  399. },
  400. // func stringVal(value string) ref
  401. "syscall/js.stringVal": (sp) => {
  402. sp >>>= 0;
  403. storeValue(sp + 24, loadString(sp + 8));
  404. },
  405. // func valueGet(v ref, p string) ref
  406. "syscall/js.valueGet": (sp) => {
  407. sp >>>= 0;
  408. const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
  409. sp = this._inst.exports.getsp() >>> 0; // see comment above
  410. storeValue(sp + 32, result);
  411. },
  412. // func valueSet(v ref, p string, x ref)
  413. "syscall/js.valueSet": (sp) => {
  414. sp >>>= 0;
  415. Reflect.set(
  416. loadValue(sp + 8),
  417. loadString(sp + 16),
  418. loadValue(sp + 32),
  419. );
  420. },
  421. // func valueDelete(v ref, p string)
  422. "syscall/js.valueDelete": (sp) => {
  423. sp >>>= 0;
  424. Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
  425. },
  426. // func valueIndex(v ref, i int) ref
  427. "syscall/js.valueIndex": (sp) => {
  428. sp >>>= 0;
  429. storeValue(
  430. sp + 24,
  431. Reflect.get(loadValue(sp + 8), getInt64(sp + 16)),
  432. );
  433. },
  434. // valueSetIndex(v ref, i int, x ref)
  435. "syscall/js.valueSetIndex": (sp) => {
  436. sp >>>= 0;
  437. Reflect.set(
  438. loadValue(sp + 8),
  439. getInt64(sp + 16),
  440. loadValue(sp + 24),
  441. );
  442. },
  443. // func valueCall(v ref, m string, args []ref) (ref, bool)
  444. "syscall/js.valueCall": (sp) => {
  445. sp >>>= 0;
  446. try {
  447. const v = loadValue(sp + 8);
  448. const m = Reflect.get(v, loadString(sp + 16));
  449. const args = loadSliceOfValues(sp + 32);
  450. const result = Reflect.apply(m, v, args);
  451. sp = this._inst.exports.getsp() >>> 0; // see comment above
  452. storeValue(sp + 56, result);
  453. this.mem.setUint8(sp + 64, 1);
  454. } catch (err) {
  455. sp = this._inst.exports.getsp() >>> 0; // see comment above
  456. storeValue(sp + 56, err);
  457. this.mem.setUint8(sp + 64, 0);
  458. }
  459. },
  460. // func valueInvoke(v ref, args []ref) (ref, bool)
  461. "syscall/js.valueInvoke": (sp) => {
  462. sp >>>= 0;
  463. try {
  464. const v = loadValue(sp + 8);
  465. const args = loadSliceOfValues(sp + 16);
  466. const result = Reflect.apply(v, undefined, args);
  467. sp = this._inst.exports.getsp() >>> 0; // see comment above
  468. storeValue(sp + 40, result);
  469. this.mem.setUint8(sp + 48, 1);
  470. } catch (err) {
  471. sp = this._inst.exports.getsp() >>> 0; // see comment above
  472. storeValue(sp + 40, err);
  473. this.mem.setUint8(sp + 48, 0);
  474. }
  475. },
  476. // func valueNew(v ref, args []ref) (ref, bool)
  477. "syscall/js.valueNew": (sp) => {
  478. sp >>>= 0;
  479. try {
  480. const v = loadValue(sp + 8);
  481. const args = loadSliceOfValues(sp + 16);
  482. const result = Reflect.construct(v, args);
  483. sp = this._inst.exports.getsp() >>> 0; // see comment above
  484. storeValue(sp + 40, result);
  485. this.mem.setUint8(sp + 48, 1);
  486. } catch (err) {
  487. sp = this._inst.exports.getsp() >>> 0; // see comment above
  488. storeValue(sp + 40, err);
  489. this.mem.setUint8(sp + 48, 0);
  490. }
  491. },
  492. // func valueLength(v ref) int
  493. "syscall/js.valueLength": (sp) => {
  494. sp >>>= 0;
  495. setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
  496. },
  497. // valuePrepareString(v ref) (ref, int)
  498. "syscall/js.valuePrepareString": (sp) => {
  499. sp >>>= 0;
  500. const str = encoder.encode(String(loadValue(sp + 8)));
  501. storeValue(sp + 16, str);
  502. setInt64(sp + 24, str.length);
  503. },
  504. // valueLoadString(v ref, b []byte)
  505. "syscall/js.valueLoadString": (sp) => {
  506. sp >>>= 0;
  507. const str = loadValue(sp + 8);
  508. loadSlice(sp + 16).set(str);
  509. },
  510. // func valueInstanceOf(v ref, t ref) bool
  511. "syscall/js.valueInstanceOf": (sp) => {
  512. sp >>>= 0;
  513. this.mem.setUint8(
  514. sp + 24,
  515. loadValue(sp + 8) instanceof loadValue(sp + 16) ? 1 : 0,
  516. );
  517. },
  518. // func copyBytesToGo(dst []byte, src ref) (int, bool)
  519. "syscall/js.copyBytesToGo": (sp) => {
  520. sp >>>= 0;
  521. const dst = loadSlice(sp + 8);
  522. const src = loadValue(sp + 32);
  523. if (
  524. !(src instanceof Uint8Array || src instanceof Uint8ClampedArray)
  525. ) {
  526. this.mem.setUint8(sp + 48, 0);
  527. return;
  528. }
  529. const toCopy = src.subarray(0, dst.length);
  530. dst.set(toCopy);
  531. setInt64(sp + 40, toCopy.length);
  532. this.mem.setUint8(sp + 48, 1);
  533. },
  534. // func copyBytesToJS(dst ref, src []byte) (int, bool)
  535. "syscall/js.copyBytesToJS": (sp) => {
  536. sp >>>= 0;
  537. const dst = loadValue(sp + 8);
  538. const src = loadSlice(sp + 16);
  539. if (
  540. !(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)
  541. ) {
  542. this.mem.setUint8(sp + 48, 0);
  543. return;
  544. }
  545. const toCopy = src.subarray(0, dst.length);
  546. dst.set(toCopy);
  547. setInt64(sp + 40, toCopy.length);
  548. this.mem.setUint8(sp + 48, 1);
  549. },
  550. debug: (value) => {
  551. console.log(value);
  552. },
  553. },
  554. };
  555. }
  556. async run(instance) {
  557. if (!(instance instanceof WebAssembly.Instance)) {
  558. throw new Error("Go.run: WebAssembly.Instance expected");
  559. }
  560. this._inst = instance;
  561. this.mem = new DataView(this._inst.exports.mem.buffer);
  562. this._values = [
  563. // JS values that Go currently has references to, indexed by reference id
  564. NaN,
  565. 0,
  566. null,
  567. true,
  568. false,
  569. global,
  570. this,
  571. ];
  572. this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
  573. this._ids = new Map([
  574. // mapping from JS values to reference ids
  575. [0, 1],
  576. [null, 2],
  577. [true, 3],
  578. [false, 4],
  579. [global, 5],
  580. [this, 6],
  581. ]);
  582. this._idPool = []; // unused ids that have been garbage collected
  583. this.exited = false; // whether the Go program has exited
  584. // Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
  585. let offset = 4096;
  586. const strPtr = (str) => {
  587. const ptr = offset;
  588. const bytes = encoder.encode(str + "\0");
  589. new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
  590. offset += bytes.length;
  591. if (offset % 8 !== 0) {
  592. offset += 8 - (offset % 8);
  593. }
  594. return ptr;
  595. };
  596. const argc = this.argv.length;
  597. const argvPtrs = [];
  598. this.argv.forEach((arg) => {
  599. argvPtrs.push(strPtr(arg));
  600. });
  601. argvPtrs.push(0);
  602. const keys = Object.keys(this.env).sort();
  603. keys.forEach((key) => {
  604. argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
  605. });
  606. argvPtrs.push(0);
  607. const argv = offset;
  608. argvPtrs.forEach((ptr) => {
  609. this.mem.setUint32(offset, ptr, true);
  610. this.mem.setUint32(offset + 4, 0, true);
  611. offset += 8;
  612. });
  613. // The linker guarantees global data starts from at least wasmMinDataAddr.
  614. // Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
  615. const wasmMinDataAddr = 4096 + 8192;
  616. if (offset >= wasmMinDataAddr) {
  617. throw new Error(
  618. "total length of command line and environment variables exceeds limit",
  619. );
  620. }
  621. this._inst.exports.run(argc, argv);
  622. if (this.exited) {
  623. this._resolveExitPromise();
  624. }
  625. await this._exitPromise;
  626. }
  627. _resume() {
  628. if (this.exited) {
  629. throw new Error("Go program has already exited");
  630. }
  631. this._inst.exports.resume();
  632. if (this.exited) {
  633. this._resolveExitPromise();
  634. }
  635. }
  636. _makeFuncWrapper(id) {
  637. const go = this;
  638. return function () {
  639. const event = { id: id, this: this, args: arguments };
  640. go._pendingEvent = event;
  641. go._resume();
  642. return event.result;
  643. };
  644. }
  645. };
  646. if (
  647. typeof module !== "undefined" &&
  648. global.require &&
  649. global.require.main === module &&
  650. global.process &&
  651. global.process.versions &&
  652. !global.process.versions.electron
  653. ) {
  654. if (process.argv.length < 3) {
  655. console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
  656. process.exit(1);
  657. }
  658. const go = new Go();
  659. go.argv = process.argv.slice(2);
  660. go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
  661. go.exit = process.exit;
  662. WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject)
  663. .then((result) => {
  664. process.on("exit", (code) => {
  665. // Node.js exits if no event handler is pending
  666. if (code === 0 && !go.exited) {
  667. // deadlock, make Go print error and stack traces
  668. go._pendingEvent = { id: 0 };
  669. go._resume();
  670. }
  671. });
  672. return go.run(result.instance);
  673. })
  674. .catch((err) => {
  675. console.error(err);
  676. process.exit(1);
  677. });
  678. }
  679. })();