GTIRB  v2.2.0
GrammaTech Intermediate Representation for Binaries
cfg-paths.py

Open an IR and print every path from some point to some other point.

1 #!/usr/bin/python
2 #
3 # An example program which opens an IR and prints all paths between
4 # two blocks.
5 #
6 # To run this example, do the following.
7 #
8 # 1. Install the gtirb package from Pypi.
9 #
10 # 2. Run ddisasm to disassemble a binary to GTIRB.
11 #
12 # $ echo 'main(){puts("hello world");}'|gcc -x c - -o /tmp/hello
13 # $ ddisasm /tmp/hello --ir /tmp/hello.gtirb
14 #
15 # 3. Execute the following command to run the program on the
16 # serialized GTIRB data.
17 #
18 # $ ./doc/examples/cfg-paths.py /tmp/hello.gtirb
19 import sys
20 
21 import networkx as nx
22 
23 import gtirb
24 
25 if len(sys.argv) < 4:
26  print(f"Usage: {sys.argv[0]} /path/to/file.gtirb source target")
27  quit(1)
28 
29 ir = gtirb.ir.IR.load_protobuf(sys.argv[1])
30 G = nx.DiGraph()
31 
32 for edge in ir.cfg:
33  if isinstance(edge.target, gtirb.block.ProxyBlock):
34  # Represent ProxyBlocks (which don't have an address) with their UUID.
35  G.add_edge(edge.source.address, edge.target.uuid)
36  else:
37  G.add_edge(edge.source.address, edge.target.address)
38 
39 for path in nx.all_simple_paths(G, int(sys.argv[2]), int(sys.argv[3])):
40  print(path)