def walk(self, node, parent=None):
        if isinstance(node, list):
            for idx, listitem in enumerate(node):
                self.walk(listitem, parent)

                if isinstance(listitem, ast2.Statement) and isinstance(
                        parent, ast2.If):
                    myif = parent
                    call = listitem.expr
                    if isinstance(call, ast2.Call):
                        if isinstance(call.func, ast2.Name):
                            if call.func.id == "_dispatch_once":
                                decl = ast2.Declaration(
                                    typename="static dispatch_once_t",
                                    name="onceToken")
                                args = [
                                    ast2.AddressOf(variable=ast2.Name(
                                        id="onceToken")),
                                    call.args[1],
                                ]
                                call = ast2.Statement(
                                    expr=ast2.Call(func=ast2.Name(
                                        id="dispatch_once"),
                                                   args=args))
                                node[:] = [decl, call]
                                parent.test = ast2.Num(n=1)
                                break

        elif isinstance(node, _ast.AST):
            for field in node.__class__._fields:
                subnode = getattr(node, field)
                self.walk(subnode, node)
Exemple #2
0
    def rewrite(self):
        self.process_block_to_be_embedded(self.ast.root)

        # Find captures
        cond = ast2.Assign(targets=[
            ast2.FieldAccess(object=ast2.Name("block_literal"), field=Any())
        ],
                           value=Any(),
                           decltype=None)
        result = AstMatcher().replace(self.ast.root, cond,
                                      self.callback_find_captures)

        # Replace block literal with ^{ ... }
        self.did_replace = False
        cond = ast2.AddressOf(variable=ast2.Name("block_literal"))
        result = AstMatcher().replace(self.ast.root, cond, self.callback)

        # bind captures
        if self.did_replace:
            cond = ast2.Assign(targets=[
                ast2.FieldAccess(object=ast2.Name("block_literal"),
                                 field=Any())
            ],
                               value=Any(),
                               decltype=None)
            result = AstMatcher().replace(self.ast.root, cond, self.callback2)

        # remove block_literal
        cond = ast2.Declaration(typename=Any(), name="block_literal")
        result = AstMatcher().replace(self.ast.root, cond,
                                      self.callback_remove_decl)
Exemple #3
0
    def get_variable(self, register):
        n = register.name
        if n in self.parameter_names:
            n = self.parameter_names[n]

        if n not in self.locals:
            self.locals[n] = ast2.Declaration(self.type_for_register(n), n)
        return ast2.Name(n)
Exemple #4
0
    def convert(self):
        cfg = self.func.ufunction.cfg
        assert(len(cfg.unassigned_bbs_with_cfg_roots) == 1)
        cfg_root = cfg.unassigned_bbs_with_cfg_roots[0]

        converter = UCodeConverter(self.func)

        # Add inputs as locals
        for (idx, p) in enumerate(self.func.ufunction.input_parameters):
            t = None
            if idx in self.func.parameters:
                t = self.func.parameters[idx].type
            converter.declare_argument(p.register, t)

        walker = CFGWalker(converter)
        ast_body = walker.visit(cfg_root)

        ast_body = [l for l in list(converter.locals.values()) if l is not None] + ast_body

        #f = FunctionDef('a', None, ast_body, [])
        #print ast.dump(f)

        from analysis.binary import ObjCMethod

        returntype = self.func.returns.type

        if self.func.method is not None:
            args = [ast2.Declaration(typename=self.func.parameters[idx + 2].type.name, name=p.name) for (idx, p) in
                    enumerate(self.func.ufunction.input_parameters[2:])]
            classname = self.func.method.cls.name
            selector = self.func.method.name
            static = self.func.method.method_type == ObjCMethod.METHOD_TYPE_CLASS
            f = ast2.ObjCFunctionDef(classname=classname, selector=selector, args=args, body=ast_body, static=static, returntype=returntype)
        else:
            args = [ast2.Declaration(typename="long", name=p.name) for (idx, p) in
                    enumerate(self.func.ufunction.input_parameters[0:])]
            f = ast2.CFunctionDef(name=self.func.name, args=args, body=ast_body, returntype=returntype)

        return f, converter.globals
