GTIRB  v2.1.0
GrammaTech Intermediate Representation for Binaries
show-cfg.py

Open an IR and draw the CFG to the screen.

1 #!/usr/bin/python
2 #
3 # An example program which opens an IR and draws the CFG to the screen.
4 #
5 # To run this example, do the following.
6 #
7 # 1. Install the gtirb package from Pypi.
8 #
9 # 2. Run ddisasm to disassemble a binary to GTIRB.
10 #
11 # $ echo 'main(){puts("hello world");}'|gcc -x c - -o /tmp/hello
12 # $ ddisasm /tmp/hello --ir /tmp/hello.gtirb
13 #
14 # 3. Execute the following command to run the program on the
15 # serialized GTIRB data.
16 #
17 # $ ./doc/examples/show-cfg.py /tmp/hello.gtirb
18 import sys
19 
20 import gtirb
21 import matplotlib.pyplot as plt
22 import networkx as nx
23 
24 if len(sys.argv) < 2:
25  print(f"Usage: {sys.argv[0]} /path/to/file.gtirb")
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 nx.draw(G, with_labels=True)
39 plt.show()