Fix memory leak in runtime interface (#4837)

* Fix memory leak in runtime interface

We used `slice::from_raw_parts` in runtime-interface which did not free
the memory afterwards. This pr changes it to `Vec::from_raw_parts` to
make sure `drop` is called properly and the values are freed.

* Check that `len` is non-zero

* Adds comment
This commit is contained in:
Bastian Köcher
2020-02-06 14:26:41 +01:00
committed by GitHub
parent 3c79e6d03c
commit c7867e5125
4 changed files with 68 additions and 12 deletions
@@ -39,6 +39,17 @@ pub trait TestApi {
data
}
/// Returns 16kb data.
///
/// # Note
///
/// We return a `Vec<u32>` because this will use the code path that uses SCALE
/// to pass the data between native/wasm. (Vec<u8> is passed without encoding the
/// data)
fn return_16kb() -> Vec<u32> {
vec![0; 4 * 1024]
}
/// Set the storage at key with value.
fn set_storage(&mut self, key: &[u8], data: &[u8]) {
self.place_storage(key.to_vec(), Some(data.to_vec()));
@@ -211,4 +222,28 @@ wasm_export_functions! {
assert_eq!(*val, test_api::get_and_return_i128(*val));
}
}
fn test_vec_return_value_memory_is_freed() {
let mut len = 0;
for _ in 0..1024 {
len += test_api::return_16kb().len();
}
assert_eq!(1024 * 1024 * 4, len);
}
fn test_encoded_return_value_memory_is_freed() {
let mut len = 0;
for _ in 0..1024 {
len += test_api::return_option_input(vec![0; 16 * 1024]).map(|v| v.len()).unwrap();
}
assert_eq!(1024 * 1024 * 16, len);
}
fn test_array_return_value_memory_is_freed() {
let mut len = 0;
for _ in 0..1024 * 1024 {
len += test_api::get_and_return_array([0; 34])[1];
}
assert_eq!(0, len);
}
}