Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove generic exceptions (#1428) #1537

Merged
merged 3 commits into from
Oct 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions manticore/binary/binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ def threads(self):
pass


class BinaryException(Exception):
"""
Binary file exception
"""

pass


class CGCElf(Binary):
@staticmethod
def _cgc2elf(filename):
Expand All @@ -51,7 +59,7 @@ def __init__(self, filename):
def maps(self):
for elf_segment in self.elf.iter_segments():
if elf_segment.header.p_type not in ["PT_LOAD", "PT_NULL", "PT_PHDR", "PT_CGCPOV2"]:
raise Exception("Not Supported Section")
raise BinaryException("Not Supported Section")

if elf_segment.header.p_type != "PT_LOAD" or elf_segment.header.p_memsz == 0:
continue
Expand All @@ -60,7 +68,7 @@ def maps(self):
# PF_X 0x1 Execute - PF_W 0x2 Write - PF_R 0x4 Read
perms = [" ", " x", " w ", " wx", "r ", "r x", "rw ", "rwx"][flags & 7]
if "r" not in perms:
raise Exception("Not readable map from cgc elf not supported")
raise BinaryException("Not readable map from cgc elf not supported")

# CGCMAP--
assert elf_segment.header.p_filesz != 0 or elf_segment.header.p_memsz != 0
Expand Down Expand Up @@ -106,7 +114,7 @@ def maps(self):
# PF_X 0x1 Execute - PF_W 0x2 Write - PF_R 0x4 Read
perms = [" ", " x", " w ", " wx", "r ", "r x", "rw ", "rwx"][flags & 7]
if "r" not in perms:
raise Exception("Not readable map from cgc elf not supported")
raise BinaryException("Not readable map from cgc elf not supported")

# CGCMAP--
assert elf_segment.header.p_filesz != 0 or elf_segment.header.p_memsz != 0
Expand Down
12 changes: 6 additions & 6 deletions manticore/core/manticore.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def to_class(self):
class ManticoreBase(Eventful):
def __new__(cls, *args, **kwargs):
if cls in (ManticoreBase, ManticoreSingle, ManticoreThreading, ManticoreMultiprocessing):
raise Exception("Should not instantiate this")
raise ManticoreError("Should not instantiate this")

cl = consts.mprocessing.to_class()
# change ManticoreBase for the more specific class
Expand Down Expand Up @@ -103,7 +103,7 @@ def at_running(func):
@functools.wraps(func)
def newFunction(self, *args, **kw):
if not self.is_running():
raise Exception(f"{func.__name__} only allowed while exploring states")
raise ManticoreError(f"{func.__name__} only allowed while exploring states")
return func(self, *args, **kw)

return newFunction
Expand All @@ -117,7 +117,7 @@ def at_not_running(func):
def newFunction(self, *args, **kw):
if self.is_running():
logger.error("Calling at running not allowed")
raise Exception(f"{func.__name__} only allowed while NOT exploring states")
raise ManticoreError(f"{func.__name__} only allowed while NOT exploring states")
return func(self, *args, **kw)

return newFunction
Expand Down Expand Up @@ -265,7 +265,7 @@ def __init__(self, initial_state, workspace_url=None, policy="random", **kwargs)
"_shared_context",
)
):
raise Exception("Need to instantiate one of: ManticoreNative, ManticoreThreads..")
raise ManticoreError("Need to instantiate one of: ManticoreNative, ManticoreThreads..")

# The workspace and the output
# Manticore will use the workspace to save and share temporary states.
Expand Down Expand Up @@ -510,7 +510,7 @@ def _terminate_state(self, state_id, delete=False):
"""
# wait for a state id to be added to the ready list and remove it
if state_id not in self._busy_states:
raise Exception("Can not terminate. State is not being analyzed")
raise ManticoreError("Can not terminate. State is not being analyzed")
self._busy_states.remove(state_id)

if delete:
Expand All @@ -537,7 +537,7 @@ def _kill_state(self, state_id, delete=False):
"""
# wait for a state id to be added to the ready list and remove it
if state_id not in self._busy_states:
raise Exception("Can not even kill it. State is not being analyzed")
raise ManticoreError("Can not even kill it. State is not being analyzed")
self._busy_states.remove(state_id)

if delete:
Expand Down
13 changes: 11 additions & 2 deletions manticore/core/parser/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@
import ply.lex as lex
import re


class ParserException(Exception):
"""
Parser exception
"""

pass


