From 304bcfc415ffa204ec9e82d5ec535708ed1bcca8 Mon Sep 17 00:00:00 2001 From: Nicolas Mattia Date: Fri, 12 Nov 2021 12:12:07 +0100 Subject: [PATCH] Add wasm32 implementation for libc This adds a wasm32 implementation for `free`, `malloc` and `realloc`. Originally written by @rodrigorc in https://github.com/rust-lang/libc/pull/1092 and adapted. --- src/ffi.rs | 9 ++++++++- src/ffi/libc.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/ffi/libc.rs diff --git a/src/ffi.rs b/src/ffi.rs index 074fc0f..09df5e5 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -8,10 +8,17 @@ use std::slice; use std::fmt; use std::os::raw::*; use std::ffi::CStr; -use std::path::*; use std::io; use crate::rustimpl; +#[cfg(target_arch = "wasm32")] +mod libc; + +#[cfg(target_arch = "wasm32")] +use std::path::{PathBuf}; + +#[cfg(not(target_arch = "wasm32"))] +use std::path::{Path}; macro_rules! lode_error { ($e:expr) => { diff --git a/src/ffi/libc.rs b/src/ffi/libc.rs new file mode 100644 index 0000000..f500afb --- /dev/null +++ b/src/ffi/libc.rs @@ -0,0 +1,36 @@ +pub type size_t = usize; + +const MALLOC_HEADER : isize = 8; +const MALLOC_ALIGN : usize = 8; + +use super::c_void; +use std::alloc::{self, Layout}; +use std::ptr; + +pub unsafe fn malloc(size: size_t) -> *mut c_void { + let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); + let p = alloc::alloc(lay); + if p.is_null() { + return ptr::null_mut(); + } + *(p as *mut size_t) = size; + p.offset(MALLOC_HEADER) as *mut c_void +} +pub unsafe fn free(p: *mut c_void) { + let p = p.offset(-MALLOC_HEADER) as *mut u8; + let size = *(p as *mut size_t); + let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); + alloc::dealloc(p, lay); +} +pub unsafe fn realloc(p: *mut c_void, _size: size_t) -> *mut c_void { + let p = p.offset(-MALLOC_HEADER) as *mut u8; + let size = *(p as *mut size_t); + let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN); + let p = alloc::realloc(p, lay, size); + if p.is_null() { + return ptr::null_mut(); + } + *(p as *mut size_t) = size; + p.offset(MALLOC_HEADER) as *mut c_void +} +