Search is not available for this dataset
text
stringlengths
75
104k
def save_state(self, state, state_id=None): """ Save a state to storage, return identifier. :param state: The state to save :param int state_id: If not None force the state id potentially overwriting old states :return: New state id :rtype: int """ assert...
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: ...
def t_UINTN(t): r"uint(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)" size = int(t.lexer.lexmatch.group('size')) t.value = ('uint', size) return t
def t_INTN(t): r"int(?P<size>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)" size = int(t.lexer.lexmatch.group('size')) t.value = ('int', size) return t
def t_UFIXEDMN(t): r"ufixed(?P<M>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)x(?P<N>80|79|78|77|76|75|74|73|72|71|70|69|68|67|66|65|64|63|62|61|60|59|58|57|56|55|54|53|52|51|50|49|48|47|46|45|44|43|42|41|40|39|38|37|36|35|34|33|32|31|30|29|28|27...
def t_BYTESM(t): r"bytes(?P<nbytes>32|31|30|29|28|27|26|25|24|23|22|21|20|19|18|17|16|15|14|13|12|11|10|9|8|7|6|5|4|3|2|1)" size = int(t.lexer.lexmatch.group('nbytes')) t.value = ('bytesM', size) return t
def p_dynamic_fixed_type(p): """ T : T LBRAKET NUMBER RBRAKET """ reps = int(p[3]) base_type = p[1] p[0] = ('array', reps, base_type)
def cmp_regs(cpu, should_print=False): """ Compare registers from a remote gdb session to current mcore. :param manticore.core.cpu Cpu: Current cpu :param bool should_print: Whether to print values to stdout :return: Whether or not any differences were detected :rtype: bool """ differin...
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 ...
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: {n...
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(addres...
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 t...
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 ...
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__: ...
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): ...
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): expr...
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 begini...
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 = exp...
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(le...
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], ri...
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): ...
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 &...
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):...
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 = ind...
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 t...
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_...
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 re...
def function_selector(method_name_and_signature): """ Makes a function hash id from a method signature """ s = sha3.keccak_256() s.update(method_name_and_signature.encode()) return bytes(s.digest()[:4])
def _serialize_uint(value, size=32, padding=0): """ Translates a python integral or a BitVec into a 32 byte string, MSB first """ if size <= 0 or size > 32: raise ValueError from .account import EVMAccount # because of circular import if not isinstance(value...
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 issymbo...
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 sign...
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 ...
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 tha...
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=s...
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...
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: ...
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...
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 InvalidOpcod...
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() ...
def _top(self, n=0): """Read a value from the top of the stack without removing it""" if len(self.stack) - n < 0: raise StackUnderflow() return self.stack[n - 1]
def _checkpoint(self): """Save and/or get a state checkpoint previous to current instruction""" #Fixme[felipe] add a with self.disabled_events context mangr to Eventful if self._checkpoint_data is None: if not self._published_pre_instruction_events: self._published_pr...
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....
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...
def _store(self, offset, value, size=1): """Stores value in memory as a big endian""" self.memory.write_BE(offset, value, size) for i in range(size): self._publish('did_evm_write_memory', offset + i, Operators.EXTRACT(value, (size - i - 1) * 8, 8))
def DIV(self, a, b): """Integer division operation""" try: result = Operators.UDIV(a, b) except ZeroDivisionError: result = 0 return Operators.ITEBV(256, b == 0, 0, result)
def SDIV(self, a, b): """Signed integer division operation (truncated)""" s0, s1 = to_signed(a), to_signed(b) try: result = (Operators.ABS(s0) // Operators.ABS(s1) * Operators.ITEBV(256, (s0 < 0) != (s1 < 0), -1, 1)) except ZeroDivisionError: result = 0 re...
def MOD(self, a, b): """Modulo remainder operation""" try: result = Operators.ITEBV(256, b == 0, 0, a % b) except ZeroDivisionError: result = 0 return result
def SMOD(self, a, b): """Signed modulo remainder operation""" s0, s1 = to_signed(a), to_signed(b) sign = Operators.ITEBV(256, s0 < 0, -1, 1) try: result = (Operators.ABS(s0) % Operators.ABS(s1)) * sign except ZeroDivisionError: result = 0 return O...
def ADDMOD(self, a, b, c): """Modulo addition operation""" try: result = Operators.ITEBV(256, c == 0, 0, (a + b) % c) except ZeroDivisionError: result = 0 return result
def EXP_gas(self, base, exponent): """Calculate extra gas fee""" EXP_SUPPLEMENTAL_GAS = 10 # cost of EXP exponent per byte def nbytes(e): result = 0 for i in range(32): result = Operators.ITEBV(512, Operators.EXTRACT(e, i * 8, 8) != 0, i + 1, result) ...
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)) ...
def LT(self, a, b): """Less-than comparison""" return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0)
def GT(self, a, b): """Greater-than comparison""" return Operators.ITEBV(256, Operators.UGT(a, b), 1, 0)
def SGT(self, a, b): """Signed greater-than comparison""" # http://gavwood.com/paper.pdf s0, s1 = to_signed(a), to_signed(b) return Operators.ITEBV(256, s0 > s1, 1, 0)
def BYTE(self, offset, value): """Retrieve single byte from word""" offset = Operators.ITEBV(256, offset < 32, (31 - offset) * 8, 256) return Operators.ZEXTEND(Operators.EXTRACT(value, offset, 8), 256)
def SHA3(self, start, size): """Compute Keccak-256 hash""" # read memory from start to end # http://gavwood.com/paper.pdf data = self.try_simplify_to_constant(self.read_buffer(start, size)) if issymbolic(data): known_sha3 = {} # Broadcast the signal ...
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, p...
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 Concr...
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._co...
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, extbytecod...
def MLOAD(self, address): """Load word from memory""" self._allocate(address, 32) value = self._load(address, 32) return value
def MSTORE(self, address, value): """Save word to memory""" if istainted(self.pc): for taint in get_taints(self.pc): value = taint_with(value, taint) self._allocate(address, 32) self._store(address, value, 32)
def MSTORE8(self, address, value): """Save byte to memory""" if istainted(self.pc): for taint in get_taints(self.pc): value = taint_with(value, taint) self._allocate(address, 1) self._store(address, Operators.EXTRACT(value, 0, 8), 1)
def SLOAD(self, offset): """Load word from storage""" storage_address = self.address self._publish('will_evm_read_storage', storage_address, offset) value = self.world.get_storage_data(storage_address, offset) self._publish('did_evm_read_storage', storage_address, offset, value) ...
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, # Opera...
def JUMPI(self, dest, cond): """Conditionally alter the program counter""" self.pc = Operators.ITEBV(256, cond != 0, dest, self.pc + self.instruction.size) #This set ups a check for JMPDEST in the next instruction if cond != 0 self._set_check_jmpdest(cond != 0)
def SWAP(self, *operands): """Exchange 1st and 2nd stack items""" a = operands[0] b = operands[-1] return (b,) + operands[1:-1] + (a,)
def CREATE(self, value, offset, size): """Create a new account with associated code""" address = self.world.create_account(address=EVMWorld.calculate_new_address(sender=self.address, nonce=self.world.get_nonce(self.address))) self.world.start_transaction('CREATE', ...
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) el...
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.rea...
def RETURN(self, offset, size): """Halt execution returning output data""" data = self.read_buffer(offset, size) raise EndTx('RETURN', data)
def SELFDESTRUCT(self, recipient): """Halt execution and register account for later deletion""" #This may create a user account recipient = Operators.EXTRACT(recipient, 0, 160) address = self.address #FIXME for on the known addresses if issymbolic(recipient): ...
def human_transactions(self): """Completed human transaction""" txs = [] for tx in self.transactions: if tx.depth == 0: txs.append(tx) return tuple(txs)
def current_vm(self): """current vm""" try: _, _, _, _, vm = self._callstack[-1] return vm except IndexError: return None
def current_transaction(self): """current tx""" try: tx, _, _, _, _ = self._callstack[-1] if tx.result is not None: #That tx finished. No current tx. return None return tx except IndexError: return None
def current_human_transaction(self): """Current ongoing human transaction""" try: tx, _, _, _, _ = self._callstack[0] if tx.result is not None: #That tx finished. No current tx. return None assert tx.depth == 0 return tx ...
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 Bit...
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 :...
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...
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 ...
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 ...
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 s...
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. :p...
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 Ye...
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. :pa...
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 = sel...
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) ...
def _swap_mode(self): """Toggle between ARM and Thumb mode""" assert self.mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB) if self.mode == cs.CS_MODE_ARM: self.mode = cs.CS_MODE_THUMB else: self.mode = cs.CS_MODE_ARM
def set_flags(self, **flags): """ Note: For any unmodified flags, update _last_flags with the most recent committed value. Otherwise, for example, this could happen: overflow=0 instr1 computes overflow=1, updates _last_flags, doesn't commit instr2 updates all...
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 ...
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 Armv7Operan...
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 = sr...
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 ...
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) ...
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(...
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 fo...
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) ...
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...
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 litera...
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 ...