Skip to content

Commit

Permalink
Use (de)alloc for allocate and free_mem
Browse files Browse the repository at this point in the history
This makes the allocator explicitly responsible for the memory
allocated, preventing any clobbering.
  • Loading branch information
ureeves committed May 8, 2024
1 parent b24bfd7 commit cd51ce0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
Binary file modified assets/dusk_wallet_core.wasm
Binary file not shown.
25 changes: 17 additions & 8 deletions src/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@

//! FFI bindings exposed to WASM module.

use alloc::{vec, vec::Vec};
use alloc::{
alloc::{alloc, dealloc, Layout},
vec::Vec,
};
use core::mem;

use dusk_bytes::Serializable;
Expand All @@ -15,22 +18,28 @@ use sha2::{Digest, Sha512};

use crate::{key, tx, types, utils, MAX_KEY, MAX_LEN};

/// The alignment of the memory allocated by the FFI.
///
/// This is 1 because we're not allocating any complex data structures, and
/// just interacting with the memory directly.
const ALIGNMENT: usize = 1;

/// Allocates a buffer of `len` bytes on the WASM memory.
#[no_mangle]
pub fn allocate(len: i32) -> i32 {
let bytes = vec![0u8; len as usize];
let ptr = bytes.as_ptr();
mem::forget(bytes);
ptr as i32
unsafe {
let layout = Layout::from_size_align_unchecked(len as usize, ALIGNMENT);
let ptr = alloc(layout);
ptr as _
}
}

/// Frees a previously allocated buffer on the WASM memory.
#[no_mangle]
pub fn free_mem(ptr: i32, len: i32) {
let ptr = ptr as *mut u8;
let len = len as usize;
unsafe {
Vec::from_raw_parts(ptr, len, len);
let layout = Layout::from_size_align_unchecked(len as usize, ALIGNMENT);
dealloc(ptr as _, layout);
}
}

Expand Down

0 comments on commit cd51ce0

Please sign in to comment.