Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions libcc2rs/src/alloc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,40 @@
// Copyright (c) 2022-present INESC-ID.
// Distributed under the MIT license that can be found in the LICENSE file.

use crate::rc::{AnyPtr, Ptr};

pub fn malloc_refcount(a0: usize) -> AnyPtr {
Ptr::alloc_array(vec![0u8; a0].into_boxed_slice()).to_any()
}

pub fn free_refcount(a0: AnyPtr) {
if a0.is_null() {
return;
}
a0.reinterpret_cast::<u8>().delete_array();
}

pub fn realloc_refcount(a0: AnyPtr, a1: usize) -> AnyPtr {
if a0.is_null() {
return malloc_refcount(a1);
}
let __new = Ptr::alloc_array(vec![0u8; a1].into_boxed_slice()).to_any();
let __n = a1.min(a0.reinterpret_cast::<u8>().len());
__new.memcpy(&a0, __n);
a0.reinterpret_cast::<u8>().delete_array();
__new
}

pub fn calloc_refcount(a0: usize, a1: usize) -> AnyPtr {
Ptr::alloc_array(vec![0u8; a0.wrapping_mul(a1)].into_boxed_slice()).to_any()
}

pub fn strdup_refcount(a0: Ptr<u8>) -> Ptr<u8> {
let mut bytes: Vec<u8> = a0.to_c_string_iterator().collect();
bytes.push(0);
Ptr::alloc_array(bytes.into_boxed_slice())
}

