Skip to content

Commit 7c51e4e

Browse files
committed
Auto merge of #5294 - tmiasko:trait-ptr-cmp, r=Manishearth
Lint unnamed address comparisons Functions and vtables have an insignificant address. Attempts to compare such addresses will lead to very surprising behaviour. For example: addresses of different functions could compare equal; two trait object pointers representing the same object and the same type could be unequal. Lint against unnamed address comparisons to avoid issues like those in rust-lang/rust#69757 and rust-lang/rust#54685. Changelog: New lints: [`fn_address_comparisons`] [#5294](#5294), [`vtable_address_comparisons`] [#5294](#5294)
2 parents 42c36dc + b77b219 commit 7c51e4e

10 files changed

+323
-2
lines changed

Diff for: CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -1271,6 +1271,7 @@ Released 2018-09-13
12711271
[`float_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#float_arithmetic
12721272
[`float_cmp`]: https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp
12731273
[`float_cmp_const`]: https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp_const
1274+
[`fn_address_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_address_comparisons
12741275
[`fn_params_excessive_bools`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools
12751276
[`fn_to_numeric_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_to_numeric_cast
12761277
[`fn_to_numeric_cast_with_truncation`]: https://rust-lang.github.io/rust-clippy/master/index.html#fn_to_numeric_cast_with_truncation
@@ -1540,6 +1541,7 @@ Released 2018-09-13
15401541
[`vec_box`]: https://rust-lang.github.io/rust-clippy/master/index.html#vec_box
15411542
[`verbose_bit_mask`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_bit_mask
15421543
[`verbose_file_reads`]: https://rust-lang.github.io/rust-clippy/master/index.html#verbose_file_reads
1544+
[`vtable_address_comparisons`]: https://rust-lang.github.io/rust-clippy/master/index.html#vtable_address_comparisons
15431545
[`while_immutable_condition`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_immutable_condition
15441546
[`while_let_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_let_loop
15451547
[`while_let_on_iterator`]: https://rust-lang.github.io/rust-clippy/master/index.html#while_let_on_iterator

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
77

8-
[There are 361 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
8+
[There are 363 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
99

1010
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1111

Diff for: clippy_lints/src/lib.rs

+8
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ pub mod trivially_copy_pass_by_ref;
309309
pub mod try_err;
310310
pub mod types;
311311
pub mod unicode;
312+
pub mod unnamed_address;
312313
pub mod unsafe_removed_from_name;
313314
pub mod unused_io_amount;
314315
pub mod unused_self;
@@ -818,6 +819,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
818819
&unicode::NON_ASCII_LITERAL,
819820
&unicode::UNICODE_NOT_NFC,
820821
&unicode::ZERO_WIDTH_SPACE,
822+
&unnamed_address::FN_ADDRESS_COMPARISONS,
823+
&unnamed_address::VTABLE_ADDRESS_COMPARISONS,
821824
&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
822825
&unused_io_amount::UNUSED_IO_AMOUNT,
823826
&unused_self::UNUSED_SELF,
@@ -1027,6 +1030,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10271030
store.register_early_pass(|| box macro_use::MacroUseImports);
10281031
store.register_late_pass(|| box verbose_file_reads::VerboseFileReads);
10291032
store.register_late_pass(|| box redundant_pub_crate::RedundantPubCrate::default());
1033+
store.register_late_pass(|| box unnamed_address::UnnamedAddress);
10301034

10311035
store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![
10321036
LintId::of(&arithmetic::FLOAT_ARITHMETIC),
@@ -1378,6 +1382,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13781382
LintId::of(&types::UNNECESSARY_CAST),
13791383
LintId::of(&types::VEC_BOX),
13801384
LintId::of(&unicode::ZERO_WIDTH_SPACE),
1385+
LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS),
1386+
LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
13811387
LintId::of(&unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME),
13821388
LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
13831389
LintId::of(&unwrap::PANICKING_UNWRAP),
@@ -1631,6 +1637,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
16311637
LintId::of(&types::CAST_REF_TO_MUT),
16321638
LintId::of(&types::UNIT_CMP),
16331639
LintId::of(&unicode::ZERO_WIDTH_SPACE),
1640+
LintId::of(&unnamed_address::FN_ADDRESS_COMPARISONS),
1641+
LintId::of(&unnamed_address::VTABLE_ADDRESS_COMPARISONS),
16341642
LintId::of(&unused_io_amount::UNUSED_IO_AMOUNT),
16351643
LintId::of(&unwrap::PANICKING_UNWRAP),
16361644
]);

Diff for: clippy_lints/src/unnamed_address.rs

+133
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
use crate::utils::{match_def_path, paths, span_lint, span_lint_and_help};
2+
use if_chain::if_chain;
3+
use rustc_hir::{BinOpKind, Expr, ExprKind};
4+
use rustc_lint::{LateContext, LateLintPass};
5+
use rustc_middle::ty;
6+
use rustc_session::{declare_lint_pass, declare_tool_lint};
7+
8+
declare_clippy_lint! {
9+
/// **What it does:** Checks for comparisons with an address of a function item.
10+
///
11+
/// **Why is this bad?** Function item address is not guaranteed to be unique and could vary
12+
/// between different code generation units. Furthermore different function items could have
13+
/// the same address after being merged together.
14+
///
15+
/// **Known problems:** None.
16+
///
17+
/// **Example:**
18+
///
19+
/// ```rust
20+
/// type F = fn();
21+
/// fn a() {}
22+
/// let f: F = a;
23+
/// if f == a {
24+
/// // ...
25+
/// }
26+
/// ```
27+
pub FN_ADDRESS_COMPARISONS,
28+
correctness,
29+
"comparison with an address of a function item"
30+
}
31+
32+
declare_clippy_lint! {
33+
/// **What it does:** Checks for comparisons with an address of a trait vtable.
34+
///
35+
/// **Why is this bad?** Comparing trait objects pointers compares an vtable addresses which
36+
/// are not guaranteed to be unique and could vary between different code generation units.
37+
/// Furthermore vtables for different types could have the same address after being merged
38+
/// together.
39+
///
40+
/// **Known problems:** None.
41+
///
42+
/// **Example:**
43+
///
44+
/// ```rust,ignore
45+
/// let a: Rc<dyn Trait> = ...
46+
/// let b: Rc<dyn Trait> = ...
47+
/// if Rc::ptr_eq(&a, &b) {
48+
/// ...
49+
/// }
50+
/// ```
51+
pub VTABLE_ADDRESS_COMPARISONS,
52+
correctness,
53+
"comparison with an address of a trait vtable"
54+
}
55+
56+
declare_lint_pass!(UnnamedAddress => [FN_ADDRESS_COMPARISONS, VTABLE_ADDRESS_COMPARISONS]);
57+
58+
impl LateLintPass<'_, '_> for UnnamedAddress {
59+
fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
60+
fn is_comparison(binop: BinOpKind) -> bool {
61+
match binop {
62+
BinOpKind::Eq | BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ne | BinOpKind::Ge | BinOpKind::Gt => true,
63+
_ => false,
64+
}
65+
}
66+
67+
fn is_trait_ptr(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
68+
match cx.tables.expr_ty_adjusted(expr).kind {
69+
ty::RawPtr(ty::TypeAndMut { ty, .. }) => ty.is_trait(),
70+
_ => false,
71+
}
72+
}
73+
74+
fn is_fn_def(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
75+
if let ty::FnDef(..) = cx.tables.expr_ty(expr).kind {
76+
true
77+
} else {
78+
false
79+
}
80+
}
81+
82+
if_chain! {
83+
if let ExprKind::Binary(binop, ref left, ref right) = expr.kind;
84+
if is_comparison(binop.node);
85+
if is_trait_ptr(cx, left) && is_trait_ptr(cx, right);
86+
then {
87+
span_lint_and_help(
88+
cx,
89+
VTABLE_ADDRESS_COMPARISONS,
90+
expr.span,
91+
"comparing trait object pointers compares a non-unique vtable address",
92+
"consider extracting and comparing data pointers only",
93+
);
94+
}
95+
}
96+
97+
if_chain! {
98+
if let ExprKind::Call(ref func, [ref _left, ref _right]) = expr.kind;
99+
if let ExprKind::Path(ref func_qpath) = func.kind;
100+
if let Some(def_id) = cx.tables.qpath_res(func_qpath, func.hir_id).opt_def_id();
101+
if match_def_path(cx, def_id, &paths::PTR_EQ) ||
102+
match_def_path(cx, def_id, &paths::RC_PTR_EQ) ||
103+
match_def_path(cx, def_id, &paths::ARC_PTR_EQ);
104+
let ty_param = cx.tables.node_substs(func.hir_id).type_at(0);
105+
if ty_param.is_trait();
106+
then {
107+
span_lint_and_help(
108+
cx,
109+
VTABLE_ADDRESS_COMPARISONS,
110+
expr.span,
111+
"comparing trait object pointers compares a non-unique vtable address",
112+
"consider extracting and comparing data pointers only",
113+
);
114+
}
115+
}
116+
117+
if_chain! {
118+
if let ExprKind::Binary(binop, ref left, ref right) = expr.kind;
119+
if is_comparison(binop.node);
120+
if cx.tables.expr_ty_adjusted(left).is_fn_ptr() &&
121+
cx.tables.expr_ty_adjusted(right).is_fn_ptr();
122+
if is_fn_def(cx, left) || is_fn_def(cx, right);
123+
then {
124+
span_lint(
125+
cx,
126+
FN_ADDRESS_COMPARISONS,
127+
expr.span,
128+
"comparing with a non-unique address of a function item",
129+
);
130+
}
131+
}
132+
}
133+
}

Diff for: clippy_lints/src/utils/paths.rs

+3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
pub const ANY_TRAIT: [&str; 3] = ["std", "any", "Any"];
55
pub const ARC: [&str; 3] = ["alloc", "sync", "Arc"];
6+
pub const ARC_PTR_EQ: [&str; 4] = ["alloc", "sync", "Arc", "ptr_eq"];
67
pub const ASMUT_TRAIT: [&str; 3] = ["core", "convert", "AsMut"];
78
pub const ASREF_TRAIT: [&str; 3] = ["core", "convert", "AsRef"];
89
pub const BEGIN_PANIC: [&str; 3] = ["std", "panicking", "begin_panic"];
@@ -74,6 +75,7 @@ pub const PATH: [&str; 3] = ["std", "path", "Path"];
7475
pub const PATH_BUF: [&str; 3] = ["std", "path", "PathBuf"];
7576
pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"];
7677
pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"];
78+
pub const PTR_EQ: [&str; 3] = ["core", "ptr", "eq"];
7779
pub const PTR_NULL: [&str; 2] = ["ptr", "null"];
7880
pub const PTR_NULL_MUT: [&str; 2] = ["ptr", "null_mut"];
7981
pub const RANGE: [&str; 3] = ["core", "ops", "Range"];
@@ -90,6 +92,7 @@ pub const RANGE_TO_INCLUSIVE: [&str; 3] = ["core", "ops", "RangeToInclusive"];
9092
pub const RANGE_TO_INCLUSIVE_STD: [&str; 3] = ["std", "ops", "RangeToInclusive"];
9193
pub const RANGE_TO_STD: [&str; 3] = ["std", "ops", "RangeTo"];
9294
pub const RC: [&str; 3] = ["alloc", "rc", "Rc"];
95+
pub const RC_PTR_EQ: [&str; 4] = ["alloc", "rc", "Rc", "ptr_eq"];
9396
pub const RECEIVER: [&str; 4] = ["std", "sync", "mpsc", "Receiver"];
9497
pub const REGEX: [&str; 3] = ["regex", "re_unicode", "Regex"];
9598
pub const REGEX_BUILDER_NEW: [&str; 5] = ["regex", "re_builder", "unicode", "RegexBuilder", "new"];

Diff for: src/lintlist/mod.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ pub use lint::Lint;
66
pub use lint::LINT_LEVELS;
77

88
// begin lint list, do not remove this comment, it’s used in `update_lints`
9-
pub const ALL_LINTS: [Lint; 361] = [
9+
pub const ALL_LINTS: [Lint; 363] = [
1010
Lint {
1111
name: "absurd_extreme_comparisons",
1212
group: "correctness",
@@ -623,6 +623,13 @@ pub const ALL_LINTS: [Lint; 361] = [
623623
deprecation: None,
624624
module: "misc",
625625
},
626+
Lint {
627+
name: "fn_address_comparisons",
628+
group: "correctness",
629+
desc: "comparison with an address of a function item",
630+
deprecation: None,
631+
module: "unnamed_address",
632+
},
626633
Lint {
627634
name: "fn_params_excessive_bools",
628635
group: "pedantic",
@@ -2408,6 +2415,13 @@ pub const ALL_LINTS: [Lint; 361] = [
24082415
deprecation: None,
24092416
module: "verbose_file_reads",
24102417
},
2418+
Lint {
2419+
name: "vtable_address_comparisons",
2420+
group: "correctness",
2421+
desc: "comparison with an address of a trait vtable",
2422+
deprecation: None,
2423+
module: "unnamed_address",
2424+
},
24112425
Lint {
24122426
name: "while_immutable_condition",
24132427
group: "correctness",

Diff for: tests/ui/fn_address_comparisons.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use std::fmt::Debug;
2+
use std::ptr;
3+
use std::rc::Rc;
4+
use std::sync::Arc;
5+
6+
fn a() {}
7+
8+
#[warn(clippy::fn_address_comparisons)]
9+
fn main() {
10+
type F = fn();
11+
let f: F = a;
12+
let g: F = f;
13+
14+
// These should fail:
15+
let _ = f == a;
16+
let _ = f != a;
17+
18+
// These should be fine:
19+
let _ = f == g;
20+
}

Diff for: tests/ui/fn_address_comparisons.stderr

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error: comparing with a non-unique address of a function item
2+
--> $DIR/fn_address_comparisons.rs:15:13
3+
|
4+
LL | let _ = f == a;
5+
| ^^^^^^
6+
|
7+
= note: `-D clippy::fn-address-comparisons` implied by `-D warnings`
8+
9+
error: comparing with a non-unique address of a function item
10+
--> $DIR/fn_address_comparisons.rs:16:13
11+
|
12+
LL | let _ = f != a;
13+
| ^^^^^^
14+
15+
error: aborting due to 2 previous errors
16+

Diff for: tests/ui/vtable_address_comparisons.rs

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use std::fmt::Debug;
2+
use std::ptr;
3+
use std::rc::Rc;
4+
use std::sync::Arc;
5+
6+
#[warn(clippy::vtable_address_comparisons)]
7+
fn main() {
8+
let a: *const dyn Debug = &1 as &dyn Debug;
9+
let b: *const dyn Debug = &1 as &dyn Debug;
10+
11+
// These should fail:
12+
let _ = a == b;
13+
let _ = a != b;
14+
let _ = a < b;
15+
let _ = a <= b;
16+
let _ = a > b;
17+
let _ = a >= b;
18+
ptr::eq(a, b);
19+
20+
let a = &1 as &dyn Debug;
21+
let b = &1 as &dyn Debug;
22+
ptr::eq(a, b);
23+
24+
let a: Rc<dyn Debug> = Rc::new(1);
25+
Rc::ptr_eq(&a, &a);
26+
27+
let a: Arc<dyn Debug> = Arc::new(1);
28+
Arc::ptr_eq(&a, &a);
29+
30+
// These should be fine:
31+
let a = &1;
32+
ptr::eq(a, a);
33+
34+
let a = Rc::new(1);
35+
Rc::ptr_eq(&a, &a);
36+
37+
let a = Arc::new(1);
38+
Arc::ptr_eq(&a, &a);
39+
40+
let a: &[u8] = b"";
41+
ptr::eq(a, a);
42+
}

0 commit comments

Comments
 (0)