Skip to content

Commit 211946c

Browse files
committed
add run-make test for wasm-exceptions
1 parent 6144130 commit 211946c

File tree

6 files changed

+252
-0
lines changed

6 files changed

+252
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
include ../tools.mk
2+
3+
# only-wasm32-bare
4+
5+
# Add a few command line args to make exceptions work
6+
RUSTC := $(RUSTC) -C llvm-args=-wasm-enable-eh
7+
RUSTC := $(RUSTC) -C target-feature=+exception-handling
8+
RUSTC := $(RUSTC) -C panic=unwind
9+
10+
all:
11+
$(RUSTC) src/lib.rs --target wasm32-unknown-unknown
12+
$(NODE) verify.mjs $(TMPDIR)/lib.wasm
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
use core::alloc::{GlobalAlloc, Layout};
2+
use core::cell::UnsafeCell;
3+
4+
#[global_allocator]
5+
static ALLOCATOR: ArenaAllocator = ArenaAllocator::new();
6+
7+
/// Very simple allocator which never deallocates memory
8+
///
9+
/// Based on the example from
10+
/// https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html
11+
pub struct ArenaAllocator {
12+
arena: UnsafeCell<Arena>,
13+
}
14+
15+
impl ArenaAllocator {
16+
pub const fn new() -> Self {
17+
Self {
18+
arena: UnsafeCell::new(Arena::new()),
19+
}
20+
}
21+
}
22+
23+
/// Safe because we are singlethreaded
24+
unsafe impl Sync for ArenaAllocator {}
25+
26+
unsafe impl GlobalAlloc for ArenaAllocator {
27+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
28+
let arena = &mut *self.arena.get();
29+
arena.alloc(layout)
30+
}
31+
32+
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
33+
}
34+
35+
const ARENA_SIZE: usize = 64 * 1024; // more than enough
36+
37+
#[repr(C, align(4096))]
38+
struct Arena {
39+
buf: [u8; ARENA_SIZE], // aligned at 4096
40+
allocated: usize,
41+
}
42+
43+
impl Arena {
44+
pub const fn new() -> Self {
45+
Self {
46+
buf: [0x55; ARENA_SIZE],
47+
allocated: 0,
48+
}
49+
}
50+
51+
pub unsafe fn alloc(&mut self, layout: Layout) -> *mut u8 {
52+
if layout.align() > 4096 || layout.size() > ARENA_SIZE {
53+
return core::ptr::null_mut();
54+
}
55+
56+
let align_minus_one = layout.align() - 1;
57+
let start = (self.allocated + align_minus_one) & !align_minus_one; // round up
58+
let new_cursor = start + layout.size();
59+
60+
if new_cursor >= ARENA_SIZE {
61+
return core::ptr::null_mut();
62+
}
63+
64+
self.allocated = new_cursor;
65+
self.buf.as_mut_ptr().add(start)
66+
}
67+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#![no_std]
2+
#![crate_type = "cdylib"]
3+
4+
// Allow a few unstable features because we create a panic
5+
// runtime for native wasm exceptions from scratch
6+
7+
#![feature(core_intrinsics)]
8+
#![feature(lang_items)]
9+
#![feature(link_llvm_intrinsics)]
10+
#![feature(panic_info_message)]
11+
12+
extern crate alloc;
13+
14+
/// This module allows us to use `Box`, `String`, ... even in no-std
15+
mod arena_alloc;
16+
17+
/// This module allows logging text, even in no-std
18+
mod logging;
19+
20+
/// This module allows exceptions, even in no-std
21+
#[cfg(target_arch = "wasm32")]
22+
mod panicking;
23+
24+
use alloc::boxed::Box;
25+
use alloc::string::String;
26+
27+
struct LogOnDrop;
28+
29+
impl Drop for LogOnDrop {
30+
fn drop(&mut self) {
31+
logging::log_str("Dropped");
32+
}
33+
}
34+
35+
#[allow(unreachable_code)]
36+
#[allow(unconditional_panic)]
37+
#[no_mangle]
38+
pub extern "C" fn start() -> usize {
39+
let data = 0x1234usize as *mut u8; // Something to recognize
40+
41+
unsafe {
42+
core::intrinsics::r#try(|data: *mut u8| {
43+
let _log_on_drop = LogOnDrop;
44+
45+
logging::log_str(&alloc::format!("`r#try` called with ptr {:?}", data));
46+
let x = [12];
47+
let _ = x[4]; // should panic
48+
49+
logging::log_str("This line should not be visible! :(");
50+
}, data, |data, exception| {
51+
let exception = *Box::from_raw(exception as *mut String);
52+
logging::log_str("Caught something!");
53+
logging::log_str(&alloc::format!(" data : {:?}", data));
54+
logging::log_str(&alloc::format!(" exception: {:?}", exception));
55+
});
56+
}
57+
58+
logging::log_str("This program terminates correctly.");
59+
0
60+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
extern "C" {
2+
fn __log_utf8(ptr: *const u8, size: usize);
3+
}
4+
5+
pub fn log_str(text: &str) {
6+
unsafe {
7+
__log_utf8(text.as_ptr(), text.len());
8+
}
9+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#[lang = "eh_personality"]
2+
fn eh_personality() {}
3+
4+
mod internal {
5+
extern "C" {
6+
#[link_name = "llvm.wasm.throw"]
7+
pub fn wasm_throw(tag: i32, ptr: *mut u8) -> !;
8+
}
9+
}
10+
11+
unsafe fn wasm_throw(ptr: *mut u8) -> ! {
12+
internal::wasm_throw(0, ptr);
13+
}
14+
15+
#[panic_handler]
16+
fn panic_handler(info: &core::panic::PanicInfo<'_>) -> ! {
17+
use alloc::boxed::Box;
18+
use alloc::string::ToString;
19+
20+
let msg = info
21+
.message()
22+
.map(|msg| msg.to_string())
23+
.unwrap_or("(no message)".to_string());
24+
let exception = Box::new(msg.to_string());
25+
unsafe {
26+
let exception_raw = Box::into_raw(exception);
27+
wasm_throw(exception_raw as *mut u8);
28+
}
29+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import fs from 'fs';
2+
3+
const dec = new TextDecoder("utf-8");
4+
5+
if (process.argv.length != 3) {
6+
console.log("Usage: node verify.mjs <wasm-file>");
7+
process.exit(0);
8+
}
9+
10+
const wasmfile = process.argv[2];
11+
if (!fs.existsSync(wasmfile)) {
12+
console.log("Error: File not found:", wasmfile);
13+
process.exit(1);
14+
}
15+
16+
const wasmBuffer = fs.readFileSync(wasmfile);
17+
18+
async function main() {
19+
20+
let memory = new ArrayBuffer(0) // will be changed after instantiate
21+
22+
const captured_output = [];
23+
24+
const imports = {
25+
env: {
26+
__log_utf8: (ptr, size) => {
27+
const str = dec.decode(new DataView(memory, ptr, size));
28+
captured_output.push(str);
29+
console.log(str);
30+
}
31+
}
32+
};
33+
34+
const wasmModule = await WebAssembly.instantiate(wasmBuffer, imports);
35+
memory = wasmModule.instance.exports.memory.buffer;
36+
37+
const start = wasmModule.instance.exports.start;
38+
const return_code = start();
39+
40+
console.log("Return-Code:", return_code);
41+
42+
if (return_code !== 0) {
43+
console.error("Expected return code 0");
44+
process.exit(return_code);
45+
}
46+
47+
const expected_output = [
48+
'`r#try` called with ptr 0x1234',
49+
'Dropped',
50+
'Caught something!',
51+
' data : 0x1234',
52+
' exception: "index out of bounds: the len is 1 but the index is 4"',
53+
'This program terminates correctly.',
54+
];
55+
56+
assert_equal(captured_output, expected_output);
57+
}
58+
59+
function assert_equal(captured_output, expected_output) {
60+
if (captured_output.length != expected_output.length) {
61+
console.error("Unexpected number of output lines. Got", captured_output.length, "but expected", expected_output.length);
62+
process.exit(1); // exit with error
63+
}
64+
65+
for (let idx = 0; idx < expected_output.length; ++idx) {
66+
if (captured_output[idx] !== expected_output[idx]) {
67+
console.error("Unexpected output");
68+
console.error("[got] ", captured_output[idx]);
69+
console.error("[expected]", expected_output[idx]);
70+
process.exit(2); // exit with error
71+
}
72+
}
73+
}
74+
75+
await main();

0 commit comments

Comments
 (0)