load-primitive.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var waitFor;
  2. if (typeof drainJobQueue !== 'undefined') {
  3. waitFor = function waitFor(p) { drainJobQueue(); return p; };
  4. } else {
  5. // JSC and V8 will drain promises before exiting and don't require a
  6. // specific waiter.
  7. waitFor = function waitFor(p) { return p; };
  8. }
  9. var args;
  10. if (typeof process !== 'undefined') {
  11. args = process.argv.slice(3);
  12. } else if (typeof scriptArgs !== 'undefined') {
  13. args = scriptArgs;
  14. } else if (typeof arguments !== 'undefined') {
  15. args = arguments;
  16. } else {
  17. // No script arguments available
  18. args = [];
  19. }
  20. var log;
  21. var logErr;
  22. if (typeof print !== 'undefined') {
  23. log = print;
  24. } else if (typeof console !== 'undefined') {
  25. log = console.log.bind(console);
  26. }
  27. if (typeof printErr !== 'undefined') {
  28. logErr = printErr;
  29. } else {
  30. logErr = log;
  31. }
  32. var _exit;
  33. if (typeof quit !== 'undefined') {
  34. _exit = quit.bind(this);
  35. } else if (typeof testRunner !== 'undefined') {
  36. _exit = testRunner.quit.bind(testRunner);
  37. } else if (typeof process !== 'undefined') {
  38. _exit = process.exit.bind(process);
  39. }
  40. // V8 treats multiple arguments as files, unless -- is given, but
  41. // SpiderMonkey doesn't treat -- specially. This is a hack to allow
  42. // for -- on SpiderMonkey.
  43. if (args[0] == '--') {
  44. args.shift();
  45. }
  46. if (args.length < 2) {
  47. logErr('usage: load-primitive.js FOO.WASM FUNC [ARGS ...]');
  48. _exit(1);
  49. }
  50. async function instantiateStreaming(path, imports) {
  51. if (typeof fetch !== 'undefined' && typeof window !== 'undefined')
  52. return WebAssembly.instantiateStreaming(fetch(path), imports);
  53. let bytes;
  54. if (typeof read !== 'undefined') {
  55. bytes = read(path, 'binary');
  56. } else if (typeof readFile !== 'undefined') {
  57. bytes = readFile(path);
  58. } else {
  59. let fs = require('fs');
  60. bytes = fs.readFileSync(path);
  61. }
  62. return WebAssembly.instantiate(bytes, imports);
  63. }
  64. async function compileAndRun(wasmFile, funcName, args) {
  65. const imports = {};
  66. const { module, instance } = await instantiateStreaming(wasmFile, imports);
  67. const f = instance.exports[funcName];
  68. return f.apply(null, args);
  69. }
  70. async function runTest(wasmFile, funcName, ...args) {
  71. const parsedArgs = args.map(JSON.parse);
  72. try {
  73. const result = await compileAndRun(wasmFile, funcName, parsedArgs);
  74. log(result.toString());
  75. } catch (e) {
  76. log(`error: ${e} (${e.stack})`);
  77. _exit(1);
  78. }
  79. }
  80. waitFor(runTest.apply(null, args));