Skip to content

Commit

Permalink
Enable no_std
Browse files Browse the repository at this point in the history
  • Loading branch information
Veykril committed Jan 26, 2020
1 parent 6188b2a commit 1cf95dc
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 45 deletions.
6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ license = "MIT"

[features]
wasi = ["ffi/wasi"]
default = ["wasi"]
std = []
default = ["wasi", "std"]

[dependencies]
libc = "^0.2"

[dependencies.ffi]
path = "wasm3-sys"
Expand Down
15 changes: 8 additions & 7 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::error;
use std::fmt;
use core::fmt;
use core::str;

pub type Result<T> = std::result::Result<T, Error>;
use crate::bytes_till_null;

pub type Result<T> = core::result::Result<T, Error>;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
Expand All @@ -16,15 +18,14 @@ impl Error {
if ptr.is_null() {
Ok(())
} else {
Err(Error::Wasm3(
std::ffi::CStr::from_ptr(ptr).to_str().unwrap(),
))
Err(Error::Wasm3(str::from_utf8_unchecked(bytes_till_null(ptr))))
}
}
}
}

impl error::Error for Error {}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expand Down
16 changes: 6 additions & 10 deletions src/function.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::marker::PhantomData;
use core::marker::PhantomData;
use core::str;

use crate::bytes_till_null;
use crate::error::{Error, Result};
use crate::runtime::Runtime;
use crate::{WasmArgs, WasmType};
Expand Down Expand Up @@ -51,17 +53,11 @@ where
}

pub fn import_module_name(&self) -> &str {
unsafe {
std::str::from_utf8_unchecked(
std::ffi::CStr::from_ptr((*self.raw).import.moduleUtf8).to_bytes(),
)
}
unsafe { str::from_utf8_unchecked(bytes_till_null((*self.raw).import.moduleUtf8)) }
}

pub fn name(&self) -> &str {
unsafe {
std::str::from_utf8_unchecked(std::ffi::CStr::from_ptr((*self.raw).name).to_bytes())
}
unsafe { str::from_utf8_unchecked(bytes_till_null((*self.raw).name)) }
}

