From 08d848ccdd21c034d3ad06483b8f350919bac17c Mon Sep 17 00:00:00 2001 From: Perfloop Agent Date: Sat, 7 Nov 2026 04:15:40 +0000 Subject: [PATCH 1/2] Keep temporaries alive while a pointer to their field is used MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the refcount model, a pointer to a field of a temporary, such as the receiver of `f().s.substr(1, 2)`, was made inside the block of the field_ref!, field_ptr! or array_field_ptr! macro. Rust 2024 drops the temporaries of the tail expression of a block at the end of the block, so the temporary was dropped before the pointer was used, and the program panicked with "ub: dangling pointer". Bind a pointer to the temporary in a match around the field macros instead, so that the temporary lives until the end of the enclosing statement or block, which covers uses within the same expression, such as substr. The temporary is materialized like other temporaries whose address is taken, which also makes pointers to fields of aggregate temporaries, such as `T{...}.v`, compile. Signed-off-by: Perfloop Agent Signed-off-by: Tomás Senart --- .../converter/models/converter_refcount.cpp | 60 +++++- .../converter/models/converter_refcount.h | 13 ++ .../unit/out/refcount/temporary_field_addr.rs | 178 ++++++++++++++++++ tests/unit/out/unsafe/temporary_field_addr.rs | 120 ++++++++++++ tests/unit/temporary_field_addr.cpp | 38 ++++ 5 files changed, 400 insertions(+), 9 deletions(-) create mode 100644 tests/unit/out/refcount/temporary_field_addr.rs create mode 100644 tests/unit/out/unsafe/temporary_field_addr.rs create mode 100644 tests/unit/temporary_field_addr.cpp diff --git a/cpp2rust/converter/models/converter_refcount.cpp b/cpp2rust/converter/models/converter_refcount.cpp index 94d199073a..05aa3be4b1 100644 --- a/cpp2rust/converter/models/converter_refcount.cpp +++ b/cpp2rust/converter/models/converter_refcount.cpp @@ -1821,21 +1821,55 @@ bool ConverterRefCount::VisitMemberExpr(clang::MemberExpr *expr) { return false; } +// The temporary that `expr` is a field of, or a field of a field of, e.g., +// the result of f() in f().a.b. +static clang::Expr *GetFieldTemporary(clang::ASTContext &ctx, + clang::MemberExpr *expr) { + clang::Expr *base = expr; + while (auto *member = clang::dyn_cast(base)) { + if (member->isArrow()) { + return nullptr; + } + base = member->getBase()->IgnoreParenNoopCasts(ctx); + } + return clang::isa(base) ? base : nullptr; +} + void ConverterRefCount::ConvertInlineField(clang::MemberExpr *expr) { auto name = GetNamedDeclAsString(expr->getMemberDecl()); auto type = expr->getType(); auto *base = expr->getBase(); if (isAddrOf()) { - // A pointer to the struct, offset to the field. An array decays to a - // pointer to its first element, and a vector can be used as one. - if (type->isArrayType()) { - StrCat(std::format("array_field_ptr!({}, {})", ConvertRecordPtr(expr), - name)); - } else if (IsBoxedType(type)) { - StrCat(std::format("field_ref!({}, {}){}", ConvertRecordPtr(expr), name, - AsPointerMethod(type))); + // The outermost field of a temporary binds a pointer to the temporary. + FieldTemporary temporary{GetFieldTemporary(ctx_, expr), ""}; + bool outermost = temporary.temporary && + (!field_temporary_ || + field_temporary_->temporary != temporary.temporary); + std::string str; + { + Buffer buf(*this); + ScopedValue push(field_temporary_, + outermost ? &temporary : field_temporary_); + // A pointer to the struct, offset to the field. An array decays to a + // pointer to its first element, and a vector can be used as one. + if (type->isArrayType()) { + StrCat(std::format("array_field_ptr!({}, {})", ConvertRecordPtr(expr), + name)); + } else if (IsBoxedType(type)) { + StrCat(std::format("field_ref!({}, {}){}", ConvertRecordPtr(expr), name, + AsPointerMethod(type))); + } else { + StrCat(std::format("field_ptr!({}, {})", ConvertRecordPtr(expr), name)); + } + str = std::move(buf).str(); + } + if (temporary.var.empty()) { + StrCat(str); } else { - StrCat(std::format("field_ptr!({}, {})", ConvertRecordPtr(expr), name)); + PushParen paren(*this); + StrCat("match", ConvertTemporaryPointer(temporary.temporary, {})); + PushBrace brace(*this); + StrCat(temporary.var, "=>", str); } MarkFresh(); return; @@ -1878,6 +1912,14 @@ void ConverterRefCount::ConvertInlineField(clang::MemberExpr *expr) { } std::string ConverterRefCount::ConvertRecordPtr(clang::MemberExpr *expr) { + auto *base = expr->getBase()->IgnoreParenNoopCasts(ctx_); + if (field_temporary_ && !expr->isArrow() && + base == field_temporary_->temporary) { + if (field_temporary_->var.empty()) { + field_temporary_->var = NewTempName(); + } + return field_temporary_->var; + } Buffer buf(*this); PushExprKind push(*this, ExprKind::AddrOf); if (expr->isArrow()) { diff --git a/cpp2rust/converter/models/converter_refcount.h b/cpp2rust/converter/models/converter_refcount.h index ed535b487e..8730bdf57d 100644 --- a/cpp2rust/converter/models/converter_refcount.h +++ b/cpp2rust/converter/models/converter_refcount.h @@ -202,6 +202,19 @@ class ConverterRefCount final : public Converter { std::string *record_ptr_ = nullptr; const clang::Expr *record_base_ = nullptr; + // The temporary whose field, or field of a field, a pointer is being made + // to, e.g., the result of f() in &f().a.b, and the variable that a match + // binds a pointer to the temporary to. The temporaries in the block of a + // field macro end with the block, while those of the matched value live + // until the end of the enclosing statement or block. That can be before + // the end of the C++ full-expression, e.g., for a call argument that is + // bound to a variable or converted in a block of its own. + struct FieldTemporary { + clang::Expr *temporary; + std::string var; + }; + FieldTemporary *field_temporary_ = nullptr; + // The expression that ConvertFreshRValue copies. const clang::Expr *copied_expr_ = nullptr; diff --git a/tests/unit/out/refcount/temporary_field_addr.rs b/tests/unit/out/refcount/temporary_field_addr.rs new file mode 100644 index 0000000000..8930305995 --- /dev/null +++ b/tests/unit/out/refcount/temporary_field_addr.rs @@ -0,0 +1,178 @@ +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}; +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign, Default)] +#[byte_size(24)] +pub struct Inner { + #[offset(0)] + #[byte_size(24)] + pub values: Vec, +} +impl Inner { + pub fn move_from(_a0: Ptr) -> Self { + Self { + values: field!(_a0, values).with_mut(std::mem::take), + } + } +} +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign)] +#[byte_size(56)] +pub struct Outer { + #[offset(0)] + #[byte_size(24)] + pub values: Vec, + #[offset(24)] + #[byte_size(24)] + pub inner: Inner, + #[offset(48)] + #[byte_size(8)] + pub name: Box<[i8]>, +} +impl Outer { + pub fn move_from(_a0: Ptr) -> Self { + Self { + values: field!(_a0, values).with_mut(std::mem::take), + inner: Inner::move_from({ field_ptr!(_a0, inner) }), + name: Box::new(std::array::from_fn::<_, 8, _>(|__i: usize| { + (*_a0.upgrade().deref()).name[(__i) as usize] + })), + } + } +} +impl Default for Outer { + fn default() -> Self { + { + Outer { + values: Default::default(), + inner: ::default(), + name: (0..8).map(|_| 0_i8).collect::>(), + } + } + } +} +pub fn make_0(calls: Ptr) -> Outer { + calls.with_mut(|__v| __v.prefix_inc()); + return Outer { + values: Vec::from([1, 2, 3]), + inner: Inner { + values: Vec::from([4, 5, 6]), + }, + name: i8::array_from_literal(b"abc\0\0\0\0\0"), + }; +} +pub fn sum_1(values: Ptr>) -> i32 { + let mut total: i32 = 0; + 'loop_: for value in IterRange::new(values.decay().begin(), values.decay().end()) { + let mut value: i32 = (value.iter_deref().read()); + total += value; + } + return total; +} +pub fn main() { + __cpp2rust_init_globals(); + std::process::exit(main_0()); +} +fn main_0() -> i32 { + let calls: Value = Rc::new(RefCell::new(0)); + let mut member: i32 = ({ + sum_1( + (match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() { + __tmp_1 => field_ref!(__tmp_1, values).as_pointer(), + }), + ) + }); + let mut nested: i32 = ({ + sum_1( + (match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() { + __tmp_2 => field_ref!(field_ptr!(__tmp_2, inner), values).as_pointer(), + }), + ) + }); + let mut element: i32 = (match ( + (match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() { + __tmp_4 => field_ref!(__tmp_4, values).as_pointer(), + }), + { (((*calls.borrow()) - 2) as usize) }, + ) { + (__tmp_3, mut __tmp_5) => { + if __tmp_5 as usize >= __tmp_3.decay().len() { + panic!("out of bounds access") + } else { + __tmp_3.decay().offset(__tmp_5 as isize) + } + } + } + .read()); + let mut length: usize = + ((match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() { + __tmp_6 => array_field_ptr!(__tmp_6, name), + }) as Ptr) + .to_c_string_iterator() + .count(); + let mut aggregate: i32 = ({ + sum_1( + (match Rc::new(RefCell::new(Outer { + values: Vec::from([7]), + inner: Inner { + values: Vec::from([8, 9]), + }, + name: i8::array_from_literal(b"x\0\0\0\0\0\0\0"), + })) + .as_pointer() + { + __tmp_7 => field_ref!(field_ptr!(__tmp_7, inner), values).as_pointer(), + }), + ) + }); + println!( + "{} {} {} {} {} {}", + member, + nested, + element, + length, + aggregate, + (*calls.borrow()) + ); + return 0; +} +pub trait InnerImpl { + fn move_assign(&self, _a0: Ptr) -> Ptr; +} +impl InnerImpl for Ptr { + fn move_assign(&self, _a0: Ptr) -> Ptr { + field_ref!((*self), values) + .as_pointer() + .write(field!(_a0, values).with_mut(std::mem::take)); + return (*self).clone(); + } +} +pub trait OuterImpl { + fn move_assign(&self, _a0: Ptr) -> Ptr; +} +impl OuterImpl for Ptr { + fn move_assign(&self, _a0: Ptr) -> Ptr { + field_ref!((*self), values) + .as_pointer() + .write(field!(_a0, values).with_mut(std::mem::take)); + ({ + let _arg0: Ptr = field_ptr!(_a0, inner); + InnerImpl::move_assign(&field_ptr!((*self), inner), _arg0) + }); + match ({ ((array_field_ptr!((*self), name)) as Ptr).to_any() },) { + (mut __tmp_0,) => { + __tmp_0.memcpy( + &((array_field_ptr!(_a0, name)) as Ptr).to_any(), + 8_usize as usize, + ); + (__tmp_0).clone() + } + }; + return (*self).clone(); + } +} +pub fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/unsafe/temporary_field_addr.rs b/tests/unit/out/unsafe/temporary_field_addr.rs new file mode 100644 index 0000000000..80d714725e --- /dev/null +++ b/tests/unit/out/unsafe/temporary_field_addr.rs @@ -0,0 +1,120 @@ +extern crate libc; +use libc::*; +extern crate libcc2rs; +use libcc2rs::*; +use std::collections::BTreeMap; +use std::io::{Read, Seek, Write}; +use std::os::fd::{AsFd, FromRawFd, IntoRawFd}; +use std::rc::Rc; +#[repr(C)] +#[derive(Clone, VaArg, FnPtrArg, MoveCtorUnsafe, MoveAssignUnsafe, Default)] +pub struct Inner { + pub values: Vec, +} +impl Inner { + pub unsafe fn move_from(_a0: *mut Inner) -> Self { + let mut this = Self { + values: std::mem::take(&mut (*_a0).values), + }; + this + } + pub unsafe fn move_assign(&mut self, _a0: *mut Inner) -> *mut Inner { + self.values = std::mem::take(&mut (*_a0).values); + return &mut (*(self as *mut Inner)); + } +} +#[repr(C)] +#[derive(Clone, VaArg, FnPtrArg, MoveCtorUnsafe, MoveAssignUnsafe, Default)] +pub struct Outer { + pub values: Vec, + pub inner: Inner, + pub name: [libc::c_char; 8], +} +impl Outer { + pub unsafe fn move_from(_a0: *mut Outer) -> Self { + let mut this = Self { + values: std::mem::take(&mut (*_a0).values), + inner: Inner::move_from({ &mut (*_a0).inner }), + name: std::array::from_fn::<_, 8, _>(|__i: usize| (*_a0).name[(__i)]), + }; + this + } + pub unsafe fn move_assign(&mut self, _a0: *mut Outer) -> *mut Outer { + self.values = std::mem::take(&mut (*_a0).values); + (unsafe { + let _arg0: *mut Inner = &mut (*_a0).inner; + Inner::move_assign(&mut self.inner, _arg0) + }); + match ( + { ((&mut self.name as *mut [libc::c_char; 8]) as *mut ::libc::c_void) }, + { ((&mut (*_a0).name as *mut [libc::c_char; 8]) as *const ::libc::c_void) }, + ) { + (mut __tmp_0, mut __tmp_1) => { + if 8_usize != 0 { + ::std::ptr::copy_nonoverlapping(__tmp_1, __tmp_0, 8_usize as usize) + } + __tmp_0 + } + }; + return &mut (*(self as *mut Outer)); + } +} +pub unsafe fn make_0(calls: *mut i32) -> Outer { + (*calls).prefix_inc(); + return Outer { + values: Vec::from([1, 2, 3]), + inner: Inner { + values: Vec::from([4, 5, 6]), + }, + name: std::mem::transmute(*b"abc\0\0\0\0\0"), + }; +} +pub unsafe fn sum_1(values: *const Vec) -> i32 { + let mut total: i32 = 0; + 'loop_: for value in IterRange::new((*values).begin(), (*values).end()) { + let mut value: i32 = (*value.iter_deref()); + total += value; + } + return total; +} +pub fn main() { + unsafe { + __cpp2rust_init_globals(); + std::process::exit(main_0() as i32); + } +} +unsafe fn main_0() -> i32 { + let mut calls: i32 = 0; + let mut member: i32 = (unsafe { sum_1(&(unsafe { make_0(&mut calls) }).values) }); + let mut nested: i32 = (unsafe { sum_1(&(unsafe { make_0(&mut calls) }).inner.values) }); + let mut element: i32 = (*(&mut ((unsafe { make_0(&mut calls) }).values) + [(((calls) - (2)) as usize) as usize] as *mut i32)); + let mut length: usize = + libc::strlen(((unsafe { make_0(&mut calls) }).name.as_mut_ptr()).cast_const()); + let mut aggregate: i32 = (unsafe { + sum_1( + &Outer { + values: Vec::from([7]), + inner: Inner { + values: Vec::from([8, 9]), + }, + name: std::mem::transmute(*b"x\0\0\0\0\0\0\0"), + } + .inner + .values, + ) + }); + (unsafe { + libc::printf( + c"%d %d %d %zu %d %d\n".as_ptr() as *const libc::c_char, + (member), + (nested), + (element), + (length), + (aggregate), + (calls), + ) + }); + return 0; +} +pub unsafe fn __cpp2rust_init_globals() {} diff --git a/tests/unit/temporary_field_addr.cpp b/tests/unit/temporary_field_addr.cpp new file mode 100644 index 0000000000..15b1f63e9d --- /dev/null +++ b/tests/unit/temporary_field_addr.cpp @@ -0,0 +1,38 @@ +#include +#include +#include + +struct Inner { + std::vector values; +}; + +struct Outer { + std::vector values; + Inner inner; + char name[8]; +}; + +static Outer make(int &calls) { + ++calls; + return {{1, 2, 3}, {{4, 5, 6}}, "abc"}; +} + +static int sum(const std::vector &values) { + int total = 0; + for (int value : values) { + total += value; + } + return total; +} + +int main() { + int calls = 0; + int member = sum(make(calls).values); + int nested = sum(make(calls).inner.values); + int element = make(calls).values.at(calls - 2); + std::size_t length = strlen(make(calls).name); + int aggregate = sum(Outer{{7}, {{8, 9}}, "x"}.inner.values); + printf("%d %d %d %zu %d %d\n", member, nested, element, length, aggregate, + calls); + return 0; +} From 0b173d55d99f911d68e895098884e351c582d863 Mon Sep 17 00:00:00 2001 From: Perfloop Agent Date: Sat, 7 Nov 2026 06:56:16 +0000 Subject: [PATCH 2/2] Test fields of temporaries that still dangle in refcount MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two pointers to fields of temporaries still dangle in the refcount model: two such arguments of one call, which are bound to variables before the call, and a constructor argument, which is converted in a block of its own. Both programs are valid C++, so add a unit test for each that records the refcount translation's panic as an expected failure. The unsafe translation of the constructor argument reads freed memory, so its result is not compared. Signed-off-by: Perfloop Agent Signed-off-by: Tomás Senart --- .../out/refcount/temporary_field_ctor_arg.rs | 66 +++++++++++++ .../out/refcount/temporary_field_two_args.rs | 97 +++++++++++++++++++ .../out/unsafe/temporary_field_ctor_arg.rs | 56 +++++++++++ .../out/unsafe/temporary_field_two_args.rs | 79 +++++++++++++++ tests/unit/temporary_field_ctor_arg.cpp | 26 +++++ tests/unit/temporary_field_two_args.cpp | 28 ++++++ 6 files changed, 352 insertions(+) create mode 100644 tests/unit/out/refcount/temporary_field_ctor_arg.rs create mode 100644 tests/unit/out/refcount/temporary_field_two_args.rs create mode 100644 tests/unit/out/unsafe/temporary_field_ctor_arg.rs create mode 100644 tests/unit/out/unsafe/temporary_field_two_args.rs create mode 100644 tests/unit/temporary_field_ctor_arg.cpp create mode 100644 tests/unit/temporary_field_two_args.cpp diff --git a/tests/unit/out/refcount/temporary_field_ctor_arg.rs b/tests/unit/out/refcount/temporary_field_ctor_arg.rs new file mode 100644 index 0000000000..f5286e479a --- /dev/null +++ b/tests/unit/out/refcount/temporary_field_ctor_arg.rs @@ -0,0 +1,66 @@ +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}; +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign, Default)] +#[byte_size(24)] +pub struct Outer { + #[offset(0)] + #[byte_size(24)] + pub values: Vec, +} +impl Outer { + pub fn move_from(_a0: Ptr) -> Self { + Self { + values: field!(_a0, values).with_mut(std::mem::take), + } + } +} +pub fn make_0() -> Outer { + return Outer { + values: Vec::from([1, 2, 3, 4]), + }; +} +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, CppFrom, Default)] +#[cpp_from(Vec , new, ptr)] +#[byte_size(4)] +pub struct H { + #[offset(0)] + pub last: i32, +} +impl H { + pub fn new(values: Ptr>) -> Self { + Self { + last: (index!(values, 3_usize).read()), + } + } +} +pub fn main() { + __cpp2rust_init_globals(); + std::process::exit(main_0()); +} +fn main_0() -> i32 { + let mut h: H = H::new({ + (match Rc::new(RefCell::new(({ make_0() }))).as_pointer() { + __tmp_0 => field_ref!(__tmp_0, values).as_pointer(), + }) + }); + println!("{}", h.last); + return 0; +} +pub trait OuterImpl { + fn move_assign(&self, _a0: Ptr) -> Ptr; +} +impl OuterImpl for Ptr { + fn move_assign(&self, _a0: Ptr) -> Ptr { + field_ref!((*self), values) + .as_pointer() + .write(field!(_a0, values).with_mut(std::mem::take)); + return (*self).clone(); + } +} +pub fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/refcount/temporary_field_two_args.rs b/tests/unit/out/refcount/temporary_field_two_args.rs new file mode 100644 index 0000000000..46c92e4f26 --- /dev/null +++ b/tests/unit/out/refcount/temporary_field_two_args.rs @@ -0,0 +1,97 @@ +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}; +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign, Default)] +#[byte_size(24)] +pub struct Inner { + #[offset(0)] + #[byte_size(24)] + pub values: Vec, +} +impl Inner { + pub fn move_from(_a0: Ptr) -> Self { + Self { + values: field!(_a0, values).with_mut(std::mem::take), + } + } +} +#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign, Default)] +#[byte_size(48)] +pub struct Outer { + #[offset(0)] + #[byte_size(24)] + pub values: Vec, + #[offset(24)] + #[byte_size(24)] + pub inner: Inner, +} +impl Outer { + pub fn move_from(_a0: Ptr) -> Self { + Self { + values: field!(_a0, values).with_mut(std::mem::take), + inner: Inner::move_from({ field_ptr!(_a0, inner) }), + } + } +} +pub fn make_0() -> Outer { + return Outer { + values: Vec::from([1, 2, 3]), + inner: Inner { + values: Vec::from([4, 5, 6]), + }, + }; +} +pub fn two_1(a: Ptr>, b: Ptr>) -> i32 { + return ({ (index!(a, 0_usize).read()) } + { (index!(b, 2_usize).read()) }); +} +pub fn main() { + __cpp2rust_init_globals(); + std::process::exit(main_0()); +} +fn main_0() -> i32 { + println!( + "{}", + ({ + let _a: Ptr> = (match Rc::new(RefCell::new(({ make_0() }))).as_pointer() { + __tmp_0 => field_ref!(__tmp_0, values).as_pointer(), + }); + let _b: Ptr> = (match Rc::new(RefCell::new(({ make_0() }))).as_pointer() { + __tmp_1 => field_ref!(field_ptr!(__tmp_1, inner), values).as_pointer(), + }); + two_1(_a, _b) + }) + ); + return 0; +} +pub trait InnerImpl { + fn move_assign(&self, _a0: Ptr) -> Ptr; +} +impl InnerImpl for Ptr { + fn move_assign(&self, _a0: Ptr) -> Ptr { + field_ref!((*self), values) + .as_pointer() + .write(field!(_a0, values).with_mut(std::mem::take)); + return (*self).clone(); + } +} +pub trait OuterImpl { + fn move_assign(&self, _a0: Ptr) -> Ptr; +} +impl OuterImpl for Ptr { + fn move_assign(&self, _a0: Ptr) -> Ptr { + field_ref!((*self), values) + .as_pointer() + .write(field!(_a0, values).with_mut(std::mem::take)); + ({ + let _arg0: Ptr = field_ptr!(_a0, inner); + InnerImpl::move_assign(&field_ptr!((*self), inner), _arg0) + }); + return (*self).clone(); + } +} +pub fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/unsafe/temporary_field_ctor_arg.rs b/tests/unit/out/unsafe/temporary_field_ctor_arg.rs new file mode 100644 index 0000000000..8421b4c294 --- /dev/null +++ b/tests/unit/out/unsafe/temporary_field_ctor_arg.rs @@ -0,0 +1,56 @@ +extern crate libc; +use libc::*; +extern crate libcc2rs; +use libcc2rs::*; +use std::collections::BTreeMap; +use std::io::{Read, Seek, Write}; +use std::os::fd::{AsFd, FromRawFd, IntoRawFd}; +use std::rc::Rc; +#[repr(C)] +#[derive(Clone, VaArg, FnPtrArg, MoveCtorUnsafe, MoveAssignUnsafe, Default)] +pub struct Outer { + pub values: Vec, +} +impl Outer { + pub unsafe fn move_from(_a0: *mut Outer) -> Self { + let mut this = Self { + values: std::mem::take(&mut (*_a0).values), + }; + this + } + pub unsafe fn move_assign(&mut self, _a0: *mut Outer) -> *mut Outer { + self.values = std::mem::take(&mut (*_a0).values); + return &mut (*(self as *mut Outer)); + } +} +pub unsafe fn make_0() -> Outer { + return Outer { + values: Vec::from([1, 2, 3, 4]), + }; +} +#[repr(C)] +#[derive(Copy, Clone, VaArg, FnPtrArg, CppFromUnsafe, Default)] +#[cpp_from(Vec , new, ptr)] +pub struct H { + pub last: i32, +} +impl H { + pub unsafe fn new(values: *const Vec) -> Self { + let mut this = Self { + last: (&(*values))[(3_usize)], + }; + this + } +} +pub fn main() { + unsafe { + __cpp2rust_init_globals(); + std::process::exit(main_0() as i32); + } +} +unsafe fn main_0() -> i32 { + let mut h: H = H::new({ &(unsafe { make_0() }).values }); + (unsafe { libc::printf(c"%d\n".as_ptr() as *const libc::c_char, (h.last)) }); + return 0; +} +pub unsafe fn __cpp2rust_init_globals() {} diff --git a/tests/unit/out/unsafe/temporary_field_two_args.rs b/tests/unit/out/unsafe/temporary_field_two_args.rs new file mode 100644 index 0000000000..33f6ad3dfa --- /dev/null +++ b/tests/unit/out/unsafe/temporary_field_two_args.rs @@ -0,0 +1,79 @@ +extern crate libc; +use libc::*; +extern crate libcc2rs; +use libcc2rs::*; +use std::collections::BTreeMap; +use std::io::{Read, Seek, Write}; +use std::os::fd::{AsFd, FromRawFd, IntoRawFd}; +use std::rc::Rc; +#[repr(C)] +#[derive(Clone, VaArg, FnPtrArg, MoveCtorUnsafe, MoveAssignUnsafe, Default)] +pub struct Inner { + pub values: Vec, +} +impl Inner { + pub unsafe fn move_from(_a0: *mut Inner) -> Self { + let mut this = Self { + values: std::mem::take(&mut (*_a0).values), + }; + this + } + pub unsafe fn move_assign(&mut self, _a0: *mut Inner) -> *mut Inner { + self.values = std::mem::take(&mut (*_a0).values); + return &mut (*(self as *mut Inner)); + } +} +#[repr(C)] +#[derive(Clone, VaArg, FnPtrArg, MoveCtorUnsafe, MoveAssignUnsafe, Default)] +pub struct Outer { + pub values: Vec, + pub inner: Inner, +} +impl Outer { + pub unsafe fn move_from(_a0: *mut Outer) -> Self { + let mut this = Self { + values: std::mem::take(&mut (*_a0).values), + inner: Inner::move_from({ &mut (*_a0).inner }), + }; + this + } + pub unsafe fn move_assign(&mut self, _a0: *mut Outer) -> *mut Outer { + self.values = std::mem::take(&mut (*_a0).values); + (unsafe { + let _arg0: *mut Inner = &mut (*_a0).inner; + Inner::move_assign(&mut self.inner, _arg0) + }); + return &mut (*(self as *mut Outer)); + } +} +pub unsafe fn make_0() -> Outer { + return Outer { + values: Vec::from([1, 2, 3]), + inner: Inner { + values: Vec::from([4, 5, 6]), + }, + }; +} +pub unsafe fn two_1(a: *const Vec, b: *const Vec) -> i32 { + return (((&(*a))[(0_usize)]) + ((&(*b))[(2_usize)])); +} +pub fn main() { + unsafe { + __cpp2rust_init_globals(); + std::process::exit(main_0() as i32); + } +} +unsafe fn main_0() -> i32 { + (unsafe { + libc::printf( + c"%d\n".as_ptr() as *const libc::c_char, + (unsafe { + let _a: *const Vec = &(unsafe { make_0() }).values; + let _b: *const Vec = &(unsafe { make_0() }).inner.values; + two_1(_a, _b) + }), + ) + }); + return 0; +} +pub unsafe fn __cpp2rust_init_globals() {} diff --git a/tests/unit/temporary_field_ctor_arg.cpp b/tests/unit/temporary_field_ctor_arg.cpp new file mode 100644 index 0000000000..2aae845bd5 --- /dev/null +++ b/tests/unit/temporary_field_ctor_arg.cpp @@ -0,0 +1,26 @@ +// panic: refcount +// nondet-result: unsafe + +// Valid C++: the temporary lives until H's constructor returns. Both +// translations convert the argument in a block of its own, and that drops the +// temporary. + +#include +#include + +struct Outer { + std::vector values; +}; + +static Outer make() { return {{1, 2, 3, 4}}; } + +struct H { + int last; + H(const std::vector &values) : last(values[3]) {} +}; + +int main() { + H h(make().values); + printf("%d\n", h.last); + return 0; +} diff --git a/tests/unit/temporary_field_two_args.cpp b/tests/unit/temporary_field_two_args.cpp new file mode 100644 index 0000000000..0f0f81dbeb --- /dev/null +++ b/tests/unit/temporary_field_two_args.cpp @@ -0,0 +1,28 @@ +// panic: refcount + +// Valid C++: both temporaries live until two() returns. The refcount +// translation binds each argument to a variable before the call, and that +// drops its temporary. + +#include +#include + +struct Inner { + std::vector values; +}; + +struct Outer { + std::vector values; + Inner inner; +}; + +static Outer make() { return {{1, 2, 3}, {{4, 5, 6}}}; } + +static int two(const std::vector &a, const std::vector &b) { + return a[0] + b[2]; +} + +int main() { + printf("%d\n", two(make().values, make().inner.values)); + return 0; +}