Skip to content
Open
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
219 changes: 163 additions & 56 deletions cpp2rust/converter/converter.cpp

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions cpp2rust/converter/converter.h
Original file line number Diff line number Diff line change
Expand Up @@ -1294,6 +1294,12 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
// converts the pointer to it to a pointer to that type.
std::optional<clang::QualType> new_pointee_;

// Controls whether an array new expression emits a leaked Box<[T]> (for
// std::unique_ptr<T[]> construction and reset in unsafe mode) instead of a
// raw header-prefixed array pointer.
bool array_new_as_box_ = false;
std::optional<std::pair<const clang::Expr *, size_t>> box_array_arg_;

// Converts a full expression with convert, in a block that declares the
// temporaries that live through it, if there are any.
void ConvertFullExpression(llvm::function_ref<void()> convert);
Expand Down
326 changes: 326 additions & 0 deletions libcc2rs/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,329 @@ pub unsafe fn calloc_unsafe(a0: usize, a1: usize) -> *mut libc::c_void {
pub unsafe fn strdup_unsafe(a0: *const libc::c_char) -> *mut libc::c_char {
unsafe { libc::strdup(a0) }
}

const fn array_header_size<T>() -> usize {
let align = if std::mem::align_of::<T>() > std::mem::align_of::<usize>() {
std::mem::align_of::<T>()
} else {
std::mem::align_of::<usize>()
};
std::mem::size_of::<usize>().next_multiple_of(align)
}

fn array_layout_unsafe<T>(len: usize) -> (std::alloc::Layout, usize) {
let align = std::mem::align_of::<T>().max(std::mem::align_of::<usize>());
let header_size = array_header_size::<T>();
let payload_size = len
.checked_mul(std::mem::size_of::<T>())
.expect("array allocation size overflow");
let total_size = header_size
.checked_add(payload_size)
.expect("array allocation size overflow");
let layout = std::alloc::Layout::from_size_align(total_size, align)
.expect("invalid array allocation layout");
(layout, header_size)
}

struct ArrayInitGuard<T> {
base: *mut u8,
layout: std::alloc::Layout,
data: *mut T,
initialized: usize,
}

impl<T> Drop for ArrayInitGuard<T> {
fn drop(&mut self) {
unsafe {
if std::mem::needs_drop::<T>() {
for i in (0..self.initialized).rev() {
std::ptr::drop_in_place(self.data.add(i));
}
}
std::alloc::dealloc(self.base, self.layout);
}
}
}

fn alloc_array_raw_unsafe<T>(len: usize) -> (*mut u8, std::alloc::Layout, *mut T) {
let (layout, header_size) = array_layout_unsafe::<T>(len);
let base = unsafe { std::alloc::alloc(layout) };
if base.is_null() {
std::alloc::handle_alloc_error(layout);
}
unsafe {
base.cast::<usize>().write(len);
let data = base.add(header_size).cast::<T>();
(base, layout, data)
}
}

pub fn alloc_array_unsafe<T>(len: usize, mut init: impl FnMut() -> T) -> *mut T {
let (base, layout, data) = alloc_array_raw_unsafe::<T>(len);
let mut guard = ArrayInitGuard {
base,
layout,
data,
initialized: 0,
};
for i in 0..len {
unsafe {
data.add(i).write(init());
}
guard.initialized = i + 1;
}
std::mem::forget(guard);
data
}

pub fn alloc_array_from_unsafe<T, const N: usize>(elems: [T; N]) -> *mut T {
let (_, _, data) = alloc_array_raw_unsafe::<T>(N);
let elems = std::mem::ManuallyDrop::new(elems);
unsafe {
std::ptr::copy_nonoverlapping(elems.as_ptr(), data, N);
}
data
}

/// # Safety
///
/// `ptr` must be a non-null pointer returned by [`alloc_array_unsafe`] or
/// [`alloc_array_from_unsafe`] for the same element type `T`, and must not have
/// been deallocated.
pub unsafe fn array_len_unsafe<T>(ptr: *mut T) -> usize {
let header_size = array_header_size::<T>();
unsafe { ptr.cast::<u8>().sub(header_size).cast::<usize>().read() }
}

/// # Safety
///
/// `ptr` must be null or a pointer returned by [`alloc_array_unsafe`] or
/// [`alloc_array_from_unsafe`] for the same element type `T`, and must not have
/// been deallocated.
pub unsafe fn dealloc_array_unsafe<T>(ptr: *mut T) {
if ptr.is_null() {
return;
}
let header_size = array_header_size::<T>();
let base = unsafe { ptr.cast::<u8>().sub(header_size) };
let len = unsafe { base.cast::<usize>().read() };
let (layout, _) = array_layout_unsafe::<T>(len);
struct DeallocGuard {
base: *mut u8,
layout: std::alloc::Layout,
}
impl Drop for DeallocGuard {
fn drop(&mut self) {
unsafe {
std::alloc::dealloc(self.base, self.layout);
}
}
}
let _guard = DeallocGuard { base, layout };
if std::mem::needs_drop::<T>() {
for i in (0..len).rev() {
unsafe {
std::ptr::drop_in_place(ptr.add(i));
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
use std::rc::Rc;

struct DropTracker {
id: usize,
log: Rc<RefCell<Vec<usize>>>,
}

impl Drop for DropTracker {
fn drop(&mut self) {
self.log.borrow_mut().push(self.id);
}
}

#[repr(align(64))]
struct Aligned64 {
id: usize,
log: Rc<RefCell<Vec<usize>>>,
}

impl Drop for Aligned64 {
fn drop(&mut self) {
self.log.borrow_mut().push(self.id);
}
}

thread_local! {
static ZST_DROPS: RefCell<usize> = const { RefCell::new(0) };
}

struct ZstDrop;

impl Drop for ZstDrop {
fn drop(&mut self) {
ZST_DROPS.with(|c| *c.borrow_mut() += 1);
}
}

#[test]
fn alloc_and_dealloc_reverse_drop_order() {
let log = Rc::new(RefCell::new(Vec::new()));
let mut next = 1usize;
let ptr = alloc_array_unsafe(3, || {
let id = next;
next += 1;
DropTracker {
id,
log: Rc::clone(&log),
}
});
assert!(!ptr.is_null());
unsafe {
assert_eq!(array_len_unsafe(ptr), 3);
assert_eq!((*ptr.add(0)).id, 1);
assert_eq!((*ptr.add(1)).id, 2);
assert_eq!((*ptr.add(2)).id, 3);
dealloc_array_unsafe(ptr);
}
assert_eq!(*log.borrow(), vec![3, 2, 1]);
}

#[test]
fn dealloc_null_is_noop() {
unsafe {
dealloc_array_unsafe(std::ptr::null_mut::<DropTracker>());
}
}

#[test]
fn zero_length_allocations_are_non_null_and_distinct() {
let log = Rc::new(RefCell::new(Vec::new()));
let p1 = alloc_array_unsafe(0, || DropTracker {
id: 99,
log: Rc::clone(&log),
});
let p2 = alloc_array_unsafe(0, || DropTracker {
id: 100,
log: Rc::clone(&log),
});
assert!(!p1.is_null());
assert!(!p2.is_null());
assert_ne!(p1, p2);
unsafe {
assert_eq!(array_len_unsafe(p1), 0);
assert_eq!(array_len_unsafe(p2), 0);
dealloc_array_unsafe(p1);
dealloc_array_unsafe(p2);
}
assert!(log.borrow().is_empty());
}

#[test]
fn init_panic_drops_initialized_prefix_in_reverse() {
let log = Rc::new(RefCell::new(Vec::new()));
let log_clone = Rc::clone(&log);
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
let mut idx = 0usize;
let _ = alloc_array_unsafe(5, || {
if idx == 2 {
panic!("init failed at 2");
}
let id = idx;
idx += 1;
DropTracker {
id,
log: Rc::clone(&log_clone),
}
});
}));
assert!(result.is_err());
assert_eq!(*log.borrow(), vec![1, 0]);
}

#[test]
fn alloc_array_from_non_empty_and_empty() {
let log = Rc::new(RefCell::new(Vec::new()));
let ptr = alloc_array_from_unsafe([
DropTracker {
id: 10,
log: Rc::clone(&log),
},
DropTracker {
id: 20,
log: Rc::clone(&log),
},
DropTracker {
id: 30,
log: Rc::clone(&log),
},
]);
assert!(!ptr.is_null());
unsafe {
assert_eq!(array_len_unsafe(ptr), 3);
assert_eq!((*ptr.add(0)).id, 10);
assert_eq!((*ptr.add(2)).id, 30);
dealloc_array_unsafe(ptr);
}
assert_eq!(*log.borrow(), vec![30, 20, 10]);

let empty: *mut DropTracker = alloc_array_from_unsafe([]);
assert!(!empty.is_null());
unsafe {
assert_eq!(array_len_unsafe(empty), 0);
dealloc_array_unsafe(empty);
}
assert_eq!(*log.borrow(), vec![30, 20, 10]);
}

#[test]
fn over_aligned_and_zst_drop_layouts() {
let log = Rc::new(RefCell::new(Vec::new()));
let mut next = 1usize;
let ptr = alloc_array_unsafe(2, || {
let id = next;
next += 1;
Aligned64 {
id,
log: Rc::clone(&log),
}
});
assert!(!ptr.is_null());
assert_eq!((ptr as usize) % 64, 0);
unsafe {
assert_eq!(array_len_unsafe(ptr), 2);
dealloc_array_unsafe(ptr);
}
assert_eq!(*log.borrow(), vec![2, 1]);

let empty_aligned = alloc_array_unsafe(0, || Aligned64 {
id: 0,
log: Rc::clone(&log),
});
assert!(!empty_aligned.is_null());
assert_eq!((empty_aligned as usize) % 64, 0);
unsafe {
assert_eq!(array_len_unsafe(empty_aligned), 0);
dealloc_array_unsafe(empty_aligned);
}

ZST_DROPS.with(|c| *c.borrow_mut() = 0);
let z0 = alloc_array_unsafe(0, || ZstDrop);
let z4 = alloc_array_unsafe(4, || ZstDrop);
assert!(!z0.is_null());
assert!(!z4.is_null());
assert_ne!(z0, z4);
unsafe {
assert_eq!(array_len_unsafe(z0), 0);
assert_eq!(array_len_unsafe(z4), 4);
dealloc_array_unsafe(z0);
assert_eq!(ZST_DROPS.with(|c| *c.borrow()), 0);
dealloc_array_unsafe(z4);
assert_eq!(ZST_DROPS.with(|c| *c.borrow()), 4);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,7 @@ pub unsafe fn test_21() {
i.prefix_inc();
}
}
let mut heap_numbers: *mut i32 =
Box::leak((0..3_usize).map(|_| 0_i32).collect::<Box<[i32]>>()).as_mut_ptr();
let mut heap_numbers: *mut i32 = libcc2rs::alloc_array_unsafe::<i32>(3_usize, || 0_i32);
{
let mut i: i32 = 0;
'loop_: while ((i) < (3)) {
Expand All @@ -318,11 +317,7 @@ pub unsafe fn test_21() {
{
let __p = heap_numbers;
if !__p.is_null() {
::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut(
__p,
libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void)
/ ::std::mem::size_of::<i32>(),
)))
libcc2rs::dealloc_array_unsafe(__p);
}
};
}
Expand Down
8 changes: 2 additions & 6 deletions tests/ub/out/unsafe/int_to_ptr_dangling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,12 @@ pub fn main() {
}
}
unsafe fn main_0() -> i32 {
let mut p: *mut i32 = Box::leak(Box::new([1, 2])).as_mut_ptr();
let mut p: *mut i32 = libcc2rs::alloc_array_from_unsafe::<i32, _>([1, 2]);
let mut i: usize = (p as usize);
{
let __p = p;
if !__p.is_null() {
::std::mem::drop(Box::from_raw(::std::slice::from_raw_parts_mut(
__p,
libcc2rs::malloc_usable_size(__p as *mut ::libc::c_void)
/ ::std::mem::size_of::<i32>(),
)))
libcc2rs::dealloc_array_unsafe(__p);
}
};
return (*(i as *mut i32).offset((1) as isize));
Expand Down
Loading
Loading