Exemple #5
0
 def convert1(self, o):
     c = self.convert1
     if isinstance(o, UCodeAdd):
         return ast2.Assign(targets=[c(o.destination())], value=ast2.BinOp(c(o.source1()), ast2.Add(), c(o.source2())), decltype=None)
     elif isinstance(o, UCodeRet):
         if len(o.operands) == 0:
             return ast2.Return(None)
         else:
             assert(len(o.operands) == 1)
             return ast2.Return(c(o.operands[0]))
     elif isinstance(o, UCodeCall):
         call = ast2.Call(c(o.callee()), [c(p) for p in o.params()])
         if o.has_destination:
             return ast2.Assign(targets=[c(o.destination())], value=call, decltype=None)
         else:
             return ast2.Statement(expr=call)
     elif isinstance(o, UCodeMov):
         return ast2.Assign(targets=[c(o.destination())], value=c(o.source()), decltype=None)
     elif isinstance(o, UCodeRegister):
         return self.get_variable(o)
     elif isinstance(o, UCodeStore):
         deref = ast2.Dereference(c(o.pointer()))
         return ast2.Assign(targets=[deref], value=c(o.source()), decltype=None)
     elif isinstance(o, UCodeLoad):
         deref = ast2.Dereference(c(o.pointer()))
         return ast2.Assign(targets=[c(o.destination())], value=deref, decltype=None)
     elif isinstance(o, UCodeAddressOfLocal):
         return ast2.Assign(targets=[c(o.destination())], value=ast2.AddressOf(variable=c(o.source())), decltype=None)
     elif isinstance(o, UCodeSetMember):
         field = "off_%x" % o.offset()
         target = ast2.FieldAccess(object=c(o.destination()), field=field)
         return ast2.Assign(targets=[target], value=c(o.value()), decltype=None)
     elif isinstance(o, UCodeGetMember):
         field = "off_%x" % o.offset()
         value = ast2.FieldAccess(object=c(o.value()), field=field)
         return ast2.Assign(targets=[c(o.destination())], value=value, decltype=None)
     elif isinstance(o, UCodeBranch):
         return ast2.Statement(c(o.condition()))
     elif isinstance(o, UCodeSetFlag):
         if o.type == UCodeSetFlag.TYPE_ZERO and o.operation == UCodeSetFlag.OPERATION_SUB:
             comparison = ast2.Equals(left=c(o.source1()), right=c(o.source2()))
         elif o.type == UCodeSetFlag.TYPE_ZERO and o.operation == UCodeSetFlag.OPERATION_AND:
             comparison = ast2.BinOp(left=c(o.source1()), op=ast2.And(), right=c(o.source2()))
         elif o.type == UCodeSetFlag.TYPE_CARRY and o.operation == UCodeSetFlag.OPERATION_SUB:
             comparison = ast2.BinOp(left=c(o.source1()), op=ast2.Gt(), right=c(o.source2()))
         else:
             comparison = ast2.Todo(str(o))
         target = c(o.destination())
         return ast2.Assign(targets=[target], value=comparison, decltype=None)
     elif isinstance(o, UCodeNeg):
         target = c(o.destination())
         value = ast2.Negation(value=c(o.source1()))
         return ast2.Assign(targets=[target], value=value, decltype=None)
     elif isinstance(o, UCodeTruncate) or isinstance(o, UCodeExtend):
         target = c(o.destination())
         value = c(o.source())
         return ast2.Assign(targets=[target], value=value, decltype=None)
     elif isinstance(o, UCodeArithmeticOperation):
         target = c(o.destination())
         mnem_to_op = {"uADD": ast2.Add, "uSUB": ast2.Sub, "uMUL": ast2.Mult, "uDIV": ast2.Div, "uMOD": ast2.Mod,
                       "uAND": ast2.And, "uOR": ast2.Or, "uXOR": ast2.Xor, "uSHL": ast2.Shl, "uSHR": ast2.Shr}
         op = mnem_to_op[o.mnem()]()
         value = ast2.BinOp(left=c(o.source1()), op=op, right=c(o.source2()))
         return ast2.Assign(targets=[target], value=value, decltype=None)
     elif isinstance(o, UCodeInstruction):
         return ast2.Statement(ast2.Todo(str(o)))  # TODO
     elif isinstance(o, UCodeConstant):
         if not o.name:
             return ast2.Num(n=o.value)
         if o.name.startswith("_OBJC_CFSTRING_$_"):
             if o.value in self.func.binary.cfstrings:
                 return ast2.ObjCString(value=self.func.binary.cfstrings[o.value].string)
         if o.name.startswith("_OBJC_SELECTOR_$_"):
             return ast2.ObjCSelector(value=o.name.replace("_OBJC_SELECTOR_$_", ""))
         if o.name not in self.globals:
             self.globals[o.name] = ast2.Declaration("long", o.name)
         return ast2.Name(o.name)
     else:
         return ast2.Todo(str(o))  # TODO
    def rewrite(self):
        self.walk(self.ast.root.body)

        cond = ast2.Declaration(name=Any(), typename=Any())
        AstMatcher().replace(self.ast.root, cond, self.callback)