Skip to content

Commit 7ceffde

Browse files
committed
Auto merge of #8289 - jubnzv:unspecified-layout-union, r=camsteffen
Add `default_union_representation` lint Closes #8235 changelog: Added a new lint [`default_union_representation`]
2 parents 8d5d9e0 + b7000b2 commit 7ceffde

7 files changed

+236
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2930,6 +2930,7 @@ Released 2018-09-13
29302930
[`declare_interior_mutable_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const
29312931
[`default_numeric_fallback`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_numeric_fallback
29322932
[`default_trait_access`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_trait_access
2933+
[`default_union_representation`]: https://rust-lang.github.io/rust-clippy/master/index.html#default_union_representation
29332934
[`deprecated_cfg_attr`]: https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_cfg_attr
29342935
[`deprecated_semver`]: https://rust-lang.github.io/rust-clippy/master/index.html#deprecated_semver
29352936
[`deref_addrof`]: https://rust-lang.github.io/rust-clippy/master/index.html#deref_addrof
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
use clippy_utils::diagnostics::span_lint_and_help;
2+
use rustc_hir::{self as hir, HirId, Item, ItemKind};
3+
use rustc_lint::{LateContext, LateLintPass};
4+
use rustc_middle::ty::layout::LayoutOf;
5+
use rustc_session::{declare_lint_pass, declare_tool_lint};
6+
use rustc_span::sym;
7+
use rustc_typeck::hir_ty_to_ty;
8+
9+
declare_clippy_lint! {
10+
/// ### What it does
11+
/// Displays a warning when a union is declared with the default representation (without a `#[repr(C)]` attribute).
12+
///
13+
/// ### Why is this bad?
14+
/// Unions in Rust have unspecified layout by default, despite many people thinking that they
15+
/// lay out each field at the start of the union (like C does). That is, there are no guarantees
16+
/// about the offset of the fields for unions with multiple non-ZST fields without an explicitly
17+
/// specified layout. These cases may lead to undefined behavior in unsafe blocks.
18+
///
19+
/// ### Example
20+
/// ```rust
21+
/// union Foo {
22+
/// a: i32,
23+
/// b: u32,
24+
/// }
25+
///
26+
/// fn main() {
27+
/// let _x: u32 = unsafe {
28+
/// Foo { a: 0_i32 }.b // Undefined behaviour: `b` is allowed to be padding
29+
/// };
30+
/// }
31+
/// ```
32+
/// Use instead:
33+
/// ```rust
34+
/// #[repr(C)]
35+
/// union Foo {
36+
/// a: i32,
37+
/// b: u32,
38+
/// }
39+
///
40+
/// fn main() {
41+
/// let _x: u32 = unsafe {
42+
/// Foo { a: 0_i32 }.b // Now defined behaviour, this is just an i32 -> u32 transmute
43+
/// };
44+
/// }
45+
/// ```
46+
#[clippy::version = "1.60.0"]
47+
pub DEFAULT_UNION_REPRESENTATION,
48+
restriction,
49+
"unions without a `#[repr(C)]` attribute"
50+
}
51+
declare_lint_pass!(DefaultUnionRepresentation => [DEFAULT_UNION_REPRESENTATION]);
52+
53+
impl<'tcx> LateLintPass<'tcx> for DefaultUnionRepresentation {
54+
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
55+
if is_union_with_two_non_zst_fields(cx, item) && !has_c_repr_attr(cx, item.hir_id()) {
56+
span_lint_and_help(
57+
cx,
58+
DEFAULT_UNION_REPRESENTATION,
59+
item.span,
60+
"this union has the default representation",
61+
None,
62+
&format!(
63+
"consider annotating `{}` with `#[repr(C)]` to explicitly specify memory layout",
64+
cx.tcx.def_path_str(item.def_id.to_def_id())
65+
),
66+
);
67+
}
68+
}
69+
}
70+
71+
/// Returns true if the given item is a union with at least two non-ZST fields.
72+
fn is_union_with_two_non_zst_fields(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
73+
if let ItemKind::Union(data, _) = &item.kind {
74+
data.fields().iter().filter(|f| !is_zst(cx, f.ty)).count() >= 2
75+
} else {
76+
false
77+
}
78+
}
79+
80+
fn is_zst(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>) -> bool {
81+
if hir_ty.span.from_expansion() {
82+
return false;
83+
}
84+
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
85+
if let Ok(layout) = cx.layout_of(ty) {
86+
layout.is_zst()
87+
} else {
88+
false
89+
}
90+
}
91+
92+
fn has_c_repr_attr(cx: &LateContext<'_>, hir_id: HirId) -> bool {
93+
cx.tcx.hir().attrs(hir_id).iter().any(|attr| {
94+
if attr.has_name(sym::repr) {
95+
if let Some(items) = attr.meta_item_list() {
96+
for item in items {
97+
if item.is_word() && matches!(item.name_or_empty(), sym::C) {
98+
return true;
99+
}
100+
}
101+
}
102+
}
103+
false
104+
})
105+
}

