GTIRB  v2.1.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 gtirb
22 import networkx as nx
23 
24 if len(sys.argv) < 4:
25  print(f"Usage: {sys.argv[0]} /path/to/file.gtirb source target")
26  quit(1)
27 
28 ir = gtirb.ir.IR.load_protobuf(sys.argv[1])
29 G = nx.DiGraph()
30 
31 for edge in ir.cfg:
32  if isinstance(edge.target, gtirb.block.ProxyBlock):
33  # Represent ProxyBlocks (which don't have an address) with their UUID.
34  G.add_edge(edge.source.address, edge.target.uuid)
35  else:
36  G.add_edge(edge.source.address, edge.target.address)
37 
38 for path in nx.all_simple_paths(G, int(sys.argv[2]), int(sys.argv[3])):
39  print(path)