Skip to content

Commit

Permalink
Add memory cleanup to rust
Browse files Browse the repository at this point in the history
  • Loading branch information
KendallWeihe committed Sep 17, 2024
1 parent f2bdf51 commit 0531071
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 15 deletions.
8 changes: 8 additions & 0 deletions bindings/web5_c/src/c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ pub extern "C" fn free_string(s: *mut c_char) {
}
}

pub fn free_bytes(ptr: *mut u8) {
if !ptr.is_null() {
unsafe {
let _ = Box::from_raw(ptr);
}
}
}

pub unsafe fn opt_cstr_to_string(c_str: *const c_char) -> Option<String> {
if c_str.is_null() {
None
Expand Down
12 changes: 5 additions & 7 deletions bindings/web5_c/src/crypto/dsa/poc.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::CSigner;
use super::{call_sign, CSigner};
use crate::c::free_bytes;

#[no_mangle]
pub extern "C" fn poc_signer_from_foreign(signer: *const CSigner) {
Expand All @@ -10,10 +11,7 @@ pub extern "C" fn poc_signer_from_foreign(signer: *const CSigner) {
let payload = b"Test message";

let mut out_len: usize = 0;
(signer.sign)(
signer.signer_id,
payload.as_ptr(),
payload.len(),
&mut out_len,
);
let signature = call_sign(signer, payload.as_ptr(), payload.len(), &mut out_len);

free_bytes(signature);
}
18 changes: 10 additions & 8 deletions bindings/web5_c/src/crypto/key_managers/poc.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
use super::{call_get_signer, call_import_private_jwk, CKeyManager};
use crate::crypto::{dsa::call_sign, jwk::CJwk};
use crate::{
c::free_bytes,
crypto::{
dsa::{call_sign, free_csigner},
jwk::{free_cjwk, CJwk},
},
};
use web5::crypto::jwk::Jwk;

#[no_mangle]
Expand All @@ -26,11 +32,7 @@ pub extern "C" fn poc_key_manager_from_foreign(manager: *const CKeyManager) {
let mut out_len: usize = 0;
let signature = call_sign(signer, payload.as_ptr(), payload.len(), &mut out_len);

if !signature.is_null() {
let signature_slice = unsafe { std::slice::from_raw_parts(signature, out_len) };
println!("Signature: {:?}", signature_slice);
unsafe {
let _ = Box::from_raw(signature);
}
}
free_cjwk(public_jwk);
free_csigner(signer);
free_bytes(signature);
}

0 comments on commit 0531071

Please sign in to comment.