Section 3.12

Context sensitivity

Definition

Context sensitivity is a property of a static analysis §3.1, a tool that reasons about every run of a program without running it. A context-sensitive analysis keeps apart the facts it derives about one function for different calling contexts. A calling context describes how execution reached the function: for example, the chain of call sites (places in the code that make a call) that led there, or what is known about the arguments. A context-insensitive analysis merges all callers of a function into a single analysis of that function.

The idea

A function is written once and called from many places, and each place passes its own arguments. Take the function int id(int x) { return x; } and the two calls a = id(1); and b = id(2);. A context-insensitive analysis analyzes id once, for both calls together. It sees that x can be 1 or 2, concludes that id returns 1 or 2, and passes that result back to both call sites. It then reports that a may be 2, which no run produces. The analysis has followed an impossible path: into id from the first call and back out to the second. Such a path is called unrealizable.

A context-sensitive analysis keeps the facts for the two calls apart. It analyzes id once for the context “called from the first call site” and once for the context “called from the second call site”, and finds the exact answer: a is 1 and b is 2. The price is work. Every context the analysis distinguishes is one more analysis of the function, and the number of possible contexts grows very fast with the depth of the call chain. Each context-sensitive analysis therefore decides how much of the calling history to remember, and merges the contexts that differ only in what it forgets.

How it works

An analysis that follows calls has three parts.

  1. A call graph: a directed graph whose nodes are the functions, with an edge from function ff to function gg for each call site in ff that may call gg.

  2. A context abstraction: a rule that maps each way of reaching a function to one of finitely many contexts. Calls mapped to the same context share one analysis of the called function, so their facts are merged.

  3. A return rule: the facts at the called function’s exit, computed in the context that this call selects, become the facts after the call in this caller.

The common context abstractions are these.

Sharir and Pnueli described the two classical approaches in 1981: the call-string approach, and the functional approach, which computes a function’s effect as a mapping from entry facts to exit facts and applies that mapping at each call.

An interprocedural summary §15.14 records a function’s effect once, in terms of its inputs, so that each call site can apply it to its own facts. One common form is a precondition and a postcondition: what the function requires of its caller, and what it guarantees in return. The analysis checks the function’s body once against the pair, and checks each call site’s own facts against the precondition. A summary whose precondition relates several inputs to each other, such as “the offset plus the length is at most the size of the buffer”, keeps the precision of separate contexts without analyzing the function again. A helper contract §2.21, the stated requirements of a function that a checked program may call but whose code the checker does not analyze, is a summary of this kind.

Recursion makes the chain of call sites unbounded. Call-string analyses therefore keep only the last kk sites. Summary-based analyses compute the summary of a recursive function by repeating the analysis until the summary stops changing, which is a fixed point §3.22.

Each extra level of context multiplies the work. If every function is called from exactly 2 call sites and k=3k = 3, a function at the end of a chain of at least 3 calls can be reached by 2×2×2=82 \times 2 \times 2 = 8 different call strings, and the analysis may analyze it 8 times. This growth is one form of state explosion §3.26.

Worked example

A function read4(p, off) reads 4 bytes, starting off bytes after the start of the buffer that p points to. Let size\mathrm{size} be the length of that buffer in bytes and off\mathrm{off} the value of off. The read stays inside the buffer when off+4≤size\mathrm{off} + 4 \le \mathrm{size}. Two callers use the function.

A context-insensitive interval analysis §3.9, one that tracks each number as a range of possible values, merges the two callers. Writing [a,b][a, b] for the whole numbers from aa to bb, the analysis knows only size∈[4,16]\mathrm{size} \in [4, 16] and off∈[0,3]\mathrm{off} \in [0, 3]. The worst combination in these ranges is off=3\mathrm{off} = 3 with size=4\mathrm{size} = 4, and 3+4=7>43 + 4 = 7 > 4. The analysis cannot prove the read safe and reports a possible out-of-bounds read §4.5. That report is a false alarm §1.22: no caller passes this combination. The merge lost the link between the two numbers: the large offset comes only with the large buffer.

A context-sensitive analysis with k=1k = 1 analyzes read4 once in the context of caller A and once in the context of caller B, and proves both reads: 7≤167 \le 16 and 4≤44 \le 4. A relational summary reaches the same result with a single analysis of read4. Its precondition off+4≤size\mathrm{off} + 4 \le \mathrm{size} is checked at each call site with that caller’s own numbers, which are the same two checks.

Now add caller C, which passes a 2-byte buffer with off=0\mathrm{off} = 0. The check 0+4=4≤20 + 4 = 4 \le 2 is false: this read really runs 4−2=24 - 2 = 2 bytes past the end of the buffer. The context-sensitive analysis reports the read in the context of caller C and still proves the reads of callers A and B, so the report points at the call that is wrong.

