Merge branch 'feature/wasi-fs' into feature/wasi

This commit is contained in:
Lachlan Sneff 2019-04-01 15:17:13 -07:00
commit c12c7d558c
52 changed files with 3922 additions and 1822 deletions

View File

@ -1,20 +1,28 @@
run_with_build_env_vars: &run_with_build_env_vars
environment:
LLVM_SYS_70_PREFIX: /home/circleci/project/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04/
run_install_dependencies: &run_install_dependencies
run:
name: install dependencies
command: |
sudo apt-get install -y cmake
curl -O https://releases.llvm.org/7.0.0/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz
tar xf clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz
version: 2
jobs:
# Job used for testing
lint:
docker:
- image: circleci/rust:latest
<<: *run_with_build_env_vars
steps:
- checkout
- restore_cache:
keys:
- v6-lint-{{ arch }}-{{ checksum "Cargo.lock" }}
- run:
name: Install dependencies
command: |
sudo apt-get install -y cmake
curl -O https://releases.llvm.org/7.0.0/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz
tar xf clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz
- <<: *run_install_dependencies
- run:
name: Install lint deps
command: |
@ -25,7 +33,6 @@ jobs:
- run:
name: Execute lints
command: |
export LLVM_SYS_70_PREFIX="`pwd`/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04/"
make lint
- save_cache:
paths:
@ -33,37 +40,27 @@ jobs:
- target/debug/.fingerprint
- target/debug/build
- target/debug/deps
key: v6-lint-{{ arch }}-{{ checksum "Cargo.lock" }}
key: v6-test-cargo-cache-linux-{{ arch }}-{{ checksum "Cargo.lock" }}
test:
docker:
- image: circleci/rust:latest
<<: *run_with_build_env_vars
steps:
- checkout
- restore_cache:
keys:
- v6-test-cargo-cache-linux-{{ arch }}-{{ checksum "Cargo.lock" }}
- run:
name: Install dependencies
command: |
sudo apt-get install -y cmake
curl -O https://releases.llvm.org/7.0.0/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz
tar xf clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz
- <<: *run_install_dependencies
- run:
name: Tests
command: |
export LLVM_SYS_70_PREFIX="`pwd`/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04/"
make test
command: make test
- run:
name: Emscripten Tests
command: |
export LLVM_SYS_70_PREFIX="`pwd`/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04/"
make test-emscripten
command: make test-emscripten
- run:
name: Integration Tests
command: |
export LLVM_SYS_70_PREFIX="`pwd`/clang+llvm-7.0.0-x86_64-linux-gnu-ubuntu-16.04/"
make integration-tests
command: make integration-tests
- save_cache:
paths:
- /usr/local/cargo/registry

1085
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -19,29 +19,32 @@ include = [
]
[dependencies]
errno = "0.2.4"
structopt = "0.2.11"
wabt = "0.7.2"
hashbrown = "0.1.8"
wasmer-clif-backend = { path = "lib/clif-backend" }
wasmer-dynasm-backend = { path = "lib/dynasm-backend", optional = true }
wasmer-runtime = { path = "lib/runtime" }
wasmer-runtime-abi = { path = "lib/runtime-abi", optional = true }
wasmer-runtime-core = { path = "lib/runtime-core" }
wasmer-emscripten = { path = "lib/emscripten" }
wasmer-llvm-backend = { path = "lib/llvm-backend", optional = true }
wasmer-dynasm-backend = { path = "lib/dynasm-backend", optional = true }
wasmer-wasi = { path = "lib/wasi", optional = true }
[workspace]
members = ["lib/clif-backend", "lib/dynasm-backend", "lib/runtime", "lib/runtime-core", "lib/emscripten", "lib/spectests", "lib/win-exception-handler", "lib/runtime-c-api", "lib/llvm-backend", "lib/wasi"]
members = ["lib/clif-backend", "lib/dynasm-backend", "lib/runtime", "lib/runtime-abi", "lib/runtime-core", "lib/emscripten", "lib/spectests", "lib/win-exception-handler", "lib/runtime-c-api", "lib/llvm-backend", "lib/wasi"]
[build-dependencies]
wabt = "0.7.2"
glob = "0.2.11"
[features]
debug = ["wasmer-clif-backend/debug", "wasmer-runtime-core/debug"]
default = ["fast-tests"]
debug = ["wasmer-clif-backend/debug", "wasmer-runtime-core/debug"]
# This feature will allow cargo test to run much faster
fast-tests = []
llvm = ["wasmer-llvm-backend"]
dynasm = ["wasmer-dynasm-backend"]
wasi = ["wasmer-wasi"]
wasi = ["wasmer-wasi"]
vfs = ["wasmer-runtime-abi"]

View File

@ -8,7 +8,7 @@ repository = "https://github.com/wasmerio/wasmer"
edition = "2018"
[dependencies]
wasmer-runtime-core = { path = "../runtime-core", version = "0.2.0" }
wasmer-runtime-core = { path = "../runtime-core", version = "0.2.1" }
cranelift-native = "0.26.0"
cranelift-codegen = "0.26.0"
cranelift-entity = "0.26.0"

View File

@ -0,0 +1,31 @@
<p align="center">
<a href="https://wasmer.io" target="_blank" rel="noopener noreferrer">
<img width="400" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/logo.png" alt="Wasmer logo">
</a>
</p>
<p align="center">
<a href="https://circleci.com/gh/wasmerio/wasmer/">
<img src="https://img.shields.io/circleci/project/github/wasmerio/wasmer/master.svg" alt="Build Status">
</a>
<a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License">
</a>
<a href="https://spectrum.chat/wasmer">
<img src="https://withspectrum.github.io/badge/badge.svg" alt="Join the Wasmer Community">
</a>
<a href="https://crates.io/crates/wasmer-clif-backend">
<img src="https://img.shields.io/crates/d/wasmer-clif-backend.svg" alt="Number of downloads from crates.io">
</a>
<a href="https://docs.rs/wasmer-clif-backend">
<img src="https://docs.rs/wasmer-clif-backend/badge.svg" alt="Read our API documentation">
</a>
</p>
# Wasmer Cranelift backend
Wasmer is a standalone JIT WebAssembly runtime, aiming to be fully
compatible with Emscripten, Rust and Go. [Learn
more](https://github.com/wasmerio/wasmer).
This crate represents the Cranelift backend.

View File

@ -51,6 +51,8 @@ impl Module {
namespace_table: StringTable::new(),
name_table: StringTable::new(),
em_symbol_map: compiler_config.symbol_map.clone(),
custom_sections: HashMap::new(),
},
}
}

View File

@ -16,3 +16,4 @@ lazy_static = "1.2.0"
byteorder = "1"
nix = "0.13.0"
libc = "0.2.49"
hashbrown = "0.1"

View File

