partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
Workspace.save_state
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
manticore/core/workspace.py
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 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
[ "Save", "a", "state", "to", "storage", "return", "identifier", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L386-L402
[ "def", "save_state", "(", "self", ",", "state", ",", "state_id", "=", "None", ")", ":", "assert", "isinstance", "(", "state", ",", "StateBase", ")", "if", "state_id", "is", "None", ":", "state_id", "=", "self", ".", "_get_id", "(", ")", "else", ":", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ManticoreOutput._named_stream
Create an indexed output stream i.e. 'test_00000001.name' :param name: Identifier for the stream :return: A context-managed stream-like object
manticore/core/workspace.py
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 _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
[ "Create", "an", "indexed", "output", "stream", "i", ".", "e", ".", "test_00000001", ".", "name" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L470-L478
[ "def", "_named_stream", "(", "self", ",", "name", ",", "binary", "=", "False", ")", ":", "with", "self", ".", "_store", ".", "save_stream", "(", "self", ".", "_named_key", "(", "name", ")", ",", "binary", "=", "binary", ")", "as", "s", ":", "yield", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
t_UINTN
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)
manticore/ethereum/abitypes.py
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_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
[ "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", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abitypes.py#L51-L55
[ "def", "t_UINTN", "(", "t", ")", ":", "size", "=", "int", "(", "t", ".", "lexer", ".", "lexmatch", ".", "group", "(", "'size'", ")", ")", "t", ".", "value", "=", "(", "'uint'", ",", "size", ")", "return", "t" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
t_INTN
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)
manticore/ethereum/abitypes.py
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_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
[ "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", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abitypes.py#L76-L80
[ "def", "t_INTN", "(", "t", ")", ":", "size", "=", "int", "(", "t", ".", "lexer", ".", "lexmatch", ".", "group", "(", "'size'", ")", ")", "t", ".", "value", "=", "(", "'int'", ",", "size", ")", "return", "t" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
t_UFIXEDMN
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)
manticore/ethereum/abitypes.py
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_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
[ "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|...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abitypes.py#L103-L108
[ "def", "t_UFIXEDMN", "(", "t", ")", ":", "M", "=", "int", "(", "t", ".", "lexer", ".", "lexmatch", ".", "group", "(", "'M'", ")", ")", "N", "=", "int", "(", "t", ".", "lexer", ".", "lexmatch", ".", "group", "(", "'N'", ")", ")", "t", ".", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
t_BYTESM
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)
manticore/ethereum/abitypes.py
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 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
[ "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", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abitypes.py#L117-L121
[ "def", "t_BYTESM", "(", "t", ")", ":", "size", "=", "int", "(", "t", ".", "lexer", ".", "lexmatch", ".", "group", "(", "'nbytes'", ")", ")", "t", ".", "value", "=", "(", "'bytesM'", ",", "size", ")", "return", "t" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
p_dynamic_fixed_type
T : T LBRAKET NUMBER RBRAKET
manticore/ethereum/abitypes.py
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 p_dynamic_fixed_type(p): """ T : T LBRAKET NUMBER RBRAKET """ reps = int(p[3]) base_type = p[1] p[0] = ('array', reps, base_type)
[ "T", ":", "T", "LBRAKET", "NUMBER", "RBRAKET" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abitypes.py#L210-L216
[ "def", "p_dynamic_fixed_type", "(", "p", ")", ":", "reps", "=", "int", "(", "p", "[", "3", "]", ")", "base_type", "=", "p", "[", "1", "]", "p", "[", "0", "]", "=", "(", "'array'", ",", "reps", ",", "base_type", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
cmp_regs
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
scripts/verify.py
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 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
[ "Compare", "registers", "from", "a", "remote", "gdb", "session", "to", "current", "mcore", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/verify.py#L36-L60
[ "def", "cmp_regs", "(", "cpu", ",", "should_print", "=", "False", ")", ":", "differing", "=", "False", "gdb_regs", "=", "gdb", ".", "getCanonicalRegisters", "(", ")", "for", "name", "in", "sorted", "(", "gdb_regs", ")", ":", "vg", "=", "gdb_regs", "[", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
post_mcore
Handle syscalls (import memory) and bail if we diverge
scripts/verify.py
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 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()
[ "Handle", "syscalls", "(", "import", "memory", ")", "and", "bail", "if", "we", "diverge" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/verify.py#L67-L112
[ "def", "post_mcore", "(", "state", ",", "last_instruction", ")", ":", "global", "in_helper", "# Synchronize qemu state to manticore's after a system call", "if", "last_instruction", ".", "mnemonic", ".", "lower", "(", ")", "==", "'svc'", ":", "# Synchronize all writes tha...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
sync_svc
Mirror some service calls in manticore. Happens after qemu executed a SVC instruction, but before manticore did.
scripts/verify.py
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 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
[ "Mirror", "some", "service", "calls", "in", "manticore", ".", "Happens", "after", "qemu", "executed", "a", "SVC", "instruction", "but", "before", "manticore", "did", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/verify.py#L122-L143
[ "def", "sync_svc", "(", "state", ")", ":", "syscall", "=", "state", ".", "cpu", ".", "R7", "# Grab idx from manticore since qemu could have exited", "name", "=", "linux_syscalls", ".", "armv7", "[", "syscall", "]", "logger", ".", "debug", "(", "f\"Syncing syscall:...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
initialize
Synchronize the stack and register state (manticore->qemu)
scripts/verify.py
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 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)
[ "Synchronize", "the", "stack", "and", "register", "state", "(", "manticore", "-", ">", "qemu", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/scripts/verify.py#L145-L169
[ "def", "initialize", "(", "state", ")", ":", "logger", ".", "debug", "(", "f\"Copying {stack_top - state.cpu.SP} bytes in the stack..\"", ")", "stack_bottom", "=", "min", "(", "state", ".", "cpu", ".", "SP", ",", "gdb", ".", "getR", "(", "'SP'", ")", ")", "f...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
to_constant
Iff the expression can be simplified to a Constant get the actual concrete value. This discards/ignore any taint
manticore/core/smtlib/visitors.py
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 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
[ "Iff", "the", "expression", "can", "be", "simplified", "to", "a", "Constant", "get", "the", "actual", "concrete", "value", ".", "This", "discards", "/", "ignore", "any", "taint" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L580-L601
[ "def", "to_constant", "(", "expression", ")", ":", "value", "=", "simplify", "(", "expression", ")", "if", "isinstance", "(", "value", ",", "Expression", ")", "and", "value", ".", "taint", ":", "raise", "ValueError", "(", "\"Can not simplify tainted values to co...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Visitor.visit
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
manticore/core/smtlib/visitors.py
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 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)
[ "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",...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L65-L107
[ "def", "visit", "(", "self", ",", "node", ",", "use_fixed_point", "=", "False", ")", ":", "cache", "=", "self", ".", "_cache", "visited", "=", "set", "(", ")", "stack", "=", "[", "]", "stack", ".", "append", "(", "node", ")", "while", "stack", ":",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
PrettyPrinter._method
Overload Visitor._method because we want to stop to iterate over the visit_ functions as soon as a valid visit_ function is found
manticore/core/smtlib/visitors.py
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 _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
[ "Overload", "Visitor", ".", "_method", "because", "we", "want", "to", "stop", "to", "iterate", "over", "the", "visit_", "functions", "as", "soon", "as", "a", "valid", "visit_", "function", "is", "found" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L197-L210
[ "def", "_method", "(", "self", ",", "expression", ",", "*", "args", ")", ":", "assert", "expression", ".", "__class__", ".", "__mro__", "[", "-", "1", "]", "is", "object", "for", "cls", "in", "expression", ".", "__class__", ".", "__mro__", ":", "sort",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConstantFolderSimplifier.visit_Operation
constant folding, if all operands of an expression are a Constant do the math
manticore/core/smtlib/visitors.py
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 """ 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
[ "constant", "folding", "if", "all", "operands", "of", "an", "expression", "are", "a", "Constant", "do", "the", "math" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L317-L331
[ "def", "visit_Operation", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "operation", "=", "self", ".", "operations", ".", "get", "(", "type", "(", "expression", ")", ",", "None", ")", "if", "operation", "is", "not", "None", "and", "al...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_Operation
constant folding, if all operands of an expression are a Constant do the math
manticore/core/smtlib/visitors.py
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_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
[ "constant", "folding", "if", "all", "operands", "of", "an", "expression", "are", "a", "Constant", "do", "the", "math" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L362-L368
[ "def", "visit_Operation", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "if", "all", "(", "isinstance", "(", "o", ",", "Constant", ")", "for", "o", "in", "operands", ")", ":", "expression", "=", "constant_folder", "(", "expression", ")"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_BitVecConcat
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)
manticore/core/smtlib/visitors.py
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_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)
[ "concat", "(", "extract", "(", "k1", "0", "a", ")", "extract", "(", "sizeof", "(", "a", ")", "-", "k1", "k1", "a", "))", "==", ">", "a", "concat", "(", "extract", "(", "k1", "beg", "a", ")", "extract", "(", "end", "k1", "a", "))", "==", ">", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L388-L420
[ "def", "visit_BitVecConcat", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "op", "=", "expression", ".", "operands", "[", "0", "]", "value", "=", "None", "end", "=", "None", "begining", "=", "None", "for", "o", "in", "operands", ":", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_BitVecExtract
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)
manticore/core/smtlib/visitors.py
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_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)
[ "extract", "(", "sizeof", "(", "a", ")", "0", ")", "(", "a", ")", "==", ">", "a", "extract", "(", "16", "0", ")", "(", "concat", "(", "a", "b", "c", "d", ")", ")", "=", ">", "concat", "(", "c", "d", ")", "extract", "(", "m", "M", ")", "...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L422-L452
[ "def", "visit_BitVecExtract", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "op", "=", "expression", ".", "operands", "[", "0", "]", "begining", "=", "expression", ".", "begining", "end", "=", "expression", ".", "end", "size", "=", "end...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_BitVecAdd
a + 0 ==> a 0 + a ==> a
manticore/core/smtlib/visitors.py
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_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
[ "a", "+", "0", "==", ">", "a", "0", "+", "a", "==", ">", "a" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L454-L465
[ "def", "visit_BitVecAdd", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "left", "=", "expression", ".", "operands", "[", "0", "]", "right", "=", "expression", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "right", ",", "Bit...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_BitVecSub
a - 0 ==> 0 (a + b) - b ==> a (b + a) - b ==> a
manticore/core/smtlib/visitors.py
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_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]
[ "a", "-", "0", "==", ">", "0", "(", "a", "+", "b", ")", "-", "b", "==", ">", "a", "(", "b", "+", "a", ")", "-", "b", "==", ">", "a" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L467-L478
[ "def", "visit_BitVecSub", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "left", "=", "expression", ".", "operands", "[", "0", "]", "right", "=", "expression", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "left", ",", "BitV...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_BitVecOr
a | 0 => a 0 | a => a 0xffffffff & a => 0xffffffff a & 0xffffffff => 0xffffffff
manticore/core/smtlib/visitors.py
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_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)
[ "a", "|", "0", "=", ">", "a", "0", "|", "a", "=", ">", "a", "0xffffffff", "&", "a", "=", ">", "0xffffffff", "a", "&", "0xffffffff", "=", ">", "0xffffffff" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L480-L500
[ "def", "visit_BitVecOr", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "left", "=", "expression", ".", "operands", "[", "0", "]", "right", "=", "expression", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "right", ",", "BitV...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_BitVecAnd
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 |
manticore/core/smtlib/visitors.py
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_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)
[ "ct", "&", "x", "=", ">", "x", "&", "ct", "move", "constants", "to", "the", "right", "a", "&", "0", "=", ">", "0", "remove", "zero", "a", "&", "0xffffffff", "=", ">", "a", "remove", "full", "mask", "(", "b", "&", "ct2", ")", "&", "ct", "=", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L502-L527
[ "def", "visit_BitVecAnd", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "left", "=", "expression", ".", "operands", "[", "0", "]", "right", "=", "expression", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "right", ",", "Bit...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_BitVecShiftLeft
a << 0 => a remove zero a << ct => 0 if ct > sizeof(a) remove big constant shift
manticore/core/smtlib/visitors.py
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_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
[ "a", "<<", "0", "=", ">", "a", "remove", "zero", "a", "<<", "ct", "=", ">", "0", "if", "ct", ">", "sizeof", "(", "a", ")", "remove", "big", "constant", "shift" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L529-L539
[ "def", "visit_BitVecShiftLeft", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "left", "=", "expression", ".", "operands", "[", "0", "]", "right", "=", "expression", ".", "operands", "[", "1", "]", "if", "isinstance", "(", "right", ",", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ArithmeticSimplifier.visit_ArraySelect
ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0) -> v0
manticore/core/smtlib/visitors.py
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 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)
[ "ArraySelect", "(", "ArrayStore", "((", "ArrayStore", "(", "x0", "v0", ")", "...", ")", "xn", "vn", ")", "x0", ")", "-", ">", "v0" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/smtlib/visitors.py#L541-L561
[ "def", "visit_ArraySelect", "(", "self", ",", "expression", ",", "*", "operands", ")", ":", "arr", ",", "index", "=", "operands", "if", "isinstance", "(", "arr", ",", "ArrayVariable", ")", ":", "return", "if", "isinstance", "(", "index", ",", "BitVecConsta...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI._type_size
Calculate `static` type size
manticore/ethereum/abi.py
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 _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
[ "Calculate", "static", "type", "size" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L24-L40
[ "def", "_type_size", "(", "ty", ")", ":", "if", "ty", "[", "0", "]", "in", "(", "'int'", ",", "'uint'", ",", "'bytesM'", ",", "'function'", ")", ":", "return", "32", "elif", "ty", "[", "0", "]", "in", "(", "'tuple'", ")", ":", "result", "=", "0...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI.function_call
Build transaction data from function signature and arguments
manticore/ethereum/abi.py
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 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
[ "Build", "transaction", "data", "from", "function", "signature", "and", "arguments" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L56-L68
[ "def", "function_call", "(", "type_spec", ",", "*", "args", ")", ":", "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 e...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI.serialize
Serialize value using type specification in ty. ABI.serialize('int256', 1000) ABI.serialize('(int, int256)', 1000, 2000)
manticore/ethereum/abi.py
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 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
[ "Serialize", "value", "using", "type", "specification", "in", "ty", ".", "ABI", ".", "serialize", "(", "int256", "1000", ")", "ABI", ".", "serialize", "(", "(", "int", "int256", ")", "1000", "2000", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L71-L95
[ "def", "serialize", "(", "ty", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "try", ":", "parsed_ty", "=", "abitypes", ".", "parse", "(", "ty", ")", "except", "Exception", "as", "e", ":", "# Catch and rebrand parsing errors", "raise", "EthereumErr...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI.function_selector
Makes a function hash id from a method signature
manticore/ethereum/abi.py
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 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])
[ "Makes", "a", "function", "hash", "id", "from", "a", "method", "signature" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L180-L186
[ "def", "function_selector", "(", "method_name_and_signature", ")", ":", "s", "=", "sha3", ".", "keccak_256", "(", ")", "s", ".", "update", "(", "method_name_and_signature", ".", "encode", "(", ")", ")", "return", "bytes", "(", "s", ".", "digest", "(", ")",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI._serialize_uint
Translates a python integral or a BitVec into a 32 byte string, MSB first
manticore/ethereum/abi.py
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_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
[ "Translates", "a", "python", "integral", "or", "a", "BitVec", "into", "a", "32", "byte", "string", "MSB", "first" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L254-L281
[ "def", "_serialize_uint", "(", "value", ",", "size", "=", "32", ",", "padding", "=", "0", ")", ":", "if", "size", "<=", "0", "or", "size", ">", "32", ":", "raise", "ValueError", "from", ".", "account", "import", "EVMAccount", "# because of circular import"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI._serialize_int
Translates a signed python integral or a BitVec into a 32 byte string, MSB first
manticore/ethereum/abi.py
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 _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
[ "Translates", "a", "signed", "python", "integral", "or", "a", "BitVec", "into", "a", "32", "byte", "string", "MSB", "first" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L284-L304
[ "def", "_serialize_int", "(", "value", ",", "size", "=", "32", ",", "padding", "=", "0", ")", ":", "if", "size", "<=", "0", "or", "size", ">", "32", ":", "raise", "ValueError", "if", "not", "isinstance", "(", "value", ",", "(", "int", ",", "BitVec"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI._deserialize_uint
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
manticore/ethereum/abi.py
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_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
[ "Read", "a", "nbytes", "bytes", "long", "big", "endian", "unsigned", "integer", "from", "data", "starting", "at", "offset" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L334-L345
[ "def", "_deserialize_uint", "(", "data", ",", "nbytes", "=", "32", ",", "padding", "=", "0", ",", "offset", "=", "0", ")", ":", "assert", "isinstance", "(", "data", ",", "(", "bytearray", ",", "Array", ")", ")", "value", "=", "ABI", ".", "_readBE", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ABI._deserialize_int
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
manticore/ethereum/abi.py
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 _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
[ "Read", "a", "nbytes", "bytes", "long", "big", "endian", "signed", "integer", "from", "data", "starting", "at", "offset" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/ethereum/abi.py#L348-L363
[ "def", "_deserialize_int", "(", "data", ",", "nbytes", "=", "32", ",", "padding", "=", "0", ")", ":", "assert", "isinstance", "(", "data", ",", "(", "bytearray", ",", "Array", ")", ")", "value", "=", "ABI", ".", "_readBE", "(", "data", ",", "nbytes",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
concretized_args
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
manticore/platforms/evm.py
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 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
[ "Make", "sure", "an", "EVM", "instruction", "has", "all", "of", "its", "arguments", "concretized", "according", "to", "provided", "policies", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L402-L445
[ "def", "concretized_args", "(", "*", "*", "policies", ")", ":", "def", "concretizer", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "spec", "=", "inspect", ".", "getful...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Transaction.to_dict
Only meant to be used with concrete Transaction objects! (after calling .concretize())
manticore/platforms/evm.py
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 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())
[ "Only", "meant", "to", "be", "used", "with", "concrete", "Transaction", "objects!", "(", "after", "calling", ".", "concretize", "()", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L98-L109
[ "def", "to_dict", "(", "self", ",", "mevm", ")", ":", "return", "dict", "(", "type", "=", "self", ".", "sort", ",", "from_address", "=", "self", ".", "caller", ",", "from_name", "=", "mevm", ".", "account_name", "(", "self", ".", "caller", ")", ",", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Transaction.dump
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:
manticore/platforms/evm.py
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 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
[ "Concretize", "and", "write", "a", "human", "readable", "version", "of", "the", "transaction", "into", "the", "stream", ".", "Used", "during", "testcase", "generation", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L111-L203
[ "def", "dump", "(", "self", ",", "stream", ",", "state", ",", "mevm", ",", "conc_tx", "=", "None", ")", ":", "from", ".", ".", "ethereum", "import", "ABI", "# circular imports", "from", ".", ".", "ethereum", ".", "manticore", "import", "flagged", "is_som...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM._get_memfee
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
manticore/platforms/evm.py
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 _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))
[ "This", "calculates", "the", "amount", "of", "extra", "gas", "needed", "for", "accessing", "to", "previously", "unused", "memory", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L659-L681
[ "def", "_get_memfee", "(", "self", ",", "address", ",", "size", "=", "1", ")", ":", "if", "not", "issymbolic", "(", "size", ")", "and", "size", "==", "0", ":", "return", "0", "address", "=", "self", ".", "safe_add", "(", "address", ",", "size", ")"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.read_code
Read size byte from bytecode. If less than size bytes are available result will be pad with \x00
manticore/platforms/evm.py
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 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
[ "Read", "size", "byte", "from", "bytecode", ".", "If", "less", "than", "size", "bytes", "are", "available", "result", "will", "be", "pad", "with", "\\", "x00" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L699-L708
[ "def", "read_code", "(", "self", ",", "address", ",", "size", "=", "1", ")", ":", "assert", "address", "<", "len", "(", "self", ".", "bytecode", ")", "value", "=", "self", ".", "bytecode", "[", "address", ":", "address", "+", "size", "]", "if", "le...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.instruction
Current instruction pointed by self.pc
manticore/platforms/evm.py
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 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
[ "Current", "instruction", "pointed", "by", "self", ".", "pc" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L718-L747
[ "def", "instruction", "(", "self", ")", ":", "# 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", ":"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM._push
Push into the stack ITEM0 ITEM1 ITEM2 sp-> {empty}
manticore/platforms/evm.py
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 _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)
[ "Push", "into", "the", "stack" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L751-L770
[ "def", "_push", "(", "self", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "int", ")", "or", "isinstance", "(", "value", ",", "BitVec", ")", "and", "value", ".", "size", "==", "256", "if", "len", "(", "self", ".", "stack", ")",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM._top
Read a value from the top of the stack without removing it
manticore/platforms/evm.py
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 _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]
[ "Read", "a", "value", "from", "the", "top", "of", "the", "stack", "without", "removing", "it" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L772-L776
[ "def", "_top", "(", "self", ",", "n", "=", "0", ")", ":", "if", "len", "(", "self", ".", "stack", ")", "-", "n", "<", "0", ":", "raise", "StackUnderflow", "(", ")", "return", "self", ".", "stack", "[", "n", "-", "1", "]" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM._checkpoint
Save and/or get a state checkpoint previous to current instruction
manticore/platforms/evm.py
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 _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
[ "Save", "and", "/", "or", "get", "a", "state", "checkpoint", "previous", "to", "current", "instruction" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L919-L938
[ "def", "_checkpoint", "(", "self", ")", ":", "#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_...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM._rollback
Revert the stack, gas, pc and memory allocation so it looks like before executing the instruction
manticore/platforms/evm.py
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 _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
[ "Revert", "the", "stack", "gas", "pc", "and", "memory", "allocation", "so", "it", "looks", "like", "before", "executing", "the", "instruction" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L940-L947
[ "def", "_rollback", "(", "self", ")", ":", "last_pc", ",", "last_gas", ",", "last_instruction", ",", "last_arguments", ",", "fee", ",", "allocated", "=", "self", ".", "_checkpoint_data", "self", ".", "_push_arguments", "(", "last_arguments", ")", "self", ".", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM._check_jmpdest
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.
manticore/platforms/evm.py
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 _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()
[ "If", "the", "previous", "instruction", "was", "a", "JUMP", "/", "JUMPI", "and", "the", "conditional", "was", "True", "this", "checks", "that", "the", "current", "instruction", "must", "be", "a", "JUMPDEST", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L958-L979
[ "def", "_check_jmpdest", "(", "self", ")", ":", "should_check_jumpdest", "=", "self", ".", "_check_jumpdest", "if", "issymbolic", "(", "should_check_jumpdest", ")", ":", "should_check_jumpdest_solutions", "=", "solver", ".", "get_all_values", "(", "self", ".", "cons...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM._store
Stores value in memory as a big endian
manticore/platforms/evm.py
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 _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))
[ "Stores", "value", "in", "memory", "as", "a", "big", "endian" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1101-L1105
[ "def", "_store", "(", "self", ",", "offset", ",", "value", ",", "size", "=", "1", ")", ":", "self", ".", "memory", ".", "write_BE", "(", "offset", ",", "value", ",", "size", ")", "for", "i", "in", "range", "(", "size", ")", ":", "self", ".", "_...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.DIV
Integer division operation
manticore/platforms/evm.py
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 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)
[ "Integer", "division", "operation" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1146-L1152
[ "def", "DIV", "(", "self", ",", "a", ",", "b", ")", ":", "try", ":", "result", "=", "Operators", ".", "UDIV", "(", "a", ",", "b", ")", "except", "ZeroDivisionError", ":", "result", "=", "0", "return", "Operators", ".", "ITEBV", "(", "256", ",", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SDIV
Signed integer division operation (truncated)
manticore/platforms/evm.py
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 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
[ "Signed", "integer", "division", "operation", "(", "truncated", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1154-L1164
[ "def", "SDIV", "(", "self", ",", "a", ",", "b", ")", ":", "s0", ",", "s1", "=", "to_signed", "(", "a", ")", ",", "to_signed", "(", "b", ")", "try", ":", "result", "=", "(", "Operators", ".", "ABS", "(", "s0", ")", "//", "Operators", ".", "ABS...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.MOD
Modulo remainder operation
manticore/platforms/evm.py
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 MOD(self, a, b): """Modulo remainder operation""" try: result = Operators.ITEBV(256, b == 0, 0, a % b) except ZeroDivisionError: result = 0 return result
[ "Modulo", "remainder", "operation" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1166-L1172
[ "def", "MOD", "(", "self", ",", "a", ",", "b", ")", ":", "try", ":", "result", "=", "Operators", ".", "ITEBV", "(", "256", ",", "b", "==", "0", ",", "0", ",", "a", "%", "b", ")", "except", "ZeroDivisionError", ":", "result", "=", "0", "return",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SMOD
Signed modulo remainder operation
manticore/platforms/evm.py
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 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)
[ "Signed", "modulo", "remainder", "operation" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1174-L1183
[ "def", "SMOD", "(", "self", ",", "a", ",", "b", ")", ":", "s0", ",", "s1", "=", "to_signed", "(", "a", ")", ",", "to_signed", "(", "b", ")", "sign", "=", "Operators", ".", "ITEBV", "(", "256", ",", "s0", "<", "0", ",", "-", "1", ",", "1", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.ADDMOD
Modulo addition operation
manticore/platforms/evm.py
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 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
[ "Modulo", "addition", "operation" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1185-L1191
[ "def", "ADDMOD", "(", "self", ",", "a", ",", "b", ",", "c", ")", ":", "try", ":", "result", "=", "Operators", ".", "ITEBV", "(", "256", ",", "c", "==", "0", ",", "0", ",", "(", "a", "+", "b", ")", "%", "c", ")", "except", "ZeroDivisionError",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.EXP_gas
Calculate extra gas fee
manticore/platforms/evm.py
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 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)
[ "Calculate", "extra", "gas", "fee" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1201-L1210
[ "def", "EXP_gas", "(", "self", ",", "base", ",", "exponent", ")", ":", "EXP_SUPPLEMENTAL_GAS", "=", "10", "# cost of EXP exponent per byte", "def", "nbytes", "(", "e", ")", ":", "result", "=", "0", "for", "i", "in", "range", "(", "32", ")", ":", "result"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SIGNEXTEND
Extend length of two's complement signed integer
manticore/platforms/evm.py
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 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)
[ "Extend", "length", "of", "two", "s", "complement", "signed", "integer" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1220-L1227
[ "def", "SIGNEXTEND", "(", "self", ",", "size", ",", "value", ")", ":", "# FIXME maybe use Operators.SEXTEND", "testbit", "=", "Operators", ".", "ITEBV", "(", "256", ",", "size", "<=", "31", ",", "size", "*", "8", "+", "7", ",", "257", ")", "result1", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.LT
Less-than comparison
manticore/platforms/evm.py
def LT(self, a, b): """Less-than comparison""" return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0)
def LT(self, a, b): """Less-than comparison""" return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0)
[ "Less", "-", "than", "comparison" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1231-L1233
[ "def", "LT", "(", "self", ",", "a", ",", "b", ")", ":", "return", "Operators", ".", "ITEBV", "(", "256", ",", "Operators", ".", "ULT", "(", "a", ",", "b", ")", ",", "1", ",", "0", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.GT
Greater-than comparison
manticore/platforms/evm.py
def GT(self, a, b): """Greater-than comparison""" return Operators.ITEBV(256, Operators.UGT(a, b), 1, 0)
def GT(self, a, b): """Greater-than comparison""" return Operators.ITEBV(256, Operators.UGT(a, b), 1, 0)
[ "Greater", "-", "than", "comparison" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1235-L1237
[ "def", "GT", "(", "self", ",", "a", ",", "b", ")", ":", "return", "Operators", ".", "ITEBV", "(", "256", ",", "Operators", ".", "UGT", "(", "a", ",", "b", ")", ",", "1", ",", "0", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SGT
Signed greater-than comparison
manticore/platforms/evm.py
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 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)
[ "Signed", "greater", "-", "than", "comparison" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1245-L1249
[ "def", "SGT", "(", "self", ",", "a", ",", "b", ")", ":", "# http://gavwood.com/paper.pdf", "s0", ",", "s1", "=", "to_signed", "(", "a", ")", ",", "to_signed", "(", "b", ")", "return", "Operators", ".", "ITEBV", "(", "256", ",", "s0", ">", "s1", ","...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.BYTE
Retrieve single byte from word
manticore/platforms/evm.py
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 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)
[ "Retrieve", "single", "byte", "from", "word" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1275-L1278
[ "def", "BYTE", "(", "self", ",", "offset", ",", "value", ")", ":", "offset", "=", "Operators", ".", "ITEBV", "(", "256", ",", "offset", "<", "32", ",", "(", "31", "-", "offset", ")", "*", "8", ",", "256", ")", "return", "Operators", ".", "ZEXTEND...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SHA3
Compute Keccak-256 hash
manticore/platforms/evm.py
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 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
[ "Compute", "Keccak", "-", "256", "hash" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1302-L1326
[ "def", "SHA3", "(", "self", ",", "start", ",", "size", ")", ":", "# read memory from start to end", "# http://gavwood.com/paper.pdf", "data", "=", "self", ".", "try_simplify_to_constant", "(", "self", ".", "read_buffer", "(", "start", ",", "size", ")", ")", "if"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.CALLDATALOAD
Get input data of current environment
manticore/platforms/evm.py
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 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)
[ "Get", "input", "data", "of", "current", "environment" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1353-L1374
[ "def", "CALLDATALOAD", "(", "self", ",", "offset", ")", ":", "if", "issymbolic", "(", "offset", ")", ":", "if", "solver", ".", "can_be_true", "(", "self", ".", "_constraints", ",", "offset", "==", "self", ".", "_used_calldata_size", ")", ":", "self", "."...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.CALLDATACOPY
Copy input data in current environment to memory
manticore/platforms/evm.py
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 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)
[ "Copy", "input", "data", "in", "current", "environment", "to", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1392-L1414
[ "def", "CALLDATACOPY", "(", "self", ",", "mem_offset", ",", "data_offset", ",", "size", ")", ":", "if", "issymbolic", "(", "size", ")", ":", "if", "solver", ".", "can_be_true", "(", "self", ".", "_constraints", ",", "size", "<=", "len", "(", "self", "....
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.CODECOPY
Copy code running in current environment to memory
manticore/platforms/evm.py
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 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)
[ "Copy", "code", "running", "in", "current", "environment", "to", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1424-L1454
[ "def", "CODECOPY", "(", "self", ",", "mem_offset", ",", "code_offset", ",", "size", ")", ":", "self", ".", "_allocate", "(", "mem_offset", ",", "size", ")", "GCOPY", "=", "3", "# cost to copy one 32 byte word", "copyfee", "=", "self", ".", "safe_mul", "(", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.EXTCODECOPY
Copy an account's code to memory
manticore/platforms/evm.py
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 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)
[ "Copy", "an", "account", "s", "code", "to", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1472-L1481
[ "def", "EXTCODECOPY", "(", "self", ",", "account", ",", "address", ",", "offset", ",", "size", ")", ":", "extbytecode", "=", "self", ".", "world", ".", "get_code", "(", "account", ")", "self", ".", "_allocate", "(", "address", "+", "size", ")", "for", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.MLOAD
Load word from memory
manticore/platforms/evm.py
def MLOAD(self, address): """Load word from memory""" self._allocate(address, 32) value = self._load(address, 32) return value
def MLOAD(self, address): """Load word from memory""" self._allocate(address, 32) value = self._load(address, 32) return value
[ "Load", "word", "from", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1536-L1540
[ "def", "MLOAD", "(", "self", ",", "address", ")", ":", "self", ".", "_allocate", "(", "address", ",", "32", ")", "value", "=", "self", ".", "_load", "(", "address", ",", "32", ")", "return", "value" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.MSTORE
Save word to memory
manticore/platforms/evm.py
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 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)
[ "Save", "word", "to", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1545-L1551
[ "def", "MSTORE", "(", "self", ",", "address", ",", "value", ")", ":", "if", "istainted", "(", "self", ".", "pc", ")", ":", "for", "taint", "in", "get_taints", "(", "self", ".", "pc", ")", ":", "value", "=", "taint_with", "(", "value", ",", "taint",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.MSTORE8
Save byte to memory
manticore/platforms/evm.py
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 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)
[ "Save", "byte", "to", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1556-L1562
[ "def", "MSTORE8", "(", "self", ",", "address", ",", "value", ")", ":", "if", "istainted", "(", "self", ".", "pc", ")", ":", "for", "taint", "in", "get_taints", "(", "self", ".", "pc", ")", ":", "value", "=", "taint_with", "(", "value", ",", "taint"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SLOAD
Load word from storage
manticore/platforms/evm.py
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 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
[ "Load", "word", "from", "storage" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1564-L1570
[ "def", "SLOAD", "(", "self", ",", "offset", ")", ":", "storage_address", "=", "self", ".", "address", "self", ".", "_publish", "(", "'will_evm_read_storage'", ",", "storage_address", ",", "offset", ")", "value", "=", "self", ".", "world", ".", "get_storage_d...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SSTORE
Save word to storage
manticore/platforms/evm.py
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 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)
[ "Save", "word", "to", "storage" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1588-L1601
[ "def", "SSTORE", "(", "self", ",", "offset", ",", "value", ")", ":", "storage_address", "=", "self", ".", "address", "self", ".", "_publish", "(", "'will_evm_write_storage'", ",", "storage_address", ",", "offset", ",", "value", ")", "#refund = Operators.ITEBV(25...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.JUMPI
Conditionally alter the program counter
manticore/platforms/evm.py
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 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)
[ "Conditionally", "alter", "the", "program", "counter" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1609-L1613
[ "def", "JUMPI", "(", "self", ",", "dest", ",", "cond", ")", ":", "self", ".", "pc", "=", "Operators", ".", "ITEBV", "(", "256", ",", "cond", "!=", "0", ",", "dest", ",", "self", ".", "pc", "+", "self", ".", "instruction", ".", "size", ")", "#Th...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SWAP
Exchange 1st and 2nd stack items
manticore/platforms/evm.py
def SWAP(self, *operands): """Exchange 1st and 2nd stack items""" a = operands[0] b = operands[-1] return (b,) + operands[1:-1] + (a,)
def SWAP(self, *operands): """Exchange 1st and 2nd stack items""" a = operands[0] b = operands[-1] return (b,) + operands[1:-1] + (a,)
[ "Exchange", "1st", "and", "2nd", "stack", "items" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1645-L1649
[ "def", "SWAP", "(", "self", ",", "*", "operands", ")", ":", "a", "=", "operands", "[", "0", "]", "b", "=", "operands", "[", "-", "1", "]", "return", "(", "b", ",", ")", "+", "operands", "[", "1", ":", "-", "1", "]", "+", "(", "a", ",", ")...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.CREATE
Create a new account with associated code
manticore/platforms/evm.py
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""" 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()
[ "Create", "a", "new", "account", "with", "associated", "code" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1669-L1679
[ "def", "CREATE", "(", "self", ",", "value", ",", "offset", ",", "size", ")", ":", "address", "=", "self", ".", "world", ".", "create_account", "(", "address", "=", "EVMWorld", ".", "calculate_new_address", "(", "sender", "=", "self", ".", "address", ",",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.CREATE
Create a new account with associated code
manticore/platforms/evm.py
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 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
[ "Create", "a", "new", "account", "with", "associated", "code" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1682-L1691
[ "def", "CREATE", "(", "self", ",", "value", ",", "offset", ",", "size", ")", ":", "tx", "=", "self", ".", "world", ".", "last_transaction", "# At this point last and current tx are the same.", "address", "=", "tx", ".", "address", "if", "tx", ".", "result", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.CALLCODE
Message-call into this account with alternative account's code
manticore/platforms/evm.py
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 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()
[ "Message", "-", "call", "into", "this", "account", "with", "alternative", "account", "s", "code" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1723-L1731
[ "def", "CALLCODE", "(", "self", ",", "gas", ",", "_ignored_", ",", "value", ",", "in_offset", ",", "in_size", ",", "out_offset", ",", "out_size", ")", ":", "self", ".", "world", ".", "start_transaction", "(", "'CALLCODE'", ",", "address", "=", "self", "....
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.RETURN
Halt execution returning output data
manticore/platforms/evm.py
def RETURN(self, offset, size): """Halt execution returning output data""" data = self.read_buffer(offset, size) raise EndTx('RETURN', data)
def RETURN(self, offset, size): """Halt execution returning output data""" data = self.read_buffer(offset, size) raise EndTx('RETURN', data)
[ "Halt", "execution", "returning", "output", "data" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1747-L1750
[ "def", "RETURN", "(", "self", ",", "offset", ",", "size", ")", ":", "data", "=", "self", ".", "read_buffer", "(", "offset", ",", "size", ")", "raise", "EndTx", "(", "'RETURN'", ",", "data", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVM.SELFDESTRUCT
Halt execution and register account for later deletion
manticore/platforms/evm.py
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 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')
[ "Halt", "execution", "and", "register", "account", "for", "later", "deletion" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L1814-L1830
[ "def", "SELFDESTRUCT", "(", "self", ",", "recipient", ")", ":", "#This may create a user account", "recipient", "=", "Operators", ".", "EXTRACT", "(", "recipient", ",", "0", ",", "160", ")", "address", "=", "self", ".", "address", "#FIXME for on the known addresse...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.human_transactions
Completed human transaction
manticore/platforms/evm.py
def human_transactions(self): """Completed human transaction""" txs = [] for tx in self.transactions: if tx.depth == 0: txs.append(tx) return tuple(txs)
def human_transactions(self): """Completed human transaction""" txs = [] for tx in self.transactions: if tx.depth == 0: txs.append(tx) return tuple(txs)
[ "Completed", "human", "transaction" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2058-L2064
[ "def", "human_transactions", "(", "self", ")", ":", "txs", "=", "[", "]", "for", "tx", "in", "self", ".", "transactions", ":", "if", "tx", ".", "depth", "==", "0", ":", "txs", ".", "append", "(", "tx", ")", "return", "tuple", "(", "txs", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.current_vm
current vm
manticore/platforms/evm.py
def current_vm(self): """current vm""" try: _, _, _, _, vm = self._callstack[-1] return vm except IndexError: return None
def current_vm(self): """current vm""" try: _, _, _, _, vm = self._callstack[-1] return vm except IndexError: return None
[ "current", "vm" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2088-L2094
[ "def", "current_vm", "(", "self", ")", ":", "try", ":", "_", ",", "_", ",", "_", ",", "_", ",", "vm", "=", "self", ".", "_callstack", "[", "-", "1", "]", "return", "vm", "except", "IndexError", ":", "return", "None" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.current_transaction
current tx
manticore/platforms/evm.py
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_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
[ "current", "tx" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2097-L2106
[ "def", "current_transaction", "(", "self", ")", ":", "try", ":", "tx", ",", "_", ",", "_", ",", "_", ",", "_", "=", "self", ".", "_callstack", "[", "-", "1", "]", "if", "tx", ".", "result", "is", "not", "None", ":", "#That tx finished. No current tx....
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.current_human_transaction
Current ongoing human transaction
manticore/platforms/evm.py
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 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
[ "Current", "ongoing", "human", "transaction" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2109-L2119
[ "def", "current_human_transaction", "(", "self", ")", ":", "try", ":", "tx", ",", "_", ",", "_", ",", "_", ",", "_", "=", "self", ".", "_callstack", "[", "0", "]", "if", "tx", ".", "result", "is", "not", "None", ":", "#That tx finished. No current tx."...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.get_storage_data
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
manticore/platforms/evm.py
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 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)
[ "Read", "a", "value", "from", "a", "storage", "slot", "on", "the", "specified", "account" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2149-L2160
[ "def", "get_storage_data", "(", "self", ",", "storage_address", ",", "offset", ")", ":", "value", "=", "self", ".", "_world_state", "[", "storage_address", "]", "[", "'storage'", "]", ".", "get", "(", "offset", ",", "0", ")", "return", "simplify", "(", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.set_storage_data
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
manticore/platforms/evm.py
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 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
[ "Writes", "a", "value", "to", "a", "storage", "slot", "in", "specified", "account" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2162-L2172
[ "def", "set_storage_data", "(", "self", ",", "storage_address", ",", "offset", ",", "value", ")", ":", "self", ".", "_world_state", "[", "storage_address", "]", "[", "'storage'", "]", "[", "offset", "]", "=", "value" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.get_storage_items
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)]
manticore/platforms/evm.py
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 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
[ "Gets", "all", "items", "in", "an", "account", "storage" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2174-L2188
[ "def", "get_storage_items", "(", "self", ",", "address", ")", ":", "storage", "=", "self", ".", "_world_state", "[", "address", "]", "[", "'storage'", "]", "items", "=", "[", "]", "array", "=", "storage", ".", "array", "while", "not", "isinstance", "(", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.has_storage
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.
manticore/platforms/evm.py
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 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
[ "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", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2190-L2202
[ "def", "has_storage", "(", "self", ",", "address", ")", ":", "storage", "=", "self", ".", "_world_state", "[", "address", "]", "[", "'storage'", "]", "array", "=", "storage", ".", "array", "while", "not", "isinstance", "(", "array", ",", "ArrayVariable", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.block_hash
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
manticore/platforms/evm.py
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 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
[ "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", "...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2302-L2324
[ "def", "block_hash", "(", "self", ",", "block_number", "=", "None", ",", "force_recent", "=", "True", ")", ":", "if", "block_number", "is", "None", ":", "block_number", "=", "self", ".", "block_number", "(", ")", "-", "1", "# We are not maintaining an actual -...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.new_address
Create a fresh 160bit address
manticore/platforms/evm.py
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 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
[ "Create", "a", "fresh", "160bit", "address" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2338-L2346
[ "def", "new_address", "(", "self", ",", "sender", "=", "None", ",", "nonce", "=", "None", ")", ":", "if", "sender", "is", "not", "None", "and", "nonce", "is", "None", ":", "nonce", "=", "self", ".", "get_nonce", "(", "sender", ")", "new_address", "="...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.create_account
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
manticore/platforms/evm.py
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_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
[ "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", "clos...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2376-L2432
[ "def", "create_account", "(", "self", ",", "address", "=", "None", ",", "balance", "=", "0", ",", "code", "=", "None", ",", "storage", "=", "None", ",", "nonce", "=", "None", ")", ":", "if", "code", "is", "None", ":", "code", "=", "bytes", "(", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.create_contract
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.
manticore/platforms/evm.py
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 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
[ "Create", "a", "contract", "account", ".", "Sends", "a", "transaction", "to", "initialize", "the", "contract" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2434-L2457
[ "def", "create_contract", "(", "self", ",", "price", "=", "0", ",", "address", "=", "None", ",", "caller", "=", "None", ",", "balance", "=", "0", ",", "init", "=", "None", ",", "gas", "=", "None", ")", ":", "expected_address", "=", "self", ".", "cr...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
EVMWorld.start_transaction
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.
manticore/platforms/evm.py
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 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)
[ "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"...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/evm.py#L2463-L2476
[ "def", "start_transaction", "(", "self", ",", "sort", ",", "address", ",", "price", "=", "None", ",", "data", "=", "None", ",", "caller", "=", "None", ",", "value", "=", "0", ",", "gas", "=", "2300", ")", ":", "assert", "self", ".", "_pending_transac...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Operand._get_expand_imm_carry
Manually compute the carry bit produced by expanding an immediate operand (see ARMExpandImm_C)
manticore/native/cpu/arm.py
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 _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
[ "Manually", "compute", "the", "carry", "bit", "produced", "by", "expanding", "an", "immediate", "operand", "(", "see", "ARMExpandImm_C", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L197-L203
[ "def", "_get_expand_imm_carry", "(", "self", ",", "carryIn", ")", ":", "insn", "=", "struct", ".", "unpack", "(", "'<I'", ",", "self", ".", "cpu", ".", "instruction", ".", "bytes", ")", "[", "0", "]", "unrotated", "=", "insn", "&", "Mask", "(", "8", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7RegisterFile._write_APSR
Auxiliary function - Writes flags from a full APSR (only 4 msb used)
manticore/native/cpu/arm.py
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 _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)
[ "Auxiliary", "function", "-", "Writes", "flags", "from", "a", "full", "APSR", "(", "only", "4", "msb", "used", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L270-L280
[ "def", "_write_APSR", "(", "self", ",", "apsr", ")", ":", "V", "=", "Operators", ".", "EXTRACT", "(", "apsr", ",", "28", ",", "1", ")", "C", "=", "Operators", ".", "EXTRACT", "(", "apsr", ",", "29", ",", "1", ")", "Z", "=", "Operators", ".", "E...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu._swap_mode
Toggle between ARM and Thumb mode
manticore/native/cpu/arm.py
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 _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
[ "Toggle", "between", "ARM", "and", "Thumb", "mode" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L411-L417
[ "def", "_swap_mode", "(", "self", ")", ":", "assert", "self", ".", "mode", "in", "(", "cs", ".", "CS_MODE_ARM", ",", "cs", ".", "CS_MODE_THUMB", ")", "if", "self", ".", "mode", "==", "cs", ".", "CS_MODE_ARM", ":", "self", ".", "mode", "=", "cs", "....
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.set_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
manticore/native/cpu/arm.py
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 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)
[ "Note", ":", "For", "any", "unmodified", "flags", "update", "_last_flags", "with", "the", "most", "recent", "committed", "value", ".", "Otherwise", "for", "example", "this", "could", "happen", ":" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L423-L438
[ "def", "set_flags", "(", "self", ",", "*", "*", "flags", ")", ":", "unupdated_flags", "=", "self", ".", "_last_flags", ".", "keys", "(", ")", "-", "flags", ".", "keys", "(", ")", "for", "flag", "in", "unupdated_flags", ":", "flag_name", "=", "f'APSR_{f...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu._shift
See Shift() and Shift_C() in the ARM manual
manticore/native/cpu/arm.py
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 _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")
[ "See", "Shift", "()", "and", "Shift_C", "()", "in", "the", "ARM", "manual" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L448-L481
[ "def", "_shift", "(", "cpu", ",", "value", ",", "_type", ",", "amount", ",", "carry", ")", ":", "assert", "(", "cs", ".", "arm", ".", "ARM_SFT_INVALID", "<", "_type", "<=", "cs", ".", "arm", ".", "ARM_SFT_RRX_REG", ")", "# XXX: Capstone should set the valu...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.MOV
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.
manticore/native/cpu/arm.py
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 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))
[ "Implement", "the", "MOV", "{", "S", "}", "instruction", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L640-L658
[ "def", "MOV", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "cpu", ".", "mode", "==", "cs", ".", "CS_MODE_ARM", ":", "result", ",", "carry_out", "=", "src", ".", "read", "(", "with_carry", "=", "True", ")", "dest", ".", "write", "(", "resu...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.MOVT
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
manticore/native/cpu/arm.py
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 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)
[ "MOVT", "writes", "imm16", "to", "Rd", "[", "31", ":", "16", "]", ".", "The", "write", "does", "not", "affect", "Rd", "[", "15", ":", "0", "]", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L661-L671
[ "def", "MOVT", "(", "cpu", ",", "dest", ",", "src", ")", ":", "assert", "src", ".", "type", "==", "'immediate'", "imm", "=", "src", ".", "read", "(", ")", "low_halfword", "=", "dest", ".", "read", "(", ")", "&", "Mask", "(", "16", ")", "dest", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.MRC
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
manticore/native/cpu/arm.py
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 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")
[ "MRC", "moves", "to", "ARM", "register", "from", "coprocessor", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L674-L701
[ "def", "MRC", "(", "cpu", ",", "coprocessor", ",", "opcode1", ",", "dest", ",", "coprocessor_reg_n", ",", "coprocessor_reg_m", ",", "opcode2", ")", ":", "assert", "coprocessor", ".", "type", "==", "'coprocessor'", "assert", "opcode1", ".", "type", "==", "'im...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.LDRD
Loads double width data from memory.
manticore/native/cpu/arm.py
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 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)
[ "Loads", "double", "width", "data", "from", "memory", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L704-L714
[ "def", "LDRD", "(", "cpu", ",", "dest1", ",", "dest2", ",", "src", ",", "offset", "=", "None", ")", ":", "assert", "dest1", ".", "type", "==", "'register'", "assert", "dest2", ".", "type", "==", "'register'", "assert", "src", ".", "type", "==", "'mem...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.STRD
Writes the contents of two registers to memory.
manticore/native/cpu/arm.py
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 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)
[ "Writes", "the", "contents", "of", "two", "registers", "to", "memory", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L717-L727
[ "def", "STRD", "(", "cpu", ",", "src1", ",", "src2", ",", "dest", ",", "offset", "=", "None", ")", ":", "assert", "src1", ".", "type", "==", "'register'", "assert", "src2", ".", "type", "==", "'register'", "assert", "dest", ".", "type", "==", "'memor...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.LDREX
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
manticore/native/cpu/arm.py
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 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)
[ "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", "cl...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L730-L744
[ "def", "LDREX", "(", "cpu", ",", "dest", ",", "src", ",", "offset", "=", "None", ")", ":", "# TODO: add lock mechanism to underlying memory --GR, 2017-06-06", "cpu", ".", "_LDR", "(", "dest", ",", "src", ",", "32", ",", "False", ",", "offset", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.STREX
STREX performs a conditional store to memory. :param Armv7Operand status: the destination register for the returned status; register
manticore/native/cpu/arm.py
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 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)
[ "STREX", "performs", "a", "conditional", "store", "to", "memory", ".", ":", "param", "Armv7Operand", "status", ":", "the", "destination", "register", "for", "the", "returned", "status", ";", "register" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L747-L754
[ "def", "STREX", "(", "cpu", ",", "status", ",", "*", "args", ")", ":", "# TODO: implement conditional return with appropriate status --GR, 2017-06-06", "status", ".", "write", "(", "0", ")", "return", "cpu", ".", "_STR", "(", "cpu", ".", "address_bit_size", ",", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu._UXT
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
manticore/native/cpu/arm.py
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 _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)
[ "Helper", "for", "UXT", "*", "family", "of", "instructions", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L756-L766
[ "def", "_UXT", "(", "cpu", ",", "dest", ",", "src", ",", "src_width", ")", ":", "val", "=", "GetNBits", "(", "src", ".", "read", "(", ")", ",", "src_width", ")", "word", "=", "Operators", ".", "ZEXTEND", "(", "val", ",", "cpu", ".", "address_bit_si...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.ADR
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.
manticore/native/cpu/arm.py
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 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())
[ "Address", "to", "Register", "adds", "an", "immediate", "value", "to", "the", "PC", "value", "and", "writes", "the", "result", "to", "the", "destination", "register", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L943-L954
[ "def", "ADR", "(", "cpu", ",", "dest", ",", "src", ")", ":", "aligned_pc", "=", "(", "cpu", ".", "instruction", ".", "address", "+", "4", ")", "&", "0xfffffffc", "dest", ".", "write", "(", "aligned_pc", "+", "src", ".", "read", "(", ")", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Armv7Cpu.ADDW
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.
manticore/native/cpu/arm.py
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())
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())
[ "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", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/arm.py#L957-L975
[ "def", "ADDW", "(", "cpu", ",", "dest", ",", "src", ",", "add", ")", ":", "aligned_pc", "=", "(", "cpu", ".", "instruction", ".", "address", "+", "4", ")", "&", "0xfffffffc", "if", "src", ".", "type", "==", "'register'", "and", "src", ".", "reg", ...
54c5a15b1119c523ae54c09972413e8b97f11629