Skip to content

Commit a6ba58e

Browse files
committed
new lint: mem-replace-with-uninit
1 parent ff4a3fb commit a6ba58e

File tree

8 files changed

+171
-33
lines changed

8 files changed

+171
-33
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1050,6 +1050,7 @@ Released 2018-09-13
10501050
[`mem_discriminant_non_enum`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_discriminant_non_enum
10511051
[`mem_forget`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_forget
10521052
[`mem_replace_option_with_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_option_with_none
1053+
[`mem_replace_with_uninit`]: https://rust-lang.github.io/rust-clippy/master/index.html#mem_replace_with_uninit
10531054
[`min_max`]: https://rust-lang.github.io/rust-clippy/master/index.html#min_max
10541055
[`misaligned_transmute`]: https://rust-lang.github.io/rust-clippy/master/index.html#misaligned_transmute
10551056
[`misrefactored_assign_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#misrefactored_assign_op

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

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

9-
[There are 313 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
9+
[There are 314 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1010

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

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
781781
matches::SINGLE_MATCH,
782782
mem_discriminant::MEM_DISCRIMINANT_NON_ENUM,
783783
mem_replace::MEM_REPLACE_OPTION_WITH_NONE,
784+
mem_replace::MEM_REPLACE_WITH_UNINIT,
784785
methods::CHARS_LAST_CMP,
785786
methods::CHARS_NEXT_CMP,
786787
methods::CLONE_DOUBLE_REF,
@@ -1116,6 +1117,7 @@ pub fn register_plugins(reg: &mut rustc_driver::plugin::Registry<'_>, conf: &Con
11161117
loops::REVERSE_RANGE_LOOP,
11171118
loops::WHILE_IMMUTABLE_CONDITION,
11181119
mem_discriminant::MEM_DISCRIMINANT_NON_ENUM,
1120+
mem_replace::MEM_REPLACE_WITH_UNINIT,
11191121
methods::CLONE_DOUBLE_REF,
11201122
methods::INTO_ITER_ON_ARRAY,
11211123
methods::TEMPORARY_CSTRING_AS_PTR,

clippy_lints/src/mem_replace.rs

+95-31
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
use crate::utils::{match_def_path, match_qpath, paths, snippet_with_applicability, span_lint_and_sugg};
1+
use crate::utils::{
2+
match_def_path, match_qpath, paths, snippet_with_applicability, span_help_and_lint, span_lint_and_sugg,
3+
};
24
use if_chain::if_chain;
35
use rustc::hir::{Expr, ExprKind, MutMutable, QPath};
46
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
@@ -32,7 +34,40 @@ declare_clippy_lint! {
3234
"replacing an `Option` with `None` instead of `take()`"
3335
}
3436

35-
declare_lint_pass!(MemReplace => [MEM_REPLACE_OPTION_WITH_NONE]);
37+
declare_clippy_lint! {
38+
/// **What it does:** Checks for `mem::replace(&mut _, mem::uninitialized())`
39+
/// and `mem::replace(&mut _, mem::zeroed())`.
40+
///
41+
/// **Why is this bad?** This will lead to undefined behavior even if the
42+
/// value is overwritten later, because the uninitialized value may be
43+
/// observed in the case of a panic.
44+
///
45+
/// **Known problems:** None.
46+
///
47+
/// **Example:**
48+
///
49+
/// ```
50+
/// use std::mem;
51+
///# fn may_panic(v: Vec<i32>) -> Vec<i32> { v }
52+
///
53+
/// #[allow(deprecated, invalid_value)]
54+
/// fn myfunc (v: &mut Vec<i32>) {
55+
/// let taken_v = unsafe { mem::replace(v, mem::uninitialized()) };
56+
/// let new_v = may_panic(taken_v); // undefined behavior on panic
57+
/// mem::forget(mem::replace(v, new_v));
58+
/// }
59+
/// ```
60+
///
61+
/// The [take_mut](https://docs.rs/take_mut) crate offers a sound solution,
62+
/// at the cost of either lazily creating a replacement value or aborting
63+
/// on panic, to ensure that the uninitialized value cannot be observed.
64+
pub MEM_REPLACE_WITH_UNINIT,
65+
correctness,
66+
"`mem::replace(&mut _, mem::uninitialized())` or `mem::replace(&mut _, mem::zeroed())`"
67+
}
68+
69+
declare_lint_pass!(MemReplace =>
70+
[MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT]);
3671

3772
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
3873
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
@@ -45,37 +80,66 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace {
4580
if match_def_path(cx, def_id, &paths::MEM_REPLACE);
4681

4782
// Check that second argument is `Option::None`
48-
if let ExprKind::Path(ref replacement_qpath) = func_args[1].node;
49-
if match_qpath(replacement_qpath, &paths::OPTION_NONE);
50-
5183
then {
52-
// Since this is a late pass (already type-checked),
53-
// and we already know that the second argument is an
54-
// `Option`, we do not need to check the first
55-
// argument's type. All that's left is to get
56-
// replacee's path.
57-
let replaced_path = match func_args[0].node {
58-
ExprKind::AddrOf(MutMutable, ref replaced) => {
59-
if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
60-
replaced_path
61-
} else {
62-
return
63-
}
64-
},
65-
ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
66-
_ => return,
67-
};
84+
if let ExprKind::Path(ref replacement_qpath) = func_args[1].node {
85+
if match_qpath(replacement_qpath, &paths::OPTION_NONE) {
6886

69-
let mut applicability = Applicability::MachineApplicable;
70-
span_lint_and_sugg(
71-
cx,
72-
MEM_REPLACE_OPTION_WITH_NONE,
73-
expr.span,
74-
"replacing an `Option` with `None`",
75-
"consider `Option::take()` instead",
76-
format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),
77-
applicability,
78-
);
87+
// Since this is a late pass (already type-checked),
88+
// and we already know that the second argument is an
89+
// `Option`, we do not need to check the first
90+
// argument's type. All that's left is to get
91+
// replacee's path.
92+
let replaced_path = match func_args[0].node {
93+
ExprKind::AddrOf(MutMutable, ref replaced) => {
94+
if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.node {
95+
replaced_path
96+
} else {
97+
return
98+
}
99+
},
100+
ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path,
101+
_ => return,
102+
};
103+
104+
let mut applicability = Applicability::MachineApplicable;
105+
span_lint_and_sugg(
106+
cx,
107+
MEM_REPLACE_OPTION_WITH_NONE,
108+
expr.span,
109+
"replacing an `Option` with `None`",
110+
"consider `Option::take()` instead",
111+
format!("{}.take()", snippet_with_applicability(cx, replaced_path.span, "", &mut applicability)),
112+
applicability,
113+
);
114+
}
115+
}
116+
if let ExprKind::Call(ref repl_func, ref repl_args) = func_args[1].node {
117+
if_chain! {
118+
if repl_args.is_empty();
119+
if let ExprKind::Path(ref repl_func_qpath) = repl_func.node;
120+
if let Some(repl_def_id) = cx.tables.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
121+
then {
122+
if match_def_path(cx, repl_def_id, &paths::MEM_UNINITIALIZED) {
123+
span_help_and_lint(
124+
cx,
125+
MEM_REPLACE_WITH_UNINIT,
126+
expr.span,
127+
"replacing with `mem::uninitialized()`",
128+
"consider using the `take_mut` crate instead",
129+
);
130+
} else if match_def_path(cx, repl_def_id, &paths::MEM_ZEROED) &&
131+
!cx.tables.expr_ty(&func_args[1]).is_primitive() {
132+
span_help_and_lint(
133+
cx,
134+
MEM_REPLACE_WITH_UNINIT,
135+
expr.span,
136+
"replacing with `mem::zeroed()`",
137+
"consider using a default value or the `take_mut` crate instead",
138+
);
139+
}
140+
}
141+
}
142+
}
79143
}
80144
}
81145
}

clippy_lints/src/utils/paths.rs

+2
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ pub const MEM_FORGET: [&str; 3] = ["core", "mem", "forget"];
5252
pub const MEM_MAYBEUNINIT: [&str; 4] = ["core", "mem", "maybe_uninit", "MaybeUninit"];
5353
pub const MEM_MAYBEUNINIT_UNINIT: [&str; 5] = ["core", "mem", "maybe_uninit", "MaybeUninit", "uninit"];
5454
pub const MEM_REPLACE: [&str; 3] = ["core", "mem", "replace"];
55+
pub const MEM_UNINITIALIZED: [&str; 3] = ["core", "mem", "uninitialized"];
56+
pub const MEM_ZEROED: [&str; 3] = ["core", "mem", "zeroed"];
5557
pub const MUTEX: [&str; 4] = ["std", "sync", "mutex", "Mutex"];
5658
pub const OPEN_OPTIONS: [&str; 3] = ["std", "fs", "OpenOptions"];
5759
pub const OPS_MODULE: [&str; 2] = ["core", "ops"];

src/lintlist/mod.rs

+8-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; 313] = [
9+
pub const ALL_LINTS: [Lint; 314] = [
1010
Lint {
1111
name: "absurd_extreme_comparisons",
1212
group: "correctness",
@@ -1043,6 +1043,13 @@ pub const ALL_LINTS: [Lint; 313] = [
10431043
deprecation: None,
10441044
module: "mem_replace",
10451045
},
1046+
Lint {
1047+
name: "mem_replace_with_uninit",
1048+
group: "correctness",
1049+
desc: "`mem::replace(&mut _, mem::uninitialized())` or `mem::zeroed()`",
1050+
deprecation: None,
1051+
module: "mem_replace",
1052+
},
10461053
Lint {
10471054
name: "min_max",
10481055
group: "correctness",

tests/ui/repl_uninit.rs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#![allow(deprecated, invalid_value)]
2+
#![warn(clippy::all)]
3+
4+
use std::mem;
5+
6+
fn might_panic<X>(x: X) -> X {
7+
// in practice this would be a possibly-panicky operation
8+
x
9+
}
10+
11+
fn main() {
12+
let mut v = vec![0i32; 4];
13+
// the following is UB if `might_panic` panics
14+
unsafe {
15+
let taken_v = mem::replace(&mut v, mem::uninitialized());
16+
let new_v = might_panic(taken_v);
17+
std::mem::forget(mem::replace(&mut v, new_v));
18+
}
19+
20+
unsafe {
21+
let taken_v = mem::replace(&mut v, mem::uninitialized());
22+
let new_v = might_panic(taken_v);
23+
std::mem::forget(mem::replace(&mut v, new_v));
24+
}
25+
26+
// this is silly but OK, because usize is a primitive type
27+
let mut u: usize = 42;
28+
let uref = &mut u;
29+
let taken_u = unsafe { mem::replace(uref, mem::zeroed()) };
30+
*uref = taken_u + 1;
31+
32+
// this is still not OK, because uninit
33+
let taken_u = unsafe { mem::replace(uref, mem::uninitialized()) };
34+
*uref = taken_u + 1;
35+
}

tests/ui/repl_uninit.stderr

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
error: replacing with `mem::uninitialized()`
2+
--> $DIR/repl_uninit.rs:15:23
3+
|
4+
LL | let taken_v = mem::replace(&mut v, mem::uninitialized());
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= note: `-D clippy::mem-replace-with-uninit` implied by `-D warnings`
8+
= help: consider using the `take_mut` crate instead
9+
10+
error: replacing with `mem::uninitialized()`
11+
--> $DIR/repl_uninit.rs:21:23
12+
|
13+
LL | let taken_v = mem::replace(&mut v, mem::uninitialized());
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15+
|
16+
= help: consider using the `take_mut` crate instead
17+
18+
error: replacing with `mem::uninitialized()`
19+
--> $DIR/repl_uninit.rs:33:28
20+
|
21+
LL | let taken_u = unsafe { mem::replace(uref, mem::uninitialized()) };
22+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
23+
|
24+
= help: consider using the `take_mut` crate instead
25+
26+
error: aborting due to 3 previous errors
27+

0 commit comments

Comments
 (0)