Skip to content

Commit

Permalink
Merge #1416
Browse files Browse the repository at this point in the history
1416: unsafe: Add checks for union field accesses r=CohenArthur a=CohenArthur

Addresses #1411 

Co-authored-by: Arthur Cohen <arthur.cohen@embecosm.com>
  • Loading branch information
bors[bot] and CohenArthur committed Jul 28, 2022
2 parents add0846 + f532ae5 commit 6d5eb73
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
20 changes: 17 additions & 3 deletions gcc/rust/checks/errors/rust-unsafe-checker.cc
Original file line number Diff line number Diff line change
Expand Up @@ -332,10 +332,24 @@ UnsafeChecker::visit (MethodCallExpr &expr)
void
UnsafeChecker::visit (FieldAccessExpr &expr)
{
// FIXME: If the receiver is an union, we need to be in an unsafe context to
// access it. Make sure to check.

expr.get_receiver_expr ()->accept_vis (*this);

if (is_unsafe_context ())
return;

TyTy::BaseType *receiver_ty;
auto ok = context.lookup_type (
expr.get_receiver_expr ()->get_mappings ().get_hirid (), &receiver_ty);
rust_assert (ok);

if (receiver_ty->get_kind () == TyTy::TypeKind::ADT)
{
auto maybe_union = static_cast<TyTy::ADTType *> (receiver_ty);
if (maybe_union->is_union ())
rust_error_at (
expr.get_locus (),
"access to union field requires unsafe function or block");
}
}

void
Expand Down
10 changes: 10 additions & 0 deletions gcc/testsuite/rust/compile/unsafe9.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
union U {
a: i32,
b: f32,
c: u8,
}

fn main() {
let u = U { a: 14 };
let _ = u.a; // { dg-error "access to union" }
}

0 comments on commit 6d5eb73

Please sign in to comment.