@ -0,0 +1,31 @@
<p align="center">
<a href="https://wasmer.io" target="_blank" rel="noopener noreferrer">
<img width="400" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/logo.png" alt="Wasmer logo">
</a>
</p>
<p align="center">
<a href="https://circleci.com/gh/wasmerio/wasmer/">
<img src="https://img.shields.io/circleci/project/github/wasmerio/wasmer/master.svg" alt="Build Status">
</a>
<a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License">
</a>
<a href="https://spectrum.chat/wasmer">
<img src="https://withspectrum.github.io/badge/badge.svg" alt="Join the Wasmer Community">
</a>
<a href="https://crates.io/crates/wasmer-dynasm-backend">
<img src="https://img.shields.io/crates/d/wasmer-dynasm-backend.svg" alt="Number of downloads from crates.io">
</a>
<a href="https://docs.rs/wasmer-dynasm-backend">
<img src="https://docs.rs/wasmer-dynasm-backend/badge.svg" alt="Read our API documentation">
</a>
</p>
# Wasmer dynasm backend
Wasmer is a standalone JIT WebAssembly runtime, aiming to be fully
compatible with Emscripten, Rust and Go. [Learn
more](https://github.com/wasmerio/wasmer).
This crate represents the dynasm backend.

View File

@ -1,4 +1,5 @@
use crate::codegen::{CodegenError, FunctionCodeGenerator, ModuleCodeGenerator};
use hashbrown::HashMap;
use wasmer_runtime_core::{
backend::{Backend, CompilerConfig, FuncResolver, ProtectedCaller},
module::{
@ -98,6 +99,8 @@ pub fn read_module<
name_table: StringTable::new(),
em_symbol_map: compiler_config.symbol_map.clone(),
custom_sections: HashMap::new(),
};
let mut reader = ModuleReader::new(wasm)?;

12
lib/emscripten/emtests/test_vfs.c vendored Normal file
View File

@ -0,0 +1,12 @@
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
char data[256] = {0};
ssize_t fd = open("data.txt", 0);
ssize_t result = read((int)fd, &data, 255);
printf("content: %s", data);
printf("fd: %zd\n", fd);
return 0;
}

6
lib/emscripten/emtests/test_vfs.md vendored Normal file
View File

@ -0,0 +1,6 @@
The wasm file `test_vfs.wasm` is generated by compiling the `test_vfs.c` and writing a tar.zst blob with a single file
named `data.txt`.
The program expects to find a file named `data.txt` and reads the contents and the file descriptor.
The runtime should mount the virtual filesystem and expose the file.

1
lib/emscripten/emtests/test_vfs.out vendored Normal file
View File

@ -0,0 +1 @@
content: wasmer is awesomer

BIN
lib/emscripten/emtests/test_vfs.wasm vendored Normal file

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1 @@
wasmer is awesomer

View File

@ -0,0 +1,8 @@
use crate::emtests::_common::assert_emscripten_output;
#[test]
fn test_vfs() {
let wasm_bytes = include_bytes!("../../emtests/test_vfs_bundle.wasm");
let expected_str = include_str!("../../emtests/test_vfs.out");
assert_emscripten_output(wasm_bytes, expected_str);
}

View File

@ -0,0 +1,31 @@
<p align="center">
<a href="https://wasmer.io" target="_blank" rel="noopener noreferrer">
<img width="400" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/logo.png" alt="Wasmer logo">
</a>
</p>
<p align="center">
<a href="https://circleci.com/gh/wasmerio/wasmer/">
<img src="https://img.shields.io/circleci/project/github/wasmerio/wasmer/master.svg" alt="Build Status">
</a>
<a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License">
</a>
<a href="https://spectrum.chat/wasmer">
<img src="https://withspectrum.github.io/badge/badge.svg" alt="Join the Wasmer Community">
</a>
<a href="https://crates.io/crates/wasmer-llvm-backend">
<img src="https://img.shields.io/crates/d/wasmer-llvm-backend.svg" alt="Number of downloads from crates.io">
</a>
<a href="https://docs.rs/wasmer-llvm-backend">
<img src="https://docs.rs/wasmer-llvm-backend/badge.svg" alt="Read our API documentation">
</a>
</p>
# Wasmer LLVM backend
Wasmer is a standalone JIT WebAssembly runtime, aiming to be fully
compatible with Emscripten, Rust and Go. [Learn
more](https://github.com/wasmerio/wasmer).
This crate represents the LLVM backend.

View File

@ -18,6 +18,8 @@ use wasmparser::{
SectionCode, Type as WpType,
};
use hashbrown::HashMap;
pub fn read_module(
wasm: &[u8],
compiler_config: CompilerConfig,
@ -47,6 +49,8 @@ pub fn read_module(
name_table: StringTable::new(),
em_symbol_map: compiler_config.symbol_map.clone(),
custom_sections: HashMap::new(),
};
let mut reader = ModuleReader::new(wasm)?;

View File

@ -0,0 +1,28 @@
[package]
name = "wasmer-runtime-abi"
version = "0.2.1"
description = "Wasmer runtime core library"
license = "MIT"
authors = ["The Wasmer Engineering Team <engineering@wasmer.io>"]
repository = "https://github.com/wasmerio/wasmer"
edition = "2018"
[dependencies]
libc = "0.2.50"
wasmer-runtime-core = { path = "../runtime-core" }
hashbrown = "0.1"
failure = "0.1"
tar = "0.4"
wasmparser = "0.23.0"
zstd = "0.4"
[target.'cfg(unix)'.dependencies.zbox]
git = "https://github.com/wasmerio/zbox"
branch = "bundle-libsodium"
features = ["libsodium-bundled"]
[dev-dependencies]
tempdir = "0.3"
[features]
debug = []

23
lib/runtime-abi/README.md Normal file
View File

@ -0,0 +1,23 @@
# runtime-abi
This crate has ABI functions (like syscalls) and extensions to the runtime for enabling ABIs (e.g. virtual filesystem).
## Virtual Filesystem (experimental)
The virtual filesystem allows the runtime to read bundled wasm data as if they were files. Data that is stored in a
custom section compressed with [zstd][1] compression and archived with [tar][2] will be exposed as files and mounted
in the `/` root.
The only current supported operation is the `read` syscall.
The virtual filesystem is not enabled by default. Build with `--features vfs` to use it.
[Zbox][3] is a virtual filesystem that depends on [libsodium][4]. See [installation instructions][5] for libsodium here. One can
statically link libsodium with the [instructions][6] on Zbox's readme.
[1]: https://facebook.github.io/zstd/
[2]: https://www.gnu.org/software/tar/
[3]: https://zbox.io/
[4]: https://download.libsodium.org/doc/
[5]: https://download.libsodium.org/doc/installation
[6]: https://github.com/zboxfs/zbox#static-linking-with-libsodium

View File

@ -0,0 +1,6 @@
#[cfg(not(target_os = "windows"))]
#[macro_use]
extern crate failure;
#[cfg(not(target_os = "windows"))]
pub mod vfs;

View File

@ -0,0 +1,111 @@
use crate::vfs::file_like::{FileLike, Metadata};
use failure::Error;
use std::io;
pub struct Stdin;
pub struct Stdout;
pub struct Stderr;
impl FileLike for Stdin {
fn metadata(&self) -> Result<Metadata, Error> {
unimplemented!()
}
fn set_file_len(&mut self, _len: usize) -> Result<(), failure::Error> {
panic!("Cannot set length of stdin");
}
}
impl io::Read for Stdin {
fn read(&mut self, _buf: &mut [u8]) -> Result<usize, io::Error> {
unimplemented!()
}
}
impl io::Write for Stdin {
fn write(&mut self, _buf: &[u8]) -> Result<usize, io::Error> {
unimplemented!()
}
fn flush(&mut self) -> Result<(), io::Error> {
unimplemented!()
}
}
impl io::Seek for Stdin {
fn seek(&mut self, _pos: io::SeekFrom) -> Result<u64, io::Error> {
unimplemented!()
}
}
impl FileLike for Stdout {
fn metadata(&self) -> Result<Metadata, failure::Error> {
unimplemented!()
}
fn set_file_len(&mut self, _len: usize) -> Result<(), failure::Error> {
panic!("Cannot set length of stdout");
}
}
impl io::Read for Stdout {
fn read(&mut self, _buf: &mut [u8]) -> Result<usize, io::Error> {
unimplemented!()
}
}
impl io::Write for Stdout {
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
let stdout = io::stdout();
let mut handle = stdout.lock();
handle.write(buf)
}
fn flush(&mut self) -> Result<(), io::Error> {
let stdout = io::stdout();
let mut handle = stdout.lock();
handle.flush()
}
}
impl io::Seek for Stdout {
fn seek(&mut self, _pos: io::SeekFrom) -> Result<u64, io::Error> {
unimplemented!()
}
}
impl FileLike for Stderr {
fn metadata(&self) -> Result<Metadata, failure::Error> {
unimplemented!()
}
fn set_file_len(&mut self, _len: usize) -> Result<(), failure::Error> {
panic!("Cannot set length of stderr");
}
}
impl io::Read for Stderr {
fn read(&mut self, _buf: &mut [u8]) -> Result<usize, io::Error> {
unimplemented!()
}
}
impl io::Write for Stderr {
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
let stderr = io::stderr();
let mut handle = stderr.lock();
handle.write(buf)
}
fn flush(&mut self) -> Result<(), io::Error> {
let stderr = io::stderr();
let mut handle = stderr.lock();
handle.flush()
}
}
impl io::Seek for Stderr {
fn seek(&mut self, _pos: io::SeekFrom) -> Result<u64, io::Error> {
unimplemented!()
}
}

View File

@ -0,0 +1,21 @@
pub type Fd = isize;
#[derive(Debug)]
pub struct Metadata {
pub len: usize,
pub is_file: bool,
}
pub trait FileLike: std::io::Write + std::io::Read + std::io::Seek {
// get metadata
fn metadata(&self) -> Result<Metadata, failure::Error>;
// write
// fn write_file(&mut self, buf: &[u8]) -> Result<usize, io::Error>;
// read
// fn read_file(&mut self, buf: &mut [u8]) -> Result<usize, io::Error>;
// set_file_len
fn set_file_len(&mut self, len: usize) -> Result<(), failure::Error>;
}

View File

@ -0,0 +1,5 @@
pub mod device_file;
pub mod file_like;
pub mod vfs;
pub mod vfs_header;
pub mod virtual_file;

View File

@ -0,0 +1,170 @@
use crate::vfs::file_like::FileLike;
use crate::vfs::vfs_header::{header_from_bytes, ArchiveType, CompressionType};
use crate::vfs::virtual_file::VirtualFile;
use hashbrown::HashMap;
use std::cell::RefCell;
use std::io;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use tar::EntryType;
use zbox::{init_env, OpenOptions, Repo, RepoOpener};
pub struct Vfs {
repo: Repo,
device_files: HashMap<PathBuf, Rc<RefCell<dyn FileLike>>>,
}
impl Vfs {
/// Like `VfsBacking::from_tar_bytes` except it also decompresses from the zstd format.
pub fn from_tar_zstd_bytes<Reader: Read>(tar_bytes: Reader) -> Result<Self, failure::Error> {
let result = zstd::decode_all(tar_bytes);
let decompressed_data = result.unwrap();
Self::from_tar_bytes(&decompressed_data[..])
}
/// Match on the type of the compressed-archive and select the correct unpack method
pub fn from_compressed_bytes(compressed_data_slice: &[u8]) -> Result<Self, failure::Error> {
let data_bytes = &compressed_data_slice[4..];
match header_from_bytes(compressed_data_slice)? {
(_, CompressionType::ZSTD, ArchiveType::TAR) => Self::from_tar_zstd_bytes(data_bytes),
(_, CompressionType::NONE, ArchiveType::TAR) => Self::from_tar_bytes(data_bytes),
}
}
/// Create a vfs from raw bytes in tar format
pub fn from_tar_bytes<Reader: Read>(tar_bytes: Reader) -> Result<Self, failure::Error> {
init_env();
let mut repo = RepoOpener::new()
.create(true)
.open("mem://wasmer_fs", "")
.unwrap();
let _errors = tar::Archive::new(tar_bytes)
.entries()?
.map(|entry| {
let mut entry: tar::Entry<Reader> = entry?;
let path = entry.path()?;
let path = convert_to_absolute_path(path);
let _result = match (entry.header().entry_type(), path.parent()) {
(EntryType::Regular, Some(parent)) => {
if let Err(e) = repo.create_dir_all(parent) {
if e == zbox::Error::AlreadyExists || e == zbox::Error::IsRoot {
} else {
return Err(VfsAggregateError::ZboxError(e));
}
} else {
}
let mut file = repo.create_file(&path)?;
if entry.header().size().unwrap_or(0) > 0 {
io::copy(&mut entry, &mut file)?;
file.finish()?;
}
}
(EntryType::Directory, _) => {
if let Err(e) = repo.create_dir_all(path) {
if e == zbox::Error::AlreadyExists || e == zbox::Error::IsRoot {
} else {
return Err(VfsAggregateError::ZboxError(e));
}
} else {
}
}
_ => return Err(VfsAggregateError::UnsupportedFileType),
};
Ok(())
})
.collect::<Vec<Result<(), VfsAggregateError>>>();
// let import_errors = errors.iter().filter_map(|e| e.err()).collect::<Vec<_>>();
let vfs = Self {
repo,
device_files: HashMap::new(),
// import_errors: vec![],
};
Ok(vfs)
}
pub fn new() -> Result<(Self, Vec<VfsError>), failure::Error> {
init_env();
let repo = RepoOpener::new()
.create(true)
.open("mem://wasmer_fs", "")
.unwrap();
Ok((
Vfs {
repo,
device_files: HashMap::new(),
},
vec![],
))
}
pub fn open_file<P: AsRef<Path>>(&mut self, path: P) -> Option<Rc<RefCell<dyn FileLike>>> {
init_env();
let path = convert_to_absolute_path(path);
if let Ok(file) = OpenOptions::new().write(true).open(&mut self.repo, &path) {
Some(Rc::new(RefCell::new(VirtualFile::new(file))))
} else if let Some(dev_file) = self.device_files.get(&path) {
Some(dev_file.clone())
} else {
None
}
}
pub fn make_dir<P: AsRef<Path>>(&mut self, path: P) {
self.repo.create_dir_all(path).unwrap();
}
pub fn create_device_file<P: AsRef<Path>>(&mut self, path: P, file: Rc<RefCell<dyn FileLike>>) {
self.device_files.insert(path.as_ref().to_path_buf(), file);
}
}
fn convert_to_absolute_path<P: AsRef<Path>>(path: P) -> PathBuf {
let path = path.as_ref();
if path.is_relative() {
std::path::PathBuf::from("/").join(path)
} else {
path.to_path_buf()
}
}
pub type Handle = i32;
#[derive(Debug, Fail)]
pub enum VfsError {
#[fail(display = "File with file descriptor \"{}\" does not exist.", _0)]
FileWithFileDescriptorNotExist(Handle),
#[fail(display = "File descriptor does not exist.")]
FileDescriptorNotExist(Handle),
#[fail(display = "Source file descriptor does not exist.")]
SourceFileDescriptorDoesNotExist,
#[fail(display = "Target file descriptor already exists.")]
TargetFileDescriptorAlreadyExists,
#[fail(display = "Could not get a mutable reference to the file because it is in use.")]
CouldNotGetMutableReferenceToFile,
}
#[derive(Debug, Fail)]
pub enum VfsAggregateError {
#[fail(display = "Entry error.")]
EntryError(std::io::Error),
#[fail(display = "IO error.")]
IoError(std::io::Error),
#[fail(display = "Zbox error.")]
ZboxError(zbox::Error),
#[fail(display = "Unsupported file type.")]
UnsupportedFileType,
}
impl std::convert::From<std::io::Error> for VfsAggregateError {
fn from(error: std::io::Error) -> VfsAggregateError {
VfsAggregateError::EntryError(error)
}
}
impl std::convert::From<zbox::Error> for VfsAggregateError {
fn from(error: zbox::Error) -> VfsAggregateError {
VfsAggregateError::ZboxError(error)
}
}

View File

@ -0,0 +1,57 @@
/// Represents the version of this header schema.
#[repr(u8)]
#[derive(Debug, PartialEq)]
pub enum HeaderVersion {
Version1 = 1,
}
/// Represents the compression type of the file data. Only Zstd or no-compression is supported.
#[repr(u8)]
#[derive(Debug, PartialEq)]
pub enum CompressionType {
NONE = 0,
ZSTD = 1,
}
/// Represents the type of archive. The only supported archive is the Tar format.
#[repr(u8)]
#[derive(Debug, PartialEq)]
pub enum ArchiveType {
TAR = 0,
}
// extract the header data from bytes
pub fn header_from_bytes(
bytes: &[u8],
) -> Result<(HeaderVersion, CompressionType, ArchiveType), HeaderError> {
if let Some(bytes) = bytes.get(..4) {
let version = match bytes[0] {
1 => HeaderVersion::Version1,
x => return Err(HeaderError::UnknownHeaderVersion(x)),
};
let compression_type = match bytes[1] {
0 => CompressionType::NONE,
1 => CompressionType::ZSTD,
x => return Err(HeaderError::UnknownCompressionType(x)),
};
let archive_type = match bytes[2] {
0 => ArchiveType::TAR,
x => return Err(HeaderError::UnknownArchiveType(x)),
};
Ok((version, compression_type, archive_type))
} else {
Err(HeaderError::HeaderTooSmall)
}
}
#[derive(Debug, Fail)]
pub enum HeaderError {
#[fail(display = "The version is not supported: \"{}\"", _0)]
UnknownHeaderVersion(u8),
#[fail(display = "The compression type is unknown: \"{}\"", _0)]
UnknownCompressionType(u8),
#[fail(display = "The archive type is unknown: \"{}\"", _0)]
UnknownArchiveType(u8),
#[fail(display = "The header is too small.")]
HeaderTooSmall,
}

View File

@ -0,0 +1,51 @@
use crate::vfs::file_like::{FileLike, Metadata};
use failure::Error;
use std::io;
pub struct VirtualFile(zbox::File);
impl VirtualFile {
pub fn new(file: zbox::File) -> Self {
VirtualFile(file)
}
}
impl FileLike for VirtualFile {
fn metadata(&self) -> Result<Metadata, Error> {
self.0
.metadata()
.map(|m| Metadata {
len: m.content_len(),
is_file: m.is_file(),
})
.map_err(|e: zbox::Error| e.into())
}
fn set_file_len(&mut self, len: usize) -> Result<(), failure::Error> {
self.0.set_len(len).map_err(|e| e.into())
}
}
impl io::Write for VirtualFile {
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
let result = self.0.write(buf)?;
self.0.finish().unwrap();
Ok(result)
}
fn flush(&mut self) -> Result<(), io::Error> {
self.0.flush()
}
}
impl io::Read for VirtualFile {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
self.0.read(buf)
}
}
impl io::Seek for VirtualFile {
fn seek(&mut self, pos: io::SeekFrom) -> Result<u64, io::Error> {
self.0.seek(pos)
}
}

