about summary refs log tree commit diff stats
path: root/example/expression/expr_c.py
blob: 37c9f510d0d624e3341472f5bac882edfe159f6d (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
"""
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


"""
C manipulation example
"""

# Digest C information
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)
c_context = {ptr.name: ptr_rectangle}
mychandler = CHandler(types_mngr, C_types=c_context)

# 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