Skip to content

Commit

Permalink
Merge pull request rust-lang#225 from Hywan/fix-module-leak
Browse files Browse the repository at this point in the history
fix(module,values) Fix memory leaks
  • Loading branch information
TheDan64 authored Dec 1, 2020
2 parents 5e64c01 + f3a9aac commit 3eab4db
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 19 deletions.
15 changes: 6 additions & 9 deletions src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use std::mem::{forget, MaybeUninit};
use std::path::Path;
use std::ptr;
use std::rc::Rc;
use std::slice::from_raw_parts;

use crate::{AddressSpace, OptimizationLevel};
#[llvm_versions(7.0..=latest)]
Expand Down Expand Up @@ -930,20 +929,18 @@ impl<'ctx> Module<'ctx> {
/// ```
pub fn get_global_metadata(&self, key: &str) -> Vec<MetadataValue<'ctx>> {
let c_string = to_c_str(key);
let count = self.get_global_metadata_size(key);
let count = self.get_global_metadata_size(key) as usize;

let mut raw_vec: Vec<LLVMValueRef> = Vec::with_capacity(count as usize);
let ptr = raw_vec.as_mut_ptr();
let mut vec: Vec<LLVMValueRef> = Vec::with_capacity(count);
let ptr = vec.as_mut_ptr();

forget(raw_vec);

let slice = unsafe {
unsafe {
LLVMGetNamedMetadataOperands(self.module.get(), c_string.as_ptr(), ptr);

from_raw_parts(ptr, count as usize)
vec.set_len(count);
};

slice.iter().map(|val| MetadataValue::new(*val)).collect()
vec.iter().map(|val| MetadataValue::new(*val)).collect()
}

/// Gets the first `GlobalValue` in a module.
Expand Down
18 changes: 8 additions & 10 deletions src/values/metadata_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ use crate::values::{BasicMetadataValueEnum, Value};

use std::ffi::CStr;
use std::fmt;
use std::mem::forget;
use std::slice::from_raw_parts;

// TODOC: Varies by version
#[cfg(feature = "llvm3-6")]
Expand Down Expand Up @@ -109,19 +107,19 @@ impl<'ctx> MetadataValue<'ctx> {
return Vec::new();
}

let count = self.get_node_size();
let mut raw_vec: Vec<LLVMValueRef> = Vec::with_capacity(count as usize);
let ptr = raw_vec.as_mut_ptr();
let count = self.get_node_size() as usize;
let mut vec: Vec<LLVMValueRef> = Vec::with_capacity(count);
let ptr = vec.as_mut_ptr();

forget(raw_vec);

let slice = unsafe {
unsafe {
LLVMGetMDNodeOperands(self.as_value_ref(), ptr);

from_raw_parts(ptr, count as usize)
vec.set_len(count)
};

slice.iter().map(|val| BasicMetadataValueEnum::new(*val)).collect()
vec.iter()
.map(|val| BasicMetadataValueEnum::new(*val))
.collect()
}

pub fn print_to_string(self) -> LLVMString {
Expand Down

0 comments on commit 3eab4db

Please sign in to comment.