clippy_lints/src/lib.register_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ store.register_lints(&[
9292
default::DEFAULT_TRAIT_ACCESS,
9393
default::FIELD_REASSIGN_WITH_DEFAULT,
9494
default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK,
95+
default_union_representation::DEFAULT_UNION_REPRESENTATION,
9596
dereference::EXPLICIT_DEREF_METHODS,
9697
dereference::NEEDLESS_BORROW,
9798
dereference::REF_BINDING_TO_REFERENCE,

clippy_lints/src/lib.register_restriction.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ store.register_group(true, "clippy::restriction", Some("clippy_restriction"), ve
1212
LintId::of(create_dir::CREATE_DIR),
1313
LintId::of(dbg_macro::DBG_MACRO),
1414
LintId::of(default_numeric_fallback::DEFAULT_NUMERIC_FALLBACK),
15+
LintId::of(default_union_representation::DEFAULT_UNION_REPRESENTATION),
1516
LintId::of(disallowed_script_idents::DISALLOWED_SCRIPT_IDENTS),
1617
LintId::of(else_if_without_else::ELSE_IF_WITHOUT_ELSE),
1718
LintId::of(exhaustive_items::EXHAUSTIVE_ENUMS),

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ mod create_dir;
189189
mod dbg_macro;
190190
mod default;
191191
mod default_numeric_fallback;
192+
mod default_union_representation;
192193
mod dereference;
193194
mod derivable_impls;
194195
mod derive;
@@ -859,6 +860,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
859860
store.register_early_pass(|| Box::new(single_char_lifetime_names::SingleCharLifetimeNames));
860861
store.register_late_pass(move || Box::new(borrow_as_ptr::BorrowAsPtr::new(msrv)));
861862
store.register_late_pass(move || Box::new(manual_bits::ManualBits::new(msrv)));
863+
store.register_late_pass(|| Box::new(default_union_representation::DefaultUnionRepresentation));
862864
// add lints here, do not remove this comment, it's used in `new_lint`
863865
}
864866

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#![feature(transparent_unions)]
2+
#![warn(clippy::default_union_representation)]
3+
4+
union NoAttribute {
5+
a: i32,
6+
b: u32,
7+
}
8+
9+
#[repr(C)]
10+
union ReprC {
11+
a: i32,
12+
b: u32,
13+
}
14+
15+
#[repr(packed)]
16+
union ReprPacked {
17+
a: i32,
18+
b: u32,
19+
}
20+
21+
#[repr(C, packed)]
22+
union ReprCPacked {
23+
a: i32,
24+
b: u32,
25+
}
26+
27+
#[repr(C, align(32))]
28+
union ReprCAlign {
29+
a: i32,
30+
b: u32,
31+
}
32+
33+
#[repr(align(32))]
34+
union ReprAlign {
35+
a: i32,
36+
b: u32,
37+
}
38+
39+
union SingleZST {
40+
f0: (),
41+
}
42+
union ZSTsAndField1 {
43+
f0: u32,
44+
f1: (),
45+
f2: (),
46+
f3: (),
47+
}
48+
union ZSTsAndField2 {
49+
f0: (),
50+
f1: (),
51+
f2: u32,
52+
f3: (),
53+
}
54+
union ZSTAndTwoFields {
55+
f0: u32,
56+
f1: u64,
57+
f2: (),
58+
}
59+
60+
#[repr(C)]
61+
union CZSTAndTwoFields {
62+
f0: u32,
63+
f1: u64,
64+
f2: (),
65+
}
66+
67+
#[repr(transparent)]
68+
union ReprTransparent {
69+
a: i32,
70+
}
71+
72+
#[repr(transparent)]
73+
union ReprTransparentZST {
74+
a: i32,
75+
b: (),
76+
}
77+
78+
fn main() {}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
error: this union has the default representation
2+
--> $DIR/default_union_representation.rs:4:1
3+
|
4+
LL | / union NoAttribute {
5+
LL | | a: i32,
6+
LL | | b: u32,
7+
LL | | }
8+
| |_^
9+
|
10+
= note: `-D clippy::default-union-representation` implied by `-D warnings`
11+
= help: consider annotating `NoAttribute` with `#[repr(C)]` to explicitly specify memory layout
12+
13+
error: this union has the default representation
14+
--> $DIR/default_union_representation.rs:16:1
15+
|
16+
LL | / union ReprPacked {
17+
LL | | a: i32,
18+
LL | | b: u32,
19+
LL | | }
20+
| |_^
21+
|
22+
= help: consider annotating `ReprPacked` with `#[repr(C)]` to explicitly specify memory layout
23+
24+
error: this union has the default representation
25+
--> $DIR/default_union_representation.rs:34:1
26+
|
27+
LL | / union ReprAlign {
28+
LL | | a: i32,
29+
LL | | b: u32,
30+
LL | | }
31+
| |_^
32+
|
33+
= help: consider annotating `ReprAlign` with `#[repr(C)]` to explicitly specify memory layout
34+
35+
error: this union has the default representation
36+
--> $DIR/default_union_representation.rs:54:1
37+
|
38+
LL | / union ZSTAndTwoFields {
39+
LL | | f0: u32,
40+
LL | | f1: u64,
41+
LL | | f2: (),
42+
LL | | }
43+
| |_^
44+
|
45+
= help: consider annotating `ZSTAndTwoFields` with `#[repr(C)]` to explicitly specify memory layout
46+
47+
error: aborting due to 4 previous errors
48+

0 commit comments

Comments
 (0)