GTIRB  v2.2.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 matplotlib.pyplot as plt
21 import networkx as nx
22 
23 import gtirb
24 
25 if len(sys.argv) < 2:
26  print(f"Usage: {sys.argv[0]} /path/to/file.gtirb")
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 nx.draw(G, with_labels=True)
40 plt.show()