Skip to content

Commit 7312a93

Browse files
committed
new lint: large_stack_frames
1 parent a3b185b commit 7312a93

File tree

9 files changed

+262
-1
lines changed

9 files changed

+262
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4815,6 +4815,7 @@ Released 2018-09-13
48154815
[`get_last_with_len`]: https://rust-lang.github.io/rust-clippy/master/index.html#get_last_with_len
48164816
[`get_unwrap`]: https://rust-lang.github.io/rust-clippy/master/index.html#get_unwrap
48174817
[`host_endian_bytes`]: https://rust-lang.github.io/rust-clippy/master/index.html#host_endian_bytes
4818+
[`large_stack_frames`]: https://rust-lang.github.io/rust-clippy/master/index.html#large_stack_frames
48184819
[`identity_conversion`]: https://rust-lang.github.io/rust-clippy/master/index.html#identity_conversion
48194820
[`identity_op`]: https://rust-lang.github.io/rust-clippy/master/index.html#identity_op
48204821
[`if_let_mutex`]: https://rust-lang.github.io/rust-clippy/master/index.html#if_let_mutex

book/src/lint_configuration.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,15 @@ The maximum allowed size for arrays on the stack
338338
* [`large_const_arrays`](https://rust-lang.github.io/rust-clippy/master/index.html#large_const_arrays)
339339

340340

341-
## `vec-box-size-threshold`
341+
### stack-size-threshold
342+
The maximum allowed stack size for functions in bytes
343+
344+
**Default Value:** `512000` (`u64`)
345+
346+
* [large_stack_frames](https://rust-lang.github.io/rust-clippy/master/index.html#large_stack_frames)
347+
348+
349+
### vec-box-size-threshold
342350
The size of the boxed type in bytes, where boxing in a `Vec` is allowed
343351

344352
**Default Value:** `4096` (`u64`)

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
198198
crate::functions::TOO_MANY_ARGUMENTS_INFO,
199199
crate::functions::TOO_MANY_LINES_INFO,
200200
crate::future_not_send::FUTURE_NOT_SEND_INFO,
201+
crate::large_stack_frames::LARGE_STACK_FRAMES_INFO,
201202
crate::if_let_mutex::IF_LET_MUTEX_INFO,
202203
crate::if_not_else::IF_NOT_ELSE_INFO,
203204
crate::if_then_some_else_none::IF_THEN_SOME_ELSE_NONE_INFO,
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
use std::ops::AddAssign;
2+
3+
use clippy_utils::diagnostics::span_lint_and_then;
4+
use rustc_hir::def_id::LocalDefId;
5+
use rustc_hir::intravisit::FnKind;
6+
use rustc_hir::Body;
7+
use rustc_hir::FnDecl;
8+
use rustc_lint::{LateContext, LateLintPass};
9+
use rustc_session::declare_tool_lint;
10+
use rustc_session::impl_lint_pass;
11+
use rustc_span::Span;
12+
13+
declare_clippy_lint! {
14+
/// ### What it does
15+
/// Checks for functions that use a lot of stack space.
16+
///
17+
/// This often happens when constructing a large type, such as an array with a lot of elements,
18+
/// or constructing *many* smaller-but-still-large structs, or copying around a lot of large types.
19+
///
20+
/// This lint is a more general version of [`large_stack_arrays`](https://rust-lang.github.io/rust-clippy/master/#large_stack_arrays)
21+
/// that is intended to look at functions as a whole instead of only individual array expressions inside of a function.
22+
///
23+
/// ### Why is this bad?
24+
/// The stack region of memory is very limited in size (usually *much* smaller than the heap) and attempting to
25+
/// use too much will result in a stack overflow and crash the program.
26+
/// To avoid this, you should consider allocating large types on the heap instead (e.g. by boxing them).
27+
///
28+
/// Keep in mind that the code path to construction of large types does not even need to be reachable;
29+
/// it purely needs to *exist* inside of the function to contribute to the stack size.
30+
/// For example, this causes a stack overflow even though the branch is unreachable (with `-Zmir-opt-level=0`):
31+
/// ```rust,ignore
32+
/// fn main() {
33+
/// if false {
34+
/// let x = [0u8; 10000000]; // 10 MB stack array
35+
/// black_box(&x);
36+
/// }
37+
/// }
38+
/// ```
39+
///
40+
/// ### Drawbacks
41+
/// False positives. The stack size that clippy sees is an estimated value and can be vastly different
42+
/// from the actual stack usage after optimizations passes have run (especially true in release mode).
43+
/// Modern compilers are very smart and are able to optimize away a lot of unnecessary stack allocations.
44+
/// In debug mode however, it is usually more accurate.
45+
///
46+
/// This lint works by summing up the size of all locals and comparing them against a (configurable, but high-by-default)
47+
/// threshold.
48+
/// Note that "locals" in this context refers to [MIR locals](https://rustc-dev-guide.rust-lang.org/mir/index.html#key-mir-vocabulary),
49+
/// i.e. real local variables that the user typed, storage for temporary values, function arguments
50+
/// and the return value.
51+
///
52+
/// ### Example
53+
/// This function creates four 500 KB arrays on the stack. Quite big but just small enough to not trigger `large_stack_arrays`.
54+
/// However, looking at the function as a whole, it's clear that this uses a lot of stack space.
55+
/// ```rust
56+
/// struct QuiteLargeType([u8; 500_000]);
57+
/// fn foo() {
58+
/// // ... some function that uses a lot of stack space ...
59+
/// let _x1 = QuiteLargeType([0; 500_000]);
60+
/// let _x2 = QuiteLargeType([0; 500_000]);
61+
/// let _x3 = QuiteLargeType([0; 500_000]);
62+
/// let _x4 = QuiteLargeType([0; 500_000]);
63+
/// }
64+
/// ```
65+
///
66+
/// Instead of doing this, allocate the arrays on the heap.
67+
/// This currently requires going through a `Vec` first and then converting it to a `Box`:
68+
/// ```rust
69+
/// struct NotSoLargeType(Box<[u8]>);
70+
///
71+
/// fn foo() {
72+
/// let _x1 = NotSoLargeType(vec![0; 500_000].into_boxed_slice());
73+
/// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Now heap allocated.
74+
/// // The size of `NotSoLargeType` is 16 bytes.
75+
/// // ...
76+
/// }
77+
/// ```
78+
#[clippy::version = "1.71.0"]
79+
pub LARGE_STACK_FRAMES,
80+
nursery,
81+
"checks for functions that allocate a lot of stack space"
82+
}
83+
84+
pub struct LargeStackFrames {
85+
maximum_allowed_size: u64,
86+
}
87+
88+
impl LargeStackFrames {
89+
#[must_use]
90+
pub fn new(size: u64) -> Self {
91+
Self {
92+
maximum_allowed_size: size,
93+
}
94+
}
95+
}
96+
97+
impl_lint_pass!(LargeStackFrames => [LARGE_STACK_FRAMES]);
98+
99+
#[derive(Copy, Clone)]
100+
enum Space {
101+
Used(u64),
102+
Overflow,
103+
}
104+
105+
impl Space {
106+
pub fn exceeds_limit(self, limit: u64) -> bool {
107+
match self {
108+
Self::Used(used) => used > limit,
109+
Self::Overflow => true,
110+
}
111+
}
112+
}
113+
114+
impl AddAssign<u64> for Space {
115+
fn add_assign(&mut self, rhs: u64) {
116+
if let Self::Used(lhs) = self {
117+
match lhs.checked_add(rhs) {
118+
Some(sum) => *self = Self::Used(sum),
119+
None => {
120+
*self = Self::Overflow;
121+
},
122+
}
123+
}
124+
}
125+
}
126+
127+
impl<'tcx> LateLintPass<'tcx> for LargeStackFrames {
128+
fn check_fn(
129+
&mut self,
130+
cx: &LateContext<'tcx>,
131+
_: FnKind<'tcx>,
132+
_: &'tcx FnDecl<'tcx>,
133+
_: &'tcx Body<'tcx>,
134+
span: Span,
135+
local_def_id: LocalDefId,
136+
) {
137+
let def_id = local_def_id.to_def_id();
138+
139+
let mir = cx.tcx.optimized_mir(def_id);
140+
let param_env = cx.tcx.param_env(def_id);
141+
142+
let mut frame_size = Space::Used(0);
143+
144+
for local in &mir.local_decls {
145+
if let Ok(layout) = cx.tcx.layout_of(param_env.and(local.ty)) {
146+
frame_size += layout.size.bytes();
147+
}
148+
}
149+
150+
if frame_size.exceeds_limit(self.maximum_allowed_size) {
151+
span_lint_and_then(
152+
cx,
153+
LARGE_STACK_FRAMES,
154+
span,
155+
"this function allocates a large amount of stack space",
156+
|diag| {
157+
diag.note("allocating large amounts of stack space can overflow the stack");
158+
},
159+
);
160+
}
161+
}
162+
}

clippy_lints/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ mod from_raw_with_void_ptr;
142142
mod from_str_radix_10;
143143
mod functions;
144144
mod future_not_send;
145+
mod large_stack_frames;
145146
mod if_let_mutex;
146147
mod if_not_else;
147148
mod if_then_some_else_none;
@@ -1042,6 +1043,8 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10421043
min_ident_chars_threshold,
10431044
})
10441045
});
1046+
let stack_size_threshold = conf.stack_size_threshold;
1047+
store.register_late_pass(move |_| Box::new(large_stack_frames::LargeStackFrames::new(stack_size_threshold)));
10451048
// add lints here, do not remove this comment, it's used in `new_lint`
10461049
}
10471050

