Isolated emscripten in new lib

This commit is contained in:
Syrus
2019-01-10 21:37:59 -08:00
parent ab0dae6d0c
commit de459fa5bd
990 changed files with 136 additions and 857 deletions

View File

@ -0,0 +1,532 @@
## HOST APIS
#### EMSCRIPTEN APIS
###### PROCESS
- **\_abort** ✅     [:top:](#host-apis)
```rust
fn _abort()
```
- **abort** ✅ 🔥     [:top:](#host-apis)
```rust
fn abort(message: u32, instance: &mut Instance)
```
- **abort_on_cannot_grow_memory** ✅     [:top:](#host-apis)
```rust
fn abort_on_cannot_grow_memory()
```
###### TIMING
- **\_clock_gettime**     [:top:](#host-apis)
```rust
```
###### ENVIRONMENT
- **\_getenv** ✅     [:top:](#host-apis)
```rust
fn _getenv(name: c_int, instance: &mut Instance)
```
- **\_putenv** ✅     [:top:](#host-apis)
```rust
fn _putenv(name: c_int, instance: &mut Instance)
```
- **\_setenv** ✅     [:top:](#host-apis)
```rust
fn _setenv(name: c_int, value: c_int, overwrite: c_int, instance: &mut Instance
```
- **\_unsetenv** ✅     [:top:](#host-apis)
```rust
fn _unsetenv(name: c_int, instance: &mut Instance)
```
###### THREAD
- **\_pthread_getspecific**     [:top:](#host-apis)
```rust
```
- **\_pthread_key_create**     [:top:](#host-apis)
```rust
```
- **\_pthread_setspecific**     [:top:](#host-apis)
```rust
```
- **\_\_\_lock**     [:top:](#host-apis)
```rust
```
- **\_\_\_unlock**     [:top:](#host-apis)
```rust
```
###### MEMORY
- **\_emscripten_memcpy_big** ✅ 🔥     [:top:](#host-apis)
```rust
fn _emscripten_memcpy_big(dest: u32, src: u32, len: u32, instance: &mut Instance) -> u32
```
- **enlarge_memory** ✅     [:top:](#host-apis)
```rust
fn enlarge_memory()
```
- **get_total_memory** ✅     [:top:](#host-apis)
```rust
fn get_total_memory(instance: &mut Instance) -> u32
```
###### TIMING
- **\_clock_gettime**     [:top:](#host-apis)
```rust
```
###### STATUS
- **\_\_\_set_err_no**     [:top:](#host-apis)
```rust
```
---
#### EMSCRIPTEN SYSCALLS
- **access** (\_\_\_syscall33)     [:top:](#host-apis)
```rust
```
- **acct** (\_\_\_syscall51)     [:top:](#host-apis)
```rust
```
- **chdir** (\_\_\_syscall12)     [:top:](#host-apis)
```rust
```
- **chmod** (\_\_\_syscall15)     [:top:](#host-apis)
```rust
```
- **chown** (\_\_\_syscall212)     [:top:](#host-apis)
```rust
```
- **clock_nanosleep** (\_\_\_syscall265)     [:top:](#host-apis)
```rust
```
- **close** (\_\_\_syscall6) ✅ ❗️     [:top:](#host-apis)
```rust
fn close(fd: c_int) -> c_int
```
- **dup** (\_\_\_syscall330)     [:top:](#host-apis)
```rust
```
- **dup** (\_\_\_syscall41)     [:top:](#host-apis)
```rust
```
- **dup2** (\_\_\_syscall63)     [:top:](#host-apis)
```rust
```
- **exit** (\_\_\_syscall1) ✅     [:top:](#host-apis)
```rust
fn exit(status: c_int)
```
- **faccessat** (\_\_\_syscall307)     [:top:](#host-apis)
```rust
```
- **fadvise** (\_\_\_syscall272)     [:top:](#host-apis)
```rust
```
- **fallocate** (\_\_\_syscall324)     [:top:](#host-apis)
```rust
```
- **fchdir** (\_\_\_syscall133)     [:top:](#host-apis)
```rust
```
- **fchmod** (\_\_\_syscall94)     [:top:](#host-apis)
```rust
```
- **fchmodat** (\_\_\_syscall306)     [:top:](#host-apis)
```rust
```
- **fchown** (\_\_\_syscall207)     [:top:](#host-apis)
```rust
```
- **fchownat** (\_\_\_syscall298)     [:top:](#host-apis)
```rust
```
- **fcntl** (\_\_\_syscall221)     [:top:](#host-apis)
```rust
```
- **fdatasync** (\_\_\_syscall148)     [:top:](#host-apis)
```rust
```
- **fstat** (\_\_\_syscall197)     [:top:](#host-apis)
```rust
```
- **fstatat** (\_\_\_syscall300)     [:top:](#host-apis)
```rust
```
- **fstatfs** (\_\_\_syscall269)     [:top:](#host-apis)
```rust
```
- **fsync** (\_\_\_syscall118)     [:top:](#host-apis)
```rust
```
- **ftruncate** (\_\_\_syscall194)     [:top:](#host-apis)
```rust
```
- **futimesat** (\_\_\_syscall299)     [:top:](#host-apis)
```rust
```
- **getcwd** (\_\_\_syscall183)     [:top:](#host-apis)
```rust
```
- **getdents** (\_\_\_syscall220)     [:top:](#host-apis)
```rust
```
- **getgid** (\_\_\_syscall202)     [:top:](#host-apis)
```rust
```
- **getgroups** (\_\_\_syscall205)     [:top:](#host-apis)
```rust
```
- **getpgid** (\_\_\_syscall132)     [:top:](#host-apis)
```rust
```
- **getpgrp** (\_\_\_syscall65)     [:top:](#host-apis)
```rust
```
- **getpid** (\_\_\_syscall20)     [:top:](#host-apis)
```rust
```
- **getppid** (\_\_\_syscall64)     [:top:](#host-apis)
```rust
```
- **getpriority** (\_\_\_syscall96)     [:top:](#host-apis)
```rust
```
- **getresgid** (\_\_\_syscall211)     [:top:](#host-apis)
```rust
```
- **getrusage** (\_\_\_syscall77)     [:top:](#host-apis)
```rust
```
- **getsid** (\_\_\_syscall147)     [:top:](#host-apis)
```rust
```
- **ioctl** (\_\_\_syscall54)     [:top:](#host-apis)
```rust
```
- **lchown** (\_\_\_syscall198)     [:top:](#host-apis)
```rust
```
- **link** (\_\_\_syscall9)     [:top:](#host-apis)
```rust
```
- **linkat** (\_\_\_syscall303)     [:top:](#host-apis)
```rust
```
- **llseek** (\_\_\_syscall140)     [:top:](#host-apis)
```rust
```
- **lstat** (\_\_\_syscall196)     [:top:](#host-apis)
```rust
```
- **madvise** (\_\_\_syscall219)     [:top:](#host-apis)
```rust
```
- **mincore** (\_\_\_syscall218)     [:top:](#host-apis)
```rust
```
- **mkdir** (\_\_\_syscall39)     [:top:](#host-apis)
```rust
```
- **mkdirat** (\_\_\_syscall296)     [:top:](#host-apis)
```rust
```
- **mknod** (\_\_\_syscall14)     [:top:](#host-apis)
```rust
```
- **mknodat** (\_\_\_syscall297)     [:top:](#host-apis)
```rust
```
- **mmap** (\_\_\_syscall192)     [:top:](#host-apis)
```rust
```
- **mprotect** (\_\_\_syscall125)     [:top:](#host-apis)
```rust
```
- **mremap** (\_\_\_syscall163)     [:top:](#host-apis)
```rust
```
- **msync** (\_\_\_syscall144)     [:top:](#host-apis)
```rust
```
- **munlockall** (\_\_\_syscall153)     [:top:](#host-apis)
```rust
```
- **munmap** (\_\_\_syscall91)     [:top:](#host-apis)
```rust
```
- **newselect** (\_\_\_syscall142)     [:top:](#host-apis)
```rust
```
- **nice** (\_\_\_syscall34)     [:top:](#host-apis)
```rust
```
- **open** (\_\_\_syscall5) ✅ ❗️ 🔥     [:top:](#host-apis)
```rust
fn open(path: u32, flags: c_int, mode: c_int, instance: &mut Instance) -> c_int
```
- **openat** (\_\_\_syscall295)     [:top:](#host-apis)
```rust
```
- **pause** (\_\_\_syscall29)     [:top:](#host-apis)
```rust
```
- **pipe** (\_\_\_syscall331)     [:top:](#host-apis)
```rust
```
- **pipe** (\_\_\_syscall42)     [:top:](#host-apis)
```rust
```
- **poll** (\_\_\_syscall168)     [:top:](#host-apis)
```rust
```
- **pread** (\_\_\_syscall180)     [:top:](#host-apis)
```rust
```
- **preadv** (\_\_\_syscall333)     [:top:](#host-apis)
```rust
```
- **prlimit** (\_\_\_syscall340)     [:top:](#host-apis)
```rust
```
- **pselect** (\_\_\_syscall308)     [:top:](#host-apis)
```rust
```
- **pwrite** (\_\_\_syscall181)     [:top:](#host-apis)
```rust
```
- **pwritev** (\_\_\_syscall334)     [:top:](#host-apis)
```rust
```
- **read** (\_\_\_syscall3) ✅ ❗️     [:top:](#host-apis)
```rust
fn read(fd: c_int, buf: u32, count: size_t, instance: &mut Instance) -> ssize_t
```
- **readlink** (\_\_\_syscall85)     [:top:](#host-apis)
```rust
```
- **readlinkat** (\_\_\_syscall305)     [:top:](#host-apis)
```rust
```
- **readv** (\_\_\_syscall145)     [:top:](#host-apis)
```rust
```
- **recvmmsg** (\_\_\_syscall337)     [:top:](#host-apis)
```rust
```
- **rename** (\_\_\_syscall38)     [:top:](#host-apis)
```rust
```
- **renameat** (\_\_\_syscall302)     [:top:](#host-apis)
```rust
```
- **rmdir** (\_\_\_syscall40)     [:top:](#host-apis)
```rust
```
- **rt_sigqueueinfo** (\_\_\_syscall178)     [:top:](#host-apis)
```rust
```
- **sendmmsg** (\_\_\_syscall345)     [:top:](#host-apis)
```rust
```
- **setdomainname** (\_\_\_syscall121)     [:top:](#host-apis)
```rust
```
- **setgid** (\_\_\_syscall214)     [:top:](#host-apis)
```rust
```
- **setitimer** (\_\_\_syscall104)     [:top:](#host-apis)
```rust
```
- **setpgid** (\_\_\_syscall57)     [:top:](#host-apis)
```rust
```
- **setpriority** (\_\_\_syscall97)     [:top:](#host-apis)
```rust
```
- **setresgid** (\_\_\_syscall210)     [:top:](#host-apis)
```rust
```
- **setrlimit** (\_\_\_syscall75)     [:top:](#host-apis)
```rust
```
- **setsid** (\_\_\_syscall66)     [:top:](#host-apis)
```rust
```
- **socketcall** (\_\_\_syscall102)     [:top:](#host-apis)
```rust
```
- **stat** (\_\_\_syscall195)     [:top:](#host-apis)
```rust
```
- **statfs** (\_\_\_syscall268)     [:top:](#host-apis)
```rust
```
- **symlink** (\_\_\_syscall83)     [:top:](#host-apis)
```rust
```
- **symlinkat** (\_\_\_syscall304)     [:top:](#host-apis)
```rust
```
- **sync** (\_\_\_syscall36)     [:top:](#host-apis)
```rust
```
- **truncate** (\_\_\_syscall193)     [:top:](#host-apis)
```rust
```
- **ugetrlimit** (\_\_\_syscall191)     [:top:](#host-apis)
```rust
```
- **umask** (\_\_\_syscall60)     [:top:](#host-apis)
```rust
```
- **uname** (\_\_\_syscall122)     [:top:](#host-apis)
```rust
```
- **unlink** (\_\_\_syscall10)     [:top:](#host-apis)
```rust
```
- **unlinkat** (\_\_\_syscall301)     [:top:](#host-apis)
```rust
```
- **utimensat** (\_\_\_syscall320)     [:top:](#host-apis)
```rust
```
- **wait** (\_\_\_syscall114)     [:top:](#host-apis)
```rust
```
- **write** (\_\_\_syscall4)     [:top:](#host-apis)
```rust
```
- **writev** (\_\_\_syscall146)     [:top:](#host-apis)
```rust
```
### LEGEND     [:top:](#host-apis)
✅ - Implemented
❗️ - Elevated privilege
🔥 - Possible memory access violation
📥 - Access to external memory
📝 - External write to internal memory

218
lib/emscripten/src/env.rs Normal file
View File

@ -0,0 +1,218 @@
/// NOTE: These syscalls only support wasm_32 for now because they take u32 offset
use libc::{
c_int, c_long, getenv, getgrnam as libc_getgrnam, getpwnam as libc_getpwnam, putenv, setenv,
sysconf, unsetenv,
};
use std::ffi::CStr;
use std::mem;
use std::os::raw::c_char;
use super::utils::{allocate_on_stack, copy_cstr_into_wasm, copy_terminated_array_of_cstrs};
use super::EmscriptenData;
use wasmer_runtime::{types::Value, Instance};
//impl Instance {
// pub fn memory_offset_addr(&self, index: usize, offset: usize) -> *const usize {
// unimplemented!("TODO replace this stub")
// }
//
// pub fn emscripten_data(&self) -> &'static mut Option<EmscriptenData> {
// unimplemented!("TODO replace this stub")
// }
//}
// #[no_mangle]
/// emscripten: _getenv // (name: *const char) -> *const c_char;
pub extern "C" fn _getenv(name: c_int, instance: &mut Instance) -> u32 {
debug!("emscripten::_getenv");
let name_addr = instance.memory_offset_addr(0, name as usize) as *const c_char;
debug!("=> name({:?})", unsafe { CStr::from_ptr(name_addr) });
let c_str = unsafe { getenv(name_addr) };
if c_str.is_null() {
return 0;
}
unsafe { copy_cstr_into_wasm(instance, c_str) }
}
/// emscripten: _setenv // (name: *const char, name: *const value, overwrite: int);
pub extern "C" fn _setenv(name: c_int, value: c_int, overwrite: c_int, instance: &mut Instance) {
debug!("emscripten::_setenv");
let name_addr = instance.memory_offset_addr(0, name as usize) as *const c_char;
let value_addr = instance.memory_offset_addr(0, value as usize) as *const c_char;
debug!("=> name({:?})", unsafe { CStr::from_ptr(name_addr) });
debug!("=> value({:?})", unsafe { CStr::from_ptr(value_addr) });
unsafe { setenv(name_addr, value_addr, overwrite) };
}
/// emscripten: _putenv // (name: *const char);
pub extern "C" fn _putenv(name: c_int, instance: &mut Instance) {
debug!("emscripten::_putenv");
let name_addr = instance.memory_offset_addr(0, name as usize) as *const c_char;
debug!("=> name({:?})", unsafe { CStr::from_ptr(name_addr) });
unsafe { putenv(name_addr as _) };
}
/// emscripten: _unsetenv // (name: *const char);
pub extern "C" fn _unsetenv(name: c_int, instance: &mut Instance) {
debug!("emscripten::_unsetenv");
let name_addr = instance.memory_offset_addr(0, name as usize) as *const c_char;
debug!("=> name({:?})", unsafe { CStr::from_ptr(name_addr) });
unsafe { unsetenv(name_addr) };
}
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 = call_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 = call_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 fn call_malloc(size: i32, instance: &mut Instance) -> u32 {
let ret = instance
.call("_malloc", &[Value::I32(size)])
.expect("_malloc call failed");
if let Some(Value::I32(ptr)) = ret {
ptr as u32
} else {
panic!("unexpected value from _malloc: {:?}", ret);
}
}
pub fn call_memalign(alignment: u32, size: u32, instance: &mut Instance) -> u32 {
let ret = instance
.call(
"_memalign",
&[Value::I32(alignment as i32), Value::I32(size as i32)],
)
.expect("_memalign call failed");
if let Some(Value::I32(res)) = ret {
res as u32
} else {
panic!("unexpected value from _memalign {:?}", ret);
}
}
pub fn call_memset(pointer: u32, value: i32, size: u32, instance: &mut Instance) -> u32 {
let ret = instance
.call(
"_memset",
&[
Value::I32(pointer as i32),
Value::I32(value),
Value::I32(size as i32),
],
)
.expect("_memset call failed");
if let Some(Value::I32(res)) = ret {
res as u32
} else {
panic!("unexpected value from _memset {:?}", ret);
}
}
pub extern "C" fn _getpagesize() -> u32 {
debug!("emscripten::_getpagesize");
16384
}
pub extern "C" fn ___build_environment(environ: c_int, instance: &mut Instance) {
debug!("emscripten::___build_environment {}", environ);
const MAX_ENV_VALUES: u32 = 64;
const TOTAL_ENV_SIZE: u32 = 1024;
let mut environment = instance.memory_offset_addr(0, environ as _) as *mut c_int;
unsafe {
let (pool_offset, pool_slice): (u32, &mut [u8]) =
allocate_on_stack(TOTAL_ENV_SIZE as u32, instance);
let (env_offset, env_slice): (u32, &mut [u8]) =
allocate_on_stack((MAX_ENV_VALUES * 4) as u32, instance);
let mut env_ptr = instance.memory_offset_addr(0, env_offset as _) as *mut c_int;
let mut pool_ptr = instance.memory_offset_addr(0, pool_offset as _) as *mut c_int;
*env_ptr = pool_offset as i32;
*environment = env_offset as i32;
// *env_ptr = 0;
};
// unsafe {
// *env_ptr = 0;
// };
}
pub extern "C" fn _sysconf(name: c_int, _instance: &mut Instance) -> c_long {
debug!("emscripten::_sysconf {}", name);
// TODO: Implement like emscripten expects regarding memory/page size
unsafe { sysconf(name) }
}

265
lib/emscripten/src/errno.rs Normal file
View File

@ -0,0 +1,265 @@
// use std::collections::HashMap;
pub extern "C" fn ___seterrno(value: i32) -> i32 {
debug!("emscripten::___seterrno {}", value);
// 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,16 @@
use super::process::_abort;
use super::env;
use wasmer_runtime::Instance;
/// emscripten: ___cxa_allocate_exception
pub extern "C" fn ___cxa_allocate_exception(size: u32, instance: &mut Instance) -> u32 {
debug!("emscripten::___cxa_allocate_exception");
env::call_malloc(size as _, instance)
}
/// emscripten: ___cxa_throw
/// TODO: We don't have support for exceptions yet
pub extern "C" fn ___cxa_throw(ptr: u32, ty: u32, destructor: u32, instance: &mut Instance) {
debug!("emscripten::___cxa_throw");
_abort();
}

15
lib/emscripten/src/io.rs Normal file
View File

@ -0,0 +1,15 @@
use libc::printf as _printf;
use wasmer_runtime::Instance;
/// putchar
pub use libc::putchar;
/// printf
pub extern "C" fn printf(memory_offset: i32, extra: i32, instance: &Instance) -> i32 {
debug!("emscripten::printf {}, {}", memory_offset, extra);
unsafe {
let addr = instance.memory_offset_addr(0, memory_offset as _) as _;
_printf(addr, extra)
}
}

43
lib/emscripten/src/jmp.rs Normal file
View File

@ -0,0 +1,43 @@
use wasmer_runtime::Instance;
use libc::{c_int, c_void};
use std::cell::UnsafeCell;
/// setjmp
pub extern "C" fn __setjmp(env_addr: u32, instance: &mut Instance) -> c_int {
debug!("emscripten::__setjmp (setjmp)");
unimplemented!()
// unsafe {
// // Rather than using the env as the holder of the jump buffer pointer,
// // we use the environment address to store the index relative to jumps
// // so the address of the jump it's outside the wasm memory itself.
// let jump_index = instance.memory_offset_addr(0, env_addr as usize) as *mut i8;
// // We create the jump buffer outside of the wasm memory
// let jump_buf: UnsafeCell<[c_int; 27]> = UnsafeCell::new([0; 27]);
// let mut jumps = &mut instance.emscripten_data().as_mut().unwrap().jumps;
// let result = setjmp(jump_buf.get() as _);
// // We set the jump index to be the last value of jumps
// *jump_index = jumps.len() as _;
// // We hold the reference of the jump buffer
// jumps.push(jump_buf);
// result
// }
}
/// longjmp
pub extern "C" fn __longjmp(env_addr: u32, val: c_int, instance: &mut Instance) -> ! {
debug!("emscripten::__longjmp (longjmp) {}", val);
unimplemented!()
// unsafe {
// // We retrieve the jump index from the env address
// let jump_index = instance.memory_offset_addr(0, env_addr as usize) as *mut i8;
// let mut jumps = &mut instance.emscripten_data().as_mut().unwrap().jumps;
// // We get the real jump buffer from the jumps vector, using the retrieved index
// let mut jump_buf = &jumps[*jump_index as usize];
// longjmp(jump_buf.get() as _, val)
// };
}
extern "C" {
fn setjmp(env: *mut c_void) -> c_int;
fn longjmp(env: *mut c_void, val: c_int) -> !;
}

1299
lib/emscripten/src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,27 @@
use wasmer_runtime::Instance;
// TODO: Need to implement.
/// emscripten: dlopen(filename: *const c_char, flag: c_int) -> *mut c_void
pub extern "C" fn _dlopen(filename: u32, flag: c_int) -> u32 {
debug!("emscripten::_dlopen");
-1
}
/// emscripten: dlclose(handle: *mut c_void) -> c_int
pub extern "C" fn _dlclose(filename: u32) -> u32 {
debug!("emscripten::_dlclose");
-1
}
/// emscripten: dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void
pub extern "C" fn _dlsym(filepath: u32, symbol: u32) -> u32 {
debug!("emscripten::_dlerror");
-1
}
/// emscripten: dlerror() -> *mut c_char
pub extern "C" fn _dlerror() -> u32 {
debug!("emscripten::_dlerror");
-1
}

View File

@ -0,0 +1,17 @@
use wasmer_runtime::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 {}, {}", which, varargs);
}
// NOTE: Not implemented by Emscripten
pub extern "C" fn ___unlock(which: c_int, varargs: c_int, _instance: &mut Instance) {
debug!("emscripten::___unlock {}, {}", which, varargs);
}
// NOTE: Not implemented by Emscripten
pub extern "C" fn ___wait(_which: c_int, _varargs: c_int, _instance: &mut Instance) {
debug!("emscripten::___wait");
}

View File

@ -0,0 +1,17 @@
/// emscripten: _llvm_log10_f64
pub extern "C" fn _llvm_log10_f64(value: f64) -> f64 {
debug!("emscripten::_llvm_log10_f64");
value.log10()
}
/// emscripten: _llvm_log2_f64
pub extern "C" fn _llvm_log2_f64(value: f64) -> f64 {
debug!("emscripten::_llvm_log2_f64");
value.log2()
}
// emscripten: f64-rem
pub extern "C" fn f64_rem(x: f64, y: f64) -> f64 {
debug!("emscripten::f64-rem");
x % y
}

View File

@ -0,0 +1,48 @@
use super::process::abort_with_message;
use wasmer_runtime::Instance;
use libc::{c_int, c_void, memcpy, size_t};
/// emscripten: _emscripten_memcpy_big
pub extern "C" fn _emscripten_memcpy_big(
dest: u32,
src: u32,
len: u32,
instance: &mut Instance,
) -> u32 {
debug!(
"emscripten::_emscripten_memcpy_big {}, {}, {}",
dest, src, len
);
let dest_addr = instance.memory_offset_addr(0, dest as usize) as *mut c_void;
let src_addr = instance.memory_offset_addr(0, src as usize) as *mut c_void;
unsafe {
memcpy(dest_addr, src_addr, len as size_t);
}
dest
}
/// emscripten: getTotalMemory
pub extern "C" fn get_total_memory(_instance: &mut Instance) -> u32 {
debug!("emscripten::get_total_memory");
// instance.memories[0].current_pages()
16_777_216
}
/// emscripten: enlargeMemory
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!");
}
/// emscripten: ___map_file
pub extern "C" fn ___map_file() -> c_int {
debug!("emscripten::___map_file");
// NOTE: TODO: Em returns -1 here as well. May need to implement properly
-1
}

View File

@ -0,0 +1,62 @@
use super::process::abort_with_message;
use wasmer_runtime::Instance;
pub extern "C" fn nullfunc_ii(x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_ii {}", x);
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 {}", x);
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 {}", x);
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 {}", x);
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 {}", x);
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_v(x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_v {}", x);
abort_with_message("Invalid function pointer called with signature 'v'. 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 {}", x);
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 {}", x);
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 {}", x);
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 {}", x);
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)");
}
pub extern "C" fn nullfunc_viiiii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_viiiii");
abort_with_message("Invalid function pointer called with signature 'viiiii'. 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_viiiiii(_x: u32, _instance: &Instance) {
debug!("emscripten::nullfunc_viiiiii");
abort_with_message("Invalid function pointer called with signature 'viiiiii'. 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

@ -0,0 +1,69 @@
use libc::{abort, c_char, c_int, exit, pid_t, EAGAIN};
use wasmer_runtime::Instance;
use std::ffi::CStr;
pub extern "C" fn abort_with_message(message: &str) {
debug!("emscripten::abort_with_message");
println!("{}", message);
_abort();
}
pub extern "C" fn _abort() {
debug!("emscripten::_abort");
unsafe {
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 {}", status);
unsafe { exit(status) }
}
pub extern "C" fn em_abort(message: u32, instance: &mut Instance) {
debug!("emscripten::em_abort {}", message);
let message_addr = instance.memory_offset_addr(0, message as usize) as *mut c_char;
unsafe {
let message = CStr::from_ptr(message_addr)
.to_str()
.unwrap_or("Unexpected abort");
abort_with_message(message);
}
}
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");
}
pub extern "C" fn _llvm_trap() {
debug!("emscripten::_llvm_trap");
abort_with_message("abort!");
}
pub extern "C" fn _system() -> c_int {
debug!("emscripten::_system");
// TODO: May need to change this Em impl to a working version
eprintln!("Can't call external programs");
return EAGAIN;
}
pub extern "C" fn _popen() -> c_int {
debug!("emscripten::_popen");
// TODO: May need to change this Em impl to a working version
eprintln!("Missing function: popen");
unsafe {
abort();
}
}

View File

@ -0,0 +1,35 @@
// use super::varargs::VarArgs;
use wasmer_runtime::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 {}, {}, {}", signum, act, oldact);
0
}
pub extern "C" fn _sigaddset(set: u32, signum: u32, instance: &mut Instance) -> i32 {
debug!("emscripten::_sigaddset {}, {}", set, signum);
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,17 @@
// use crate::webassembly::LinearMemory;
pub fn align_memory(ptr: u32) -> u32 {
(ptr + 15) & !15
}
// 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

@ -0,0 +1,965 @@
use super::utils::copy_stat_into_wasm;
use super::varargs::VarArgs;
use wasmer_runtime::Instance;
use byteorder::{ByteOrder, LittleEndian};
/// 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,
// ENOTTY,
c_char,
c_int,
c_void,
chdir,
chown,
// fcntl, setsockopt, getppid
close,
connect,
dup2,
exit,
fcntl,
fstat,
getgid,
getpeername,
getpid,
getsockname,
getsockopt,
gid_t,
in_addr_t,
in_port_t,
ioctl,
// iovec,
listen,
lseek,
mkdir,
msghdr,
off_t,
open,
pid_t,
pread,
pwrite,
read,
// readv,
recvfrom,
recvmsg,
rmdir,
// ENOTTY,
rusage,
sa_family_t,
// writev,
select,
sendmsg,
sendto,
setpgid,
setsockopt,
sockaddr,
socket,
socklen_t,
ssize_t,
stat,
uname,
utsname,
write,
EINVAL,
// sockaddr_in,
FIOCLEX,
FIONBIO,
F_GETFD,
F_SETFD,
SOL_SOCKET,
TIOCGWINSZ,
};
use super::env;
use std::mem;
use std::slice;
// use std::sys::fd::FileDesc;
// Linking to functions that are not provided by rust libc
#[cfg(target_os = "macos")]
#[link(name = "c")]
extern "C" {
pub fn wait4(pid: pid_t, status: *mut c_int, options: c_int, rusage: *mut rusage) -> pid_t;
}
#[cfg(not(target_os = "macos"))]
use libc::wait4;
// 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) {}", which);
let status: i32 = varargs.get(instance);
unsafe {
exit(status);
}
}
/// read
pub extern "C" fn ___syscall3(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> ssize_t {
debug!("emscripten::___syscall3 (read) {}", which);
let fd: i32 = varargs.get(instance);
let buf: u32 = varargs.get(instance);
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) {}", which);
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) {}", which);
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) {}", which);
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) {}", which);
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) {}", which);
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 _) }
}
// rmdir
pub extern "C" fn ___syscall40(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall40 (rmdir)");
let pathname: u32 = varargs.get(instance);
let pathname_addr = instance.memory_offset_addr(0, pathname as usize) as *const i8;
unsafe { rmdir(pathname_addr) }
}
/// ioctl
pub extern "C" fn ___syscall54(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall54 (ioctl) {}", which);
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(FIONBIO): {}", ret);
ret
// 0
}
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(TIOCGWINSZ): {} (harcoded to 0)", ret);
// ret
// TODO: We hardcode the value to have emscripten tests pass, as for some reason
// when the capturer is active, ioctl returns -1 instead of 0
if ret == -1 {
0
} else {
ret
}
}
_ => {
debug!(
"emscripten::___syscall54 -> non implemented case {}",
request
);
0
}
}
}
// setpgid
pub extern "C" fn ___syscall57(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall57 (setpgid) {}", which);
let pid: i32 = varargs.get(instance);
let pgid: i32 = varargs.get(instance);
unsafe { setpgid(pid, pgid) }
}
// dup2
pub extern "C" fn ___syscall63(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall63 (dup2) {}", which);
let src: i32 = varargs.get(instance);
let dst: i32 = varargs.get(instance);
unsafe { dup2(src, dst) }
}
// getppid
pub extern "C" fn ___syscall64() -> pid_t {
debug!("emscripten::___syscall64 (getppid)");
unsafe { getpid() }
}
// socketcall
pub extern "C" fn ___syscall102(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall102 (socketcall) {}", which);
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>());
pub struct LinuxSockAddr {
pub sa_family: u16,
pub sa_data: [c_char; 14],
}
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_addr: u32 = socket_varargs.get(instance);
let address_len: u32 = socket_varargs.get(instance);
let address = instance.memory_offset_addr(0, address_addr 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) };
unsafe {
let address_linux =
instance.memory_offset_addr(0, address_addr as usize) as *mut LinuxSockAddr;
(*address_linux).sa_family = (*address).sa_family as u16;
(*address_linux).sa_data = (*address).sa_data;
};
// // 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
// );
// debug!(
// "=> address.sa_family: {:?}",
// (*address).sa_family
// );
// }
// 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
}
}
}
/// wait4
pub extern "C" fn ___syscall114(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> pid_t {
debug!("emscripten::___syscall114 (wait4)");
let pid: pid_t = varargs.get(instance);
let status: u32 = varargs.get(instance);
let options: c_int = varargs.get(instance);
let rusage: u32 = varargs.get(instance);
let status_addr = instance.memory_offset_addr(0, status as usize) as *mut c_int;
let rusage_addr = instance.memory_offset_addr(0, rusage as usize) as *mut rusage;
let res = unsafe { wait4(pid, status_addr, options, rusage_addr) };
debug!(
"=> pid: {}, status: {:?}, options: {}, rusage: {:?} = pid: {}",
pid, status_addr, options, rusage_addr, res
);
res
}
/// 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) {}", which);
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) }
}
// select
pub extern "C" fn ___syscall142(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall142 (newselect) {}", which);
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 _) }
}
// mmap2
pub extern "C" fn ___syscall192(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall192 (mmap2) {}", which);
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
);
if fd == -1 {
let ptr = env::call_memalign(16384, len, instance);
if ptr == 0 {
return -1;
}
env::call_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) {}", which);
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) {}", which);
// 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 += curr;
}
// debug!(" => ret: {}", ret);
ret
}
}
// writev
pub extern "C" fn ___syscall146(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> ssize_t {
debug!("emscripten::___syscall146 (writev) {}", which);
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 += curr;
}
// debug!(" => ret: {}", ret);
ret
}
}
// pread
pub extern "C" fn ___syscall180(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall180 (pread) {}", which);
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) {}", which);
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) {}", which);
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) {}", which);
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
}
// 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) {}", which);
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) {}", which);
// fcntl64
let _fd: i32 = varargs.get(instance);
let cmd: u32 = varargs.get(instance);
match cmd {
2 => 0,
_ => -1,
}
}
/// dup3
pub extern "C" fn ___syscall330(
_which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> pid_t {
// Implementation based on description at https://linux.die.net/man/2/dup3
debug!("emscripten::___syscall330 (dup3)");
let oldfd: c_int = varargs.get(instance);
let newfd: c_int = varargs.get(instance);
let flags: c_int = varargs.get(instance);
if oldfd == newfd {
return EINVAL;
}
let res = unsafe { dup2(oldfd, newfd) };
// Set flags on newfd (https://www.gnu.org/software/libc/manual/html_node/Descriptor-Flags.html)
let mut old_flags = unsafe { fcntl(newfd, F_GETFD, 0) };
if old_flags > 0 {
old_flags |= flags;
} else if old_flags == 0 {
old_flags &= !flags;
}
unsafe {
fcntl(newfd, F_SETFD, old_flags);
}
debug!(
"=> oldfd: {}, newfd: {}, flags: {} = pid: {}",
oldfd, newfd, flags, res
);
res
}
// prlimit64
pub extern "C" fn ___syscall340(
which: c_int,
mut varargs: VarArgs,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___syscall340 (prlimit64), {}", which);
// 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
}

View File

@ -0,0 +1,9 @@
(module
(table 0 anyfunc)
(memory $0 1)
(export "memory" (memory $0))
(export "main" (func $main))
(func $main (; 1 ;) (result i32)
(i32.const 0)
)
)

View File

@ -0,0 +1,18 @@
(module
(type $FUNCSIG$ii (func (param i32) (result i32)))
(import "env" "puts" (func $puts (param i32) (result i32)))
(import "env" "_emscripten_memcpy_big" (func $_emscripten_memcpy_big (param i32 i32 i32) (result i32)))
(table 0 anyfunc)
(memory $0 1)
(data (i32.const 16) "hello, world!\00")
(export "memory" (memory $0))
(export "main" (func $main))
(func $main (; 1 ;) (result i32)
(drop
(call $puts
(i32.const 16)
)
)
(i32.const 0)
)
)

278
lib/emscripten/src/time.rs Normal file
View File

@ -0,0 +1,278 @@
use super::utils::{copy_cstr_into_wasm, write_to_buf};
use libc::{c_char, c_int, time as libc_time, time_t};
use std::mem;
use std::time::SystemTime;
use time;
use super::env;
use wasmer_runtime::Instance;
#[cfg(target_os = "linux")]
use libc::{CLOCK_MONOTONIC, CLOCK_MONOTONIC_COARSE, CLOCK_REALTIME};
#[cfg(target_os = "macos")]
use libc::{CLOCK_MONOTONIC, CLOCK_REALTIME};
#[cfg(target_os = "macos")]
const CLOCK_MONOTONIC_COARSE: libc::clockid_t = 6;
// some assumptions about the constants when targeting windows
#[cfg(target_os = "windows")]
const CLOCK_REALTIME: libc::clockid_t = 0;
#[cfg(target_os = "windows")]
const CLOCK_MONOTONIC: libc::clockid_t = 1;
#[cfg(target_os = "windows")]
const CLOCK_MONOTONIC_COARSE: libc::clockid_t = 6;
/// 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: libc::clockid_t,
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,
}
let timespec = match clk_id {
CLOCK_REALTIME => time::get_time(),
CLOCK_MONOTONIC | CLOCK_MONOTONIC_COARSE => {
let precise_ns = time::precise_time_ns();
time::Timespec::new(
(precise_ns / 1000000000) as i64,
(precise_ns % 1000000000) as i32,
)
}
_ => panic!("Clock with id \"{}\" is not supported.", clk_id),
};
unsafe {
let timespec_struct_ptr = instance.memory_offset_addr(0, tp as _) as *mut GuestTimeSpec;
(*timespec_struct_ptr).tv_sec = timespec.sec as _;
(*timespec_struct_ptr).tv_nsec = timespec.nsec as _;
}
0
}
/// emscripten: ___clock_gettime
pub extern "C" fn ___clock_gettime(
clk_id: libc::clockid_t,
tp: c_int,
instance: &mut Instance,
) -> c_int {
debug!("emscripten::___clock_gettime {} {}", clk_id, tp);
_clock_gettime(clk_id, tp, instance)
}
/// emscripten: _clock
pub extern "C" fn _clock() -> c_int {
debug!("emscripten::_clock");
0 // TODO: unimplemented
}
/// emscripten: _difftime
pub extern "C" fn _difftime(t0: u32, t1: u32) -> c_int {
debug!("emscripten::_difftime");
(t0 - t1) as _
}
#[repr(C)]
struct guest_tm {
pub tm_sec: c_int, // 0
pub tm_min: c_int, // 4
pub tm_hour: c_int, // 8
pub tm_mday: c_int, // 12
pub tm_mon: c_int, // 16
pub tm_year: c_int, // 20
pub tm_wday: c_int, // 24
pub tm_yday: c_int, // 28
pub tm_isdst: c_int, // 32
pub tm_gmtoff: c_int, // 36
pub tm_zone: c_int, // 40
}
/// emscripten: _tvset
pub extern "C" fn _tvset() {
debug!("emscripten::_tvset UNIMPLEMENTED");
}
/// formats time as a C string
unsafe extern "C" fn fmt_time(time: u32, instance: &Instance) -> *const c_char {
let date = &*(instance.memory_offset_addr(0, time as _) as *mut guest_tm);
let days = vec!["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
let months = vec![
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let year = 1900 + date.tm_year;
let time_str = format!(
// NOTE: TODO: Hack! The 14 accompanying chars are needed for some reason
"{} {} {:2} {:02}:{:02}:{:02} {:4}\n\0\0\0\0\0\0\0\0\0\0\0\0\0",
days[date.tm_wday as usize],
months[date.tm_mon as usize],
date.tm_mday,
date.tm_hour,
date.tm_min,
date.tm_sec,
year
);
time_str[0..26].as_ptr() as _
}
/// emscripten: _asctime
pub extern "C" fn _asctime(time: u32, instance: &mut Instance) -> u32 {
debug!("emscripten::_asctime {}", time);
unsafe {
let time_str_ptr = fmt_time(time, instance);
copy_cstr_into_wasm(instance, time_str_ptr)
// let c_str = instance.memory_offset_addr(0, res as _) as *mut i8;
// use std::ffi::CStr;
// debug!("#### cstr = {:?}", CStr::from_ptr(c_str));
}
}
/// emscripten: _asctime_r
pub extern "C" fn _asctime_r(time: u32, buf: u32, instance: &mut Instance) -> u32 {
debug!("emscripten::_asctime_r {}, {}", time, buf);
unsafe {
// NOTE: asctime_r is specced to behave in an undefined manner if the algorithm would attempt
// to write out more than 26 bytes (including the null terminator).
// See http://pubs.opengroup.org/onlinepubs/9699919799/functions/asctime.html
// Our undefined behavior is to truncate the write to at most 26 bytes, including null terminator.
let time_str_ptr = fmt_time(time, instance);
write_to_buf(time_str_ptr, buf, 26, instance)
// let c_str = instance.memory_offset_addr(0, res as _) as *mut i8;
// use std::ffi::CStr;
// debug!("#### cstr = {:?}", CStr::from_ptr(c_str));
}
}
/// emscripten: _localtime
pub extern "C" fn _localtime(time_p: u32, instance: &mut Instance) -> c_int {
debug!("emscripten::_localtime {}", time_p);
// NOTE: emscripten seems to want tzset() called in this function
// https://stackoverflow.com/questions/19170721/real-time-awareness-of-timezone-change-in-localtime-vs-localtime-r
let timespec = unsafe {
let time_p_addr = instance.memory_offset_addr(0, time_p as _) as *mut i64;
let seconds = *time_p_addr.clone();
time::Timespec::new(seconds, 0)
};
let result_tm = time::at(timespec);
unsafe {
let tm_struct_offset = env::call_malloc(mem::size_of::<guest_tm>() as _, instance);
let tm_struct_ptr = instance.memory_offset_addr(0, tm_struct_offset as _) as *mut guest_tm;
// debug!(
// ">>>>>>> time = {}, {}, {}, {}, {}, {}, {}, {}",
// result_tm.tm_sec, result_tm.tm_min, result_tm.tm_hour, result_tm.tm_mday,
// result_tm.tm_mon, result_tm.tm_year, result_tm.tm_wday, result_tm.tm_yday,
// );
(*tm_struct_ptr).tm_sec = result_tm.tm_sec;
(*tm_struct_ptr).tm_min = result_tm.tm_min;
(*tm_struct_ptr).tm_hour = result_tm.tm_hour;
(*tm_struct_ptr).tm_mday = result_tm.tm_mday;
(*tm_struct_ptr).tm_mon = result_tm.tm_mon;
(*tm_struct_ptr).tm_year = result_tm.tm_year;
(*tm_struct_ptr).tm_wday = result_tm.tm_wday;
(*tm_struct_ptr).tm_yday = result_tm.tm_yday;
(*tm_struct_ptr).tm_isdst = result_tm.tm_isdst;
(*tm_struct_ptr).tm_gmtoff = 0;
(*tm_struct_ptr).tm_zone = 0;
tm_struct_offset as _
}
}
/// emscripten: _localtime_r
pub extern "C" fn _localtime_r(time_p: u32, result: u32, instance: &mut Instance) -> c_int {
debug!("emscripten::_localtime_r {}", time_p);
// NOTE: emscripten seems to want tzset() called in this function
// https://stackoverflow.com/questions/19170721/real-time-awareness-of-timezone-change-in-localtime-vs-localtime-r
unsafe {
let seconds = instance.memory_offset_addr(0, time_p as _) as *const i64;
let timespec = time::Timespec::new(*seconds, 0);
let result_tm = time::at(timespec);
// debug!(
// ">>>>>>> time = {}, {}, {}, {}, {}, {}, {}, {}",
// result_tm.tm_sec, result_tm.tm_min, result_tm.tm_hour, result_tm.tm_mday,
// result_tm.tm_mon, result_tm.tm_year, result_tm.tm_wday, result_tm.tm_yday,
// );
let result_addr = instance.memory_offset_addr(0, result as _) as *mut guest_tm;
(*result_addr).tm_sec = result_tm.tm_sec;
(*result_addr).tm_min = result_tm.tm_min;
(*result_addr).tm_hour = result_tm.tm_hour;
(*result_addr).tm_mday = result_tm.tm_mday;
(*result_addr).tm_mon = result_tm.tm_mon;
(*result_addr).tm_year = result_tm.tm_year;
(*result_addr).tm_wday = result_tm.tm_wday;
(*result_addr).tm_yday = result_tm.tm_yday;
(*result_addr).tm_isdst = result_tm.tm_isdst;
(*result_addr).tm_gmtoff = 0;
(*result_addr).tm_zone = 0;
result as _
}
}
/// 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;
libc_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
}

162
lib/emscripten/src/utils.rs Normal file
View File

@ -0,0 +1,162 @@
use wasmer_runtime::{Instance, module::Module};
//use wasmer_runtime::Instance;
use super::env;
use libc::stat;
use std::ffi::CStr;
use std::mem::size_of;
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 {
for (_, import_name) in &module.imported_functions {
if import_name.name == "_emscripten_memcpy_big" && import_name.module == "env" {
return true;
}
}
false
}
pub unsafe fn write_to_buf(string: *const c_char, buf: u32, max: u32, instance: &Instance) -> u32 {
let buf_addr = instance.memory_offset_addr(0, buf as _) as *mut c_char;
for i in 0..max {
*buf_addr.add(i as _) = *string.add(i as _);
}
buf
}
/// This function expects nullbyte to be appended.
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 cstr_len = s.len();
let space_offset = env::call_malloc((cstr_len as i32) + 1, instance);
let raw_memory = instance.memory_offset_addr(0, space_offset as _) as *mut u8;
let slice = slice::from_raw_parts_mut(raw_memory, cstr_len);
for (byte, loc) in s.bytes().zip(slice.iter_mut()) {
*loc = byte;
}
// TODO: Appending null byte won't work, because there is CStr::from_ptr(cstr)
// at the top that crashes when there is no null byte
*raw_memory.add(cstr_len) = 0;
space_offset
}
pub unsafe fn allocate_on_stack<'a, T: Copy>(
count: u32,
instance: &'a Instance,
) -> (u32, &'a mut [T]) {
unimplemented!("allocate_on_stack not implemented")
// let offset = (instance.emscripten_data().as_ref().unwrap().stack_alloc)(
// count * (size_of::<T>() as u32),
// instance,
// );
// let addr = instance.memory_offset_addr(0, offset as _) as *mut T;
// let slice = slice::from_raw_parts_mut(addr, count as usize);
//
// (offset, slice)
}
pub unsafe fn allocate_cstr_on_stack<'a>(s: &str, instance: &'a Instance) -> (u32, &'a [u8]) {
let (offset, slice) = allocate_on_stack((s.len() + 1) as u32, instance);
use std::iter;
for (byte, loc) in s.bytes().chain(iter::once(0)).zip(slice.iter_mut()) {
*loc = byte;
}
(offset, slice)
}
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
}
#[repr(C)]
pub struct GuestStat {
st_dev: u32,
__st_dev_padding: u32,
__st_ino_truncated: u32,
st_mode: u32,
st_nlink: u32,
st_uid: u32,
st_gid: u32,
st_rdev: u32,
__st_rdev_padding: u32,
st_size: u32,
st_blksize: u32,
st_blocks: u32,
st_atime: u64,
st_mtime: u64,
st_ctime: u64,
st_ino: u64,
}
pub unsafe fn copy_stat_into_wasm(instance: &mut Instance, buf: u32, stat: &stat) {
let stat_ptr = instance.memory_offset_addr(0, buf as _) as *mut GuestStat;
(*stat_ptr).st_dev = stat.st_dev as _;
(*stat_ptr).__st_dev_padding = 0;
(*stat_ptr).__st_ino_truncated = stat.st_ino as _;
(*stat_ptr).st_mode = stat.st_mode as _;
(*stat_ptr).st_nlink = stat.st_nlink as _;
(*stat_ptr).st_uid = stat.st_uid as _;
(*stat_ptr).st_gid = stat.st_gid as _;
(*stat_ptr).st_rdev = stat.st_rdev as _;
(*stat_ptr).__st_rdev_padding = 0;
(*stat_ptr).st_size = stat.st_size as _;
(*stat_ptr).st_blksize = 4096;
#[cfg(not(target_os = "windows"))]
{
(*stat_ptr).st_blocks = stat.st_blocks as _;
}
#[cfg(target_os = "windows")]
{
(*stat_ptr).st_blocks = 0;
}
(*stat_ptr).st_atime = stat.st_atime as _;
(*stat_ptr).st_mtime = stat.st_mtime as _;
(*stat_ptr).st_ctime = stat.st_ctime as _;
(*stat_ptr).st_ino = stat.st_ino as _;
}
#[cfg(test)]
mod tests {
use super::is_emscripten_module;
use wasmer_clif_backend::CraneliftCompiler;
use wabt::wat2wasm;
#[test]
fn should_detect_emscripten_files() {
const wast_bytes: &[u8] = include_bytes!("tests/is_emscripten_true.wast");
let wasm_binary = wat2wasm(wast_bytes.to_vec()).expect("Can't convert to wasm");
let module = wasmer_runtime::compile(&wasm_binary[..], &CraneliftCompiler::new()).expect("WASM can't be compiled");
assert!(is_emscripten_module(&module));
}
#[test]
fn should_detect_non_emscripten_files() {
const wast_bytes: &[u8] = include_bytes!("tests/is_emscripten_false.wast");
let wasm_binary = wat2wasm(wast_bytes.to_vec()).expect("Can't convert to wasm");
let module = wasmer_runtime::compile(&wasm_binary[..], &CraneliftCompiler::new()).expect("WASM can't be compiled");
assert!(!is_emscripten_module(&module));
}
}

View File

@ -0,0 +1,15 @@
use wasmer_runtime::Instance;
use std::mem;
#[repr(transparent)]
pub struct VarArgs {
pub pointer: u32, // assuming 32bit wasm
}
impl VarArgs {
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() }
}
}