Search is not available for this dataset
text stringlengths 75 104k |
|---|
def save_state(self, state, state_id=None):
"""
Save a state to storage, return identifier.
:param state: The state to save
:param int state_id: If not None force the state id potentially overwriting old states
:return: New state id
:rtype: int
"""
assert isinstance(state, StateBase)
if state_id is None:
state_id = self._get_id()
else:
self.rm_state(state_id)
self._store.save_state(state, f'{self._prefix}{state_id:08x}{self._suffix}')
return state_id |
def _named_stream(self, name, binary=False):
"""
Create an indexed output stream i.e. 'test_00000001.name'
:param name: Identifier for the stream
:return: A context-managed stream-like object
"""
with self._store.save_stream(self._named_key(name), binary=binary) as s:
yield s |
def t_UINTN(t):
r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)"
size = int(t.lexer.lexmatch.group('size'))
t.value = ('uint', size)
return t |
def t_INTN(t):
r"int(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)"
size = int(t.lexer.lexmatch.group('size'))
t.value = ('int', size)
return t |
def t_UFIXEDMN(t):
r"ufixed(?P<M>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)x(?P<N>80|79|78|77|76|75|74|73|72|71|70|69|68|67|66|65|64|63|62|61|60|59|58|57|56|55|54|53|52|51|50|49|48|47|46|45|44|43|42|41|40|39|38|37|36|35|34|33|32|31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|15|14|13|12|11|10|9|8|7|6|5|4|3|2|1)"
M = int(t.lexer.lexmatch.group('M'))
N = int(t.lexer.lexmatch.group('N'))
t.value = ("ufixed", M, N)
return t |
def t_BYTESM(t):
r"bytes(?P<nbytes>32|31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|15|14|13|12|11|10|9|8|7|6|5|4|3|2|1)"
size = int(t.lexer.lexmatch.group('nbytes'))
t.value = ('bytesM', size)
return t |
def p_dynamic_fixed_type(p):
"""
T : T LBRAKET NUMBER RBRAKET
"""
reps = int(p[3])
base_type = p[1]
p[0] = ('array', reps, base_type) |
def cmp_regs(cpu, should_print=False):
"""
Compare registers from a remote gdb session to current mcore.
:param manticore.core.cpu Cpu: Current cpu
:param bool should_print: Whether to print values to stdout
:return: Whether or not any differences were detected
:rtype: bool
"""
differing = False
gdb_regs = gdb.getCanonicalRegisters()
for name in sorted(gdb_regs):
vg = gdb_regs[name]
if name.endswith('psr'):
name = 'apsr'
v = cpu.read_register(name.upper())
if should_print:
logger.debug(f'{name} gdb:{vg:x} mcore:{v:x}')
if vg != v:
if should_print:
logger.warning('^^ unequal')
differing = True
if differing:
logger.debug(qemu.correspond(None))
return differing |
def post_mcore(state, last_instruction):
"""
Handle syscalls (import memory) and bail if we diverge
"""
global in_helper
# Synchronize qemu state to manticore's after a system call
if last_instruction.mnemonic.lower() == 'svc':
# Synchronize all writes that have happened
writes = state.cpu.memory.pop_record_writes()
if writes:
logger.debug("Got %d writes", len(writes))
for addr, val in writes:
gdb.setByte(addr, val[0])
# Write return val to gdb
gdb_r0 = gdb.getR('R0')
if gdb_r0 != state.cpu.R0:
logger.debug(f"Writing 0x{state.cpu.R0:x} to R0 (overwriting 0x{gdb.getR('R0'):x})")
for reg in state.cpu.canonical_registers:
if reg.endswith('PSR') or reg in ('R15', 'PC'):
continue
val = state.cpu.read_register(reg)
gdb.setR(reg, val)
# Ignore Linux kernel helpers
if (state.cpu.PC >> 16) == 0xffff:
in_helper = True
return
# If we executed a few instructions of a helper, we need to sync Manticore's
# state to GDB as soon as we stop executing a helper.
if in_helper:
for reg in state.cpu.canonical_registers:
if reg.endswith('PSR'):
continue
# Don't sync pc
if reg == 'R15':
continue
gdb.setR(reg, state.cpu.read_register(reg))
in_helper = False
if cmp_regs(state.cpu):
cmp_regs(state.cpu, should_print=True)
state.abandon() |
def sync_svc(state):
"""
Mirror some service calls in manticore. Happens after qemu executed a SVC
instruction, but before manticore did.
"""
syscall = state.cpu.R7 # Grab idx from manticore since qemu could have exited
name = linux_syscalls.armv7[syscall]
logger.debug(f"Syncing syscall: {name}")
try:
# Make sure mmap returns the same address
if 'mmap' in name:
returned = gdb.getR('R0')
logger.debug(f"Syncing mmap ({returned:x})")
state.cpu.write_register('R0', returned)
if 'exit' in name:
return
except ValueError:
for reg in state.cpu.canonical_registers:
print(f'{reg}: {state.cpu.read_register(reg):x}')
raise |
def initialize(state):
"""
Synchronize the stack and register state (manticore->qemu)
"""
logger.debug(f"Copying {stack_top - state.cpu.SP} bytes in the stack..")
stack_bottom = min(state.cpu.SP, gdb.getR('SP'))
for address in range(stack_bottom, stack_top):
b = state.cpu.read_int(address, 8)
gdb.setByte(address, chr(b))
logger.debug("Done")
# Qemu fd's start at 5, ours at 3. Add two filler fds
mcore_stdout = state.platform.files[1]
state.platform.files.append(mcore_stdout)
state.platform.files.append(mcore_stdout)
# Sync gdb's regs
for gdb_reg in gdb.getCanonicalRegisters():
if gdb_reg.endswith('psr'):
mcore_reg = 'APSR'
else:
mcore_reg = gdb_reg.upper()
value = state.cpu.read_register(mcore_reg)
gdb.setR(gdb_reg, value) |
def to_constant(expression):
"""
Iff the expression can be simplified to a Constant get the actual concrete value.
This discards/ignore any taint
"""
value = simplify(expression)
if isinstance(value, Expression) and value.taint:
raise ValueError("Can not simplify tainted values to constant")
if isinstance(value, Constant):
return value.value
elif isinstance(value, Array):
if expression.index_max:
ba = bytearray()
for i in range(expression.index_max):
value_i = simplify(value[i])
if not isinstance(value_i, Constant):
break
ba.append(value_i.value)
else:
return bytes(ba)
return expression
return value |
def visit(self, node, use_fixed_point=False):
"""
The entry point of the visitor.
The exploration algorithm is a DFS post-order traversal
The implementation used two stacks instead of a recursion
The final result is store in self.result
:param node: Node to explore
:type node: Expression
:param use_fixed_point: if True, it runs _methods until a fixed point is found
:type use_fixed_point: Bool
"""
cache = self._cache
visited = set()
stack = []
stack.append(node)
while stack:
node = stack.pop()
if node in cache:
self.push(cache[node])
elif isinstance(node, Operation):
if node in visited:
operands = [self.pop() for _ in range(len(node.operands))]
value = self._method(node, *operands)
visited.remove(node)
self.push(value)
cache[node] = value
else:
visited.add(node)
stack.append(node)
stack.extend(node.operands)
else:
self.push(self._method(node))
if use_fixed_point:
old_value = None
new_value = self.pop()
while old_value is not new_value:
self.visit(new_value)
old_value = new_value
new_value = self.pop()
self.push(new_value) |
def _method(self, expression, *args):
"""
Overload Visitor._method because we want to stop to iterate over the
visit_ functions as soon as a valid visit_ function is found
"""
assert expression.__class__.__mro__[-1] is object
for cls in expression.__class__.__mro__:
sort = cls.__name__
methodname = 'visit_%s' % sort
method = getattr(self, methodname, None)
if method is not None:
method(expression, *args)
return
return |
def visit_Operation(self, expression, *operands):
""" constant folding, if all operands of an expression are a Constant do the math """
operation = self.operations.get(type(expression), None)
if operation is not None and \
all(isinstance(o, Constant) for o in operands):
value = operation(*(x.value for x in operands))
if isinstance(expression, BitVec):
return BitVecConstant(expression.size, value, taint=expression.taint)
else:
isinstance(expression, Bool)
return BoolConstant(value, taint=expression.taint)
else:
if any(operands[i] is not expression.operands[i] for i in range(len(operands))):
expression = self._rebuild(expression, operands)
return expression |
def visit_Operation(self, expression, *operands):
""" constant folding, if all operands of an expression are a Constant do the math """
if all(isinstance(o, Constant) for o in operands):
expression = constant_folder(expression)
if self._changed(expression, operands):
expression = self._rebuild(expression, operands)
return expression |
def visit_BitVecConcat(self, expression, *operands):
""" concat( extract(k1, 0, a), extract(sizeof(a)-k1, k1, a)) ==> a
concat( extract(k1, beg, a), extract(end, k1, a)) ==> extract(beg, end, a)
"""
op = expression.operands[0]
value = None
end = None
begining = None
for o in operands:
# If found a non BitVecExtract, do not apply
if not isinstance(o, BitVecExtract):
return None
# Set the value for the first item
if value is None:
value = o.value
begining = o.begining
end = o.end
else:
# If concat of extracts of different values do not apply
if value is not o.value:
return None
# If concat of non contiguous extracs do not apply
if begining != o.end + 1:
return None
# update begining variable
begining = o.begining
if value is not None:
if end + 1 == value.size and begining == 0:
return value
else:
return BitVecExtract(value, begining, end - begining + 1, taint=expression.taint) |
def visit_BitVecExtract(self, expression, *operands):
""" extract(sizeof(a), 0)(a) ==> a
extract(16, 0)( concat(a,b,c,d) ) => concat(c, d)
extract(m,M)(and/or/xor a b ) => and/or/xor((extract(m,M) a) (extract(m,M) a)
"""
op = expression.operands[0]
begining = expression.begining
end = expression.end
size = end - begining + 1
# extract(sizeof(a), 0)(a) ==> a
if begining == 0 and end + 1 == op.size:
return op
elif isinstance(op, BitVecExtract):
return BitVecExtract(op.value, op.begining + begining, size, taint=expression.taint)
elif isinstance(op, BitVecConcat):
new_operands = []
bitcount = 0
for item in reversed(op.operands):
if begining >= item.size:
begining -= item.size
else:
if bitcount < expression.size:
new_operands.append(item)
bitcount += item.size
if begining != expression.begining:
return BitVecExtract(BitVecConcat(sum([x.size for x in new_operands]), *reversed(new_operands)),
begining, expression.size, taint=expression.taint)
if isinstance(op, (BitVecAnd, BitVecOr, BitVecXor)):
bitoperand_a, bitoperand_b = op.operands
return op.__class__(BitVecExtract(bitoperand_a, begining, expression.size), BitVecExtract(bitoperand_b, begining, expression.size), taint=expression.taint) |
def visit_BitVecAdd(self, expression, *operands):
""" a + 0 ==> a
0 + a ==> a
"""
left = expression.operands[0]
right = expression.operands[1]
if isinstance(right, BitVecConstant):
if right.value == 0:
return left
if isinstance(left, BitVecConstant):
if left.value == 0:
return right |
def visit_BitVecSub(self, expression, *operands):
""" a - 0 ==> 0
(a + b) - b ==> a
(b + a) - b ==> a
"""
left = expression.operands[0]
right = expression.operands[1]
if isinstance(left, BitVecAdd):
if self._same_constant(left.operands[0], right):
return left.operands[1]
elif self._same_constant(left.operands[1], right):
return left.operands[0] |
def visit_BitVecOr(self, expression, *operands):
""" a | 0 => a
0 | a => a
0xffffffff & a => 0xffffffff
a & 0xffffffff => 0xffffffff
"""
left = expression.operands[0]
right = expression.operands[1]
if isinstance(right, BitVecConstant):
if right.value == 0:
return left
elif right.value == left.mask:
return right
elif isinstance(left, BitVecOr):
left_left = left.operands[0]
left_right = left.operands[1]
if isinstance(right, Constant):
return BitVecOr(left_left, (left_right | right), taint=expression.taint)
elif isinstance(left, BitVecConstant):
return BitVecOr(right, left, taint=expression.taint) |
def visit_BitVecAnd(self, expression, *operands):
""" ct & x => x & ct move constants to the right
a & 0 => 0 remove zero
a & 0xffffffff => a remove full mask
(b & ct2) & ct => b & (ct&ct2) associative property
(a & (b | c) => a&b | a&c distribute over |
"""
left = expression.operands[0]
right = expression.operands[1]
if isinstance(right, BitVecConstant):
if right.value == 0:
return right
elif right.value == right.mask:
return left
elif isinstance(left, BitVecAnd):
left_left = left.operands[0]
left_right = left.operands[1]
if isinstance(right, Constant):
return BitVecAnd(left_left, left_right & right, taint=expression.taint)
elif isinstance(left, BitVecOr):
left_left = left.operands[0]
left_right = left.operands[1]
return BitVecOr(right & left_left, right & left_right, taint=expression.taint)
elif isinstance(left, BitVecConstant):
return BitVecAnd(right, left, taint=expression.taint) |
def visit_BitVecShiftLeft(self, expression, *operands):
""" a << 0 => a remove zero
a << ct => 0 if ct > sizeof(a) remove big constant shift
"""
left = expression.operands[0]
right = expression.operands[1]
if isinstance(right, BitVecConstant):
if right.value == 0:
return left
elif right.value >= right.size:
return left |
def visit_ArraySelect(self, expression, *operands):
""" ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0)
-> v0
"""
arr, index = operands
if isinstance(arr, ArrayVariable):
return
if isinstance(index, BitVecConstant):
ival = index.value
# props are slow and using them in tight loops should be avoided, esp when they offer no additional validation
# arr._operands[1] = arr.index, arr._operands[0] = arr.array
while isinstance(arr, ArrayStore) and isinstance(arr._operands[1], BitVecConstant) and arr._operands[1]._value != ival:
arr = arr._operands[0] # arr.array
if isinstance(index, BitVecConstant) and isinstance(arr, ArrayStore) and isinstance(arr.index, BitVecConstant) and arr.index.value == index.value:
return arr.value
else:
if arr is not expression.array:
return arr.select(index) |
def _type_size(ty):
""" Calculate `static` type size """
if ty[0] in ('int', 'uint', 'bytesM', 'function'):
return 32
elif ty[0] in ('tuple'):
result = 0
for ty_i in ty[1]:
result += ABI._type_size(ty_i)
return result
elif ty[0] in ('array'):
rep = ty[1]
result = 32 # offset link
return result
elif ty[0] in ('bytes', 'string'):
result = 32 # offset link
return result
raise ValueError |
def function_call(type_spec, *args):
"""
Build transaction data from function signature and arguments
"""
m = re.match(r"(?P<name>[a-zA-Z_][a-zA-Z_0-9]*)(?P<type>\(.*\))", type_spec)
if not m:
raise EthereumError("Function signature expected")
ABI._check_and_warn_num_args(type_spec, *args)
result = ABI.function_selector(type_spec) # Funcid
result += ABI.serialize(m.group('type'), *args)
return result |
def serialize(ty, *values, **kwargs):
"""
Serialize value using type specification in ty.
ABI.serialize('int256', 1000)
ABI.serialize('(int, int256)', 1000, 2000)
"""
try:
parsed_ty = abitypes.parse(ty)
except Exception as e:
# Catch and rebrand parsing errors
raise EthereumError(str(e))
if parsed_ty[0] != 'tuple':
if len(values) > 1:
raise ValueError('too many values passed for non-tuple')
values = values[0]
if isinstance(values, str):
values = values.encode()
else:
# implement type forgiveness for bytesM/string types
# allow python strs also to be used for Solidity bytesM/string types
values = tuple(val.encode() if isinstance(val, str) else val for val in values)
result, dyn_result = ABI._serialize(parsed_ty, values)
return result + dyn_result |
def function_selector(method_name_and_signature):
"""
Makes a function hash id from a method signature
"""
s = sha3.keccak_256()
s.update(method_name_and_signature.encode())
return bytes(s.digest()[:4]) |
def _serialize_uint(value, size=32, padding=0):
"""
Translates a python integral or a BitVec into a 32 byte string, MSB first
"""
if size <= 0 or size > 32:
raise ValueError
from .account import EVMAccount # because of circular import
if not isinstance(value, (int, BitVec, EVMAccount)):
raise ValueError
if issymbolic(value):
# FIXME This temporary array variable should be obtained from a specific constraint store
bytes = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))
if value.size <= size * 8:
value = Operators.ZEXTEND(value, size * 8)
else:
# automatically truncate, e.g. if they passed a BitVec(256) for an `address` argument (160 bits)
value = Operators.EXTRACT(value, 0, size * 8)
bytes = ArrayProxy(bytes.write_BE(padding, value, size))
else:
value = int(value)
bytes = bytearray()
for _ in range(padding):
bytes.append(0)
for position in reversed(range(size)):
bytes.append(Operators.EXTRACT(value, position * 8, 8))
assert len(bytes) == size + padding
return bytes |
def _serialize_int(value, size=32, padding=0):
"""
Translates a signed python integral or a BitVec into a 32 byte string, MSB first
"""
if size <= 0 or size > 32:
raise ValueError
if not isinstance(value, (int, BitVec)):
raise ValueError
if issymbolic(value):
buf = ArrayVariable(index_bits=256, index_max=32, value_bits=8, name='temp{}'.format(uuid.uuid1()))
value = Operators.SEXTEND(value, value.size, size * 8)
buf = ArrayProxy(buf.write_BE(padding, value, size))
else:
value = int(value)
buf = bytearray()
for _ in range(padding):
buf.append(0)
for position in reversed(range(size)):
buf.append(Operators.EXTRACT(value, position * 8, 8))
return buf |
def _deserialize_uint(data, nbytes=32, padding=0, offset=0):
"""
Read a `nbytes` bytes long big endian unsigned integer from `data` starting at `offset`
:param data: sliceable buffer; symbolic buffer of Eth ABI encoded data
:param nbytes: number of bytes to read starting from least significant byte
:rtype: int or Expression
"""
assert isinstance(data, (bytearray, Array))
value = ABI._readBE(data, nbytes, padding=True, offset=offset)
value = Operators.ZEXTEND(value, (nbytes + padding) * 8)
return value |
def _deserialize_int(data, nbytes=32, padding=0):
"""
Read a `nbytes` bytes long big endian signed integer from `data` starting at `offset`
:param data: sliceable buffer; symbolic buffer of Eth ABI encoded data
:param nbytes: number of bytes to read starting from least significant byte
:rtype: int or Expression
"""
assert isinstance(data, (bytearray, Array))
value = ABI._readBE(data, nbytes, padding=True)
value = Operators.SEXTEND(value, nbytes * 8, (nbytes + padding) * 8)
if not issymbolic(value):
# sign bit on
if value & (1 << (nbytes * 8 - 1)):
value = -(((~value) + 1) & ((1 << (nbytes * 8)) - 1))
return value |
def concretized_args(**policies):
"""
Make sure an EVM instruction has all of its arguments concretized according to
provided policies.
Example decoration:
@concretized_args(size='ONE', address='')
def LOG(self, address, size, *topics):
...
The above will make sure that the |size| parameter to LOG is Concretized when symbolic
according to the 'ONE' policy and concretize |address| with the default policy.
:param policies: A kwargs list of argument names and their respective policies.
Provide None or '' as policy to use default.
:return: A function decorator
"""
def concretizer(func):
@wraps(func)
def wrapper(*args, **kwargs):
spec = inspect.getfullargspec(func)
for arg, policy in policies.items():
assert arg in spec.args, "Concretizer argument not found in wrapped function."
# index is 0-indexed, but ConcretizeArgument is 1-indexed. However, this is correct
# since implementation method is always a bound method (self is param 0)
index = spec.args.index(arg)
if not issymbolic(args[index]):
continue
if not policy:
policy = 'SAMPLED'
if policy == "ACCOUNTS":
value = args[index]
world = args[0].world
#special handler for EVM only policy
cond = world._constraint_to_accounts(value, ty='both', include_zero=True)
world.constraints.add(cond)
policy = 'ALL'
raise ConcretizeArgument(index, policy=policy)
return func(*args, **kwargs)
wrapper.__signature__ = inspect.signature(func)
return wrapper
return concretizer |
def to_dict(self, mevm):
"""
Only meant to be used with concrete Transaction objects! (after calling .concretize())
"""
return dict(type=self.sort,
from_address=self.caller,
from_name=mevm.account_name(self.caller),
to_address=self.address,
to_name=mevm.account_name(self.address),
value=self.value,
gas=self.gas,
data=binascii.hexlify(self.data).decode()) |
def dump(self, stream, state, mevm, conc_tx=None):
"""
Concretize and write a human readable version of the transaction into the stream. Used during testcase
generation.
:param stream: Output stream to write to. Typically a file.
:param manticore.ethereum.State state: state that the tx exists in
:param manticore.ethereum.ManticoreEVM mevm: manticore instance
:return:
"""
from ..ethereum import ABI # circular imports
from ..ethereum.manticore import flagged
is_something_symbolic = False
if conc_tx is None:
conc_tx = self.concretize(state)
# The result if any RETURN or REVERT
stream.write("Type: %s (%d)\n" % (self.sort, self.depth))
caller_solution = conc_tx.caller
caller_name = mevm.account_name(caller_solution)
stream.write("From: %s(0x%x) %s\n" % (caller_name, caller_solution, flagged(issymbolic(self.caller))))
address_solution = conc_tx.address
address_name = mevm.account_name(address_solution)
stream.write("To: %s(0x%x) %s\n" % (address_name, address_solution, flagged(issymbolic(self.address))))
stream.write("Value: %d %s\n" % (conc_tx.value, flagged(issymbolic(self.value))))
stream.write("Gas used: %d %s\n" % (conc_tx.gas, flagged(issymbolic(self.gas))))
tx_data = conc_tx.data
stream.write("Data: 0x{} {}\n".format(binascii.hexlify(tx_data).decode(), flagged(issymbolic(self.data))))
if self.return_data is not None:
return_data = conc_tx.return_data
stream.write("Return_data: 0x{} {}\n".format(binascii.hexlify(return_data).decode(), flagged(issymbolic(self.return_data))))
metadata = mevm.get_metadata(self.address)
if self.sort == 'CREATE':
if metadata is not None:
conc_args_data = conc_tx.data[len(metadata._init_bytecode):]
arguments = ABI.deserialize(metadata.get_constructor_arguments(), conc_args_data)
# TODO confirm: arguments should all be concrete?
is_argument_symbolic = any(map(issymbolic, arguments)) # is this redundant since arguments are all concrete?
stream.write('Function call:\n')
stream.write("Constructor(")
stream.write(','.join(map(repr, map(state.solve_one, arguments)))) # is this redundant since arguments are all concrete?
stream.write(') -> %s %s\n' % (self.result, flagged(is_argument_symbolic)))
if self.sort == 'CALL':
if metadata is not None:
calldata = conc_tx.data
is_calldata_symbolic = issymbolic(self.data)
function_id = calldata[:4] # hope there is enough data
signature = metadata.get_func_signature(function_id)
function_name = metadata.get_func_name(function_id)
if signature:
_, arguments = ABI.deserialize(signature, calldata)
else:
arguments = (calldata,)
return_data = None
if self.result == 'RETURN':
ret_types = metadata.get_func_return_types(function_id)
return_data = conc_tx.return_data
return_values = ABI.deserialize(ret_types, return_data) # function return
is_return_symbolic = issymbolic(self.return_data)
stream.write('\n')
stream.write("Function call:\n")
stream.write("%s(" % function_name)
stream.write(','.join(map(repr, arguments)))
stream.write(') -> %s %s\n' % (self.result, flagged(is_calldata_symbolic)))
if return_data is not None:
if len(return_values) == 1:
return_values = return_values[0]
stream.write('return: %r %s\n' % (return_values, flagged(is_return_symbolic)))
is_something_symbolic = is_calldata_symbolic or is_return_symbolic
stream.write('\n\n')
return is_something_symbolic |
def _get_memfee(self, address, size=1):
"""
This calculates the amount of extra gas needed for accessing to
previously unused memory.
:param address: base memory offset
:param size: size of the memory access
"""
if not issymbolic(size) and size == 0:
return 0
address = self.safe_add(address, size)
allocated = self.allocated
GMEMORY = 3
GQUADRATICMEMDENOM = 512 # 1 gas per 512 quadwords
old_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(allocated, 31), 32), 512)
new_size = Operators.ZEXTEND(Operators.UDIV(self.safe_add(address, 31), 32), 512)
old_totalfee = self.safe_mul(old_size, GMEMORY) + Operators.UDIV(self.safe_mul(old_size, old_size), GQUADRATICMEMDENOM)
new_totalfee = self.safe_mul(new_size, GMEMORY) + Operators.UDIV(self.safe_mul(new_size, new_size), GQUADRATICMEMDENOM)
memfee = new_totalfee - old_totalfee
flag = Operators.UGT(new_totalfee, old_totalfee)
return Operators.ITEBV(512, size == 0, 0, Operators.ITEBV(512, flag, memfee, 0)) |
def read_code(self, address, size=1):
"""
Read size byte from bytecode.
If less than size bytes are available result will be pad with \x00
"""
assert address < len(self.bytecode)
value = self.bytecode[address:address + size]
if len(value) < size:
value += '\x00' * (size - len(value)) # pad with null (spec)
return value |
def instruction(self):
"""
Current instruction pointed by self.pc
"""
# FIXME check if pc points to invalid instruction
# if self.pc >= len(self.bytecode):
# return InvalidOpcode('Code out of range')
# if self.pc in self.invalid:
# raise InvalidOpcode('Opcode inside a PUSH immediate')
try:
_decoding_cache = getattr(self, '_decoding_cache')
except Exception:
_decoding_cache = self._decoding_cache = {}
pc = self.pc
if isinstance(pc, Constant):
pc = pc.value
if pc in _decoding_cache:
return _decoding_cache[pc]
def getcode():
bytecode = self.bytecode
for pc_i in range(pc, len(bytecode)):
yield simplify(bytecode[pc_i]).value
while True:
yield 0
instruction = EVMAsm.disassemble_one(getcode(), pc=pc, fork=DEFAULT_FORK)
_decoding_cache[pc] = instruction
return instruction |
def _push(self, value):
"""
Push into the stack
ITEM0
ITEM1
ITEM2
sp-> {empty}
"""
assert isinstance(value, int) or isinstance(value, BitVec) and value.size == 256
if len(self.stack) >= 1024:
raise StackOverflow()
if isinstance(value, int):
value = value & TT256M1
value = simplify(value)
if isinstance(value, Constant) and not value.taint:
value = value.value
self.stack.append(value) |
def _top(self, n=0):
"""Read a value from the top of the stack without removing it"""
if len(self.stack) - n < 0:
raise StackUnderflow()
return self.stack[n - 1] |
def _checkpoint(self):
"""Save and/or get a state checkpoint previous to current instruction"""
#Fixme[felipe] add a with self.disabled_events context mangr to Eventful
if self._checkpoint_data is None:
if not self._published_pre_instruction_events:
self._published_pre_instruction_events = True
self._publish('will_decode_instruction', self.pc)
self._publish('will_execute_instruction', self.pc, self.instruction)
self._publish('will_evm_execute_instruction', self.instruction, self._top_arguments())
pc = self.pc
instruction = self.instruction
old_gas = self.gas
allocated = self._allocated
#FIXME Not clear which exception should trigger first. OOG or insuficient stack
# this could raise an insuficient stack exception
arguments = self._pop_arguments()
fee = self._calculate_gas(*arguments)
self._checkpoint_data = (pc, old_gas, instruction, arguments, fee, allocated)
return self._checkpoint_data |
def _rollback(self):
"""Revert the stack, gas, pc and memory allocation so it looks like before executing the instruction"""
last_pc, last_gas, last_instruction, last_arguments, fee, allocated = self._checkpoint_data
self._push_arguments(last_arguments)
self._gas = last_gas
self._pc = last_pc
self._allocated = allocated
self._checkpoint_data = None |
def _check_jmpdest(self):
"""
If the previous instruction was a JUMP/JUMPI and the conditional was
True, this checks that the current instruction must be a JUMPDEST.
Here, if symbolic, the conditional `self._check_jumpdest` would be
already constrained to a single concrete value.
"""
should_check_jumpdest = self._check_jumpdest
if issymbolic(should_check_jumpdest):
should_check_jumpdest_solutions = solver.get_all_values(self.constraints, should_check_jumpdest)
if len(should_check_jumpdest_solutions) != 1:
raise EthereumError("Conditional not concretized at JMPDEST check")
should_check_jumpdest = should_check_jumpdest_solutions[0]
if should_check_jumpdest:
self._check_jumpdest = False
pc = self.pc.value if isinstance(self.pc, Constant) else self.pc
if pc not in self._valid_jumpdests:
raise InvalidOpcode() |
def _store(self, offset, value, size=1):
"""Stores value in memory as a big endian"""
self.memory.write_BE(offset, value, size)
for i in range(size):
self._publish('did_evm_write_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8)) |
def DIV(self, a, b):
"""Integer division operation"""
try:
result = Operators.UDIV(a, b)
except ZeroDivisionError:
result = 0
return Operators.ITEBV(256, b == 0, 0, result) |
def SDIV(self, a, b):
"""Signed integer division operation (truncated)"""
s0, s1 = to_signed(a), to_signed(b)
try:
result = (Operators.ABS(s0) // Operators.ABS(s1) * Operators.ITEBV(256, (s0 < 0) != (s1 < 0), -1, 1))
except ZeroDivisionError:
result = 0
result = Operators.ITEBV(256, b == 0, 0, result)
if not issymbolic(result):
result = to_signed(result)
return result |
def MOD(self, a, b):
"""Modulo remainder operation"""
try:
result = Operators.ITEBV(256, b == 0, 0, a % b)
except ZeroDivisionError:
result = 0
return result |
def SMOD(self, a, b):
"""Signed modulo remainder operation"""
s0, s1 = to_signed(a), to_signed(b)
sign = Operators.ITEBV(256, s0 < 0, -1, 1)
try:
result = (Operators.ABS(s0) % Operators.ABS(s1)) * sign
except ZeroDivisionError:
result = 0
return Operators.ITEBV(256, s1 == 0, 0, result) |
def ADDMOD(self, a, b, c):
"""Modulo addition operation"""
try:
result = Operators.ITEBV(256, c == 0, 0, (a + b) % c)
except ZeroDivisionError:
result = 0
return result |
def EXP_gas(self, base, exponent):
"""Calculate extra gas fee"""
EXP_SUPPLEMENTAL_GAS = 10 # cost of EXP exponent per byte
def nbytes(e):
result = 0
for i in range(32):
result = Operators.ITEBV(512, Operators.EXTRACT(e, i * 8, 8) != 0, i + 1, result)
return result
return EXP_SUPPLEMENTAL_GAS * nbytes(exponent) |
def SIGNEXTEND(self, size, value):
"""Extend length of two's complement signed integer"""
# FIXME maybe use Operators.SEXTEND
testbit = Operators.ITEBV(256, size <= 31, size * 8 + 7, 257)
result1 = (value | (TT256 - (1 << testbit)))
result2 = (value & ((1 << testbit) - 1))
result = Operators.ITEBV(256, (value & (1 << testbit)) != 0, result1, result2)
return Operators.ITEBV(256, size <= 31, result, value) |
def LT(self, a, b):
"""Less-than comparison"""
return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0) |
def GT(self, a, b):
"""Greater-than comparison"""
return Operators.ITEBV(256, Operators.UGT(a, b), 1, 0) |
def SGT(self, a, b):
"""Signed greater-than comparison"""
# http://gavwood.com/paper.pdf
s0, s1 = to_signed(a), to_signed(b)
return Operators.ITEBV(256, s0 > s1, 1, 0) |
def BYTE(self, offset, value):
"""Retrieve single byte from word"""
offset = Operators.ITEBV(256, offset < 32, (31 - offset) * 8, 256)
return Operators.ZEXTEND(Operators.EXTRACT(value, offset, 8), 256) |
def SHA3(self, start, size):
"""Compute Keccak-256 hash"""
# read memory from start to end
# http://gavwood.com/paper.pdf
data = self.try_simplify_to_constant(self.read_buffer(start, size))
if issymbolic(data):
known_sha3 = {}
# Broadcast the signal
self._publish('on_symbolic_sha3', data, known_sha3) # This updates the local copy of sha3 with the pairs we need to explore
value = 0 # never used
known_hashes_cond = False
for key, hsh in known_sha3.items():
assert not issymbolic(key), "Saved sha3 data,hash pairs should be concrete"
cond = key == data
known_hashes_cond = Operators.OR(cond, known_hashes_cond)
value = Operators.ITEBV(256, cond, hsh, value)
return value
value = sha3.keccak_256(data).hexdigest()
value = int(value, 16)
self._publish('on_concrete_sha3', data, value)
logger.info("Found a concrete SHA3 example %r -> %x", data, value)
return value |
def CALLDATALOAD(self, offset):
"""Get input data of current environment"""
if issymbolic(offset):
if solver.can_be_true(self._constraints, offset == self._used_calldata_size):
self.constraints.add(offset == self._used_calldata_size)
raise ConcretizeArgument(1, policy='SAMPLED')
self._use_calldata(offset, 32)
data_length = len(self.data)
bytes = []
for i in range(32):
try:
c = Operators.ITEBV(8, offset + i < data_length, self.data[offset + i], 0)
except IndexError:
# offset + i is concrete and outside data
c = 0
bytes.append(c)
return Operators.CONCAT(256, *bytes) |
def CALLDATACOPY(self, mem_offset, data_offset, size):
"""Copy input data in current environment to memory"""
if issymbolic(size):
if solver.can_be_true(self._constraints, size <= len(self.data) + 32):
self.constraints.add(size <= len(self.data) + 32)
raise ConcretizeArgument(3, policy='SAMPLED')
if issymbolic(data_offset):
if solver.can_be_true(self._constraints, data_offset == self._used_calldata_size):
self.constraints.add(data_offset == self._used_calldata_size)
raise ConcretizeArgument(2, policy='SAMPLED')
#account for calldata usage
self._use_calldata(data_offset, size)
self._allocate(mem_offset, size)
for i in range(size):
try:
c = Operators.ITEBV(8, data_offset + i < len(self.data), Operators.ORD(self.data[data_offset + i]), 0)
except IndexError:
# data_offset + i is concrete and outside data
c = 0
self._store(mem_offset + i, c) |
def CODECOPY(self, mem_offset, code_offset, size):
"""Copy code running in current environment to memory"""
self._allocate(mem_offset, size)
GCOPY = 3 # cost to copy one 32 byte word
copyfee = self.safe_mul(GCOPY, Operators.UDIV(self.safe_add(size, 31), 32))
self._consume(copyfee)
if issymbolic(size):
max_size = solver.max(self.constraints, size)
else:
max_size = size
for i in range(max_size):
if issymbolic(i < size):
default = Operators.ITEBV(8, i < size, 0, self._load(mem_offset + i, 1)) # Fixme. unnecessary memory read
else:
if i < size:
default = 0
else:
default = self._load(mem_offset + i, 1)
if issymbolic(code_offset):
value = Operators.ITEBV(8, code_offset + i >= len(self.bytecode), default, self.bytecode[code_offset + i])
else:
if code_offset + i >= len(self.bytecode):
value = default
else:
value = self.bytecode[code_offset + i]
self._store(mem_offset + i, value)
self._publish('did_evm_read_code', code_offset, size) |
def EXTCODECOPY(self, account, address, offset, size):
"""Copy an account's code to memory"""
extbytecode = self.world.get_code(account)
self._allocate(address + size)
for i in range(size):
if offset + i < len(extbytecode):
self._store(address + i, extbytecode[offset + i])
else:
self._store(address + i, 0) |
def MLOAD(self, address):
"""Load word from memory"""
self._allocate(address, 32)
value = self._load(address, 32)
return value |
def MSTORE(self, address, value):
"""Save word to memory"""
if istainted(self.pc):
for taint in get_taints(self.pc):
value = taint_with(value, taint)
self._allocate(address, 32)
self._store(address, value, 32) |
def MSTORE8(self, address, value):
"""Save byte to memory"""
if istainted(self.pc):
for taint in get_taints(self.pc):
value = taint_with(value, taint)
self._allocate(address, 1)
self._store(address, Operators.EXTRACT(value, 0, 8), 1) |
def SLOAD(self, offset):
"""Load word from storage"""
storage_address = self.address
self._publish('will_evm_read_storage', storage_address, offset)
value = self.world.get_storage_data(storage_address, offset)
self._publish('did_evm_read_storage', storage_address, offset, value)
return value |
def SSTORE(self, offset, value):
"""Save word to storage"""
storage_address = self.address
self._publish('will_evm_write_storage', storage_address, offset, value)
#refund = Operators.ITEBV(256,
# previous_value != 0,
# Operators.ITEBV(256, value != 0, 0, GSTORAGEREFUND),
# 0)
if istainted(self.pc):
for taint in get_taints(self.pc):
value = taint_with(value, taint)
self.world.set_storage_data(storage_address, offset, value)
self._publish('did_evm_write_storage', storage_address, offset, value) |
def JUMPI(self, dest, cond):
"""Conditionally alter the program counter"""
self.pc = Operators.ITEBV(256, cond != 0, dest, self.pc + self.instruction.size)
#This set ups a check for JMPDEST in the next instruction if cond != 0
self._set_check_jmpdest(cond != 0) |
def SWAP(self, *operands):
"""Exchange 1st and 2nd stack items"""
a = operands[0]
b = operands[-1]
return (b,) + operands[1:-1] + (a,) |
def CREATE(self, value, offset, size):
"""Create a new account with associated code"""
address = self.world.create_account(address=EVMWorld.calculate_new_address(sender=self.address, nonce=self.world.get_nonce(self.address)))
self.world.start_transaction('CREATE',
address,
data=self.read_buffer(offset, size),
caller=self.address,
value=value,
gas=self.gas)
raise StartTx() |
def CREATE(self, value, offset, size):
"""Create a new account with associated code"""
tx = self.world.last_transaction # At this point last and current tx are the same.
address = tx.address
if tx.result == 'RETURN':
self.world.set_code(tx.address, tx.return_data)
else:
self.world.delete_account(address)
address = 0
return address |
def CALLCODE(self, gas, _ignored_, value, in_offset, in_size, out_offset, out_size):
"""Message-call into this account with alternative account's code"""
self.world.start_transaction('CALLCODE',
address=self.address,
data=self.read_buffer(in_offset, in_size),
caller=self.address,
value=value,
gas=gas)
raise StartTx() |
def RETURN(self, offset, size):
"""Halt execution returning output data"""
data = self.read_buffer(offset, size)
raise EndTx('RETURN', data) |
def SELFDESTRUCT(self, recipient):
"""Halt execution and register account for later deletion"""
#This may create a user account
recipient = Operators.EXTRACT(recipient, 0, 160)
address = self.address
#FIXME for on the known addresses
if issymbolic(recipient):
logger.info("Symbolic recipient on self destruct")
recipient = solver.get_value(self.constraints, recipient)
if recipient not in self.world:
self.world.create_account(address=recipient)
self.world.send_funds(address, recipient, self.world.get_balance(address))
self.world.delete_account(address)
raise EndTx('SELFDESTRUCT') |
def human_transactions(self):
"""Completed human transaction"""
txs = []
for tx in self.transactions:
if tx.depth == 0:
txs.append(tx)
return tuple(txs) |
def current_vm(self):
"""current vm"""
try:
_, _, _, _, vm = self._callstack[-1]
return vm
except IndexError:
return None |
def current_transaction(self):
"""current tx"""
try:
tx, _, _, _, _ = self._callstack[-1]
if tx.result is not None:
#That tx finished. No current tx.
return None
return tx
except IndexError:
return None |
def current_human_transaction(self):
"""Current ongoing human transaction"""
try:
tx, _, _, _, _ = self._callstack[0]
if tx.result is not None:
#That tx finished. No current tx.
return None
assert tx.depth == 0
return tx
except IndexError:
return None |
def get_storage_data(self, storage_address, offset):
"""
Read a value from a storage slot on the specified account
:param storage_address: an account address
:param offset: the storage slot to use.
:type offset: int or BitVec
:return: the value
:rtype: int or BitVec
"""
value = self._world_state[storage_address]['storage'].get(offset, 0)
return simplify(value) |
def set_storage_data(self, storage_address, offset, value):
"""
Writes a value to a storage slot in specified account
:param storage_address: an account address
:param offset: the storage slot to use.
:type offset: int or BitVec
:param value: the value to write
:type value: int or BitVec
"""
self._world_state[storage_address]['storage'][offset] = value |
def get_storage_items(self, address):
"""
Gets all items in an account storage
:param address: account address
:return: all items in account storage. items are tuple of (index, value). value can be symbolic
:rtype: list[(storage_index, storage_value)]
"""
storage = self._world_state[address]['storage']
items = []
array = storage.array
while not isinstance(array, ArrayVariable):
items.append((array.index, array.value))
array = array.array
return items |
def has_storage(self, address):
"""
True if something has been written to the storage.
Note that if a slot has been erased from the storage this function may
lose any meaning.
"""
storage = self._world_state[address]['storage']
array = storage.array
while not isinstance(array, ArrayVariable):
if isinstance(array, ArrayStore):
return True
array = array.array
return False |
def block_hash(self, block_number=None, force_recent=True):
"""
Calculates a block's hash
:param block_number: the block number for which to calculate the hash, defaulting to the most recent block
:param force_recent: if True (the default) return zero for any block that is in the future or older than 256 blocks
:return: the block hash
"""
if block_number is None:
block_number = self.block_number() - 1
# We are not maintaining an actual -block-chain- so we just generate
# some hashes for each virtual block
value = sha3.keccak_256((repr(block_number) + 'NONCE').encode()).hexdigest()
value = int(value, 16)
if force_recent:
# 0 is left on the stack if the looked for block number is greater or equal
# than the current block number or more than 256 blocks behind the current
# block. (Current block hash is unknown from inside the tx)
bnmax = Operators.ITEBV(256, self.block_number() > 256, 256, self.block_number())
value = Operators.ITEBV(256, Operators.OR(block_number >= self.block_number(), block_number < bnmax), 0, value)
return value |
def new_address(self, sender=None, nonce=None):
"""Create a fresh 160bit address"""
if sender is not None and nonce is None:
nonce = self.get_nonce(sender)
new_address = self.calculate_new_address(sender, nonce)
if sender is None and new_address in self:
return self.new_address(sender, nonce)
return new_address |
def create_account(self, address=None, balance=0, code=None, storage=None, nonce=None):
"""
Low level account creation. No transaction is done.
:param address: the address of the account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible.
:param balance: the initial balance of the account in Wei
:param code: the runtime code of the account, if a contract
:param storage: storage array
:param nonce: the nonce for the account; contracts should have a nonce greater than or equal to 1
"""
if code is None:
code = bytes()
else:
if not isinstance(code, (bytes, Array)):
raise EthereumError('Wrong code type')
# nonce default to initial nonce
if nonce is None:
# As per EIP 161, contract accounts are initialized with a nonce of 1
nonce = 1 if code else 0
if address is None:
address = self.new_address()
if not isinstance(address, int):
raise EthereumError('You must provide an address')
if address in self.accounts:
# FIXME account may have been created via selfdestruct destination
# or CALL and may contain some ether already, though if it was a
# selfdestructed address, it can not be reused
raise EthereumError('The account already exists')
if storage is None:
# Uninitialized values in a storage are 0 by spec
storage = self.constraints.new_array(index_bits=256, value_bits=256, name=f'STORAGE_{address:x}', avoid_collisions=True, default=0)
else:
if isinstance(storage, ArrayProxy):
if storage.index_bits != 256 or storage.value_bits != 256:
raise TypeError("An ArrayProxy 256bits -> 256bits is needed")
else:
if any((k < 0 or k >= 1 << 256 for k, v in storage.items())):
raise TypeError("Need a dict like object that maps 256 bits keys to 256 bits values")
# Hopefully here we have a mapping from 256b to 256b
self._world_state[address] = {}
self._world_state[address]['nonce'] = nonce
self._world_state[address]['balance'] = balance
self._world_state[address]['storage'] = storage
self._world_state[address]['code'] = code
# adds hash of new address
data = binascii.unhexlify('{:064x}{:064x}'.format(address, 0))
value = sha3.keccak_256(data).hexdigest()
value = int(value, 16)
self._publish('on_concrete_sha3', data, value)
return address |
def create_contract(self, price=0, address=None, caller=None, balance=0, init=None, gas=None):
"""
Create a contract account. Sends a transaction to initialize the contract
:param address: the address of the new account, if known. If omitted, a new address will be generated as closely to the Yellow Paper as possible.
:param balance: the initial balance of the account in Wei
:param init: the initialization code of the contract
The way that the Solidity compiler expects the constructor arguments to
be passed is by appending the arguments to the byte code produced by the
Solidity compiler. The arguments are formatted as defined in the Ethereum
ABI2. The arguments are then copied from the init byte array to the EVM
memory through the CODECOPY opcode with appropriate values on the stack.
This is done when the byte code in the init byte array is actually run
on the network.
"""
expected_address = self.create_account(self.new_address(sender=caller))
if address is None:
address = expected_address
elif caller is not None and address != expected_address:
raise EthereumError(f"Error: contract created from address {hex(caller)} with nonce {self.get_nonce(caller)} was expected to be at address {hex(expected_address)}, but create_contract was called with address={hex(address)}")
self.start_transaction('CREATE', address, price, init, caller, balance, gas=gas)
self._process_pending_transaction()
return address |
def start_transaction(self, sort, address, price=None, data=None, caller=None, value=0, gas=2300):
"""
Initiate a transaction
:param sort: the type of transaction. CREATE or CALL or DELEGATECALL
:param address: the address of the account which owns the code that is executing.
:param price: the price of gas in the transaction that originated this execution.
:param data: the byte array that is the input data to this execution
:param caller: the address of the account which caused the code to be executing. A 160-bit code used for identifying Accounts
:param value: the value, in Wei, passed to this account as part of the same procedure as execution. One Ether is defined as being 10**18 Wei.
:param bytecode: the byte array that is the machine code to be executed.
:param gas: gas budget for this transaction.
"""
assert self._pending_transaction is None, "Already started tx"
self._pending_transaction = PendingTransaction(sort, address, price, data, caller, value, gas) |
def _get_expand_imm_carry(self, carryIn):
"""Manually compute the carry bit produced by expanding an immediate operand (see ARMExpandImm_C)"""
insn = struct.unpack('<I', self.cpu.instruction.bytes)[0]
unrotated = insn & Mask(8)
shift = Operators.EXTRACT(insn, 8, 4)
_, carry = self.cpu._shift(unrotated, cs.arm.ARM_SFT_ROR, 2 * shift, carryIn)
return carry |
def _write_APSR(self, apsr):
"""Auxiliary function - Writes flags from a full APSR (only 4 msb used)"""
V = Operators.EXTRACT(apsr, 28, 1)
C = Operators.EXTRACT(apsr, 29, 1)
Z = Operators.EXTRACT(apsr, 30, 1)
N = Operators.EXTRACT(apsr, 31, 1)
self.write('APSR_V', V)
self.write('APSR_C', C)
self.write('APSR_Z', Z)
self.write('APSR_N', N) |
def _swap_mode(self):
"""Toggle between ARM and Thumb mode"""
assert self.mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB)
if self.mode == cs.CS_MODE_ARM:
self.mode = cs.CS_MODE_THUMB
else:
self.mode = cs.CS_MODE_ARM |
def set_flags(self, **flags):
"""
Note: For any unmodified flags, update _last_flags with the most recent
committed value. Otherwise, for example, this could happen:
overflow=0
instr1 computes overflow=1, updates _last_flags, doesn't commit
instr2 updates all flags in _last_flags except overflow (overflow remains 1 in _last_flags)
instr2 commits all in _last_flags
now overflow=1 even though it should still be 0
"""
unupdated_flags = self._last_flags.keys() - flags.keys()
for flag in unupdated_flags:
flag_name = f'APSR_{flag}'
self._last_flags[flag] = self.regfile.read(flag_name)
self._last_flags.update(flags) |
def _shift(cpu, value, _type, amount, carry):
"""See Shift() and Shift_C() in the ARM manual"""
assert(cs.arm.ARM_SFT_INVALID < _type <= cs.arm.ARM_SFT_RRX_REG)
# XXX: Capstone should set the value of an RRX shift to 1, which is
# asserted in the manual, but it sets it to 0, so we have to check
if _type in (cs.arm.ARM_SFT_RRX, cs.arm.ARM_SFT_RRX_REG) and amount != 1:
amount = 1
elif _type in range(cs.arm.ARM_SFT_ASR_REG, cs.arm.ARM_SFT_RRX_REG + 1):
if cpu.mode == cs.CS_MODE_THUMB:
src = amount.read()
else:
src_reg = cpu.instruction.reg_name(amount).upper()
src = cpu.regfile.read(src_reg)
amount = Operators.EXTRACT(src, 0, 8)
if amount == 0:
return value, carry
width = cpu.address_bit_size
if _type in (cs.arm.ARM_SFT_ASR, cs.arm.ARM_SFT_ASR_REG):
return ASR_C(value, amount, width)
elif _type in (cs.arm.ARM_SFT_LSL, cs.arm.ARM_SFT_LSL_REG):
return LSL_C(value, amount, width)
elif _type in (cs.arm.ARM_SFT_LSR, cs.arm.ARM_SFT_LSR_REG):
return LSR_C(value, amount, width)
elif _type in (cs.arm.ARM_SFT_ROR, cs.arm.ARM_SFT_ROR_REG):
return ROR_C(value, amount, width)
elif _type in (cs.arm.ARM_SFT_RRX, cs.arm.ARM_SFT_RRX_REG):
return RRX_C(value, carry, width)
raise NotImplementedError("Bad shift value") |
def MOV(cpu, dest, src):
"""
Implement the MOV{S} instruction.
Note: If src operand is PC, temporarily release our logical PC
view and conform to the spec, which dictates PC = curr instr + 8
:param Armv7Operand dest: The destination operand; register.
:param Armv7Operand src: The source operand; register or immediate.
"""
if cpu.mode == cs.CS_MODE_ARM:
result, carry_out = src.read(with_carry=True)
dest.write(result)
cpu.set_flags(C=carry_out, N=HighBit(result), Z=(result == 0))
else:
# thumb mode cannot do wonky things to the operand, so no carry calculation
result = src.read()
dest.write(result)
cpu.set_flags(N=HighBit(result), Z=(result == 0)) |
def MOVT(cpu, dest, src):
"""
MOVT writes imm16 to Rd[31:16]. The write does not affect Rd[15:0].
:param Armv7Operand dest: The destination operand; register
:param Armv7Operand src: The source operand; 16-bit immediate
"""
assert src.type == 'immediate'
imm = src.read()
low_halfword = dest.read() & Mask(16)
dest.write((imm << 16) | low_halfword) |
def MRC(cpu, coprocessor, opcode1, dest, coprocessor_reg_n, coprocessor_reg_m, opcode2):
"""
MRC moves to ARM register from coprocessor.
:param Armv7Operand coprocessor: The name of the coprocessor; immediate
:param Armv7Operand opcode1: coprocessor specific opcode; 3-bit immediate
:param Armv7Operand dest: the destination operand: register
:param Armv7Operand coprocessor_reg_n: the coprocessor register; immediate
:param Armv7Operand coprocessor_reg_m: the coprocessor register; immediate
:param Armv7Operand opcode2: coprocessor specific opcode; 3-bit immediate
"""
assert coprocessor.type == 'coprocessor'
assert opcode1.type == 'immediate'
assert opcode2.type == 'immediate'
assert dest.type == 'register'
imm_coprocessor = coprocessor.read()
imm_opcode1 = opcode1.read()
imm_opcode2 = opcode2.read()
coprocessor_n_name = coprocessor_reg_n.read()
coprocessor_m_name = coprocessor_reg_m.read()
if 15 == imm_coprocessor: # MMU
if 0 == imm_opcode1:
if 13 == coprocessor_n_name:
if 3 == imm_opcode2:
dest.write(cpu.regfile.read('P15_C13'))
return
raise NotImplementedError("MRC: unimplemented combination of coprocessor, opcode, and coprocessor register") |
def LDRD(cpu, dest1, dest2, src, offset=None):
"""Loads double width data from memory."""
assert dest1.type == 'register'
assert dest2.type == 'register'
assert src.type == 'memory'
mem1 = cpu.read_int(src.address(), 32)
mem2 = cpu.read_int(src.address() + 4, 32)
writeback = cpu._compute_writeback(src, offset)
dest1.write(mem1)
dest2.write(mem2)
cpu._cs_hack_ldr_str_writeback(src, offset, writeback) |
def STRD(cpu, src1, src2, dest, offset=None):
"""Writes the contents of two registers to memory."""
assert src1.type == 'register'
assert src2.type == 'register'
assert dest.type == 'memory'
val1 = src1.read()
val2 = src2.read()
writeback = cpu._compute_writeback(dest, offset)
cpu.write_int(dest.address(), val1, 32)
cpu.write_int(dest.address() + 4, val2, 32)
cpu._cs_hack_ldr_str_writeback(dest, offset, writeback) |
def LDREX(cpu, dest, src, offset=None):
"""
LDREX loads data from memory.
* If the physical address has the shared TLB attribute, LDREX
tags the physical address as exclusive access for the current
processor, and clears any exclusive access tag for this
processor for any other physical address.
* Otherwise, it tags the fact that the executing processor has
an outstanding tagged physical address.
:param Armv7Operand dest: the destination register; register
:param Armv7Operand src: the source operand: register
"""
# TODO: add lock mechanism to underlying memory --GR, 2017-06-06
cpu._LDR(dest, src, 32, False, offset) |
def STREX(cpu, status, *args):
"""
STREX performs a conditional store to memory.
:param Armv7Operand status: the destination register for the returned status; register
"""
# TODO: implement conditional return with appropriate status --GR, 2017-06-06
status.write(0)
return cpu._STR(cpu.address_bit_size, *args) |
def _UXT(cpu, dest, src, src_width):
"""
Helper for UXT* family of instructions.
:param ARMv7Operand dest: the destination register; register
:param ARMv7Operand dest: the source register; register
:param int src_width: bits to consider of the src operand
"""
val = GetNBits(src.read(), src_width)
word = Operators.ZEXTEND(val, cpu.address_bit_size)
dest.write(word) |
def ADR(cpu, dest, src):
"""
Address to Register adds an immediate value to the PC value, and writes the result to the destination register.
:param ARMv7Operand dest: Specifies the destination register.
:param ARMv7Operand src:
Specifies the label of an instruction or literal data item whose address is to be loaded into
<Rd>. The assembler calculates the required value of the offset from the Align(PC,4)
value of the ADR instruction to this label.
"""
aligned_pc = (cpu.instruction.address + 4) & 0xfffffffc
dest.write(aligned_pc + src.read()) |
def ADDW(cpu, dest, src, add):
"""
This instruction adds an immediate value to a register value, and writes the result to the destination register.
It doesn't update the condition flags.
:param ARMv7Operand dest: Specifies the destination register. If omitted, this register is the same as src.
:param ARMv7Operand src:
Specifies the register that contains the first operand. If the SP is specified for dest, see ADD (SP plus
immediate). If the PC is specified for dest, see ADR.
:param ARMv7Operand add:
Specifies the immediate value to be added to the value obtained from src. The range of allowed values is
0-4095.
"""
aligned_pc = (cpu.instruction.address + 4) & 0xfffffffc
if src.type == 'register' and src.reg in ('PC', 'R15'):
src = aligned_pc
else:
src = src.read()
dest.write(src + add.read()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.