about summary refs log tree commit diff stats
path: root/example/expression/expr_c.py
blob: e2986c5501d3072aece6014f9f561a227f16c9be (plain) (blame)
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
"""
Parse C expression to access variables and retrieve information:
* Miasm expression to access this variable
* variable type
"""

from miasm2.core.ctypesmngr import CTypeStruct, CAstTypes, CTypePtr
from miasm2.arch.x86.ctype import CTypeAMD64_unk
from miasm2.core.objc import CTypesManagerNotPacked, CHandler
from miasm2.expression.expression import ExprId


def test():
    """
    C manipulation example
    """

    # Digest C informations
    text = """
    struct line {
            char color[20];
            int size;
    };

    struct rectangle {
            unsigned int width;
            unsigned int length;
            struct line* line;
    };
    """

    # Type manager for x86 64: structures not packed
    base_types = CTypeAMD64_unk()
    types_ast = CAstTypes()

    # Add C types definition
    types_ast.add_c_decl(text)

    types_mngr = CTypesManagerNotPacked(types_ast, base_types)

    # Create the ptr variable with type "struct rectangle*"
    ptr_rectangle = types_mngr.get_objc(CTypePtr(CTypeStruct('rectangle')))

    ptr = ExprId('ptr', 64)
    expr_types = {ptr.name: ptr_rectangle}

    mychandler = CHandler(types_mngr, expr_types)

    # Parse some C accesses
    c_acceses = ["ptr->width",
                 "ptr->length",
                 "ptr->line",
                 "ptr->line->color",
                 "ptr->line->color[3]",
                 "ptr->line->size"
                ]

    for c_str in c_acceses:
        expr = mychandler.c_to_expr(c_str)
        c_type = mychandler.c_to_type(c_str)
        print 'C access:', c_str
        print '\tExpr:', expr
        print '\tType:', c_type

if __name__ == '__main__':
    test()