Algorithmadvanced
IFDS framework
Also called IFDS, Reps-Horwitz-Sagiv algorithm.
Solves interprocedural, finite, distributive, subset problems exactly in O(E D^3) time by graph reachability on an exploded supergraph.
- Time
- O(E D^3) worst · averageΘ(N + E) best
- Space
- O(N D^2 + C D^2) extra
- Where
- C = the number of call sites; D = the largest number of facts of one procedure; E = the number of edges of the supergraph; N = the number of nodes of the supergraph
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
The IFDS framework of Reps, Horwitz and Sagiv solves a large class of interprocedural dataflow problems exactly. The class is in the name: Interprocedural, Finite, Distributive, Subset. The facts form a finite set , an analysis result at a point is a subset of , and every flow function distributes over union. Taint analysis, reaching definitions, possibly uninitialized variables and all gen-kill problems fit. The algorithm turns the problem into reachability in an exploded supergraph, which has one node for each pair of a program point and a fact. A fact holds at a point exactly when its node can be reached along a path whose calls and returns match. The tabulation algorithm finds these nodes with a worklist. It records path edges inside procedures and summary edges across calls, so it never walks through a procedure twice for the same fact. The answer is the meet over all valid paths, the best answer that ignores branch conditions, even with recursion. The time is , where is the number of edges of the supergraph.
In plain words
Many questions about a program are yes or no questions about a fixed list of facts, such as "this variable may hold a secret". IFDS answers them across procedure calls without mixing up the callers. It draws a big graph with one copy of every program point for each fact. An edge says that a fact at one point causes a fact at the next point. Then "does this fact hold here" becomes "can we walk to this node". The walk must leave each procedure back to the call it came in by. To avoid walking through a procedure again and again, the algorithm remembers, for each fact at the entry of a procedure, which facts come out at its exit. These shortcuts are the summary edges. The cost grows with the size of the program times the cube of the number of facts.
The problem
An IFDS instance is a supergraph with a finite set of facts for each procedure , a seed set , and a flow function for each edge with . The supergraph has the call edge, the return edge and the call-to-return edge of each call site, as on the interprocedural dataflow analysis page. The output is, for every node ,
where a path is valid when every return goes back to the call that its procedure was entered from. Sets of facts are ordered by , so union is the meet and is : this is the meet convention of Kildall, and the result is the greatest solution. In the join convention of Cousot the order flips, union is the join, and the same set is the least solution. A problem whose meet is intersection, such as available expressions, fits after a change to the complement facts, since the complement of a distributive intersection problem is a distributive union problem.
The implementation solves a taint problem on the toy IR. The question is which variables may depend on the first parameter of main. It follows data flow only, not branches.
| item | choice |
|---|---|
| facts of | the variables of , and RET for its return value |
| seed | the first parameter of main |
x = k |
kills x |
x = a |
a gives a and x; x itself dies unless it is a |
x = a op b |
each operand gives itself and x; x itself dies unless it is an operand |
ret a |
every fact stays; a also gives RET |
call edge of x = call q(a, b) |
an argument gives the parameters it is passed to |
| call-to-return edge | every fact of the caller stays, except x |
| return edge | RET gives x; nothing else crosses |
jump, br |
every fact stays |
The algorithm
The exploded supergraph. A distributive function on subsets is fixed by what it does to each single fact and to the empty set. So draw it as a bipartite graph on . The extra fact always holds. There is an edge , an edge for every that makes from nothing, and an edge for every . The facts reachable from are then , and composing two functions is joining their graphs end to end. The exploded supergraph puts these small graphs on every edge of . Its nodes are the pairs .
| flow function | edges out of |
|---|---|
| identity | for every |
kill x |
for ; no edge out of x |
gen x |
, plus the identity |
copy x = a |
a a, a x, for |
Tabulation. The algorithm does not build . It finds the reachable part with a worklist. A path edge says that can be reached from , the start of its own procedure, by a same-level path, which is a path whose calls all return inside it. A summary edge says that a call at with the fact can come back at the return site with the fact . Summary edges are found once per call site and used by every caller context that reaches the call with the same fact.
TABULATE(G*, F, S) F gives the flow of each edge one fact at a time; S is the seed set- 1
PathEdge ← ∅; WorkList ← []; Summary ← ∅; Through ← ∅ - 2
for each d in S ∪ {0} do PROPAGATE(s_main, d, d) - 3
while WorkList is not empty do - 4
(n, d1, d2) ← remove the first item of WorkList (n is in procedure p) - 5
if n is a call node c, with callee q and return site r then - 6
for each d3 in F_call(c)(d2) do PROPAGATE(s_q, d3, d3) - 7
for each d3 in F_c2r(c)(d2) ∪ Summary[c, d2] do PROPAGATE(r, d1, d3) - 8
else if n is the exit node e_p then - 9
for each call node c of p, with return site r, and each d5 in F_ret(c)(d2) do - 10
if (c, d1, d5) is in Through then skip it, else add it to Through - 11
for each d4 with d1 in F_call(c)(d4) do - 12
if d5 is not in Summary[c, d4] then add it - 13
for each d3 with (c, d3, d4) in PathEdge do PROPAGATE(r, d3, d5) - 14
else for each successor m of n and each d3 in F_(n,m)(d2) do PROPAGATE(m, d1, d3) - 15
return X, with X[n] = {d ≠ 0 : (n, d1, d) is in PathEdge for some d1} PROPAGATE(n, d1, d2)- 16
if (n, d1, d2) is not in PathEdge then add it to PathEdge and append it to WorkList
Line L6 starts the callee with a self loop, so the callee is analysed once per entry fact, not once per caller. Line L7 does two things. It carries the caller's facts around the call, and it reuses every summary that is already known. When a fact reaches the exit (L8 to L13), the algorithm turns it into summary edges at every call site of the procedure. It then extends every path edge that already reaches that call with the matching fact.
The set of line L10 is not in the pseudocode of the paper. Without it, a direct count of the exit case gives steps per call site. Line L13 needs, for each pair , the set of with a path edge to . The implementation keeps this index next to .
Example
This is the program of the interprocedural dataflow analysis page, in the toy IR. The seed is secret.
id(a): B0: ret a
main(secret): B0: x = call id(secret) c1
y = call id(0) c2, also the return site of c1
ret y the return site of c2
The worklist is a queue. The steps, with written as 0:
| step | item taken | new path edges and summary edges |
|---|---|---|
| L2 | , | |
| 1 | L6: . L7: | |
| 2 | L6: . L7: | |
| 3 | L14 through ret a: , |
|
| 4 | L6: none, the argument is a constant. L7: | |
| 5, 6 | , | , |
| 7 | none: the return edge passes only | |
| 8 | at : gives x, and came from secret. Summary , path edge . At : no fact of main gives , so no summary |
|
| 9, 10 | , | ; summaries and |
| 11 to 16 | the rest | from L7 at , then the exit of main |
In total there are 16 path edges, 3 summary edges and 24 flow steps.
The result is after each call, and y is never tainted. A context-insensitive analysis of the same supergraph lets RET flow from the exit of id to both return sites, so it reports y as tainted. The tabulation avoids this. A summary edge exists only at a call site whose own arguments reach the fact at the entry of id.
Correctness
The full proof is in the proof file. Its steps:
- One path, many facts. Following a path of the supergraph through the exploded graph from reaches exactly . The proof is an induction on the length of .
- MVP is reachability. Valid paths of are the valid paths of with a fact at each node. So exactly when a valid path reaches from a seed or from .
- Path edges and summary edges are sound. Each insertion extends a path that already exists by one edge or by a summary edge, and each summary edge is a call edge, a same-level path in the callee and the return edge of the same call site. The proof is an induction on the order of insertion.
- Path edges are complete. Every valid path to ends with a same-level part that starts at some , and is found. The proof is an induction on the length of the path. The hard case ends with a return edge. Then the summary edge is found at the exit, and it meets the path edge at the call either at L7 or at L13, whichever runs later.
- The result. Steps 3 and 4 show that the targets of the path edges are exactly the reachable nodes of . With step 2 this gives .
- Termination and cost. Each path edge enters the worklist once, and there are at most per node. The cost bound counts the work of each kind of node.
Proof: The tabulation algorithm computes the meet over all valid paths in O(E D^3) timefull
Setting. is the supergraph of the program, as on the page. Every procedure has a start node and an exit node . A call site has a call node and a return site , and three edges: the call edge , the return edge and the intraprocedural call-to-return edge . The facts of form a finite set , and . is a new fact that is in no . Every edge of has a flow function, given pointwise as a map from to subsets of with and for . It stands for the function
These functions are exactly the functions with : given such an , take and . For a path , , and the empty path gives the identity. is the set of seed facts at .
A path of is valid if its call and return edges, read as brackets and , form a prefix of a word in which every closes the last open . A path is same-level if it is valid and every is closed in it. A same-level path starts and ends in the same procedure. The meet over all valid paths is
Sets of facts are ordered by , so union is the meet and is , as in Kildall's convention. In Cousot's join convention the order flips and the same set is the least solution.
The exploded supergraph has a node for every node of in procedure and every . For every edge of and every , it has the edge of the same kind as . Valid and same-level paths of are defined by the same brackets.
We use the lines L1 to L16 of the pseudocode. A path edge stands for , where is the procedure of . A summary edge stands for . is the set of triples of line L10, and for the call edge of .
Lemma 1 (one path, many facts). For a path of from to and a set , the facts such that has a path that follows from some with to are exactly .
Proof. Induction on the length of . For both sides are . Let . By induction, the facts reached after are with . One more edge reaches . This contains , because , and without it is . So it is .
A path of is valid exactly when its shadow in is valid, since the brackets are the same. So Lemma 1 gives:
Corollary 2 (MVP is reachability). Let be the set of nodes of that a valid path reaches from some with . Then for every , if and only if .
Decomposition. Cut a valid path of from at its call edges that are never closed. The part after the last such call edge (or all of , if there is none) is a same-level path. It starts at , where is the procedure of the end of , and is or the target fact of that call edge. We call the entry fact of .
Let be the set of path edges at the end and the set of summary edges at the end.
Lemma 3 (path edges are sound). Every path edge that L16 inserts has a valid path of from some , , to whose entry fact is . Every summary edge that L12 inserts has a same-level path in .
Proof. Induction on the order of insertion. The claim for a path edge says: is reached by a valid path that is empty or ends with a call edge that is never closed, and a same-level path goes from to .
- L2 inserts with . Take the empty path.
- L6 inserts while it handles a path edge , with for the call edge. By induction, reaches . Add the call edge. It is never closed, so it is the last open call, and the new entry fact is . is now empty.
- L7 extends for by the call-to-return edge, which is intraprocedural, or by a summary edge from . By induction, the summary edge stands for a same-level path. Either way stays same-level and the entry fact stays .
- L14 extends by one intraprocedural edge.
- L13 inserts from a path edge and a new summary edge . Both are older, and the same argument as for L7 applies.
- L12 inserts when L10 meets a new triple . At that time a path edge exists with for the return edge of , and L11 chose with for the call edge of . By induction, for this path edge is a same-level path from to . The call edge, and the return edge of the same site form a same-level path.
Lemma 4 (path edges are complete). If a valid path of goes from some , , to and has the entry fact , then .
Proof. Strong induction on the number of edges of . Every path edge that L16 inserts is put on the worklist, and the loop runs until the worklist is empty (L3). So every path edge in is taken off once, at L4.
-
is empty. Then and , and L2 inserts the edge.
-
The last edge is a call edge from . The prefix is shorter and reaches with some entry fact , so . When it is taken off, L6 inserts , and .
-
The last edge is intraprocedural, from . The prefix is shorter and has the same entry fact , so . When it is taken off, L14 or (for a call-to-return edge) L7 inserts .
-
The last edge is a return edge of a call site . It must close an open call edge , so with same-level. The path is shorter and has the entry fact , so . The path is shorter and has the entry fact , since is same-level. So .
First, . When is taken off, L9 looks at the site and at for its return edge. If the triple is new, L11 runs over , which contains , and L12 inserts unless it is there already. If the triple is old, the run of L11 that added it did the same.
Next, the path edge was inserted at some time and taken off at a later time . The summary edge was inserted at a time . If , L7 sees the summary edge at . If , then is among the sources of at , and L13 uses it. One of the two holds, since . Either way is inserted.
Theorem (correctness). At the end, for every node , the set of line L15 is .
Proof. By Lemma 3, every path edge gives a valid path to , so . By the decomposition, every node of has a valid path with some entry fact, and Lemma 4 gives a path edge to it. So . Leave out and use Corollary 2.
Lemma 5 (termination). The algorithm stops.
Proof. L16 inserts each path edge at most once, and there are at most of them per node. So the loop of L3 runs at most times. Each run does a finite amount of work, since each set it loops over is finite.
Theorem (cost). Let be the number of nodes of , its number of edges, and the number of call sites. With hash sets of constant expected cost per operation, the algorithm runs in time and uses space.
Proof. Write . Each PROPAGATE is . Count the work by the kind of node that the taken-off path edge ends in. A node has at most path edges ending in it, and each is taken off once.
- An ordinary node with successors. Each path edge gives at most calls of PROPAGATE at L14. In total . The sum over all nodes is at most .
- A call node . Each path edge gives at most calls at L6, at L7 for the call-to-return edge, and at L7 for the summary edges, since has at most edges out of . In total per call site.
- An exit node . Each path edge and each call site of give at most tests at L10. In total per call site, since each call site calls one procedure. A triple passes L10 only once, there are at most of them per site, and each runs L11 over at most facts: per site. A summary edge is inserted at L12 only once, there are at most per site, and each runs L13 over at most sources: per site.
The set takes time per site to build. A call site has three edges in , so , and the total is , since . The path edges and their index of sources take space. The summary edges, the triples and the sets take per call site.
Without L10, the exit case would combine every path edge of with every and every source of . That is steps per call site in the worst case. The set of triples is what keeps this case at .
Complexity
- Ordinary nodes. A node has at most path edges. Each is taken once and gives at most new items per outgoing edge. Over all nodes this is .
- Call nodes. Each path edge gives at most items at L6 and L7, so per call site.
- Exit nodes. Each path edge gives at most tests at L10 per call site. Each new triple of runs over at most facts at L11, and each new summary edge over at most sources at L13. Each of these costs per call site.
- Total. time with hash sets. Space is for the path edges and for the summary edges, where is the number of call sites.
- Special cases. Reps, Horwitz and Sagiv also give smaller bounds for special classes. For a gen-kill problem every fact flows only to itself, so a node has path edges, and the time is . A flow function where each fact reaches only a few facts also costs less than per edge.
- Best case. Building the supergraph reads the whole program, , even when only the fact is ever reached.
The tables below are measured, not proved. The first has random modules of the toy IR with loops and recursion. f0 calls f1, each fi calls f(i+1) and one random procedure, and the seeds are both parameters of f0.
| procedures | variables | path edges | summary edges | flow steps | ms | ||||
|---|---|---|---|---|---|---|---|---|---|
| 4 | 4 | 133 | 155 | 15 | 413 | 8 | 466 | 634880 | 0.6 |
| 16 | 4 | 517 | 605 | 15 | 1785 | 46 | 2047 | 2478080 | 3.2 |
| 64 | 4 | 2036 | 2401 | 15 | 6155 | 161 | 7153 | 9834496 | 8.2 |
| 64 | 8 | 2321 | 2696 | 19 | 2546 | 128 | 3195 | 21568000 | 3.7 |
| 64 | 16 | 2752 | 3111 | 27 | 2917 | 128 | 3543 | 68292672 | 4.5 |
The taint dies quickly in these programs, because constants and loop counters overwrite it. So the work grows with the program and stays far below the bound. The second table is a worst case for the number of path edges. A procedure g with parameters mixes all of them in a loop, so every entry fact reaches every variable. main calls g twice.
| path edges | flow steps | ms | ||||||
|---|---|---|---|---|---|---|---|---|
| 4 | 12 | 15 | 5 | 167 | 432 | 217 | 3240 | 0.3 |
| 8 | 16 | 19 | 9 | 811 | 1600 | 937 | 19000 | 1.0 |
| 16 | 24 | 27 | 17 | 5075 | 7776 | 5449 | 157464 | 5.4 |
| 32 | 40 | 43 | 33 | 36259 | 46240 | 37513 | 1690072 | 39.1 |
Here the path edges come close to . The flow steps stay near the number of path edges, because a taint flow sends each fact to at most two facts. A problem whose flow functions send one fact to many facts pays the full factor on top.
Properties
- Exact. For a distributive problem the result is the meet over all valid paths, with and without recursion. Context-insensitive analysis can only be less precise.
- Order free. The set of path edges at the end does not depend on the order of the worklist.
- Per fact. Facts are tracked one at a time. The seeds give the union of the results for and for .
- Reuse. A procedure is analysed once per entry fact, and its summary edges serve every caller that reaches the call with that fact.
- Only what is reached. Procedures and facts that no valid path reaches cost nothing beyond building the supergraph.
Variants and improvements
- IDE. The IDE framework puts a function on values on each exploded edge. It solves environment problems such as linear constant propagation in the same time bound.
- Practical extensions. Naeem, Lhoták and Rodriguez build the supergraph on demand, return from the start procedure to all callers when a seed is not in
main, and avoid repeated work for facts that pass into a callee. - Solvers. Heros (Bodden 2012) is a generic multi-threaded solver for IFDS and IDE on Soot. FlowDroid (Arzt et al. 2014) runs taint analysis of Android apps as an IFDS problem, with access paths such as
x.f.gas facts, and adds an alias search on demand. - Demand queries. A query for one node and one fact can run the reachability backwards from that node, so only the part of the graph that can matter is explored.
- Other forms. The same problems are CFL-reachability problems over the language of matched calls and returns, see CFL-reachability. They are also reachability in a pushdown system, and Datalog programs can express the tabulation directly.
When to use it
Use IFDS when the facts are a finite set that you can list per procedure, every flow function is a union of effects of single facts, and you need precision across calls. Taint and information flow, uninitialized variables, interprocedural reaching definitions, and typestate with a small set of states are typical. If you need values, such as constants, use IDE. If the flow functions are not distributive, a functional approach with general summaries or context sensitivity with call strings is the choice.
Pitfalls
- Large fact sets. The bound has , and can be large. With access paths as facts, the number of facts grows quickly, so tools cut access paths at a fixed length.
- No . Without the fact , a fact that a statement makes from nothing never appears. Every edge must also map to , or whole regions of the graph go missing.
- Locals through the callee. The caller's locals belong on the call-to-return edge. If the call edge passes them into the callee, every callee must carry every caller local back, which costs more and can lose precision.
- Facts that need two inputs. A distributive function treats each fact alone. "x is constant if a and b are constant" needs two facts at once, and IFDS cannot express it. IDE cannot either, since
x = a + bis not distributive over its value lattice and IDE sendsxto . Use a non-distributive method. - Seeds outside main. If the analysis starts inside a procedure, the facts at its exit must return to every caller, with no matching call. Forgetting this loses results.
- Data flow only. The taint instance here does not follow branches. A secret that only decides which constant is stored does not taint the result.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ifds-framework/. The authors are listed in prov/K1QASX.jsonl.
"""The IFDS tabulation algorithm of Reps, Horwitz and Sagiv on the toy IR.
A module is a dict from procedure name to toyir.Program. Calls are
("call", x, f, args) instructions. The supergraph has one node per
instruction and one per terminator, as (proc, label, i), where i is the
index of the instruction in its block and i = len(instrs) is the
terminator. Each procedure also has an exit node (proc, EXIT, 0). A call
node c has three edges: to the start of the callee, from the exit of the
callee to the return site (the next node), and the call-to-return edge.
The problem solved here is "which variables may depend on the secret
inputs" (a taint analysis that follows data flow, not branches). It is a
distributive subset problem. The facts of a procedure are its variables
and the slot RET for its return value. ZERO is the extra fact that is
always present; it is the Lambda of the exploded supergraph.
ifds() returns, for every node, the set of facts that hold there on some
valid path from the start of main, and a Counter of the work done.
"""
from collections import Counter, deque
import toyir
ZERO = "0"
RET = "RET"
EXIT = "$exit"
class Supergraph:
"""The supergraph of a module and the flow functions of the problem."""
def __init__(self, module, main=None):
self.module = module
self.main = main if main is not None else next(iter(module))
self.facts = {}
self.start = {}
self.exit = {}
self.succ = {}
self.callee = {}
self.ret_site = {}
self.callers = {p: [] for p in module}
self.nodes = []
self.proc = {}
for p, prog in module.items():
names = set(prog.params)
for label, blk in prog.blocks.items():
for i, ins in enumerate(blk.instrs):
if ins[0] not in ("const", "copy", "op", "call"):
raise ValueError("unsupported instruction: %r" % (ins,))
names.add(ins[1])
names.update(toyir.uses(ins))
node = (p, label, i)
self.nodes.append(node)
if ins[0] == "call":
q = ins[2]
if q not in module:
raise ValueError("unknown procedure %r" % q)
if len(ins[3]) != len(module[q].params):
raise ValueError("wrong number of arguments for %r" % q)
self.callee[node] = q
self.ret_site[node] = (p, label, i + 1)
self.callers[q].append(node)
else:
self.succ[node] = [(p, label, i + 1)]
names.update(toyir.term_uses(blk.term))
tnode = (p, label, len(blk.instrs))
self.nodes.append(tnode)
if blk.term[0] == "ret":
self.succ[tnode] = [(p, EXIT, 0)]
else:
self.succ[tnode] = [(p, s, 0) for s in toyir.succs(prog, label)]
if RET in names or ZERO in names:
raise ValueError("reserved name used as a variable")
self.facts[p] = sorted(names) + [RET]
self.start[p] = (p, prog.entry, 0)
self.exit[p] = (p, EXIT, 0)
self.nodes.append(self.exit[p])
self.succ[self.exit[p]] = []
for n in self.nodes:
self.proc[n] = n[0]
def num_edges(self):
"""Edges of the supergraph: three per call site, the rest one each."""
return sum(len(v) for v in self.succ.values()) + 3 * len(self.callee)
def instr(self, n):
p, label, i = n
blk = self.module[p].blocks[label]
return blk.instrs[i] if i < len(blk.instrs) else blk.term
def normal_flow(self, n, m, d):
"""The facts at m that the fact d at n gives, for an edge n -> m that
is not a call edge (the successor m does not change the result)."""
if d == ZERO:
return (ZERO,)
ins = self.instr(n)
k = ins[0]
if k == "jump" or k == "br":
return (d,)
if k == "ret":
return (d, RET) if d == ins[1] else (d,)
x = ins[1]
if k == "const":
srcs = ()
elif k == "copy":
srcs = (ins[2],)
else:
srcs = (ins[3], ins[4])
out = []
if d != x:
out.append(d)
if d in srcs:
out.append(x)
return tuple(out)
def call_flow(self, c, d):
"""From the fact d before the call c to the facts at the callee start."""
if d == ZERO:
return (ZERO,)
ins = self.instr(c)
params = self.module[ins[2]].params
return tuple(params[j] for j, a in enumerate(ins[3]) if a == d)
def c2r_flow(self, c, d):
"""The call-to-return edge: the caller's facts, minus the target."""
if d == ZERO:
return (ZERO,)
return () if d == self.instr(c)[1] else (d,)
def ret_flow(self, c, d):
"""From the fact d at the callee exit to the facts at the return site."""
if d == ZERO:
return (ZERO,)
return (self.instr(c)[1],) if d == RET else ()
def ifds(sg, seeds=None):
"""Run the tabulation algorithm. seeds are the facts at the start of
main; the default is the first parameter of main. Returns (X, stats)."""
main = sg.main
if seeds is None:
seeds = [sg.module[main].params[0]]
stats = Counter()
path = set() # @line L1
sources = {} # (n, d2) -> the set of d1 with a path edge <s_p,d1> -> <n,d2>
summary = {} # (c, d4) -> the set of d5 with a summary edge <c,d4> -> <r,d5>
through = set() # (c, d1, d5): <s_q,d1> reaches <e_q,d2> and d5 is in ret_c(d2)
inv_call = {} # c -> d1 -> the d4 with d1 in call_c(d4)
for c in sg.callee:
inv = {}
for d4 in sg.facts[sg.proc[c]] + [ZERO]:
for d1 in sg.call_flow(c, d4):
inv.setdefault(d1, []).append(d4)
inv_call[c] = inv
work = deque()
def propagate(d1, n, d2):
key = (n, d1, d2)
if key not in path: # @line L16
path.add(key)
sources.setdefault((n, d2), set()).add(d1)
work.append(key)
stats["path_edges"] += 1
s_main = sg.start[main]
for d in list(seeds) + [ZERO]: # @line L2
propagate(d, s_main, d)
while work: # @line L3
n, d1, d2 = work.popleft() # @line L4
stats["pops"] += 1
p = sg.proc[n]
if n in sg.callee: # @line L5
c, q, r = n, sg.callee[n], sg.ret_site[n]
for d3 in sg.call_flow(c, d2): # @line L6
stats["flow"] += 1
propagate(d3, sg.start[q], d3)
for d3 in sg.c2r_flow(c, d2): # @line L7
stats["flow"] += 1
propagate(d1, r, d3)
for d3 in list(summary.get((c, d2), ())):
stats["flow"] += 1
propagate(d1, r, d3)
elif n == sg.exit[p]: # @line L8
for c in sg.callers[p]: # @line L9
r = sg.ret_site[c]
for d5 in sg.ret_flow(c, d2):
stats["flow"] += 1
if (c, d1, d5) in through: # @line L10
continue
through.add((c, d1, d5))
for d4 in inv_call[c].get(d1, ()): # @line L11
stats["flow"] += 1
sset = summary.setdefault((c, d4), set())
if d5 in sset:
continue
sset.add(d5) # @line L12
stats["summary_edges"] += 1
for d3 in list(sources.get((c, d4), ())): # @line L13
stats["flow"] += 1
propagate(d3, r, d5)
else:
for m in sg.succ[n]: # @line L14
for d3 in sg.normal_flow(n, m, d2):
stats["flow"] += 1
propagate(d1, m, d3)
X = {n: set() for n in sg.nodes} # @line L15
for n, _d1, d2 in path:
if d2 != ZERO:
X[n].add(d2)
return X, stats
def ifds_framework(module, main=None, seeds=None):
"""Convenience wrapper: the facts at every node of the module."""
sg = Supergraph(module, main)
X, _ = ifds(sg, seeds)
return X
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_ifds_framework.py 378 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ifds-framework/. The authors are listed in prov/K1QASX.jsonl.
import random
import toyir
from toyir import parse, random_program
from ifds_framework import EXIT, RET, ZERO, Supergraph, ifds, ifds_framework
# The example of the page: id is called twice, once with the secret and
# once with a constant. Only the first result may depend on the secret.
ID = """
# params: a
B0:
ret a
"""
MAIN = """
# params: secret
B0:
x = call id(secret)
y = call id(0)
ret y
"""
def id_module():
return {"main": parse(MAIN), "id": parse(ID)}
# ------------------------------------------------------------ brute force
def apply(fn, facts):
"""Apply a flow function given pointwise to a set of facts. ZERO is
always in the set, as on every path of the exploded supergraph."""
out = {ZERO}
for d in facts:
out.update(fn(d))
return frozenset(out)
def mvp_by_paths(sg, seeds, cap=20000, max_depth=None):
"""The meet over all valid paths, by walking every valid path from the
start of main one by one. A path is a list of nodes; its state is the
set of facts and the stack of open calls. At a call node the path
either enters the callee or takes the call-to-return edge. At an exit
it returns to the call on top of the stack. The result at a node is the
union of the facts at the node over all paths that reach it. Returns
None when more than cap steps are needed. With max_depth, calls deeper
than that are not entered, which gives a subset of the valid paths."""
M = {n: set() for n in sg.nodes}
start = (sg.start[sg.main], frozenset(list(seeds) + [ZERO]), ())
todo = [start]
steps = 0
while todo:
n, facts, stack = todo.pop()
steps += 1
if steps > cap:
return None
M[n].update(facts)
if n in sg.callee:
q = sg.callee[n]
if max_depth is None or len(stack) < max_depth:
todo.append((sg.start[q], apply(lambda d: sg.call_flow(n, d), facts), stack + (n,)))
todo.append((sg.ret_site[n], apply(lambda d: sg.c2r_flow(n, d), facts), stack))
elif n[1] == EXIT:
if stack:
c = stack[-1]
todo.append((sg.ret_site[c], apply(lambda d: sg.ret_flow(c, d), facts), stack[:-1]))
else:
for m in sg.succ[n]:
todo.append((m, apply(lambda d: sg.normal_flow(n, m, d), facts), stack))
for n in M:
M[n].discard(ZERO)
return M
def mfp_supergraph(sg, seeds):
"""The context-insensitive solution: the supergraph is one big graph,
and every exit flows back to every caller."""
IN = {n: set() for n in sg.nodes}
IN[sg.start[sg.main]] = set(seeds)
work = list(sg.nodes)
queued = set(work)
def add(m, facts):
if not facts <= IN[m]:
IN[m] |= facts
if m not in queued:
queued.add(m)
work.append(m)
while work:
n = work.pop()
queued.discard(n)
X = IN[n]
if n in sg.callee:
q = sg.callee[n]
add(sg.start[q], set(apply(lambda d: sg.call_flow(n, d), X)) - {ZERO})
add(sg.ret_site[n], set(apply(lambda d: sg.c2r_flow(n, d), X)) - {ZERO})
out = set(apply(lambda d: sg.ret_flow(n, d), IN[sg.exit[q]])) - {ZERO}
add(sg.ret_site[n], out)
elif n[1] == EXIT:
for c in sg.callers[n[0]]:
out = set(apply(lambda d: sg.ret_flow(c, d), X)) - {ZERO}
add(sg.ret_site[c], out)
else:
for m in sg.succ[n]:
add(m, set(apply(lambda d: sg.normal_flow(n, m, d), X)) - {ZERO})
return IN
# ------------------------------------------------------- tainted execution
class Frame:
def __init__(self, p, env, taint):
self.p = p
self.env = env
self.taint = taint
self.label = None
self.pc = 0
self.dest = None
def run_tainted(module, main, args, tainted, fuel=3000):
"""Run the module and track which values depend on the tainted
arguments, following data flow only. Returns the outcome, in the form
of toyir.run, and the list of (node, tainted facts) seen before each
node runs. The fuel is counted as in toyir.run."""
seen = []
prog = module[main]
fr = Frame(main, dict(zip(prog.params, args)), {x for x, t in zip(prog.params, tainted) if t})
fr.label = prog.entry
stack = []
def val(fr, a):
if isinstance(a, int):
return a, False
return fr.env[a], a in fr.taint
def tick():
nonlocal fuel
if fuel <= 0:
raise toyir._Fuel()
fuel -= 1
try:
while True:
blk = module[fr.p].blocks[fr.label]
called = False
while fr.pc < len(blk.instrs):
ins = blk.instrs[fr.pc]
seen.append(((fr.p, fr.label, fr.pc), frozenset(fr.taint)))
tick()
k, x = ins[0], ins[1]
if k == "const":
v, t = ins[2], False
elif k == "copy":
v, t = val(fr, ins[2])
elif k == "op":
a, ta = val(fr, ins[3])
b, tb = val(fr, ins[4])
v, t = toyir._binop(ins[2], a, b), ta or tb
else:
vals = [val(fr, a) for a in ins[3]]
q = module[ins[2]]
fr.dest = x
fr.pc += 1
stack.append(fr)
env = {pn: v for pn, (v, _t) in zip(q.params, vals)}
taint = {pn for pn, (_v, t) in zip(q.params, vals) if t}
fr = Frame(ins[2], env, taint)
fr.label = q.entry
called = True
break
fr.env[x] = v
if t:
fr.taint.add(x)
else:
fr.taint.discard(x)
fr.pc += 1
if called:
continue
seen.append(((fr.p, fr.label, len(blk.instrs)), frozenset(fr.taint)))
tick()
term = blk.term
if term[0] == "jump":
fr.label, fr.pc = term[1], 0
continue
if term[0] == "br":
v, _t = val(fr, term[1])
fr.label, fr.pc = (term[2] if v != 0 else term[3]), 0
continue
v, t = val(fr, term[1])
seen.append(((fr.p, EXIT, 0), frozenset(fr.taint | ({RET} if t else set()))))
if not stack:
return ("ret", v), seen
fr = stack.pop()
fr.env[fr.dest] = v
if t:
fr.taint.add(fr.dest)
else:
fr.taint.discard(fr.dest)
except toyir._Trap:
return ("trap",), seen
except toyir._Fuel:
return ("fuel",), seen
# ---------------------------------------------------------- random modules
def random_module(rng, recursive=False):
"""Three procedures f0, f1 and f2 from random_program, with two to four
calls x = call fj(a, b) added. Without recursion, fi only calls fj with
j > i. A call in B0 goes after the constants that start B0, so every
name is defined before it is read."""
names = ["f0", "f1", "f2"]
module = {}
for f in names:
module[f] = random_program(rng, 4, rng.randint(2, 4), True)
xs = ["x%d" % i for i in range(4)]
for _ in range(rng.randint(2, 4)):
i = rng.randrange(0, 3 if recursive else 2)
j = rng.randrange(0, 3) if recursive else rng.randrange(i + 1, 3)
prog = module[names[i]]
label = rng.choice(list(prog.blocks))
instrs = prog.blocks[label].instrs
lo = 2 if label == prog.entry else 0
pos = rng.randint(lo, len(instrs))
args = [rng.choice(xs) if rng.random() < 0.85 else rng.randint(0, 5) for _ in range(2)]
instrs.insert(pos, ("call", rng.choice(xs), names[j], args))
return module
def bound_checks(sg, stats):
D1 = max(len(f) for f in sg.facts.values()) + 1
N = len(sg.nodes)
E = sg.num_edges()
assert stats["path_edges"] <= N * D1 * D1
assert stats["pops"] == stats["path_edges"]
assert stats["summary_edges"] <= len(sg.callee) * D1 * D1
assert stats["flow"] <= 3 * E * D1 ** 3
def arg_lists(rng):
out = [[0, 0], [1, 2], [-3, 7]]
for _ in range(3):
out.append([rng.randint(-6, 9), rng.randint(-6, 9)])
return out
# ------------------------------------------------------------------- tests
def test_id_example() -> None:
module = id_module()
sg = Supergraph(module, "main")
X, stats = ifds(sg)
assert X[("id", "B0", 0)] == {"a"}
assert X[("id", EXIT, 0)] == {"a", RET}
assert X[("main", "B0", 1)] == {"secret", "x"}
assert X[("main", "B0", 2)] == {"secret", "x"}
assert X[("main", EXIT, 0)] == {"secret", "x"}
# The context-insensitive solution leaks the secret into y.
MFP = mfp_supergraph(sg, ["secret"])
assert MFP[("main", "B0", 2)] == {"secret", "x", "y"}
assert MFP[("main", EXIT, 0)] == {"secret", "x", "y", RET}
assert mvp_by_paths(sg, ["secret"]) == X
# Summary edges: secret to x and ZERO to ZERO at s1, and only ZERO to
# ZERO at s2, since the argument of s2 is a constant.
assert stats["summary_edges"] == 3
bound_checks(sg, stats)
assert run_tainted(module, "main", [5], [True])[0] == ("ret", 0)
def test_wrapper_chain() -> None:
# The secret goes in through two levels of calls and comes back only on
# the path where it went in.
inner = parse("# params: a, b\nB0:\n t = a + 1\n ret t\n")
outer = parse("# params: u, v\nB0:\n r = call inner(u, v)\n s = call inner(v, u)\n ret r\n")
main = parse("# params: p, q\nB0:\n m = call outer(p, q)\n n = call outer(q, p)\n ret n\n")
module = {"main": main, "outer": outer, "inner": inner}
X = ifds_framework(module, "main", ["p"])
assert X[("main", "B0", 1)] == {"p", "m"}
assert X[("main", EXIT, 0)] == {"p", "m"}
assert X[("outer", "B0", 1)] == {"u", "v", "r"}
assert X[("outer", "B0", 2)] == {"u", "v", "r", "s"}
sg = Supergraph(module, "main")
assert mvp_by_paths(sg, ["p"]) == X
MFP = mfp_supergraph(sg, ["p"])
assert "n" in MFP[("main", EXIT, 0)]
def test_random_acyclic_modules() -> None:
rng = random.Random(4101)
compared = strict = runs = 0
for _ in range(400):
module = random_module(rng)
sg = Supergraph(module, "f0")
X, stats = ifds(sg)
bound_checks(sg, stats)
M = mvp_by_paths(sg, ["x0"])
if M is not None:
compared += 1
assert X == M
MFP = mfp_supergraph(sg, ["x0"])
assert all(X[n] <= MFP[n] for n in sg.nodes)
if any(X[n] != MFP[n] for n in sg.nodes):
strict += 1
for args in arg_lists(rng):
out, seen = run_tainted(module, "f0", args, [True, False])
assert out == toyir.run(module["f0"], args, fuel=3000, funcs=module)
runs += 1
for n, t in seen:
assert t <= X[n], (n, t, X[n])
assert compared >= 380
assert strict >= 15
assert runs == 2400
def test_random_recursive_modules() -> None:
rng = random.Random(4102)
for _ in range(150):
module = random_module(rng, recursive=True)
sg = Supergraph(module, "f0")
X, stats = ifds(sg)
bound_checks(sg, stats)
MFP = mfp_supergraph(sg, ["x0"])
assert all(X[n] <= MFP[n] for n in sg.nodes)
# Valid paths with at most three open calls are a subset of all
# valid paths, so their union must be inside the result.
M = mvp_by_paths(sg, ["x0"], cap=20000, max_depth=3)
if M is not None:
assert all(M[n] <= X[n] for n in sg.nodes)
for args in arg_lists(rng):
out, seen = run_tainted(module, "f0", args, [True, False], fuel=400)
assert out == toyir.run(module["f0"], args, fuel=400, funcs=module)
for n, t in seen:
assert t <= X[n]
def test_seeds_and_zero() -> None:
# With no seed, nothing is tainted, but ZERO still reaches every node
# that some valid path reaches.
module = id_module()
sg = Supergraph(module, "main")
X, stats = ifds(sg, seeds=[])
assert all(not v for v in X.values())
assert stats["path_edges"] == len(sg.nodes)
# Both parameters as seeds: the union of the two single-seed results.
rng = random.Random(4103)
for _ in range(60):
module = random_module(rng)
sg = Supergraph(module, "f0")
A, _ = ifds(sg, ["x0"])
B, _ = ifds(sg, ["x1"])
AB, _ = ifds(sg, ["x0", "x1"])
assert all(AB[n] == A[n] | B[n] for n in sg.nodes)
def test_bad_input() -> None:
bad = {"main": parse("# params: a\nB0:\n x = call nope(a)\n ret x\n")}
try:
Supergraph(bad)
except ValueError:
pass
else:
raise AssertionError("unknown callee accepted")
bad = {"main": parse("# params: a\nB0:\n RET = a\n ret a\n")}
try:
Supergraph(bad)
except ValueError:
pass
else:
raise AssertionError("reserved name accepted")
History
Sharir and Pnueli (1981) defined the meet over valid paths and the functional approach, which computes the effect of each procedure as a function. Knoop and Steffen (1992) proved the interprocedural coincidence theorem for distributive problems. Horwitz, Reps and Binkley (1990) had already used summary edges at call sites for interprocedural slicing. Reps, Horwitz and Sagiv (POPL 1995) combined these ideas. They noted that a distributive function on a finite set of facts is a small graph, so the functional approach becomes reachability in an exploded supergraph, and they gave the tabulation algorithm with its bound. Sagiv, Reps and Horwitz (1996) extended it to IDE. Reps (1998) presented both as CFL-reachability. Naeem, Lhoták and Rodriguez (2010) made the algorithm practical for large programs. The Heros solver (2012) and FlowDroid (2014) brought it into wide use for Java and Android.
References
- Thomas Reps, Susan Horwitz and Mooly Sagiv, Precise interprocedural dataflow analysis via graph reachability, Proceedings of the 22nd ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL '95), 49 to 61, 1995, the IFDS problem, the exploded supergraph, the tabulation algorithm with path edges and summary edges, and its O(E D^3) bound
- Mooly Sagiv, Thomas Reps and Susan Horwitz, Precise interprocedural dataflow analysis with applications to constant propagation, Theoretical Computer Science 167(1-2), 131 to 170, 1996, the IDE generalization, where the edges of the exploded supergraph carry functions on values
- Thomas Reps, Program analysis via graph reachability, Information and Software Technology 40(11-12), 701 to 726, 1998, IFDS as an instance of CFL-reachability, and its relation to interprocedural slicing
- Susan Horwitz, Thomas Reps and David Binkley, Interprocedural slicing using dependence graphs, ACM Transactions on Programming Languages and Systems 12(1), 26 to 60, 1990, summary edges at call sites, the earlier form of the same idea for slicing
- Nomair A. Naeem, Ondřej Lhoták and Jonathan Rodriguez, Practical extensions to the IFDS algorithm, Compiler Construction (CC 2010), Lecture Notes in Computer Science, 124 to 144, 2010, the supergraph built on demand, unbalanced returns, and faster handling of flows into callees
- Eric Bodden, Inter-procedural data-flow analysis with IFDS/IDE and Soot, Proceedings of the ACM SIGPLAN International Workshop on State of the Art in Java Program Analysis (SOAP '12), 3 to 8, 2012, the Heros solver, a generic IFDS and IDE solver with multi-threading
- Steven Arzt, Siegfried Rasthofer, Christian Fritz, Eric Bodden, Alexandre Bartel, Jacques Klein, Yves Le Traon, Damien Octeau and Patrick McDaniel, FlowDroid: precise context, flow, field, object-sensitive and lifecycle-aware taint analysis for Android apps, Proceedings of the 35th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI '14), 259 to 269, 2014, taint analysis as an IFDS problem with access paths as facts
- Micha Sharir and Amir Pnueli, Two approaches to interprocedural data flow analysis, in Steven S. Muchnick and Neil D. Jones (eds.), Program Flow Analysis: Theory and Applications, Prentice-Hall, 1981, the meet over valid paths and the functional approach that the tabulation algorithm makes concrete
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag K1QASX Edit this page History Report an error Markdown