Ejemplo n.º 1
0
# Copyright (C) 2006-2011 Axel Tillequin ([email protected])
# published under GPLv2 license

"""
cfg.py
======

This module provides elements to define *control flow graphs* (CFG).
It is based essentially on classes provided by the `grandalf`_ package.

.. _grandalf: https://grandalf.readthedocs.io/

"""

from amoco.logger import Log
logger = Log(__name__)
logger.debug('loading module')

from grandalf.graphs import Vertex,Edge,Graph
from amoco.cas.mapper import mapper
from amoco.system.memory import MemoryZone

from amoco.code import defaultdict,_code_misc_default

#------------------------------------------------------------------------------
class node(Vertex):
    """A node is a graph vertex that embeds a :mod:`code` object.
    It extends the :ref:`Vertex <grandalf:Vertex>` class in order to compare
    nodes by their data blocks rather than their id.

    Args:
Ejemplo n.º 2
0
# -*- coding: utf-8 -*-

from io import BytesIO as StringIO

from amoco.config import conf

from amoco.logger import Log

logger = Log(__name__)
logger.debug("loading module")

import re

try:
    from pygments.token import Token
    from pygments.style import Style
    from pygments.lexer import RegexLexer
    from pygments.formatters import *
except ImportError:
    logger.info("pygments package not found, no renderer defined")
    has_pygments = False

    # metaclass definition, with a syntax compatible with python2 and python3
    class TokenType(type):
        def __getattr__(cls, key):
            return key

    Token_base = TokenType("Token_base", (), {})

    class Token(Token_base):
        pass
Ejemplo n.º 3
0
from amoco.config import conf
from amoco.logger import Log
logger = Log(__name__)

try:
    import blinker
    has_blinker = True

except ImportError:
    logger.info('blinker package not found, no ui.signals defined')
    has_blinker = False
Ejemplo n.º 4
0
# -*- coding: utf-8 -*-

try:
    from cStringIO import StringIO
except ImportError:
    from io import BytesIO as StringIO

from amoco.config import conf_proxy
conf = conf_proxy('ui')

from amoco.logger import Log
logger = Log(__name__)

import re
try:
    from pygments.token import Token
    from pygments.style import Style
    from pygments.lexer import RegexLexer
    from pygments.formatters import *
except ImportError:
    logger.info("pygments package not found, no renderer defined")
    has_pygments = False

    # metaclass definition, with a syntax compatible with python2 and python3
    class TokenType(type):
        def __getattr__(cls, key):
            return key

    Token_base = TokenType('Token_base', (), {})

    class Token(Token_base):
Ejemplo n.º 5
0
# This code is part of Amoco
# Copyright (C) 2014 Axel Tillequin ([email protected])
# published under GPLv2 license

import importlib

from amoco.logger import Log
logger = Log(__name__)

from amoco.cas.expressions import exp
from amoco.arch.core import instruction
from amoco.system.core import CoreExec
from amoco.code import mapper,block,func,xfunc
from amoco.cfg import node,link,graph

class db_core(object):
    @staticmethod
    def dump(self):
        raise NotImplementedError
    @staticmethod
    def load(self):
        raise NotImplementedError

#------------------------------------------------------------------------------
class db_instruction(db_core):

    def __init__(self,i):
        self.address = i.address
        self.misc = dict(i.misc)
        self.bytes = i.bytes
        self.view = str(i)
Ejemplo n.º 6
0
db.py
=====

This module implements all amoco's database facilities using the
`sqlalchemy`_ package, allowing to store many analysis results and
pickled objects.

.. _sqlalchemy: http://www.sqlalchemy.org/

"""

from amoco.config import conf_proxy
conf = conf_proxy(__name__)

from amoco.logger import Log, logging
logger = Log(__name__)

try:
    import sqlalchemy as sql
    from sqlalchemy import orm
    from sqlalchemy.ext.declarative import declarative_base
    has_sql = True
    Session = orm.scoped_session(orm.sessionmaker())
    Base = declarative_base()
    if conf['log']:
        for l in ('sqlalchemy.engine', 'sqlalchemy.orm'):
            alog = logging.getLogger(l)
            for h in logger.handlers:
                alog.addHandler(h)
except ImportError:
    logger.warning(u"package sqlalchemy not found.")
Ejemplo n.º 7
0
"""
db.py
=====

This module implements all amoco's database facilities using the
`sqlalchemy`_ package, allowing to store many analysis results and
pickled objects.

.. _sqlalchemy: http://www.sqlalchemy.org/

"""

from amoco.config import conf

