Skip to main content

forge_lint/sol/low/
reentrancy_events.rs

1use super::{ReentrancyEvents, calls_loop::is_state_mutating_external_call};
2use crate::{
3    linter::{LateLintPass, LintContext},
4    sol::{
5        Severity, SolLint,
6        analysis::{
7            DEFAULT_HELPER_ANALYSIS_CACHE_LIMIT, HelperAnalysisCache, dispatched_function,
8            for_each_child, is_exit_call, loop_stmts, loop_update,
9        },
10    },
11};
12use solar::{
13    interface::Span,
14    sema::{
15        Gcx,
16        builtins::Builtin,
17        hir::{
18            self, BinOpKind, Block, ContractId, Expr, ExprKind, Function, FunctionId, LoopSource,
19            Stmt, StmtKind,
20        },
21    },
22};
23use std::collections::{HashMap, HashSet};
24
25declare_forge_lint!(
26    REENTRANCY_EVENTS,
27    Severity::Low,
28    "reentrancy-events",
29    "event emitted after an external call; reentrancy can reorder or fabricate logs that off-chain consumers rely on"
30);
31
32impl<'gcx> LateLintPass<'gcx> for ReentrancyEvents {
33    fn check_function(&mut self, ctx: &LintContext, gcx: Gcx<'gcx>, func: &'gcx Function<'gcx>) {
34        let Some(body) = func.body else { return };
35        Analyzer::new(ctx, gcx, func.contract).analyze_callable(func, body, false);
36    }
37}
38
39type Placeholder<'gcx> = Option<(&'gcx [hir::Modifier<'gcx>], usize, Block<'gcx>)>;
40
41/// How control can leave a piece of code. Each exit kind records whether an external call was
42/// seen on some path reaching it; `None` means no path exits that way. Aborting paths
43/// (`revert`, `require(false)`, ...) are simply absent, so they cannot taint later statements.
44#[derive(Clone, Copy, Debug, Default)]
45struct Exits {
46    fallthrough: Option<bool>,
47    return_: Option<bool>,
48    break_: Option<bool>,
49    continue_: Option<bool>,
50}
51
52impl Exits {
53    fn fallthrough(tainted: bool) -> Self {
54        Self { fallthrough: Some(tainted), ..Self::default() }
55    }
56
57    fn return_(tainted: bool) -> Self {
58        Self { return_: Some(tainted), ..Self::default() }
59    }
60
61    fn break_(tainted: bool) -> Self {
62        Self { break_: Some(tainted), ..Self::default() }
63    }
64
65    fn continue_(tainted: bool) -> Self {
66        Self { continue_: Some(tainted), ..Self::default() }
67    }
68
69    fn merge(&mut self, other: Self) {
70        self.fallthrough = join(self.fallthrough, other.fallthrough);
71        self.return_ = join(self.return_, other.return_);
72        self.break_ = join(self.break_, other.break_);
73        self.continue_ = join(self.continue_, other.continue_);
74    }
75
76    /// State of the paths that return to the caller normally.
77    fn normal(self) -> Option<bool> {
78        join(self.fallthrough, self.return_)
79    }
80}
81
82/// Joins two path states: reachable if either is, tainted if either is.
83fn join(lhs: Option<bool>, rhs: Option<bool>) -> Option<bool> {
84    match (lhs, rhs) {
85        (Some(lhs), Some(rhs)) => Some(lhs || rhs),
86        _ => lhs.or(rhs),
87    }
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
91struct InlineCallKey {
92    func_id: FunctionId,
93    external_call_seen: bool,
94    suppress_inline_reports: bool,
95}
96
97struct Analyzer<'ctx, 's, 'c, 'gcx> {
98    ctx: &'ctx LintContext<'s, 'c>,
99    gcx: Gcx<'gcx>,
100    /// Contract being analysed; `this.f()` and `super.f()` resolve against it, also inside
101    /// inlined helpers (runtime `this`).
102    enclosing_contract: Option<ContractId>,
103    call_stack: Vec<FunctionId>,
104    inline_cache: HelperAnalysisCache<InlineCallKey, Exits>,
105    /// Whether a helper can ever perform an external call; used where a recursive edge is cut.
106    external_call_reachability: HashMap<FunctionId, bool>,
107    /// Set when a reachability walk hit a recursive edge, so a negative result is inconclusive.
108    reachability_cut: bool,
109    emitted: HashSet<Span>,
110    /// Inside a helper entered with a clean state: the helper's own pass reports its emits.
111    suppress_inline_reports: bool,
112    /// Set by an inlined callee with no normal exit, so the enclosing statement aborts.
113    expr_aborted: bool,
114}
115
116impl<'ctx, 's, 'c, 'gcx> Analyzer<'ctx, 's, 'c, 'gcx> {
117    fn new(
118        ctx: &'ctx LintContext<'s, 'c>,
119        gcx: Gcx<'gcx>,
120        enclosing_contract: Option<ContractId>,
121    ) -> Self {
122        Self {
123            ctx,
124            gcx,
125            enclosing_contract,
126            call_stack: Vec::new(),
127            inline_cache: HelperAnalysisCache::new(DEFAULT_HELPER_ANALYSIS_CACHE_LIMIT),
128            external_call_reachability: HashMap::new(),
129            reachability_cut: false,
130            emitted: HashSet::new(),
131            suppress_inline_reports: false,
132            expr_aborted: false,
133        }
134    }
135
136    fn analyze_callable(
137        &mut self,
138        func: &'gcx Function<'gcx>,
139        body: Block<'gcx>,
140        entry: bool,
141    ) -> Exits {
142        self.analyze_modifier_chain(func.modifiers, 0, body, entry)
143    }
144
145    fn analyze_modifier_chain(
146        &mut self,
147        modifiers: &'gcx [hir::Modifier<'gcx>],
148        index: usize,
149        body: Block<'gcx>,
150        mut entry: bool,
151    ) -> Exits {
152        let Some(modifier) = modifiers.get(index) else {
153            return self.analyze_block(body, None, entry);
154        };
155        for arg in modifier.args.exprs() {
156            self.expr_aborted = false;
157            self.analyze_expr(arg, &mut entry);
158            // An aborting argument means the modifier, and so the body, is never entered.
159            if self.expr_aborted {
160                return Exits::default();
161            }
162        }
163        // A modifier may legitimately appear several times in the chain (`m(false) m(true)`),
164        // so duplicates are not skipped; `index` strictly increases, and recursion through
165        // internal calls is handled by `analyze_internal_call`.
166        let Some((modifier_id, modifier_body)) = self
167            .enclosing_contract
168            .map_or_else(
169                || modifier.id.as_function(),
170                |contract| self.gcx.resolve_modifier_target(contract, modifier),
171            )
172            .and_then(|id| Some((id, self.gcx.hir.function(id).body?)))
173        else {
174            return self.analyze_modifier_chain(modifiers, index + 1, body, entry);
175        };
176        self.call_stack.push(modifier_id);
177        let exits = self.analyze_block(modifier_body, Some((modifiers, index + 1, body)), entry);
178        self.call_stack.pop();
179        exits
180    }
181
182    /// Analyzes one loop iteration: the body, then the `for` update on the paths that complete it.
183    fn analyze_iteration(
184        &mut self,
185        block: Block<'gcx>,
186        source: LoopSource<'gcx>,
187        placeholder: Placeholder<'gcx>,
188        entry: bool,
189    ) -> Exits {
190        let mut exits = self.analyze_block(block, placeholder, entry);
191        if let (Some(update), Some(state)) = (loop_update(source), exits.fallthrough.take()) {
192            exits.merge(self.analyze_stmt(update, placeholder, state));
193        }
194        exits
195    }
196
197    fn analyze_block(
198        &mut self,
199        block: Block<'gcx>,
200        placeholder: Placeholder<'gcx>,
201        mut entry: bool,
202    ) -> Exits {
203        let mut exits = Exits::default();
204        for stmt in block.stmts {
205            let stmt_exits = self.analyze_stmt(stmt, placeholder, entry);
206            exits.merge(Exits { fallthrough: None, ..stmt_exits });
207            // Only the fallthrough state reaches the next statement; without it the rest is dead.
208            let Some(next) = stmt_exits.fallthrough else { return exits };
209            entry = next;
210        }
211        exits.fallthrough = Some(entry);
212        exits
213    }
214
215    fn analyze_stmt(
216        &mut self,
217        stmt: &'gcx Stmt<'gcx>,
218        placeholder: Placeholder<'gcx>,
219        mut entry: bool,
220    ) -> Exits {
221        self.expr_aborted = false;
222        match stmt.kind {
223            StmtKind::DeclSingle(var_id) => {
224                if let Some(init) = self.gcx.hir.variable(var_id).initializer {
225                    self.analyze_expr(init, &mut entry);
226                }
227                self.unless_aborted(Exits::fallthrough(entry))
228            }
229            StmtKind::DeclMulti(_, expr) | StmtKind::Expr(expr) => {
230                self.analyze_expr(expr, &mut entry);
231                if is_exit_call(self.gcx, expr) {
232                    return Exits::default();
233                }
234                self.unless_aborted(Exits::fallthrough(entry))
235            }
236            StmtKind::Block(block) | StmtKind::UncheckedBlock(block) => {
237                self.analyze_block(block, placeholder, entry)
238            }
239            StmtKind::Emit(expr) => {
240                // Event arguments are evaluated before emitting, so an external call in them
241                // taints this emit too, and an aborting argument makes it unreachable.
242                self.analyze_expr(expr, &mut entry);
243                if self.expr_aborted {
244                    return Exits::default();
245                }
246                if entry && !self.suppress_inline_reports && self.emitted.insert(stmt.span) {
247                    self.ctx.emit(&REENTRANCY_EVENTS, stmt.span);
248                }
249                Exits::fallthrough(entry)
250            }
251            StmtKind::Revert(expr) => {
252                self.analyze_expr(expr, &mut entry);
253                Exits::default()
254            }
255            StmtKind::Return(expr) => {
256                if let Some(expr) = expr {
257                    self.analyze_expr(expr, &mut entry);
258                }
259                self.unless_aborted(Exits::return_(entry))
260            }
261            StmtKind::Break => Exits::break_(entry),
262            StmtKind::Continue => Exits::continue_(entry),
263            StmtKind::Loop(block, source) => {
264                // Two passes suffice: the one-bit state can only go from clean to tainted around
265                // the back-edge, so a second pass from the merged entry catches emits tainted
266                // only on later iterations. `emitted` dedupes the diagnostics.
267                let first = self.analyze_iteration(block, source, placeholder, entry);
268                let back_edge =
269                    entry || first.fallthrough.unwrap_or(false) || first.continue_.unwrap_or(false);
270                let body = if back_edge == entry {
271                    first
272                } else {
273                    self.analyze_iteration(block, source, placeholder, back_edge)
274                };
275                // Zero iterations, the end of the body, `break` and `continue` all reach the exit.
276                let post = entry
277                    || body.fallthrough.unwrap_or(false)
278                    || body.break_.unwrap_or(false)
279                    || body.continue_.unwrap_or(false);
280                Exits { fallthrough: Some(post), return_: body.return_, ..Exits::default() }
281            }
282            StmtKind::If(cond, then_stmt, else_stmt) => {
283                self.analyze_expr(cond, &mut entry);
284                if self.expr_aborted {
285                    return Exits::default();
286                }
287                let mut exits = self.analyze_stmt(then_stmt, placeholder, entry);
288                exits.merge(match else_stmt {
289                    Some(else_stmt) => self.analyze_stmt(else_stmt, placeholder, entry),
290                    None => Exits::fallthrough(entry),
291                });
292                exits
293            }
294            StmtKind::Try(try_stmt) => {
295                self.analyze_expr(&try_stmt.expr, &mut entry);
296                if self.expr_aborted {
297                    return Exits::default();
298                }
299                let mut exits = Exits::default();
300                for clause in try_stmt.clauses {
301                    exits.merge(self.analyze_block(clause.block, placeholder, entry));
302                }
303                exits
304            }
305            StmtKind::Placeholder => match placeholder {
306                Some((modifiers, index, body)) => {
307                    self.analyze_modifier_chain(modifiers, index, body, entry)
308                }
309                None => Exits::fallthrough(entry),
310            },
311            // Inline assembly taints only if it can reach a mutating Yul call or a creation.
312            StmtKind::AssemblyBlock(..) | StmtKind::Switch(_) => Exits::fallthrough(
313                entry || self.stmt_may_reach_external_call(stmt, &mut HashSet::new()),
314            ),
315            StmtKind::Err(_) => Exits::fallthrough(true),
316        }
317    }
318
319    fn unless_aborted(&self, exits: Exits) -> Exits {
320        if self.expr_aborted { Exits::default() } else { exits }
321    }
322
323    fn analyze_expr(&mut self, expr: &'gcx Expr<'gcx>, tainted: &mut bool) {
324        match &expr.kind {
325            ExprKind::Call(callee, ..) => {
326                for_each_child(expr, &mut |child| self.analyze_expr(child, tainted));
327                if is_state_mutating_external_call(self.gcx, callee) {
328                    *tainted = true;
329                }
330                // Follow internal helpers and `super` dispatch so their external calls taint the
331                // caller too.
332                for func_id in self.callees(callee) {
333                    self.analyze_internal_call(func_id, tainted);
334                }
335            }
336            ExprKind::Binary(lhs, op, rhs) if matches!(op.kind, BinOpKind::And | BinOpKind::Or) => {
337                // The RHS is conditional: model it on a fork so its taint joins the result next
338                // to the short-circuit path, and an aborting RHS only drops the non-short-circuit
339                // path.
340                self.analyze_expr(lhs, tainted);
341                let lhs_aborted = std::mem::replace(&mut self.expr_aborted, false);
342                let mut rhs_tainted = *tainted;
343                self.analyze_expr(rhs, &mut rhs_tainted);
344                let rhs_aborted = self.expr_aborted;
345                self.expr_aborted = lhs_aborted;
346                if !lhs_aborted && !rhs_aborted {
347                    *tainted |= rhs_tainted;
348                }
349            }
350            ExprKind::Ternary(cond, then_expr, else_expr) => {
351                self.analyze_expr(cond, tainted);
352                let cond_aborted = std::mem::replace(&mut self.expr_aborted, false);
353                let mut then_tainted = *tainted;
354                self.analyze_expr(then_expr, &mut then_tainted);
355                let then_aborted = std::mem::replace(&mut self.expr_aborted, false);
356                let mut else_tainted = *tainted;
357                self.analyze_expr(else_expr, &mut else_tainted);
358                let else_aborted = self.expr_aborted;
359                // The ternary aborts iff the condition does or both branches do; aborting
360                // branches drop their state.
361                self.expr_aborted = cond_aborted || (then_aborted && else_aborted);
362                if !(then_aborted && else_aborted) {
363                    *tainted = (!then_aborted && then_tainted) || (!else_aborted && else_tainted);
364                }
365            }
366            _ => for_each_child(expr, &mut |child| self.analyze_expr(child, tainted)),
367        }
368    }
369
370    /// Internal functions and `super` targets a call through `callee` dispatches to.
371    fn callees(&self, callee: &'gcx Expr<'gcx>) -> Vec<FunctionId> {
372        self.enclosing_contract
373            .map_or_else(
374                || self.gcx.resolved_function(callee),
375                |contract| dispatched_function(self.gcx, contract, callee),
376            )
377            .into_iter()
378            .collect()
379    }
380
381    fn analyze_internal_call(&mut self, func_id: FunctionId, tainted: &mut bool) {
382        if self.call_stack.contains(&func_id) {
383            // Replace the cut recursive edge with the conservative "can this helper ever call
384            // out?" summary so inline summaries stay stack-insensitive.
385            *tainted |= self.helper_may_reach_external_call(func_id, &mut HashSet::new());
386            return;
387        }
388        let func = self.gcx.hir.function(func_id);
389        let Some(body) = func.body else { return };
390
391        // Diagnostics inside a helper entered clean are left to the helper's own pass, which
392        // avoids duplicate reports across callers.
393        let suppress = self.suppress_inline_reports || !*tainted;
394        let key = InlineCallKey {
395            func_id,
396            external_call_seen: *tainted,
397            suppress_inline_reports: suppress,
398        };
399        if self.inline_cache.is_in_progress(&key) {
400            return;
401        }
402        let summary = match self.inline_cache.get(&key) {
403            Some(summary) => *summary,
404            None => {
405                let prev_suppress = std::mem::replace(&mut self.suppress_inline_reports, suppress);
406                self.inline_cache.start(key);
407                self.call_stack.push(func_id);
408                let summary = self.analyze_callable(func, body, *tainted);
409                self.call_stack.pop();
410                self.inline_cache.finish(key, summary);
411                self.suppress_inline_reports = prev_suppress;
412                summary
413            }
414        };
415        // The caller continues in the state of the normally returning paths; a callee without
416        // any aborts the enclosing statement.
417        match summary.normal() {
418            Some(after) => *tainted = after,
419            None => self.expr_aborted = true,
420        }
421    }
422
423    /// Conservative summary of whether `func_id` can ever perform an external call.
424    fn helper_may_reach_external_call(
425        &mut self,
426        func_id: FunctionId,
427        seen: &mut HashSet<FunctionId>,
428    ) -> bool {
429        if let Some(&cached) = self.external_call_reachability.get(&func_id) {
430            return cached;
431        }
432        if !seen.insert(func_id) {
433            self.reachability_cut = true;
434            return false;
435        }
436        let outer_cut = std::mem::replace(&mut self.reachability_cut, false);
437        let func = self.gcx.hir.function(func_id);
438        let may_reach = func.modifiers.iter().any(|modifier| {
439            modifier.args.exprs().any(|arg| self.expr_may_reach_external_call(arg, seen))
440                || modifier
441                    .id
442                    .as_function()
443                    .is_some_and(|id| self.helper_may_reach_external_call(id, seen))
444        }) || func.body.is_some_and(|body| {
445            body.stmts.iter().any(|stmt| self.stmt_may_reach_external_call(stmt, seen))
446        });
447        // `func_id` stays in `seen` for the rest of the query: a revisit cannot find a new call,
448        // and removing it lets recursive helpers enumerate every simple path.
449        // A negative answer that relied on a cut recursive edge is not conclusive.
450        if may_reach || !self.reachability_cut {
451            self.external_call_reachability.insert(func_id, may_reach);
452        }
453        self.reachability_cut |= outer_cut;
454        may_reach
455    }
456
457    fn stmt_may_reach_external_call(
458        &mut self,
459        stmt: &'gcx Stmt<'gcx>,
460        seen: &mut HashSet<FunctionId>,
461    ) -> bool {
462        match stmt.kind {
463            StmtKind::DeclSingle(var_id) => self
464                .gcx
465                .hir
466                .variable(var_id)
467                .initializer
468                .is_some_and(|init| self.expr_may_reach_external_call(init, seen)),
469            StmtKind::DeclMulti(_, expr)
470            | StmtKind::Expr(expr)
471            | StmtKind::Emit(expr)
472            | StmtKind::Revert(expr) => self.expr_may_reach_external_call(expr, seen),
473            StmtKind::Return(expr) => {
474                expr.is_some_and(|expr| self.expr_may_reach_external_call(expr, seen))
475            }
476            StmtKind::Block(block)
477            | StmtKind::UncheckedBlock(block)
478            | StmtKind::AssemblyBlock(block, _) => {
479                block.stmts.iter().any(|stmt| self.stmt_may_reach_external_call(stmt, seen))
480            }
481            StmtKind::Loop(block, source) => {
482                loop_stmts(block, source).any(|stmt| self.stmt_may_reach_external_call(stmt, seen))
483            }
484            StmtKind::Switch(switch) => {
485                self.expr_may_reach_external_call(switch.selector, seen)
486                    || switch.cases.iter().any(|case| {
487                        case.body
488                            .stmts
489                            .iter()
490                            .any(|stmt| self.stmt_may_reach_external_call(stmt, seen))
491                    })
492            }
493            StmtKind::If(cond, then_stmt, else_stmt) => {
494                self.expr_may_reach_external_call(cond, seen)
495                    || self.stmt_may_reach_external_call(then_stmt, seen)
496                    || else_stmt.is_some_and(|stmt| self.stmt_may_reach_external_call(stmt, seen))
497            }
498            StmtKind::Try(try_stmt) => {
499                self.expr_may_reach_external_call(&try_stmt.expr, seen)
500                    || try_stmt.clauses.iter().any(|clause| {
501                        clause
502                            .block
503                            .stmts
504                            .iter()
505                            .any(|stmt| self.stmt_may_reach_external_call(stmt, seen))
506                    })
507            }
508            StmtKind::Break | StmtKind::Continue | StmtKind::Placeholder | StmtKind::Err(_) => {
509                false
510            }
511        }
512    }
513
514    fn expr_may_reach_external_call(
515        &mut self,
516        expr: &'gcx Expr<'gcx>,
517        seen: &mut HashSet<FunctionId>,
518    ) -> bool {
519        let mut reached = false;
520        for_each_child(expr, &mut |child| {
521            reached = reached || self.expr_may_reach_external_call(child, seen);
522        });
523        if reached {
524            return true;
525        }
526        let ExprKind::Call(callee, ..) = &expr.kind else { return false };
527        // Yul `staticcall` is excluded like other static calls.
528        let yul_interaction = matches!(
529            self.gcx.resolved_builtin(callee),
530            Some(
531                Builtin::YulCall
532                    | Builtin::YulCallcode
533                    | Builtin::YulDelegatecall
534                    | Builtin::YulCreate
535                    | Builtin::YulCreate2
536            )
537        );
538        yul_interaction
539            || is_state_mutating_external_call(self.gcx, callee)
540            || self
541                .callees(callee)
542                .into_iter()
543                .any(|id| self.helper_may_reach_external_call(id, seen))
544    }
545}