/// # Safety
///
/// Same contract as C's `malloc`.
Expand Down
46 changes: 28 additions & 18 deletions libcc2rs/src/rc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,32 +210,38 @@ impl<T> Ptr<T> {

#[inline]
pub fn delete(&self) {
assert_eq!(self.offset, 0, "ub: invalid delete");
let weak = match self.kind {
PtrKind::HeapSingle(ref weak) => weak,
match &self.kind {
PtrKind::HeapSingle(weak) => {
assert_eq!(self.offset, 0, "ub: invalid delete");
assert_eq!(Weak::strong_count(weak), 1, "ub: invalid delete");
unsafe {
let strong = weak.upgrade().expect("ub: dangling pointer");
Rc::from_raw(Rc::as_ptr(&strong));
}
assert_eq!(Weak::strong_count(weak), 0, "ub: double free");
}
PtrKind::Reinterpreted(data) => data.alloc.delete(),
PtrKind::Null => {}
_ => panic!("ub: invalid delete"),
};
assert_eq!(Weak::strong_count(weak), 1, "ub: invalid delete");
unsafe {
let strong = weak.upgrade().expect("ub: dangling pointer");
Rc::from_raw(Rc::as_ptr(&strong));
}
assert_eq!(Weak::strong_count(weak), 0, "ub: strong count is not zero");
}

#[inline]
pub fn delete_array(&self) {
assert_eq!(self.offset, 0, "ub: invalid delete");
let weak = match self.kind {
PtrKind::HeapArray(ref weak) => weak,
match &self.kind {
PtrKind::HeapArray(weak) => {
assert_eq!(self.offset, 0, "ub: invalid delete");
assert_eq!(Weak::strong_count(weak), 1, "ub: invalid delete");
unsafe {
let strong = weak.upgrade().expect("ub: dangling pointer");
Rc::from_raw(Rc::as_ptr(&strong));
}
assert_eq!(Weak::strong_count(weak), 0, "ub: double free");
}
PtrKind::Reinterpreted(data) => data.alloc.delete(),
PtrKind::Null => {}
_ => panic!("ub: invalid delete"),
};
assert_eq!(Weak::strong_count(weak), 1, "ub: invalid delete");
unsafe {
let strong = weak.upgrade().expect("ub: dangling pointer");
Rc::from_raw(Rc::as_ptr(&strong));
}
assert_eq!(Weak::strong_count(weak), 0, "ub: strong count is not zero");
}

#[inline]
Expand Down Expand Up @@ -1109,6 +1115,10 @@ impl AnyPtr {
}
self.ptr.as_bytes().reinterpret_cast::<T>()
}

pub fn is_null(&self) -> bool {
self.ptr.is_null()
}
}

impl PartialEq for AnyPtr {
Expand Down
24 changes: 23 additions & 1 deletion libcc2rs/src/reinterpret.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// Copyright (c) 2022-present INESC-ID.
// Distributed under the MIT license that can be found in the LICENSE file.

use std::{cell::RefCell, rc::Weak};
use std::{
cell::RefCell,
rc::{Rc, Weak},
};

pub trait ByteRepr: 'static {
fn byte_size() -> usize
Expand Down Expand Up @@ -100,6 +103,7 @@ pub trait OriginalAlloc {
fn total_byte_len(&self) -> usize;
// Stable address used for pointer equality across PtrKind variants.
fn address(&self) -> usize;
fn delete(&self);
}

// Read bytes starting at `byte_offset` from a slice of S elements into `buf`.
Expand Down Expand Up @@ -165,6 +169,15 @@ impl<T: ByteRepr> OriginalAlloc for SingleOriginalAlloc<T> {
fn address(&self) -> usize {
self.weak.as_ptr() as usize
}

fn delete(&self) {
assert_eq!(Weak::strong_count(&self.weak), 1, "ub: invalid delete");
unsafe {
let strong = self.weak.upgrade().expect("ub: dangling pointer");
Rc::from_raw(Rc::as_ptr(&strong));
}
assert_eq!(Weak::strong_count(&self.weak), 0, "ub: double free");
}
}

pub(crate) trait AsSlice {
Expand Down Expand Up @@ -219,4 +232,13 @@ impl<T: AsSlice + 'static> OriginalAlloc for SliceOriginalAlloc<T> {
fn address(&self) -> usize {
self.weak.as_ptr() as usize
}

fn delete(&self) {
assert_eq!(Weak::strong_count(&self.weak), 1, "ub: invalid delete");
unsafe {
let strong = self.weak.upgrade().expect("ub: dangling pointer");
Rc::from_raw(Rc::as_ptr(&strong));
}
assert_eq!(Weak::strong_count(&self.weak), 0, "ub: double free");
}
}
20 changes: 20 additions & 0 deletions rules/cstdlib/tgt_refcount.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) 2022-present INESC-ID.
// Distributed under the MIT license that can be found in the LICENSE file.

use libcc2rs::*;

fn f2(a0: AnyPtr) {
libcc2rs::free_refcount(a0)
}

fn f3(a0: usize) -> AnyPtr {
libcc2rs::malloc_refcount(a0)
}

fn f4(a0: AnyPtr, a1: usize) -> AnyPtr {
libcc2rs::realloc_refcount(a0, a1)
}

fn f5(a0: usize, a1: usize) -> AnyPtr {
libcc2rs::calloc_refcount(a0, a1)
}
4 changes: 4 additions & 0 deletions rules/cstring/tgt_refcount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ fn f4(a0: AnyPtr, a1: AnyPtr, a2: usize) -> AnyPtr {
unsafe fn f7(a0: Ptr<u8>) -> usize {
a0.to_string_iterator().count()
}

fn f15(a0: Ptr<u8>) -> Ptr<u8> {
libcc2rs::strdup_refcount(a0)
}
2 changes: 2 additions & 0 deletions rules/src/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ pub mod carray_tgt_refcount;
pub mod carray_tgt_unsafe;
#[path = r#"../cmath/tgt_unsafe.rs"#]
pub mod cmath_tgt_unsafe;
#[path = r#"../cstdlib/tgt_refcount.rs"#]
pub mod cstdlib_tgt_refcount;
#[path = r#"../cstdlib/tgt_unsafe.rs"#]
pub mod cstdlib_tgt_unsafe;
#[path = r#"../cstring/tgt_refcount.rs"#]
Expand Down
1 change: 0 additions & 1 deletion tests/unit/malloc_realloc_free.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// no-compile: refcount
#include <assert.h>
#include <stdlib.h>

Expand Down
151 changes: 151 additions & 0 deletions tests/unit/out/refcount/malloc_realloc_free.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
extern crate libcc2rs;
use libcc2rs::*;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::prelude::*;
use std::io::{Read, Seek, Write};
use std::os::fd::AsFd;
use std::rc::{Rc, Weak};
pub fn main() {
std::process::exit(main_0());
}
fn main_0() -> i32 {
let mut __do_while = true;
'loop_: while __do_while || (0 != 0) {
__do_while = false;
let p: Value<Ptr<i32>> = Rc::new(RefCell::new(
libcc2rs::malloc_refcount(::std::mem::size_of::<i32>()).reinterpret_cast::<i32>(),
));
(*p.borrow()).write(42);
assert!((((((*p.borrow()).read()) == 42) as i32) != 0));
libcc2rs::free_refcount(((*p.borrow()).clone() as Ptr<i32>).to_any());
let arr: Value<Ptr<i32>> = Rc::new(RefCell::new(
libcc2rs::malloc_refcount(
(4_usize).wrapping_mul((::std::mem::size_of::<i32>() as usize)),
)
.reinterpret_cast::<i32>(),
));
let i: Value<i32> = Rc::new(RefCell::new(0));
'loop_: while ((((*i.borrow()) < 4) as i32) != 0) {
let __rhs = ((*i.borrow()) * 10);
(*arr.borrow()).offset((*i.borrow()) as isize).write(__rhs);
(*i.borrow_mut()).postfix_inc();
}
assert!((((((*arr.borrow()).offset((0) as isize).read()) == 0) as i32) != 0));
assert!((((((*arr.borrow()).offset((3) as isize).read()) == 30) as i32) != 0));
libcc2rs::free_refcount(((*arr.borrow()).clone() as Ptr<i32>).to_any());
let grow: Value<Ptr<i32>> = Rc::new(RefCell::new(
libcc2rs::malloc_refcount(
(2_usize).wrapping_mul((::std::mem::size_of::<i32>() as usize)),
)
.reinterpret_cast::<i32>(),
));
(*grow.borrow()).offset((0) as isize).write(1);
(*grow.borrow()).offset((1) as isize).write(2);
let __rhs = libcc2rs::realloc_refcount(
((*grow.borrow()).clone() as Ptr<i32>).to_any(),
(4_usize).wrapping_mul((::std::mem::size_of::<i32>() as usize)),
)
.reinterpret_cast::<i32>();
(*grow.borrow_mut()) = __rhs;
(*grow.borrow()).offset((2) as isize).write(3);
(*grow.borrow()).offset((3) as isize).write(4);
assert!((((((*grow.borrow()).offset((0) as isize).read()) == 1) as i32) != 0));
assert!((((((*grow.borrow()).offset((1) as isize).read()) == 2) as i32) != 0));
assert!((((((*grow.borrow()).offset((2) as isize).read()) == 3) as i32) != 0));
assert!((((((*grow.borrow()).offset((3) as isize).read()) == 4) as i32) != 0));
libcc2rs::free_refcount(((*grow.borrow()).clone() as Ptr<i32>).to_any());
let zeros: Value<Ptr<i32>> = Rc::new(RefCell::new(
libcc2rs::calloc_refcount(4_usize, ::std::mem::size_of::<i32>())
.reinterpret_cast::<i32>(),
));
let i: Value<i32> = Rc::new(RefCell::new(0));
'loop_: while ((((*i.borrow()) < 4) as i32) != 0) {
assert!(
(((((*zeros.borrow()).offset((*i.borrow()) as isize).read()) == 0) as i32) != 0)
);
(*i.borrow_mut()).postfix_inc();
}
libcc2rs::free_refcount(((*zeros.borrow()).clone() as Ptr<i32>).to_any());
}
let pmalloc: Value<FnPtr<fn(usize) -> AnyPtr>> =
Rc::new(RefCell::new(FnPtr::<fn(usize) -> AnyPtr>::new(
libcc2rs::malloc_refcount,
)));
let pfree: Value<FnPtr<fn(AnyPtr)>> = Rc::new(RefCell::new(FnPtr::<fn(AnyPtr)>::new(
libcc2rs::free_refcount,
)));
let prealloc: Value<FnPtr<fn(AnyPtr, usize) -> AnyPtr>> =
Rc::new(RefCell::new(FnPtr::<fn(AnyPtr, usize) -> AnyPtr>::new(
libcc2rs::realloc_refcount,
)));
let pcalloc: Value<FnPtr<fn(usize, usize) -> AnyPtr>> =
Rc::new(RefCell::new(FnPtr::<fn(usize, usize) -> AnyPtr>::new(
libcc2rs::calloc_refcount,
)));
let mut __do_while = true;
'loop_: while __do_while || (0 != 0) {
__do_while = false;
let p: Value<Ptr<i32>> = Rc::new(RefCell::new(
({ (*(*pmalloc.borrow()))(::std::mem::size_of::<i32>()) }).reinterpret_cast::<i32>(),
));
(*p.borrow()).write(42);
assert!((((((*p.borrow()).read()) == 42) as i32) != 0));
({ (*(*pfree.borrow()))(((*p.borrow()).clone() as Ptr<i32>).to_any()) });
let arr: Value<Ptr<i32>> = Rc::new(RefCell::new(
({
(*(*pmalloc.borrow()))(
(4_usize).wrapping_mul((::std::mem::size_of::<i32>() as usize)),
)
})
.reinterpret_cast::<i32>(),
));
let i: Value<i32> = Rc::new(RefCell::new(0));
'loop_: while ((((*i.borrow()) < 4) as i32) != 0) {
let __rhs = ((*i.borrow()) * 10);
(*arr.borrow()).offset((*i.borrow()) as isize).write(__rhs);
(*i.borrow_mut()).postfix_inc();
}
assert!((((((*arr.borrow()).offset((0) as isize).read()) == 0) as i32) != 0));
assert!((((((*arr.borrow()).offset((3) as isize).read()) == 30) as i32) != 0));
({ (*(*pfree.borrow()))(((*arr.borrow()).clone() as Ptr<i32>).to_any()) });
let grow: Value<Ptr<i32>> = Rc::new(RefCell::new(
({
(*(*pmalloc.borrow()))(
(2_usize).wrapping_mul((::std::mem::size_of::<i32>() as usize)),
)
})
.reinterpret_cast::<i32>(),
));
(*grow.borrow()).offset((0) as isize).write(1);
(*grow.borrow()).offset((1) as isize).write(2);
let __rhs = ({
(*(*prealloc.borrow()))(
((*grow.borrow()).clone() as Ptr<i32>).to_any(),
(4_usize).wrapping_mul((::std::mem::size_of::<i32>() as usize)),
)
})
.reinterpret_cast::<i32>();
(*grow.borrow_mut()) = __rhs;
(*grow.borrow()).offset((2) as isize).write(3);
(*grow.borrow()).offset((3) as isize).write(4);
assert!((((((*grow.borrow()).offset((0) as isize).read()) == 1) as i32) != 0));
assert!((((((*grow.borrow()).offset((1) as isize).read()) == 2) as i32) != 0));
assert!((((((*grow.borrow()).offset((2) as isize).read()) == 3) as i32) != 0));
assert!((((((*grow.borrow()).offset((3) as isize).read()) == 4) as i32) != 0));
({ (*(*pfree.borrow()))(((*grow.borrow()).clone() as Ptr<i32>).to_any()) });
let zeros: Value<Ptr<i32>> = Rc::new(RefCell::new(
({ (*(*pcalloc.borrow()))(4_usize, ::std::mem::size_of::<i32>()) })
.reinterpret_cast::<i32>(),
));
let i: Value<i32> = Rc::new(RefCell::new(0));
'loop_: while ((((*i.borrow()) < 4) as i32) != 0) {
assert!(
(((((*zeros.borrow()).offset((*i.borrow()) as isize).read()) == 0) as i32) != 0)
);
(*i.borrow_mut()).postfix_inc();
}
({ (*(*pfree.borrow()))(((*zeros.borrow()).clone() as Ptr<i32>).to_any()) });
}
return 0;
}
Loading
Loading