from amoco.logger import Log, logging
logger = Log(__name__)

try:
    import sqlalchemy as sql
    from sqlalchemy import orm
    from sqlalchemy.ext.declarative import declarative_base
    has_sql = True
    Session = orm.scoped_session(orm.sessionmaker())
    Base = declarative_base()
    logflag = conf.getboolean('db', 'log')
    if logflag:
        for l in ('sqlalchemy.engine', 'sqlalchemy.orm'):
            alog = logging.getLogger(l)
            for h in logger.handlers:
                alog.addHandler(h)
            alog.setLevel(logger.level)
Ejemplo n.º 8
0
Archivo: smt.py Proyecto: LRGH/amoco
# Copyright (C) 2015 Axel Tillequin ([email protected])
# published under GPLv2 license
"""
cas/smt.py
==========

The smt module defines the amoco interface to the SMT solver.
Currently, only z3 is supported. This module allows to translate
any amoco expression into its z3 equivalent formula, as well as
getting the z3 solver results back as :class:`cas.mapper.mapper`
instances.
"""

from amoco.logger import Log

logger = Log(__name__)
logger.debug("loading module")

from .expressions import *
from amoco.cas.mapper import mapper

try:
    import z3
except ImportError:
    logger.info("z3 package not found => solve() method is not implemented")

    class solver(object):
        def __init__(self, eqns=None, tactics=None, timeout=None):
            raise NotImplementedError

    has_solver = False
Ejemplo n.º 9
0
# This code is part of Amoco
# Copyright (C) 2014 Axel Tillequin ([email protected])
# published under GPLv2 license

import importlib

from amoco.logger import Log
logger = Log(__name__)

from amoco.cas.expressions import exp
from amoco.arch.core import instruction
from amoco.system.core import CoreExec
from amoco.code import mapper, block, func, xfunc
from amoco.cfg import node, link, graph


class db_core(object):
    @staticmethod
    def dump(self):
        raise NotImplementedError

    @staticmethod
    def load(self):
        raise NotImplementedError


#------------------------------------------------------------------------------
class db_instruction(db_core):
    def __init__(self, i):
        self.address = i.address
        self.misc = dict(i.misc)
Ejemplo n.º 10
0
emu.py
======
The emu module of amoco.

"""

# This code is part of Amoco
# Copyright (C) 2019 Axel Tillequin ([email protected])
# published under GPLv2 license

from amoco.config import conf
from amoco.arch.core import DecodeError
from amoco.logger import Log

logger = Log(__name__)
logger.debug('loading emu')

try:
    IntType = (int, long)
except NameError:
    IntType = (int, )
else:
    conf.Cas.unicode = False


class emul(object):
    def __init__(self, task):
        self.task = task
        self.cpu = task.cpu
        self.pc = task.cpu.PC()
Ejemplo n.º 11
0
# -*- coding: utf-8 -*-

# This code is part of Amoco
# Copyright (C) 2007-2013 Axel Tillequin ([email protected])
# published under GPLv2 license


from amoco.logger import Log
logger = Log(__name__)

from bisect import bisect_left

from amoco.cas.expressions import top

#------------------------------------------------------------------------------
# datadiv provides the API for manipulating data values extracted from memory.
# These values are either considered as 'raw' (byte strings) or can be any
# abstractions (or symbolic expressions)
# The datadiv.val required API is:
#   .__len__ => byte length
#   .size => bit length
#   .__getitem__ => extraction of bit slices.
#   .__setitem__ => overwrite given bit slice.
class datadiv(object):
    __slot__ = ['val']

    def __init__(self,data):
        self.val = data

    @property
    def _is_raw(self):
Ejemplo n.º 12
0
Archivo: emu.py Proyecto: sthagen/amoco
emu.py
======
The emu module of amoco implements the emulator class :class:`emul`.

"""

from collections import deque

from amoco.config import conf
from amoco.arch.core import DecodeError
from amoco.sa import lsweep
from amoco.ui.views import emulView
from amoco.logger import Log

logger = Log(__name__)
logger.debug("loading emu")


class EmulError(Exception):
    pass


class emul(object):
    def __init__(self, task):
        self.task = task
        self.cpu = task.cpu
        self.pc = task.cpu.PC()
        self.psz = self.pc.size
        self.hooks = []
        self.watch = {}
Ejemplo n.º 13
0
Archivo: db.py Proyecto: sthagen/amoco
db.py
=====

This module implements all amoco's database facilities using the
`sqlalchemy`_ package, allowing to store many analysis results and
pickled objects.

.. _sqlalchemy: http://www.sqlalchemy.org/