View File

@ -0,0 +1,102 @@
//! Errors.
use libc::{c_char, c_int};
use std::cell::RefCell;
use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::ptr;
use std::slice;
thread_local! {
static LAST_ERROR: RefCell<Option<Box<Error>>> = RefCell::new(None);
}
pub(crate) fn update_last_error<E: Error + 'static>(err: E) {
LAST_ERROR.with(|prev| {
*prev.borrow_mut() = Some(Box::new(err));
});
}
/// Retrieve the most recent error, clearing it in the process.
pub(crate) fn take_last_error() -> Option<Box<Error>> {
LAST_ERROR.with(|prev| prev.borrow_mut().take())
}
/// Gets the length in bytes of the last error.
/// This can be used to dynamically allocate a buffer with the correct number of
/// bytes needed to store a message.
///
/// # Example
///
/// ```c
/// int error_len = wasmer_last_error_length();
/// char *error_str = malloc(error_len);
/// ```
#[no_mangle]
pub extern "C" fn wasmer_last_error_length() -> c_int {
LAST_ERROR.with(|prev| match *prev.borrow() {
Some(ref err) => err.to_string().len() as c_int + 1,
None => 0,
})
}
/// Stores the last error message into the provided buffer up to the given `length`.
/// The `length` parameter must be large enough to store the last error message.
///
/// Returns the length of the string in bytes.
/// Returns `-1` if an error occurs.
///
/// # Example
///
/// ```c
/// int error_len = wasmer_last_error_length();
/// char *error_str = malloc(error_len);
/// wasmer_last_error_message(error_str, error_len);
/// printf("Error str: `%s`\n", error_str);
/// ```
#[no_mangle]
pub unsafe extern "C" fn wasmer_last_error_message(buffer: *mut c_char, length: c_int) -> c_int {
if buffer.is_null() {
// buffer pointer is null
return -1;
}
let last_error = match take_last_error() {
Some(err) => err,
None => return 0,
};
let error_message = last_error.to_string();
let buffer = slice::from_raw_parts_mut(buffer as *mut u8, length as usize);
if error_message.len() >= buffer.len() {
// buffer to small for err message
return -1;
}
ptr::copy_nonoverlapping(
error_message.as_ptr(),
buffer.as_mut_ptr(),
error_message.len(),
);
// Add a trailing null so people using the string as a `char *` don't
// accidentally read into garbage.
buffer[error_message.len()] = 0;
error_message.len() as c_int
}
#[derive(Debug)]
pub(crate) struct CApiError {
pub(crate) msg: String,
}
impl Display for CApiError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", &self.msg)
}
}
impl Error for CApiError {}

View File

