From 42af38d38317804c1339abbb33ca1369e7597b30 Mon Sep 17 00:00:00 2001 From: Mark McCaskey Date: Tue, 1 Dec 2020 11:38:25 -0800 Subject: [PATCH] Fix memory leak in wat2wasm function --- lib/c-api/src/wasm_c_api/macros.rs | 13 +++++++------ lib/c-api/src/wasm_c_api/wat.rs | 17 +++++++++++++---- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/lib/c-api/src/wasm_c_api/macros.rs b/lib/c-api/src/wasm_c_api/macros.rs index ffd95b701e9..c425d985da7 100644 --- a/lib/c-api/src/wasm_c_api/macros.rs +++ b/lib/c-api/src/wasm_c_api/macros.rs @@ -102,12 +102,13 @@ macro_rules! wasm_declare_vec { #[no_mangle] - pub unsafe extern "C" fn [](ptr: *mut []) { - let vec = &mut *ptr; - if !vec.data.is_null() { - Vec::from_raw_parts(vec.data, vec.size, vec.size); - vec.data = ::std::ptr::null_mut(); - vec.size = 0; + pub unsafe extern "C" fn [](ptr: Option<&mut []>) { + if let Some(vec) = ptr { + if !vec.data.is_null() { + Vec::from_raw_parts(vec.data, vec.size, vec.size); + vec.data = ::std::ptr::null_mut(); + vec.size = 0; + } } } } diff --git a/lib/c-api/src/wasm_c_api/wat.rs b/lib/c-api/src/wasm_c_api/wat.rs index 185b61e91c0..fdfcc7e45cd 100644 --- a/lib/c-api/src/wasm_c_api/wat.rs +++ b/lib/c-api/src/wasm_c_api/wat.rs @@ -6,11 +6,20 @@ use super::types::wasm_byte_vec_t; /// In case of failure, `wat2wasm` returns `NULL`. #[cfg(feature = "wat")] #[no_mangle] -pub unsafe extern "C" fn wat2wasm(wat: &wasm_byte_vec_t) -> Option> { - let wat: &[u8] = wat.into_slice()?; - let result: wasm_byte_vec_t = c_try!(wasmer::wat2wasm(wat)).into_owned().into(); +pub unsafe extern "C" fn wat2wasm(wat: &wasm_byte_vec_t, out: &mut wasm_byte_vec_t) { + let wat: &[u8] = match wat.into_slice() { + Some(v) => v, + _ => return, + }; + let result: wasm_byte_vec_t = match wasmer::wat2wasm(wat) { + Ok(val) => val.into_owned().into(), + Err(err) => { + crate::error::update_last_error(err); + return; + } + }; - Some(Box::new(result)) + *out = result; } #[cfg(test)]