"""

from amoco.config import conf

from amoco.logger import Log, logging

logger = Log(__name__)
logger.debug("loading module")

try:
    import sqlalchemy as sql
    from sqlalchemy import orm
    from sqlalchemy.ext.declarative import declarative_base

    has_sql = True
    Session = orm.scoped_session(orm.sessionmaker())
    Base = declarative_base()
    if conf.DB.log:
        for l in ("sqlalchemy.engine", "sqlalchemy.orm"):
            alog = logging.getLogger(l)
            for h in logger.handlers:
                alog.addHandler(h)
Ejemplo n.º 14
0
# -*- coding: utf-8 -*-

# This code is part of Amoco
# Copyright (C) 2007-2013 Axel Tillequin ([email protected])
# published under GPLv2 license

from amoco.logger import Log
logger = Log(__name__)

from bisect import bisect_left

from amoco.cas.expressions import top


#------------------------------------------------------------------------------
# datadiv provides the API for manipulating data values extracted from memory.
# These values are either considered as 'raw' (byte strings) or can be any
# abstractions (or symbolic expressions)
# The datadiv.val required API is:
#   .__len__ => byte length
#   .size => bit length
#   .__getitem__ => extraction of bit slices.
#   .__setitem__ => overwrite given bit slice.
class datadiv(object):
    __slot__ = ['val']

    def __init__(self, data):
        self.val = data

    @property
    def _is_raw(self):
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-

# This code is part of Amoco
# Copyright (C) 2006-2014 Axel Tillequin ([email protected])
# published under GPLv2 license

from os import path
from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QPointF

from amoco.ui.render import Formats,conf
from amoco.logger import Log

logger = Log(__name__)
logger.debug("loading module")


#from . import rc_icons

try:
    # integrate Qt mainloop into IPython console:
    # (the name qt4 here is a relic of the API but what happens
    # really is not restricted to Qt4...)
    from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
    app = get_app_qt4()
    start_event_loop_qt4(app)
except ImportError:
    app = QApplication.instance() or QApplication([])

app.setApplicationName("amoco-qt")
# set default styleSheet:
Ejemplo n.º 16
0
# -*- coding: utf-8 -*-

# This code is part of Amoco
# Copyright (C) 2015 Axel Tillequin ([email protected])
# published under GPLv2 license

from amoco.logger import Log
logger = Log(__name__)

from .expressions import *
from amoco.cas.mapper import mapper

try:
    import z3
except ImportError:
    logger.info('z3 package not found => solve() method is not implemented')
    class solver(object):
        def __init__(self,eqns=None):
            raise NotImplementedError
    has_solver = False
else:
    logger.info('z3 package imported')
    class solver(object):
        def __init__(self,eqns=None):
            self.eqns = []
            self.locs = []
            self.solver = z3.Solver()
            if eqns: self.add(eqns)
            self._ctr = 0

        def add(self,eqns):
Ejemplo n.º 17
0
# -*- coding: utf-8 -*-

# This code is part of Amoco
# Copyright (C) 2006-2011 Axel Tillequin ([email protected])
# published under GPLv2 license

from .env import *
from amoco.cas.utils import *

from amoco.logger import Log
logger = Log(__name__)

#------------------------------------------------------------------------------
# utils :
def push(fmap,x):
  fmap[esp] = fmap(esp-x.length)
  fmap[mem(esp,x.size)] = x

def pop(fmap,l):
  fmap[l] = fmap(mem(esp,l.size))
  fmap[esp] = fmap(esp+l.length)

def parity(x):
  x = x ^ (x>>1)
  x = (x ^ (x>>2)) & 0x11111111
  x = x * 0x11111111
  p = (x>>28).bit(0)
  return p

def parity8(x):
  y = x ^ (x>>4)
Ejemplo n.º 18
0
from collections import defaultdict

from amoco.logger import Log
logger = Log(__name__)

try:
    import ConfigParser as cp
except ImportError:
    logger.info('ConfigParser not found, fallback to default config')
    cp = None

if cp:
    import os
    conf = cp.SafeConfigParser()
    conf.add_section('block')
    conf.set('block', 'header', 'True')
    conf.set('block', 'bytecode', 'True')
    conf.set('block', 'padding', '4')
    conf.read([os.path.expanduser('~/.amocorc')])
else:
    conf = None

    class DefaultConf(object):
        def __init__(self):
            self.sections = defaultdict(lambda: {})
            self.setdefaults()

        def get(self, section, item):
            s = self.sections[section]
            return s.get(item, None) if s else None