Stated precisely

Let CC be a finite set of contexts. A context-sensitive analysis computes, for each function ff and each context c∈Cc \in C, an abstract state A(f,c)A(f, c): a description of every run of ff that the analysis maps to context cc. A selection rule gives the context of the called function: when call site ss runs in a caller analyzed in context cc, the called function is analyzed in context sel(c,s)\mathrm{sel}(c, s). For call strings of depth kk, a context is a list of at most kk call sites, and sel(c,s)\mathrm{sel}(c, s) is the last kk elements of the list cc followed by ss. A context-insensitive analysis is the case in which CC has exactly one element.

A path through several functions is realizable when every return goes back to the call site that made the matching call, the way each closing bracket in an arithmetic expression matches the latest unmatched opening bracket. The ideal result at a program point combines the facts along all realizable paths to that point. A context-insensitive analysis also combines facts along unrealizable paths, so its result is at best as precise as the ideal and usually less precise. Consider problems whose facts are subsets of a finite set and whose transfer functions, the functions that describe how each instruction changes the facts, distribute over union: applying one to the union of two sets gives the union of the two separate results. For these problems the functional approach computes the ideal result exactly, and the IFDS (interprocedural, finite, distributive, subset) algorithm §14.1 of Reps, Horwitz and Sagiv (1995) [257] does so in polynomial time.

Context sensitivity never makes an analysis sound by itself. The analysis keeps its soundness §3.7, meaning its result describes every real run, only when three conditions hold.

  1. Every real call, including calls through function pointers (variables that hold the address of a function) and calls from code outside the analyzed program, is mapped to some context.

  2. The facts for each context describe every run that is mapped to that context, including the runs that a limited kk merges into it.

  3. Every summary used in place of a function’s body describes every effect of that function: what the function writes, what it frees, and how it can fail.

Limits and common mistakes

Context sensitivity does not separate paths inside one function. Two branches inside read4 still merge where they meet; keeping such paths apart is path sensitivity §3.11. Flow sensitivity is a third, separate property: a flow-sensitive analysis keeps separate facts for each point inside a function, in the order of the instructions, while a flow-insensitive analysis keeps one set of facts for the whole function.

Limited contexts merge again. With k=1k = 1, if callers A and B both call read4 through the same wrapper function §14.27, both calls of read4 come from the single call site inside the wrapper. The two calls share one context, and the false alarm of the example returns. Depth k=2k = 2, or contexts made of entry facts, would separate them.

Callers that the analysis cannot see need a context of their own. A library function, an interrupt handler §6.12 or a callback §14.22 (a function handed to other code to be called later) can be entered from code outside the analysis. Such an entry needs a context that assumes nothing about the arguments, or a precondition that every outside caller is required to meet.

A wrong summary is wrong at every call. If a summary omits that the function frees its argument or writes past its end, every proof that relies on the summary is wrong, however many contexts the analysis keeps.

Context sensitivity removes false alarms; it never removes a real error. If one real context is unsafe, as the context of caller C is in the example, a sound analysis must still report it.

Questions answered

Which call contexts need to remain separate to prove a pointer valid?

Two calling contexts need to remain separate when each one alone lets the analysis prove the pointer valid but their merged facts do not. A pointer access is valid when the pointer is not a null pointer §4.26, the object it refers to is still alive, and the accessed bytes lie inside that object: the offset plus the access length is at most the object’s size. Calling contexts can differ in any of these facts: which object the pointer refers to, the object’s size or lifetime, whether the pointer can be null, the offset, and the length.

Merging two contexts is harmless when the merged facts still imply every condition. Merging breaks the proof when it loses a link between facts, such as which offset comes with which buffer size. For example, a 16-byte buffer read at offset 3 and a 4-byte buffer read at offset 0 are both safe 4-byte reads, since 3+4=7≤163 + 4 = 7 \le 16 and 0+4=4≤40 + 4 = 4 \le 4. Merged into ranges, offset 0 to 3 and size 4 to 16, the facts allow offset 3 in a 4-byte buffer, and 3+4=7>43 + 4 = 7 > 4, so the proof fails. Such calls need separate contexts, or a relational summary: a precondition, offset plus length at most size, that the analysis checks at each call site with that caller’s own values. A context in which the access really is unsafe must never be merged away; the analysis must report it.

Related entries: Helper contract (§2.21), Path sensitivity (§3.11), Alias analysis (§3.18), Interprocedural summary (§15.14), State explosion (§3.26). Further reading: [257].