|
| 1 | +// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2024 Datadog, Inc. |
| 2 | + |
| 3 | +use rustc_hir::def_id::DefId; |
| 4 | +use rustc_middle::mir::{Body, TerminatorKind}; |
| 5 | +use rustc_middle::ty::TyCtxt; |
| 6 | +use rustc_span::Span; |
| 7 | +use std::collections::HashMap; |
| 8 | + |
| 9 | +/// Represents a violation of the no-allocation rule |
| 10 | +#[derive(Debug)] |
| 11 | +pub struct AllocationViolation { |
| 12 | + pub span: Span, |
| 13 | + pub reason: String, |
| 14 | +} |
| 15 | + |
| 16 | +/// Detects heap allocations in a function's MIR |
| 17 | +pub fn detect_allocation_in_mir<'tcx>( |
| 18 | + tcx: TyCtxt<'tcx>, |
| 19 | + mir: &Body<'tcx>, |
| 20 | + _fn_def_id: DefId, |
| 21 | + cache: &mut HashMap<DefId, bool>, |
| 22 | +) -> Option<AllocationViolation> { |
| 23 | + // Iterate through basic blocks |
| 24 | + for (_bb, bb_data) in mir.basic_blocks.iter_enumerated() { |
| 25 | + // Check terminator for calls |
| 26 | + if let Some(terminator) = &bb_data.terminator |
| 27 | + && let TerminatorKind::Call { func, .. } = &terminator.kind |
| 28 | + { |
| 29 | + // Extract function DefId using const_fn_def |
| 30 | + if let Some((callee_def_id, _generics)) = func.const_fn_def() { |
| 31 | + let path = tcx.def_path_str(callee_def_id); |
| 32 | + |
| 33 | + // Check if it's a known allocating function |
| 34 | + if is_allocating_function(&path) { |
| 35 | + return Some(AllocationViolation { |
| 36 | + span: terminator.source_info.span, |
| 37 | + reason: format!("calls allocating function: {path}"), |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + // Check transitively (with cycle detection) |
| 42 | + if should_analyze_transitively(tcx, callee_def_id) |
| 43 | + && function_allocates(tcx, callee_def_id, cache) |
| 44 | + { |
| 45 | + return Some(AllocationViolation { |
| 46 | + span: terminator.source_info.span, |
| 47 | + reason: format!("calls function that allocates: {path}"), |
| 48 | + }); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + None |
| 55 | +} |
| 56 | + |
| 57 | +/// Checks if a function path corresponds to a known allocating function |
| 58 | +fn is_allocating_function(path: &str) -> bool { |
| 59 | + // Direct allocation functions - these are the low-level allocators |
| 60 | + if path.contains("alloc::alloc::") |
| 61 | + && (path.contains("::alloc") |
| 62 | + || path.contains("::allocate") |
| 63 | + || path.contains("::exchange_malloc") |
| 64 | + || path.contains("::box_free")) |
| 65 | + { |
| 66 | + return true; |
| 67 | + } |
| 68 | + |
| 69 | + // Box allocations - check for various Box patterns |
| 70 | + if (path.contains("::Box::") || path.contains("::Box::<")) && path.contains("::new") { |
| 71 | + return true; |
| 72 | + } |
| 73 | + |
| 74 | + // Vec allocations and operations that may allocate |
| 75 | + if (path.contains("::Vec::") || path.contains("::Vec::<")) |
| 76 | + && (path.contains("::new") |
| 77 | + || path.contains("::with_capacity") |
| 78 | + || path.contains("::push") |
| 79 | + || path.contains("::insert") |
| 80 | + || path.contains("::extend") |
| 81 | + || path.contains("::append") |
| 82 | + || path.contains("::resize") |
| 83 | + || path.contains("::from_elem")) |
| 84 | + { |
| 85 | + return true; |
| 86 | + } |
| 87 | + |
| 88 | + // String allocations |
| 89 | + if path.contains("::String::") |
| 90 | + && (path.contains("::new") |
| 91 | + || path.contains("::from") |
| 92 | + || path.contains("::from_utf8") |
| 93 | + || path.contains("::from_utf16") |
| 94 | + || path.contains("::push_str") |
| 95 | + || path.contains("::push") |
| 96 | + || path.contains("::insert") |
| 97 | + || path.contains("::insert_str")) |
| 98 | + { |
| 99 | + return true; |
| 100 | + } |
| 101 | + |
| 102 | + // Format macro and related |
| 103 | + if path.contains("::format") || path.contains("fmt::format") { |
| 104 | + return true; |
| 105 | + } |
| 106 | + |
| 107 | + // Rc and Arc |
| 108 | + if (path.contains("::Rc::") |
| 109 | + || path.contains("::Rc::<") |
| 110 | + || path.contains("::Arc::") |
| 111 | + || path.contains("::Arc::<")) |
| 112 | + && (path.contains("::new") || path.contains("::clone")) |
| 113 | + { |
| 114 | + return true; |
| 115 | + } |
| 116 | + |
| 117 | + // Collection types - broader matching |
| 118 | + if (path.contains("HashMap") |
| 119 | + || path.contains("BTreeMap") |
| 120 | + || path.contains("HashSet") |
| 121 | + || path.contains("BTreeSet") |
| 122 | + || path.contains("VecDeque") |
| 123 | + || path.contains("LinkedList") |
| 124 | + || path.contains("BinaryHeap")) |
| 125 | + && (path.contains(">::new") |
| 126 | + || path.contains(">::with_capacity") |
| 127 | + || path.contains(">::insert") |
| 128 | + || path.contains(">::push")) |
| 129 | + { |
| 130 | + return true; |
| 131 | + } |
| 132 | + |
| 133 | + // to_string, to_owned methods - these allocate |
| 134 | + if path.contains("::to_string") || path.contains("::to_owned") { |
| 135 | + return true; |
| 136 | + } |
| 137 | + |
| 138 | + // RawVec - internal vec allocator |
| 139 | + if path.contains("RawVec") && (path.contains("::new") || path.contains("::allocate")) { |
| 140 | + return true; |
| 141 | + } |
| 142 | + |
| 143 | + false |
| 144 | +} |
| 145 | + |
| 146 | +/// Determines if we should recursively analyze a function |
| 147 | +fn should_analyze_transitively(tcx: TyCtxt<'_>, def_id: DefId) -> bool { |
| 148 | + // Only analyze functions in the local crate |
| 149 | + // External crates are harder to analyze and may not have MIR available |
| 150 | + def_id.krate == rustc_hir::def_id::LOCAL_CRATE && tcx.is_mir_available(def_id) |
| 151 | +} |
| 152 | + |
| 153 | +/// Recursively checks if a function allocates, with memoization |
| 154 | +fn function_allocates<'tcx>( |
| 155 | + tcx: TyCtxt<'tcx>, |
| 156 | + def_id: DefId, |
| 157 | + cache: &mut HashMap<DefId, bool>, |
| 158 | +) -> bool { |
| 159 | + // Check cache |
| 160 | + if let Some(&result) = cache.get(&def_id) { |
| 161 | + return result; |
| 162 | + } |
| 163 | + |
| 164 | + // Mark as false initially (cycle detection) |
| 165 | + cache.insert(def_id, false); |
| 166 | + |
| 167 | + // Try to get MIR |
| 168 | + if !tcx.is_mir_available(def_id) { |
| 169 | + // Conservative: assume external functions don't allocate |
| 170 | + // This prevents false positives for standard library functions |
| 171 | + return false; |
| 172 | + } |
| 173 | + |
| 174 | + let mir = tcx.optimized_mir(def_id); |
| 175 | + let allocates = detect_allocation_in_mir(tcx, mir, def_id, cache).is_some(); |
| 176 | + |
| 177 | + // Update cache with actual result |
| 178 | + cache.insert(def_id, allocates); |
| 179 | + allocates |
| 180 | +} |
0 commit comments