Chip Foundry Services Request Assessment

Abstract Interpretation

Abstract interpretation is a formal framework for sound static analysis. It computes over *abstract values*, each standing for a whole set of concrete values, and propagates them through the program to prove properties such as the absence of certain runtime errors. For the properties and semantics it models, an analysis that raises no alarm has covered every execution.

Choose the property
No overflow, no divide by zero
Choose an abstract domain
Signs, intervals, octagons
Analyze to a fixpointRepeat at every loop head
Define abstract operations
Sound transfer functions
Join the paths
Merge states at branch joins
↻ refine the domain if alarms are too many
Iterate until stable
F#(x) is contained in x
Widen at loops
Push growing bounds to infinity
Check the property
Proved, or an alarm is raised
Triage the alarms
Real bug or false alarm?

svg

Abstract interpretation of a loop with intervals A number line shows loop index values. One concrete run with n equal to 13 touches indices 0 through 12, and indices 10 to 12 fall outside a ten-slot buffer. Below, the interval analysis starts at the point 0, joins to the interval 0 to 1, then widening jumps the growing upper bound to infinity and the iteration is stable. The resulting interval 0 to infinity is not inside the valid range 0 to 9, so the analysis raises a sound alarm. Analyze Every Run at Once intervals stand for sets of values; widening makes the loop analysis terminate One concrete run n = 13, i = 0 … 12 0 5 10 15 i Iteration 1 i = [0, 0] Iteration 2 [0,0] ⊔ [1,1] = [0, 1] Widening [0,0] ∇ [0,1] = [0, +∞] stable: F#(x) ⊑ x first invalid index (10) valid: 0 … 9 Is [0, +∞] inside the valid range [0, 9]? No, so the analysis raises an alarm Sound: it cannot miss an overflow. Here the alarm is real whenever n > 10. Bounded n would shrink the invariant; this run assumes n is unconstrained. Conceptual interval analysis · integers treated as unbounded · axis truncated at 15

What Is Abstract Interpretation?
- Abstraction: Replace concrete values with abstract representations.
- Concrete: x = 5, y = -3, z = 0
- Abstract: x = positive, y = negative, z = zero
- Sound approximation: The analysis over-approximates the set of possible behaviors. If it reports no alarm for a property, the property holds for every modeled execution. It may still report false alarms.
- Formal framework: Built on lattice theory, Galois connections and fixpoints, introduced by Patrick and Radhia Cousot in 1977.

Why Use It?
- Soundness: For the error classes and language semantics it models, no real error is missed (no false negatives).
- Scalability: Coarse domains scale to large programs. Precise domains cost more.
- Automation: The analysis runs without per-function proofs, though good results usually need tuning of the domain, the iteration strategy and the assumptions about the environment.
- Verification: The guarantee is a mathematical one, relative to the semantics that were modeled.

How Abstract Interpretation Works
1. Choose an abstract domain: Select an abstraction that captures the relevant property.
- Sign domain: negative, zero, positive, unknown
- Interval domain: ranges $[l, u]$
- Parity domain: even, odd, unknown
2. Define abstract semantics: Say how each operation acts on abstract values.
- Concrete: 5 + 3 = 8
- Abstract: positive + positive = positive
3. Compute a fixpoint: Iterate until the abstract state stops changing.
- Analyze a loop by iterating its body until the state is stable.
4. Check the property: Test whether the final abstract state satisfies it.
- Example: Is the array index always within bounds?

The Mathematics

Let $\Sigma$ be the set of program states, $I \subseteq \Sigma$ the initial states, and $\mathrm{post}$ the one-step successor function lifted to sets of states. The reachable states are the least fixpoint of

$$\begin{aligned}F(X) &= I \cup \mathrm{post}(X), \\ \mathrm{Reach} &= \mathrm{lfp}\,F\end{aligned}$$

An abstract domain is an ordered set $(A, \sqsubseteq)$ with a monotone meaning function $\gamma : A \to \wp(\Sigma)$ that maps each abstract value to the set of states it represents. When an abstraction function $\alpha$ also exists, the pair forms a Galois connection:

$$\alpha(C) \sqsubseteq a \iff C \subseteq \gamma(a)$$

