Skip to content

Commit 242534e

Browse files
Keep temporaries alive for pointers to their fields in refcount (#614)
#577 made the refcount `substr` rule take its receiver by pointer, so `make().s.substr(7, 6)` now takes a pointer to a field of a temporary; it worked before #577. The converter emitted that pointer inside the block of `field_ref!` (likewise `field_ptr!` and `array_field_ptr!`), and Rust 2024 drops the temporaries of a block's tail expression at the end of the block. The temporary was dropped before `substr` read it, and the program panicked with `ub: dangling pointer`. Other pointers to a field of a temporary, such as one passed to a `const std::vector<int> &` parameter, failed the same way. The converter now binds a pointer to the temporary in a `match` around the outermost field macro, so the temporary lives until the end of the enclosing Rust statement or block. That covers uses within the same expression, such as `substr`: ```rust (match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() { __tmp_1 => field_ref!(__tmp_1, values).as_pointer(), }) ``` This also makes pointers to fields of aggregate temporaries, such as `Outer{...}.inner.values`, compile. Pointers to fields of lvalues and the unsafe model are unchanged. Still dangling in refcount, as before: - a `const` reference or range-for bound to a field of a temporary; - a field reached through an array element of a temporary, such as `make().items[1].values`, or through a reference that a call returns, such as `identity(make().s).substr(7, 6)`; - two such arguments of one call, such as `two(make().values, make().inner.values)`, which are bound to variables before the call; - constructor arguments, such as `H h(make().values);`, which are converted in a block of their own (the unsafe translation prints a wrong value there too). [Case and evidence](<https://app.perfloop.ai/t/oss/case_9f1n2zm9dz>) --- Made by [Perfloop](https://app.perfloop.ai). Human sponsor: [Tomás Senart](https://github.com/tsenart). To ask for a change, comment or review in plain words. [How Perfloop handles pull requests](https://perfloop.ai/docs/work/pull-requests). --------- Signed-off-by: Perfloop Agent <agent@perfloop.ai> Signed-off-by: Tomás Senart <ts@perfloop.ai>
1 parent 92318f5 commit 242534e

11 files changed

Lines changed: 752 additions & 9 deletions

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1821,21 +1821,55 @@ bool ConverterRefCount::VisitMemberExpr(clang::MemberExpr *expr) {
18211821
return false;
18221822
}
18231823

1824+
// The temporary that `expr` is a field of, or a field of a field of, e.g.,
1825+
// the result of f() in f().a.b.
1826+
static clang::Expr *GetFieldTemporary(clang::ASTContext &ctx,
1827+
clang::MemberExpr *expr) {
1828+
clang::Expr *base = expr;
1829+
while (auto *member = clang::dyn_cast<clang::MemberExpr>(base)) {
1830+
if (member->isArrow()) {
1831+
return nullptr;
1832+
}
1833+
base = member->getBase()->IgnoreParenNoopCasts(ctx);
1834+
}
1835+
return clang::isa<clang::MaterializeTemporaryExpr>(base) ? base : nullptr;
1836+
}
1837+
18241838
void ConverterRefCount::ConvertInlineField(clang::MemberExpr *expr) {
18251839
auto name = GetNamedDeclAsString(expr->getMemberDecl());
18261840
auto type = expr->getType();
18271841
auto *base = expr->getBase();
18281842
if (isAddrOf()) {
1829-
// A pointer to the struct, offset to the field. An array decays to a
1830-
// pointer to its first element, and a vector can be used as one.
1831-
if (type->isArrayType()) {
1832-
StrCat(std::format("array_field_ptr!({}, {})", ConvertRecordPtr(expr),
1833-
name));
1834-
} else if (IsBoxedType(type)) {
1835-
StrCat(std::format("field_ref!({}, {}){}", ConvertRecordPtr(expr), name,
1836-
AsPointerMethod(type)));
1843+
// The outermost field of a temporary binds a pointer to the temporary.
1844+
FieldTemporary temporary{GetFieldTemporary(ctx_, expr), ""};
1845+
bool outermost = temporary.temporary &&
1846+
(!field_temporary_ ||
1847+
field_temporary_->temporary != temporary.temporary);
1848+
std::string str;
1849+
{
1850+
Buffer buf(*this);
1851+
ScopedValue push(field_temporary_,
1852+
outermost ? &temporary : field_temporary_);
1853+
// A pointer to the struct, offset to the field. An array decays to a
1854+
// pointer to its first element, and a vector can be used as one.
1855+
if (type->isArrayType()) {
1856+
StrCat(std::format("array_field_ptr!({}, {})", ConvertRecordPtr(expr),
1857+
name));
1858+
} else if (IsBoxedType(type)) {
1859+
StrCat(std::format("field_ref!({}, {}){}", ConvertRecordPtr(expr), name,
1860+
AsPointerMethod(type)));
1861+
} else {
1862+
StrCat(std::format("field_ptr!({}, {})", ConvertRecordPtr(expr), name));
1863+
}
1864+
str = std::move(buf).str();
1865+
}
1866+
if (temporary.var.empty()) {
1867+
StrCat(str);
18371868
} else {
1838-
StrCat(std::format("field_ptr!({}, {})", ConvertRecordPtr(expr), name));
1869+
PushParen paren(*this);
1870+
StrCat("match", ConvertTemporaryPointer(temporary.temporary, {}));
1871+
PushBrace brace(*this);
1872+
StrCat(temporary.var, "=>", str);
18391873
}
18401874
MarkFresh();
18411875
return;
@@ -1878,6 +1912,14 @@ void ConverterRefCount::ConvertInlineField(clang::MemberExpr *expr) {
18781912
}
18791913

18801914
std::string ConverterRefCount::ConvertRecordPtr(clang::MemberExpr *expr) {
1915+
auto *base = expr->getBase()->IgnoreParenNoopCasts(ctx_);
1916+
if (field_temporary_ && !expr->isArrow() &&
1917+
base == field_temporary_->temporary) {
1918+
if (field_temporary_->var.empty()) {
1919+
field_temporary_->var = NewTempName();
1920+
}
1921+
return field_temporary_->var;
1922+
}
18811923
Buffer buf(*this);
18821924
PushExprKind push(*this, ExprKind::AddrOf);
18831925
if (expr->isArrow()) {

‎cpp2rust/converter/models/converter_refcount.h‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,19 @@ class ConverterRefCount final : public Converter {
202202
std::string *record_ptr_ = nullptr;
203203
const clang::Expr *record_base_ = nullptr;
204204

205+
// The temporary whose field, or field of a field, a pointer is being made
206+
// to, e.g., the result of f() in &f().a.b, and the variable that a match
207+
// binds a pointer to the temporary to. The temporaries in the block of a
208+
// field macro end with the block, while those of the matched value live
209+
// until the end of the enclosing statement or block. That can be before
210+
// the end of the C++ full-expression, e.g., for a call argument that is
211+
// bound to a variable or converted in a block of its own.
212+
struct FieldTemporary {
213+
clang::Expr *temporary;
214+
std::string var;
215+
};
216+
FieldTemporary *field_temporary_ = nullptr;
217+
205218
// The expression that ConvertFreshRValue copies.
206219
const clang::Expr *copied_expr_ = nullptr;
207220

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
extern crate libcc2rs;
2+
use libcc2rs::*;
3+
use std::cell::RefCell;
4+
use std::collections::BTreeMap;
5+
use std::io::prelude::*;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::AsFd;
8+
use std::rc::{Rc, Weak};
9+
#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign, Default)]
10+
#[byte_size(24)]
11+
pub struct Inner {
12+
#[offset(0)]
13+
#[byte_size(24)]
14+
pub values: Vec<i32>,
15+
}
16+
impl Inner {
17+
pub fn move_from(_a0: Ptr<Inner>) -> Self {
18+
Self {
19+
values: field!(_a0, values).with_mut(std::mem::take),
20+
}
21+
}
22+
}
23+
#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign)]
24+
#[byte_size(56)]
25+
pub struct Outer {
26+
#[offset(0)]
27+
#[byte_size(24)]
28+
pub values: Vec<i32>,
29+
#[offset(24)]
30+
#[byte_size(24)]
31+
pub inner: Inner,
32+
#[offset(48)]
33+
#[byte_size(8)]
34+
pub name: Box<[i8]>,
35+
}
36+
impl Outer {
37+
pub fn move_from(_a0: Ptr<Outer>) -> Self {
38+
Self {
39+
values: field!(_a0, values).with_mut(std::mem::take),
40+
inner: Inner::move_from({ field_ptr!(_a0, inner) }),
41+
name: Box::new(std::array::from_fn::<_, 8, _>(|__i: usize| {
42+
(*_a0.upgrade().deref()).name[(__i) as usize]
43+
})),
44+
}
45+
}
46+
}
47+
impl Default for Outer {
48+
fn default() -> Self {
49+
{
50+
Outer {
51+
values: Default::default(),
52+
inner: <Inner>::default(),
53+
name: (0..8).map(|_| 0_i8).collect::<Box<[i8]>>(),
54+
}
55+
}
56+
}
57+
}
58+
pub fn make_0(calls: Ptr<i32>) -> Outer {
59+
calls.with_mut(|__v| __v.prefix_inc());
60+
return Outer {
61+
values: Vec::from([1, 2, 3]),
62+
inner: Inner {
63+
values: Vec::from([4, 5, 6]),
64+
},
65+
name: i8::array_from_literal(b"abc\0\0\0\0\0"),
66+
};
67+
}
68+
pub fn sum_1(values: Ptr<Vec<i32>>) -> i32 {
69+
let mut total: i32 = 0;
70+
'loop_: for value in IterRange::new(values.decay().begin(), values.decay().end()) {
71+
let mut value: i32 = (value.iter_deref().read());
72+
total += value;
73+
}
74+
return total;
75+
}
76+
pub fn main() {
77+
__cpp2rust_init_globals();
78+
std::process::exit(main_0());
79+
}
80+
fn main_0() -> i32 {
81+
let calls: Value<i32> = Rc::new(RefCell::new(0));
82+
let mut member: i32 = ({
83+
sum_1(
84+
(match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() {
85+
__tmp_1 => field_ref!(__tmp_1, values).as_pointer(),
86+
}),
87+
)
88+
});
89+
let mut nested: i32 = ({
90+
sum_1(
91+
(match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() {
92+
__tmp_2 => field_ref!(field_ptr!(__tmp_2, inner), values).as_pointer(),
93+
}),
94+
)
95+
});
96+
let mut element: i32 = (match (
97+
(match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() {
98+
__tmp_4 => field_ref!(__tmp_4, values).as_pointer(),
99+
}),
100+
{ (((*calls.borrow()) - 2) as usize) },
101+
) {
102+
(__tmp_3, mut __tmp_5) => {
103+
if __tmp_5 as usize >= __tmp_3.decay().len() {
104+
panic!("out of bounds access")
105+
} else {
106+
__tmp_3.decay().offset(__tmp_5 as isize)
107+
}
108+
}
109+
}
110+
.read());
111+
let mut length: usize =
112+
((match Rc::new(RefCell::new(({ make_0(calls.as_pointer()) }))).as_pointer() {
113+
__tmp_6 => array_field_ptr!(__tmp_6, name),
114+
}) as Ptr<i8>)
115+
.to_c_string_iterator()
116+
.count();
117+
let mut aggregate: i32 = ({
118+
sum_1(
119+
(match Rc::new(RefCell::new(Outer {
120+
values: Vec::from([7]),
121+
inner: Inner {
122+
values: Vec::from([8, 9]),
123+
},
124+
name: i8::array_from_literal(b"x\0\0\0\0\0\0\0"),
125+
}))
126+
.as_pointer()
127+
{
128+
__tmp_7 => field_ref!(field_ptr!(__tmp_7, inner), values).as_pointer(),
129+
}),
130+
)
131+
});
132+
println!(
133+
"{} {} {} {} {} {}",
134+
member,
135+
nested,
136+
element,
137+
length,
138+
aggregate,
139+
(*calls.borrow())
140+
);
141+
return 0;
142+
}
143+
pub trait InnerImpl {
144+
fn move_assign(&self, _a0: Ptr<Inner>) -> Ptr<Inner>;
145+
}
146+
impl InnerImpl for Ptr<Inner> {
147+
fn move_assign(&self, _a0: Ptr<Inner>) -> Ptr<Inner> {
148+
field_ref!((*self), values)
149+
.as_pointer()
150+
.write(field!(_a0, values).with_mut(std::mem::take));
151+
return (*self).clone();
152+
}
153+
}
154+
pub trait OuterImpl {
155+
fn move_assign(&self, _a0: Ptr<Outer>) -> Ptr<Outer>;
156+
}
157+
impl OuterImpl for Ptr<Outer> {
158+
fn move_assign(&self, _a0: Ptr<Outer>) -> Ptr<Outer> {
159+
field_ref!((*self), values)
160+
.as_pointer()
161+
.write(field!(_a0, values).with_mut(std::mem::take));
162+
({
163+
let _arg0: Ptr<Inner> = field_ptr!(_a0, inner);
164+
InnerImpl::move_assign(&field_ptr!((*self), inner), _arg0)
165+
});
166+
match ({ ((array_field_ptr!((*self), name)) as Ptr<i8>).to_any() },) {
167+
(mut __tmp_0,) => {
168+
__tmp_0.memcpy(
169+
&((array_field_ptr!(_a0, name)) as Ptr<i8>).to_any(),
170+
8_usize as usize,
171+
);
172+
(__tmp_0).clone()
173+
}
174+
};
175+
return (*self).clone();
176+
}
177+
}
178+
pub fn __cpp2rust_init_globals() {}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
extern crate libcc2rs;
2+
use libcc2rs::*;
3+
use std::cell::RefCell;
4+
use std::collections::BTreeMap;
5+
use std::io::prelude::*;
6+
use std::io::{Read, Seek, Write};
7+
use std::os::fd::AsFd;
8+
use std::rc::{Rc, Weak};
9+
#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, MoveCtor, MoveAssign, Default)]
10+
#[byte_size(24)]
11+
pub struct Outer {
12+
#[offset(0)]
13+
#[byte_size(24)]
14+
pub values: Vec<i32>,
15+
}
16+
impl Outer {
17+
pub fn move_from(_a0: Ptr<Outer>) -> Self {
18+
Self {
19+
values: field!(_a0, values).with_mut(std::mem::take),
20+
}
21+
}
22+
}
23+
pub fn make_0() -> Outer {
24+
return Outer {
25+
values: Vec::from([1, 2, 3, 4]),
26+
};
27+
}
28+
#[derive(Clone, Record, ByteRepr, VaArg, FnPtrArg, CppFrom, Default)]
29+
#[cpp_from(Vec<i32 > , new, ptr)]
30+
#[byte_size(4)]
31+
pub struct H {
32+
#[offset(0)]
33+
pub last: i32,
34+
}
35+
impl H {
36+
pub fn new(values: Ptr<Vec<i32>>) -> Self {
37+
Self {
38+
last: (index!(values, 3_usize).read()),
39+
}
40+
}
41+
}
42+
pub fn main() {
43+
__cpp2rust_init_globals();
44+
std::process::exit(main_0());
45+
}
46+
fn main_0() -> i32 {
47+
let mut h: H = H::new({
48+
(match Rc::new(RefCell::new(({ make_0() }))).as_pointer() {
49+
__tmp_0 => field_ref!(__tmp_0, values).as_pointer(),
50+
})
51+
});
52+
println!("{}", h.last);
53+
return 0;
54+
}
55+
pub trait OuterImpl {
56+
fn move_assign(&self, _a0: Ptr<Outer>) -> Ptr<Outer>;
57+
}
58+
impl OuterImpl for Ptr<Outer> {
59+
fn move_assign(&self, _a0: Ptr<Outer>) -> Ptr<Outer> {
60+
field_ref!((*self), values)
61+
.as_pointer()
62+
.write(field!(_a0, values).with_mut(std::mem::take));
63+
return (*self).clone();
64+
}
65+
}
66+
pub fn __cpp2rust_init_globals() {}

0 commit comments

Comments
 (0)