fn call_impl(&self, args: ARGS) -> Result<RET> {
Expand All @@ -73,7 +69,7 @@ where
stack.as_mut_ptr(),
self.rt.mallocated(),
666,
std::f64::NAN,
core::f64::NAN,
)
};
match self.rt.rt_error() {
Expand Down
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(clippy::all)]
pub mod environment;
pub mod error;
Expand All @@ -16,3 +17,14 @@ pub fn print_m3_info() {
pub fn print_profiler_info() {
unsafe { ffi::m3_PrintProfilerInfo() };
}

pub(crate) unsafe fn bytes_till_null<'a>(ptr: *const libc::c_char) -> &'a [u8] {
let start = ptr.cast::<u8>();
let mut ptr = start;
let mut len = 0;
while *ptr != 0 {
ptr = ptr.add(1);
len += 1;
}
core::slice::from_raw_parts(start, len - 1)
}
46 changes: 26 additions & 20 deletions src/module.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::cmp::Ordering;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::ptr;
use core::marker::PhantomData;
use core::ptr;
use core::slice;

use crate::environment::Environment;
use crate::error::{Error, Result};
Expand Down Expand Up @@ -85,10 +84,7 @@ impl<'env, 'rt> Module<'env, 'rt> {
(*m3_func).compiled = ffi::GetPagePC(page);
(*m3_func).module = self.raw;
ffi::EmitWord_impl(page, ffi::op_CallRawFunction as _);
ffi::EmitWord_impl(
page,
func.map(|f| f as _).unwrap_or_else(std::ptr::null_mut),
);
ffi::EmitWord_impl(page, func.map(|f| f as _).unwrap_or_else(ptr::null_mut));

ffi::ReleaseCodePage(self.rt.as_ptr(), page);
}
Expand All @@ -100,10 +96,10 @@ impl<'env, 'rt> Module<'env, 'rt> {
function_name: &str,
) -> Result<ffi::IM3Function> {
if let Some(func) = unsafe {
std::slice::from_raw_parts_mut((*self.raw).functions, (*self.raw).numFunctions as usize)
slice::from_raw_parts_mut((*self.raw).functions, (*self.raw).numFunctions as usize)
.iter_mut()
.filter(|func| eq_cstr_str(CStr::from_ptr(func.import.moduleUtf8), module_name))
.find(|func| eq_cstr_str(CStr::from_ptr(func.import.fieldUtf8), function_name))
.filter(|func| eq_cstr_str(func.import.moduleUtf8, module_name))
.find(|func| eq_cstr_str(func.import.fieldUtf8, function_name))
} {
Ok(func)
} else {
Expand All @@ -121,16 +117,16 @@ impl<'env, 'rt> Module<'env, 'rt> {
{
if let Some(func) = unsafe {
let functions_ptr = (*self.raw).functions;
std::slice::from_raw_parts_mut(
slice::from_raw_parts_mut(
if functions_ptr.is_null() {
std::ptr::NonNull::dangling().as_ptr()
ptr::NonNull::dangling().as_ptr()
} else {
functions_ptr
},
(*self.raw).numFunctions as usize,
)
.iter_mut()
.find(|func| eq_cstr_str(CStr::from_ptr(func.name), function_name))
.find(|func| eq_cstr_str(func.name, function_name))
} {
Function::from_raw(self.rt, func).and_then(Function::compile)
} else {
Expand All @@ -148,12 +144,22 @@ impl<'env, 'rt> Module<'env, 'rt> {
}
}

fn cmp_cstr_str(cstr: &CStr, str: &str) -> Ordering {
cstr.to_bytes().iter().cmp(str.as_bytes())
}

fn eq_cstr_str(cstr: &CStr, str: &str) -> bool {
cmp_cstr_str(cstr, str) == Ordering::Equal
fn eq_cstr_str(cstr: *const libc::c_char, str: &str) -> bool {
if cstr.is_null() {
return str.is_empty();
}
let mut bytes = str.as_bytes().iter();
let mut cstr = cstr.cast::<u8>();
loop {
match (bytes.next(), unsafe { *cstr }) {
(None, 0) => break true,
(Some(_), 0) => break false,
(Some(&byte), cbyte) if cbyte == byte => unsafe {
cstr = cstr.add(1);
},
_ => break false,
}
}
}

#[test]
Expand Down
14 changes: 7 additions & 7 deletions src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::mem;
use std::ptr;
use std::slice;
use core::mem;
use core::ptr;
use core::slice;

use crate::environment::Environment;
use crate::error::{Error, Result};
Expand Down Expand Up @@ -31,7 +31,7 @@ impl<'env> Runtime<'env> {
pub fn load_module<'rt>(
&'rt self,
module: ParsedModule<'env>,
) -> std::result::Result<Module<'env, 'rt>, (ParsedModule<'env>, Error)> {
) -> core::result::Result<Module<'env, 'rt>, (ParsedModule<'env>, Error)> {
if let Err(err) =
unsafe { Error::from_ffi_res(ffi::m3_LoadModule(self.raw, module.as_ptr())) }
{
Expand Down Expand Up @@ -83,7 +83,7 @@ impl<'env> Runtime<'env> {
let ptr = ffi::m3_GetMemory(self.raw, &mut size, 0);
slice::from_raw_parts(
if size == 0 {
std::ptr::NonNull::dangling().as_ptr()
ptr::NonNull::dangling().as_ptr()
} else {
ptr
},
Expand All @@ -95,7 +95,7 @@ impl<'env> Runtime<'env> {
/// This function is unsafe because it allows aliasing to happen.
/// The underlying memory may change if a runtimes exposed function is called.
pub unsafe fn stack(&self) -> &[u64] {
std::slice::from_raw_parts(
slice::from_raw_parts(
(*self.raw).stack as ffi::m3stack_t,
(*self.raw).numStackSlots as usize,
)
Expand All @@ -106,7 +106,7 @@ impl<'env> Runtime<'env> {
/// The underlying memory may change if a runtimes exposed function is called.
#[allow(clippy::mut_from_ref)]
pub unsafe fn stack_mut(&self) -> &mut [u64] {
std::slice::from_raw_parts_mut(
slice::from_raw_parts_mut(
(*self.raw).stack as ffi::m3stack_t,
(*self.raw).numStackSlots as usize,
)
Expand Down
3 changes: 3 additions & 0 deletions wasm3-sys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ links = "wasm3"
[features]
wasi = []

[dependencies]
libc = "^0.2"

[build-dependencies]
bindgen = "0.52"
cc = "1"
2 changes: 2 additions & 0 deletions wasm3-sys/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ fn gen_bindings() -> io::Result<()> {
let whitelist_regex =
"((?:I|c_)?[Mm]3.*)|.*Page.*|Module_.*|EmitWord_impl|op_CallRawFunction|Compile_Function";
let bindgen = bindgen::builder()
.use_core()
.ctypes_prefix("libc")
.layout_tests(false)
.generate_comments(false)
.default_enum_style(bindgen::EnumVariation::ModuleConsts)
Expand Down
1 change: 1 addition & 0 deletions wasm3-sys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![no_std]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
Expand Down

0 comments on commit 1cf95dc

Please sign in to comment.