Skip to main content

forge_lint/sol/high/
reentrancy.rs

1use super::ReentrancyEth;
2use crate::{
3    linter::{LateLintPass, LintContext},
4    sol::{
5        Severity, SolLint,
6        analysis::{
7            DEFAULT_HELPER_ANALYSIS_CACHE_LIMIT, HelperAnalysisCache, arg_for_param,
8            branch_always_exits, cast_type, count_placeholders, expr_is_address, for_each_child,
9            for_each_lhs_var, is_address_cast, is_builtin, is_require_or_assert, lhs_local_var,
10            loop_update, state_lhs_vars, stmts_before_placeholder, tuple_elems,
11        },
12    },
13};
14use alloy_primitives::U256;
15use solar::{
16    ast::{BinOpKind, FunctionKind, LitKind, StateMutability, UnOpKind, Visibility},
17    interface::{Span, Symbol, data_structures::Never, kw, sym},
18    sema::{
19        Gcx,
20        builtins::Builtin,
21        hir::{
22            self, CallArgs, CallOptions, Expr, ExprKind, FunctionId, ItemId, LoopSource, Stmt,
23            StmtKind, VariableId, Visit,
24        },
25        ty::{TyFnKind, TyKind},
26    },
27};
28use std::{
29    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
30    ops::ControlFlow,
31};
32
33/// Gas stipend forwarded by `transfer`/`send`; a call capped at or below it cannot reenter.
34const REENTRANCY_GAS_STIPEND: u64 = 2_300;
35
36declare_forge_lint!(
37    REENTRANCY_BALANCE,
38    Severity::High,
39    "reentrancy-balance",
40    "external call can be reentered before a stale contract balance is checked"
41);
42
43declare_forge_lint!(
44    REENTRANCY_ETH,
45    Severity::High,
46    "reentrancy-eth",
47    "state read before ETH transfer is written after the transfer"
48);
49
50declare_forge_lint!(
51    REENTRANCY_NO_ETH,
52    Severity::Med,
53    "reentrancy-no-eth",
54    "state read before external call is written after the call"
55);
56
57impl<'gcx> LateLintPass<'gcx> for ReentrancyEth {
58    fn check_function(
59        &mut self,
60        ctx: &LintContext,
61        gcx: Gcx<'gcx>,
62        func: &'gcx hir::Function<'gcx>,
63    ) {
64        let Some(body) = func.body.filter(|_| is_entry_point(func)) else { return };
65        let mut analyzer = Analyzer::new(ctx, gcx, func);
66        if analyzer.has_enabled_lints() {
67            analyzer.analyze_callable(func, body, &mut FlowState::default());
68        }
69    }
70}
71
72/// Non-view functions an external caller can invoke: public/external functions, `fallback` and
73/// `receive`.
74fn is_entry_point(func: &hir::Function<'_>) -> bool {
75    !is_view_or_pure(func.state_mutability)
76        && !func.is_constructor()
77        && (func.is_special()
78            || (func.kind.is_function()
79                && matches!(func.visibility, Visibility::Public | Visibility::External)))
80}
81
82const fn is_view_or_pure(mutability: StateMutability) -> bool {
83    matches!(mutability, StateMutability::Pure | StateMutability::View)
84}
85
86type PathPredicates = BTreeMap<PathPredicate, bool>;
87type PathAlternatives = BTreeSet<PathPredicates>;
88
89/// Facts that hold along one execution path.
90#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
91struct FlowState {
92    /// State variables read so far.
93    state_reads: BTreeSet<VariableId>,
94    /// Reentrant calls made after a state read, with the state read before each, awaiting a
95    /// later write to that state.
96    pending_calls: BTreeMap<(Span, ReentrantCallKind), BTreeSet<VariableId>>,
97    /// Internal functions a function-typed local may point to.
98    internal_function_targets: BTreeMap<VariableId, BTreeSet<FunctionId>>,
99    /// Locals holding `address(this)`, with the path predicates under which they do.
100    self_address_local_paths: BTreeMap<VariableId, PathAlternatives>,
101    /// Locals derived from `address(this).balance`, with the predicates under which they are.
102    balance_local_paths: BTreeMap<VariableId, PathAlternatives>,
103    /// Supported arithmetic forms of local values; an empty set means unknown.
104    balance_local_forms: BTreeMap<VariableId, BTreeSet<BalanceForm>>,
105    /// Balance occurrences retained through arbitrary arithmetic on local values.
106    balance_local_dependencies: BTreeMap<VariableId, BTreeSet<BalanceForm>>,
107    /// Locals holding a comparison against a balance made stale by the given calls.
108    balance_comparison_locals: BTreeMap<VariableId, BTreeSet<Span>>,
109    /// External calls after which cached balance locals are stale.
110    pending_balance_calls: BTreeMap<Span, PathAlternatives>,
111    /// Reentrancy-guard locks written or bypassed while active.
112    invalidated_balance_guards: BTreeSet<VariableId>,
113    /// Boolean facts known to hold on this path.
114    path_predicates: PathPredicates,
115}
116
117#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
118enum PathPredicate {
119    Boolean(VariableId),
120    Equality(Operand, Operand),
121}
122
123impl PathPredicate {
124    fn mentions(self, f: impl Fn(VariableId) -> bool) -> bool {
125        match self {
126            Self::Boolean(var_id) => f(var_id),
127            Self::Equality(lhs, rhs) => {
128                [lhs, rhs].into_iter().any(|op| matches!(op, Operand::Variable(v) if f(v)))
129            }
130        }
131    }
132}
133
134/// A local variable or constant appearing in a predicate or lock expression.
135#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
136enum Operand {
137    Variable(VariableId),
138    Number(U256),
139    Boolean(bool),
140}
141
142#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
143enum ReentrantCallKind {
144    Eth,
145    NoEth,
146}
147
148/// One signed balance read, retaining the calls across which it was cached.
149#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
150struct BalanceTerm {
151    negative: bool,
152    stale_calls: BTreeSet<Span>,
153}
154
155/// A supported additive source pattern on one path. An empty term list is balance-independent.
156/// At most two balance terms are retained: a stale/current comparison needs one of each. More
157/// terms are rejected rather than cancelled, since Solidity arithmetic may wrap or revert.
158#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
159struct BalanceForm {
160    terms: Vec<BalanceTerm>,
161    path: PathPredicates,
162}
163
164impl BalanceForm {
165    fn combine(&self, rhs: &Self, subtract: bool) -> Option<Self> {
166        if self.terms.len() + rhs.terms.len() > 2 || !paths_compatible(&self.path, &rhs.path) {
167            return None;
168        }
169        let mut terms = self.terms.clone();
170        terms.extend(rhs.terms.iter().cloned().map(|mut term| {
171            term.negative ^= subtract;
172            term
173        }));
174        Some(Self {
175            terms,
176            path: self.path.iter().chain(&rhs.path).map(|(p, v)| (*p, *v)).collect(),
177        })
178    }
179
180    fn constrained(&self, active: &PathPredicates) -> Option<Self> {
181        paths_compatible(&self.path, active).then(|| Self {
182            terms: self.terms.clone(),
183            path: self.path.iter().chain(active).map(|(p, v)| (*p, *v)).collect(),
184        })
185    }
186}
187
188/// Balance-related facts about a value flowing into a local, parameter or return slot.
189#[derive(Clone, Debug, Default)]
190struct BalanceValue {
191    /// Supported arithmetic forms, separate from occurrence-based dependencies.
192    forms: BTreeSet<BalanceForm>,
193    /// Individual balance occurrences, without arithmetic signs or identities.
194    dependencies: BTreeSet<BalanceForm>,
195    /// Predicates under which the value derives from `address(this).balance`.
196    balance_paths: PathAlternatives,
197    /// Predicates under which the value is `address(this)`.
198    self_address_paths: PathAlternatives,
199    /// Calls whose stale balance the value compares against.
200    stale_comparisons: BTreeSet<Span>,
201}
202
203impl BalanceValue {
204    fn merge(&mut self, other: Self) {
205        self.forms.extend(other.forms);
206        self.dependencies.extend(other.dependencies);
207        self.balance_paths.extend(other.balance_paths);
208        self.self_address_paths.extend(other.self_address_paths);
209        self.stale_comparisons.extend(other.stale_comparisons);
210    }
211
212    /// The same value seen from a path on which `predicates` hold.
213    fn constrained(&self, predicates: &PathPredicates) -> Self {
214        Self {
215            forms: self.forms.iter().filter_map(|form| form.constrained(predicates)).collect(),
216            dependencies: self
217                .dependencies
218                .iter()
219                .filter_map(|form| form.constrained(predicates))
220                .collect(),
221            balance_paths: constrain_paths(&self.balance_paths, predicates),
222            self_address_paths: constrain_paths(&self.self_address_paths, predicates),
223            ..self.clone()
224        }
225    }
226}
227
228impl FlowState {
229    fn push_call(&mut self, span: Span, kind: ReentrantCallKind) {
230        if !self.state_reads.is_empty() {
231            self.pending_calls.entry((span, kind)).or_default().extend(&self.state_reads);
232        }
233    }
234
235    fn push_balance_call(&mut self, span: Span) {
236        if self
237            .balance_local_paths
238            .values()
239            .any(|paths| paths.iter().any(|path| paths_compatible(path, &self.path_predicates)))
240        {
241            self.pending_balance_calls
242                .entry(span)
243                .or_default()
244                .insert(self.path_predicates.clone());
245            for forms in self
246                .balance_local_forms
247                .values_mut()
248                .chain(self.balance_local_dependencies.values_mut())
249            {
250                *forms = std::mem::take(forms)
251                    .into_iter()
252                    .map(|mut form| {
253                        if paths_compatible(&form.path, &self.path_predicates) {
254                            for term in &mut form.terms {
255                                term.stale_calls.insert(span);
256                            }
257                        }
258                        form
259                    })
260                    .collect();
261            }
262        }
263    }
264
265    fn merge(&mut self, other: &Self) {
266        self.state_reads.extend(&other.state_reads);
267        merge_maps(&mut self.pending_calls, &other.pending_calls);
268        self.merge_balance(other);
269    }
270
271    fn merge_balance(&mut self, other: &Self) {
272        merge_maps(&mut self.internal_function_targets, &other.internal_function_targets);
273        merge_maps(&mut self.self_address_local_paths, &other.self_address_local_paths);
274        merge_maps(&mut self.balance_local_paths, &other.balance_local_paths);
275        merge_maps(&mut self.balance_local_forms, &other.balance_local_forms);
276        merge_maps(&mut self.balance_local_dependencies, &other.balance_local_dependencies);
277        merge_maps(&mut self.balance_comparison_locals, &other.balance_comparison_locals);
278        self.invalidated_balance_guards.extend(&other.invalidated_balance_guards);
279        merge_maps(&mut self.pending_balance_calls, &other.pending_balance_calls);
280    }
281
282    fn balance_only(&self) -> Self {
283        Self { state_reads: BTreeSet::new(), pending_calls: BTreeMap::new(), ..self.clone() }
284    }
285
286    /// Records that `predicate` holds; returns `false` if that contradicts a known fact.
287    fn constrain_path(&mut self, (predicate, value): (PathPredicate, bool)) -> bool {
288        match self.path_predicates.get(&predicate) {
289            Some(existing) => *existing == value,
290            None => {
291                self.path_predicates.insert(predicate, value);
292                for paths in self.self_address_local_paths.values_mut() {
293                    *paths = constrain_paths(paths, &self.path_predicates);
294                }
295                true
296            }
297        }
298    }
299}
300
301fn merge_maps<K: Copy + Ord, V: Clone + Ord>(
302    into: &mut BTreeMap<K, BTreeSet<V>>,
303    from: &BTreeMap<K, BTreeSet<V>>,
304) {
305    for (key, values) in from {
306        into.entry(*key).or_default().extend(values.iter().cloned());
307    }
308}
309
310/// Replaces `state` with the union of the reachable `branches`, keeping only the path predicates
311/// all of them agree on. Returns whether any branch was reachable.
312fn join_branches(
313    state: &mut FlowState,
314    branches: impl IntoIterator<Item = Option<FlowState>>,
315) -> bool {
316    *state = FlowState::default();
317    let mut predicates = None;
318    for branch in branches.into_iter().flatten() {
319        state.merge(&branch);
320        predicates = Some(match predicates {
321            Some(common) => common_path_predicates(&common, &branch.path_predicates),
322            None => branch.path_predicates,
323        });
324    }
325    let reachable = predicates.is_some();
326    state.path_predicates = predicates.unwrap_or_default();
327    reachable
328}
329
330struct Analyzer<'ctx, 's, 'c, 'gcx> {
331    ctx: &'ctx LintContext<'s, 'c>,
332    gcx: Gcx<'gcx>,
333    emitted: HashSet<Span>,
334    emitted_balance: HashSet<Span>,
335    call_stack: Vec<FunctionId>,
336    inline_cache: HelperAnalysisCache<InlineCallKey, (FlowState, Vec<BalanceValue>)>,
337    /// First function on the given call stack reachable again from a callee, per callee.
338    recursive_cuts: HashMap<(FunctionId, BTreeSet<FunctionId>), Option<FunctionId>>,
339    direct_internal_calls: HashMap<FunctionId, Vec<FunctionId>>,
340    reentrancy_eth_enabled: bool,
341    reentrancy_no_eth_enabled: bool,
342    reentrancy_balance_enabled: bool,
343    /// Prunes branches that path predicates rule out; tied to the lint config so the ETH lints
344    /// report the same whether or not an entry point reads a balance.
345    prune_paths: bool,
346    /// Set while re-running code only to refine the balance analysis.
347    balance_only_analysis: bool,
348    /// Balance facts about the return values of each analysed internal call site.
349    call_balance_values: HashMap<Span, Vec<BalanceValue>>,
350    /// Return-value accumulators of the internal calls currently being inlined.
351    return_collectors: Vec<(FunctionId, Vec<BalanceValue>)>,
352    /// Reentrancy-guard locks held by the modifiers wrapping the code being analysed.
353    active_balance_guards: Vec<VariableId>,
354    /// The lock guarding every entry point of each deployable contract, if any.
355    balance_reentry_lock: Option<VariableId>,
356}
357
358#[derive(Clone, Debug, PartialEq, Eq, Hash)]
359struct InlineCallKey {
360    func_id: FunctionId,
361    /// First active function that can cut recursion from this callee.
362    recursive_cut: Option<FunctionId>,
363    balance_only: bool,
364    active_balance_guards: Vec<VariableId>,
365    parameter_predicates: Vec<Option<(PathPredicate, bool)>>,
366    state: FlowState,
367}
368
369/// What to analyse when a modifier's `_` is reached: the remaining modifiers, the function body
370/// and the reentrancy-guard lock the current modifier holds.
371type ModifierContinuation<'gcx> =
372    (&'gcx [hir::Modifier<'gcx>], usize, hir::Block<'gcx>, Option<VariableId>);
373
374impl<'ctx, 's, 'c, 'gcx> Analyzer<'ctx, 's, 'c, 'gcx> {
375    fn new(
376        ctx: &'ctx LintContext<'s, 'c>,
377        gcx: Gcx<'gcx>,
378        entry: &'gcx hir::Function<'gcx>,
379    ) -> Self {
380        let prune_paths = ctx.is_lint_enabled(REENTRANCY_BALANCE.id);
381        let reentrancy_balance_enabled = prune_paths && reaches_balance_read(gcx, entry);
382        Self {
383            ctx,
384            gcx,
385            emitted: HashSet::new(),
386            emitted_balance: HashSet::new(),
387            call_stack: Vec::new(),
388            inline_cache: HelperAnalysisCache::new(DEFAULT_HELPER_ANALYSIS_CACHE_LIMIT),
389            recursive_cuts: HashMap::new(),
390            direct_internal_calls: HashMap::new(),
391            reentrancy_eth_enabled: ctx.is_lint_enabled(REENTRANCY_ETH.id),
392            reentrancy_no_eth_enabled: ctx.is_lint_enabled(REENTRANCY_NO_ETH.id),
393            reentrancy_balance_enabled,
394            prune_paths,
395            balance_only_analysis: false,
396            call_balance_values: HashMap::new(),
397            return_collectors: Vec::new(),
398            active_balance_guards: Vec::new(),
399            balance_reentry_lock: reentrancy_balance_enabled
400                .then(|| balance_reentry_lock(gcx, entry))
401                .flatten(),
402        }
403    }
404
405    const fn has_enabled_lints(&self) -> bool {
406        self.reentrancy_eth_enabled
407            || self.reentrancy_no_eth_enabled
408            || self.reentrancy_balance_enabled
409    }
410
411    /// Analyses `func` (modifiers first, then `body`); returns whether it can fall through.
412    fn analyze_callable(
413        &mut self,
414        func: &'gcx hir::Function<'gcx>,
415        body: hir::Block<'gcx>,
416        state: &mut FlowState,
417    ) -> bool {
418        self.analyze_modifier_chain(func.modifiers, 0, body, state)
419    }
420
421    fn analyze_modifier_chain(
422        &mut self,
423        modifiers: &'gcx [hir::Modifier<'gcx>],
424        index: usize,
425        body: hir::Block<'gcx>,
426        state: &mut FlowState,
427    ) -> bool {
428        let Some(modifier) = modifiers.get(index) else {
429            return self.analyze_block(body, None, state);
430        };
431        for arg in modifier.args.exprs() {
432            self.analyze_expr(arg, state);
433        }
434        let Some((modifier_id, modifier_func, modifier_body)) = modifier
435            .id
436            .as_function()
437            .filter(|id| !self.call_stack.contains(id))
438            .map(|id| (id, self.gcx.hir.function(id)))
439            .and_then(|(id, func)| Some((id, func, func.body?)))
440        else {
441            return self.analyze_modifier_chain(modifiers, index + 1, body, state);
442        };
443
444        self.seed_balance_parameters(modifier_id, &modifier.args, state);
445        self.call_stack.push(modifier_id);
446        let balance_guard = self
447            .reentrancy_balance_enabled
448            .then(|| standard_reentrancy_guard_lock(self.gcx, modifier_func))
449            .flatten();
450        let continuation = Some((modifiers, index + 1, body, balance_guard));
451        let falls_through = self.analyze_block(modifier_body, continuation, state);
452        self.call_stack.pop();
453        self.clear_function_locals(modifier_id, state);
454        falls_through
455    }
456
457    /// Analyzes one loop iteration: the body, then the `for` update if the body completes.
458    fn analyze_iteration(
459        &mut self,
460        block: hir::Block<'gcx>,
461        source: LoopSource<'gcx>,
462        placeholder: Option<ModifierContinuation<'gcx>>,
463        state: &mut FlowState,
464    ) -> bool {
465        self.analyze_block(block, placeholder, state)
466            && loop_update(source)
467                .is_none_or(|update| self.analyze_stmt(update, placeholder, state))
468    }
469
470    fn analyze_block(
471        &mut self,
472        block: hir::Block<'gcx>,
473        placeholder: Option<ModifierContinuation<'gcx>>,
474        state: &mut FlowState,
475    ) -> bool {
476        block.stmts.iter().all(|stmt| self.analyze_stmt(stmt, placeholder, state))
477    }
478
479    /// Analyses `stmt`; returns whether control can continue past it.
480    fn analyze_stmt(
481        &mut self,
482        stmt: &'gcx Stmt<'gcx>,
483        placeholder: Option<ModifierContinuation<'gcx>>,
484        state: &mut FlowState,
485    ) -> bool {
486        match stmt.kind {
487            StmtKind::DeclSingle(var_id) => {
488                if let Some(init) = self.gcx.hir.variable(var_id).initializer {
489                    self.analyze_expr(init, state);
490                    self.update_internal_function_target(state, var_id, init);
491                    if self.reentrancy_balance_enabled {
492                        self.bind_locals(state, &[Some(var_id)], init, None);
493                    }
494                } else if self.reentrancy_balance_enabled {
495                    self.set_self_address_paths(state, var_id, PathAlternatives::new());
496                }
497                true
498            }
499            StmtKind::DeclMulti(vars, expr) => {
500                self.analyze_expr(expr, state);
501                if self.reentrancy_balance_enabled {
502                    self.bind_locals(state, vars, expr, None);
503                }
504                true
505            }
506            StmtKind::Expr(expr) | StmtKind::Emit(expr) => {
507                self.analyze_expr(expr, state);
508                true
509            }
510            StmtKind::Revert(expr) => {
511                self.analyze_expr(expr, state);
512                false
513            }
514            StmtKind::Block(block) | StmtKind::UncheckedBlock(block) => {
515                self.analyze_block(block, placeholder, state)
516            }
517            StmtKind::Return(expr) => {
518                if let Some(expr) = expr {
519                    self.analyze_expr(expr, state);
520                }
521                if self.reentrancy_balance_enabled {
522                    self.record_return(expr, state);
523                }
524                false
525            }
526            StmtKind::Break | StmtKind::Continue => false,
527            StmtKind::Loop(block, source) => {
528                let before_loop = state.clone();
529                let mut body_state = state.clone();
530                self.analyze_iteration(block, source, placeholder, &mut body_state);
531                // One bounded second iteration exposes loop-carried balance checks while leaving
532                // the established ETH and no-ETH analysis unchanged.
533                let second_iteration = self.reentrancy_balance_enabled.then(|| {
534                    let mut second = body_state.balance_only();
535                    self.analyze_with_only_balance(|this| {
536                        this.analyze_iteration(block, source, placeholder, &mut second)
537                    });
538                    second
539                });
540                join_branches(state, [Some(before_loop), Some(body_state)]);
541                if let Some(second) = second_iteration {
542                    state.path_predicates =
543                        common_path_predicates(&state.path_predicates, &second.path_predicates);
544                    state.merge_balance(&second);
545                }
546                true
547            }
548            StmtKind::If(cond, then_stmt, else_stmt) => {
549                self.analyze_expr(cond, state);
550                if self.reentrancy_balance_enabled
551                    && (branch_stops_current_path(self.gcx, then_stmt)
552                        || else_stmt.is_some_and(|expr| branch_stops_current_path(self.gcx, expr)))
553                {
554                    self.emit_balance_calls(cond, state);
555                }
556                let (mut then_state, mut else_state) = (state.clone(), state.clone());
557                let (then_reachable, else_reachable) =
558                    self.split_on(cond, &mut then_state, &mut else_state);
559                let then_falls_through =
560                    then_reachable && self.analyze_stmt(then_stmt, placeholder, &mut then_state);
561                let else_falls_through = else_reachable
562                    && else_stmt.is_none_or(|e| self.analyze_stmt(e, placeholder, &mut else_state));
563                join_branches(
564                    state,
565                    [
566                        then_falls_through.then_some(then_state),
567                        else_falls_through.then_some(else_state),
568                    ],
569                )
570            }
571            StmtKind::Try(try_stmt) => {
572                self.analyze_expr(&try_stmt.expr, state);
573                let clauses = try_stmt
574                    .clauses
575                    .iter()
576                    .map(|clause| {
577                        let mut clause_state = state.clone();
578                        self.analyze_block(clause.block, placeholder, &mut clause_state)
579                            .then_some(clause_state)
580                    })
581                    .collect::<Vec<_>>();
582                join_branches(state, clauses)
583            }
584            StmtKind::Placeholder => {
585                let Some((modifiers, index, body, balance_guard)) = placeholder else {
586                    return true;
587                };
588                if let Some(lock_var) = balance_guard {
589                    state.invalidated_balance_guards.remove(&lock_var);
590                    self.active_balance_guards.push(lock_var);
591                }
592                let falls_through = self.analyze_modifier_chain(modifiers, index, body, state);
593                if balance_guard.is_some() {
594                    self.active_balance_guards.pop();
595                }
596                falls_through
597            }
598            StmtKind::AssemblyBlock(..) | StmtKind::Switch(_) => {
599                state.invalidated_balance_guards.extend(&self.active_balance_guards);
600                state.internal_function_targets.clear();
601                state.self_address_local_paths.clear();
602                true
603            }
604            StmtKind::Err(_) => true,
605        }
606    }
607
608    /// Constrains the branch states of a conditional on `cond`; returns whether each is reachable.
609    fn split_on(
610        &self,
611        cond: &'gcx Expr<'gcx>,
612        then_state: &mut FlowState,
613        else_state: &mut FlowState,
614    ) -> (bool, bool) {
615        let predicate = self.prune_paths.then(|| path_predicate(self.gcx, cond)).flatten();
616        let Some((predicate, value)) = predicate else { return (true, true) };
617        (
618            then_state.constrain_path((predicate, value)),
619            else_state.constrain_path((predicate, !value)),
620        )
621    }
622
623    fn analyze_expr(&mut self, expr: &'gcx Expr<'gcx>, state: &mut FlowState) {
624        match &expr.kind {
625            ExprKind::Assign(lhs, op, rhs) => {
626                if op.is_some() {
627                    self.analyze_expr(lhs, state);
628                }
629                self.analyze_expr(rhs, state);
630                self.analyze_lhs_indices(lhs, state);
631                self.record_write(lhs, state);
632                if let Some(var_id) = lhs_local_var(self.gcx, lhs) {
633                    if op.is_none() {
634                        self.update_internal_function_target(state, var_id, rhs);
635                    } else {
636                        state.internal_function_targets.remove(&var_id);
637                    }
638                }
639                if self.reentrancy_balance_enabled {
640                    let targets = match tuple_elems(lhs) {
641                        Some(elems) => elems
642                            .iter()
643                            .map(|e| e.and_then(|e| lhs_local_var(self.gcx, e)))
644                            .collect(),
645                        None => vec![lhs_local_var(self.gcx, lhs)],
646                    };
647                    self.bind_locals(state, &targets, rhs, op.map(|op| op.kind));
648                }
649            }
650            ExprKind::Delete(inner) => {
651                self.analyze_lhs_indices(inner, state);
652                self.record_write(inner, state);
653                if let Some(var_id) = lhs_local_var(self.gcx, inner) {
654                    state.internal_function_targets.remove(&var_id);
655                    if self.reentrancy_balance_enabled {
656                        self.clear_local(state, var_id);
657                    }
658                }
659            }
660            ExprKind::Unary(op, inner) => {
661                self.analyze_expr(inner, state);
662                if op.kind.has_side_effects() {
663                    self.record_write(inner, state);
664                    if self.reentrancy_balance_enabled
665                        && let Some(var_id) = lhs_local_var(self.gcx, inner)
666                    {
667                        self.set_self_address_paths(state, var_id, PathAlternatives::new());
668                    }
669                }
670            }
671            ExprKind::Call(callee, args) => {
672                let (callee, opts) = callee.split_call_options();
673                let mut operands = vec![callee];
674                operands.extend(opts.iter().flat_map(|opts| opts.args).map(|opt| &opt.value));
675                operands.extend(args.exprs());
676
677                let before_operands = state.clone();
678                for operand in &operands {
679                    self.analyze_expr(operand, state);
680                }
681                // Solidity does not specify operand evaluation order. Reversing the operands
682                // covers both relative orders for each pair without changing the shared
683                // reentrancy analysis.
684                if self.reentrancy_balance_enabled && operands.len() > 1 {
685                    let mut reverse_state = before_operands.balance_only();
686                    self.analyze_with_only_balance(|this| {
687                        for operand in operands.iter().rev() {
688                            this.analyze_expr(operand, &mut reverse_state);
689                        }
690                    });
691                    state.merge_balance(&reverse_state);
692                }
693
694                if self.reentrancy_balance_enabled
695                    && is_require_or_assert(self.gcx, callee)
696                    && let Some(cond) = args.exprs().next()
697                {
698                    self.emit_balance_calls(cond, state);
699                }
700
701                for func_id in self.internal_callees(callee, state) {
702                    let returns = self.analyze_internal_call(func_id, args, state);
703                    self.merge_call_balance_values(expr.span, returns);
704                }
705                if !state.state_reads.is_empty()
706                    && let Some(kind) = self.reentrant_call_kind(callee, opts)
707                {
708                    state.push_call(expr.span, kind);
709                }
710                if self.reentrancy_balance_enabled
711                    && call_options_allow_reentrancy(self.gcx, opts)
712                    && callee_can_reenter(self.gcx, callee)
713                    && !self.balance_guard_blocks_call(state, callee)
714                {
715                    state.push_balance_call(expr.span);
716                }
717                if call_uses_delegate_context(self.gcx, callee) {
718                    state.invalidated_balance_guards.extend(&self.active_balance_guards);
719                }
720            }
721            ExprKind::Binary(lhs, op, rhs)
722                if self.prune_paths && matches!(op.kind, BinOpKind::And | BinOpKind::Or) =>
723            {
724                self.analyze_expr(lhs, state);
725                let rhs_outcome = op.kind == BinOpKind::And;
726                let (mut short_state, mut rhs_state) = (state.clone(), state.clone());
727                let short_reachable =
728                    constrain_boolean_outcome(self.gcx, lhs, !rhs_outcome, &mut short_state);
729                let rhs_reachable =
730                    constrain_boolean_outcome(self.gcx, lhs, rhs_outcome, &mut rhs_state);
731                if rhs_reachable {
732                    self.analyze_expr(rhs, &mut rhs_state);
733                }
734                join_branches(
735                    state,
736                    [short_reachable.then_some(short_state), rhs_reachable.then_some(rhs_state)],
737                );
738            }
739            ExprKind::Ternary(cond, true_expr, false_expr) => {
740                self.analyze_expr(cond, state);
741                let (mut true_state, mut false_state) = (state.clone(), state.clone());
742                let (true_reachable, false_reachable) =
743                    self.split_on(cond, &mut true_state, &mut false_state);
744                if true_reachable {
745                    self.analyze_expr(true_expr, &mut true_state);
746                }
747                if false_reachable {
748                    self.analyze_expr(false_expr, &mut false_state);
749                }
750                join_branches(
751                    state,
752                    [true_reachable.then_some(true_state), false_reachable.then_some(false_state)],
753                );
754            }
755            ExprKind::Ident(_) => state.state_reads.extend(
756                self.gcx
757                    .resolved_variable(expr)
758                    .into_iter()
759                    .filter(|v| self.gcx.hir.variable(*v).kind.is_state()),
760            ),
761            _ => for_each_child(expr, &mut |child| self.analyze_expr(child, state)),
762        }
763    }
764
765    /// Evaluates the index and slice operands of an lvalue; the written root itself is no read.
766    fn analyze_lhs_indices(&mut self, expr: &'gcx Expr<'gcx>, state: &mut FlowState) {
767        match &expr.kind {
768            ExprKind::Index(base, index) => {
769                self.analyze_lhs_indices(base, state);
770                if let Some(index) = index {
771                    self.analyze_expr(index, state);
772                }
773            }
774            ExprKind::Slice(base, start, end) => {
775                self.analyze_lhs_indices(base, state);
776                for bound in [start, end].into_iter().flatten() {
777                    self.analyze_expr(bound, state);
778                }
779            }
780            ExprKind::Member(base, _) | ExprKind::Payable(base) => {
781                self.analyze_lhs_indices(base, state);
782            }
783            ExprKind::Tuple(exprs) => {
784                for expr in exprs.iter().flatten() {
785                    self.analyze_lhs_indices(expr, state);
786                }
787            }
788            _ => {}
789        }
790    }
791
792    /// Handles a write to `lhs`: reports pending reentrant calls that read the written state,
793    /// invalidates written guard locks and forgets path facts about written locals.
794    fn record_write(&mut self, lhs: &'gcx Expr<'gcx>, state: &mut FlowState) {
795        let written = state_lhs_vars(self.gcx, lhs);
796        self.emit_pending_calls(state, &written);
797        state
798            .invalidated_balance_guards
799            .extend(written.iter().filter(|v| self.active_balance_guards.contains(v)));
800        for_each_lhs_var(self.gcx, lhs, &mut |var_id| {
801            if !self.gcx.hir.variable(var_id).kind.is_state() {
802                forget_path_predicates(state, var_id);
803            }
804        });
805    }
806
807    fn analyze_internal_call(
808        &mut self,
809        func_id: FunctionId,
810        args: &CallArgs<'gcx>,
811        state: &mut FlowState,
812    ) -> Vec<BalanceValue> {
813        let func = self.gcx.hir.function(func_id);
814        let Some(body) = func.body.filter(|_| !self.call_stack.contains(&func_id)) else {
815            return Vec::new();
816        };
817
818        self.seed_balance_parameters(func_id, args, state);
819        let parameter_predicates = if self.reentrancy_balance_enabled {
820            func.parameters
821                .iter()
822                .map(|&param| {
823                    arg_for_param(self.gcx, func_id, param, args)
824                        .and_then(|arg| path_predicate(self.gcx, arg))
825                })
826                .collect()
827        } else {
828            Vec::new()
829        };
830
831        // The callee can neither read nor change other functions' balance-independent locals, so
832        // they stay out of its cache key.
833        let inert = take_inert_locals(&self.gcx.hir, func_id, state);
834        let returns = self.inline_internal_call(func_id, func, body, parameter_predicates, state);
835        state.balance_local_forms.extend(inert.0);
836        state.balance_local_dependencies.extend(inert.1);
837        returns
838    }
839
840    fn inline_internal_call(
841        &mut self,
842        func_id: FunctionId,
843        func: &'gcx hir::Function<'gcx>,
844        body: hir::Block<'gcx>,
845        parameter_predicates: Vec<Option<(PathPredicate, bool)>>,
846        state: &mut FlowState,
847    ) -> Vec<BalanceValue> {
848        let key = InlineCallKey {
849            func_id,
850            recursive_cut: self.first_recursive_cut(func_id),
851            balance_only: self.balance_only_analysis,
852            active_balance_guards: self.active_balance_guards.clone(),
853            parameter_predicates: parameter_predicates.clone(),
854            state: state.clone(),
855        };
856        if self.inline_cache.is_in_progress(&key) {
857            self.clear_function_locals(func_id, state);
858            return Vec::new();
859        }
860        if let Some((cached, returns)) = self.inline_cache.get(&key).cloned() {
861            *state = if self.balance_only_analysis { cached.balance_only() } else { cached };
862            return returns;
863        }
864
865        self.inline_cache.start(key.clone());
866        if self.reentrancy_balance_enabled {
867            let slots = vec![BalanceValue::default(); func.returns.len()];
868            self.return_collectors.push((func_id, slots));
869        }
870        // Call-site results belong to this invocation; only its evaluation alternatives merge.
871        let caller_balance_values = std::mem::take(&mut self.call_balance_values);
872        self.call_stack.push(func_id);
873        let mut after = state.clone();
874        let falls_through = self.analyze_callable(func, body, &mut after);
875        self.call_stack.pop();
876
877        let mut returns = Vec::new();
878        if self.reentrancy_balance_enabled {
879            if falls_through {
880                self.record_return(None, &after);
881            }
882            returns = self.return_collectors.pop().expect("return collector is active").1;
883            remap_return_paths(
884                &self.gcx.hir,
885                func_id,
886                func.parameters,
887                &parameter_predicates,
888                &mut returns,
889            );
890        }
891        self.call_balance_values = caller_balance_values;
892        self.clear_function_locals(func_id, &mut after);
893        if self.balance_only_analysis {
894            after = after.balance_only();
895        }
896
897        self.inline_cache.finish(key, (after.clone(), returns.clone()));
898        *state = after;
899        returns
900    }
901
902    /// Internal functions a call through `callee` may reach, following function-typed locals.
903    fn internal_callees(
904        &self,
905        callee: &'gcx Expr<'gcx>,
906        state: &FlowState,
907    ) -> BTreeSet<FunctionId> {
908        if let Some(targets) =
909            lhs_local_var(self.gcx, callee).and_then(|v| state.internal_function_targets.get(&v))
910        {
911            return targets.clone();
912        }
913        static_internal_callee(self.gcx, callee).into_iter().collect()
914    }
915
916    fn update_internal_function_target(
917        &self,
918        state: &mut FlowState,
919        var_id: VariableId,
920        value: &'gcx Expr<'gcx>,
921    ) {
922        let targets = self.internal_callees(value, state);
923        state.internal_function_targets.remove(&var_id);
924        if !targets.is_empty() {
925            state.internal_function_targets.insert(var_id, targets);
926        }
927    }
928
929    fn merge_call_balance_values(&mut self, span: Span, values: Vec<BalanceValue>) {
930        let stored = self.call_balance_values.entry(span).or_default();
931        if stored.len() < values.len() {
932            stored.resize_with(values.len(), BalanceValue::default);
933        }
934        for (stored, value) in stored.iter_mut().zip(values) {
935            stored.merge(value);
936        }
937    }
938
939    fn analyze_with_only_balance<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
940        let saved = (
941            self.reentrancy_eth_enabled,
942            self.reentrancy_no_eth_enabled,
943            self.balance_only_analysis,
944        );
945        (self.reentrancy_eth_enabled, self.reentrancy_no_eth_enabled, self.balance_only_analysis) =
946            (false, false, true);
947        let result = f(self);
948        (self.reentrancy_eth_enabled, self.reentrancy_no_eth_enabled, self.balance_only_analysis) =
949            saved;
950        result
951    }
952
953    fn first_recursive_cut(&mut self, func_id: FunctionId) -> Option<FunctionId> {
954        if self.call_stack.is_empty() {
955            return None;
956        }
957        let key = (func_id, self.call_stack.iter().copied().collect::<BTreeSet<_>>());
958        if let Some(cut) = self.recursive_cuts.get(&key) {
959            return *cut;
960        }
961        let cut = self.first_recursive_cut_from(func_id, &key.1, &mut HashSet::new());
962        self.recursive_cuts.insert(key, cut);
963        cut
964    }
965
966    /// Depth-first search from `func_id` for the first callee that is currently `active`.
967    fn first_recursive_cut_from(
968        &mut self,
969        func_id: FunctionId,
970        active: &BTreeSet<FunctionId>,
971        seen: &mut HashSet<FunctionId>,
972    ) -> Option<FunctionId> {
973        if !seen.insert(func_id) {
974            return None;
975        }
976        self.direct_internal_calls(func_id).into_iter().find_map(|callee| {
977            if active.contains(&callee) {
978                Some(callee)
979            } else {
980                self.first_recursive_cut_from(callee, active, seen)
981            }
982        })
983    }
984
985    /// Internal functions and modifiers `func_id` invokes directly.
986    fn direct_internal_calls(&mut self, func_id: FunctionId) -> Vec<FunctionId> {
987        if let Some(calls) = self.direct_internal_calls.get(&func_id) {
988            return calls.clone();
989        }
990        let mut collector = CallCollector { gcx: self.gcx, calls: BTreeSet::new() };
991        let _ = collector.visit_function(self.gcx.hir.function(func_id));
992        let calls = collector.calls.into_iter().collect::<Vec<_>>();
993        self.direct_internal_calls.insert(func_id, calls.clone());
994        calls
995    }
996
997    fn emit_pending_calls(&mut self, state: &FlowState, written_vars: &[VariableId]) {
998        for (&(span, kind), reads) in &state.pending_calls {
999            let Some(var_id) = written_vars.iter().find(|v| reads.contains(v)) else { continue };
1000            if !self.emitted.insert(span) {
1001                continue;
1002            }
1003            let (lint, what) = match kind {
1004                ReentrantCallKind::Eth => (&REENTRANCY_ETH, "uncapped ETH transfer"),
1005                ReentrantCallKind::NoEth => (&REENTRANCY_NO_ETH, "external call"),
1006            };
1007            let name = self
1008                .gcx
1009                .hir
1010                .variable(*var_id)
1011                .name
1012                .map_or_else(|| "state".to_string(), |name| name.to_string());
1013            let msg = format!("{what} can be reentered before `{name}` is updated");
1014            self.ctx.emit_with_msg(lint, span, msg);
1015        }
1016    }
1017
1018    /// Reports pending balance calls whose stale balance `guard` compares against.
1019    fn emit_balance_calls(&mut self, guard: &'gcx Expr<'gcx>, state: &FlowState) {
1020        for (&span, call) in &state.pending_balance_calls {
1021            if !self.emitted_balance.contains(&span)
1022                && self.guard_has_stale_balance_comparison(guard, span, call, state)
1023            {
1024                self.ctx.emit(&REENTRANCY_BALANCE, span);
1025                self.emitted_balance.insert(span);
1026            }
1027        }
1028    }
1029
1030    /// True if `expr` compares a balance read before the pending `call` against one read after.
1031    fn guard_has_stale_balance_comparison(
1032        &self,
1033        expr: &'gcx Expr<'gcx>,
1034        span: Span,
1035        call: &PathAlternatives,
1036        state: &FlowState,
1037    ) -> bool {
1038        let expr = expr.peel_parens();
1039        let recurse = |e, s| self.guard_has_stale_balance_comparison(e, span, call, s);
1040        match &expr.kind {
1041            ExprKind::Binary(lhs, op, rhs) if matches!(op.kind, BinOpKind::And | BinOpKind::Or) => {
1042                if recurse(lhs, state) {
1043                    return true;
1044                }
1045                let mut rhs_state = state.clone();
1046                constrain_boolean_outcome(self.gcx, lhs, op.kind == BinOpKind::And, &mut rhs_state)
1047                    && recurse(rhs, &rhs_state)
1048            }
1049            ExprKind::Binary(lhs, op, rhs) => {
1050                let is_comparison = matches!(
1051                    op.kind,
1052                    BinOpKind::Lt
1053                        | BinOpKind::Le
1054                        | BinOpKind::Gt
1055                        | BinOpKind::Ge
1056                        | BinOpKind::Eq
1057                        | BinOpKind::Ne
1058                );
1059                (is_comparison && {
1060                    let lhs_dependencies = self.balance_operand_dependencies(lhs, state);
1061                    let rhs_dependencies = self.balance_operand_dependencies(rhs, state);
1062                    let direct = lhs_dependencies.iter().any(|lhs| {
1063                        rhs_dependencies.iter().any(|rhs| {
1064                            paths_compatible(&lhs.path, &rhs.path)
1065                                && call.iter().any(|path| {
1066                                    paths_compatible(path, &lhs.path)
1067                                        && paths_compatible(path, &rhs.path)
1068                                })
1069                                && lhs.terms.iter().any(|a| {
1070                                    rhs.terms.iter().any(|b| {
1071                                        a.stale_calls.contains(&span)
1072                                            != b.stale_calls.contains(&span)
1073                                    })
1074                                })
1075                        })
1076                    });
1077                    let lhs = self.balance_forms(lhs, state);
1078                    let rhs = self.balance_forms(rhs, state);
1079                    direct
1080                        || lhs.iter().any(|lhs| {
1081                            rhs.iter().filter_map(|rhs| lhs.combine(rhs, true)).any(|form| {
1082                                let [a, b] = form.terms.as_slice() else { return false };
1083                                a.negative != b.negative
1084                                    && a.stale_calls.contains(&span)
1085                                        != b.stale_calls.contains(&span)
1086                                    && call.iter().any(|path| paths_compatible(path, &form.path))
1087                            })
1088                        })
1089                }) || recurse(lhs, state)
1090                    || recurse(rhs, state)
1091            }
1092            ExprKind::Unary(_, inner) | ExprKind::Payable(inner) => recurse(inner, state),
1093            ExprKind::Ternary(cond, true_expr, false_expr) => {
1094                [*cond, *true_expr, *false_expr].into_iter().any(|e| recurse(e, state))
1095            }
1096            ExprKind::Call(..) => match cast_args(expr) {
1097                Some(args) => args.exprs().any(|arg| recurse(arg, state)),
1098                None => self.call_balance_values.get(&expr.span).is_some_and(|values| {
1099                    values.iter().any(|value| value.stale_comparisons.contains(&span))
1100                }),
1101            },
1102            ExprKind::Ident(_) => self.gcx.resolved_variable(expr).is_some_and(|var_id| {
1103                state
1104                    .balance_comparison_locals
1105                    .get(&var_id)
1106                    .is_some_and(|calls| calls.contains(&span))
1107            }),
1108            _ => false,
1109        }
1110    }
1111
1112    /// Binds the components of `rhs` to the local `targets` they are assigned to.
1113    fn bind_locals(
1114        &mut self,
1115        state: &mut FlowState,
1116        targets: &[Option<VariableId>],
1117        rhs: &'gcx Expr<'gcx>,
1118        op: Option<BinOpKind>,
1119    ) {
1120        if targets.iter().all(Option::is_none) {
1121            return;
1122        }
1123        let values = self.balance_values(rhs, state);
1124        for (var_id, value) in targets.iter().zip(values) {
1125            let Some(var_id) = *var_id else { continue };
1126            self.set_balance_local(state, var_id, &value, op);
1127            let paths =
1128                if op.is_some() { PathAlternatives::new() } else { value.self_address_paths };
1129            self.set_self_address_paths(state, var_id, paths);
1130        }
1131    }
1132
1133    fn set_self_address_paths(
1134        &self,
1135        state: &mut FlowState,
1136        var_id: VariableId,
1137        paths: PathAlternatives,
1138    ) {
1139        state.self_address_local_paths.remove(&var_id);
1140        if !paths.is_empty() {
1141            state.self_address_local_paths.insert(var_id, paths);
1142        }
1143    }
1144
1145    /// Makes `var_id` hold `value`; a compound assignment also keeps what the local held before.
1146    fn set_balance_local(
1147        &self,
1148        state: &mut FlowState,
1149        var_id: VariableId,
1150        value: &BalanceValue,
1151        op: Option<BinOpKind>,
1152    ) {
1153        let forms = match op {
1154            None => value.forms.clone(),
1155            Some(op @ (BinOpKind::Add | BinOpKind::Sub)) => state
1156                .balance_local_forms
1157                .get(&var_id)
1158                .into_iter()
1159                .flatten()
1160                .flat_map(|lhs| {
1161                    value.forms.iter().filter_map(move |rhs| lhs.combine(rhs, op == BinOpKind::Sub))
1162                })
1163                .collect(),
1164            Some(_) => BTreeSet::new(),
1165        };
1166        state.balance_local_forms.insert(var_id, forms);
1167        let mut dependencies = value.dependencies.clone();
1168        let mut balance_paths = value.balance_paths.clone();
1169        let mut stale_comparisons = value.stale_comparisons.clone();
1170        if op.is_some() {
1171            dependencies.extend(
1172                state
1173                    .balance_local_dependencies
1174                    .get(&var_id)
1175                    .into_iter()
1176                    .flatten()
1177                    .filter_map(|form| form.constrained(&state.path_predicates)),
1178            );
1179            balance_paths
1180                .extend(state.balance_local_paths.get(&var_id).into_iter().flatten().cloned());
1181            stale_comparisons
1182                .extend(state.balance_comparison_locals.get(&var_id).into_iter().flatten());
1183        }
1184        state.balance_local_dependencies.insert(var_id, dependencies);
1185        state.balance_local_paths.remove(&var_id);
1186        state.balance_comparison_locals.remove(&var_id);
1187        if !balance_paths.is_empty() {
1188            state.balance_local_paths.insert(var_id, balance_paths);
1189        }
1190        if !stale_comparisons.is_empty() {
1191            state.balance_comparison_locals.insert(var_id, stale_comparisons);
1192        }
1193    }
1194
1195    /// Balance facts of each component of `rhs`, one per destructuring target.
1196    fn balance_values(&self, rhs: &'gcx Expr<'gcx>, state: &FlowState) -> Vec<BalanceValue> {
1197        if let Some(elems) = tuple_elems(rhs) {
1198            return elems
1199                .iter()
1200                .map(|e| e.map(|e| self.balance_dependency(e, state)).unwrap_or_default())
1201                .collect();
1202        }
1203        match self.call_balance_values.get(&rhs.peel_parens().span) {
1204            Some(values) if !values.is_empty() => {
1205                values.iter().map(|v| v.constrained(&state.path_predicates)).collect()
1206            }
1207            _ => vec![self.balance_dependency(rhs, state)],
1208        }
1209    }
1210
1211    fn balance_dependency(&self, expr: &'gcx Expr<'gcx>, state: &FlowState) -> BalanceValue {
1212        let pending = &state.pending_balance_calls;
1213        BalanceValue {
1214            forms: self.balance_forms(expr, state),
1215            dependencies: self.balance_operand_dependencies(expr, state),
1216            balance_paths: self.expr_balance_paths(expr, state),
1217            self_address_paths: self.self_address_path(expr, state),
1218            stale_comparisons: pending
1219                .iter()
1220                .filter(|(span, call)| {
1221                    self.guard_has_stale_balance_comparison(expr, **span, call, state)
1222                })
1223                .map(|(span, _)| *span)
1224                .collect(),
1225        }
1226    }
1227
1228    /// Predicates under which `expr` evaluates to `address(this)`.
1229    fn self_address_path(&self, expr: &Expr<'_>, state: &FlowState) -> PathAlternatives {
1230        let expr = expr.peel_parens();
1231        match &expr.kind {
1232            ExprKind::Payable(inner) => self.self_address_path(inner, state),
1233            ExprKind::Call(callee, args)
1234                if callee.split_call_options().1.is_none()
1235                    && is_address_cast(callee)
1236                    && args.len() == 1 =>
1237            {
1238                self.self_address_path(args.exprs().next().expect("one argument"), state)
1239            }
1240            ExprKind::Call(..) => self
1241                .call_balance_values
1242                .get(&expr.span)
1243                .and_then(|values| values.first())
1244                .map(|value| constrain_paths(&value.self_address_paths, &state.path_predicates))
1245                .unwrap_or_default(),
1246            ExprKind::Ident(_) if is_builtin(self.gcx, expr, sym::this) => {
1247                BTreeSet::from([state.path_predicates.clone()])
1248            }
1249            ExprKind::Ident(_) => self
1250                .gcx
1251                .resolved_variable(expr)
1252                .into_iter()
1253                .filter_map(|v| state.self_address_local_paths.get(&v))
1254                .flat_map(|paths| constrain_paths(paths, &state.path_predicates))
1255                .collect(),
1256            _ => PathAlternatives::new(),
1257        }
1258    }
1259
1260    /// Predicates under which `expr` is `<self address>.balance`.
1261    fn self_balance_paths(&self, expr: &Expr<'_>, state: &FlowState) -> PathAlternatives {
1262        match &expr.peel_parens().kind {
1263            ExprKind::Member(base, member) if member.name == kw::Balance => {
1264                self.self_address_path(base, state)
1265            }
1266            _ => PathAlternatives::new(),
1267        }
1268    }
1269
1270    /// Predicates under which `expr` derives from the contract's own balance.
1271    fn expr_balance_paths(&self, expr: &'gcx Expr<'gcx>, state: &FlowState) -> PathAlternatives {
1272        let expr = expr.peel_parens();
1273        let self_balance = self.self_balance_paths(expr, state);
1274        if !self_balance.is_empty() {
1275            return self_balance;
1276        }
1277        let recurse = |e| self.expr_balance_paths(e, state);
1278        match &expr.kind {
1279            ExprKind::Ident(_) => self
1280                .gcx
1281                .resolved_variable(expr)
1282                .into_iter()
1283                .filter_map(|v| state.balance_local_paths.get(&v))
1284                .flat_map(|paths| constrain_paths(paths, &state.path_predicates))
1285                .collect(),
1286            ExprKind::Unary(_, inner) | ExprKind::Payable(inner) => recurse(inner),
1287            ExprKind::Binary(lhs, _, rhs) => [*lhs, *rhs].into_iter().flat_map(recurse).collect(),
1288            ExprKind::Ternary(cond, true_expr, false_expr) => {
1289                [*cond, *true_expr, *false_expr].into_iter().flat_map(recurse).collect()
1290            }
1291            ExprKind::Call(..) => match cast_args(expr) {
1292                Some(args) => args.exprs().flat_map(recurse).collect(),
1293                None => self
1294                    .call_balance_values
1295                    .get(&expr.span)
1296                    .into_iter()
1297                    .flatten()
1298                    .flat_map(|value| constrain_paths(&value.balance_paths, &state.path_predicates))
1299                    .collect(),
1300            },
1301            _ => PathAlternatives::new(),
1302        }
1303    }
1304
1305    /// Retains balance occurrences across comparison operands without assuming arithmetic
1306    /// identities.
1307    fn balance_operand_dependencies(
1308        &self,
1309        expr: &'gcx Expr<'gcx>,
1310        state: &FlowState,
1311    ) -> BTreeSet<BalanceForm> {
1312        let recurse = |expr| self.balance_operand_dependencies(expr, state);
1313        match &expr.peel_parens().kind {
1314            ExprKind::Binary(lhs, _, rhs) => [*lhs, *rhs].into_iter().flat_map(recurse).collect(),
1315            ExprKind::Unary(_, inner) | ExprKind::Payable(inner) => recurse(inner),
1316            ExprKind::Ternary(cond, true_expr, false_expr) => {
1317                let mut then_state = state.clone();
1318                let mut else_state = state.clone();
1319                let (then_reachable, else_reachable) =
1320                    self.split_on(cond, &mut then_state, &mut else_state);
1321                [(true_expr, then_state, then_reachable), (false_expr, else_state, else_reachable)]
1322                    .into_iter()
1323                    .filter(|(_, _, reachable)| *reachable)
1324                    .flat_map(|(expr, state, _)| self.balance_operand_dependencies(expr, &state))
1325                    .collect()
1326            }
1327            ExprKind::Call(..) if let Some(args) = cast_args(expr) => {
1328                args.exprs().flat_map(recurse).collect()
1329            }
1330            ExprKind::Ident(_) => self
1331                .gcx
1332                .resolved_variable(expr)
1333                .into_iter()
1334                .filter_map(|var| state.balance_local_dependencies.get(&var))
1335                .flatten()
1336                .filter_map(|form| form.constrained(&state.path_predicates))
1337                .collect(),
1338            ExprKind::Call(..) => self
1339                .call_balance_values
1340                .get(&expr.peel_parens().span)
1341                .into_iter()
1342                .flatten()
1343                .flat_map(|value| &value.dependencies)
1344                .filter_map(|form| form.constrained(&state.path_predicates))
1345                .collect(),
1346            _ => self.balance_forms(expr, state),
1347        }
1348    }
1349
1350    /// Preserves balance terms through addition/subtraction and value-preserving integer casts.
1351    /// Other operators may form independent offsets, but cannot transform balance terms.
1352    /// Unsupported expressions return no forms, rather than an independent offset.
1353    fn balance_forms(&self, expr: &'gcx Expr<'gcx>, state: &FlowState) -> BTreeSet<BalanceForm> {
1354        let expr = expr.peel_parens();
1355        let paths = self.self_balance_paths(expr, state);
1356        if !paths.is_empty() {
1357            return paths
1358                .into_iter()
1359                .map(|path| BalanceForm {
1360                    terms: vec![BalanceTerm { negative: false, stale_calls: BTreeSet::new() }],
1361                    path,
1362                })
1363                .collect();
1364        }
1365        let independent = || {
1366            BTreeSet::from([BalanceForm {
1367                path: state.path_predicates.clone(),
1368                ..BalanceForm::default()
1369            }])
1370        };
1371        match &expr.kind {
1372            ExprKind::Lit(_) => independent(),
1373            ExprKind::Ident(_) => {
1374                let Some(var) = self.gcx.resolved_variable(expr) else {
1375                    return BTreeSet::new();
1376                };
1377                match state.balance_local_forms.get(&var) {
1378                    Some(forms) => forms
1379                        .iter()
1380                        .filter_map(|form| form.constrained(&state.path_predicates))
1381                        .collect(),
1382                    None => independent(),
1383                }
1384            }
1385            ExprKind::Ternary(cond, true_expr, false_expr) => {
1386                let mut then_state = state.clone();
1387                let mut else_state = state.clone();
1388                let (then_reachable, else_reachable) =
1389                    self.split_on(cond, &mut then_state, &mut else_state);
1390                [(true_expr, then_state, then_reachable), (false_expr, else_state, else_reachable)]
1391                    .into_iter()
1392                    .filter(|(_, _, reachable)| *reachable)
1393                    .flat_map(|(expr, state, _)| self.balance_forms(expr, &state))
1394                    .collect()
1395            }
1396            ExprKind::Binary(lhs, op, rhs) => {
1397                let lhs = self.balance_forms(lhs, state);
1398                let rhs = self.balance_forms(rhs, state);
1399                lhs.iter()
1400                    .flat_map(|lhs| {
1401                        rhs.iter().filter_map(|rhs| {
1402                            if matches!(op.kind, BinOpKind::Add | BinOpKind::Sub)
1403                                || (lhs.terms.is_empty() && rhs.terms.is_empty())
1404                            {
1405                                lhs.combine(rhs, op.kind == BinOpKind::Sub)
1406                            } else {
1407                                None
1408                            }
1409                        })
1410                    })
1411                    .collect()
1412            }
1413            ExprKind::Call(callee, args) if cast_type(callee).is_some() && args.len() == 1 => {
1414                let inner = args.exprs().next().expect("one argument");
1415                let preserving = match (
1416                    self.gcx.type_of_expr(inner.peel_parens().id),
1417                    self.gcx.type_of_expr(expr.peel_parens().id),
1418                ) {
1419                    (Some(from), Some(to)) => {
1420                        from.is_integer()
1421                            && to.is_integer()
1422                            && from.is_signed() == to.is_signed()
1423                            && from.convert_implicit_to(to, self.gcx)
1424                    }
1425                    _ => false,
1426                };
1427                self.balance_forms(inner, state)
1428                    .into_iter()
1429                    .filter(|form| preserving || form.terms.is_empty())
1430                    .collect()
1431            }
1432            ExprKind::Call(..) => self
1433                .call_balance_values
1434                .get(&expr.span)
1435                .into_iter()
1436                .flatten()
1437                .flat_map(|value| {
1438                    value.forms.iter().filter_map(|form| form.constrained(&state.path_predicates))
1439                })
1440                .collect(),
1441            _ => BTreeSet::new(),
1442        }
1443    }
1444
1445    /// Binds the balance facts of the call arguments to the callee's parameters.
1446    fn seed_balance_parameters(
1447        &mut self,
1448        func_id: FunctionId,
1449        args: &CallArgs<'gcx>,
1450        state: &mut FlowState,
1451    ) {
1452        if !self.reentrancy_balance_enabled {
1453            return;
1454        }
1455        for &param in self.gcx.hir.function(func_id).parameters {
1456            match arg_for_param(self.gcx, func_id, param, args) {
1457                Some(arg) => self.bind_locals(state, &[Some(param)], arg, None),
1458                None => self.clear_local(state, param),
1459            }
1460        }
1461    }
1462
1463    fn clear_local(&self, state: &mut FlowState, var_id: VariableId) {
1464        self.set_balance_local(state, var_id, &BalanceValue::default(), None);
1465        self.set_self_address_paths(state, var_id, PathAlternatives::new());
1466    }
1467
1468    /// Accumulates the values returned by `return expr;` (or the named return variables when
1469    /// the function falls through) into the innermost return collector.
1470    fn record_return(&mut self, expr: Option<&'gcx Expr<'gcx>>, state: &FlowState) {
1471        let Some(&(func_id, _)) = self.return_collectors.last() else { return };
1472        let values = match expr {
1473            Some(expr) => self.balance_values(expr, state),
1474            None => self
1475                .gcx
1476                .hir
1477                .function(func_id)
1478                .returns
1479                .iter()
1480                .map(|&var_id| self.local_value(var_id, state))
1481                .collect(),
1482        };
1483        let (_, stored) = self.return_collectors.last_mut().expect("return collector is active");
1484        for (stored, value) in stored.iter_mut().zip(values) {
1485            stored.merge(value);
1486        }
1487    }
1488
1489    /// The balance facts currently recorded for the local `var_id`.
1490    fn local_value(&self, var_id: VariableId, state: &FlowState) -> BalanceValue {
1491        BalanceValue {
1492            forms: state.balance_local_forms.get(&var_id).cloned().unwrap_or_default(),
1493            dependencies: state
1494                .balance_local_dependencies
1495                .get(&var_id)
1496                .cloned()
1497                .unwrap_or_default(),
1498            balance_paths: state.balance_local_paths.get(&var_id).cloned().unwrap_or_default(),
1499            self_address_paths: state
1500                .self_address_local_paths
1501                .get(&var_id)
1502                .cloned()
1503                .unwrap_or_default(),
1504            stale_comparisons: state
1505                .balance_comparison_locals
1506                .get(&var_id)
1507                .cloned()
1508                .unwrap_or_default(),
1509        }
1510    }
1511
1512    /// Drops every fact about locals of `func_id` once its inlined body is left.
1513    fn clear_function_locals(&self, func_id: FunctionId, state: &mut FlowState) {
1514        let owned = owned_by(&self.gcx.hir, func_id);
1515        state.internal_function_targets.retain(|v, _| !owned(*v));
1516        state.self_address_local_paths.retain(|v, _| !owned(*v));
1517        state.balance_local_paths.retain(|v, _| !owned(*v));
1518        state.balance_local_forms.retain(|v, _| !owned(*v));
1519        state.balance_local_dependencies.retain(|v, _| !owned(*v));
1520        state.balance_comparison_locals.retain(|v, _| !owned(*v));
1521        state.path_predicates.retain(|predicate, _| !predicate.mentions(&owned));
1522    }
1523
1524    fn reentrant_call_kind(
1525        &self,
1526        callee: &'gcx Expr<'gcx>,
1527        opts: Option<&CallOptions<'gcx>>,
1528    ) -> Option<ReentrantCallKind> {
1529        if self.reentrancy_eth_enabled && is_uncapped_value_call(self.gcx, callee, opts) {
1530            Some(ReentrantCallKind::Eth)
1531        } else if self.reentrancy_no_eth_enabled
1532            && !call_sends_eth(self.gcx, opts)
1533            && callee_can_reenter(self.gcx, callee)
1534        {
1535            Some(ReentrantCallKind::NoEth)
1536        } else {
1537            None
1538        }
1539    }
1540
1541    /// True if the contract-wide reentrancy lock is held and intact around the call.
1542    fn balance_guard_blocks_call(&self, state: &FlowState, callee: &'gcx Expr<'gcx>) -> bool {
1543        !call_uses_delegate_context(self.gcx, callee)
1544            && self.balance_reentry_lock.is_some_and(|lock| {
1545                self.active_balance_guards.contains(&lock)
1546                    && !state.invalidated_balance_guards.contains(&lock)
1547            })
1548    }
1549}
1550
1551/// Collects the internal functions and modifiers a function invokes directly.
1552struct CallCollector<'gcx> {
1553    gcx: Gcx<'gcx>,
1554    calls: BTreeSet<FunctionId>,
1555}
1556
1557impl<'gcx> Visit<'gcx> for CallCollector<'gcx> {
1558    type BreakValue = Never;
1559
1560    fn hir(&self) -> &'gcx hir::Hir<'gcx> {
1561        &self.gcx.hir
1562    }
1563
1564    fn visit_modifier(
1565        &mut self,
1566        modifier: &'gcx hir::Modifier<'gcx>,
1567    ) -> ControlFlow<Self::BreakValue> {
1568        self.calls.extend(modifier.id.as_function());
1569        self.visit_call_args(&modifier.args)
1570    }
1571
1572    fn visit_expr(&mut self, expr: &'gcx Expr<'gcx>) -> ControlFlow<Self::BreakValue> {
1573        collect_internal_calls(self.gcx, expr, &mut self.calls);
1574        ControlFlow::Continue(())
1575    }
1576}
1577
1578fn collect_internal_calls(gcx: Gcx<'_>, expr: &Expr<'_>, calls: &mut BTreeSet<FunctionId>) {
1579    if let ExprKind::Call(callee, ..) = &expr.kind {
1580        calls.extend(static_internal_callee(gcx, callee));
1581    }
1582    for_each_child(expr, &mut |child| collect_internal_calls(gcx, child, calls));
1583}
1584
1585/// Internal function statically named by `callee`: a bare identifier or `super.f`.
1586fn static_internal_callee(gcx: Gcx<'_>, callee: &Expr<'_>) -> Option<FunctionId> {
1587    let callee = callee.peel_parens();
1588    let direct = match &callee.kind {
1589        ExprKind::Ident(_) => true,
1590        ExprKind::Member(base, _) => is_builtin(gcx, base, sym::super_),
1591        _ => false,
1592    };
1593    let TyKind::Fn(function) = gcx.type_of_expr(callee.id).filter(|_| direct)?.kind else {
1594        return None;
1595    };
1596    function.is_internal().then_some(function.function_id).flatten()
1597}
1598
1599/// The variables of `func_id`.
1600fn owned_by(hir: &hir::Hir<'_>, func_id: FunctionId) -> impl Fn(VariableId) -> bool {
1601    move |var_id| hir.variable(var_id).parent == Some(ItemId::Function(func_id))
1602}
1603
1604/// The boolean fact `expr` establishes when it evaluates to `true`: a local flag, its negation,
1605/// or an `==`/`!=` between locals and literals.
1606fn path_predicate(gcx: Gcx<'_>, expr: &Expr<'_>) -> Option<(PathPredicate, bool)> {
1607    match &expr.peel_parens().kind {
1608        ExprKind::Ident(_) => Some((PathPredicate::Boolean(lhs_local_var(gcx, expr)?), true)),
1609        ExprKind::Unary(op, inner) if op.kind == UnOpKind::Not => {
1610            path_predicate(gcx, inner).map(|(predicate, value)| (predicate, !value))
1611        }
1612        ExprKind::Binary(lhs, op, rhs) if matches!(op.kind, BinOpKind::Eq | BinOpKind::Ne) => {
1613            let (lhs, rhs) = (predicate_operand(gcx, lhs)?, predicate_operand(gcx, rhs)?);
1614            let predicate = PathPredicate::Equality(lhs.min(rhs), lhs.max(rhs));
1615            Some((predicate, op.kind == BinOpKind::Eq))
1616        }
1617        _ => None,
1618    }
1619}
1620
1621fn predicate_operand(gcx: Gcx<'_>, expr: &Expr<'_>) -> Option<Operand> {
1622    match &expr.peel_parens().kind {
1623        ExprKind::Ident(_) => Some(Operand::Variable(lhs_local_var(gcx, expr)?)),
1624        ExprKind::Lit(lit) => match lit.kind {
1625            LitKind::Number(value) => Some(Operand::Number(value)),
1626            LitKind::Bool(value) => Some(Operand::Boolean(value)),
1627            _ => None,
1628        },
1629        _ => None,
1630    }
1631}
1632
1633/// Records in `state` that `expr` evaluated to `outcome`; returns `false` if that is impossible.
1634fn constrain_boolean_outcome(
1635    gcx: Gcx<'_>,
1636    expr: &Expr<'_>,
1637    outcome: bool,
1638    state: &mut FlowState,
1639) -> bool {
1640    if let Some((predicate, value)) = path_predicate(gcx, expr) {
1641        return state.constrain_path((predicate, value == outcome));
1642    }
1643    match &expr.peel_parens().kind {
1644        // `a && b` being true (or `a || b` being false) fixes both operands.
1645        ExprKind::Binary(lhs, op, rhs)
1646            if op.kind == if outcome { BinOpKind::And } else { BinOpKind::Or } =>
1647        {
1648            constrain_boolean_outcome(gcx, lhs, outcome, state)
1649                && constrain_boolean_outcome(gcx, rhs, outcome, state)
1650        }
1651        _ => true,
1652    }
1653}
1654
1655fn common_path_predicates(lhs: &PathPredicates, rhs: &PathPredicates) -> PathPredicates {
1656    lhs.iter().filter(|(p, v)| rhs.get(p) == Some(v)).map(|(p, v)| (*p, *v)).collect()
1657}
1658
1659fn paths_compatible(lhs: &PathPredicates, rhs: &PathPredicates) -> bool {
1660    lhs.iter().all(|(p, v)| rhs.get(p).is_none_or(|other| other == v))
1661}
1662
1663/// Keeps the `paths` compatible with `active`, extended by the active predicates.
1664fn constrain_paths(paths: &PathAlternatives, active: &PathPredicates) -> PathAlternatives {
1665    paths
1666        .iter()
1667        .filter(|path| paths_compatible(path, active))
1668        .map(|path| path.iter().chain(active).map(|(p, v)| (*p, *v)).collect())
1669        .collect()
1670}
1671
1672/// Rewrites the callee-local predicates in the returned `values` into the caller's terms.
1673fn remap_return_paths(
1674    hir: &hir::Hir<'_>,
1675    func_id: FunctionId,
1676    parameters: &[VariableId],
1677    parameter_predicates: &[Option<(PathPredicate, bool)>],
1678    values: &mut [BalanceValue],
1679) {
1680    let owned = owned_by(hir, func_id);
1681    let remap = |mut path: PathPredicates| {
1682        for (&parameter, &argument) in parameters.iter().zip(parameter_predicates) {
1683            let Some(parameter_value) = path.remove(&PathPredicate::Boolean(parameter)) else {
1684                continue;
1685            };
1686            if let Some((predicate, argument_value)) = argument {
1687                let mapped = parameter_value == argument_value;
1688                if path.get(&predicate).is_some_and(|existing| *existing != mapped) {
1689                    return None;
1690                }
1691                path.insert(predicate, mapped);
1692            }
1693        }
1694        path.retain(|predicate, _| !predicate.mentions(&owned));
1695        Some(path)
1696    };
1697    for value in values {
1698        value.balance_paths =
1699            std::mem::take(&mut value.balance_paths).into_iter().filter_map(remap).collect();
1700        value.self_address_paths =
1701            std::mem::take(&mut value.self_address_paths).into_iter().filter_map(remap).collect();
1702        for forms in [&mut value.forms, &mut value.dependencies] {
1703            *forms = std::mem::take(forms)
1704                .into_iter()
1705                .filter_map(|form| Some(BalanceForm { path: remap(form.path)?, ..form }))
1706                .collect();
1707        }
1708    }
1709}
1710
1711/// Takes out the balance forms and dependencies that are balance-independent and belong to locals
1712/// of functions other than `func_id`, whose paths do not mention `func_id`'s locals.
1713fn take_inert_locals(
1714    hir: &hir::Hir<'_>,
1715    func_id: FunctionId,
1716    state: &mut FlowState,
1717) -> (BTreeMap<VariableId, BTreeSet<BalanceForm>>, BTreeMap<VariableId, BTreeSet<BalanceForm>>) {
1718    let owned = owned_by(hir, func_id);
1719    let take = |map: &mut BTreeMap<VariableId, BTreeSet<BalanceForm>>| {
1720        let (inert, kept) = std::mem::take(map).into_iter().partition(|(var_id, forms)| {
1721            !owned(*var_id)
1722                && forms.iter().all(|form| {
1723                    form.terms.is_empty() && !form.path.keys().any(|p| p.mentions(&owned))
1724                })
1725        });
1726        *map = kept;
1727        inert
1728    };
1729    (take(&mut state.balance_local_forms), take(&mut state.balance_local_dependencies))
1730}
1731
1732/// Drops every path fact that mentions the (re)assigned local `var_id`.
1733fn forget_path_predicates(state: &mut FlowState, var_id: VariableId) {
1734    let mentions = |predicate: &PathPredicate| predicate.mentions(|v| v == var_id);
1735    state.path_predicates.retain(|p, _| !mentions(p));
1736    let strip = |paths: &mut PathAlternatives| {
1737        *paths = paths
1738            .iter()
1739            .map(|path| path.iter().filter(|(p, _)| !mentions(p)).map(|(p, v)| (*p, *v)).collect())
1740            .collect();
1741    };
1742    for forms in
1743        state.balance_local_forms.values_mut().chain(state.balance_local_dependencies.values_mut())
1744    {
1745        *forms = std::mem::take(forms)
1746            .into_iter()
1747            .map(|mut form| {
1748                form.path.retain(|p, _| !mentions(p));
1749                form
1750            })
1751            .collect();
1752    }
1753    state.balance_local_paths.values_mut().for_each(strip);
1754    state.self_address_local_paths.values_mut().for_each(strip);
1755    state.pending_balance_calls.values_mut().for_each(strip);
1756}
1757
1758/// Arguments of a plain type conversion such as `uint256(x)` or `address(x)`.
1759fn cast_args<'a>(expr: &'a Expr<'a>) -> Option<&'a CallArgs<'a>> {
1760    let (callee, args, opts) = expr.peel_parens().as_call()?;
1761    (opts.is_none() && matches!(callee.kind, ExprKind::Type(_) | ExprKind::TypeCall(_)))
1762        .then_some(args)
1763}
1764
1765fn call_option<'a>(opts: Option<&'a CallOptions<'a>>, name: Symbol) -> Option<&'a Expr<'a>> {
1766    opts?.args.iter().find(|opt| opt.name.name == name).map(|opt| &opt.value)
1767}
1768
1769fn call_sends_eth(gcx: Gcx<'_>, opts: Option<&CallOptions<'_>>) -> bool {
1770    call_option(opts, sym::value).is_some_and(|value| !is_zero_value(gcx, value))
1771}
1772
1773/// `.call{value: v}(...)` with a non-zero value and no gas cap other than `gasleft()`.
1774fn is_uncapped_value_call(gcx: Gcx<'_>, callee: &Expr<'_>, opts: Option<&CallOptions<'_>>) -> bool {
1775    matches!(&callee.peel_parens().kind, ExprKind::Member(_, member) if member.name == kw::Call)
1776        && call_sends_eth(gcx, opts)
1777        && call_option(opts, kw::Gas).is_none_or(|gas| {
1778            matches!(&gas.peel_parens().kind, ExprKind::Call(callee, args)
1779                if callee.split_call_options().1.is_none()
1780                    && args.is_empty()
1781                    && is_builtin(gcx, callee, sym::gasleft))
1782        })
1783}
1784
1785/// True unless a `gas:` option provably leaves the callee too little gas to reenter.
1786fn call_options_allow_reentrancy(gcx: Gcx<'_>, opts: Option<&CallOptions<'_>>) -> bool {
1787    let Some(gas) = call_option(opts, kw::Gas) else { return true };
1788    let sends_eth = call_sends_eth(gcx, opts);
1789    match const_value(gcx, gas, None, &mut BTreeSet::new()) {
1790        Some(Operand::Number(gas)) => {
1791            gas > U256::from(REENTRANCY_GAS_STIPEND) || (sends_eth && !gas.is_zero())
1792        }
1793        _ => true,
1794    }
1795}
1796
1797fn is_zero_value(gcx: Gcx<'_>, expr: &Expr<'_>) -> bool {
1798    matches!(const_value(gcx, expr, None, &mut BTreeSet::new()), Some(Operand::Number(n)) if n.is_zero())
1799}
1800
1801/// `break`/`continue` or anything that exits the function, so the current path stops here.
1802fn branch_stops_current_path(gcx: Gcx<'_>, stmt: &Stmt<'_>) -> bool {
1803    match &stmt.kind {
1804        StmtKind::Break | StmtKind::Continue => true,
1805        StmtKind::Block(block) | StmtKind::UncheckedBlock(block) => {
1806            block.stmts.iter().any(|expr| branch_stops_current_path(gcx, expr))
1807        }
1808        StmtKind::If(_, then_stmt, Some(else_stmt)) => {
1809            branch_stops_current_path(gcx, then_stmt) && branch_stops_current_path(gcx, else_stmt)
1810        }
1811        _ => branch_always_exits(gcx, stmt),
1812    }
1813}
1814
1815/// The lock state variable of a standard reentrancy guard modifier: it rejects re-entry, sets
1816/// the lock, runs `_` exactly once and restores the lock right after.
1817fn standard_reentrancy_guard_lock(
1818    gcx: Gcx<'_>,
1819    modifier: &hir::Function<'_>,
1820) -> Option<VariableId> {
1821    if !matches!(modifier.kind, FunctionKind::Modifier) || !modifier.modifiers.is_empty() {
1822        return None;
1823    }
1824    let stmts = modifier.body?.stmts;
1825    if count_placeholders(stmts) != 1 {
1826        return None;
1827    }
1828    let mut activation = Vec::new();
1829    stmts_before_placeholder(stmts, &mut activation)?;
1830    let (lock_var, entered) = guard_activation(gcx, &activation, &mut BTreeSet::new())?;
1831    let index = stmts.iter().position(|s| count_placeholders(std::slice::from_ref(s)) == 1)?;
1832    let (restored_var, restored) = guard_restoration(gcx, stmts.get(index + 1)?)?;
1833    (lock_var == restored_var && entered != restored).then_some(lock_var)
1834}
1835
1836/// The lock and value set by the last of `stmts` (directly or via an argument-less helper), if
1837/// an earlier statement rejects that value.
1838fn guard_activation(
1839    gcx: Gcx<'_>,
1840    stmts: &[&Stmt<'_>],
1841    seen: &mut BTreeSet<FunctionId>,
1842) -> Option<(VariableId, Operand)> {
1843    let (activation, prefix) = stmts.split_last()?;
1844    if let Some((lock_var, entered)) = state_lock_assignment(gcx, activation) {
1845        return prefix
1846            .iter()
1847            .any(|stmt| stmt_rejects_lock_value(gcx, stmt, lock_var, entered))
1848            .then_some((lock_var, entered));
1849    }
1850    let helper_id = simple_internal_call(gcx, activation)?;
1851    let helper = gcx.hir.function(helper_id);
1852    if !helper.modifiers.is_empty() || !seen.insert(helper_id) {
1853        return None;
1854    }
1855    let body = helper.body?.stmts.iter().collect::<Vec<_>>();
1856    let result = guard_activation(gcx, &body, seen);
1857    seen.remove(&helper_id);
1858    result
1859}
1860
1861/// The lock and value restored by `stmt` (directly or via a single-statement helper).
1862fn guard_restoration(gcx: Gcx<'_>, stmt: &Stmt<'_>) -> Option<(VariableId, Operand)> {
1863    state_lock_assignment(gcx, stmt).or_else(|| {
1864        let helper = gcx.hir.function(simple_internal_call(gcx, stmt)?);
1865        let [stmt] = helper.modifiers.is_empty().then_some(helper.body?.stmts)? else {
1866            return None;
1867        };
1868        state_lock_assignment(gcx, stmt)
1869    })
1870}
1871
1872/// `f();` naming exactly one function.
1873fn simple_internal_call(gcx: Gcx<'_>, stmt: &Stmt<'_>) -> Option<FunctionId> {
1874    let StmtKind::Expr(expr) = stmt.kind else { return None };
1875    let (callee, args, opts) = expr.peel_parens().as_call()?;
1876    (opts.is_none() && args.is_empty() && matches!(callee.kind, ExprKind::Ident(_)))
1877        .then(|| gcx.resolved_function(callee))
1878        .flatten()
1879}
1880
1881/// `lock = <constant>;` on a state variable.
1882fn state_lock_assignment(gcx: Gcx<'_>, stmt: &Stmt<'_>) -> Option<(VariableId, Operand)> {
1883    let StmtKind::Expr(expr) = stmt.kind else { return None };
1884    let ExprKind::Assign(lhs, None, rhs) = &expr.peel_parens().kind else { return None };
1885    let ExprKind::Ident(_) = &lhs.peel_parens().kind else { return None };
1886    let lock_var = gcx.resolved_variable(lhs).filter(|&v| gcx.hir.variable(v).kind.is_state())?;
1887    Some((lock_var, const_value(gcx, rhs, None, &mut BTreeSet::new())?))
1888}
1889
1890/// True if `stmt` reverts whenever `lock_var` holds `entered`.
1891fn stmt_rejects_lock_value(
1892    gcx: Gcx<'_>,
1893    stmt: &Stmt<'_>,
1894    lock_var: VariableId,
1895    entered: Operand,
1896) -> bool {
1897    let eval = |cond| match const_value(gcx, cond, Some((lock_var, entered)), &mut BTreeSet::new())
1898    {
1899        Some(Operand::Boolean(value)) => Some(value),
1900        _ => None,
1901    };
1902    match stmt.kind {
1903        StmtKind::Expr(expr) => {
1904            let ExprKind::Call(callee, args) = &expr.peel_parens().kind else { return false };
1905            is_require_or_assert(gcx, callee)
1906                && args.exprs().next().is_some_and(|cond| eval(cond) == Some(false))
1907        }
1908        StmtKind::If(cond, then_stmt, else_stmt) => match eval(cond) {
1909            Some(true) => branch_always_exits(gcx, then_stmt),
1910            Some(false) => else_stmt.is_some_and(|expr| branch_always_exits(gcx, expr)),
1911            None => false,
1912        },
1913        _ => false,
1914    }
1915}
1916
1917/// Constant-folds `expr` over literals, `constant` variables, casts, `!` and `==`/`!=`; `lock`
1918/// supplies the value of the lock variable.
1919fn const_value(
1920    gcx: Gcx<'_>,
1921    expr: &Expr<'_>,
1922    lock: Option<(VariableId, Operand)>,
1923    seen: &mut BTreeSet<VariableId>,
1924) -> Option<Operand> {
1925    let expr = expr.peel_parens();
1926    match &expr.kind {
1927        ExprKind::Lit(lit) => match lit.kind {
1928            LitKind::Bool(value) => Some(Operand::Boolean(value)),
1929            LitKind::Number(value) => Some(Operand::Number(value)),
1930            _ => None,
1931        },
1932        ExprKind::Ident(_) => {
1933            let var_id = gcx.resolved_variable(expr)?;
1934            if let Some((lock_var, entered)) = lock
1935                && lock_var == var_id
1936            {
1937                return Some(entered);
1938            }
1939            let var = gcx.hir.variable(var_id);
1940            if !var.is_constant() || !seen.insert(var_id) {
1941                return None;
1942            }
1943            let value = const_value(gcx, var.initializer?, lock, seen);
1944            seen.remove(&var_id);
1945            value
1946        }
1947        ExprKind::Unary(op, inner) if op.kind == UnOpKind::Not => {
1948            match const_value(gcx, inner, lock, seen)? {
1949                Operand::Boolean(value) => Some(Operand::Boolean(!value)),
1950                _ => None,
1951            }
1952        }
1953        ExprKind::Binary(lhs, op, rhs) if matches!(op.kind, BinOpKind::Eq | BinOpKind::Ne) => {
1954            let lhs = const_value(gcx, lhs, lock, seen)?;
1955            let rhs = const_value(gcx, rhs, lock, seen)?;
1956            Some(Operand::Boolean((lhs == rhs) == (op.kind == BinOpKind::Eq)))
1957        }
1958        ExprKind::Call(..) => {
1959            let args = cast_args(expr).filter(|args| args.len() == 1)?;
1960            const_value(gcx, args.exprs().next()?, lock, seen)
1961        }
1962        _ => None,
1963    }
1964}
1965
1966/// Whether `entry`, or a modifier or internal function it can reach, reads a `.balance`.
1967///
1968/// The balance analysis only reports stale reads of the contract's own balance, so it can skip
1969/// entry points that never read one.
1970fn reaches_balance_read<'gcx>(gcx: Gcx<'gcx>, entry: &'gcx hir::Function<'gcx>) -> bool {
1971    struct Finder<'gcx> {
1972        gcx: Gcx<'gcx>,
1973        pending: Vec<FunctionId>,
1974    }
1975
1976    impl<'gcx> Visit<'gcx> for Finder<'gcx> {
1977        type BreakValue = ();
1978
1979        fn hir(&self) -> &'gcx hir::Hir<'gcx> {
1980            &self.gcx.hir
1981        }
1982
1983        fn visit_modifier(&mut self, modifier: &'gcx hir::Modifier<'gcx>) -> ControlFlow<()> {
1984            self.pending.extend(modifier.id.as_function());
1985            self.visit_call_args(&modifier.args)
1986        }
1987
1988        fn visit_expr(&mut self, expr: &'gcx Expr<'gcx>) -> ControlFlow<()> {
1989            if let ExprKind::Member(_, member) = &expr.kind
1990                && member.name == kw::Balance
1991            {
1992                return ControlFlow::Break(());
1993            }
1994            self.pending.extend(static_internal_callee(self.gcx, expr));
1995            self.walk_expr(expr)
1996        }
1997    }
1998
1999    let mut finder = Finder { gcx, pending: Vec::new() };
2000    if finder.visit_function(entry).is_break() {
2001        return true;
2002    }
2003    let mut seen = HashSet::new();
2004    while let Some(id) = finder.pending.pop() {
2005        if seen.insert(id) && finder.visit_function(gcx.hir.function(id)).is_break() {
2006            return true;
2007        }
2008    }
2009    false
2010}
2011
2012/// The reentrancy-guard lock, if any, that protects every entry point of every deployable
2013/// contract exposing `entry`.
2014fn balance_reentry_lock<'gcx>(
2015    gcx: Gcx<'gcx>,
2016    entry: &'gcx hir::Function<'gcx>,
2017) -> Option<VariableId> {
2018    let entry_id = gcx.hir.function_ids().find(|&id| std::ptr::eq(gcx.hir.function(id), entry))?;
2019    let defining_contract = entry.contract?;
2020    guard_locks(gcx, entry).into_iter().find(|&lock_var| {
2021        let mut deployed = false;
2022        for contract_id in gcx.hir.contract_ids() {
2023            let contract = gcx.hir.contract(contract_id);
2024            if !contract.can_be_deployed()
2025                || contract.is_abstract()
2026                || !contract.linearized_bases.contains(&defining_contract)
2027            {
2028                continue;
2029            }
2030            let interface = gcx.interface_functions(contract_id);
2031            let special = || [contract.fallback, contract.receive].into_iter().flatten();
2032            if !interface.iter().any(|f| f.id == entry_id) && !special().any(|id| id == entry_id) {
2033                continue;
2034            }
2035            deployed = true;
2036            let guarded = interface
2037                .iter()
2038                .map(|f| gcx.hir.function(f.id))
2039                .filter(|f| !is_view_or_pure(f.state_mutability))
2040                .chain(special().map(|id| gcx.hir.function(id)))
2041                .all(|f| guard_locks(gcx, f).contains(&lock_var));
2042            if !guarded {
2043                return false;
2044            }
2045        }
2046        deployed
2047    })
2048}
2049
2050/// Locks of the standard reentrancy guards among `function`'s modifiers.
2051fn guard_locks(gcx: Gcx<'_>, function: &hir::Function<'_>) -> Vec<VariableId> {
2052    function
2053        .modifiers
2054        .iter()
2055        .filter(|modifier| modifier.args.is_empty())
2056        .filter_map(|modifier| modifier.id.as_function())
2057        .filter_map(|id| standard_reentrancy_guard_lock(gcx, gcx.hir.function(id)))
2058        .collect()
2059}
2060
2061/// `delegatecall`/`callcode`, which run the callee in the caller's storage context.
2062fn call_uses_delegate_context(gcx: Gcx<'_>, callee: &Expr<'_>) -> bool {
2063    let callee = callee.peel_parens();
2064    gcx.resolved_builtin(callee) == Some(Builtin::AddressDelegatecall)
2065        || matches!(&callee.kind, ExprKind::Member(_, member) if member.name == kw::Callcode)
2066        || gcx.type_of_expr(callee.id).is_some_and(
2067            |ty| matches!(ty.kind, TyKind::Fn(function) if function.is_delegate_call()),
2068        )
2069}
2070
2071/// An external call that hands control to another contract: a low-level `call`/`callcode`/
2072/// `delegatecall` on an address, or a state-changing external function call.
2073fn callee_can_reenter<'gcx>(gcx: Gcx<'gcx>, callee: &Expr<'gcx>) -> bool {
2074    let callee = callee.peel_parens();
2075    match gcx.resolved_builtin(callee) {
2076        Some(Builtin::AddressCall | Builtin::AddressDelegatecall) => return true,
2077        Some(Builtin::AddressStaticcall) => return false,
2078        _ => {}
2079    }
2080    match &callee.kind {
2081        ExprKind::Member(receiver, member)
2082            if expr_is_address(gcx, receiver) && member.name == kw::Callcode =>
2083        {
2084            true
2085        }
2086        ExprKind::Member(receiver, _) if is_builtin(gcx, receiver, sym::super_) => false,
2087        _ => {
2088            let Some(TyKind::Fn(function)) = gcx.type_of_expr(callee.id).map(|ty| ty.kind) else {
2089                return false;
2090            };
2091            matches!(
2092                function.kind,
2093                TyFnKind::External | TyFnKind::Declaration | TyFnKind::DelegateCall
2094            ) && !is_view_or_pure(function.state_mutability)
2095        }
2096    }
2097}