interpreter.js 17.7 KB
Newer Older
1 2 3 4
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
// Flags: --wasm-interpret-all --allow-natives-syntax --expose-gc
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

load('test/mjsunit/wasm/wasm-constants.js');
load('test/mjsunit/wasm/wasm-module-builder.js');

// The stack trace contains file path, only keep "interpreter.js".
let stripPath = s => s.replace(/[^ (]*interpreter\.js/g, 'interpreter.js');

function checkStack(stack, expected_lines) {
  print('stack: ' + stack);
  var lines = stack.split('\n');
  assertEquals(expected_lines.length, lines.length);
  for (var i = 0; i < lines.length; ++i) {
    let test =
        typeof expected_lines[i] == 'string' ? assertEquals : assertMatches;
    test(expected_lines[i], lines[i], 'line ' + i);
  }
}

(function testCallImported() {
25
  print(arguments.callee.name);
26 27 28 29 30 31 32 33 34 35 36
  var stack;
  let func = () => stack = new Error('test imported stack').stack;

  var builder = new WasmModuleBuilder();
  builder.addImport('mod', 'func', kSig_v_v);
  builder.addFunction('main', kSig_v_v)
      .addBody([kExprCallFunction, 0])
      .exportFunc();
  var instance = builder.instantiate({mod: {func: func}});
  // Test that this does not mess up internal state by executing it three times.
  for (var i = 0; i < 3; ++i) {
37
    var interpreted_before = %WasmNumInterpretedCalls(instance);
38
    instance.exports.main();
39
    assertEquals(interpreted_before + 1, %WasmNumInterpretedCalls(instance));
40 41 42
    checkStack(stripPath(stack), [
      'Error: test imported stack',                           // -
      /^    at func \(interpreter.js:\d+:28\)$/,              // -
43
      '    at main (wasm-function[1]:1)',                     // -
44 45 46 47 48 49 50
      /^    at testCallImported \(interpreter.js:\d+:22\)$/,  // -
      /^    at interpreter.js:\d+:3$/
    ]);
  }
})();

(function testCallImportedWithParameters() {
51
  print(arguments.callee.name);
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  var stack;
  var passed_args = [];
  let func1 = (i, j) => (passed_args.push(i, j), 2 * i + j);
  let func2 = (f) => (passed_args.push(f), 8 * f);

  var builder = new WasmModuleBuilder();
  builder.addImport('mod', 'func1', makeSig([kWasmI32, kWasmI32], [kWasmF32]));
  builder.addImport('mod', 'func2', makeSig([kWasmF64], [kWasmI32]));
  builder.addFunction('main', makeSig([kWasmI32, kWasmF64], [kWasmF32]))
      .addBody([
        // call #0 with arg 0 and arg 0 + 1
        kExprGetLocal, 0, kExprGetLocal, 0, kExprI32Const, 1, kExprI32Add,
        kExprCallFunction, 0,
        // call #1 with arg 1
        kExprGetLocal, 1, kExprCallFunction, 1,
        // convert returned value to f32
        kExprF32UConvertI32,
        // add the two values
        kExprF32Add
      ])
      .exportFunc();
  var instance = builder.instantiate({mod: {func1: func1, func2: func2}});
74
  var interpreted_before = %WasmNumInterpretedCalls(instance);
75 76
  var args = [11, 0.3];
  var ret = instance.exports.main(...args);
77
  assertEquals(interpreted_before + 1, %WasmNumInterpretedCalls(instance));
78 79 80 81 82
  var passed_test_args = [...passed_args];
  var expected = func1(args[0], args[0] + 1) + func2(args[1]) | 0;
  assertEquals(expected, ret);
  assertArrayEquals([args[0], args[0] + 1, args[1]], passed_test_args);
})();
83 84

(function testTrap() {
85
  print(arguments.callee.name);
86 87 88 89 90 91 92 93 94 95
  var builder = new WasmModuleBuilder();
  var foo_idx = builder.addFunction('foo', kSig_v_v)
                    .addBody([kExprNop, kExprNop, kExprUnreachable])
                    .index;
  builder.addFunction('main', kSig_v_v)
      .addBody([kExprNop, kExprCallFunction, foo_idx])
      .exportFunc();
  var instance = builder.instantiate();
  // Test that this does not mess up internal state by executing it three times.
  for (var i = 0; i < 3; ++i) {
96
    var interpreted_before = %WasmNumInterpretedCalls(instance);
97 98 99 100 101 102 103
    var stack;
    try {
      instance.exports.main();
      assertUnreachable();
    } catch (e) {
      stack = e.stack;
    }
104
    assertEquals(interpreted_before + 2, %WasmNumInterpretedCalls(instance));
105 106
    checkStack(stripPath(stack), [
      'RuntimeError: unreachable',                    // -
107 108
      '    at foo (wasm-function[0]:3)',              // -
      '    at main (wasm-function[1]:2)',             // -
109 110 111 112 113
      /^    at testTrap \(interpreter.js:\d+:24\)$/,  // -
      /^    at interpreter.js:\d+:3$/
    ]);
  }
})();
114 115

(function testThrowFromImport() {
116
  print(arguments.callee.name);
117 118 119 120 121 122 123 124 125 126 127
  function func() {
    throw new Error('thrown from imported function');
  }
  var builder = new WasmModuleBuilder();
  builder.addImport("mod", "func", kSig_v_v);
  builder.addFunction('main', kSig_v_v)
      .addBody([kExprCallFunction, 0])
      .exportFunc();
  var instance = builder.instantiate({mod: {func: func}});
  // Test that this does not mess up internal state by executing it three times.
  for (var i = 0; i < 3; ++i) {
128
    var interpreted_before = %WasmNumInterpretedCalls(instance);
129 130 131 132 133 134 135
    var stack;
    try {
      instance.exports.main();
      assertUnreachable();
    } catch (e) {
      stack = e.stack;
    }
136
    assertEquals(interpreted_before + 1, %WasmNumInterpretedCalls(instance));
137
    checkStack(stripPath(stack), [
138 139
      'Error: thrown from imported function',                    // -
      /^    at func \(interpreter.js:\d+:11\)$/,                 // -
140
      '    at main (wasm-function[1]:1)',                        // -
141
      /^    at testThrowFromImport \(interpreter.js:\d+:24\)$/,  // -
142 143 144 145
      /^    at interpreter.js:\d+:3$/
    ]);
  }
})();
146 147

(function testGlobals() {
148
  print(arguments.callee.name);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  var builder = new WasmModuleBuilder();
  builder.addGlobal(kWasmI32, true);  // 0
  builder.addGlobal(kWasmI64, true);  // 1
  builder.addGlobal(kWasmF32, true);  // 2
  builder.addGlobal(kWasmF64, true);  // 3
  builder.addFunction('get_i32', kSig_i_v)
      .addBody([kExprGetGlobal, 0])
      .exportFunc();
  builder.addFunction('get_i64', kSig_d_v)
      .addBody([kExprGetGlobal, 1, kExprF64SConvertI64])
      .exportFunc();
  builder.addFunction('get_f32', kSig_d_v)
      .addBody([kExprGetGlobal, 2, kExprF64ConvertF32])
      .exportFunc();
  builder.addFunction('get_f64', kSig_d_v)
      .addBody([kExprGetGlobal, 3])
      .exportFunc();
  builder.addFunction('set_i32', kSig_v_i)
      .addBody([kExprGetLocal, 0, kExprSetGlobal, 0])
      .exportFunc();
  builder.addFunction('set_i64', kSig_v_d)
      .addBody([kExprGetLocal, 0, kExprI64SConvertF64, kExprSetGlobal, 1])
      .exportFunc();
  builder.addFunction('set_f32', kSig_v_d)
      .addBody([kExprGetLocal, 0, kExprF32ConvertF64, kExprSetGlobal, 2])
      .exportFunc();
  builder.addFunction('set_f64', kSig_v_d)
      .addBody([kExprGetLocal, 0, kExprSetGlobal, 3])
      .exportFunc();
  var instance = builder.instantiate();
  // Initially, all should be zero.
  assertEquals(0, instance.exports.get_i32());
  assertEquals(0, instance.exports.get_i64());
  assertEquals(0, instance.exports.get_f32());
  assertEquals(0, instance.exports.get_f64());
  // Assign values to all variables.
  var values = [4711, 1<<40 + 1 << 33, 0.3, 12.34567];
  instance.exports.set_i32(values[0]);
  instance.exports.set_i64(values[1]);
  instance.exports.set_f32(values[2]);
  instance.exports.set_f64(values[3]);
  // Now check the values.
  assertEquals(values[0], instance.exports.get_i32());
  assertEquals(values[1], instance.exports.get_i64());
  assertEqualsDelta(values[2], instance.exports.get_f32(), 2**-23);
  assertEquals(values[3], instance.exports.get_f64());
})();
196 197

(function testReentrantInterpreter() {
198
  print(arguments.callee.name);
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
  var stacks;
  var instance;
  function func(i) {
    stacks.push(new Error('reentrant interpreter test #' + i).stack);
    if (i < 2) instance.exports.main(i + 1);
  }

  var builder = new WasmModuleBuilder();
  builder.addImport('mod', 'func', kSig_v_i);
  builder.addFunction('main', kSig_v_i)
      .addBody([kExprGetLocal, 0, kExprCallFunction, 0])
      .exportFunc();
  instance = builder.instantiate({mod: {func: func}});
  // Test that this does not mess up internal state by executing it three times.
  for (var i = 0; i < 3; ++i) {
214
    var interpreted_before = %WasmNumInterpretedCalls(instance);
215 216
    stacks = [];
    instance.exports.main(0);
217
    assertEquals(interpreted_before + 3, %WasmNumInterpretedCalls(instance));
218 219 220 221
    assertEquals(3, stacks.length);
    for (var e = 0; e < stacks.length; ++e) {
      expected = ['Error: reentrant interpreter test #' + e];
      expected.push(/^    at func \(interpreter.js:\d+:17\)$/);
222
      expected.push('    at main (wasm-function[1]:3)');
223 224
      for (var k = e; k > 0; --k) {
        expected.push(/^    at func \(interpreter.js:\d+:33\)$/);
225
        expected.push('    at main (wasm-function[1]:3)');
226 227 228 229 230 231 232 233
      }
      expected.push(
          /^    at testReentrantInterpreter \(interpreter.js:\d+:22\)$/);
      expected.push(/    at interpreter.js:\d+:3$/);
      checkStack(stripPath(stacks[e]), expected);
    }
  }
})();
234 235

(function testIndirectImports() {
236
  print(arguments.callee.name);
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
  var builder = new WasmModuleBuilder();

  var sig_i_ii = builder.addType(kSig_i_ii);
  var sig_i_i = builder.addType(kSig_i_i);
  var mul = builder.addImport('q', 'mul', sig_i_ii);
  var add = builder.addFunction('add', sig_i_ii).addBody([
    kExprGetLocal, 0, kExprGetLocal, 1, kExprI32Add
  ]);
  var mismatch =
      builder.addFunction('sig_mismatch', sig_i_i).addBody([kExprGetLocal, 0]);
  var main = builder.addFunction('main', kSig_i_iii)
                 .addBody([
                   // Call indirect #0 with args <#1, #2>.
                   kExprGetLocal, 1, kExprGetLocal, 2, kExprGetLocal, 0,
                   kExprCallIndirect, sig_i_ii, kTableZero
                 ])
                 .exportFunc();
  builder.appendToTable([mul, add.index, mismatch.index, main.index]);

  var instance = builder.instantiate({q: {mul: (a, b) => a * b}});

  // Call mul.
  assertEquals(-6, instance.exports.main(0, -2, 3));
  // Call add.
  assertEquals(99, instance.exports.main(1, 22, 77));
  // main and sig_mismatch have another signature.
  assertTraps(kTrapFuncSigMismatch, () => instance.exports.main(2, 12, 33));
  assertTraps(kTrapFuncSigMismatch, () => instance.exports.main(3, 12, 33));
  // Function index 4 does not exist.
  assertTraps(kTrapFuncInvalid, () => instance.exports.main(4, 12, 33));
})();

(function testIllegalImports() {
270
  print(arguments.callee.name);
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  var builder = new WasmModuleBuilder();

  var sig_l_v = builder.addType(kSig_l_v);
  var imp = builder.addImport('q', 'imp', sig_l_v);
  var direct = builder.addFunction('direct', kSig_l_v)
                   .addBody([kExprCallFunction, imp])
                   .exportFunc();
  var indirect = builder.addFunction('indirect', kSig_l_v).addBody([
    kExprI32Const, 0, kExprCallIndirect, sig_l_v, kTableZero
  ]);
  var main =
      builder.addFunction('main', kSig_v_i)
          .addBody([
            // Call indirect #0 with arg #0, drop result.
            kExprGetLocal, 0, kExprCallIndirect, sig_l_v, kTableZero, kExprDrop
          ])
          .exportFunc();
  builder.appendToTable([imp, direct.index, indirect.index]);

  var instance = builder.instantiate({q: {imp: () => 1}});

  // Calling imported functions with i64 in signature should fail.
  try {
    // Via direct call.
    instance.exports.main(1);
  } catch (e) {
    if (!(e instanceof TypeError)) throw e;
    checkStack(stripPath(e.stack), [
      'TypeError: invalid type',                                // -
300 301
      '    at direct (wasm-function[1]:1)',                     // -
      '    at main (wasm-function[3]:3)',                       // -
302 303 304 305 306 307 308 309 310 311 312
      /^    at testIllegalImports \(interpreter.js:\d+:22\)$/,  // -
      /^    at interpreter.js:\d+:3$/
    ]);
  }
  try {
    // Via indirect call.
    instance.exports.main(2);
  } catch (e) {
    if (!(e instanceof TypeError)) throw e;
    checkStack(stripPath(e.stack), [
      'TypeError: invalid type',                                // -
313 314
      '    at indirect (wasm-function[2]:1)',                   // -
      '    at main (wasm-function[3]:3)',                       // -
315 316 317 318 319
      /^    at testIllegalImports \(interpreter.js:\d+:22\)$/,  // -
      /^    at interpreter.js:\d+:3$/
    ]);
  }
})();
320 321

(function testInfiniteRecursion() {
322
  print(arguments.callee.name);
323 324 325 326 327 328 329 330 331 332 333 334 335 336
  var builder = new WasmModuleBuilder();

  var direct = builder.addFunction('main', kSig_v_v)
                   .addBody([kExprNop, kExprCallFunction, 0])
                   .exportFunc();
  var instance = builder.instantiate();

  try {
    instance.exports.main();
    assertUnreachable("should throw");
  } catch (e) {
    if (!(e instanceof RangeError)) throw e;
    checkStack(stripPath(e.stack), [
      'RangeError: Maximum call stack size exceeded',
337 338
      '    at main (wasm-function[0]:0)'
    ].concat(Array(9).fill('    at main (wasm-function[0]:2)')));
339 340
  }
})();
341 342

(function testUnwindSingleActivation() {
343
  print(arguments.callee.name);
344 345 346 347 348 349 350
  // Create two activations and unwind just the top one.
  var builder = new WasmModuleBuilder();

  function MyError(i) {
    this.i = i;
  }

351
  // We call wasm -> func 1 -> wasm -> func2.
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  // func2 throws, func 1 catches.
  function func1() {
    try {
      return instance.exports.foo();
    } catch (e) {
      if (!(e instanceof MyError)) throw e;
      return e.i + 2;
    }
  }
  function func2() {
    throw new MyError(11);
  }
  var imp1 = builder.addImport('mod', 'func1', kSig_i_v);
  var imp2 = builder.addImport('mod', 'func2', kSig_v_v);
  builder.addFunction('main', kSig_i_v)
      .addBody([kExprCallFunction, imp1, kExprI32Const, 2, kExprI32Mul])
      .exportFunc();
  builder.addFunction('foo', kSig_v_v)
      .addBody([kExprCallFunction, imp2])
      .exportFunc();
  var instance = builder.instantiate({mod: {func1: func1, func2: func2}});

374
  var interpreted_before = %WasmNumInterpretedCalls(instance);
375
  assertEquals(2 * (11 + 2), instance.exports.main());
376
  assertEquals(interpreted_before + 2, %WasmNumInterpretedCalls(instance));
377
})();
378 379

(function testInterpreterGC() {
380
  print(arguments.callee.name);
381 382
  function run(f) {
    // wrap the creation in a closure so that the only thing returned is
383
    // the module (i.e. the underlying array buffer of wasm wire bytes dies).
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    var module = (() => {
      var builder = new WasmModuleBuilder();
      var imp = builder.addImport('mod', 'the_name_of_my_import', kSig_i_i);
      builder.addFunction('main', kSig_i_i)
          .addBody([kExprGetLocal, 0, kExprCallFunction, imp])
          .exportAs('main');
      print('module');
      return new WebAssembly.Module(builder.toBuffer());
    })();

    gc();
    for (var i = 0; i < 10; i++) {
      print('  instance ' + i);
      var instance =
          new WebAssembly.Instance(module, {'mod': {the_name_of_my_import: f}});
      var g = instance.exports.main;
      assertEquals('function', typeof g);
      for (var j = 0; j < 10; j++) {
        assertEquals(f(j), g(j));
      }
    }
  }

  for (var i = 0; i < 3; i++) {
    run(x => (x + 19));
    run(x => (x - 18));
  }
})();
412 413

(function testImportThrowsOnToNumber() {
414
  print(arguments.callee.name);
415
  const builder = new WasmModuleBuilder();
416
  const imp_idx = builder.addImport('mod', 'func', kSig_i_v);
417
  builder.addFunction('main', kSig_i_v)
418
      .addBody([kExprCallFunction, imp_idx])
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
      .exportFunc();
  var num_callback_calls = 0;
  const callback = () => {
    ++num_callback_calls;
    return Symbol()
  };
  var instance = builder.instantiate({mod: {func: callback}});
  // Test that this does not mess up internal state by executing it three times.
  for (var i = 0; i < 3; ++i) {
    var interpreted_before = %WasmNumInterpretedCalls(instance);
    assertThrows(
        () => instance.exports.main(), TypeError,
        'Cannot convert a Symbol value to a number');
    assertEquals(interpreted_before + 1, %WasmNumInterpretedCalls(instance));
    assertEquals(i + 1, num_callback_calls);
  }
})();
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

(function testCallWithMoreReturnsThenParams() {
  print(arguments.callee.name);
  const builder1 = new WasmModuleBuilder();
  builder1.addFunction('exp', kSig_l_v)
      .addBody([kExprI64Const, 23])
      .exportFunc();
  const exp = builder1.instantiate().exports.exp;
  const builder2 = new WasmModuleBuilder();
  const imp_idx = builder2.addImport('imp', 'func', kSig_l_v);
  builder2.addFunction('main', kSig_i_v)
      .addBody([kExprCallFunction, imp_idx, kExprI32ConvertI64])
      .exportFunc();
  const instance = builder2.instantiate({imp: {func: exp}});
  assertEquals(23, instance.exports.main());
})();
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

(function testTableCall() {
  print(arguments.callee.name);
  const builder1 = new WasmModuleBuilder();
  builder1.addFunction('func', kSig_v_v).addBody([]).exportFunc();
  const instance1 = builder1.instantiate();
  const table = new WebAssembly.Table({element: 'anyfunc', initial: 2});

  const builder2 = new WasmModuleBuilder()
  builder2.addImportedTable('m', 'table');
  const sig = builder2.addType(kSig_v_v);
  builder2.addFunction('call_func', kSig_v_v)
      .addBody([kExprI32Const, 0, kExprCallIndirect, sig, kTableZero])
      .exportFunc();
  const instance2 = builder2.instantiate({m: {table: table}});
  table.set(0, instance1.exports.func);
  instance2.exports.call_func();
})();
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

(function testTableCall2() {
  // See crbug.com/787910.
  print(arguments.callee.name);
  const builder1 = new WasmModuleBuilder();
  builder1.addFunction('exp', kSig_i_i)
      .addBody([kExprI32Const, 0])
      .exportFunc();
  const instance1 = builder1.instantiate();
  const builder2 = new WasmModuleBuilder();
  const sig1 = builder2.addType(kSig_i_v);
  const sig2 = builder2.addType(kSig_i_i);
  builder2.addFunction('call2', kSig_i_v)
      .addBody([
        kExprI32Const, 0, kExprI32Const, 0, kExprCallIndirect, sig2, kTableZero
      ])
      .exportAs('call2');
  builder2.addImportedTable('imp', 'table');
  const tab = new WebAssembly.Table({
    element: 'anyfunc',
    initial: 3,
  });
  const instance2 = builder2.instantiate({imp: {table: tab}});
  tab.set(0, instance1.exports.exp);
  instance2.exports.call2();
})();