@ -0,0 +1,440 @@
//! Wasm exports.
use crate::{
error::{update_last_error, CApiError},
global::wasmer_global_t,
import::wasmer_import_func_t,
memory::wasmer_memory_t,
module::wasmer_module_t,
table::wasmer_table_t,
value::{wasmer_value, wasmer_value_t, wasmer_value_tag},
wasmer_byte_array, wasmer_result_t,
};
use libc::{c_int, uint32_t};
use std::{ptr, slice};
use wasmer_runtime::{Instance, Memory, Module, Value};
use wasmer_runtime_core::{export::Export, module::ExportIndex};
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_export_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_exports_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_export_func_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_export_descriptor_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_export_descriptors_t;
#[repr(C)]
#[derive(Clone, Copy)]
pub union wasmer_import_export_value {
pub func: *const wasmer_import_func_t,
pub table: *const wasmer_table_t,
pub memory: *const wasmer_memory_t,
pub global: *const wasmer_global_t,
}
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Clone)]
pub enum wasmer_import_export_kind {
WASM_FUNCTION,
WASM_GLOBAL,
WASM_MEMORY,
WASM_TABLE,
}
/// Gets export descriptors for the given module
///
/// The caller owns the object and should call `wasmer_export_descriptors_destroy` to free it.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_export_descriptors(
module: *const wasmer_module_t,
export_descriptors: *mut *mut wasmer_export_descriptors_t,
) {
let module = &*(module as *const Module);
let named_export_descriptors: Box<NamedExportDescriptors> = Box::new(NamedExportDescriptors(
module.info().exports.iter().map(|e| e.into()).collect(),
));
*export_descriptors =
Box::into_raw(named_export_descriptors) as *mut wasmer_export_descriptors_t;
}
pub struct NamedExportDescriptors(Vec<NamedExportDescriptor>);
/// Frees the memory for the given export descriptors
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_export_descriptors_destroy(
export_descriptors: *mut wasmer_export_descriptors_t,
) {
if !export_descriptors.is_null() {
unsafe { Box::from_raw(export_descriptors as *mut NamedExportDescriptors) };
}
}
/// Gets the length of the export descriptors
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_export_descriptors_len(
exports: *mut wasmer_export_descriptors_t,
) -> c_int {
if exports.is_null() {
return 0;
}
(*(exports as *mut NamedExportDescriptors)).0.len() as c_int
}
/// Gets export descriptor by index
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_export_descriptors_get(
export_descriptors: *mut wasmer_export_descriptors_t,
idx: c_int,
) -> *mut wasmer_export_descriptor_t {
if export_descriptors.is_null() {
return ptr::null_mut();
}
let named_export_descriptors = &mut *(export_descriptors as *mut NamedExportDescriptors);
&mut (*named_export_descriptors).0[idx as usize] as *mut NamedExportDescriptor
as *mut wasmer_export_descriptor_t
}
/// Gets name for the export descriptor
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_descriptor_name(
export_descriptor: *mut wasmer_export_descriptor_t,
) -> wasmer_byte_array {
let named_export_descriptor = &*(export_descriptor as *mut NamedExportDescriptor);
wasmer_byte_array {
bytes: named_export_descriptor.name.as_ptr(),
bytes_len: named_export_descriptor.name.len() as u32,
}
}
/// Gets export descriptor kind
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_descriptor_kind(
export: *mut wasmer_export_descriptor_t,
) -> wasmer_import_export_kind {
let named_export_descriptor = &*(export as *mut NamedExportDescriptor);
named_export_descriptor.kind.clone()
}
pub(crate) struct NamedExports(pub Vec<NamedExport>);
/// Frees the memory for the given exports
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_exports_destroy(exports: *mut wasmer_exports_t) {
if !exports.is_null() {
unsafe { Box::from_raw(exports as *mut NamedExports) };
}
}
/// Gets the length of the exports
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_exports_len(exports: *mut wasmer_exports_t) -> c_int {
if exports.is_null() {
return 0;
}
(*(exports as *mut NamedExports)).0.len() as c_int
}
/// Gets wasmer_export by index
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_exports_get(
exports: *mut wasmer_exports_t,
idx: c_int,
) -> *mut wasmer_export_t {
if exports.is_null() {
return ptr::null_mut();
}
let named_exports = &mut *(exports as *mut NamedExports);
&mut (*named_exports).0[idx as usize] as *mut NamedExport as *mut wasmer_export_t
}
/// Gets wasmer_export kind
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_kind(
export: *mut wasmer_export_t,
) -> wasmer_import_export_kind {
let named_export = &*(export as *mut NamedExport);
match named_export.export {
Export::Table(_) => wasmer_import_export_kind::WASM_TABLE,
Export::Function { .. } => wasmer_import_export_kind::WASM_FUNCTION,
Export::Global(_) => wasmer_import_export_kind::WASM_GLOBAL,
Export::Memory(_) => wasmer_import_export_kind::WASM_MEMORY,
}
}
/// Sets the result parameter to the arity of the params of the wasmer_export_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_func_params_arity(
func: *const wasmer_export_func_t,
result: *mut uint32_t,
) -> wasmer_result_t {
let named_export = &*(func as *const NamedExport);
let export = &named_export.export;
if let Export::Function { ref signature, .. } = *export {
*result = signature.params().len() as uint32_t;
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_export_func_params_arity".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Sets the params buffer to the parameter types of the given wasmer_export_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_func_params(
func: *const wasmer_export_func_t,
params: *mut wasmer_value_tag,
params_len: c_int,
) -> wasmer_result_t {
let named_export = &*(func as *const NamedExport);
let export = &named_export.export;
if let Export::Function { ref signature, .. } = *export {
let params: &mut [wasmer_value_tag] =
slice::from_raw_parts_mut(params, params_len as usize);
for (i, item) in signature.params().iter().enumerate() {
params[i] = item.into();
}
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_export_func_params".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Sets the returns buffer to the parameter types of the given wasmer_export_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_func_returns(
func: *const wasmer_export_func_t,
returns: *mut wasmer_value_tag,
returns_len: c_int,
) -> wasmer_result_t {
let named_export = &*(func as *const NamedExport);
let export = &named_export.export;
if let Export::Function { ref signature, .. } = *export {
let returns: &mut [wasmer_value_tag] =
slice::from_raw_parts_mut(returns, returns_len as usize);
for (i, item) in signature.returns().iter().enumerate() {
returns[i] = item.into();
}
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_export_func_returns".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Sets the result parameter to the arity of the returns of the wasmer_export_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_func_returns_arity(
func: *const wasmer_export_func_t,
result: *mut uint32_t,
) -> wasmer_result_t {
let named_export = &*(func as *const NamedExport);
let export = &named_export.export;
if let Export::Function { ref signature, .. } = *export {
*result = signature.returns().len() as uint32_t;
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_export_func_results_arity".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Gets export func from export
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_to_func(
export: *const wasmer_export_t,
) -> *const wasmer_export_func_t {
export as *const wasmer_export_func_t
}
/// Gets a memory pointer from an export pointer.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_to_memory(
export: *const wasmer_export_t,
memory: *mut *mut wasmer_memory_t,
) -> wasmer_result_t {
let named_export = &*(export as *const NamedExport);
let export = &named_export.export;
if let Export::Memory(exported_memory) = export {
*memory = exported_memory as *const Memory as *mut wasmer_memory_t;
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "cannot cast the `wasmer_export_t` pointer to a `wasmer_memory_t` \
pointer because it does not represent a memory export."
.to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Gets name from wasmer_export
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_export_name(export: *mut wasmer_export_t) -> wasmer_byte_array {
let named_export = &*(export as *mut NamedExport);
wasmer_byte_array {
bytes: named_export.name.as_ptr(),
bytes_len: named_export.name.len() as u32,
}
}
/// Calls a `func` with the provided parameters.
/// Results are set using the provided `results` pointer.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_export_func_call(
func: *const wasmer_export_func_t,
params: *const wasmer_value_t,
params_len: c_int,
results: *mut wasmer_value_t,
results_len: c_int,
) -> wasmer_result_t {
if func.is_null() {
update_last_error(CApiError {
msg: "func ptr is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
if params.is_null() {
update_last_error(CApiError {
msg: "params ptr is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
let params: &[wasmer_value_t] = slice::from_raw_parts(params, params_len as usize);
let params: Vec<Value> = params.iter().cloned().map(|x| x.into()).collect();
let named_export = &*(func as *mut NamedExport);
let results: &mut [wasmer_value_t] = slice::from_raw_parts_mut(results, results_len as usize);
let instance = &*named_export.instance;
let result = instance.call(&named_export.name, &params[..]);
match result {
Ok(results_vec) => {
if !results_vec.is_empty() {
let ret = match results_vec[0] {
Value::I32(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_I32,
value: wasmer_value { I32: x },
},
Value::I64(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_I64,
value: wasmer_value { I64: x },
},
Value::F32(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_F32,
value: wasmer_value { F32: x },
},
Value::F64(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_F64,
value: wasmer_value { F64: x },
},
};
results[0] = ret;
}
wasmer_result_t::WASMER_OK
}
Err(err) => {
update_last_error(err);
wasmer_result_t::WASMER_ERROR
}
}
}
impl From<(&std::string::String, &ExportIndex)> for NamedExportDescriptor {
fn from((name, export_index): (&String, &ExportIndex)) -> Self {
let kind = match *export_index {
ExportIndex::Memory(_) => wasmer_import_export_kind::WASM_MEMORY,
ExportIndex::Global(_) => wasmer_import_export_kind::WASM_GLOBAL,
ExportIndex::Table(_) => wasmer_import_export_kind::WASM_TABLE,
ExportIndex::Func(_) => wasmer_import_export_kind::WASM_FUNCTION,
};
NamedExportDescriptor {
name: name.clone(),
kind,
}
}
}
pub(crate) struct NamedExport {
pub(crate) name: String,
pub(crate) export: Export,
pub(crate) instance: *mut Instance,
}
pub(crate) struct NamedExportDescriptor {
name: String,
kind: wasmer_import_export_kind,
}

View File

@ -0,0 +1,70 @@
//! Wasm global.
use crate::value::{wasmer_value_t, wasmer_value_tag};
use wasmer_runtime::Global;
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_global_descriptor_t {
mutable: bool,
kind: wasmer_value_tag,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_global_t;
/// Creates a new Global and returns a pointer to it.
/// The caller owns the object and should call `wasmer_global_destroy` to free it.
#[no_mangle]
pub unsafe extern "C" fn wasmer_global_new(
value: wasmer_value_t,
mutable: bool,
) -> *mut wasmer_global_t {
let global = if mutable {
Global::new_mutable(value.into())
} else {
Global::new(value.into())
};
Box::into_raw(Box::new(global)) as *mut wasmer_global_t
}
/// Gets the value stored by the given Global
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_global_get(global: *mut wasmer_global_t) -> wasmer_value_t {
let global = unsafe { &*(global as *mut Global) };
let value: wasmer_value_t = global.get().into();
value
}
/// Sets the value stored by the given Global
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_global_set(global: *mut wasmer_global_t, value: wasmer_value_t) {
let global = unsafe { &*(global as *mut Global) };
global.set(value.into());
}
/// Returns a descriptor (type, mutability) of the given Global
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_global_get_descriptor(
global: *mut wasmer_global_t,
) -> wasmer_global_descriptor_t {
let global = unsafe { &*(global as *mut Global) };
let descriptor = global.descriptor();
wasmer_global_descriptor_t {
mutable: descriptor.mutable,
kind: descriptor.ty.into(),
}
}
/// Frees memory for the given Global
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_global_destroy(global: *mut wasmer_global_t) {
if !global.is_null() {
unsafe { Box::from_raw(global as *mut Global) };
}
}

View File

@ -0,0 +1,358 @@
//! Wasm imports.
use crate::{
error::{update_last_error, CApiError},
export::{wasmer_import_export_kind, wasmer_import_export_value},
module::wasmer_module_t,
value::wasmer_value_tag,
wasmer_byte_array, wasmer_result_t,
};
use libc::{c_int, uint32_t};
use std::{ffi::c_void, ptr, slice, sync::Arc};
use wasmer_runtime::Module;
use wasmer_runtime_core::{
export::{Context, Export, FuncPointer},
module::ImportName,
types::{FuncSig, Type},
};
#[repr(C)]
pub struct wasmer_import_t {
pub module_name: wasmer_byte_array,
pub import_name: wasmer_byte_array,
pub tag: wasmer_import_export_kind,
pub value: wasmer_import_export_value,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_import_func_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_import_descriptor_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_import_descriptors_t;
/// Gets import descriptors for the given module
///
/// The caller owns the object and should call `wasmer_import_descriptors_destroy` to free it.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_import_descriptors(
module: *const wasmer_module_t,
import_descriptors: *mut *mut wasmer_import_descriptors_t,
) {
let module = &*(module as *const Module);
let total_imports = module.info().imported_functions.len()
+ module.info().imported_tables.len()
+ module.info().imported_globals.len()
+ module.info().imported_memories.len();
let mut descriptors: Vec<NamedImportDescriptor> = Vec::with_capacity(total_imports);
for (
_index,
ImportName {
namespace_index,
name_index,
},
) in &module.info().imported_functions
{
let namespace = module.info().namespace_table.get(*namespace_index);
let name = module.info().name_table.get(*name_index);
descriptors.push(NamedImportDescriptor {
module: namespace.to_string(),
name: name.to_string(),
kind: wasmer_import_export_kind::WASM_FUNCTION,
});
}
for (
_index,
(
ImportName {
namespace_index,
name_index,
},
_,
),
) in &module.info().imported_tables
{
let namespace = module.info().namespace_table.get(*namespace_index);
let name = module.info().name_table.get(*name_index);
descriptors.push(NamedImportDescriptor {
module: namespace.to_string(),
name: name.to_string(),
kind: wasmer_import_export_kind::WASM_TABLE,
});
}
for (
_index,
(
ImportName {
namespace_index,
name_index,
},
_,
),
) in &module.info().imported_globals
{
let namespace = module.info().namespace_table.get(*namespace_index);
let name = module.info().name_table.get(*name_index);
descriptors.push(NamedImportDescriptor {
module: namespace.to_string(),
name: name.to_string(),
kind: wasmer_import_export_kind::WASM_GLOBAL,
});
}
for (
_index,
(
ImportName {
namespace_index,
name_index,
},
_,
),
) in &module.info().imported_memories
{
let namespace = module.info().namespace_table.get(*namespace_index);
let name = module.info().name_table.get(*name_index);
descriptors.push(NamedImportDescriptor {
module: namespace.to_string(),
name: name.to_string(),
kind: wasmer_import_export_kind::WASM_MEMORY,
});
}
let named_import_descriptors: Box<NamedImportDescriptors> =
Box::new(NamedImportDescriptors(descriptors));
*import_descriptors =
Box::into_raw(named_import_descriptors) as *mut wasmer_import_descriptors_t;
}
pub struct NamedImportDescriptors(Vec<NamedImportDescriptor>);
/// Frees the memory for the given import descriptors
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_import_descriptors_destroy(
import_descriptors: *mut wasmer_import_descriptors_t,
) {
if !import_descriptors.is_null() {
unsafe { Box::from_raw(import_descriptors as *mut NamedImportDescriptors) };
}
}
/// Gets the length of the import descriptors
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_import_descriptors_len(
exports: *mut wasmer_import_descriptors_t,
) -> c_int {
if exports.is_null() {
return 0;
}
(*(exports as *mut NamedImportDescriptors)).0.len() as c_int
}
/// Gets import descriptor by index
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_import_descriptors_get(
import_descriptors: *mut wasmer_import_descriptors_t,
idx: c_int,
) -> *mut wasmer_import_descriptor_t {
if import_descriptors.is_null() {
return ptr::null_mut();
}
let named_import_descriptors = &mut *(import_descriptors as *mut NamedImportDescriptors);
&mut (*named_import_descriptors).0[idx as usize] as *mut NamedImportDescriptor
as *mut wasmer_import_descriptor_t
}
/// Gets name for the import descriptor
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_descriptor_name(
import_descriptor: *mut wasmer_import_descriptor_t,
) -> wasmer_byte_array {
let named_import_descriptor = &*(import_descriptor as *mut NamedImportDescriptor);
wasmer_byte_array {
bytes: named_import_descriptor.name.as_ptr(),
bytes_len: named_import_descriptor.name.len() as u32,
}
}
/// Gets module name for the import descriptor
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_descriptor_module_name(
import_descriptor: *mut wasmer_import_descriptor_t,
) -> wasmer_byte_array {
let named_import_descriptor = &*(import_descriptor as *mut NamedImportDescriptor);
wasmer_byte_array {
bytes: named_import_descriptor.module.as_ptr(),
bytes_len: named_import_descriptor.module.len() as u32,
}
}
/// Gets export descriptor kind
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_descriptor_kind(
export: *mut wasmer_import_descriptor_t,
) -> wasmer_import_export_kind {
let named_import_descriptor = &*(export as *mut NamedImportDescriptor);
named_import_descriptor.kind.clone()
}
/// Sets the result parameter to the arity of the params of the wasmer_import_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_func_params_arity(
func: *const wasmer_import_func_t,
result: *mut uint32_t,
) -> wasmer_result_t {
let export = &*(func as *const Export);
if let Export::Function { ref signature, .. } = *export {
*result = signature.params().len() as uint32_t;
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_import_func_params_arity".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Creates new func
///
/// The caller owns the object and should call `wasmer_import_func_destroy` to free it.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_func_new(
func: extern "C" fn(data: *mut c_void),
params: *const wasmer_value_tag,
params_len: c_int,
returns: *const wasmer_value_tag,
returns_len: c_int,
) -> *mut wasmer_import_func_t {
let params: &[wasmer_value_tag] = slice::from_raw_parts(params, params_len as usize);
let params: Vec<Type> = params.iter().cloned().map(|x| x.into()).collect();
let returns: &[wasmer_value_tag] = slice::from_raw_parts(returns, returns_len as usize);
let returns: Vec<Type> = returns.iter().cloned().map(|x| x.into()).collect();
let export = Box::new(Export::Function {
func: FuncPointer::new(func as _),
ctx: Context::Internal,
signature: Arc::new(FuncSig::new(params, returns)),
});
Box::into_raw(export) as *mut wasmer_import_func_t
}
/// Sets the params buffer to the parameter types of the given wasmer_import_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_func_params(
func: *const wasmer_import_func_t,
params: *mut wasmer_value_tag,
params_len: c_int,
) -> wasmer_result_t {
let export = &*(func as *const Export);
if let Export::Function { ref signature, .. } = *export {
let params: &mut [wasmer_value_tag] =
slice::from_raw_parts_mut(params, params_len as usize);
for (i, item) in signature.params().iter().enumerate() {
params[i] = item.into();
}
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_import_func_params".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Sets the returns buffer to the parameter types of the given wasmer_import_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_func_returns(
func: *const wasmer_import_func_t,
returns: *mut wasmer_value_tag,
returns_len: c_int,
) -> wasmer_result_t {
let export = &*(func as *const Export);
if let Export::Function { ref signature, .. } = *export {
let returns: &mut [wasmer_value_tag] =
slice::from_raw_parts_mut(returns, returns_len as usize);
for (i, item) in signature.returns().iter().enumerate() {
returns[i] = item.into();
}
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_import_func_returns".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Sets the result parameter to the arity of the returns of the wasmer_import_func_t
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
#[allow(clippy::cast_ptr_alignment)]
pub unsafe extern "C" fn wasmer_import_func_returns_arity(
func: *const wasmer_import_func_t,
result: *mut uint32_t,
) -> wasmer_result_t {
let export = &*(func as *const Export);
if let Export::Function { ref signature, .. } = *export {
*result = signature.returns().len() as uint32_t;
wasmer_result_t::WASMER_OK
} else {
update_last_error(CApiError {
msg: "func ptr error in wasmer_import_func_results_arity".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
/// Frees memory for the given Func
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_import_func_destroy(func: *mut wasmer_import_func_t) {
if !func.is_null() {
unsafe { Box::from_raw(func as *mut Export) };
}
}
struct NamedImportDescriptor {
module: String,
name: String,
kind: wasmer_import_export_kind,
}

View File

@ -0,0 +1,256 @@
//! Wasm instance.
use crate::{
error::{update_last_error, CApiError},
export::{wasmer_exports_t, wasmer_import_export_kind, NamedExport, NamedExports},
import::wasmer_import_t,
memory::wasmer_memory_t,
value::{wasmer_value, wasmer_value_t, wasmer_value_tag},
wasmer_result_t,
};
use libc::{c_char, c_int, c_void, uint32_t, uint8_t};
use std::{collections::HashMap, ffi::CStr, slice};
use wasmer_runtime::{Ctx, Global, ImportObject, Instance, Memory, Table, Value};
use wasmer_runtime_core::{export::Export, import::Namespace};
#[repr(C)]
pub struct wasmer_instance_t;
#[repr(C)]
pub struct wasmer_instance_context_t;
/// Creates a new Instance from the given wasm bytes and imports.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instantiate(
instance: *mut *mut wasmer_instance_t,
wasm_bytes: *mut uint8_t,
wasm_bytes_len: uint32_t,
imports: *mut wasmer_import_t,
imports_len: c_int,
) -> wasmer_result_t {
if wasm_bytes.is_null() {
update_last_error(CApiError {
msg: "wasm bytes ptr is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
let imports: &[wasmer_import_t] = slice::from_raw_parts(imports, imports_len as usize);
let mut import_object = ImportObject::new();
let mut namespaces = HashMap::new();
for import in imports {
let module_name = slice::from_raw_parts(
import.module_name.bytes,
import.module_name.bytes_len as usize,
);
let module_name = if let Ok(s) = std::str::from_utf8(module_name) {
s
} else {
update_last_error(CApiError {
msg: "error converting module name to string".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
};
let import_name = slice::from_raw_parts(
import.import_name.bytes,
import.import_name.bytes_len as usize,
);
let import_name = if let Ok(s) = std::str::from_utf8(import_name) {
s
} else {
update_last_error(CApiError {
msg: "error converting import_name to string".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
};
let namespace = namespaces.entry(module_name).or_insert_with(Namespace::new);
let export = match import.tag {
wasmer_import_export_kind::WASM_MEMORY => {
let mem = import.value.memory as *mut Memory;
Export::Memory((&*mem).clone())
}
wasmer_import_export_kind::WASM_FUNCTION => {
let func_export = import.value.func as *mut Export;
(&*func_export).clone()
}
wasmer_import_export_kind::WASM_GLOBAL => {
let global = import.value.global as *mut Global;
Export::Global((&*global).clone())
}
wasmer_import_export_kind::WASM_TABLE => {
let table = import.value.table as *mut Table;
Export::Table((&*table).clone())
}
};
namespace.insert(import_name, export);
}
for (module_name, namespace) in namespaces.into_iter() {
import_object.register(module_name, namespace);
}
let bytes: &[u8] = slice::from_raw_parts_mut(wasm_bytes, wasm_bytes_len as usize);
let result = wasmer_runtime::instantiate(bytes, &import_object);
let new_instance = match result {
Ok(instance) => instance,
Err(_error) => {
// TODO the trait bound `wasmer_runtime::error::Error: std::error::Error` is not satisfied
//update_last_error(error);
update_last_error(CApiError {
msg: "error instantiating".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
};
*instance = Box::into_raw(Box::new(new_instance)) as *mut wasmer_instance_t;
wasmer_result_t::WASMER_OK
}
/// Calls an instances exported function by `name` with the provided parameters.
/// Results are set using the provided `results` pointer.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_call(
instance: *mut wasmer_instance_t,
name: *const c_char,
params: *const wasmer_value_t,
params_len: c_int,
results: *mut wasmer_value_t,
results_len: c_int,
) -> wasmer_result_t {
if instance.is_null() {
update_last_error(CApiError {
msg: "instance ptr is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
if name.is_null() {
update_last_error(CApiError {
msg: "name ptr is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
if params.is_null() {
update_last_error(CApiError {
msg: "params ptr is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
let params: &[wasmer_value_t] = slice::from_raw_parts(params, params_len as usize);
let params: Vec<Value> = params.iter().cloned().map(|x| x.into()).collect();
let func_name_c = CStr::from_ptr(name);
let func_name_r = func_name_c.to_str().unwrap();
let results: &mut [wasmer_value_t] = slice::from_raw_parts_mut(results, results_len as usize);
let result = (&*(instance as *mut Instance)).call(func_name_r, &params[..]);
match result {
Ok(results_vec) => {
if !results_vec.is_empty() {
let ret = match results_vec[0] {
Value::I32(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_I32,
value: wasmer_value { I32: x },
},
Value::I64(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_I64,
value: wasmer_value { I64: x },
},
Value::F32(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_F32,
value: wasmer_value { F32: x },
},
Value::F64(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_F64,
value: wasmer_value { F64: x },
},
};
results[0] = ret;
}
wasmer_result_t::WASMER_OK
}
Err(err) => {
update_last_error(err);
wasmer_result_t::WASMER_ERROR
}
}
}
/// Gets Exports for the given instance
///
/// The caller owns the object and should call `wasmer_exports_destroy` to free it.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_instance_exports(
instance: *mut wasmer_instance_t,
exports: *mut *mut wasmer_exports_t,
) {
let instance_ref = &mut *(instance as *mut Instance);
let mut exports_vec: Vec<NamedExport> = Vec::with_capacity(instance_ref.exports().count());
for (name, export) in instance_ref.exports() {
exports_vec.push(NamedExport {
name: name.clone(),
export: export.clone(),
instance: instance as *mut Instance,
});
}
let named_exports: Box<NamedExports> = Box::new(NamedExports(exports_vec));
*exports = Box::into_raw(named_exports) as *mut wasmer_exports_t;
}
/// Sets the `data` field of the instance context. This context will be
/// passed to all imported function for instance.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_instance_context_data_set(
instance: *mut wasmer_instance_t,
data_ptr: *mut c_void,
) {
let instance_ref = unsafe { &mut *(instance as *mut Instance) };
instance_ref.context_mut().data = data_ptr;
}
/// Gets the memory within the context at the index `memory_idx`.
/// The index is always 0 until multiple memories are supported.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_instance_context_memory(
ctx: *const wasmer_instance_context_t,
_memory_idx: uint32_t,
) -> *const wasmer_memory_t {
let ctx = unsafe { &*(ctx as *const Ctx) };
let memory = ctx.memory(0);
memory as *const Memory as *const wasmer_memory_t
}
/// Gets the `data` field within the context.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_instance_context_data_get(
ctx: *const wasmer_instance_context_t,
) -> *mut c_void {
let ctx = unsafe { &*(ctx as *const Ctx) };
ctx.data
}
/// Frees memory for the given Instance
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_instance_destroy(instance: *mut wasmer_instance_t) {
if !instance.is_null() {
unsafe { Box::from_raw(instance as *mut Instance) };
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,108 @@
//! Wasm memory.o
use crate::{error::update_last_error, wasmer_limits_t, wasmer_result_t};
use libc::{uint32_t, uint8_t};
use std::cell::Cell;
use wasmer_runtime::Memory;
use wasmer_runtime_core::{
types::MemoryDescriptor,
units::{Bytes, Pages},
};
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_memory_t;
/// Creates a new Memory for the given descriptor and initializes the given
/// pointer to pointer to a pointer to the new memory.
///
/// The caller owns the object and should call `wasmer_memory_destroy` to free it.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
pub unsafe extern "C" fn wasmer_memory_new(
memory: *mut *mut wasmer_memory_t,
limits: wasmer_limits_t,
) -> wasmer_result_t {
let max = if limits.max.has_some {
Some(Pages(limits.max.some))
} else {
None
};
let desc = MemoryDescriptor {
minimum: Pages(limits.min),
maximum: max,
shared: false,
};
let result = Memory::new(desc);
let new_memory = match result {
Ok(memory) => memory,
Err(error) => {
update_last_error(error);
return wasmer_result_t::WASMER_ERROR;
}
};
*memory = Box::into_raw(Box::new(new_memory)) as *mut wasmer_memory_t;
wasmer_result_t::WASMER_OK
}
/// Grows a Memory by the given number of pages.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_memory_grow(
memory: *mut wasmer_memory_t,
delta: uint32_t,
) -> wasmer_result_t {
let memory = unsafe { &*(memory as *mut Memory) };
let delta_result = memory.grow(Pages(delta));
match delta_result {
Ok(_) => wasmer_result_t::WASMER_OK,
Err(grow_error) => {
update_last_error(grow_error);
wasmer_result_t::WASMER_ERROR
}
}
}
/// Returns the current length in pages of the given memory
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_memory_length(memory: *const wasmer_memory_t) -> uint32_t {
let memory = unsafe { &*(memory as *const Memory) };
let Pages(len) = memory.size();
len
}
/// Gets the start pointer to the bytes within a Memory
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_memory_data(mem: *const wasmer_memory_t) -> *mut uint8_t {
let memory = unsafe { &*(mem as *const Memory) };
memory.view::<u8>()[..].as_ptr() as *mut Cell<u8> as *mut u8
}
/// Gets the size in bytes of a Memory
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_memory_data_length(mem: *mut wasmer_memory_t) -> uint32_t {
let memory = mem as *mut Memory;
let Bytes(len) = unsafe { (*memory).size().bytes() };
len as uint32_t
}
/// Frees memory for the given Memory
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_memory_destroy(memory: *mut wasmer_memory_t) {
if !memory.is_null() {
unsafe { Box::from_raw(memory as *mut Memory) };
}
}

View File

@ -0,0 +1,289 @@
//! Wasm module.
use crate::{
error::{update_last_error, CApiError},
export::wasmer_import_export_kind,
import::wasmer_import_t,
instance::wasmer_instance_t,
wasmer_byte_array, wasmer_result_t,
};
use libc::{c_int, uint32_t, uint8_t};
use std::{collections::HashMap, slice};
use wasmer_runtime::{compile, default_compiler, Global, ImportObject, Memory, Module, Table};
use wasmer_runtime_core::{cache::Artifact, export::Export, import::Namespace, load_cache_with};
#[repr(C)]
pub struct wasmer_module_t;
#[repr(C)]
pub struct wasmer_serialized_module_t;
/// Creates a new Module from the given wasm bytes.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_compile(
module: *mut *mut wasmer_module_t,
wasm_bytes: *mut uint8_t,
wasm_bytes_len: uint32_t,
) -> wasmer_result_t {
let bytes: &[u8] = slice::from_raw_parts_mut(wasm_bytes, wasm_bytes_len as usize);
let result = compile(bytes);
let new_module = match result {
Ok(instance) => instance,
Err(error) => {
update_last_error(error);
return wasmer_result_t::WASMER_ERROR;
}
};
*module = Box::into_raw(Box::new(new_module)) as *mut wasmer_module_t;
wasmer_result_t::WASMER_OK
}
/// Returns true for valid wasm bytes and false for invalid bytes
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_validate(
wasm_bytes: *const uint8_t,
wasm_bytes_len: uint32_t,
) -> bool {
if wasm_bytes.is_null() {
return false;
}
let bytes: &[u8] = slice::from_raw_parts(wasm_bytes, wasm_bytes_len as usize);
wasmer_runtime_core::validate(bytes)
}
/// Creates a new Instance from the given module and imports.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_module_instantiate(
module: *const wasmer_module_t,
instance: *mut *mut wasmer_instance_t,
imports: *mut wasmer_import_t,
imports_len: c_int,
) -> wasmer_result_t {
let imports: &[wasmer_import_t] = slice::from_raw_parts(imports, imports_len as usize);
let mut import_object = ImportObject::new();
let mut namespaces = HashMap::new();
for import in imports {
let module_name = slice::from_raw_parts(
import.module_name.bytes,
import.module_name.bytes_len as usize,
);
let module_name = if let Ok(s) = std::str::from_utf8(module_name) {
s
} else {
update_last_error(CApiError {
msg: "error converting module name to string".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
};
let import_name = slice::from_raw_parts(
import.import_name.bytes,
import.import_name.bytes_len as usize,
);
let import_name = if let Ok(s) = std::str::from_utf8(import_name) {
s
} else {
update_last_error(CApiError {
msg: "error converting import_name to string".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
};
let namespace = namespaces.entry(module_name).or_insert_with(Namespace::new);
let export = match import.tag {
wasmer_import_export_kind::WASM_MEMORY => {
let mem = import.value.memory as *mut Memory;
Export::Memory((&*mem).clone())
}
wasmer_import_export_kind::WASM_FUNCTION => {
let func_export = import.value.func as *mut Export;
(&*func_export).clone()
}
wasmer_import_export_kind::WASM_GLOBAL => {
let global = import.value.global as *mut Global;
Export::Global((&*global).clone())
}
wasmer_import_export_kind::WASM_TABLE => {
let table = import.value.table as *mut Table;
Export::Table((&*table).clone())
}
};
namespace.insert(import_name, export);
}
for (module_name, namespace) in namespaces.into_iter() {
import_object.register(module_name, namespace);
}
let module = &*(module as *const Module);
let new_instance = if let Ok(res) = module.instantiate(&import_object) {
res
} else {
update_last_error(CApiError {
msg: "error instantiating from module".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
};
*instance = Box::into_raw(Box::new(new_instance)) as *mut wasmer_instance_t;
wasmer_result_t::WASMER_OK
}
/// Serialize the given Module.
///
/// The caller owns the object and should call `wasmer_serialized_module_destroy` to free it.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_module_serialize(
serialized_module: *mut *mut wasmer_serialized_module_t,
module: *const wasmer_module_t,
) -> wasmer_result_t {
let module = &*(module as *const Module);
match module.cache() {
Ok(artifact) => match artifact.serialize() {
Ok(serialized_artifact) => {
*serialized_module = Box::into_raw(Box::new(serialized_artifact)) as _;
wasmer_result_t::WASMER_OK
}
Err(_) => {
update_last_error(CApiError {
msg: "Failed to serialize the module artifact".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
},
Err(_) => {
update_last_error(CApiError {
msg: "Failed to serialize the module".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
}
/// Get bytes of the serialized module.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_serialized_module_bytes(
serialized_module: *const wasmer_serialized_module_t,
) -> wasmer_byte_array {
let serialized_module = &*(serialized_module as *const &[u8]);
wasmer_byte_array {
bytes: serialized_module.as_ptr(),
bytes_len: serialized_module.len() as u32,
}
}
/// Transform a sequence of bytes into a serialized module.
///
/// The caller owns the object and should call `wasmer_serialized_module_destroy` to free it.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_serialized_module_from_bytes(
serialized_module: *mut *mut wasmer_serialized_module_t,
serialized_module_bytes: *const uint8_t,
serialized_module_bytes_length: uint32_t,
) -> wasmer_result_t {
if serialized_module.is_null() {
update_last_error(CApiError {
msg: "`serialized_module_bytes` pointer is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
let serialized_module_bytes: &[u8] = slice::from_raw_parts(
serialized_module_bytes,
serialized_module_bytes_length as usize,
);
*serialized_module = Box::into_raw(Box::new(serialized_module_bytes)) as _;
wasmer_result_t::WASMER_OK
}
/// Deserialize the given serialized module.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub unsafe extern "C" fn wasmer_module_deserialize(
module: *mut *mut wasmer_module_t,
serialized_module: *const wasmer_serialized_module_t,
) -> wasmer_result_t {
if serialized_module.is_null() {
update_last_error(CApiError {
msg: "`serialized_module` pointer is null".to_string(),
});
return wasmer_result_t::WASMER_ERROR;
}
let serialized_module: &[u8] = &*(serialized_module as *const &[u8]);
match Artifact::deserialize(serialized_module) {
Ok(artifact) => match load_cache_with(artifact, default_compiler()) {
Ok(deserialized_module) => {
*module = Box::into_raw(Box::new(deserialized_module)) as _;
wasmer_result_t::WASMER_OK
}
Err(_) => {
update_last_error(CApiError {
msg: "Failed to compile the serialized module".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
},
Err(_) => {
update_last_error(CApiError {
msg: "Failed to deserialize the module".to_string(),
});
wasmer_result_t::WASMER_ERROR
}
}
}
/// Frees memory for the given serialized Module.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_serialized_module_destroy(
serialized_module: *mut wasmer_serialized_module_t,
) {
if !serialized_module.is_null() {
unsafe { Box::from_raw(serialized_module as *mut &[u8]) };
}
}
/// Frees memory for the given Module
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_module_destroy(module: *mut wasmer_module_t) {
if !module.is_null() {
unsafe { Box::from_raw(module as *mut Module) };
}
}

View File

@ -0,0 +1,86 @@
//! Wasm tables.
use crate::{error::update_last_error, wasmer_limits_t, wasmer_result_t};
use libc::uint32_t;
use wasmer_runtime::Table;
use wasmer_runtime_core::types::{ElementType, TableDescriptor};
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_table_t;
/// Creates a new Table for the given descriptor and initializes the given
/// pointer to pointer to a pointer to the new Table.
///
/// The caller owns the object and should call `wasmer_table_destroy` to free it.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[no_mangle]
pub unsafe extern "C" fn wasmer_table_new(
table: *mut *mut wasmer_table_t,
limits: wasmer_limits_t,
) -> wasmer_result_t {
let max = if limits.max.has_some {
Some(limits.max.some)
} else {
None
};
let desc = TableDescriptor {
element: ElementType::Anyfunc,
minimum: limits.min,
maximum: max,
};
let result = Table::new(desc);
let new_table = match result {
Ok(table) => table,
Err(error) => {
update_last_error(error);
return wasmer_result_t::WASMER_ERROR;
}
};
*table = Box::into_raw(Box::new(new_table)) as *mut wasmer_table_t;
wasmer_result_t::WASMER_OK
}
/// Grows a Table by the given number of elements.
///
/// Returns `wasmer_result_t::WASMER_OK` upon success.
///
/// Returns `wasmer_result_t::WASMER_ERROR` upon failure. Use `wasmer_last_error_length`
/// and `wasmer_last_error_message` to get an error message.
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_table_grow(
table: *mut wasmer_table_t,
delta: uint32_t,
) -> wasmer_result_t {
let table = unsafe { &*(table as *mut Table) };
let delta_result = table.grow(delta);
match delta_result {
Ok(_) => wasmer_result_t::WASMER_OK,
Err(grow_error) => {
update_last_error(grow_error);
wasmer_result_t::WASMER_ERROR
}
}
}
/// Returns the current length of the given Table
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_table_length(table: *mut wasmer_table_t) -> uint32_t {
let table = unsafe { &*(table as *mut Table) };
table.size()
}
/// Frees memory for the given Table
#[allow(clippy::cast_ptr_alignment)]
#[no_mangle]
pub extern "C" fn wasmer_table_destroy(table: *mut wasmer_table_t) {
if !table.is_null() {
unsafe { Box::from_raw(table as *mut Table) };
}
}

View File

@ -0,0 +1,119 @@
//! Wasm values.
use libc::{int32_t, int64_t};
use wasmer_runtime::Value;
use wasmer_runtime_core::types::Type;
#[allow(non_camel_case_types)]
#[repr(u32)]
#[derive(Clone)]
pub enum wasmer_value_tag {
WASM_I32,
WASM_I64,
WASM_F32,
WASM_F64,
}
#[repr(C)]
#[derive(Clone, Copy)]
#[allow(non_snake_case)]
pub union wasmer_value {
pub I32: int32_t,
pub I64: int64_t,
pub F32: f32,
pub F64: f64,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasmer_value_t {
pub tag: wasmer_value_tag,
pub value: wasmer_value,
}
impl From<wasmer_value_t> for Value {
fn from(v: wasmer_value_t) -> Self {
unsafe {
#[allow(unreachable_patterns, non_snake_case)]
match v {
wasmer_value_t {
tag: wasmer_value_tag::WASM_I32,
value: wasmer_value { I32 },
} => Value::I32(I32),
wasmer_value_t {
tag: wasmer_value_tag::WASM_I64,
value: wasmer_value { I64 },
} => Value::I64(I64),
wasmer_value_t {
tag: wasmer_value_tag::WASM_F32,
value: wasmer_value { F32 },
} => Value::F32(F32),
wasmer_value_t {
tag: wasmer_value_tag::WASM_F64,
value: wasmer_value { F64 },
} => Value::F64(F64),
_ => panic!("not implemented"),
}
}
}
}
impl From<Value> for wasmer_value_t {
fn from(val: Value) -> Self {
match val {
Value::I32(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_I32,
value: wasmer_value { I32: x },
},
Value::I64(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_I64,
value: wasmer_value { I64: x },
},
Value::F32(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_F32,
value: wasmer_value { F32: x },
},
Value::F64(x) => wasmer_value_t {
tag: wasmer_value_tag::WASM_F64,
value: wasmer_value { F64: x },
},
}
}
}
impl From<Type> for wasmer_value_tag {
fn from(ty: Type) -> Self {
#[allow(unreachable_patterns)]
match ty {
Type::I32 => wasmer_value_tag::WASM_I32,
Type::I64 => wasmer_value_tag::WASM_I64,
Type::F32 => wasmer_value_tag::WASM_F32,
Type::F64 => wasmer_value_tag::WASM_F64,
_ => panic!("not implemented"),
}
}
}
impl From<wasmer_value_tag> for Type {
fn from(v: wasmer_value_tag) -> Self {
#[allow(unreachable_patterns)]
match v {
wasmer_value_tag::WASM_I32 => Type::I32,
wasmer_value_tag::WASM_I64 => Type::I64,
wasmer_value_tag::WASM_F32 => Type::F32,
wasmer_value_tag::WASM_F64 => Type::F64,
_ => panic!("not implemented"),
}
}
}
impl From<&wasmer_runtime::wasm::Type> for wasmer_value_tag {
fn from(ty: &Type) -> Self {
match *ty {
Type::I32 => wasmer_value_tag::WASM_I32,
Type::I64 => wasmer_value_tag::WASM_I64,
Type::F32 => wasmer_value_tag::WASM_F32,
Type::F64 => wasmer_value_tag::WASM_F64,
}
}
}

View File

@ -43,8 +43,8 @@ winapi = { version = "0.3", features = ["memoryapi"] }
[dev-dependencies]
field-offset = "0.1.1"
[build-dependencies]
blake2b_simd = "0.4.1"
[features]
debug = []
[build-dependencies]
blake2b_simd = "0.4.1"

View File

@ -0,0 +1,31 @@
<p align="center">
<a href="https://wasmer.io" target="_blank" rel="noopener noreferrer">
<img width="400" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/logo.png" alt="Wasmer logo">
</a>
</p>
<p align="center">
<a href="https://circleci.com/gh/wasmerio/wasmer/">
<img src="https://img.shields.io/circleci/project/github/wasmerio/wasmer/master.svg" alt="Build Status">
</a>
<a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License">
</a>
<a href="https://spectrum.chat/wasmer">
<img src="https://withspectrum.github.io/badge/badge.svg" alt="Join the Wasmer Community">
</a>
<a href="https://crates.io/crates/wasmer-runtime-core">
<img src="https://img.shields.io/crates/d/wasmer-runtime-core.svg" alt="Number of downloads from crates.io">
</a>
<a href="https://docs.rs/wasmer-runtime-core">
<img src="https://docs.rs/wasmer-runtime-core/badge.svg" alt="Read our API documentation">
</a>
</p>
# Wasmer Runtime Core
Wasmer is a standalone JIT WebAssembly runtime, aiming to be fully
compatible with Emscripten, Rust and Go. [Learn
more](https://github.com/wasmerio/wasmer).
This crate represents the core of the runtime.

View File

@ -8,6 +8,7 @@ pub type LinkResult<T> = std::result::Result<T, Vec<LinkError>>;
pub type RuntimeResult<T> = std::result::Result<T, RuntimeError>;
pub type CallResult<T> = std::result::Result<T, CallError>;
pub type ResolveResult<T> = std::result::Result<T, ResolveError>;
pub type ParseResult<T> = std::result::Result<T, ParseError>;
/// This is returned when the chosen compiler is unable to
/// successfully compile the provided webassembly module into
@ -445,3 +446,14 @@ impl Into<GrowError> for MemoryProtectionError {
GrowError::CouldNotProtectMemory(self)
}
}
#[derive(Debug)]
pub enum ParseError {
BinaryReadError,
}
impl From<wasmparser::BinaryReaderError> for ParseError {
fn from(_: wasmparser::BinaryReaderError) -> Self {
ParseError::BinaryReadError
}
}

View File

@ -69,7 +69,11 @@ pub fn compile_with(
let token = backend::Token::generate();
compiler
.compile(wasm, Default::default(), token)
.map(|inner| module::Module::new(Arc::new(inner)))
.map(|mut inner| {
let inner_info: &mut crate::module::ModuleInfo = &mut inner.info;
inner_info.import_custom_sections(wasm).unwrap();
module::Module::new(Arc::new(inner))
})
}
/// The same as `compile_with` but changes the compiler behavior

View File

@ -59,6 +59,26 @@ pub struct ModuleInfo {
/// Symbol information from emscripten
pub em_symbol_map: Option<HashMap<u32, String>>,
pub custom_sections: HashMap<String, Vec<u8>>,
}
impl ModuleInfo {
pub fn import_custom_sections(&mut self, wasm: &[u8]) -> crate::error::ParseResult<()> {
let mut parser = wasmparser::ModuleReader::new(wasm)?;
while !parser.eof() {
let section = parser.read()?;
if let wasmparser::SectionCode::Custom { name, kind: _ } = section.code {
let mut reader = section.get_binary_reader();
let len = reader.bytes_remaining();
let bytes = reader.read_bytes(len)?;
let data = bytes.to_vec();
let name = String::from_utf8_lossy(name).to_string();
self.custom_sections.insert(name, data);
}
}
Ok(())
}
}
/// A compiled WebAssembly module.

View File

@ -547,7 +547,7 @@ mod vm_ctx_tests {
use crate::backend::{
sys::Memory, Backend, CacheGen, FuncResolver, ProtectedCaller, Token, UserTrapper,
};
use crate::cache::{Error as CacheError, WasmHash};
use crate::cache::Error as CacheError;
use crate::error::RuntimeResult;
use crate::types::{FuncIndex, LocalFuncIndex, Value};
use hashbrown::HashMap;
@ -617,6 +617,8 @@ mod vm_ctx_tests {
name_table: StringTable::new(),
em_symbol_map: None,
custom_sections: HashMap::new(),
},
}
}

View File

@ -1,12 +1,41 @@
# Wasmer-Runtime
<p align="center">
<a href="https://wasmer.io" target="_blank" rel="noopener noreferrer">
<img width="400" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/logo.png" alt="Wasmer logo">
</a>
</p>
Wasmer-runtime is a library that makes embedding WebAssembly
in your application easy, efficient, and safe.
<p align="center">
<a href="https://circleci.com/gh/wasmerio/wasmer/">
<img src="https://img.shields.io/circleci/project/github/wasmerio/wasmer/master.svg" alt="Build Status">
</a>
<a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License">
</a>
<a href="https://spectrum.chat/wasmer">
<img src="https://withspectrum.github.io/badge/badge.svg" alt="Join the Wasmer Community">
</a>
<a href="https://crates.io/crates/wasmer-runtime">
<img src="https://img.shields.io/crates/d/wasmer-runtime.svg" alt="Number of downloads from crates.io">
</a>
<a href="https://docs.rs/wasmer-runtime">
<img src="https://docs.rs/wasmer-runtime/badge.svg" alt="Read our API documentation">
</a>
</p>
# How to use Wasmer-Runtime
# Wasmer Runtime
The easiest way is to use the [`instantiate`] function to create an [`Instance`].
Then you can use [`call`] or [`func`] and then [`call`][func.call] to call an exported function safely.
Wasmer is a standalone JIT WebAssembly runtime, aiming to be fully
compatible with Emscripten, Rust and Go. [Learn
more](https://github.com/wasmerio/wasmer).
This crate represents the high-level runtime API, making embedding
WebAssembly in your application easy, efficient, and safe.
## How to use Wasmer Runtime
The easiest way is to use the [`instantiate`] function to create an
[`Instance`]. Then you can use [`call`] or [`func`] and then
[`call`][func.call] to call an exported function safely.
[`instantiate`]: https://docs.rs/wasmer-runtime/*/wasmer_runtime/fn.instantiate.html
[`Instance`]: https://docs.rs/wasmer-runtime/*/wasmer_runtime/struct.Instance.html
@ -14,7 +43,7 @@ Then you can use [`call`] or [`func`] and then [`call`][func.call] to call an ex
[`func`]: https://docs.rs/wasmer-runtime/*/wasmer_runtime/struct.Instance.html#method.func
[func.call]: https://docs.rs/wasmer-runtime/*/wasmer_runtime/struct.Function.html#method.call
## Here's an example:
## Example
Given this WebAssembly:
@ -27,7 +56,7 @@ Given this WebAssembly:
i32.add))
```
compiled into wasm bytecode, we can call the exported "add_one" function:
compiled into Wasm bytecode, we can call the exported `add_one` function:
```rust
static WASM: &'static [u8] = &[
@ -63,13 +92,14 @@ fn main() -> error::Result<()> {
}
```
# Additional Notes:
## Additional Notes
The `wasmer-runtime` is build to support compiler multiple backends.
Currently, we support the [Cranelift] compiler with the [`wasmer-clif-backend`] crate.
The `wasmer-runtime` crate is build to support multiple compiler
backends. Currently, we support the [Cranelift] compiler with the
[`wasmer-clif-backend`] crate by default.
You can specify the compiler you wish to use with the [`compile_with`] function.
[Cranelift]: https://github.com/CraneStation/cranelift
[`wasmer-clif-backend`]: https://crates.io/crates/wasmer-clif-backend
[`compile_with`]: https://docs.rs/wasmer-runtime/*/wasmer_runtime/fn.compile_with.html
[`compile_with`]: https://docs.rs/wasmer-runtime/*/wasmer_runtime/fn.compile_with.html

32
lib/spectests/README.md Normal file
View File

@ -0,0 +1,32 @@
<p align="center">
<a href="https://wasmer.io" target="_blank" rel="noopener noreferrer">
<img width="400" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/logo.png" alt="Wasmer logo">
</a>
</p>
<p align="center">
<a href="https://circleci.com/gh/wasmerio/wasmer/">
<img src="https://img.shields.io/circleci/project/github/wasmerio/wasmer/master.svg" alt="Build Status">
</a>
<a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License">
</a>
<a href="https://spectrum.chat/wasmer">
<img src="https://withspectrum.github.io/badge/badge.svg" alt="Join the Wasmer Community">
</a>
<a href="https://crates.io/crates/wasmer-spectests">
<img src="https://img.shields.io/crates/d/wasmer-spectests.svg" alt="Number of downloads from crates.io">
</a>
<a href="https://docs.rs/wasmer-spectests">
<img src="https://docs.rs/wasmer-spectests/badge.svg" alt="Read our API documentation">
</a>
</p>
# Wasmer Spectests
Wasmer is a standalone JIT WebAssembly runtime, aiming to be fully
compatible with Emscripten, Rust and Go. [Learn
more](https://github.com/wasmerio/wasmer).
This crate allows to test the Wasmer runtime against the official
specification test suite.

View File

@ -7,4 +7,9 @@ edition = "2018"
[dependencies]
wasmer-runtime-core = { path = "../runtime-core", version = "0.2.1" }
libc = "0.2.50"
rand = "0.6.5"
rand = "0.6.5"
# wasmer-runtime-abi = { path = "../runtime-abi" }
hashbrown = "0.1.8"
generational-arena = "0.2.2"
zbox = "0.6.1"
log = "0.4.6"

View File

@ -1,9 +1,13 @@
#[macro_use]
extern crate log;
mod ptr;
mod state;
mod syscalls;
mod utils;
use self::state::WasiState;
use self::state::{WasiState, WasiFs};
use self::syscalls::*;
use std::ffi::c_void;
@ -21,6 +25,7 @@ pub fn generate_import_object(args: Vec<Vec<u8>>, envs: Vec<Vec<u8>>) -> ImportO
}
let state = Box::new(WasiState {
fs: WasiFs::new().unwrap(),
args: &args[..],
envs: &envs[..],
});

View File

@ -1,5 +1,182 @@
// use wasmer_runtime_abi::vfs::{
// vfs::Vfs,
// file_like::{FileLike, Metadata};
// };
use std::{
cell::{Cell, RefCell},
ops::{Index, IndexMut},
rc::Rc,
time::SystemTime,
};
use generational_arena::{Arena, Index as Inode};
use hashbrown::hash_map::{HashMap, Entry};
use zbox::{
RepoOpener,
Repo,
File,
FileType,
OpenOptions,
};
use crate::syscalls::types::*;
pub const MAX_SYMLINKS: usize = 100;
pub struct InodeVal {
stat: __wasi_filestat_t,
is_preopened: bool,
name: String,
kind: Kind,
}
pub enum Kind {
File {
handle: File,
},
Dir {
handle: File,
/// The entries of a directory are lazily filled.
entries: Vec<Inode>,
},
Symlink {
forwarded: Inode,
},
Buffer {
buffer: Vec<u8>,
},
}
pub struct Fd {
rights: __wasi_rights_t,
flags: __wasi_fdflags_t,
offset: u64,
inode: Inode,
}
pub struct WasiFs {
repo: Repo,
name_map: HashMap<String, Inode>,
inodes: Arena<InodeVal>,
fd_map: HashMap<u32, Fd>,
next_fd: Cell<u32>,
inode_counter: Cell<u64>,
}
impl WasiFs {
pub fn new() -> Result<Self, String> {
Ok(Self {
repo: RepoOpener::new().create(true).open("mem://📂", "very unsafe pwd").map_err(|e| e.to_string())?,
name_map: HashMap::new(),
inodes: Arena::new(),
fd_map: HashMap::new(),
next_fd: Cell::new(3),
inode_counter: Cell::new(1000),
})
}
fn get_inode(&mut self, path: &str) -> Option<Inode> {
Some(match self.name_map.entry(path.to_string()) {
Entry::Occupied(o) => *o.get(),
Entry::Vacant(v) => {
let file = if let Ok(file) = OpenOptions::new().read(true).write(true).create(false).open(&mut self.repo, path) {
file
} else {
return None;
};
let metadata = file.metadata().unwrap();
let inode_index = {
let index = self.inode_counter.get();
self.inode_counter.replace(index + 1)
};
let systime_to_nanos = |systime: SystemTime| {
let duration = systime.duration_since(SystemTime::UNIX_EPOCH).expect("should always be after unix epoch");
duration.as_nanos() as u64
};
let inode = self.inodes.insert(InodeVal {
stat: __wasi_filestat_t {
st_dev: 0,
st_ino: inode_index,
st_filetype: match metadata.file_type() {
FileType::File => __WASI_FILETYPE_REGULAR_FILE,
FileType::Dir => __WASI_FILETYPE_DIRECTORY,
},
st_nlink: 0,
st_size: metadata.len() as u64,
st_atim: systime_to_nanos(SystemTime::now()),
st_mtim: systime_to_nanos(metadata.modified()),
st_ctim: systime_to_nanos(metadata.created()),
},
is_preopened: false,
name: path.to_string(),
kind: match metadata.file_type() {
FileType::File => Kind::File {
handle: file,
},
FileType::Dir => Kind::Dir {
handle: file,
entries: Vec::new(),
},
},
});
v.insert(inode);
inode
},
})
}
fn filestat_inode(&self, inode: Inode, flags: __wasi_lookupflags_t) -> Result<__wasi_filestat_t, __wasi_errno_t> {
let inode_val = &self.inodes[inode];
if let (true, Kind::Symlink { mut forwarded }) = (flags & __WASI_LOOKUP_SYMLINK_FOLLOW != 0, &inode_val.kind) {
// Time to follow the symlink.
let mut counter = 0;
while counter <= MAX_SYMLINKS {
let inode_val = &self.inodes[forwarded];
if let &Kind::Symlink { forwarded: new_forwarded } = &inode_val.kind {
counter += 1;
forwarded = new_forwarded;
} else {
return Ok(inode_val.stat);
}
}
Err(__WASI_EMLINK)
} else {
Ok(inode_val.stat)
}
}
pub fn filestat_path(
&mut self,
preopened_fd: __wasi_fd_t,
flags: __wasi_lookupflags_t,
path: &str,
) -> Result<__wasi_filestat_t, __wasi_errno_t> {
warn!("Should use preopned_fd: {}", preopened_fd);
let inode = if let Some(inode) = self.get_inode(path) {
inode
} else {
return Err(__WASI_EINVAL);
};
self.filestat_inode(inode, flags)
}
pub fn filestat_fd(&self, fd: __wasi_fd_t) -> Result<__wasi_filestat_t, __wasi_errno_t> {
let fd = if let Some(fd) = self.fd_map.get(&fd) {
fd
} else {
return Err(__WASI_EBADF);
};
self.filestat_inode(fd.inode, 0)
}
}
pub struct WasiState<'a> {
// vfs: Vfs,
pub fs: WasiFs,
pub args: &'a [Vec<u8>],
pub envs: &'a [Vec<u8>],
}

View File

@ -226,7 +226,20 @@ pub fn fd_fdstat_get(
fd: __wasi_fd_t,
buf: WasmPtr<__wasi_fdstat_t>,
) -> __wasi_errno_t {
unimplemented!()
let mut state = get_wasi_state(ctx);
let memory = ctx.memory(0);
let stat = match state.fs.filestat_fd(fd) {
Ok(stat) => stat,
Err(errno) => return errno,
};
if let Some(buf) = buf.deref(memory) {
buf.set(stat);
__WASI_ESUCCESS
} else {
__WASI_EFAULT
}
}
pub fn fd_fdstat_set_flags(
ctx: &mut Ctx,

View File

@ -0,0 +1,31 @@
<p align="center">
<a href="https://wasmer.io" target="_blank" rel="noopener noreferrer">
<img width="400" src="https://raw.githubusercontent.com/wasmerio/wasmer/master/logo.png" alt="Wasmer logo">
</a>
</p>
<p align="center">
<a href="https://circleci.com/gh/wasmerio/wasmer/">
<img src="https://img.shields.io/circleci/project/github/wasmerio/wasmer/master.svg" alt="Build Status">
</a>
<a href="https://github.com/wasmerio/wasmer/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/wasmerio/wasmer.svg" alt="License">
</a>
<a href="https://spectrum.chat/wasmer">
<img src="https://withspectrum.github.io/badge/badge.svg" alt="Join the Wasmer Community">
</a>
<a href="https://crates.io/crates/wasmer-win-exception-handler">
<img src="https://img.shields.io/crates/d/wasmer-win-exception-handler.svg" alt="Number of downloads from crates.io">
</a>
<a href="https://docs.rs/wasmer-win-exception-handler">
<img src="https://docs.rs/wasmer-win-exception-handler/badge.svg" alt="Read our API documentation">
</a>
</p>
# Wasmer Windows Exception Handler
Wasmer is a standalone JIT WebAssembly runtime, aiming to be fully
compatible with Emscripten, Rust and Go. [Learn
more](https://github.com/wasmerio/wasmer).
This crate provides an API for exception handling on Windows.

7
scripts/install_lib_sodium.sh Executable file
View File

@ -0,0 +1,7 @@
#!/usr/bin/env bash
curl -O https://download.libsodium.org/libsodium/releases/libsodium-1.0.17.tar.gz
tar xf libsodium-1.0.17.tar.gz
cd libsodium-1.0.17/
./configure
make && make check
sudo make install

BIN
sqlite.wasm Normal file

Binary file not shown.