Skip to content

Commit

Permalink
Add wasm32 implementation for libc
Browse files Browse the repository at this point in the history
This adds a wasm32 implementation for `free`, `malloc` and `realloc`.
Originally written by @rodrigorc in
rust-lang/libc#1092 and adapted.
  • Loading branch information
nmattia committed Nov 12, 2021
1 parent 96b2d24 commit 304bcfc
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
36 changes: 36 additions & 0 deletions src/ffi/libc.rs
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 304bcfc

Please sign in to comment.