Skip to content

Commit f9e23fc

Browse files
committed
Adds checks to build_array_malloc and add tests
1 parent 346fa64 commit f9e23fc

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/builder.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,19 @@ impl<'ctx> Builder<'ctx> {
373373

374374
// TODOC: Heap allocation
375375
pub fn build_array_malloc<T: BasicType<'ctx>>(&self, ty: T, size: IntValue<'ctx>, name: &str) -> PointerValue<'ctx> {
376+
// LLVMBulidArrayMalloc segfaults if ty is unsized
377+
let is_sized = match ty.as_basic_type_enum() {
378+
BasicTypeEnum::ArrayType(ty) => ty.is_sized(),
379+
BasicTypeEnum::FloatType(ty) => ty.is_sized(),
380+
BasicTypeEnum::IntType(ty) => ty.is_sized(),
381+
BasicTypeEnum::PointerType(ty) => ty.is_sized(),
382+
BasicTypeEnum::StructType(ty) => ty.is_sized(),
383+
BasicTypeEnum::VectorType(ty) => ty.is_sized(),
384+
};
385+
if !is_sized {
386+
panic!("Cannot build malloc call for an unsized type {:?}", ty);
387+
}
388+
376389
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
377390

378391
let value = unsafe {

tests/all/test_values.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -903,6 +903,7 @@ fn test_allocations() {
903903
let module = context.create_module("my_mod");
904904
let void_type = context.void_type();
905905
let i32_type = context.i32_type();
906+
let unsized_type = context.opaque_struct_type("my_struct");
906907
let i32_three = i32_type.const_int(3, false);
907908
let fn_type = void_type.fn_type(&[], false);
908909
let fn_value = module.add_function("my_func", fn_type, None);
@@ -932,6 +933,14 @@ fn test_allocations() {
932933
let heap_array = builder.build_array_malloc(i32_type, i32_three, "heap_array");
933934

934935
assert_eq!(*heap_array.get_type().print_to_string(), *CString::new("i32*").unwrap());
936+
937+
let bad_malloc_res = std::panic::catch_unwind(|| builder.build_malloc(unsized_type, ""));
938+
939+
assert!(bad_malloc_res.is_err());
940+
941+
let bad_array_malloc_res = std::panic::catch_unwind(|| builder.build_array_malloc(unsized_type, i32_three, ""));
942+
943+
assert!(bad_array_malloc_res.is_err());
935944
}
936945

937946
#[test]

0 commit comments

Comments
 (0)