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