Skip to content

Add wasm32 implementation for libc #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use std::path::*;
use std::io;

use crate::rustimpl;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod libc;

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
}