Skip to content

Commit

Permalink
preliminary changes to work with qira.
Browse files Browse the repository at this point in the history
  • Loading branch information
ivg committed Jan 13, 2015
1 parent 5c88397 commit ffd5ae7
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 26 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ myocamlbuild.ml
/setup.log
/setup.ml
/_tags
/python/*.pyc
/python/bap.egg-info/
2 changes: 1 addition & 1 deletion python/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,6 @@
Where data is actual string of bytes.
"""
__all__ = ['disasm', 'image']
__all__ = ['disasm', 'image', 'adt', 'asm', 'arm', 'bil']

from .bap import disasm, image
2 changes: 1 addition & 1 deletion python/adt.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __cmp__(self,other):

def __repr__(self):
def qstr(x):
if isinstance(x, int) or isinstance(x, ADT):
if isinstance(x, (int,long)) or isinstance(x, ADT):
return str(x)
else:
return '"{0}"'.format(x)
Expand Down
13 changes: 12 additions & 1 deletion python/asm.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def map_eval(ss):


class Insn(object) :
def __init__(self, name, addr, size, asm, kinds, operands, target=None, bil=[], **kw):
def __init__(self, name, addr, size, asm, kinds, operands, target=None, bil=None, **kw):
self.name = name
self.addr = int(addr)
self.size = int(size)
Expand All @@ -45,6 +45,9 @@ def __init__(self, name, addr, size, asm, kinds, operands, target=None, bil=[],
self.bil = bil
self.__dict__.update(kw)

def has_kind(self, k):
return exists(self.kinds, lambda x: isinstance(x,k))

def __repr__(self):
return 'Insn("{name}", {addr:#010x}, {size}, "{asm}", {kinds}, {operands}, {target}, {bil})'.\
format(**self.__dict__)
Expand All @@ -55,6 +58,14 @@ class Imm(Op) : pass
class Fmm(Op) : pass


def exists(cont,f):
try:
r = (x for x in cont if f(x)).next()
return True
except StopIteration:
return False


if __name__ == "__main__":
print Reg('R0')
for insn in ["Reg(\"R0\")", "Imm(5)", "Imm(14)", "Reg(\"Nil\")", "Reg(\"Nil\")"]:
Expand Down
46 changes: 27 additions & 19 deletions python/bap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# -*- coding: utf-8 -*-

import os, time, atexit
from signal import signal, SIGTERM
import requests
from subprocess import Popen
from mmap import mmap
Expand All @@ -10,41 +11,45 @@
import json
import adt, arm, asm, bil

import threading

from pprint import pprint


__all__ = ["disasm", "image"]

DEBUG_LEVEL = ["Critical", "Error"]

instance = None

storage = threading.local()

def del_instance():
instance = getattr(storage, 'instance', None)
if instance is not None:
instance.close()

def get_instance(**kwargs):
global instance
if 'server' in kwargs or instance is None:
if instance is not None:
instance.close()
instance = getattr(storage, 'instance', None)
if instance is None:
args = kwargs.get('server', {})
instance = Bap(args)
return instance
storage.instance = Bap(args)
return storage.instance

atexit.register(del_instance)
signal(SIGTERM, lambda x,y: del_instance)

def disasm(obj, **kwargs):
r""" disasm(obj) disassembles provided object.
Returns a generator object yield instructions.
"""
def ret(obj):
return get_instance(**kwargs).insns(obj)
def run(obj):
return get_instance(**kwargs).insns(obj, **kwargs)
if isinstance(obj, Id):
return ret(obj)
return run(obj)
elif isinstance(obj, Resource):
return ret(obj.ident)
return run(obj.ident)
else:
return ret(load_chunk(obj, **kwargs))
return run(load_chunk(obj, **kwargs))

def image(f, **kwargs):
bap = get_instance(**kwargs)
Expand Down Expand Up @@ -218,17 +223,19 @@ def __init__(self, server={}):
raise RuntimeError("Failed to connect to BAP server")

self.data = {}
self.temp = NamedTemporaryFile('rw+b')
self.temp = NamedTemporaryFile('rw+b', prefix="bap-")

def insns(self, src):
res = self.call({'get_insns' : {'resource' : src}})
def insns(self, src, **kwargs):
req = {'resource' : src}
req.update(kwargs)
res = self.call({'get_insns' : req})
for msg in res:
if 'error' in msg:
err = Error(msg)
if err.severity in DEBUG_LEVEL:
print err
else:
return (parse_insn(js) for js in msg['insns'])
return (x for x in [parse_insn(js) for js in msg['insns']])

def close(self):
self.__exit__()
Expand Down Expand Up @@ -270,8 +277,8 @@ def dumps(dic):
def mmap(self, data):
url = "mmap://{0}?offset=0&length={1}".format(
self.temp.name, len(data))
os.ftruncate(self.temp.fileno(), len(data))
mm = mmap(self.temp.fileno(), len(data))
os.ftruncate(self.temp.fileno(), 4096)
mm = mmap(self.temp.fileno(), 4096)
mm.write(data)
mm.close()
return url
Expand All @@ -283,6 +290,7 @@ def _load_resource(self, res):
return Id(rep['resource'])

def spawn_server(**kwargs):
print "SPAWNING SERVER!!!!!!!!"
port = kwargs.get('port', 8080)
name = kwargs.get('name', 'bap-server')
server = Popen([name, '--port=' + str(port)])
Expand Down
2 changes: 2 additions & 0 deletions src/server/.merlin
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
B ../../_build/src/server
B ../../_build/lwt
REC
PKG ezjsonm
PKG lwt
Expand All @@ -9,3 +10,4 @@ PKG cohttp.lwt
PKG cohttp

S .
S ../../lwt
1 change: 1 addition & 0 deletions src/server/mmap_client.ml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ let main () =
let data = Lwt_bytes.map_file ~fd ~shared:false () in
let entry = {data; path} in
Weak_set.add files entry;
Lwt.Unix.close (Lwt.Unix.of_unix_file_descr fd) >>= fun () ->
substring_of_entry uri entry in
Transport.register_resource_fetcher ~scheme fetch

Expand Down
2 changes: 1 addition & 1 deletion src/server/rpc.ml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type value = [
] with sexp_of


let minify = false
let minify = true


let sexp_of_response = Fn.compose Ezjsonm.to_sexp Ezjsonm.value
Expand Down
2 changes: 1 addition & 1 deletion src/server/server.ml
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ module Handlers(Ctxt : sig
~section:get_arch ~image:get_arch >>=? fun arch ->
let lifter = lifter_of_arch arch in
let target = Arch.(match backend, arch with
| "llvm", ARM -> Ok "arm"
| "llvm", ARM -> Ok "armv7"
| "llvm", X86_32 -> Ok "i386"
| "llvm", X86_64 -> Ok "x86_64"
| backend, arch ->
Expand Down
4 changes: 2 additions & 2 deletions src/server/start_server.ml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ let () =
let module F = File_fetcher in
let module M = Mmap_client in
let module N = Mmap_server in
let module Z = Zmq_server in
let module C = Zmq_client in
(* let module Z = Zmq_server in *)
(* let module C = Zmq_client in *)
let () = Plugins.load () in
Lwt.Main.run @@ main ()

0 comments on commit ffd5ae7

Please sign in to comment.