An abstract operation $f^{\#}$ is sound for a concrete operation $f$ when it never loses a concrete result:

$$f(\gamma(a)) \subseteq \gamma\bigl(f^{\#}(a)\bigr)$$

Soundness is what makes the fixpoint step trustworthy. If $F^{\#}$ soundly abstracts $F$ and an abstract value $a$ satisfies $F^{\#}(a) \sqsubseteq a$, then $\gamma(a)$ is closed under $F$, so by the Knaster-Tarski theorem

$$\mathrm{lfp}\,F \subseteq \gamma(a)$$

Every reachable state lies inside the concrete meaning of $a$. Any property that holds for all of $\gamma(a)$ therefore holds for the program.

Abstract Domains
- Sign domain: $\{\bot, -, 0, +, \top\}$
- $\bot$ = no value (unreachable), $\top$ = unknown.
- Useful for detecting division by zero and negative indices.
- It cannot express "non-zero": the join of $-$ and $+$ is $\top$, which also contains $0$.
- Interval domain: $x \in [l, u]$ with possibly infinite bounds
- Example: $x \in [0, 100]$
- Useful for range checking and buffer overflow detection.
- Octagon domain: constraints of the form $\pm x \pm y \le c$
- More precise than intervals for relational properties such as $x - y \le c$.
- Polyhedra domain: general linear inequalities $\sum_i a_i x_i \le c$
- Very precise but computationally expensive.
- Pointer domain: abstract heap structure
- Tracks aliasing, null pointers and memory safety.

Abstract Operations

For the interval domain, the three basic operations are:

$$\begin{aligned}{[a,b]} \sqcup {[c,d]} &= [\min(a,c), \\ &\phantom{= [}\max(b,d)] \\[4pt] {[a,b]} \sqcap {[c,d]} &= [\max(a,c), \\ &\phantom{= [}\min(b,d)]\end{aligned}$$

The meet is $\bot$ when the result is empty. Interval addition is $[a,b] +^{\#} [c,d] = [a+c,\ b+d]$.

  • Join ($\sqcup$): Combine abstract values arriving from different paths.
  • positive $\sqcup$ negative = $\top$ (unknown)
  • $[0, 10] \sqcup [20, 30] = [0, 30]$
  • Meet ($\sqcap$): Refine an abstract value with a constraint, such as a branch condition.
  • $\top \sqcap$ positive = positive
  • $[0, 100] \sqcap [50, 150] = [50, 100]$
  • Widening ($\nabla$): Guarantee that loop iteration terminates. A bound that keeps growing is sent to infinity, and stable bounds are kept:
$$\begin{aligned}{[a,b]} \nabla {[c,d]} &= [\ell,\ u] \\ \ell &= \begin{cases} -\infty & c < a \\ a & \text{otherwise} \end{cases} \\ u &= \begin{cases} +\infty & d > b \\ b & \text{otherwise} \end{cases}\end{aligned}$$
  • Narrowing: A short pass after widening that recovers precision lost by the jump, for example by re-applying a loop guard.

Worked Example: A Loop Invariant

For `i = 0; while (i < n) i = i + 1`, with `n` unconstrained, the widened iteration $x_{k+1} = x_k \nabla F^{\#}(x_k)$ starts from $x_0 = \bot$:

$k$$x_k$$F^{\#}(x_k)$
0$\bot$$[0, 0]$
1$[0, 0]$$[0, 1]$
2$[0, 0] \nabla [0, 1] = [0, +\infty]$$[0, +\infty]$

At $k = 2$ we have $F^{\#}(x_2) \sqsubseteq x_2$, so the iteration stops. The invariant at the loop head is $i \in [0, +\infty]$. Widening reached it in two steps, even though the concrete loop may run for any number of iterations.

Example: Sign Analysis

def example(x):
    y = x + 1
    z = 0
    if y > 0:
        z = 10 / y   # needs y != 0
    return z

# Sign-domain reasoning:
# x is unknown (top).
# y = x + 1 = unknown + positive = unknown.
# True branch of y > 0: meet with positive, so y is positive.
# 10 / y has a positive divisor, so division by zero is impossible.
# The assignment z = 0 keeps z defined on the other path.

Example: Buffer Overflow Detection

void process(int n) {
    char buffer[10];
    for (int i = 0; i < n; i++) {
        buffer[i] = 'A';   /* valid only for 0 <= i <= 9 */
    }
}

/* Interval domain, n unconstrained, int treated as unbounded:
 *   i at the loop head:  [0,0] -> [0,1] -> widening -> [0,+inf]
 *   the access needs     i in [0,9]
 *   [0,+inf] is not inside [0,9]   -> alarm
 * The alarm is a real overflow whenever n > 10. The interval domain
 * alone cannot tell that apart from a false alarm, because i < n is a
 * relation between two variables. */

Example: Proving No Division by Zero

int safe_divide(int a, int b) {
    if (b == 0) {
        return 0;   /* handle the zero case */
    }
    return a / b;
}

/* Branch b == 0:  return 0, no division.
 * Branch b != 0:  a / b is safe, but only if the domain can say
 * "b is not zero". The five-element sign domain and plain intervals
 * cannot: removing 0 from the middle of a range leaves a hole. Real
 * analyzers use richer domains or split the cases. */

Python Lab: Intervals, Widening and Soundness

This lab implements the interval domain, runs the loop above with $n$ in different ranges, and checks each invariant against the concrete values the loop actually takes.

"""
Interval abstract interpretation of a bounded loop.

Program analyzed (integers treated as unbounded):

    char buffer[10];
    for (i = 0; i < n; i++)
        buffer[i] = 'A';        /* needs 0 <= i <= 9 */

The analysis computes an interval invariant for i at the loop head,
using widening to terminate and one narrowing pass to recover precision.
"""
import math

INF = math.inf


class Interval:
    """[lo, hi] with infinite bounds allowed; lo is None for bottom."""

    def __init__(self, lo=None, hi=None):
        if lo is None or hi is None or lo > hi:
            self.lo = self.hi = None
        else:
            self.lo, self.hi = lo, hi

    @property
    def is_bottom(self):
        return self.lo is None

    def __eq__(self, other):
        return (self.lo, self.hi) == (other.lo, other.hi)

    def __repr__(self):
        if self.is_bottom:
            return "bottom"
        fmt = lambda v: "+inf" if v == INF else "-inf" if v == -INF else str(v)
        return f"[{fmt(self.lo)}, {fmt(self.hi)}]"

    def leq(self, other):
        """Abstract order: self is contained in other."""
        if self.is_bottom:
            return True
        if other.is_bottom:
            return False
        return other.lo <= self.lo and self.hi <= other.hi

    def join(self, other):
        if self.is_bottom:
            return other
        if other.is_bottom:
            return self
        return Interval(min(self.lo, other.lo), max(self.hi, other.hi))

    def meet(self, other):
        if self.is_bottom or other.is_bottom:
            return Interval()
        return Interval(max(self.lo, other.lo), min(self.hi, other.hi))

    def widen(self, other):
        """Keep stable bounds; send a growing bound to infinity."""
        if self.is_bottom:
            return other
        if other.is_bottom:
            return self
        lo = -INF if other.lo < self.lo else self.lo
        hi = INF if other.hi > self.hi else self.hi
        return Interval(lo, hi)

    def add_const(self, c):
        if self.is_bottom:
            return self
        return Interval(self.lo + c, self.hi + c)

    def contains(self, value):
        return not self.is_bottom and self.lo <= value <= self.hi


def analyze(n):
    """Return (head invariant, body interval of i) for 'for i in 0..n-1'."""
    init = Interval(0, 0)
    guard = Interval(-INF, n.hi - 1) if not n.is_bottom else Interval()

    def step(x):
        # F#(x) = init join ((x meet guard) + 1)
        return init.join(x.meet(guard).add_const(1))

    x = Interval()                       # start from bottom
    for _ in range(100):
        nxt = x.widen(step(x))           # widening iteration
        if nxt == x:
            break
        x = nxt
    assert step(x).leq(x)                # x is a post-fixpoint
    x = x.meet(step(x))                  # one narrowing pass
    assert step(x).leq(x)                # still a post-fixpoint
    return x, x.meet(guard)


def concrete_head_values(n_lo, n_hi):
    """Every value i takes at the loop head, over all n in [n_lo, n_hi]."""
    values = set()
    for n in range(n_lo, n_hi + 1):
        values.update(range(0, max(n, 0) + 1))
    return values


VALID = Interval(0, 9)                   # buffer has indices 0..9
cases = [
    ("n in [0, 10]", Interval(0, 10), (0, 10)),
    ("n in [0, 11]", Interval(0, 11), (0, 11)),
    ("n unconstrained", Interval(0, INF), None),
]

print("Loop: for (i = 0; i < n; i++) buffer[i] = 'A';  buffer has 10 slots")
print("-" * 64)
for label, n, concrete_range in cases:
    head, body = analyze(n)
    safe = body.leq(VALID)
    print(f"{label:<16} head i in {head!s:<10} body i in {body!s:<10} "
          f"-> {'proved safe' if safe else 'ALARM'}")
    if concrete_range:
        seen = concrete_head_values(*concrete_range)
        assert all(head.contains(v) for v in seen), "soundness violated"
        print(f"{'':<16} soundness check: {len(seen)} concrete head values "
              f"all lie inside {head}")

# The alarm for n in [0, 11] is a real overflow: n = 11 writes buffer[10].
head, body = analyze(Interval(0, 11))
assert body == Interval(0, 10) and not body.leq(VALID)
assert Interval(0, 10).leq(analyze(Interval(0, 10))[0])
assert analyze(Interval(0, 10))[1].leq(VALID)
assert analyze(Interval(0, INF))[0] == Interval(0, INF)

print("-" * 64)
print("Widening: [0,0] widen [0,1] =", Interval(0, 0).widen(Interval(0, 1)))
print("Join:     [0,10] join [20,30] =", Interval(0, 10).join(Interval(20, 30)))
print("Meet:     [0,100] meet [50,150] =", Interval(0, 100).meet(Interval(50, 150)))

Soundness vs. Completeness
- Sound: Every concrete behavior is covered. For the modeled error classes, no real error is missed.
- The price is false alarms: the analysis may warn about errors that cannot happen.
- Complete: Would raise an alarm only for real errors.
- By Rice's theorem, no automatic analysis can be both sound and complete for every program and every non-trivial semantic property, so abstract interpretation gives up completeness and keeps soundness.
- Trade-off: Soundness (no false negatives) against precision (few false alarms).

Applications
- Safety-critical systems: Aerospace, automotive and medical software, to show the absence of certain runtime errors.
- Compiler optimization: Proving that a transformation is safe. Classic dataflow analyses such as constant propagation are instances of abstract interpretation.
- Static analysis: Finding null pointer dereferences, buffer overflows and division by zero.
- Security: Showing that specific classes of memory error cannot occur.

Abstract Interpretation Tools
- Astrée (astree.ens.fr): A sound analyzer that aims at proving the absence of runtime errors in C and C++ programs. It grew out of research at ENS and CNRS, and is developed and distributed by AbsInt.
- Polyspace Code Prover (mathworks.com/products/polyspace-code-prover): MathWorks' sound analyzer for C and C++, built on abstract interpretation. It proves the absence of certain runtime errors, such as overflow, division by zero and out-of-bounds array access.
- IKOS (github.com/NASA-SW-VnV/ikos): NASA's open-source analyzer for C and C++, based on abstract interpretation and aimed at proving the absence of runtime errors.
- Infer (fbinfer.com): Meta's open-source static analyzer. Its InferBO checker detects out-of-bounds array accesses.

Challenges
- Precision: A coarse domain gives many false alarms.
- Scalability: Precise relational domains such as polyhedra are expensive.
- Loops: Widening guarantees termination but can lose precision.
- Pointers: Heap abstraction is complex.
- False alarms: Triage takes engineering time, and a sound result is only as useful as its alarm count is manageable.

Precision vs. Cost Trade-Off
- Coarse abstractions (sign, parity): Fast but imprecise, with many false alarms.
- Fine abstractions (octagons, polyhedra): Precise but slower, with fewer false alarms.
- In practice: Choose the domain from the property to verify and the cost you can afford, and specialize it for the code under analysis.

LLMs and Abstract Interpretation
- Domain selection: An LLM can suggest candidate domains for a given property.
- Alarm triage: An LLM can propose which alarms look spurious, to be confirmed by a stronger analysis or a human.
- Explanation: An LLM can describe findings in plain language.
- Boundary: A sound analyzer's alarm should not be dismissed on an LLM's judgement alone.

Limitations
- Unmodeled behavior: The guarantee covers only the error classes and semantics the analysis models.
- False alarms: A conservative analysis reports some errors that cannot occur.
- Expertise: Choosing and tuning domains takes experience.

Abstract interpretation is the foundation of sound static analysis. By covering every modeled execution at once, it can show that whole classes of runtime errors cannot occur, which is why it is used where proving absence matters more than avoiding false alarms.