TExcelTAD
Home › Reverse Engineering & Binary Analysis › Recovering Control Flow: a CFG in NetworkX

Recovering Control Flow: a CFG in NetworkX

A flat listing of thirty instructions with six jumps is hard to read; the same code drawn as boxes and arrows is easy. That drawing is a control-flow graph (CFG), and every serious RE tool builds one for each function: Ghidra's function graph, IDA's graph view, Binary Ninja's default view. Building one yourself from a disassembly listing takes about forty lines of Python, and it shows exactly how tools find loops, measure complexity and decide which code is reachable. Graph algorithms come from NetworkX, which runs in your browser here; the Graph Algorithms course explains dominators and cycles in depth.

Definitions

  • Basic block: a maximal run of instructions with one entry (the first) and one exit (the last): no jump lands in the middle, and only the last instruction jumps.
  • Leaders (first instructions of blocks): the function's first instruction, every jump target, and every instruction right after a jump or return.
  • Edges: from a block ending in a conditional jump to both its target and the next block (fall-through); an unconditional jmp has one edge; a ret has none; a call does not end a block (the function returns to the next instruction).
  • Dominator: block dd dominates block bb if every path from the entry to bb passes through dd.
  • Back edge: an edge b→hb \to h where hh dominates bb. It marks a loop; hh is the loop header.
  • Cyclomatic complexity of a connected CFG with EE edges and NN nodes, the number of linearly independent paths through it (and an upper bound on the test cases needed to cover every branch):
M=E−N+2M = E - N + 2

The listing

The session compiles a small function that counts passing scores and returns -1 on a negative score, and prints its disassembly. The Python below uses exactly this text as input.

bash · try it yourself
cat > grade.c <<'SRC'
int grade(const int *s, int n) {
    int pass = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] >= 50) pass++;
        else if (s[i] < 0) return -1;
    }
    return pass;
}
SRC
gcc -O1 -fcf-protection=none -c grade.c -o grade.o
objdump -d -M intel --no-show-raw-insn grade.o | grep -E '^\s+[0-9a-f]+:' | sed 's/^ *//'
0:	test   esi,esi
2:	jle    2e <grade+0x2e>
4:	mov    rax,rdi
7:	movsxd rsi,esi
a:	lea    rsi,[rdi+rsi*4]
e:	mov    ecx,0x0
13:	jmp    22 <grade+0x22>
15:	test   edx,edx
17:	js     35 <grade+0x35>
19:	add    rax,0x4
1d:	cmp    rax,rsi
20:	je     3a <grade+0x3a>
22:	mov    edx,DWORD PTR [rax]
24:	cmp    edx,0x31
27:	jle    15 <grade+0x15>
29:	add    ecx,0x1
2c:	jmp    19 <grade+0x19>
2e:	mov    ecx,0x0
33:	jmp    3a <grade+0x3a>
35:	mov    ecx,0xffffffff
3a:	mov    eax,ecx
3c:	ret

Building the CFG

python · try it yourself
import re
import networkx as nx

LISTING = """\
0:	test   esi,esi
2:	jle    2e <grade+0x2e>
4:	mov    rax,rdi
7:	movsxd rsi,esi
a:	lea    rsi,[rdi+rsi*4]
e:	mov    ecx,0x0
13:	jmp    22 <grade+0x22>
15:	test   edx,edx
17:	js     35 <grade+0x35>
19:	add    rax,0x4
1d:	cmp    rax,rsi
20:	je     3a <grade+0x3a>
22:	mov    edx,DWORD PTR [rax]
24:	cmp    edx,0x31
27:	jle    15 <grade+0x15>
29:	add    ecx,0x1
2c:	jmp    19 <grade+0x19>
2e:	mov    ecx,0x0
33:	jmp    3a <grade+0x3a>
35:	mov    ecx,0xffffffff
3a:	mov    eax,ecx
3c:	ret"""

insns = []
for line in LISTING.splitlines():
    addr, text = line.split(":", 1)
    mnem, _, ops = text.strip().partition(" ")
    insns.append((int(addr, 16), mnem, ops.strip()))

def target(ops):
    m = re.match(r"([0-9a-f]+) <", ops)
    return int(m.group(1), 16) if m else None

is_jump = lambda m: m.startswith("j")
leaders = {insns[0][0]}
for k, (addr, mnem, ops) in enumerate(insns):
    if is_jump(mnem) or mnem == "ret":
        if target(ops) is not None:
            leaders.add(target(ops))
        if k + 1 < len(insns):
            leaders.add(insns[k + 1][0])

blocks, current = {}, None
for addr, mnem, ops in insns:
    if addr in leaders:
        current = addr
        blocks[current] = []
    blocks[current].append((addr, mnem, ops))

G = nx.DiGraph()
starts = sorted(blocks)
for i, b in enumerate(starts):
    G.add_node(b)
    _, mnem, ops = blocks[b][-1]
    nxt = starts[i + 1] if i + 1 < len(starts) else None
    if mnem == "ret":
        continue
    if is_jump(mnem):
        G.add_edge(b, target(ops), kind="jump")
        if mnem != "jmp" and nxt is not None:
            G.add_edge(b, nxt, kind="fall")
    elif nxt is not None:
        G.add_edge(b, nxt, kind="fall")

print(f"{G.number_of_nodes()} basic blocks, {G.number_of_edges()} edges")
for b in starts:
    last = blocks[b][-1]
    succ = ", ".join(f"{s:#x} ({G.edges[b, s]['kind']})" for s in sorted(G.successors(b)))
    print(f"  block {b:#04x}: {len(blocks[b])} insns, ends with {last[1]:<4} -> {succ or 'exit'}")

