Merge pull request #27 from wasmerio/feature/compile-and-run-nginx-wasm

[WIP] Provide necessary APIs needed to run nginx.wasm
This commit is contained in:
Syrus Akbary 2018-12-03 17:48:27 -08:00 committed by GitHub
commit c341257df0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 2208 additions and 260 deletions

53
Cargo.lock generated
View File

@ -27,7 +27,7 @@ name = "atty"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -39,7 +39,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)",
"cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -50,7 +50,7 @@ version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -58,6 +58,11 @@ name = "bitflags"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "byteorder"
version = "1.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "cc"
version = "1.0.25"
@ -206,7 +211,7 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"errno-dragonfly 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -216,7 +221,7 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -278,12 +283,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "libc"
version = "0.2.43"
source = "git+https://github.com/rust-lang/libc#5cc006652a242c35b6fe5b615ccd39d9356a2346"
version = "0.2.44"
source = "git+https://github.com/rust-lang/libc#d4b45f51ea751d9685a956b9c011698359e4cc06"
[[package]]
name = "libc"
version = "0.2.43"
version = "0.2.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
@ -299,7 +304,7 @@ name = "mach"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -308,7 +313,7 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -317,7 +322,7 @@ name = "memmap"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -328,13 +333,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "nix"
version = "0.11.0"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)",
"cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -348,7 +353,7 @@ name = "num_cpus"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -373,7 +378,7 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -404,7 +409,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"crossbeam-deque 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -449,7 +454,7 @@ dependencies = [
"bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"errno 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
"failure 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"mach 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -592,7 +597,7 @@ name = "termion"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
"redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
@ -672,16 +677,17 @@ dependencies = [
name = "wasmer"
version = "0.1.0"
dependencies = [
"byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
"cranelift-codegen 0.23.0",
"cranelift-entity 0.23.0",
"cranelift-native 0.23.0",
"cranelift-wasm 0.23.0",
"docopt 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"error-chain 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.43 (git+https://github.com/rust-lang/libc)",
"libc 0.2.44 (git+https://github.com/rust-lang/libc)",
"log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
"memmap 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)",
"nix 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"nix 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rayon 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
"region 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)",
@ -730,6 +736,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "89a47830402e9981c5c41223151efcced65a0510c13097c769cede7efb34782a"
"checksum backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)" = "c66d56ac8dabd07f6aacdaf633f4b8262f5b3601a810a0dcddffd5c22c69daa0"
"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12"
"checksum byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "94f88df23a25417badc922ab0f5716cc1330e87f71ddd9203b3a3ccd9cedf75d"
"checksum cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)" = "f159dfd43363c4d08055a07703eb7a3406b0dac4d0584d96965a3262db3c9d16"
"checksum cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0c4e7bb64a8ebb0d856483e1e682ea3422f883c5f5615a90d51a2c82fe87fdd3"
"checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e"
@ -749,14 +756,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)" = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2"
"checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b"
"checksum lazy_static 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a374c89b9db55895453a74c1e38861d9deec0b01b405a82516e9d5de4820dea1"
"checksum libc 0.2.43 (git+https://github.com/rust-lang/libc)" = "<none>"
"checksum libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)" = "76e3a3ef172f1a0b9a9ff0dd1491ae5e6c948b94479a3021819ba7d860c8645d"
"checksum libc 0.2.44 (git+https://github.com/rust-lang/libc)" = "<none>"
"checksum libc 0.2.44 (registry+https://github.com/rust-lang/crates.io-index)" = "10923947f84a519a45c8fefb7dd1b3e8c08747993381adee176d7a82b4195311"
"checksum log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d4fcce5fa49cc693c312001daf1d13411c4a5283796bac1084299ea3e567113f"
"checksum mach 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "2fd13ee2dd61cc82833ba05ade5a30bb3d63f7ced605ef827063c63078302de9"
"checksum memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4b3629fe9fdbff6daa6c33b90f7c08355c1aca05a3d01fa8063b822fcf185f3b"
"checksum memmap 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e2ffa2c986de11a9df78620c01eeaaf27d94d3ff02bf81bfcca953102dd0c6ff"
"checksum memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3"
"checksum nix 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d37e713a259ff641624b6cb20e3b12b2952313ba36b6823c0f16e6cfd9e5de17"
"checksum nix 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "921f61dc817b379d0834e45d5ec45beaacfae97082090a49c2cf30dcbc30206f"
"checksum nodrop 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "2f9667ddcc6cc8a43afc9b7917599d7216aa09c463919ea32c59ed6cac8bc945"
"checksum num_cpus 1.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c51a3322e4bca9d212ad9a158a02abc6934d005490c054a2778df73a70aa0a30"
"checksum proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)" = "3d7b7eaaa90b4a90a932a9ea6666c95a389e424eff347f0f793979289429feee"

View File

@ -43,8 +43,9 @@ log = "0.4.5"
target-lexicon = "0.2.0"
# libc = "0.2"
libc = { git = "https://github.com/rust-lang/libc" }
nix = "0.11"
nix = "0.12.0"
rayon = "1.0.3"
byteorder = "1"
[build-dependencies]
wabt = "0.7.1"

View File

@ -25,10 +25,9 @@ release:
# If you are in OS-X, you will need mingw-w64 for cross compiling to windows
# brew install mingw-w64
cargo build --release
# mkdir -p artifacts
# BINARY_NAME := $(./binary-name.sh)
# cp ./target/release/wasmer ./artifacts/$(./binary-name.sh)
# cp ./target/release/wasmer ./artifacts/${BINARY_NAME}
debug-release:
cargo build --release --features "debug"
publish-release:
ghr -t ${GITHUB_TOKEN} -u ${CIRCLE_PROJECT_USERNAME} -r ${CIRCLE_PROJECT_REPONAME} -c ${CIRCLE_SHA1} -delete ${VERSION} ./artifacts/

View File

@ -1,31 +0,0 @@
(module
(type $t1 (func (param i32 i32) (result i32)))
(type $t2 (func (param i32)))
(type $t3 (func ))
(func $printf (import "env" "printf") (type $t1))
(func $abort (import "env" "abort") (type $t2))
(func $_abort (import "env" "_abort") (type $t3))
(func $abort_on_cannot_grow_memory (import "env" "abortOnCannotGrowMemory") (type $t3))
(memory 1)
(data (i32.const 0) ">>> First\00")
(data (i32.const 24) ">>> Second\00")
(data (i32.const 48) "Aborting abruptly!\00")
(func $main (export "main")
;; print ">>> First"
(call $printf (i32.const 0) (i32.const 0))
(drop)
;; aborts
(call $_abort) ;; ()
;; aborts
(call $abort_on_cannot_grow_memory) ;; ()
;; aborts
(call $abort (i32.const 48)) ;; (message: u32)
;; print ">>> Second"
(call $printf (i32.const 24) (i32.const 0))
(drop)
)
)

View File

@ -1,27 +0,0 @@
(module
(type $t1 (func (param i32)))
(func $putchar (import "env" "putchar") (type $t1))
(func $sys_exit (import "env" "___syscall1") (type $t1))
(memory 1)
(func $main (export "main")
;; print "Hello"
(call $putchar (i32.const 72))
(call $putchar (i32.const 101))
(call $putchar (i32.const 108))
(call $putchar (i32.const 108))
(call $putchar (i32.const 111))
(call $putchar (i32.const 32))
;; exit abruptly
(call $sys_exit (i32.const 255)) ;; (status: c_int) -> c_int
;; print " World!"
(call $putchar (i32.const 87))
(call $putchar (i32.const 111))
(call $putchar (i32.const 114))
(call $putchar (i32.const 108))
(call $putchar (i32.const 100))
(call $putchar (i32.const 33))
(call $putchar (i32.const 10))
)
)

BIN
examples/nginx.wasm Normal file

Binary file not shown.

View File

@ -5,12 +5,13 @@
(type $t4 (func (param i32 i32) (result i32)))
(func $putchar (import "env" "putchar") (type $t1))
(func $printf (import "env" "printf") (type $t4))
(func $sys_open (import "env" "___syscall5") (type $t2))
(func $sys_read (import "env" "___syscall3") (type $t2))
(func $sys_close (import "env" "___syscall6") (type $t3))
(func $sys_open (import "env" "sys_open") (type $t2))
(func $sys_read (import "env" "sys_read") (type $t2))
(func $sys_close (import "env" "sys_close") (type $t3))
(func $sys_exit (import "env" "sys_exit") (type $t1))
(memory 1)
(data $filename (i32.const 0) "/Users/xxxx/Desktop/hello.txt\00")
(func $main (export "main")
(func $main (export "_main")
;; declare variables
(local $string_buf_addr i32)
(local $string_buf_len i32)
@ -39,5 +40,8 @@
;; print file content
(call $printf (get_local $string_buf_addr) (i32.const 0))
(drop) ;; ignoring errors
;; exit
(call $exit (i32.const 0))
)
)

View File

@ -127,7 +127,7 @@
```rust
```
- **dup** (\_\_\_syscall63) &nbsp;&nbsp;&nbsp;&nbsp;[:top:](#host-apis)
- **dup2** (\_\_\_syscall63) &nbsp;&nbsp;&nbsp;&nbsp;[:top:](#host-apis)
```rust
```
@ -511,3 +511,14 @@
```rust
```
### LEGEND &nbsp;&nbsp;&nbsp;&nbsp;[:top:](#host-apis)
✅ - Implemented
❗️ - Elevated privilege
🔥 - Possible memory access violation
📥 - Access to external memory
📝 - External write to internal memory

View File

@ -1,9 +1,11 @@
use super::super::host;
/// NOTE: These syscalls only support wasm_32 for now because they take u32 offset
use libc::{c_int};
use libc::{c_int, getgrnam as libc_getgrnam, getpwnam as libc_getpwnam};
use std::ffi::CStr;
use std::mem;
use std::os::raw::c_char;
use super::utils::{copy_cstr_into_wasm, copy_terminated_array_of_cstrs};
use crate::webassembly::Instance;
/// emscripten: _getenv
@ -20,3 +22,91 @@ pub extern "C" fn _getenv(name_ptr: c_int, instance: &mut Instance) -> c_int {
Err(_) => 0,
}
}
pub extern "C" fn _getpwnam(name_ptr: c_int, instance: &mut Instance) -> c_int {
debug!("emscripten::_getpwnam {}", name_ptr);
#[repr(C)]
struct GuestPasswd {
pw_name: u32,
pw_passwd: u32,
pw_uid: u32,
pw_gid: u32,
pw_gecos: u32,
pw_dir: u32,
pw_shell: u32,
}
let name = unsafe {
let memory_name_ptr = instance.memory_offset_addr(0, name_ptr as usize) as *const c_char;
CStr::from_ptr(memory_name_ptr)
};
unsafe {
let passwd = &*libc_getpwnam(name.as_ptr());
let passwd_struct_offset = (instance.emscripten_data.as_ref().unwrap().malloc)(
mem::size_of::<GuestPasswd>() as _,
instance,
);
let passwd_struct_ptr =
instance.memory_offset_addr(0, passwd_struct_offset as _) as *mut GuestPasswd;
(*passwd_struct_ptr).pw_name = copy_cstr_into_wasm(instance, passwd.pw_name);
(*passwd_struct_ptr).pw_passwd = copy_cstr_into_wasm(instance, passwd.pw_passwd);
(*passwd_struct_ptr).pw_gecos = copy_cstr_into_wasm(instance, passwd.pw_gecos);
(*passwd_struct_ptr).pw_dir = copy_cstr_into_wasm(instance, passwd.pw_dir);
(*passwd_struct_ptr).pw_shell = copy_cstr_into_wasm(instance, passwd.pw_shell);
(*passwd_struct_ptr).pw_uid = passwd.pw_uid;
(*passwd_struct_ptr).pw_gid = passwd.pw_gid;
passwd_struct_offset as c_int
}
}
pub extern "C" fn _getgrnam(name_ptr: c_int, instance: &mut Instance) -> c_int {
debug!("emscripten::_getgrnam {}", name_ptr);
#[repr(C)]
struct GuestGroup {
gr_name: u32,
gr_passwd: u32,
gr_gid: u32,
gr_mem: u32,
}
let name = unsafe {
let memory_name_ptr = instance.memory_offset_addr(0, name_ptr as usize) as *const c_char;
CStr::from_ptr(memory_name_ptr)
};
unsafe {
let group = &*libc_getgrnam(name.as_ptr());
let group_struct_offset = (instance.emscripten_data.as_ref().unwrap().malloc)(
mem::size_of::<GuestGroup>() as _,
instance,
);
let group_struct_ptr =
instance.memory_offset_addr(0, group_struct_offset as _) as *mut GuestGroup;
(*group_struct_ptr).gr_name = copy_cstr_into_wasm(instance, group.gr_name);
(*group_struct_ptr).gr_passwd = copy_cstr_into_wasm(instance, group.gr_passwd);
(*group_struct_ptr).gr_gid = group.gr_gid;
(*group_struct_ptr).gr_mem = copy_terminated_array_of_cstrs(instance, group.gr_mem);
group_struct_offset as c_int
}
}
pub extern "C" fn _localtime_r() -> u32 {
debug!("emscripten::_localtime_r");
0
}
pub extern "C" fn _getpagesize() -> u32 {
debug!("emscripten::_getpagesize");
16384
}
pub extern "C" fn ___build_environment(environ: c_int) {
debug!("emscripten::___build_environment {}", environ);
}

View File

@ -0,0 +1,265 @@
// use std::collections::HashMap;
pub extern "C" fn ___seterrno(value: i32) -> i32 {
debug!("emscripten::___seterrno");
// TODO: Incomplete impl
eprintln!("failed to set errno!");
value
}
// pub enum ErrnoCodes {
// EPERM = 1,
// ENOENT = 2,
// ESRCH = 3,
// EINTR = 4,
// EIO = 5,
// ENXIO = 6,
// E2BIG = 7,
// ENOEXEC = 8,
// EBADF = 9,
// ECHILD = 10,
// EAGAIN = 11,
// EWOULDBLOCK = 11,
// ENOMEM = 12,
// EACCES = 13,
// EFAULT = 14,
// ENOTBLK = 15,
// EBUSY = 16,
// EEXIST = 17,
// EXDEV = 18,
// ENODEV = 19,
// ENOTDIR = 20,
// EISDIR = 21,
// EINVAL = 22,
// ENFILE = 23,
// EMFILE = 24,
// ENOTTY = 25,
// ETXTBSY = 26,
// EFBIG = 27,
// ENOSPC = 28,
// ESPIPE = 29,
// EROFS = 30,
// EMLINK = 31,
// EPIPE = 32,
// EDOM = 33,
// ERANGE = 34,
// ENOMSG = 42,
// EIDRM = 43,
// ECHRNG = 44,
// EL2NSYNC = 45,
// EL3HLT = 46,
// EL3RST = 47,
// ELNRNG = 48,
// EUNATCH = 49,
// ENOCSI = 50,
// EL2HLT = 51,
// EDEADLK = 35,
// ENOLCK = 37,
// EBADE = 52,
// EBADR = 53,
// EXFULL = 54,
// ENOANO = 55,
// EBADRQC = 56,
// EBADSLT = 57,
// EDEADLOCK = 35,
// EBFONT = 59,
// ENOSTR = 60,
// ENODATA = 61,
// ETIME = 62,
// ENOSR = 63,
// ENONET = 64,
// ENOPKG = 65,
// EREMOTE = 66,
// ENOLINK = 67,
// EADV = 68,
// ESRMNT = 69,
// ECOMM = 70,
// EPROTO = 71,
// EMULTIHOP = 72,
// EDOTDOT = 73,
// EBADMSG = 74,
// ENOTUNIQ = 76,
// EBADFD = 77,
// EREMCHG = 78,
// ELIBACC = 79,
// ELIBBAD = 80,
// ELIBSCN = 81,
// ELIBMAX = 82,
// ELIBEXEC = 83,
// ENOSYS = 38,
// ENOTEMPTY = 39,
// ENAMETOOLONG = 36,
// ELOOP = 40,
// EOPNOTSUPP = 95,
// EPFNOSUPPORT = 96,
// ECONNRESET = 104,
// ENOBUFS = 105,
// EAFNOSUPPORT = 97,
// EPROTOTYPE = 91,
// ENOTSOCK = 88,
// ENOPROTOOPT = 92,
// ESHUTDOWN = 108,
// ECONNREFUSED = 111,
// EADDRINUSE = 98,
// ECONNABORTED = 103,
// ENETUNREACH = 101,
// ENETDOWN = 100,
// ETIMEDOUT = 110,
// EHOSTDOWN = 112,
// EHOSTUNREACH = 113,
// EINPROGRESS = 115,
// EALREADY = 114,
// EDESTADDRREQ = 89,
// EMSGSIZE = 90,
// EPROTONOSUPPORT = 93,
// ESOCKTNOSUPPORT = 94,
// EADDRNOTAVAIL = 99,
// ENETRESET = 102,
// EISCONN = 106,
// ENOTCONN = 107,
// ETOOMANYREFS = 109,
// EUSERS = 87,
// EDQUOT = 122,
// ESTALE = 116,
// ENOTSUP = 95,
// ENOMEDIUM = 123,
// EILSEQ = 84,
// EOVERFLOW = 75,
// ECANCELED = 125,
// ENOTRECOVERABLE = 131,
// EOWNERDEAD = 130,
// ESTRPIPE = 86,
// }
// pub struct ErrnoMessages<'a> {
// message_map: HashMap<u32, &'a str>
// }
// impl<'a> ErrnoMessages<'a> {
// fn new() -> Self {
// let mut message_map = HashMap::new();
// message_map.insert(0, "Success");
// message_map.insert(1, "Not super-user");
// message_map.insert(2, "No such file or directory");
// message_map.insert(3, "No such process");
// message_map.insert(4, "Interrupted system call");
// message_map.insert(5, "I/O error");
// message_map.insert(6, "No such device or address");
// message_map.insert(7, "Arg list too long");
// message_map.insert(8, "Exec format error");
// message_map.insert(9, "Bad file number");
// message_map.insert(10, "No children");
// message_map.insert(11, "No more processes");
// message_map.insert(12, "Not enough core");
// message_map.insert(13, "Permission denied");
// message_map.insert(14, "Bad address");
// message_map.insert(15, "Block device required");
// message_map.insert(16, "Mount device busy");
// message_map.insert(17, "File exists");
// message_map.insert(18, "Cross-device link");
// message_map.insert(19, "No such device");
// message_map.insert(20, "Not a directory");
// message_map.insert(21, "Is a directory");
// message_map.insert(22, "Invalid argument");
// message_map.insert(23, "Too many open files in system");
// message_map.insert(24, "Too many open files");
// message_map.insert(25, "Not a typewriter");
// message_map.insert(26, "Text file busy");
// message_map.insert(27, "File too large");
// message_map.insert(28, "No space left on device");
// message_map.insert(29, "Illegal seek");
// message_map.insert(30, "Read only file system");
// message_map.insert(31, "Too many links");
// message_map.insert(32, "Broken pipe");
// message_map.insert(33, "Math arg out of domain of func");
// message_map.insert(34, "Math result not representable");
// message_map.insert(35, "File locking deadlock error");
// message_map.insert(36, "File or path name too long");
// message_map.insert(37, "No record locks available");
// message_map.insert(38, "Function not implemented");
// message_map.insert(39, "Directory not empty");
// message_map.insert(40, "Too many symbolic links");
// message_map.insert(42, "No message of desired type");
// message_map.insert(43, "Identifier removed");
// message_map.insert(44, "Channel number out of range");
// message_map.insert(45, "Level 2 not synchronized");
// message_map.insert(46, "Level 3 halted");
// message_map.insert(47, "Level 3 reset");
// message_map.insert(48, "Link number out of range");
// message_map.insert(49, "Protocol driver not attached");
// message_map.insert(50, "No CSI structure available");
// message_map.insert(51, "Level 2 halted");
// message_map.insert(52, "Invalid exchange");
// message_map.insert(53, "Invalid request descriptor");
// message_map.insert(54, "Exchange full");
// message_map.insert(55, "No anode");
// message_map.insert(56, "Invalid request code");
// message_map.insert(57, "Invalid slot");
// message_map.insert(59, "Bad font file fmt");
// message_map.insert(60, "Device not a stream");
// message_map.insert(61, "No data (for no delay io)");
// message_map.insert(62, "Timer expired");
// message_map.insert(63, "Out of streams resources");
// message_map.insert(64, "Machine is not on the network");
// message_map.insert(65, "Package not installed");
// message_map.insert(66, "The object is remote");
// message_map.insert(67, "The link has been severed");
// message_map.insert(68, "Advertise error");
// message_map.insert(69, "Srmount error");
// message_map.insert(70, "Communication error on send");
// message_map.insert(71, "Protocol error");
// message_map.insert(72, "Multihop attempted");
// message_map.insert(73, "Cross mount point (not really error)");
// message_map.insert(74, "Trying to read unreadable message");
// message_map.insert(75, "Value too large for defined data type");
// message_map.insert(76, "Given log. name not unique");
// message_map.insert(77, "f.d. invalid for this operation");
// message_map.insert(78, "Remote address changed");
// message_map.insert(79, "Can access a needed shared lib");
// message_map.insert(80, "Accessing a corrupted shared lib");
// message_map.insert(81, ".lib section in a.out corrupted");
// message_map.insert(82, "Attempting to link in too many libs");
// message_map.insert(83, "Attempting to exec a shared library");
// message_map.insert(84, "Illegal byte sequence");
// message_map.insert(86, "Streams pipe error");
// message_map.insert(87, "Too many users");
// message_map.insert(88, "Socket operation on non-socket");
// message_map.insert(89, "Destination address required");
// message_map.insert(90, "Message too long");
// message_map.insert(91, "Protocol wrong type for socket");
// message_map.insert(92, "Protocol not available");
// message_map.insert(93, "Unknown protocol");
// message_map.insert(94, "Socket type not supported");
// message_map.insert(95, "Not supported");
// message_map.insert(96, "Protocol family not supported");
// message_map.insert(97, "Address family not supported by protocol family");
// message_map.insert(98, "Address already in use");
// message_map.insert(99, "Address not available");
// message_map.insert(100, "Network interface is not configured");
// message_map.insert(101, "Network is unreachable");
// message_map.insert(102, "Connection reset by network");
// message_map.insert(103, "Connection aborted");
// message_map.insert(104, "Connection reset by peer");
// message_map.insert(105, "No buffer space available");
// message_map.insert(106, "Socket is already connected");
// message_map.insert(107, "Socket is not connected");
// message_map.insert(108, "Can't send after socket shutdown");
// message_map.insert(109, "Too many references");
// message_map.insert(110, "Connection timed out");
// message_map.insert(111, "Connection refused");
// message_map.insert(112, "Host is down");
// message_map.insert(113, "Host is unreachable");
// message_map.insert(114, "Socket already connected");
// message_map.insert(115, "Connection already in progress");
// message_map.insert(116, "Stale file handle");
// message_map.insert(122, "Quota exceeded");
// message_map.insert(123, "No medium (in tape drive)");
// message_map.insert(125, "Operation canceled");
// message_map.insert(130, "Previous owner died");
// message_map.insert(131, "State not recoverable");
// ErrnoMessages {
// message_map,
// }
// }
// }

View File

@ -0,0 +1,12 @@
use crate::webassembly::Instance;
use libc::c_int;
// NOTE: Not implemented by Emscripten
pub extern "C" fn ___lock(_which: c_int, _varargs: c_int, _instance: &mut Instance) {
debug!("emscripten::___lock");
}
// NOTE: Not implemented by Emscripten
pub extern "C" fn ___unlock(_which: c_int, _varargs: c_int, _instance: &mut Instance) {
debug!("emscripten::___unlock");
}

View File

@ -1,6 +1,6 @@
use libc::{c_void, memcpy, size_t};
use super::process::abort_with_message;
use crate::webassembly::Instance;
use libc::{c_void, memcpy, size_t};
/// emscripten: _emscripten_memcpy_big
pub extern "C" fn _emscripten_memcpy_big(
@ -19,9 +19,10 @@ pub extern "C" fn _emscripten_memcpy_big(
}
/// emscripten: getTotalMemory
pub extern "C" fn get_total_memory(instance: &mut Instance) -> u32 {
pub extern "C" fn get_total_memory(_instance: &mut Instance) -> u32 {
debug!("emscripten::get_total_memory");
instance.memories[0].current_pages()
// instance.memories[0].current_pages()
16777216
}
/// emscripten: enlargeMemory
@ -29,3 +30,9 @@ pub extern "C" fn enlarge_memory(_instance: &mut Instance) {
debug!("emscripten::enlarge_memory");
// instance.memories[0].grow(100);
}
/// emscripten: abortOnCannotGrowMemory
pub extern "C" fn abort_on_cannot_grow_memory() {
debug!("emscripten::abort_on_cannot_grow_memory");
abort_with_message("Cannot enlarge memory arrays!");
}

View File

@ -1,88 +1,490 @@
use crate::webassembly::{ImportObject, ImportValue};
use byteorder::{ByteOrder, LittleEndian};
/// NOTE: TODO: These emscripten api implementation only support wasm32 for now because they assume offsets are u32
use crate::webassembly::{ImportObject, ImportValue, LinearMemory};
use std::mem;
// EMSCRIPTEN APIS
mod env;
mod errno;
mod io;
mod lock;
mod memory;
mod nullfunc;
mod process;
mod signal;
mod storage;
mod syscalls;
mod time;
mod utils;
mod varargs;
// SYSCALLS
pub use self::storage::{align_memory, static_alloc};
pub use self::utils::is_emscripten_module;
// TODO: Magic number - how is this calculated?
const TOTAL_STACK: u32 = 5242880;
// TODO: Magic number stolen from the generated JS - how is this calculated?
const DYNAMICTOP_PTR_DIFF: u32 = 1088;
const STATIC_BUMP: u32 = 215536; // TODO: make this variable
fn stacktop(static_bump: u32) -> u32 {
align_memory(dynamictop_ptr(static_bump) + 4)
}
fn stack_max(static_bump: u32) -> u32 {
stacktop(static_bump) + TOTAL_STACK
}
fn dynamic_base(static_bump: u32) -> u32 {
align_memory(stack_max(static_bump))
}
fn dynamictop_ptr(static_bump: u32) -> u32 {
static_bump + DYNAMICTOP_PTR_DIFF
}
// fn static_alloc(size: usize, static_top: &mut size) -> usize {
// let ret = *static_top;
// *static_top = (*static_top + size + 15) & (-16 as usize);
// ret
// }
pub fn emscripten_set_up_memory(memory: &mut LinearMemory) {
let dynamictop_ptr = dynamictop_ptr(STATIC_BUMP) as usize;
let dynamictop_ptr_offset = dynamictop_ptr + mem::size_of::<u32>();
// We avoid failures of setting the u32 in our memory if it's out of bounds
if dynamictop_ptr_offset > memory.len() {
return;
}
let mem = &mut memory[dynamictop_ptr..dynamictop_ptr_offset];
LittleEndian::write_u32(mem, dynamic_base(STATIC_BUMP));
}
macro_rules! mock_external {
($import:ident, $name:ident) => {{
extern "C" fn _mocked_fn() -> i32 {
debug!("emscripten::{} <mock>", stringify!($name));
-1
}
$import.set("env", stringify!($name), ImportValue::Func(_mocked_fn as _));
}};
}
pub fn generate_emscripten_env<'a, 'b>() -> ImportObject<&'a str, &'b str> {
let mut import_object = ImportObject::new();
import_object.set("env", "printf", ImportValue::Func(io::printf as *const u8));
// Global
import_object.set(
"env",
"putchar",
ImportValue::Func(io::putchar as *const u8),
"global1",
ImportValue::Global(24), // TODO
);
// Emscripten Env
import_object.set(
"env",
"_getenv",
ImportValue::Func(env::_getenv as *const u8),
"global2",
ImportValue::Global(50), // TODO
);
import_object.set(
"env",
"global3",
ImportValue::Global(67), // TODO
);
import_object.set(
"env",
"STACKTOP",
ImportValue::Global(stacktop(STATIC_BUMP) as _),
);
import_object.set(
"env",
"STACK_MAX",
ImportValue::Global(stack_max(STATIC_BUMP) as _),
);
import_object.set(
"env",
"DYNAMICTOP_PTR",
ImportValue::Global(dynamictop_ptr(STATIC_BUMP) as _),
);
import_object.set("env", "tableBase", ImportValue::Global(0));
// Print functions
import_object.set("env", "printf", ImportValue::Func(io::printf as _));
import_object.set("env", "putchar", ImportValue::Func(io::putchar as _));
// Lock
import_object.set("env", "___lock", ImportValue::Func(lock::___lock as _));
import_object.set("env", "___unlock", ImportValue::Func(lock::___unlock as _));
// Env
import_object.set("env", "_getenv", ImportValue::Func(env::_getenv as _));
import_object.set("env", "_getpwnam", ImportValue::Func(env::_getpwnam as _));
import_object.set("env", "_getgrnam", ImportValue::Func(env::_getgrnam as _));
import_object.set("env", "___buildEnvironment", ImportValue::Func(env::___build_environment as _));
// Errno
import_object.set(
"env",
"___setErrNo",
ImportValue::Func(errno::___seterrno as _),
);
// Syscalls
import_object.set(
"env",
"___syscall1",
ImportValue::Func(syscalls::___syscall1 as _),
);
// Emscripten syscalls
import_object.set(
"env",
"___syscall3",
ImportValue::Func(syscalls::___syscall3 as *const u8),
ImportValue::Func(syscalls::___syscall3 as _),
);
import_object.set(
"env",
"___syscall4",
ImportValue::Func(syscalls::___syscall4 as *const u8),
ImportValue::Func(syscalls::___syscall4 as _),
);
import_object.set(
"env",
"___syscall5",
ImportValue::Func(syscalls::___syscall5 as *const u8),
ImportValue::Func(syscalls::___syscall5 as _),
);
import_object.set(
"env",
"___syscall6",
ImportValue::Func(syscalls::___syscall6 as _),
);
import_object.set(
"env",
"___syscall54",
ImportValue::Func(syscalls::___syscall54 as *const u8),
ImportValue::Func(syscalls::___syscall54 as _),
);
import_object.set(
"env",
"___syscall140",
ImportValue::Func(syscalls::___syscall140 as _),
);
import_object.set(
"env",
"___syscall145",
ImportValue::Func(syscalls::___syscall145 as _),
);
import_object.set(
"env",
"___syscall146",
ImportValue::Func(syscalls::___syscall146 as _),
);
import_object.set(
"env",
"___syscall221",
ImportValue::Func(syscalls::___syscall221 as _),
);
import_object.set(
"env",
"___syscall20",
ImportValue::Func(syscalls::___syscall20 as _),
);
import_object.set(
"env",
"___syscall64",
ImportValue::Func(syscalls::___syscall64 as _),
);
import_object.set(
"env",
"___syscall122",
ImportValue::Func(syscalls::___syscall122 as *const u8),
);
// Emscripten other APIs
import_object.set(
"env",
"abort",
ImportValue::Func(process::em_abort as *const u8),
ImportValue::Func(syscalls::___syscall122 as _),
);
import_object.set(
"env",
"_abort",
ImportValue::Func(process::_abort as *const u8),
"___syscall201",
ImportValue::Func(syscalls::___syscall201 as _),
);
import_object.set(
"env",
"___syscall202",
ImportValue::Func(syscalls::___syscall202 as _),
);
import_object.set(
"env",
"___syscall340",
ImportValue::Func(syscalls::___syscall340 as _),
);
import_object.set(
"env",
"___syscall197",
ImportValue::Func(syscalls::___syscall197 as _),
);
import_object.set(
"env",
"___syscall180",
ImportValue::Func(syscalls::___syscall180 as _),
);
import_object.set(
"env",
"___syscall181",
ImportValue::Func(syscalls::___syscall181 as _),
);
import_object.set(
"env",
"___syscall39",
ImportValue::Func(syscalls::___syscall39 as _),
);
import_object.set(
"env",
"___syscall195",
ImportValue::Func(syscalls::___syscall195 as _),
);
import_object.set(
"env",
"___syscall212",
ImportValue::Func(syscalls::___syscall212 as _),
);
import_object.set(
"env",
"___syscall221",
ImportValue::Func(syscalls::___syscall221 as _),
);
import_object.set(
"env",
"___syscall102",
ImportValue::Func(syscalls::___syscall102 as _),
);
import_object.set(
"env",
"___syscall54",
ImportValue::Func(syscalls::___syscall54 as _),
);
import_object.set(
"env",
"___syscall12",
ImportValue::Func(syscalls::___syscall12 as _),
);
import_object.set(
"env",
"___syscall192",
ImportValue::Func(syscalls::___syscall192 as _),
);
import_object.set(
"env",
"___syscall63",
ImportValue::Func(syscalls::___syscall63 as _),
);
import_object.set(
"env",
"___syscall142",
ImportValue::Func(syscalls::___syscall142 as _),
);
import_object.set(
"env",
"___syscall57",
ImportValue::Func(syscalls::___syscall57 as _),
);
// Process
import_object.set("env", "abort", ImportValue::Func(process::em_abort as _));
import_object.set("env", "_abort", ImportValue::Func(process::_abort as _));
import_object.set(
"env",
"abortStackOverflow",
ImportValue::Func(process::abort_stack_overflow as _),
);
import_object.set("env", "_fork", ImportValue::Func(process::_fork as _));
import_object.set("env", "_exit", ImportValue::Func(process::_exit as _));
// Signal
import_object.set(
"env",
"_sigemptyset",
ImportValue::Func(signal::_sigemptyset as _),
);
import_object.set(
"env",
"_sigaddset",
ImportValue::Func(signal::_sigaddset as _),
);
import_object.set(
"env",
"_sigprocmask",
ImportValue::Func(signal::_sigprocmask as _),
);
import_object.set(
"env",
"_sigaction",
ImportValue::Func(signal::_sigaction as _),
);
import_object.set(
"env",
"_signal",
ImportValue::Func(signal::_signal as _),
);
// Memory
import_object.set(
"env",
"abortOnCannotGrowMemory",
ImportValue::Func(process::abort_on_cannot_grow_memory as *const u8),
ImportValue::Func(memory::abort_on_cannot_grow_memory as _),
);
import_object.set(
"env",
"_emscripten_memcpy_big",
ImportValue::Func(memory::_emscripten_memcpy_big as *const u8),
ImportValue::Func(memory::_emscripten_memcpy_big as _),
);
import_object.set(
"env",
"enlargeMemory",
ImportValue::Func(memory::enlarge_memory as *const u8),
ImportValue::Func(memory::enlarge_memory as _),
);
import_object.set(
"env",
"getTotalMemory",
ImportValue::Func(memory::get_total_memory as *const u8),
ImportValue::Func(memory::get_total_memory as _),
);
// NullFuncs
import_object.set(
"env",
"nullFunc_ii",
ImportValue::Func(nullfunc::nullfunc_ii as _),
);
import_object.set(
"env",
"nullFunc_iii",
ImportValue::Func(nullfunc::nullfunc_iii as _),
);
import_object.set(
"env",
"nullFunc_iiii",
ImportValue::Func(nullfunc::nullfunc_iiii as _),
);
import_object.set(
"env",
"nullFunc_iiiii",
ImportValue::Func(nullfunc::nullfunc_iiiii as _),
);
import_object.set(
"env",
"nullFunc_iiiiii",
ImportValue::Func(nullfunc::nullfunc_iiiiii as _),
);
import_object.set(
"env",
"nullFunc_vi",
ImportValue::Func(nullfunc::nullfunc_vi as _),
);
import_object.set(
"env",
"nullFunc_vii",
ImportValue::Func(nullfunc::nullfunc_vii as _),
);
import_object.set(
"env",
"nullFunc_viii",
ImportValue::Func(nullfunc::nullfunc_viii as _),
);
import_object.set(
"env",
"nullFunc_viiii",
ImportValue::Func(nullfunc::nullfunc_viiii as _),
);
// Time
import_object.set(
"env",
"_gettimeofday",
ImportValue::Func(time::_gettimeofday as _),
);
import_object.set(
"env",
"_clock_gettime",
ImportValue::Func(time::_clock_gettime as _),
);
import_object.set(
"env",
"_localtime",
ImportValue::Func(time::_localtime as _),
);
import_object.set("env", "_time", ImportValue::Func(time::_time as _));
import_object.set("env", "_strftime", ImportValue::Func(time::_strftime as _));
import_object.set(
"env",
"_localtime_r",
ImportValue::Func(env::_localtime_r as _),
);
import_object.set(
"env",
"_getpagesize",
ImportValue::Func(env::_getpagesize as _),
);
mock_external!(import_object, _waitpid);
mock_external!(import_object, _utimes);
mock_external!(import_object, _usleep);
// mock_external!(import_object, _time);
mock_external!(import_object, _sysconf);
// mock_external!(import_object, _strftime);
mock_external!(import_object, _sigsuspend);
// mock_external!(import_object, _sigprocmask);
// mock_external!(import_object, _sigemptyset);
// mock_external!(import_object, _sigaddset);
// mock_external!(import_object, _sigaction);
mock_external!(import_object, _setitimer);
mock_external!(import_object, _setgroups);
mock_external!(import_object, _setgrent);
mock_external!(import_object, _sem_wait);
mock_external!(import_object, _sem_post);
mock_external!(import_object, _sem_init);
mock_external!(import_object, _sched_yield);
mock_external!(import_object, _raise);
mock_external!(import_object, _mktime);
// mock_external!(import_object, _localtime_r);
// mock_external!(import_object, _localtime);
mock_external!(import_object, _llvm_stacksave);
mock_external!(import_object, _llvm_stackrestore);
mock_external!(import_object, _kill);
mock_external!(import_object, _gmtime_r);
// mock_external!(import_object, _gettimeofday);
// mock_external!(import_object, _getpagesize);
mock_external!(import_object, _getgrent);
mock_external!(import_object, _getaddrinfo);
// mock_external!(import_object, _fork);
// mock_external!(import_object, _exit);
mock_external!(import_object, _execve);
mock_external!(import_object, _endgrent);
// mock_external!(import_object, _clock_gettime);
mock_external!(import_object, ___syscall97);
mock_external!(import_object, ___syscall91);
mock_external!(import_object, ___syscall85);
mock_external!(import_object, ___syscall75);
mock_external!(import_object, ___syscall66);
// mock_external!(import_object, ___syscall64);
// mock_external!(import_object, ___syscall63);
mock_external!(import_object, ___syscall60);
// mock_external!(import_object, ___syscall54);
// mock_external!(import_object, ___syscall39);
mock_external!(import_object, ___syscall38);
// mock_external!(import_object, ___syscall340);
mock_external!(import_object, ___syscall334);
mock_external!(import_object, ___syscall300);
mock_external!(import_object, ___syscall295);
mock_external!(import_object, ___syscall272);
mock_external!(import_object, ___syscall268);
// mock_external!(import_object, ___syscall221);
mock_external!(import_object, ___syscall220);
// mock_external!(import_object, ___syscall212);
// mock_external!(import_object, ___syscall201);
mock_external!(import_object, ___syscall199);
// mock_external!(import_object, ___syscall197);
mock_external!(import_object, ___syscall196);
// mock_external!(import_object, ___syscall195);
mock_external!(import_object, ___syscall194);
mock_external!(import_object, ___syscall191);
// mock_external!(import_object, ___syscall181);
// mock_external!(import_object, ___syscall180);
mock_external!(import_object, ___syscall168);
// mock_external!(import_object, ___syscall146);
// mock_external!(import_object, ___syscall145);
// mock_external!(import_object, ___syscall142);
mock_external!(import_object, ___syscall140);
// mock_external!(import_object, ___syscall122);
// mock_external!(import_object, ___syscall102);
// mock_external!(import_object, ___syscall20);
mock_external!(import_object, ___syscall15);
mock_external!(import_object, ___syscall10);
import_object
}

View File

@ -0,0 +1,47 @@
use super::process::abort_with_message;
use crate::webassembly::Instance;
pub extern "C" fn nullfunc_ii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_ii");
abort_with_message("Invalid function pointer called with signature 'ii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_iii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_iii");
abort_with_message("Invalid function pointer called with signature 'iii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_iiii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_iiii");
abort_with_message("Invalid function pointer called with signature 'iiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_iiiii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_iiiii");
abort_with_message("Invalid function pointer called with signature 'iiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_iiiiii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_iiiiii");
abort_with_message("Invalid function pointer called with signature 'iiiiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_vi(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_vi");
abort_with_message("Invalid function pointer called with signature 'vi'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_vii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_vii");
abort_with_message("Invalid function pointer called with signature 'vii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_viii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_viii");
abort_with_message("Invalid function pointer called with signature 'viii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}
pub extern "C" fn nullfunc_viiii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_viiii");
abort_with_message("Invalid function pointer called with signature 'viiii'. Perhaps this is an invalid value (e.g. caused by calling a virtual method on a NULL pointer)? Or calling a function with an incorrect type, which will fail? (it is worth building your source files with -Werror (warnings are errors), as warnings can indicate undefined behavior which can cause this)");
}

View File

@ -1,22 +1,14 @@
use libc::{
// size_t,
// ssize_t,
abort,
// c_int,
// c_void,
c_char,
};
use libc::{abort, c_char, pid_t, c_int, fork, exit};
use crate::webassembly::Instance;
use std::ffi::CStr;
extern "C" fn abort_with_message(message: &str) {
pub extern "C" fn abort_with_message(message: &str) {
debug!("emscripten::abort_with_message");
println!("{}", message);
_abort();
}
/// emscripten: _abort
pub extern "C" fn _abort() {
debug!("emscripten::_abort");
unsafe {
@ -24,7 +16,21 @@ pub extern "C" fn _abort() {
}
}
/// emscripten: abort
pub extern "C" fn _fork(_instance: &mut Instance) -> pid_t {
debug!("emscripten::_fork");
// unsafe {
// fork()
// }
-1
}
pub extern "C" fn _exit(status: c_int, _instance: &mut Instance) -> ! {
debug!("emscripten::_exit");
unsafe {
exit(status)
}
}
pub extern "C" fn em_abort(message: u32, instance: &mut Instance) {
debug!("emscripten::em_abort");
let message_addr = instance.memory_offset_addr(0, message as usize) as *mut c_char;
@ -37,8 +43,8 @@ pub extern "C" fn em_abort(message: u32, instance: &mut Instance) {
}
}
/// emscripten: abortOnCannotGrowMemory
pub extern "C" fn abort_on_cannot_grow_memory() {
debug!("emscripten::abort_on_cannot_grow_memory");
abort_with_message("Cannot enlarge memory arrays!");
pub extern "C" fn abort_stack_overflow() {
debug!("emscripten::abort_stack_overflow");
// TODO: Message incomplete. Need to finish em runtime data first
abort_with_message("Stack overflow! Attempted to allocate some bytes on the stack");
}

View File

@ -0,0 +1,35 @@
// use super::varargs::VarArgs;
use crate::webassembly::Instance;
pub extern "C" fn _sigemptyset(set: u32, instance: &mut Instance) -> i32 {
debug!("emscripten::_sigemptyset");
let set_addr = instance.memory_offset_addr(0, set as _) as *mut u32;
unsafe {
*set_addr = 0;
}
0
}
pub extern "C" fn _sigaction(_signum: u32, _act: u32, _oldact: u32, _instance: &mut Instance) -> i32 {
debug!("emscripten::_sigaction");
0
}
pub extern "C" fn _sigaddset(set: u32, signum: u32, instance: &mut Instance) -> i32 {
debug!("emscripten::_sigaddset");
let set_addr = instance.memory_offset_addr(0, set as _) as *mut u32;
unsafe {
*set_addr |= 1 << (signum - 1);
}
0
}
pub extern "C" fn _sigprocmask() -> i32 {
debug!("emscripten::_sigprocmask");
0
}
pub extern "C" fn _signal(sig: u32, _instance: &mut Instance) -> i32 {
debug!("emscripten::_signal ({})", sig);
0
}

View File

@ -0,0 +1,25 @@
use crate::webassembly::LinearMemory;
pub fn align_memory(ptr: u32) -> u32 {
(ptr + 15) & !15
}
// pub fn static_alloc(size: u32, instance: &mut Instance) -> u32 {
// let static_top = instance.emscripten_data.static_top;
// let total_memory = instance.memories[0].maximum.unwrap_or(LinearMemory::DEFAULT_HEAP_SIZE as u32);
// instance.emscripten_data.static_top = (static_top + size + 15) & 4294967280;
// assert!(static_top < total_memory, "not enough memory for static allocation - increase total_memory!");
// static_top
// }
pub fn static_alloc(size: u32, static_top: &mut u32, memory: &LinearMemory) -> u32 {
let old_static_top = *static_top;
let total_memory = memory.maximum_size() * LinearMemory::PAGE_SIZE;
// NOTE: The `4294967280` is a u32 conversion of -16 as gotten from emscripten.
*static_top = (*static_top + size + 15) & 4294967280;
assert!(
*static_top < total_memory,
"not enough memory for static allocation - increase total_memory!"
);
old_static_top
}

View File

@ -1,49 +1,852 @@
/// NOTE: These syscalls only support wasm_32 for now because they take u32 offset
/// Syscall list: https://www.cs.utexas.edu/~bismith/test/syscalls/syscalls32.html
use libc::{c_int, c_void, ssize_t, write};
use crate::webassembly::Instance;
use super::utils::copy_stat_into_wasm;
use super::varargs::VarArgs;
use crate::webassembly::Instance;
use byteorder::{ByteOrder, LittleEndian};
use std::slice;
use std::mem;
/// NOTE: TODO: These syscalls only support wasm_32 for now because they assume offsets are u32
/// Syscall list: https://www.cs.utexas.edu/~bismith/test/syscalls/syscalls32.html
use libc::{
accept,
bind,
c_int,
c_void,
chown,
ioctl,
// fcntl, setsockopt, getppid
close,
connect,
dup2,
exit,
fstat,
getgid,
getpeername,
getpid,
getsockname,
getsockopt,
gid_t,
iovec,
listen,
lseek,
mkdir,
msghdr,
off_t,
open,
pid_t,
pread,
pwrite,
read,
readv,
recvfrom,
recvmsg,
sendmsg,
sendto,
setsockopt,
sockaddr,
socket,
socklen_t,
ssize_t,
stat,
uname,
utsname,
write,
writev,
select,
FIONBIO,
setpgid,
chdir,
sa_family_t,
in_port_t,
in_addr_t,
sockaddr_in,
FIOCLEX,
SOL_SOCKET,
TIOCGWINSZ
};
// use std::sys::fd::FileDesc;
/// sys_read
pub extern "C" fn ___syscall3(_which: c_int, mut _varargs: VarArgs, _instance: &mut Instance) -> ssize_t {
debug!("emscripten::___syscall3");
0
// Another conditional constant for name resolution: Macos et iOS use
// SO_NOSIGPIPE as a setsockopt flag to disable SIGPIPE emission on socket.
// Other platforms do otherwise.
#[cfg(target_os = "darwin")]
use libc::SO_NOSIGPIPE;
#[cfg(not(target_os = "darwin"))]
const SO_NOSIGPIPE: c_int = 0;
/// exit
pub extern "C" fn ___syscall1(_which: c_int, mut varargs: VarArgs, instance: &mut Instance) {
debug!("emscripten::___syscall1 (exit)");
let status: i32 = varargs.get(instance);
unsafe {
exit(status);
}
}
/// sys_write
pub extern "C" fn ___syscall4(_which: c_int, mut varargs: VarArgs, instance: &mut Instance) -> c_int {
/// read
pub extern "C" fn ___syscall3(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> ssize_t {
debug!("emscripten::___syscall3 (read)");
let fd: i32 = varargs.get(instance);
let buf_ptr: u32 = varargs.get(instance);
let count: u32 = varargs.get(instance);
debug!("fd: {}, buf_ptr: {}, count: {}", fd, buf_ptr, count);
let buf = instance.memory_offset_addr(0, buf_ptr as usize) as *const c_void;
unsafe { write(fd, buf, count as usize) as i32 }
}
/// sys_open
pub extern "C" fn ___syscall5(_which: c_int, mut varargs: VarArgs, instance: &mut Instance) -> c_int {
debug!("emscripten::___syscall5");
let pathname: u32 = varargs.get(instance);
let flags: u32 = varargs.get(instance);
let mode: u32 = varargs.get(instance);
debug!("pathname: {}, flags: {}, mode: {}", pathname, flags, mode);
-2
}
// sys_ioctl
pub extern "C" fn ___syscall54(_which: c_int, mut varargs: VarArgs, instance: &mut Instance) -> c_int {
debug!("emscripten::___syscall54");
let stream: u32 = varargs.get(instance);
let op: u32 = varargs.get(instance);
debug!("stream: {}, op: {}", stream, op);
0
}
// sys_newuname
pub extern "C" fn ___syscall122(_which: c_int, mut varargs: VarArgs, instance: &mut Instance) -> c_int {
debug!("emscripten::___syscall122");
let buf: u32 = varargs.get(instance);
debug!("buf: {}", buf);
let count: usize = varargs.get(instance);
debug!("=> fd: {}, buf_offset: {}, count: {}", fd, buf, count);
let buf_addr = instance.memory_offset_addr(0, buf as usize) as *mut c_void;
let ret = unsafe { read(fd, buf_addr, count) };
debug!("=> ret: {}", ret);
ret
}
/// write
pub extern "C" fn ___syscall4(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall4 (write)");
let fd: i32 = varargs.get(instance);
let buf: u32 = varargs.get(instance);
let count: u32 = varargs.get(instance);
debug!("=> fd: {}, buf: {}, count: {}", fd, buf, count);
let buf_addr = instance.memory_offset_addr(0, buf as usize) as *const c_void;
unsafe { write(fd, buf_addr, count as usize) as i32 }
}
/// open
pub extern "C" fn ___syscall5(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall5 (open)");
let pathname: u32 = varargs.get(instance);
let flags: i32 = varargs.get(instance);
let mode: u32 = varargs.get(instance);
let pathname_addr = instance.memory_offset_addr(0, pathname as usize) as *const i8;
let path_str = unsafe { std::ffi::CStr::from_ptr(pathname_addr).to_str().unwrap() };
let fd = unsafe { open(pathname_addr, flags, mode) };
debug!(
"=> pathname: {}, flags: {}, mode: {} = fd: {}\npath: {}",
pathname, flags, mode, fd, path_str
);
fd
}
/// close
pub extern "C" fn ___syscall6(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall6 (close)");
let fd: i32 = varargs.get(instance);
debug!("fd: {}", fd);
unsafe { close(fd) }
}
// chdir
pub extern "C" fn ___syscall12(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall12 (chdir)");
let path_addr: i32 = varargs.get(instance);
unsafe {
let path_ptr = instance.memory_offset_addr(0, path_addr as usize) as *const i8;
let path = std::ffi::CStr::from_ptr(path_ptr);
let ret = chdir(path_ptr);
debug!("=> path: {:?}, ret: {}", path, ret);
ret
}
}
// getpid
pub extern "C" fn ___syscall20() -> pid_t {
debug!("emscripten::___syscall20 (getpid)");
unsafe { getpid() }
}
// mkdir
pub extern "C" fn ___syscall39(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall39 (mkdir)");
let pathname: u32 = varargs.get(instance);
let mode: u32 = varargs.get(instance);
let pathname_addr = instance.memory_offset_addr(0, pathname as usize) as *const i8;
unsafe { mkdir(pathname_addr, mode as _) };
0
}
// getppid
pub extern "C" fn ___syscall64() -> pid_t {
debug!("emscripten::___syscall64 (getppid)");
unsafe { getpid() }
}
/// ioctl
pub extern "C" fn ___syscall54(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall54 (ioctl)");
let fd: i32 = varargs.get(instance);
let request: u32 = varargs.get(instance);
debug!("fd: {}, op: {}", fd, request);
// Got the equivalents here: https://code.woboq.org/linux/linux/include/uapi/asm-generic/ioctls.h.html
match request as _ {
21537 => { // FIONBIO
let argp: u32 = varargs.get(instance);
let argp_ptr = instance.memory_offset_addr(0, argp as _);
let ret = unsafe { ioctl(fd, FIONBIO, argp_ptr) };
debug!("ret: {}", ret);
ret
},
21523 => { // TIOCGWINSZ
let argp: u32 = varargs.get(instance);
let argp_ptr = instance.memory_offset_addr(0, argp as _);
let ret = unsafe { ioctl(fd, TIOCGWINSZ, argp_ptr) };
debug!("ret: {}", ret);
ret
},
_ => {
debug!("emscripten::___syscall54 -> non implemented case {}", request);
0
}
}
}
// socketcall
pub extern "C" fn ___syscall102(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall102 (socketcall)");
let call: u32 = varargs.get(instance);
let mut socket_varargs: VarArgs = varargs.get(instance);
#[repr(C)]
pub struct GuestSockaddrIn {
pub sin_family: sa_family_t, // u16
pub sin_port: in_port_t, // u16
pub sin_addr: GuestInAddr, // u32
pub sin_zero: [u8; 8], // u8 * 8
// 2 + 2 + 4 + 8 = 16
}
#[repr(C)]
pub struct GuestInAddr {
pub s_addr: in_addr_t, // u32
}
// debug!("GuestSockaddrIn = {}", size_of::<GuestSockaddrIn>());
match call {
1 => {
debug!("socket: socket");
// socket (domain: c_int, ty: c_int, protocol: c_int) -> c_int
let domain: i32 = socket_varargs.get(instance);
let ty: i32 = socket_varargs.get(instance);
let protocol: i32 = socket_varargs.get(instance);
let fd = unsafe { socket(domain, ty, protocol) };
// set_cloexec
unsafe {
ioctl(fd, FIOCLEX);
};
if cfg!(target_os = "darwin") {
type T = u32;
let payload = 1 as *const T as *const c_void;
unsafe {
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, payload, mem::size_of::<T>() as socklen_t);
};
};
debug!(
"=> domain: {} (AF_INET/2), type: {} (SOCK_STREAM/1), protocol: {} = fd: {}",
domain, ty, protocol, fd
);
fd
}
2 => {
debug!("socket: bind");
// bind (socket: c_int, address: *const sockaddr, address_len: socklen_t) -> c_int
// TODO: Emscripten has a different signature.
let socket: i32 = socket_varargs.get(instance);
let address: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let address = instance.memory_offset_addr(0, address as usize) as *mut sockaddr;
// unsafe {
// debug!(
// "=> address.sin_family: {:?}, address.sin_port: {:?}, address.sin_addr.s_addr: {:?}",
// (*address).sin_family, (*address).sin_port, (*address).sin_addr.s_addr
// );
// }
// we convert address as a sockaddr (even if this is incorrect), to bypass the type
// issue with libc bind
// Debug received address
unsafe {
let proper_address = address as *const GuestSockaddrIn;
debug!(
"=> address.sin_family: {:?}, address.sin_port: {:?}, address.sin_addr.s_addr: {:?}",
(*proper_address).sin_family, (*proper_address).sin_port, (*proper_address).sin_addr.s_addr
);
}
let status = unsafe { bind(socket, address, address_len) };
// debug!("=> status: {}", status);
debug!(
"=> socketfd: {}, address: {:?}, address_len: {} = status: {}",
socket, address, address_len, status
);
status
// -1
}
3 => {
debug!("socket: connect");
// connect (socket: c_int, address: *const sockaddr, len: socklen_t) -> c_int
// TODO: Emscripten has a different signature.
let socket: i32 = socket_varargs.get(instance);
let address: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let address = instance.memory_offset_addr(0, address as usize) as *mut sockaddr;
unsafe { connect(socket, address, address_len) }
}
4 => {
debug!("socket: listen");
// listen (socket: c_int, backlog: c_int) -> c_int
let socket: i32 = socket_varargs.get(instance);
let backlog: i32 = socket_varargs.get(instance);
let status = unsafe { listen(socket, backlog) };
debug!(
"=> socketfd: {}, backlog: {} = status: {}",
socket, backlog, status
);
status
}
5 => {
debug!("socket: accept");
// accept (socket: c_int, address: *mut sockaddr, address_len: *mut socklen_t) -> c_int
let socket: i32 = socket_varargs.get(instance);
let address: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let address = instance.memory_offset_addr(0, address as usize) as *mut sockaddr;
debug!("=> socket: {}, address: {:?}, address_len: {}", socket, address, address_len);
let address_len_addr =
instance.memory_offset_addr(0, address_len as usize) as *mut socklen_t;
// let mut address_len_addr: socklen_t = 0;
let fd = unsafe { accept(socket, address, address_len_addr) };
// Debug received address
unsafe {
let proper_address = address as *const GuestSockaddrIn;
debug!(
"=> address.sin_family: {:?}, address.sin_port: {:?}, address.sin_addr.s_addr: {:?}",
(*proper_address).sin_family, (*proper_address).sin_port, (*proper_address).sin_addr.s_addr
);
}
// set_cloexec
unsafe {
ioctl(fd, FIOCLEX);
};
debug!("fd: {}", fd);
// nix::unistd::write(fd, "Hello, World!".as_bytes()).unwrap();
// nix::unistd::fsync(fd).unwrap();
fd
}
6 => {
debug!("socket: getsockname");
// getsockname (socket: c_int, address: *mut sockaddr, address_len: *mut socklen_t) -> c_int
let socket: i32 = socket_varargs.get(instance);
let address: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let address = instance.memory_offset_addr(0, address as usize) as *mut sockaddr;
let address_len_addr =
instance.memory_offset_addr(0, address_len as usize) as *mut socklen_t;
unsafe { getsockname(socket, address, address_len_addr) }
}
7 => {
debug!("socket: getpeername");
// getpeername (socket: c_int, address: *mut sockaddr, address_len: *mut socklen_t) -> c_int
let socket: i32 = socket_varargs.get(instance);
let address: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let address = instance.memory_offset_addr(0, address as usize) as *mut sockaddr;
let address_len_addr =
instance.memory_offset_addr(0, address_len as usize) as *mut socklen_t;
unsafe { getpeername(socket, address, address_len_addr) }
}
11 => {
debug!("socket: sendto");
// sendto (socket: c_int, buf: *const c_void, len: size_t, flags: c_int, addr: *const sockaddr, addrlen: socklen_t) -> ssize_t
let socket: i32 = socket_varargs.get(instance);
let buf: u32 = socket_varargs.get(instance);
let flags: usize = socket_varargs.get(instance);
let len: i32 = socket_varargs.get(instance);
let address: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let buf_addr = instance.memory_offset_addr(0, buf as usize) as *mut c_void;
let address = instance.memory_offset_addr(0, address as usize) as *mut sockaddr;
unsafe { sendto(socket, buf_addr, flags, len, address, address_len) as i32 }
}
12 => {
debug!("socket: recvfrom");
// recvfrom (socket: c_int, buf: *const c_void, len: size_t, flags: c_int, addr: *const sockaddr, addrlen: socklen_t) -> ssize_t
let socket: i32 = socket_varargs.get(instance);
let buf: u32 = socket_varargs.get(instance);
let flags: usize = socket_varargs.get(instance);
let len: i32 = socket_varargs.get(instance);
let address: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let buf_addr = instance.memory_offset_addr(0, buf as usize) as *mut c_void;
let address = instance.memory_offset_addr(0, address as usize) as *mut sockaddr;
let address_len_addr =
instance.memory_offset_addr(0, address_len as usize) as *mut socklen_t;
unsafe { recvfrom(socket, buf_addr, flags, len, address, address_len_addr) as i32 }
}
14 => {
debug!("socket: setsockopt");
// NOTE: Emscripten seems to be passing the wrong values to this syscall
// level: Em passes 1 as SOL_SOCKET; SOL_SOCKET is 0xffff in BSD
// name: Em passes SO_ACCEPTCONN, but Nginx complains about REUSEADDR
// https://github.com/openbsd/src/blob/master/sys/sys/socket.h#L156
// setsockopt (socket: c_int, level: c_int, name: c_int, value: *const c_void, option_len: socklen_t) -> c_int
let socket: i32 = socket_varargs.get(instance);
// SOL_SOCKET = 0xffff in BSD
let level: i32 = 0xffff;
let _: u32 = socket_varargs.get(instance);
// SO_ACCEPTCONN = 0x4
let name: i32 = 0x4;
let _: u32 = socket_varargs.get(instance);
let value: u32 = socket_varargs.get(instance);
let option_len: u32 = socket_varargs.get(instance);
let value_addr = instance.memory_offset_addr(0, value as usize) as *mut c_void; // Endian problem
let ret = unsafe { setsockopt(socket, level, name, value_addr, option_len) };
// debug!("option_value = {:?}", unsafe { *(value_addr as *const u32) });
debug!("=> socketfd: {}, level: {} (SOL_SOCKET/0xffff), name: {} (SO_REUSEADDR/4), value_addr: {:?}, option_len: {} = status: {}", socket, level, name, value_addr, option_len, ret);
ret
}
15 => {
debug!("socket: getsockopt");
// getsockopt (sockfd: c_int, level: c_int, optname: c_int, optval: *mut c_void, optlen: *mut socklen_t) -> c_int
let socket: i32 = socket_varargs.get(instance);
let level: i32 = socket_varargs.get(instance);
let name: i32 = socket_varargs.get(instance);
let value: u32 = socket_varargs.get(instance);
let option_len: u32 = socket_varargs.get(instance);
let value_addr = instance.memory_offset_addr(0, value as usize) as *mut c_void;
let option_len_addr =
instance.memory_offset_addr(0, option_len as usize) as *mut socklen_t;
unsafe { getsockopt(socket, level, name, value_addr, option_len_addr) }
}
16 => {
debug!("socket: sendmsg");
// sendmsg (fd: c_int, msg: *const msghdr, flags: c_int) -> ssize_t
let socket: i32 = socket_varargs.get(instance);
let msg: u32 = socket_varargs.get(instance);
let flags: i32 = socket_varargs.get(instance);
let msg_addr = instance.memory_offset_addr(0, msg as usize) as *const msghdr;
unsafe { sendmsg(socket, msg_addr, flags) as i32 }
}
17 => {
debug!("socket: recvmsg");
// recvmsg (fd: c_int, msg: *mut msghdr, flags: c_int) -> ssize_t
let socket: i32 = socket_varargs.get(instance);
let msg: u32 = socket_varargs.get(instance);
let flags: i32 = socket_varargs.get(instance);
let msg_addr = instance.memory_offset_addr(0, msg as usize) as *mut msghdr;
unsafe { recvmsg(socket, msg_addr, flags) as i32 }
}
_ => {
// others
-1
}
}
}
/// uname
// NOTE: Wondering if we should return custom utsname, like Emscripten.
pub extern "C" fn ___syscall122(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall122 (uname)");
let buf: u32 = varargs.get(instance);
debug!("=> buf: {}", buf);
let buf_addr = instance.memory_offset_addr(0, buf as usize) as *mut utsname;
unsafe { uname(buf_addr) }
}
// mmap2
pub extern "C" fn ___syscall192(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall192 (mmap2)");
let addr: i32 = varargs.get(instance);
let len: u32 = varargs.get(instance);
let prot: i32 = varargs.get(instance);
let flags: i32 = varargs.get(instance);
let fd: i32 = varargs.get(instance);
let off: i32 = varargs.get(instance);
debug!(
"=> addr: {}, len: {}, prot: {}, flags: {}, fd: {}, off: {}",
addr, len, prot, flags, fd, off
);
let (memalign, memset) = {
let emscripten_data = &instance.emscripten_data.as_ref().unwrap();
(emscripten_data.memalign, emscripten_data.memset)
};
if fd == -1 {
let ptr = memalign(16384, len, instance);
if ptr == 0 {
return -1;
}
memset(ptr, 0, len, instance);
ptr as _
} else {
-1
}
}
/// lseek
pub extern "C" fn ___syscall140(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> off_t {
debug!("emscripten::___syscall140 (lseek)");
let fd: i32 = varargs.get(instance);
let offset: i64 = varargs.get(instance);
let whence: i32 = varargs.get(instance);
debug!("=> fd: {}, offset: {}, whence = {}", fd, offset, whence);
unsafe { lseek(fd, offset, whence) }
}
/// readv
pub extern "C" fn ___syscall145(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> ssize_t {
debug!("emscripten::___syscall145 (readv)");
// let fd: i32 = varargs.get(instance);
// let iov: u32 = varargs.get(instance);
// let iovcnt: i32 = varargs.get(instance);
// debug!("=> fd: {}, iov: {}, iovcnt = {}", fd, iov, iovcnt);
// let iov_addr = instance.memory_offset_addr(0, iov as usize) as *mut iovec;
// unsafe { readv(fd, iov_addr, iovcnt) }
let fd: i32 = varargs.get(instance);
let iov: i32 = varargs.get(instance);
let iovcnt: i32 = varargs.get(instance);
#[repr(C)]
struct GuestIovec {
iov_base: i32,
iov_len: i32,
}
debug!("=> fd: {}, iov: {}, iovcnt = {}", fd, iov, iovcnt);
let mut ret = 0;
unsafe {
for i in 0..iovcnt {
let guest_iov_addr = instance.memory_offset_addr(0, (iov + i*8) as usize) as *mut GuestIovec;
let iov_base = instance.memory_offset_addr(0, (*guest_iov_addr).iov_base as usize) as *mut c_void;
let iov_len: usize = (*guest_iov_addr).iov_len as _;
// debug!("=> iov_addr: {:?}, {:?}", iov_base, iov_len);
let curr = read(fd, iov_base, iov_len);
if curr < 0 {
return -1
}
ret = ret + curr;
}
// debug!(" => ret: {}", ret);
return ret
}
}
// writev
pub extern "C" fn ___syscall146(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> ssize_t {
debug!("emscripten::___syscall146 (writev)");
let fd: i32 = varargs.get(instance);
let iov: i32 = varargs.get(instance);
let iovcnt: i32 = varargs.get(instance);
#[repr(C)]
struct GuestIovec {
iov_base: i32,
iov_len: i32,
}
debug!("=> fd: {}, iov: {}, iovcnt = {}", fd, iov, iovcnt);
let mut ret = 0;
unsafe {
for i in 0..iovcnt {
let guest_iov_addr = instance.memory_offset_addr(0, (iov + i*8) as usize) as *mut GuestIovec;
let iov_base = instance.memory_offset_addr(0, (*guest_iov_addr).iov_base as usize) as *const c_void;
let iov_len: usize = (*guest_iov_addr).iov_len as _;
// debug!("=> iov_addr: {:?}, {:?}", iov_base, iov_len);
let curr = write(fd, iov_base, iov_len);
if curr < 0 {
return -1
}
ret = ret + curr;
}
// debug!(" => ret: {}", ret);
return ret
}
}
// pread
pub extern "C" fn ___syscall180(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall180 (pread)");
let fd: i32 = varargs.get(instance);
let buf: u32 = varargs.get(instance);
let count: u32 = varargs.get(instance);
{
let zero: u32 = varargs.get(instance);
assert_eq!(zero, 0);
}
let offset: i64 = varargs.get(instance);
let buf_ptr = instance.memory_offset_addr(0, buf as _) as _;
unsafe { pread(fd, buf_ptr, count as _, offset) as _ }
}
// pwrite
pub extern "C" fn ___syscall181(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall181 (pwrite)");
let fd: i32 = varargs.get(instance);
let buf: u32 = varargs.get(instance);
let count: u32 = varargs.get(instance);
{
let zero: u32 = varargs.get(instance);
assert_eq!(zero, 0);
}
let offset: i64 = varargs.get(instance);
let buf_ptr = instance.memory_offset_addr(0, buf as _) as _;
let status = unsafe { pwrite(fd, buf_ptr, count as _, offset) as _ };
debug!(
"=> fd: {}, buf: {}, count: {}, offset: {} = status:{}",
fd, buf, count, offset, status
);
status
}
// stat64
pub extern "C" fn ___syscall195(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall195 (stat64)");
let pathname: u32 = varargs.get(instance);
let buf: u32 = varargs.get(instance);
let pathname_addr = instance.memory_offset_addr(0, pathname as usize) as *const i8;
unsafe {
let mut _stat: stat = std::mem::zeroed();
let ret = stat(pathname_addr, &mut _stat);
debug!("ret: {}", ret);
if ret != 0 {
return ret;
}
copy_stat_into_wasm(instance, buf, &_stat);
}
0
}
// fstat64
pub extern "C" fn ___syscall197(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall197 (fstat64)");
let fd: c_int = varargs.get(instance);
let buf: u32 = varargs.get(instance);
unsafe {
let mut stat = std::mem::zeroed();
let ret = fstat(fd, &mut stat);
debug!("ret: {}", ret);
if ret != 0 {
return ret;
}
copy_stat_into_wasm(instance, buf, &stat);
}
0
}
// /// fcntl64
// pub extern "C" fn ___syscall221(_which: c_int, mut varargs: VarArgs, instance: &mut Instance) -> c_int {
// debug!("emscripten::___syscall221");
// let fd: i32 = varargs.get(instance);
// let cmd: i32 = varargs.get(instance);
// debug!("fd: {}, cmd: {}", fd, cmd);
// unsafe { fcntl(fd, cmd) }
// }
// getgid
pub extern "C" fn ___syscall201() -> gid_t {
debug!("emscripten::___syscall201 (getgid)");
unsafe {
// Maybe fix: Emscripten returns 0 always
getgid()
}
}
// getgid32
pub extern "C" fn ___syscall202() -> gid_t {
debug!("emscripten::___syscall202 (getgid32)");
unsafe {
// Maybe fix: Emscripten returns 0 always
getgid()
}
}
// chown
pub extern "C" fn ___syscall212(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall212 (chown)");
let pathname: u32 = varargs.get(instance);
let owner: u32 = varargs.get(instance);
let group: u32 = varargs.get(instance);
let pathname_addr = instance.memory_offset_addr(0, pathname as usize) as *const i8;
unsafe { chown(pathname_addr, owner, group) }
}
// fcntl64
pub extern "C" fn ___syscall221(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall221 (fcntl64)");
// fcntl64
let _fd: i32 = varargs.get(instance);
let cmd: u32 = varargs.get(instance);
match cmd {
2 => 0,
_ => -1,
}
}
// prlimit64
pub extern "C" fn ___syscall340(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall340 (prlimit64)");
// NOTE: Doesn't really matter. Wasm modules cannot exceed WASM_PAGE_SIZE anyway.
let _pid: i32 = varargs.get(instance);
let _resource: i32 = varargs.get(instance);
let _new_limit: u32 = varargs.get(instance);
let old_limit: u32 = varargs.get(instance);
if old_limit != 0 {
// just report no limits
let buf_ptr = instance.memory_offset_addr(0, old_limit as _) as *mut u8;
let buf = unsafe { slice::from_raw_parts_mut(buf_ptr, 16) };
LittleEndian::write_i32(&mut buf[..], -1); // RLIM_INFINITY
LittleEndian::write_i32(&mut buf[4..], -1); // RLIM_INFINITY
LittleEndian::write_i32(&mut buf[8..], -1); // RLIM_INFINITY
LittleEndian::write_i32(&mut buf[12..], -1); // RLIM_INFINITY
}
0
}
// dup2
pub extern "C" fn ___syscall63(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall63 (dup2)");
let src: i32 = varargs.get(instance);
let dst: i32 = varargs.get(instance);
unsafe { dup2(src, dst) }
}
// newselect
pub extern "C" fn ___syscall142(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall142 (newselect)");
let nfds: i32 = varargs.get(instance);
let readfds: u32 = varargs.get(instance);
let writefds: u32 = varargs.get(instance);
let exceptfds: u32 = varargs.get(instance);
let _timeout: i32 = varargs.get(instance);
assert!(nfds <= 64, "`nfds` must be less than or equal to 64");
assert!(exceptfds == 0, "`exceptfds` is not supporrted");
let readfds_ptr = instance.memory_offset_addr(0, readfds as _) as _;
let writefds_ptr = instance.memory_offset_addr(0, writefds as _) as _;
unsafe { select(nfds, readfds_ptr, writefds_ptr, 0 as _, 0 as _) }
}
// setpgid
pub extern "C" fn ___syscall57(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall57 (setpgid)");
let pid: i32 = varargs.get(instance);
let pgid: i32 = varargs.get(instance);
unsafe {
setpgid(pid, pgid)
}
}

137
src/apis/emscripten/time.rs Normal file
View File

@ -0,0 +1,137 @@
use super::utils::copy_cstr_into_wasm;
use libc::{
c_int,
c_long,
clock_gettime as libc_clock_gettime,
// tm,
localtime,
time,
time_t,
timespec,
};
use std::mem;
use std::time::SystemTime;
use crate::webassembly::Instance;
/// emscripten: _gettimeofday
pub extern "C" fn _gettimeofday(tp: c_int, tz: c_int, instance: &mut Instance) -> c_int {
debug!("emscripten::_gettimeofday {} {}", tp, tz);
#[repr(C)]
struct GuestTimeVal {
tv_sec: i32,
tv_usec: i32,
}
assert!(
tz == 0,
"the timezone argument of `_gettimeofday` must be null"
);
unsafe {
let now = SystemTime::now();
let since_epoch = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
let timeval_struct_ptr = instance.memory_offset_addr(0, tp as _) as *mut GuestTimeVal;
(*timeval_struct_ptr).tv_sec = since_epoch.as_secs() as _;
(*timeval_struct_ptr).tv_usec = since_epoch.subsec_nanos() as _;
}
0
}
/// emscripten: _clock_gettime
pub extern "C" fn _clock_gettime(clk_id: c_int, tp: c_int, instance: &mut Instance) -> c_int {
debug!("emscripten::_clock_gettime {} {}", clk_id, tp);
#[repr(C)]
struct GuestTimeSpec {
tv_sec: i32,
tv_nsec: i32,
}
unsafe {
let mut timespec = timespec {
tv_sec: 0,
tv_nsec: 0,
};
let ret = libc_clock_gettime(clk_id as _, &mut timespec);
if ret != 0 {
return ret;
}
let timespec_struct_ptr = instance.memory_offset_addr(0, tp as _) as *mut GuestTimeSpec;
(*timespec_struct_ptr).tv_sec = timespec.tv_sec as _;
(*timespec_struct_ptr).tv_nsec = timespec.tv_nsec as _;
}
0
}
/// emscripten: _localtime
pub extern "C" fn _localtime(time_p: u32, instance: &mut Instance) -> c_int {
debug!("emscripten::_localtime {}", time_p);
#[repr(C)]
struct GuestTm {
tm_sec: i32,
tm_min: i32,
tm_hour: i32,
tm_mday: i32,
tm_mon: i32,
tm_year: i32,
tm_wday: i32,
tm_yday: i32,
tm_isdst: i32,
tm_gmtoff: c_long,
tm_zone: u32,
}
unsafe {
let time_p_addr = instance.memory_offset_addr(0, time_p as _) as *mut i64;
let tm_struct = &*localtime(time_p_addr);
// Webassembly allocation
let tm_struct_offset = (instance.emscripten_data.as_ref().unwrap().malloc)(
mem::size_of::<GuestTm>() as _,
instance,
);
let tm_struct_ptr = instance.memory_offset_addr(0, tm_struct_offset as _) as *mut GuestTm;
// Initializing
(*tm_struct_ptr).tm_sec = tm_struct.tm_sec;
(*tm_struct_ptr).tm_min = tm_struct.tm_min;
(*tm_struct_ptr).tm_hour = tm_struct.tm_hour;
(*tm_struct_ptr).tm_mday = tm_struct.tm_mday;
(*tm_struct_ptr).tm_mon = tm_struct.tm_mon;
(*tm_struct_ptr).tm_year = tm_struct.tm_year;
(*tm_struct_ptr).tm_wday = tm_struct.tm_wday;
(*tm_struct_ptr).tm_yday = tm_struct.tm_yday;
(*tm_struct_ptr).tm_isdst = tm_struct.tm_isdst;
(*tm_struct_ptr).tm_gmtoff = tm_struct.tm_gmtoff;
(*tm_struct_ptr).tm_zone = copy_cstr_into_wasm(instance, tm_struct.tm_zone);
tm_struct_offset as c_int
}
}
/// emscripten: _time
pub extern "C" fn _time(time_p: u32, instance: &mut Instance) -> time_t {
debug!("emscripten::_time {}", time_p);
unsafe {
let time_p_addr = instance.memory_offset_addr(0, time_p as _) as *mut i64;
time(time_p_addr)
}
}
/// emscripten: _strftime
pub extern "C" fn _strftime(
s_ptr: c_int,
maxsize: u32,
format_ptr: c_int,
tm_ptr: c_int,
_instance: &mut Instance,
) -> time_t {
debug!(
"emscripten::_strftime {} {} {} {}",
s_ptr, maxsize, format_ptr, tm_ptr
);
0
}

View File

@ -1,4 +1,10 @@
use byteorder::{ByteOrder, LittleEndian};
use crate::webassembly::module::Module;
use crate::webassembly::Instance;
use libc::stat;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::slice;
/// We check if a provided module is an Emscripten generated one
pub fn is_emscripten_module(module: &Module) -> bool {
@ -10,6 +16,63 @@ pub fn is_emscripten_module(module: &Module) -> bool {
return false;
}
pub unsafe fn copy_cstr_into_wasm(instance: &mut Instance, cstr: *const c_char) -> u32 {
let s = CStr::from_ptr(cstr).to_str().unwrap();
let space_offset = (instance.emscripten_data.as_ref().unwrap().malloc)(s.len() as _, instance);
let raw_memory = instance.memory_offset_addr(0, space_offset as _) as *mut u8;
let slice = slice::from_raw_parts_mut(raw_memory, s.len());
for (byte, loc) in s.bytes().zip(slice.iter_mut()) {
*loc = byte;
}
space_offset
}
pub unsafe fn copy_terminated_array_of_cstrs(
_instance: &mut Instance,
cstrs: *mut *mut c_char,
) -> u32 {
let total_num = {
let mut ptr = cstrs;
let mut counter = 0;
while !(*ptr).is_null() {
counter += 1;
ptr = ptr.add(1);
}
counter
};
debug!(
"emscripten::copy_terminated_array_of_cstrs::total_num: {}",
total_num
);
0
}
pub unsafe fn copy_stat_into_wasm(instance: &mut Instance, buf: u32, stat: &stat) {
let buf_ptr = instance.memory_offset_addr(0, buf as _) as *mut u8;
let buf = slice::from_raw_parts_mut(buf_ptr, 76);
LittleEndian::write_u32(&mut buf[..], stat.st_dev as _);
LittleEndian::write_u32(&mut buf[4..], 0);
LittleEndian::write_u32(&mut buf[8..], stat.st_ino as _);
LittleEndian::write_u32(&mut buf[12..], stat.st_mode as _);
LittleEndian::write_u32(&mut buf[16..], stat.st_nlink as _);
LittleEndian::write_u32(&mut buf[20..], stat.st_uid);
LittleEndian::write_u32(&mut buf[24..], stat.st_gid);
LittleEndian::write_u32(&mut buf[28..], stat.st_rdev as _);
LittleEndian::write_u32(&mut buf[32..], 0);
LittleEndian::write_u32(&mut buf[36..], stat.st_size as _);
LittleEndian::write_u32(&mut buf[40..], 4096);
LittleEndian::write_u32(&mut buf[44..], stat.st_blocks as _);
LittleEndian::write_u32(&mut buf[48..], stat.st_atime as _);
LittleEndian::write_u32(&mut buf[52..], 0);
LittleEndian::write_u32(&mut buf[56..], stat.st_mtime as _);
LittleEndian::write_u32(&mut buf[60..], 0);
LittleEndian::write_u32(&mut buf[64..], stat.st_ctime as _);
LittleEndian::write_u32(&mut buf[68..], 0);
LittleEndian::write_u32(&mut buf[72..], stat.st_ino as _);
}
#[cfg(test)]
mod tests {
use super::super::generate_emscripten_env;

View File

@ -7,9 +7,9 @@ pub struct VarArgs {
}
impl VarArgs {
pub fn get<T: Copy>(&mut self, instance: &mut Instance) -> T {
pub fn get<T: Sized>(&mut self, instance: &mut Instance) -> T {
let ptr = instance.memory_offset_addr(0, self.pointer as usize);
self.pointer += mem::size_of::<T>() as u32;
unsafe { (ptr as *const T).read() }
}
}
}

View File

@ -1,4 +1,4 @@
pub mod emscripten;
pub mod host;
pub use self::emscripten::{generate_emscripten_env, is_emscripten_module};
pub use self::emscripten::{align_memory, generate_emscripten_env, is_emscripten_module};

View File

@ -61,7 +61,15 @@ fn execute_wasm(wasm_path: PathBuf) -> Result<(), String> {
webassembly::instantiate(wasm_binary, import_object)
.map_err(|err| format!("Can't instantiate the WebAssembly module: {}", err))?;
if apis::is_emscripten_module(&module) {
if apis::emscripten::is_emscripten_module(&module) {
// Emscripten __ATINIT__
if let Some(&webassembly::Export::Function(environ_constructor_index)) = module.info.exports.get("___emscripten_environ_constructor") {
debug!("emscripten::___emscripten_environ_constructor");
let ___emscripten_environ_constructor: extern "C" fn(&webassembly::Instance) =
get_instance_function!(instance, environ_constructor_index);
call_protected!(___emscripten_environ_constructor(&instance)).map_err(|err| format!("{}", err))?;
};
// TODO: We also need to handle TTY.init() and SOCKFS.root = FS.mount(SOCKFS, {}, null)
let func_index = match module.info.exports.get("_main") {
Some(&webassembly::Export::Function(index)) => index,
_ => panic!("_main emscripten function not found"),
@ -69,6 +77,7 @@ fn execute_wasm(wasm_path: PathBuf) -> Result<(), String> {
let main: extern "C" fn(u32, u32, &webassembly::Instance) =
get_instance_function!(instance, func_index);
return call_protected!(main(0, 0, &instance)).map_err(|err| format!("{}", err));
// TODO: We should implement emscripten __ATEXIT__
} else {
let func_index =
instance

View File

@ -12,6 +12,7 @@ extern crate wabt;
extern crate wasmparser;
#[macro_use]
extern crate target_lexicon;
extern crate byteorder;
pub extern crate nix; // re-exported for usage in macros
extern crate rayon;
@ -24,5 +25,5 @@ pub mod common;
pub mod sighandler;
#[cfg(test)]
mod spectests;
pub mod webassembly;
pub mod update;
pub mod webassembly;

View File

@ -21,6 +21,6 @@ macro_rules! include_wast2wasm_bytes {
#[macro_export]
macro_rules! debug {
($fmt:expr) => (if cfg!(debug_assertions) { println!(concat!("Wasmer::", $fmt)) });
($fmt:expr, $($arg:tt)*) => (if cfg!(debug_assertions) { println!(concat!("Wasmer::", $fmt, "\n"), $($arg)*) });
}
($fmt:expr) => (if cfg!(any(debug_assertions, feature="debug")) { println!(concat!("Wasmer::", $fmt)) });
($fmt:expr, $($arg:tt)*) => (if cfg!(any(debug_assertions, feature="debug")) { println!(concat!("Wasmer::", $fmt, "\n"), $($arg)*) });
}

View File

@ -4,7 +4,8 @@
//! are very special, the async signal unsafety of Rust's TLS implementation generally does not affect the correctness here
//! unless you have memory unsafety elsewhere in your code.
use std::cell::UnsafeCell;
use nix::libc::siginfo_t;
use std::cell::{Cell, UnsafeCell};
use std::sync::Once;
extern "C" {
@ -17,6 +18,7 @@ pub static SIGHANDLER_INIT: Once = Once::new();
thread_local! {
pub static SETJMP_BUFFER: UnsafeCell<[::nix::libc::c_int; SETJMP_BUFFER_LEN]> = UnsafeCell::new([0; SETJMP_BUFFER_LEN]);
pub static CAUGHT_ADDRESS: Cell<usize> = Cell::new(0);
}
// We need a macro since the arguments we will provide to the funciton
@ -30,7 +32,7 @@ thread_local! {
macro_rules! call_protected {
($x:expr) => {
unsafe {
use crate::recovery::{setjmp, SETJMP_BUFFER, SIGHANDLER_INIT};
use crate::recovery::{setjmp, CAUGHT_ADDRESS, SETJMP_BUFFER, SIGHANDLER_INIT};
use crate::sighandler::install_sighandler;
use crate::webassembly::ErrorKind;
@ -46,6 +48,8 @@ macro_rules! call_protected {
let signum = setjmp(jmp_buf as *mut ::nix::libc::c_void);
if signum != 0 {
*jmp_buf = prev_jmp_buf;
let addr = CAUGHT_ADDRESS.with(|cell| cell.get());
let signal = match Signal::from_c_int(signum) {
Ok(SIGFPE) => "floating-point exception",
Ok(SIGILL) => "illegal instruction",
@ -54,7 +58,10 @@ macro_rules! call_protected {
Err(_) => "error while getting the Signal",
_ => "unkown trapped signal",
};
Err(ErrorKind::RuntimeError(format!("trap - {}", signal)))
Err(ErrorKind::RuntimeError(format!(
"trap at {:#x} - {}",
addr, signal
)))
} else {
let ret = $x; // TODO: Switch stack?
*jmp_buf = prev_jmp_buf;
@ -65,7 +72,7 @@ macro_rules! call_protected {
}
/// Unwinds to last protected_call.
pub unsafe fn do_unwind(signum: i32) -> ! {
pub unsafe fn do_unwind(signum: i32, siginfo: *mut siginfo_t) -> ! {
// Since do_unwind is only expected to get called from WebAssembly code which doesn't hold any host resources (locks etc.)
// itself, accessing TLS here is safe. In case any other code calls this, it often indicates a memory safety bug and you should
// temporarily disable the signal handlers to debug it.
@ -74,6 +81,9 @@ pub unsafe fn do_unwind(signum: i32) -> ! {
if *jmp_buf == [0; SETJMP_BUFFER_LEN] {
::std::process::abort();
}
// We only target macos at the moment as other ones might not have si_addr field
#[cfg(target_os="macos")]
CAUGHT_ADDRESS.with(|cell| cell.set((*siginfo).si_addr as _));
longjmp(jmp_buf as *mut ::nix::libc::c_void, signum)
}

View File

@ -5,13 +5,14 @@
//! Please read more about this here: https://github.com/CraneStation/wasmtime/issues/15
//! This code is inspired by: https://github.com/pepyakin/wasmtime/commit/625a2b6c0815b21996e111da51b9664feb174622
use super::recovery;
use nix::libc::{c_void, siginfo_t};
use nix::sys::signal::{
sigaction, SaFlags, SigAction, SigHandler, SigSet, SIGBUS, SIGFPE, SIGILL, SIGSEGV,
};
pub unsafe fn install_sighandler() {
let sa = SigAction::new(
SigHandler::Handler(signal_trap_handler),
SigHandler::SigAction(signal_trap_handler),
SaFlags::SA_ONSTACK,
SigSet::empty(),
);
@ -21,8 +22,12 @@ pub unsafe fn install_sighandler() {
sigaction(SIGBUS, &sa).unwrap();
}
extern "C" fn signal_trap_handler(signum: ::nix::libc::c_int) {
extern "C" fn signal_trap_handler(
signum: ::nix::libc::c_int,
siginfo: *mut siginfo_t,
_ucontext: *mut c_void,
) {
unsafe {
recovery::do_unwind(signum);
recovery::do_unwind(signum, siginfo);
}
}

View File

@ -10,8 +10,8 @@ static GLOBAL_I32: i32 = 666;
pub fn spectest_importobject<'a, 'b>() -> ImportObject<&'a str, &'b str> {
let mut import_object = ImportObject::new();
import_object.set("spectest", "print_i32", ImportValue::Func(print_i32 as *const u8));
import_object.set("spectest", "print", ImportValue::Func(print as *const u8));
import_object.set("spectest", "print_i32", ImportValue::Func(print_i32 as _));
import_object.set("spectest", "print", ImportValue::Func(print as _));
import_object.set("spectest", "global_i32", ImportValue::Global(GLOBAL_I32 as _));
import_object.set("spectest", "table", ImportValue::Table(vec![0; 30]));
return import_object;

View File

@ -1,17 +1,21 @@
//! When wasmer self-update is executed, this is what gets executed
use std::process::{Command, Stdio};
use std::io;
pub fn self_update() {
println!("Fetching latest installer");
let cmd = Command::new("curl").arg("https://get.wasmer.io").arg("-sSfL")
.stdout(Stdio::piped()).spawn().unwrap();
let cmd = Command::new("curl")
.arg("https://get.wasmer.io")
.arg("-sSfL")
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut the_process = Command::new("sh")
.stdin(cmd.stdout.unwrap())
.stdout(Stdio::inherit())
.spawn()
.ok().expect("Failed to execute.");
let mut the_process = Command::new("sh")
.stdin(cmd.stdout.unwrap())
.stdout(Stdio::inherit())
.spawn()
.ok()
.expect("Failed to execute.");
the_process.wait();
the_process.wait().unwrap();
}

View File

@ -125,10 +125,10 @@ mod tests {
fn test_import_object() {
fn x() {}
let mut import_object = ImportObject::new();
import_object.set("abc", "def", ImportValue::Func(x as *const u8));
import_object.set("abc", "def", ImportValue::Func(x as _));
assert_eq!(
*import_object.get(&"abc", &"def").unwrap(),
ImportValue::Func(x as *const u8)
ImportValue::Func(x as _)
);
}
}

View File

@ -18,8 +18,8 @@ use std::iter::FromIterator;
use std::iter::Iterator;
use std::mem::size_of;
use std::ptr::write_unaligned;
use std::slice;
use std::sync::Arc;
use std::{fmt, mem, slice};
use super::super::common::slice::{BoundedSlice, UncheckedSlice};
use super::errors::ErrorKind;
@ -67,10 +67,25 @@ fn get_function_addr(
func_pointer
}
pub struct EmscriptenData {
pub malloc: extern "C" fn(i32, &mut Instance) -> u32,
pub free: extern "C" fn(i32, &mut Instance),
pub memalign: extern "C" fn (u32, u32, &mut Instance) -> u32,
pub memset: extern "C" fn(u32, i32, u32, &mut Instance) -> u32,
}
impl fmt::Debug for EmscriptenData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("EmscriptenData")
.field("malloc", &(self.malloc as usize))
.field("free", &(self.free as usize))
.finish()
}
}
/// An Instance of a WebAssembly module
/// NOTE: There is an assumption that data_pointers is always the
/// first field
#[repr(C)]
#[derive(Debug)]
#[repr(C)]
pub struct Instance {
@ -98,12 +113,12 @@ pub struct Instance {
pub start_func: Option<FuncIndex>,
// Region start memory location
// code_base: *const (),
pub emscripten_data: Option<EmscriptenData>,
}
/// Contains pointers to data (heaps, globals, tables) needed
/// by Cranelift.
/// NOTE: Rearranging the fields will break the memory arrangement model
#[repr(C)]
#[derive(Debug)]
#[repr(C)]
pub struct DataPointers {
@ -122,13 +137,16 @@ pub struct InstanceOptions {
pub mock_missing_imports: bool,
pub mock_missing_globals: bool,
pub mock_missing_tables: bool,
pub use_emscripten: bool,
pub isa: Box<TargetIsa>,
}
extern "C" fn mock_fn() -> i32 {
println!("CALLING MOCKED FUNC");
return 0;
}
#[allow(dead_code)]
struct CompiledFunction {
code_buf: Vec<u8>,
reloc_sink: RelocSink,
@ -203,7 +221,7 @@ impl Instance {
"The import {}.{} is not provided, therefore will be mocked.",
module, field
);
&(mock_fn as *const u8)
&(mock_fn as _)
} else {
return Err(ErrorKind::LinkError(format!(
"Imported function {}.{} was not provided in the import_functions",
@ -228,8 +246,7 @@ impl Instance {
// let r = *Arc::from_raw(isa_ptr);
compile_function(&*options.isa, function_body).unwrap()
// unimplemented!()
})
.collect();
}).collect();
for compiled_func in compiled_funcs.into_iter() {
let CompiledFunction {
@ -446,9 +463,18 @@ impl Instance {
// Get memories in module
for memory in &module.info.memories {
let memory = memory.entity;
let v =
LinearMemory::new(memory.pages_count as u32, memory.maximum.map(|m| m as u32));
memories.push(v);
// If we use emscripten, we set a fixed initial and maximum
debug!("Instance - init memory ({}, {:?})", memory.pages_count, memory.maximum);
let memory = if options.use_emscripten {
// We use MAX_PAGES, so at the end the result is:
// (initial * LinearMemory::PAGE_SIZE) == LinearMemory::DEFAULT_HEAP_SIZE
// However, it should be: (initial * LinearMemory::PAGE_SIZE) == 16777216
LinearMemory::new(LinearMemory::MAX_PAGES as u32, None)
}
else {
LinearMemory::new(memory.pages_count as u32, memory.maximum.map(|m| m as u32))
};
memories.push(memory);
}
for init in &module.info.data_initializers {
@ -464,6 +490,11 @@ impl Instance {
let to_init = &mut mem[offset..offset + init.data.len()];
to_init.copy_from_slice(&init.data);
}
if options.use_emscripten {
debug!("emscripten::setup memory");
crate::apis::emscripten::emscripten_set_up_memory(&mut memories[0]);
debug!("emscripten::finish setup memory");
}
}
let start_func: Option<FuncIndex> =
@ -475,7 +506,6 @@ impl Instance {
_ => None,
});
// TODO: Refactor repetitive code
let tables_pointer: Vec<BoundedSlice<usize>> =
tables.iter().map(|table| table[..].into()).collect();
let memories_pointer: Vec<BoundedSlice<u8>> = memories
@ -490,7 +520,33 @@ impl Instance {
tables: tables_pointer[..].into(),
};
// let mem = data_pointers.memories;
let emscripten_data = if options.use_emscripten {
unsafe {
debug!("emscripten::initiating data");
let malloc_export = module.info.exports.get("_malloc");
let free_export = module.info.exports.get("_free");
let memalign_export = module.info.exports.get("_memalign");
let memset_export = module.info.exports.get("_memset");
if let (Some(Export::Function(malloc_index)), Some(Export::Function(free_index)), Some(Export::Function(memalign_index)), Some(Export::Function(memset_index))) = (malloc_export, free_export, memalign_export, memset_export) {
let malloc_addr = get_function_addr(&malloc_index, &import_functions, &functions);
let free_addr = get_function_addr(&free_index, &import_functions, &functions);
let memalign_addr = get_function_addr(&memalign_index, &import_functions, &functions);
let memset_addr = get_function_addr(&memset_index, &import_functions, &functions);
Some(EmscriptenData {
malloc: mem::transmute(malloc_addr),
free: mem::transmute(free_addr),
memalign: mem::transmute(memalign_addr),
memset: mem::transmute(memset_addr),
})
} else {
None
}
}
} else {
None
};
Ok(Instance {
data_pointers,
@ -500,6 +556,7 @@ impl Instance {
functions,
import_functions,
start_func,
emscripten_data,
})
}

View File

@ -3,20 +3,17 @@
//! webassembly::Instance.
//! A memory created by Rust or in WebAssembly code will be accessible and
//! mutable from both Rust and WebAssembly.
use nix::sys::mman::{mmap, MapFlags, ProtFlags};
use nix::libc::{c_void, mprotect, PROT_READ, PROT_WRITE};
use std::slice;
use nix::sys::mman::{mmap, MapFlags, ProtFlags};
use std::ops::{Deref, DerefMut};
const PAGE_SIZE: u32 = 65536;
const MAX_PAGES: u32 = 65536;
use std::slice;
/// A linear memory instance.
//
#[derive(Debug)]
pub struct LinearMemory {
base: *mut c_void, // The size will always be `LinearMemory::DEFAULT_SIZE`
current: u32, // current number of wasm pages
current: u32, // current number of wasm pages
// The maximum size the WebAssembly Memory is allowed to grow
// to, in units of WebAssembly pages. When present, the maximum
// parameter acts as a hint to the engine to reserve memory up
@ -28,6 +25,8 @@ pub struct LinearMemory {
/// It holds the raw bytes of memory accessed by a WebAssembly Instance
impl LinearMemory {
pub const PAGE_SIZE: u32 = 65536;
pub const MAX_PAGES: u32 = 65536;
pub const WASM_PAGE_SIZE: usize = 1 << 16; // 64 KiB
pub const DEFAULT_HEAP_SIZE: usize = 1 << 32; // 4 GiB
pub const DEFAULT_GUARD_SIZE: usize = 1 << 31; // 2 GiB
@ -37,8 +36,8 @@ impl LinearMemory {
///
/// `maximum` cannot be set to more than `65536` pages.
pub fn new(initial: u32, maximum: Option<u32>) -> Self {
assert!(initial <= MAX_PAGES);
assert!(maximum.is_none() || maximum.unwrap() <= MAX_PAGES);
assert!(initial <= Self::MAX_PAGES);
assert!(maximum.is_none() || maximum.unwrap() <= Self::MAX_PAGES);
debug!(
"Instantiate LinearMemory(initial={:?}, maximum={:?})",
initial, maximum
@ -50,23 +49,29 @@ impl LinearMemory {
0 as _,
LinearMemory::DEFAULT_SIZE,
ProtFlags::PROT_NONE,
MapFlags::MAP_ANON | MapFlags::MAP_SHARED,
MapFlags::MAP_ANON | MapFlags::MAP_PRIVATE,
-1,
0,
).unwrap()
};
if initial > 0 {
assert_eq!(unsafe {
mprotect(
base,
(initial * PAGE_SIZE) as _,
PROT_READ | PROT_WRITE,
)
}, 0);
assert_eq!(
unsafe {
mprotect(
base,
initial as usize * Self::PAGE_SIZE as usize,
// Self::DEFAULT_HEAP_SIZE,
PROT_READ | PROT_WRITE,
)
},
0
);
}
debug!("LinearMemory instantiated");
debug!(" - usable: {:#x}..{:#x}", base as usize, (base as usize) + LinearMemory::DEFAULT_HEAP_SIZE);
debug!(" - guard: {:#x}..{:#x}", (base as usize) + LinearMemory::DEFAULT_HEAP_SIZE, (base as usize) + LinearMemory::DEFAULT_SIZE);
Self {
base,
current: initial,
@ -81,7 +86,7 @@ impl LinearMemory {
/// Returns a number of allocated wasm pages.
pub fn current_size(&self) -> usize {
(self.current * PAGE_SIZE) as _
self.current as usize * Self::PAGE_SIZE as usize
}
pub fn current_pages(&self) -> u32 {
@ -117,19 +122,22 @@ impl LinearMemory {
// Wasm linear memories are never allowed to grow beyond what is
// indexable. If the memory has no maximum, enforce the greatest
// limit here.
} else if new_pages >= MAX_PAGES {
} else if new_pages >= Self::MAX_PAGES {
return None;
}
let prev_bytes = (prev_pages * PAGE_SIZE) as usize;
let new_bytes = (new_pages * PAGE_SIZE) as usize;
let prev_bytes = (prev_pages * Self::PAGE_SIZE) as usize;
let new_bytes = (new_pages * Self::PAGE_SIZE) as usize;
unsafe {
assert_eq!(mprotect(
self.base.add(prev_bytes),
new_bytes - prev_bytes,
PROT_READ | PROT_WRITE,
), 0);
assert_eq!(
mprotect(
self.base.add(prev_bytes),
new_bytes - prev_bytes,
PROT_READ | PROT_WRITE,
),
0
);
}
self.current = new_pages;
@ -142,11 +150,11 @@ impl LinearMemory {
let end = start + size as usize;
let slice: &[u8] = &*self;
// if end <= self.mapped_size() {
Some(&slice[start..end])
// } else {
// None
// }
if end <= self.current_size() as usize {
Some(&slice[start..end])
} else {
None
}
}
}
@ -157,20 +165,15 @@ impl PartialEq for LinearMemory {
}
}
impl Deref for LinearMemory {
type Target = [u8];
fn deref(&self) -> &[u8] {
unsafe {
slice::from_raw_parts(self.base as _, (self.current * PAGE_SIZE) as _)
}
unsafe { slice::from_raw_parts(self.base as _, self.current as usize * Self::PAGE_SIZE as usize) }
}
}
impl DerefMut for LinearMemory {
fn deref_mut(&mut self) -> &mut [u8] {
unsafe {
slice::from_raw_parts_mut(self.base as _, (self.current * PAGE_SIZE) as _)
}
unsafe { slice::from_raw_parts_mut(self.base as _, self.current as usize * Self::PAGE_SIZE as usize) }
}
}
}

View File

@ -7,7 +7,10 @@ pub mod module;
pub mod relocation;
pub mod utils;
use cranelift_codegen::{isa, settings::{self, Configurable}};
use cranelift_codegen::{
isa,
settings::{self, Configurable},
};
use std::panic;
use std::str::FromStr;
use target_lexicon;
@ -19,6 +22,7 @@ pub use self::import_object::{ImportObject, ImportValue};
pub use self::instance::{Instance, InstanceOptions};
pub use self::memory::LinearMemory;
pub use self::module::{Export, Module, ModuleInfo};
use crate::apis::is_emscripten_module;
pub struct ResultObject {
/// A webassembly::Module object representing the compiled WebAssembly module.
@ -47,11 +51,9 @@ pub fn instantiate(
buffer_source: Vec<u8>,
import_object: ImportObject<&str, &str>,
) -> Result<ResultObject, ErrorKind> {
let flags = {
let mut builder = settings::builder();
builder.set("opt_level", "best")
.unwrap();
builder.set("opt_level", "best").unwrap();
let flags = settings::Flags::new(builder);
debug_assert_eq!(flags.opt_level(), settings::OptLevel::Best);
@ -68,6 +70,7 @@ pub fn instantiate(
mock_missing_imports: true,
mock_missing_globals: true,
mock_missing_tables: true,
use_emscripten: is_emscripten_module(&module),
isa: isa,
},
)?;