clippy_lints/src/utils/conf.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,10 @@ define_Conf! {
387387
///
388388
/// The maximum allowed size for arrays on the stack
389389
(array_size_threshold: u64 = 512_000),
390+
/// Lint: LARGE_STACK_FRAMES.
391+
///
392+
/// The maximum allowed stack size for functions in bytes
393+
(stack_size_threshold: u64 = 512_000),
390394
/// Lint: VEC_BOX.
391395
///
392396
/// The size of the boxed type in bytes, where boxing in a `Vec` is allowed

tests/ui-toml/toml_unknown_key/conf_unknown_key.stderr

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ error: error reading Clippy's configuration file: unknown field `foobar`, expect
4444
semicolon-inside-block-ignore-singleline
4545
semicolon-outside-block-ignore-multiline
4646
single-char-binding-names-threshold
47+
stack-size-threshold
4748
standard-macro-braces
4849
suppress-restriction-lint-in-const
4950
third-party

tests/ui/large_stack_frames.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#![allow(unused, incomplete_features)]
2+
#![warn(clippy::large_stack_frames)]
3+
#![feature(unsized_locals)]
4+
5+
use std::hint::black_box;
6+
7+
fn generic<T: Default>() {
8+
let x = T::default();
9+
black_box(&x);
10+
}
11+
12+
fn unsized_local() {
13+
let x: dyn std::fmt::Display = *(Box::new(1) as Box<dyn std::fmt::Display>);
14+
black_box(&x);
15+
}
16+
17+
struct ArrayDefault<const N: usize>([u8; N]);
18+
19+
impl<const N: usize> Default for ArrayDefault<N> {
20+
fn default() -> Self {
21+
Self([0; N])
22+
}
23+
}
24+
25+
fn many_small_arrays() {
26+
let x = [0u8; 500_000];
27+
let x2 = [0u8; 500_000];
28+
let x3 = [0u8; 500_000];
29+
let x4 = [0u8; 500_000];
30+
let x5 = [0u8; 500_000];
31+
black_box((&x, &x2, &x3, &x4, &x5));
32+
}
33+
34+
fn large_return_value() -> ArrayDefault<1_000_000> {
35+
Default::default()
36+
}
37+
38+
fn large_fn_arg(x: ArrayDefault<1_000_000>) {
39+
black_box(&x);
40+
}
41+
42+
fn main() {
43+
generic::<ArrayDefault<1_000_000>>();
44+
}

tests/ui/large_stack_frames.stderr

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
error: this function allocates a large amount of stack space
2+
--> $DIR/large_stack_frames.rs:25:1
3+
|
4+
LL | / fn many_small_arrays() {
5+
LL | | let x = [0u8; 500_000];
6+
LL | | let x2 = [0u8; 500_000];
7+
LL | | let x3 = [0u8; 500_000];
8+
... |
9+
LL | | black_box((&x, &x2, &x3, &x4, &x5));
10+
LL | | }
11+
| |_^
12+
|
13+
= note: allocating large amounts of stack space can overflow the stack
14+
= note: `-D clippy::large-stack-frames` implied by `-D warnings`
15+
16+
error: this function allocates a large amount of stack space
17+
--> $DIR/large_stack_frames.rs:34:1
18+
|
19+
LL | / fn large_return_value() -> ArrayDefault<1_000_000> {
20+
LL | | Default::default()
21+
LL | | }
22+
| |_^
23+
|
24+
= note: allocating large amounts of stack space can overflow the stack
25+
26+
error: this function allocates a large amount of stack space
27+
--> $DIR/large_stack_frames.rs:38:1
28+
|
29+
LL | / fn large_fn_arg(x: ArrayDefault<1_000_000>) {
30+
LL | | black_box(&x);
31+
LL | | }
32+
| |_^
33+
|
34+
= note: allocating large amounts of stack space can overflow the stack
35+
36+
error: aborting due to 3 previous errors
37+

0 commit comments

Comments
 (0)