Skip to content

Commit 304bcfc

Browse files
committed
Add wasm32 implementation for libc
This adds a wasm32 implementation for `free`, `malloc` and `realloc`. Originally written by @rodrigorc in rust-lang/libc#1092 and adapted.
1 parent 96b2d24 commit 304bcfc

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/ffi.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,17 @@ use std::slice;
88
use std::fmt;
99
use std::os::raw::*;
1010
use std::ffi::CStr;
11-
use std::path::*;
1211
use std::io;
1312

1413
use crate::rustimpl;
14+
#[cfg(target_arch = "wasm32")]
15+
mod libc;
16+
17+
#[cfg(target_arch = "wasm32")]
18+
use std::path::{PathBuf};
19+
20+
#[cfg(not(target_arch = "wasm32"))]
21+
use std::path::{Path};
1522

1623
macro_rules! lode_error {
1724
($e:expr) => {

src/ffi/libc.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
pub type size_t = usize;
2+
3+
const MALLOC_HEADER : isize = 8;
4+
const MALLOC_ALIGN : usize = 8;
5+
6+
use super::c_void;
7+
use std::alloc::{self, Layout};
8+
use std::ptr;
9+
10+
pub unsafe fn malloc(size: size_t) -> *mut c_void {
11+
let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN);
12+
let p = alloc::alloc(lay);
13+
if p.is_null() {
14+
return ptr::null_mut();
15+
}
16+
*(p as *mut size_t) = size;
17+
p.offset(MALLOC_HEADER) as *mut c_void
18+
}
19+
pub unsafe fn free(p: *mut c_void) {
20+
let p = p.offset(-MALLOC_HEADER) as *mut u8;
21+
let size = *(p as *mut size_t);
22+
let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN);
23+
alloc::dealloc(p, lay);
24+
}
25+
pub unsafe fn realloc(p: *mut c_void, _size: size_t) -> *mut c_void {
26+
let p = p.offset(-MALLOC_HEADER) as *mut u8;
27+
let size = *(p as *mut size_t);
28+
let lay = Layout::from_size_align_unchecked(MALLOC_HEADER as usize + size, MALLOC_ALIGN);
29+
let p = alloc::realloc(p, lay, size);
30+
if p.is_null() {
31+
return ptr::null_mut();
32+
}
33+
*(p as *mut size_t) = size;
34+
p.offset(MALLOC_HEADER) as *mut c_void
35+
}
36+

0 commit comments

Comments
 (0)