blob: db5a9390fddeccc60fa281558656f10a60509c0c [file] [log] [blame]
Kaido Kertf309f9a2021-04-30 12:09:15 -07001// Copyright 2016 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Flags: --expose-wasm
6
7load("test/mjsunit/wasm/wasm-module-builder.js");
8
9// Collect the Callsite objects instead of just a string:
10Error.prepareStackTrace = function(error, frames) {
11 return frames;
12};
13
14function testTrapLocations(instance, expected_stack_length) {
15 function testWasmTrap(value, reason, position) {
16 let function_name = arguments.callee.name;
17 try {
18 instance.exports.main(value);
19 fail('expected wasm exception');
20 } catch (e) {
21 assertEquals(kTrapMsgs[reason], e.message, 'trap reason');
22 // Check that the trapping function is the one which was called from this
23 // function.
24 assertTrue(
25 e.stack[1].toString().startsWith(function_name), 'stack depth');
26 assertEquals(0, e.stack[0].getLineNumber(), 'wasmFunctionIndex');
27 assertEquals(position, e.stack[0].getPosition(), 'position');
28 }
29 }
30
31 // The actual tests:
32 testWasmTrap(0, kTrapDivByZero, 14);
33 testWasmTrap(1, kTrapMemOutOfBounds, 15);
34 testWasmTrap(2, kTrapUnreachable, 28);
35 testWasmTrap(3, kTrapTableOutOfBounds, 32);
36}
37
38var builder = new WasmModuleBuilder();
39builder.addMemory(0, 1, false);
40var sig_index = builder.addType(kSig_i_v)
41
42// Build a function to resemble this code:
43// if (idx < 2) {
44// return load(-2 / idx);
45// } else if (idx == 2) {
46// unreachable;
47// } else {
48// return call_indirect(idx);
49// }
50// There are four different traps which are triggered by different input values:
51// (0) division by zero; (1) mem oob; (2) unreachable; (3) invalid call target
52// Each of them also has a different location where it traps.
53builder.addFunction("main", kSig_i_i)
54 .addBody([
55 // offset 1
56 kExprBlock, kWasmI32,
57 kExprLocalGet, 0,
58 kExprI32Const, 2,
59 kExprI32LtU,
60 kExprIf, kWasmStmt,
61 // offset 9
62 kExprI32Const, 0x7e /* -2 */,
63 kExprLocalGet, 0,
64 kExprI32DivU,
65 // offset 15
66 kExprI32LoadMem, 0, 0,
67 kExprBr, 1,
68 kExprEnd,
69 // offset 21
70 kExprLocalGet, 0,
71 kExprI32Const, 2,
72 kExprI32Eq,
73 kExprIf, kWasmStmt,
74 kExprUnreachable,
75 kExprEnd,
76 // offset 30
77 kExprLocalGet, 0,
78 kExprCallIndirect, sig_index, kTableZero,
79 kExprEnd,
80 ])
81 .exportAs("main");
82builder.appendToTable([0]);
83
84let buffer = builder.toBuffer();
85
86// Test async compilation and instantiation.
87assertPromiseResult(WebAssembly.instantiate(buffer), pair => {
88 testTrapLocations(pair.instance, 5);
89});
90
91// Test sync compilation and instantiation.
92testTrapLocations(builder.instantiate(), 4);