summaryrefslogtreecommitdiff
path: root/python/basic_blocks.py
blob: 74b1d3dd159fa8b893988cde56f37b182e675e44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/python
# -*- coding: utf-8 -*-


import argparse
import sys

# from pychrysalide.features import *
from pychrysalide.analysis.contents import FileContent
from pychrysalide.analysis import StudyProject
from pychrysalide.arch import ArchInstruction
from pychrysalide.core import wait_for_all_global_works


def link_type_to_str(t):

    links = [ getattr(ArchInstruction, a) for a in dir(ArchInstruction) if a.startswith('ILT_') ]

    return str(links[links.index(t)])[4:]


def show_block(blk, grp):

    first, last = blk.boundaries

    #misc = '*' if len(first.sources) == 0 else ' '

    misc = ' [%u]' % blk.rank

    print('%s Block @ 0x%x: %s - %s' % (misc, first.range.addr.phys, first.keyword, last.keyword), end='')

    for db, dt in blk.destinations:
        print('  |-> 0x%x (%s)' % (db.boundaries[0].range.addr.phys, link_type_to_str(dt)), end='')

    print()


if __name__ == '__main__':

    title = '%s - Show basic blocks of a given function.' % sys.argv[0]

    parser = argparse.ArgumentParser(description=title, add_help=False)

    parser.add_argument('-h', '--help', action='store_true', help='Display the command line options understood by %s.' % sys.argv[0])

    parser.add_argument('binfile', type=str, help='The object file to be examined')
    parser.add_argument('fname', type=str, help='The analyzed function to display')

    args = parser.parse_args()

    if args.help:
        parser.print_help()
        sys.exit(1)

    prj = StudyProject()

    cnt = FileContent(args.binfile)

    prj.discover(cnt)

    wait_for_all_global_works()

    binary = prj.contents[0]

    sym = binary.format.find_symbol_by_label(args.fname)

    if not(sym):
        print('Function "%s" not found!' % args.fname)
        sys.exit(1)

    for bb in sym.basic_blocks:
        show_block(bb, sym.basic_blocks)