load-wasm-and-print-primitive.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 scriptArgs !== 'undefined') {
  11. args = scriptArgs;
  12. } else if (typeof arguments !== 'undefined') {
  13. args = arguments;
  14. } else {
  15. // No script arguments available
  16. args = [];
  17. }
  18. var log = print;
  19. var logErr = print;
  20. if (typeof printErr !== 'undefined') {
  21. logErr = printErr;
  22. }
  23. var _exit;
  24. if (typeof quit !== 'undefined') {
  25. _exit = quit.bind(this);
  26. } else if (typeof testRunner !== 'undefined') {
  27. _exit = testRunner.quit.bind(testRunner);
  28. }
  29. // V8 treats multiple arguments as files, unless -- is given, but
  30. // SpiderMonkey doesn't treat -- specially. This is a hack to allow
  31. // for -- on SpiderMonkey.
  32. if (args[0] == '--') {
  33. args.shift();
  34. }
  35. if (args.length < 2) {
  36. logErr('usage: load-wasm-and-print-primitive.js FOO.WASM FUNC [ARGS ...]');
  37. _exit(1);
  38. }
  39. async function instantiateStreaming(path, imports) {
  40. if (typeof fetch !== 'undefined')
  41. return WebAssembly.instantiateStreaming(fetch(path), imports);
  42. let bytes;
  43. if (typeof read !== 'undefined') {
  44. bytes = read(path, 'binary');
  45. } else if (typeof readFile !== 'undefined') {
  46. bytes = readFile(path);
  47. } else {
  48. let fs = require('fs');
  49. bytes = fs.readFileSync(path);
  50. }
  51. return WebAssembly.instantiate(bytes, imports);
  52. }
  53. async function compileAndRun(wasmFile, funcName, args) {
  54. const imports = {};
  55. const { module, instance } = await instantiateStreaming(wasmFile, imports);
  56. const f = instance.exports[funcName];
  57. return f.apply(null, args);
  58. }
  59. async function runTest(wasmFile, funcName, ...args) {
  60. const parsedArgs = args.map(JSON.parse);
  61. try {
  62. log(await compileAndRun(wasmFile, funcName, parsedArgs));
  63. } catch (e) {
  64. log(`error: ${e}`);
  65. _exit(1);
  66. }
  67. }
  68. waitFor(runTest.apply(null, args));