Skip to content

Commit bd4ead7

Browse files
jimpoVeykril
authored andcommitted
Fix memory leak in ParsedModule::take_data
1 parent 5d08124 commit bd4ead7

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

src/module.rs

+20-14
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,19 @@ use crate::function::{CallContext, Function, RawCall};
1010
use crate::runtime::Runtime;
1111
use crate::utils::{cstr_to_str, str_to_cstr_owned};
1212

13+
#[derive(Debug)]
14+
struct DropModule(NonNull<ffi::M3Module>);
15+
16+
impl Drop for DropModule {
17+
fn drop(&mut self) {
18+
unsafe { ffi::m3_FreeModule(self.0.as_ptr()) };
19+
}
20+
}
21+
1322
/// A parsed module which can be loaded into a [`Runtime`].
1423
pub struct ParsedModule {
1524
data: Box<[u8]>,
16-
raw: ffi::IM3Module,
25+
raw: DropModule,
1726
env: Environment,
1827
}
1928

@@ -26,21 +35,24 @@ impl ParsedModule {
2635
let res = unsafe {
2736
ffi::m3_ParseModule(env.as_ptr(), &mut module, data.as_ptr(), data.len() as u32)
2837
};
29-
Error::from_ffi_res(res).map(|_| ParsedModule {
38+
Error::from_ffi_res(res)?;
39+
let module = NonNull::new(module)
40+
.expect("module pointer is non-null after m3_ParseModule if result is not error");
41+
Ok(ParsedModule {
3042
data,
31-
raw: module,
43+
raw: DropModule(module),
3244
env: env.clone(),
3345
})
3446
}
3547

3648
pub(crate) fn as_ptr(&self) -> ffi::IM3Module {
37-
self.raw
49+
self.raw.0.as_ptr()
3850
}
3951

40-
pub(crate) fn take_data(mut self) -> Box<[u8]> {
41-
let res = mem::replace(&mut self.data, <Box<[u8]>>::default());
42-
mem::forget(self);
43-
res
52+
pub(crate) fn take_data(self) -> Box<[u8]> {
53+
let ParsedModule { data, raw, env: _env } = self;
54+
mem::forget(raw);
55+
data
4456
}
4557

4658
/// The environment this module was parsed in.
@@ -49,12 +61,6 @@ impl ParsedModule {
4961
}
5062
}
5163

52-
impl Drop for ParsedModule {
53-
fn drop(&mut self) {
54-
unsafe { ffi::m3_FreeModule(self.raw) };
55-
}
56-
}
57-
5864
/// A loaded module belonging to a specific runtime. Allows for linking and looking up functions.
5965
// needs no drop as loaded modules will be cleaned up by the runtime
6066
pub struct Module<'rt> {

0 commit comments

Comments
 (0)