M = G.number_of_edges() - G.number_of_nodes() + 2
print("cyclomatic complexity M = E - N + 2 =", M)

idom = nx.immediate_dominators(G, starts[0])
def dominates(d, b):
    while True:
        if b == d: return True
        if idom[b] == b: return False
        b = idom[b]
back = [(b, h) for b, h in G.edges if dominates(h, b)]
for b, h in back:
    body = {h} | {n for n in nx.ancestors(G, b) if dominates(h, n)} | {b}
    print(f"back edge {b:#x} -> {h:#x}: loop header {h:#x}, body {sorted(hex(n) for n in body)}")
print("exit blocks:", [hex(b) for b in starts if G.out_degree(b) == 0])
9 basic blocks, 12 edges
  block 0x00: 2 insns, ends with jle  -> 0x4 (fall), 0x2e (jump)
  block 0x04: 5 insns, ends with jmp  -> 0x22 (jump)
  block 0x15: 2 insns, ends with js   -> 0x19 (fall), 0x35 (jump)
  block 0x19: 3 insns, ends with je   -> 0x22 (fall), 0x3a (jump)
  block 0x22: 3 insns, ends with jle  -> 0x15 (jump), 0x29 (fall)
  block 0x29: 2 insns, ends with jmp  -> 0x19 (jump)
  block 0x2e: 2 insns, ends with jmp  -> 0x3a (jump)
  block 0x35: 1 insns, ends with mov  -> 0x3a (fall)
  block 0x3a: 2 insns, ends with ret  -> exit
cyclomatic complexity M = E - N + 2 = 5
back edge 0x19 -> 0x22: loop header 0x22, body ['0x15', '0x19', '0x22', '0x29']
exit blocks: ['0x3a']
0x0 n <= 0? 0x4 setup 0x2e pass = 0 0x22 s[i] <= 49? 0x29 pass++ 0x15 s[i] < 0? 0x19 next, end? 0x35 -1 0x3a return back edge

Nine blocks and twelve edges give M=12−9+2=5M = 12 - 9 + 2 = 5: four conditional jumps plus one. The dominator test finds exactly one back edge, from 0x19 to 0x22: block 0x22 (load s[i], compare with 49) is the loop header, and the loop body is the four blocks of the for. GCC put the loop test (0x19: advance the pointer, compare with the end) after the body and entered the loop with a jmp into the middle, at the header. Two blocks set the return value (0x2e for an empty array, 0x35 for -1) and join at 0x3a, the single exit.

How CFGs are used in detection and analysis

  • Function similarity: graph shapes (block counts, edges, loops) are features for matching functions across binaries: library identification, patch diffing (BinDiff matches functions partly by CFG structure) and malware family clustering.
  • Anomalies: a function whose blocks all lead to one dispatcher block with huge in-degree is control-flow flattening (Obfuscation); blocks unreachable from the entry may be dead code, data, or code reached only by computed jumps.
  • Vulnerability research: loops that copy from input with an exit condition depending on input data; paths from an input-reading block to a dangerous call (path finding with nx.all_simple_paths); coverage-guided fuzzers count edges of this graph.
  • Testing: MM is the number of tests needed to cover a basis set of paths, and an upper bound for covering every branch; high values point to code that deserves review.

How it goes wrong, and how to make it right

  • Indirect jumps (jmp rax) have no static target in the listing; the CFG is incomplete until the jump table is recovered (Compiled Control Flow).
  • Calls that don't return (exit, abort, __stack_chk_fail) would add a false fall-through edge; tools keep a list of non-returning functions.
  • Overlapping instructions and anti-disassembly break the leader computation; build CFGs from recursive descent, not from a linear listing of untrusted code.

Pitfalls

  • A call is not a block end in an intraprocedural CFG; it is an edge in the call graph, a different graph (nodes are functions).
  • Fall-through needs the next block in address order, which is why blocks are sorted by start address.
  • Several back edges to one header are one loop with several continue paths, not several loops.
  • Cyclomatic complexity counts paths in the graph, not in the source: an optimiser can raise or lower it.

Practice

1. Add a call to the listing in the middle of block 0x4. Does the number of blocks change?

No: in this CFG, a call doesn't end a basic block because execution continues at the next instruction.

2. What would $M$ be for a function with one if/else and no loops?

Four blocks (test, then, else, join) and four edges: M=4−4+2=2M = 4 - 4 + 2 = 2, one decision plus one.

3. Use NetworkX to list every path from the entry block to the block that returns -1. How many are there, ignoring loops?

list(nx.all_simple_paths(G, 0x0, 0x35)) gives one simple path: 0x0 -> 0x4 -> 0x22 -> 0x15 -> 0x35. Paths that go round the loop first repeat nodes, which simple paths exclude.

Test yourself

Which instructions start a new basic block?

  1. Only the first instruction of the function
  2. The first instruction, every jump target, and the instruction after a jump or return
  3. Every call
  4. Every mov

When is an edge b -> h a back edge?

  1. When h has a lower address than b
  2. When h dominates b
  3. When b ends with ret
  4. When it is a fall-through edge

The CFG of grade has 9 nodes and 12 edges. What is its cyclomatic complexity?

  1. 3
  2. 5
  3. 21
  4. 9

Why does an indirect jmp rax make a CFG incomplete?

  1. NetworkX can't handle it
  2. Its targets are not in the instruction, so they must be recovered from a jump table or by other analysis
  3. It is always a bug
  4. It ends the function