# List of token names. This is always required
tokens = (
"NUMBER",
Expand Down Expand Up @@ -100,7 +109,7 @@ def t_TOKEN(t):
elif re_SEGMENT.match(t.value):
t.type = "SEGMENT"
else:
raise Exception(f"Unknown:<{t.value}>")
raise ParserException(f"Unknown:<{t.value}>")
return t


Expand Down Expand Up @@ -326,7 +335,7 @@ def parse(expression, read_memory=None, read_register=None, get_descriptor=None,
elif word_size == 64:
sizes = copy.copy(default_sizes_64)
else:
raise Exception("Not Supported")
raise ParserException("Got unsupported word size")
result = parser.parse(expression, tracking=True)
del functions["read_memory"]
del functions["read_register"]
Expand Down
15 changes: 12 additions & 3 deletions manticore/core/smtlib/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys

from ...utils.helpers import PickleSerializer
from ...exceptions import SmtlibError
from .expression import (
BitVecVariable,
BoolVariable,
Expand All @@ -21,6 +22,14 @@
logger = logging.getLogger(__name__)


class ConstraintException(SmtlibError):
"""
Constraint exception
"""

pass


class ConstraintSet:
""" Constraint Sets

Expand Down Expand Up @@ -81,7 +90,7 @@ def add(self, constraint, check=False):
# constraints to this one. After the child constraintSet is deleted
# we regain the ability to add constraints.
if self._child is not None:
raise Exception("ConstraintSet is frozen")
raise ConstraintException("ConstraintSet is frozen")

if isinstance(constraint, BoolConstant):
if not constraint.value:
Expand Down Expand Up @@ -186,7 +195,7 @@ def to_string(self, related_to=None, replace_constants=True):
elif isinstance(exp, Array):
result += f"(declare-fun {name} () (Array (_ BitVec {exp.index_bits}) (_ BitVec {exp.value_bits})))"
else:
raise Exception(f"Type not supported {exp!r}")
raise ConstraintException(f"Type not supported {exp!r}")
result += f"(assert (= {name} {smtlib}))\n"

constraint_str = translator.pop()
Expand Down Expand Up @@ -221,7 +230,7 @@ def declarations(self):
except RuntimeError:
# TODO: (defunct) move recursion management out of PickleSerializer
if sys.getrecursionlimit() >= PickleSerializer.MAX_RECURSION:
raise Exception(
raise ConstraintException(
f"declarations recursion limit surpassed {PickleSerializer.MAX_RECURSION}, aborting"
)
new_limit = sys.getrecursionlimit() + PickleSerializer.DEFAULT_RECURSION
Expand Down
15 changes: 12 additions & 3 deletions manticore/core/smtlib/expression.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
from functools import reduce
from ...exceptions import SmtlibError
import uuid

import re
import copy


class ExpressionException(SmtlibError):
"""
Expression exception
"""

pass


class Expression:
""" Abstract taintable Expression. """

Expand Down Expand Up @@ -118,10 +127,10 @@ def name(self):
return self._name

def __copy__(self, memo):
raise Exception("Copying of Variables is not allowed.")
raise ExpressionException("Copying of Variables is not allowed.")

def __deepcopy__(self, memo):
raise Exception("Copying of Variables is not allowed.")
raise ExpressionException("Copying of Variables is not allowed.")

def __repr__(self):
return "<{:s}({:s}) at {:x}>".format(type(self).__name__, self.name, id(self))
Expand Down Expand Up @@ -697,7 +706,7 @@ def cast_value(self, value):

def __len__(self):
if self.index_max is None:
raise Exception("Array max index not set")
raise ExpressionException("Array max index not set")
return self.index_max

@property
Expand Down
24 changes: 16 additions & 8 deletions manticore/core/smtlib/solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from . import operators as Operators
from .constraints import *
from .visitors import *
from ...exceptions import Z3NotFoundError, SolverError, SolverUnknown, TooManySolutions
from ...exceptions import Z3NotFoundError, SolverError, SolverUnknown, TooManySolutions, SmtlibError
from ...utils import config
from . import issymbolic
import time
Expand Down Expand Up @@ -62,6 +62,14 @@ def instance(cls):
return cls.__singleton_instances[(pid, tid)]


class SolverException(SmtlibError):
"""
Solver exception
"""

pass


class Solver(SingletonMixin):
def __init__(self):
pass
Expand All @@ -75,15 +83,15 @@ def optimize(self, constraints, X, operation, M=10000):
:param X: a symbol or expression
:param M: maximum number of iterations allowed
"""
raise Exception("Abstract method not implemented")
raise SmtlibError("Abstract method not implemented")

def check(self, constraints) -> bool:
"""Check if given constraints can be valid"""
return self.can_be_true(constraints, True)

def can_be_true(self, constraints, expression) -> bool:
"""Check if given expression could be valid"""
raise Exception("Abstract method not implemented")
raise SolverException("Abstract method not implemented")

def must_be_true(self, constraints, expression) -> bool:
"""Check if expression is True and that it can not be False with current constraints"""
Expand All @@ -92,11 +100,11 @@ def must_be_true(self, constraints, expression) -> bool:

def get_all_values(self, constraints, x, maxcnt=10000, silent=False):
"""Returns a list with all the possible values for the symbol x"""
raise Exception("Abstract method not implemented")
raise SolverException("Abstract method not implemented")

def get_value(self, constraints, expression):
"""Ask the solver for one possible result of given expression using given set of constraints."""
raise Exception("Abstract method not implemented")
raise SolverException("Abstract method not implemented")

def max(self, constraints, X: BitVec, M=10000):
"""
Expand Down Expand Up @@ -246,10 +254,10 @@ def _stop_proc(self):

# marshaling/pickle
def __getstate__(self):
raise Exception()
raise SolverException()

def __setstate__(self, state):
raise Exception()
raise SolverException()

def __del__(self):
try:
Expand Down Expand Up @@ -306,7 +314,7 @@ def _recv(self) -> str:

# logger.debug('<%s', buf)
if "(error" in bufl[0]:
raise Exception(f"Error in smtlib: {bufl[0]}")
raise SolverException(f"Error in smtlib: {bufl[0]}")
return buf

def __readline_and_count(self):
Expand Down
5 changes: 3 additions & 2 deletions manticore/core/smtlib/visitors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from ...utils.helpers import CacheDict
from ...exceptions import SmtlibError
from .expression import *
from functools import lru_cache
import logging
Expand Down Expand Up @@ -136,7 +137,7 @@ def _method(self, expression, *args):
value = getattr(self, methodname)(expression, *args)
if value is not None:
return value
raise Exception(f"No translation for this {expression}")
raise SmtlibError(f"No translation for this {expression}")


class GetDeclarations(Visitor):
Expand Down Expand Up @@ -749,7 +750,7 @@ def visit_Operation(self, expression, *operands):

@property
def results(self):
raise Exception("NOOO")
raise SmtlibError("NOOO")

@property
def result(self):
Expand Down
4 changes: 3 additions & 1 deletion manticore/core/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ def __init__(self, message, expression, setstate=None, policy=None, **kwargs):
if policy is None:
policy = "ALL"
if policy not in self._ValidPolicies:
raise Exception(f'Policy ({policy}) must be one of: {", ".join(self._ValidPolicies)}')
raise StateException(
f'Policy ({policy}) must be one of: {", ".join(self._ValidPolicies)}'
)
self.expression = expression
self.setstate = setstate
self.policy = policy
Expand Down
3 changes: 2 additions & 1 deletion manticore/core/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def __exit__(self, *excinfo):
from ..utils.helpers import PickleSerializer
from .smtlib.solver import Z3Solver
from .state import StateBase
from ..exceptions import ManticoreError

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -342,7 +343,7 @@ def lock(self):
@contextmanager
def stream(self, key, mode="r", lock=False):
if lock:
raise Exception("mem: does not support concurrency")
raise ManticoreError("mem: does not support concurrency")
if "b" in mode:
s = io.BytesIO(self._data.get(key, b""))
else:
Expand Down
6 changes: 3 additions & 3 deletions manticore/ethereum/abitypes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Minimal ethereum type signature parser.
# This parses the signature and types used to calculate the function hash
import warnings

from ..exceptions import EthereumError
import ply.yacc as yacc

# Lexer
Expand Down Expand Up @@ -141,7 +141,7 @@ def t_FUNCTION(t):

# Error handling rule
def t_error(t):
raise Exception("Illegal character '%s'" % t.value[0])
raise EthereumError("Illegal character '%s'" % t.value[0])


# Build the lexer
Expand Down Expand Up @@ -217,7 +217,7 @@ def p_dynamic_fixed_type(p):


def p_error(p):
raise Exception("Syntax Error at abitypes")
raise EthereumError("Syntax Error at abitypes")
# print(f"Syntax error at offset {lexer.lexpos:d}")


Expand Down
Loading