Search is not available for this dataset
text
stringlengths
75
104k
def new_symbolic_buffer(self, nbytes, **options): """Create and return a symbolic buffer of length `nbytes`. The buffer is not written into State's memory; write it to the state's memory to introduce it into the program state. :param int nbytes: Length of the new buffer :param str label: (keyword arg only) The label to assign to the buffer :param bool cstring: (keyword arg only) Whether or not to enforce that the buffer is a cstring (i.e. no NULL bytes, except for the last byte). (bool) :param taint: Taint identifier of the new buffer :type taint: tuple or frozenset :return: :class:`~manticore.core.smtlib.expression.Expression` representing the buffer. """ label = options.get('label') avoid_collisions = False if label is None: label = 'buffer' avoid_collisions = True taint = options.get('taint', frozenset()) expr = self._constraints.new_array(name=label, index_max=nbytes, value_bits=8, taint=taint, avoid_collisions=avoid_collisions) self._input_symbols.append(expr) if options.get('cstring', False): for i in range(nbytes - 1): self._constraints.add(expr[i] != 0) return expr
def new_symbolic_value(self, nbits, label=None, taint=frozenset()): """Create and return a symbolic value that is `nbits` bits wide. Assign the value to a register or write it into the address space to introduce it into the program state. :param int nbits: The bitwidth of the value returned :param str label: The label to assign to the value :param taint: Taint identifier of this value :type taint: tuple or frozenset :return: :class:`~manticore.core.smtlib.expression.Expression` representing the value """ assert nbits in (1, 4, 8, 16, 32, 64, 128, 256) avoid_collisions = False if label is None: label = 'val' avoid_collisions = True expr = self._constraints.new_bitvec(nbits, name=label, taint=taint, avoid_collisions=avoid_collisions) self._input_symbols.append(expr) return expr
def concretize(self, symbolic, policy, maxcount=7): """ This finds a set of solutions for symbolic using policy. This raises TooManySolutions if more solutions than maxcount """ assert self.constraints == self.platform.constraints symbolic = self.migrate_expression(symbolic) vals = [] if policy == 'MINMAX': vals = self._solver.minmax(self._constraints, symbolic) elif policy == 'MAX': vals = self._solver.max(self._constraints, symbolic) elif policy == 'MIN': vals = self._solver.min(self._constraints, symbolic) elif policy == 'SAMPLED': m, M = self._solver.minmax(self._constraints, symbolic) vals += [m, M] if M - m > 3: if self._solver.can_be_true(self._constraints, symbolic == (m + M) // 2): vals.append((m + M) // 2) if M - m > 100: for i in (0, 1, 2, 5, 32, 64, 128, 320): if self._solver.can_be_true(self._constraints, symbolic == m + i): vals.append(m + i) if maxcount <= len(vals): break if M - m > 1000 and maxcount > len(vals): vals += self._solver.get_all_values(self._constraints, symbolic, maxcnt=maxcount - len(vals), silent=True) elif policy == 'ONE': vals = [self._solver.get_value(self._constraints, symbolic)] else: assert policy == 'ALL' vals = solver.get_all_values(self._constraints, symbolic, maxcnt=maxcount, silent=True) return tuple(set(vals))
def solve_one(self, expr, constrain=False): """ Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into one solution. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :param bool constrain: If True, constrain expr to concretized value :return: Concrete value :rtype: int """ expr = self.migrate_expression(expr) value = self._solver.get_value(self._constraints, expr) if constrain: self.constrain(expr == value) #Include forgiveness here if isinstance(value, bytearray): value = bytes(value) return value
def solve_n(self, expr, nsolves): """ Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into `nsolves` solutions. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :return: Concrete value :rtype: list[int] """ expr = self.migrate_expression(expr) return self._solver.get_all_values(self._constraints, expr, nsolves, silent=True)
def solve_max(self, expr): """ Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into its maximum solution :param manticore.core.smtlib.Expression expr: Symbolic value to solve :return: Concrete value :rtype: list[int] """ if isinstance(expr, int): return expr expr = self.migrate_expression(expr) return self._solver.max(self._constraints, expr)
def solve_min(self, expr): """ Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into its minimum solution :param manticore.core.smtlib.Expression expr: Symbolic value to solve :return: Concrete value :rtype: list[int] """ if isinstance(expr, int): return expr expr = self.migrate_expression(expr) return self._solver.min(self._constraints, expr)
def solve_minmax(self, expr): """ Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into its minimum and maximun solution. Only defined for bitvects. :param manticore.core.smtlib.Expression expr: Symbolic value to solve :return: Concrete value :rtype: list[int] """ if isinstance(expr, int): return expr expr = self.migrate_expression(expr) return self._solver.minmax(self._constraints, expr)
def solve_buffer(self, addr, nbytes, constrain=False): """ Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to concretize it :param int address: Address of buffer to concretize :param int nbytes: Size of buffer to concretize :param bool constrain: If True, constrain the buffer to the concretized value :return: Concrete contents of buffer :rtype: list[int] """ buffer = self.cpu.read_bytes(addr, nbytes) result = [] with self._constraints as temp_cs: cs_to_use = self.constraints if constrain else temp_cs for c in buffer: result.append(self._solver.get_value(cs_to_use, c)) cs_to_use.add(c == result[-1]) return result
def symbolicate_buffer(self, data, label='INPUT', wildcard='+', string=False, taint=frozenset()): """Mark parts of a buffer as symbolic (demarked by the wildcard byte) :param str data: The string to symbolicate. If no wildcard bytes are provided, this is the identity function on the first argument. :param str label: The label to assign to the value :param str wildcard: The byte that is considered a wildcard :param bool string: Ensure bytes returned can not be NULL :param taint: Taint identifier of the symbolicated data :type taint: tuple or frozenset :return: If data does not contain any wildcard bytes, data itself. Otherwise, a list of values derived from data. Non-wildcard bytes are kept as is, wildcard bytes are replaced by Expression objects. """ if wildcard in data: size = len(data) symb = self._constraints.new_array(name=label, index_max=size, taint=taint, avoid_collisions=True) self._input_symbols.append(symb) tmp = [] for i in range(size): if data[i] == wildcard: tmp.append(symb[i]) else: tmp.append(data[i]) data = tmp if string: for b in data: if issymbolic(b): self._constraints.add(b != 0) else: assert b != 0 return data
def _create_emulated_mapping(self, uc, address): """ Create a mapping in Unicorn and note that we'll need it if we retry. :param uc: The Unicorn instance. :param address: The address which is contained by the mapping. :rtype Map """ m = self._cpu.memory.map_containing(address) permissions = UC_PROT_NONE if 'r' in m.perms: permissions |= UC_PROT_READ if 'w' in m.perms: permissions |= UC_PROT_WRITE if 'x' in m.perms: permissions |= UC_PROT_EXEC uc.mem_map(m.start, len(m), permissions) self._should_be_mapped[m.start] = (len(m), permissions) return m
def _hook_xfer_mem(self, uc, access, address, size, value, data): """ Handle memory operations from unicorn. """ assert access in (UC_MEM_WRITE, UC_MEM_READ, UC_MEM_FETCH) if access == UC_MEM_WRITE: self._cpu.write_int(address, value, size * 8) # If client code is attempting to read a value, we need to bring it # in from Manticore state. If we try to mem_write it here, Unicorn # will segfault. We add the value to a list of things that need to # be written, and ask to restart the emulation. elif access == UC_MEM_READ: value = self._cpu.read_bytes(address, size) if address in self._should_be_written: return True self._should_be_written[address] = value self._should_try_again = True return False return True
def _hook_unmapped(self, uc, access, address, size, value, data): """ We hit an unmapped region; map it into unicorn. """ try: m = self._create_emulated_mapping(uc, address) except MemoryException as e: self._to_raise = e self._should_try_again = False return False self._should_try_again = True return False
def _interrupt(self, uc, number, data): """ Handle software interrupt (SVC/INT) """ from ..native.cpu.abstractcpu import Interruption # prevent circular imports self._to_raise = Interruption(number) return True
def emulate(self, instruction): """ Emulate a single instruction. """ # The emulation might restart if Unicorn needs to bring in a memory map # or bring a value from Manticore state. while True: self.reset() # Establish Manticore state, potentially from past emulation # attempts for base in self._should_be_mapped: size, perms = self._should_be_mapped[base] self._emu.mem_map(base, size, perms) for address, values in self._should_be_written.items(): for offset, byte in enumerate(values, start=address): if issymbolic(byte): from ..native.cpu.abstractcpu import ConcretizeMemory raise ConcretizeMemory(self._cpu.memory, offset, 8, "Concretizing for emulation") self._emu.mem_write(address, b''.join(values)) # Try emulation self._should_try_again = False self._step(instruction) if not self._should_try_again: break
def _step(self, instruction): """ A single attempt at executing an instruction. """ logger.debug("0x%x:\t%s\t%s" % (instruction.address, instruction.mnemonic, instruction.op_str)) registers = set(self._cpu.canonical_registers) # Refer to EFLAGS instead of individual flags for x86 if self._cpu.arch == CS_ARCH_X86: # The last 8 canonical registers of x86 are individual flags; replace # with the eflags registers -= set(['CF', 'PF', 'AF', 'ZF', 'SF', 'IF', 'DF', 'OF']) registers.add('EFLAGS') # TODO(mark): Unicorn 1.0.1 does not support reading YMM registers, # and simply returns back zero. If a unicorn emulated instruction writes to an # XMM reg, we will read back the corresponding YMM register, resulting in an # incorrect zero value being actually written to the XMM register. This is # fixed in Unicorn PR #819, so when that is included in a release, delete # these two lines. registers -= set(['YMM0', 'YMM1', 'YMM2', 'YMM3', 'YMM4', 'YMM5', 'YMM6', 'YMM7', 'YMM8', 'YMM9', 'YMM10', 'YMM11', 'YMM12', 'YMM13', 'YMM14', 'YMM15']) registers |= set(['XMM0', 'XMM1', 'XMM2', 'XMM3', 'XMM4', 'XMM5', 'XMM6', 'XMM7', 'XMM8', 'XMM9', 'XMM10', 'XMM11', 'XMM12', 'XMM13', 'XMM14', 'XMM15']) # XXX(yan): This concretizes the entire register state. This is overly # aggressive. Once capstone adds consistent support for accessing # referred registers, make this only concretize those registers being # read from. for reg in registers: val = self._cpu.read_register(reg) if issymbolic(val): from ..native.cpu.abstractcpu import ConcretizeRegister raise ConcretizeRegister(self._cpu, reg, "Concretizing for emulation.", policy='ONE') self._emu.reg_write(self._to_unicorn_id(reg), val) # Bring in the instruction itself instruction = self._cpu.decode_instruction(self._cpu.PC) text_bytes = self._cpu.read_bytes(self._cpu.PC, instruction.size) self._emu.mem_write(self._cpu.PC, b''.join(text_bytes)) self._emu.hook_add(UC_HOOK_MEM_READ_UNMAPPED, self._hook_unmapped) self._emu.hook_add(UC_HOOK_MEM_WRITE_UNMAPPED, self._hook_unmapped) self._emu.hook_add(UC_HOOK_MEM_FETCH_UNMAPPED, self._hook_unmapped) self._emu.hook_add(UC_HOOK_MEM_READ, self._hook_xfer_mem) self._emu.hook_add(UC_HOOK_MEM_WRITE, self._hook_xfer_mem) self._emu.hook_add(UC_HOOK_INTR, self._interrupt) saved_PC = self._cpu.PC try: pc = self._cpu.PC if self._cpu.arch == CS_ARCH_ARM and self._uc_mode == UC_MODE_THUMB: pc |= 1 self._emu.emu_start(pc, self._cpu.PC + instruction.size, count=1) except UcError as e: # We request re-execution by signaling error; if we we didn't set # _should_try_again, it was likely an actual error if not self._should_try_again: raise if self._should_try_again: return if logger.isEnabledFor(logging.DEBUG): logger.debug("=" * 10) for register in self._cpu.canonical_registers: logger.debug( f"Register {register:3s} " f"Manticore: {self._cpu.read_register(register):08x}, " f"Unicorn {self._emu.reg_read(self._to_unicorn_id(register)):08x}" ) logger.debug(">" * 10) # Bring back Unicorn registers to Manticore for reg in registers: val = self._emu.reg_read(self._to_unicorn_id(reg)) self._cpu.write_register(reg, val) # Unicorn hack. On single step, unicorn wont advance the PC register mu_pc = self.get_unicorn_pc() if saved_PC == mu_pc: self._cpu.PC = saved_PC + instruction.size # Raise the exception from a hook that Unicorn would have eaten if self._to_raise: raise self._to_raise return
def rlp_encode(item): r""" Recursive Length Prefix Encoding :param item: the object to encode, either a string, bytes, bytearray, int, long, or sequence https://github.com/ethereum/wiki/wiki/RLP >>> rlp_encode('dog') b'\x83dog' >>> rlp_encode([ 'cat', 'dog' ]) b'\xc8\x83cat\x83dog' >>> rlp_encode('') b'\x80' >>> rlp_encode([]) b'\xc0' >>> rlp_encode(0) b'\x80' >>> rlp_encode('\x00') b'\x00' >>> rlp_encode(15) b'\x0f' >>> rlp_encode(1024) b'\x82\x04\x00' >>> rlp_encode([ [], [[]], [ [], [[]] ] ]) b'\xc7\xc0\xc1\xc0\xc3\xc0\xc1\xc0' """ if item is None or item == 0: ret = b'\x80' elif isinstance(item, str): ret = rlp_encode(item.encode('utf8')) elif isinstance(item, (bytearray, bytes)): if len(item) == 1 and item[0] < 0x80: # For a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding. ret = item else: ret = encode_length(len(item), 0x80) + item elif isinstance(item, collections.abc.Sequence): output = b''.join(map(rlp_encode, item)) ret = encode_length(len(output), 0xC0) + output elif isinstance(item, int): ret = rlp_encode(int_to_bytes(item)) else: raise Exception("Cannot encode object of type %s" % type(item).__name__) return ret
def must_be_true(self, constraints, expression) -> bool: """Check if expression is True and that it can not be False with current constraints""" solutions = self.get_all_values(constraints, expression, maxcnt=2, silent=True) return solutions == [True]
def max(self, constraints, X: BitVec, M=10000): """ Iteratively finds the maximum value for a symbol within given constraints. :param X: a symbol or expression :param M: maximum number of iterations allowed """ assert isinstance(X, BitVec) return self.optimize(constraints, X, 'maximize', M)
def min(self, constraints, X: BitVec, M=10000): """ Iteratively finds the minimum value for a symbol within given constraints. :param constraints: constraints that the expression must fulfil :param X: a symbol or expression :param M: maximum number of iterations allowed """ assert isinstance(X, BitVec) return self.optimize(constraints, X, 'minimize', M)
def minmax(self, constraints, x, iters=10000): """Returns the min and max possible values for x within given constraints""" if issymbolic(x): m = self.min(constraints, x, iters) M = self.max(constraints, x, iters) return m, M else: return x, x
def _solver_version(self) -> Version: """ If we fail to parse the version, we assume z3's output has changed, meaning it's a newer version than what's used now, and therefore ok. Anticipated version_cmd_output format: 'Z3 version 4.4.2' 'Z3 version 4.4.5 - 64 bit - build hashcode $Z3GITHASH' """ self._reset() if self._received_version is None: self._send('(get-info :version)') self._received_version = self._recv() key, version = shlex.split(self._received_version[1:-1]) return Version(*map(int, version.split('.')))
def _start_proc(self): """Spawns z3 solver process""" assert '_proc' not in dir(self) or self._proc is None try: self._proc = Popen(shlex.split(self._command), stdin=PIPE, stdout=PIPE, bufsize=0, universal_newlines=True) except OSError as e: print(e, "Probably too many cached expressions? visitors._cache...") # Z3 was removed from the system in the middle of operation raise Z3NotFoundError # TODO(mark) don't catch this exception in two places # run solver specific initializations for cfg in self._init: self._send(cfg)
def _stop_proc(self): """ Stops the z3 solver process by: - sending an exit command to it, - sending a SIGKILL signal, - waiting till the process terminates (so we don't leave a zombie process) """ if self._proc is None: return if self._proc.returncode is None: try: self._send("(exit)") except (SolverError, IOError) as e: # z3 was too fast to close logger.debug(str(e)) finally: try: self._proc.stdin.close() except IOError as e: logger.debug(str(e)) try: self._proc.stdout.close() except IOError as e: logger.debug(str(e)) self._proc.kill() # Wait for termination, to avoid zombies. self._proc.wait() self._proc: Popen = None
def _reset(self, constraints=None): """Auxiliary method to reset the smtlib external solver to initial defaults""" if self._proc is None: self._start_proc() else: if self.support_reset: self._send("(reset)") for cfg in self._init: self._send(cfg) else: self._stop_proc() self._start_proc() if constraints is not None: self._send(constraints)
def _send(self, cmd: str): """ Send a string to the solver. :param cmd: a SMTLIBv2 command (ex. (check-sat)) """ logger.debug('>%s', cmd) try: self._proc.stdout.flush() self._proc.stdin.write(f'{cmd}\n') except IOError as e: raise SolverError(str(e))
def _recv(self) -> str: """Reads the response from the solver""" buf, left, right = self.__readline_and_count() bufl = [buf] while left != right: buf, l, r = self.__readline_and_count() bufl.append(buf) left += l right += r buf = ''.join(bufl).strip() logger.debug('<%s', buf) if '(error' in bufl[0]: raise Exception(f"Error in smtlib: {bufl[0]}") return buf
def _is_sat(self) -> bool: """ Check the satisfiability of the current state :return: whether current state is satisfiable or not. """ logger.debug("Solver.check() ") start = time.time() self._send('(check-sat)') status = self._recv() logger.debug("Check took %s seconds (%s)", time.time() - start, status) if status not in ('sat', 'unsat', 'unknown'): raise SolverError(status) if consider_unknown_as_unsat: if status == 'unknown': logger.info('Found an unknown core, probably a solver timeout') status = 'unsat' if status == 'unknown': raise SolverUnknown(status) return status == 'sat'
def _assert(self, expression: Bool): """Auxiliary method to send an assert""" assert isinstance(expression, Bool) smtlib = translate_to_smtlib(expression) self._send('(assert %s)' % smtlib)
def _getvalue(self, expression): """ Ask the solver for one possible assignment for given expression using current set of constraints. The current set of expressions must be sat. NOTE: This is an internal method: it uses the current solver state (set of constraints!). """ if not issymbolic(expression): return expression assert isinstance(expression, Variable) if isinstance(expression, Array): result = bytearray() for c in expression: expression_str = translate_to_smtlib(c) self._send('(get-value (%s))' % expression_str) response = self._recv() result.append(int('0x{:s}'.format(response.split(expression_str)[1][3:-2]), 16)) return bytes(result) else: self._send('(get-value (%s))' % expression.name) ret = self._recv() assert ret.startswith('((') and ret.endswith('))'), ret if isinstance(expression, Bool): return {'true': True, 'false': False}[ret[2:-2].split(' ')[1]] elif isinstance(expression, BitVec): pattern, base = self._get_value_fmt m = pattern.match(ret) expr, value = m.group('expr'), m.group('value') return int(value, base) raise NotImplementedError("_getvalue only implemented for Bool and BitVec")
def can_be_true(self, constraints, expression): """Check if two potentially symbolic values can be equal""" if isinstance(expression, bool): if not expression: return expression else: # if True check if constraints are feasible self._reset(constraints) return self._is_sat() assert isinstance(expression, Bool) with constraints as temp_cs: temp_cs.add(expression) self._reset(temp_cs.to_string(related_to=expression)) return self._is_sat()
def get_all_values(self, constraints, expression, maxcnt=None, silent=False): """Returns a list with all the possible values for the symbol x""" if not isinstance(expression, Expression): return [expression] assert isinstance(constraints, ConstraintSet) assert isinstance(expression, Expression) expression = simplify(expression) if maxcnt is None: maxcnt = consts.maxsolutions with constraints as temp_cs: if isinstance(expression, Bool): var = temp_cs.new_bool() elif isinstance(expression, BitVec): var = temp_cs.new_bitvec(expression.size) elif isinstance(expression, Array): var = temp_cs.new_array(index_max=expression.index_max, value_bits=expression.value_bits, taint=expression.taint).array else: raise NotImplementedError(f"get_all_values only implemented for {type(expression)} expression type.") temp_cs.add(var == expression) self._reset(temp_cs.to_string(related_to=var)) result = [] while self._is_sat(): value = self._getvalue(var) result.append(value) self._assert(var != value) if len(result) >= maxcnt: if silent: # do not throw an exception if set to silent # Default is not silent, assume user knows # what they are doing and will check the size # of returned vals list (previous smtlib behavior) break else: raise TooManySolutions(result) return result
def optimize(self, constraints: ConstraintSet, x: BitVec, goal: str, M=10000): """ Iteratively finds the maximum or minimum value for the operation (Normally Operators.UGT or Operators.ULT) :param constraints: constraints to take into account :param x: a symbol or expression :param goal: goal to achieve, either 'maximize' or 'minimize' :param M: maximum number of iterations allowed """ assert goal in ('maximize', 'minimize') assert isinstance(x, BitVec) operation = {'maximize': Operators.UGE, 'minimize': Operators.ULE}[goal] with constraints as temp_cs: X = temp_cs.new_bitvec(x.size) temp_cs.add(X == x) aux = temp_cs.new_bitvec(X.size, name='optimized_') self._reset(temp_cs.to_string(related_to=X)) self._send(aux.declaration) if getattr(self, f'support_{goal}'): self._push() try: self._assert(operation(X, aux)) self._send('(%s %s)' % (goal, aux.name)) self._send('(check-sat)') _status = self._recv() if _status not in ('sat', 'unsat', 'unknown'): # Minimize (or Maximize) sometimes prints the objective before the status # This will be a line like NAME |-> VALUE maybe_sat = self._recv() if maybe_sat == 'sat': m = RE_MIN_MAX_OBJECTIVE_EXPR_VALUE.match(_status) expr, value = m.group('expr'), m.group('value') assert expr == aux.name return int(value) elif _status == 'sat': ret = self._recv() if not (ret.startswith('(') and ret.endswith(')')): raise SolverError('bad output on max, z3 may have been killed') m = RE_OBJECTIVES_EXPR_VALUE.match(ret) expr, value = m.group('expr'), m.group('value') assert expr == aux.name return int(value) finally: self._pop() self._reset(temp_cs) self._send(aux.declaration) operation = {'maximize': Operators.UGT, 'minimize': Operators.ULT}[goal] self._assert(aux == X) last_value = None i = 0 while self._is_sat(): last_value = self._getvalue(aux) self._assert(operation(aux, last_value)) i = i + 1 if i > M: raise SolverError("Optimizing error, maximum number of iterations was reached") if last_value is not None: return last_value raise SolverError("Optimizing error, unsat or unknown core")
def get_value(self, constraints, expression): """ Ask the solver for one possible result of given expression using given set of constraints. """ if not issymbolic(expression): return expression assert isinstance(expression, (Bool, BitVec, Array)) with constraints as temp_cs: if isinstance(expression, Bool): var = temp_cs.new_bool() elif isinstance(expression, BitVec): var = temp_cs.new_bitvec(expression.size) elif isinstance(expression, Array): var = [] result = [] for i in range(expression.index_max): subvar = temp_cs.new_bitvec(expression.value_bits) var.append(subvar) temp_cs.add(subvar == simplify(expression[i])) self._reset(temp_cs) if not self._is_sat(): raise SolverError('Model is not available') for i in range(expression.index_max): self._send('(get-value (%s))' % var[i].name) ret = self._recv() assert ret.startswith('((') and ret.endswith('))') pattern, base = self._get_value_fmt m = pattern.match(ret) expr, value = m.group('expr'), m.group('value') result.append(int(value, base)) return bytes(result) temp_cs.add(var == expression) self._reset(temp_cs) if not self._is_sat(): raise SolverError('Model is not available') self._send('(get-value (%s))' % var.name) ret = self._recv() if not (ret.startswith('((') and ret.endswith('))')): raise SolverError('SMTLIB error parsing response: %s' % ret) if isinstance(expression, Bool): return {'true': True, 'false': False}[ret[2:-2].split(' ')[1]] if isinstance(expression, BitVec): pattern, base = self._get_value_fmt m = pattern.match(ret) expr, value = m.group('expr'), m.group('value') return int(value, base) raise NotImplementedError("get_value only implemented for Bool and BitVec")
def summarized_name(self, name): """ Produce a summarized record name i.e. manticore.core.executor -> m.c.executor """ components = name.split('.') prefix = '.'.join(c[0] for c in components[:-1]) return f'{prefix}.{components[-1]}'
def colored_level_name(self, levelname): """ Colors the logging level in the logging record """ if self.colors_disabled: return self.plain_levelname_format.format(levelname) else: return self.colored_levelname_format.format(self.color_map[levelname], levelname)
def _find_zero(cpu, constrs, ptr): """ Helper for finding the closest NULL or, effectively NULL byte from a starting address. :param Cpu cpu: :param ConstraintSet constrs: Constraints for current `State` :param int ptr: Address to start searching for a zero from :return: Offset from `ptr` to first byte that is 0 or an `Expression` that must be zero """ offset = 0 while True: byt = cpu.read_int(ptr + offset, 8) if issymbolic(byt): if not solver.can_be_true(constrs, byt != 0): break else: if byt == 0: break offset += 1 return offset
def strcmp(state, s1, s2): """ strcmp symbolic model. Algorithm: Walks from end of string (minimum offset to NULL in either string) to beginning building tree of ITEs each time either of the bytes at current offset is symbolic. Points of Interest: - We've been building up a symbolic tree but then encounter two concrete bytes that differ. We can throw away the entire symbolic tree! - If we've been encountering concrete bytes that match at the end of the string as we walk forward, and then we encounter a pair where one is symbolic, we can forget about that 0 `ret` we've been tracking and just replace it with the symbolic subtraction of the two :param State state: Current program state :param int s1: Address of string 1 :param int s2: Address of string 2 :return: Symbolic strcmp result :rtype: Expression or int """ cpu = state.cpu if issymbolic(s1): raise ConcretizeArgument(state.cpu, 1) if issymbolic(s2): raise ConcretizeArgument(state.cpu, 2) s1_zero_idx = _find_zero(cpu, state.constraints, s1) s2_zero_idx = _find_zero(cpu, state.constraints, s2) min_zero_idx = min(s1_zero_idx, s2_zero_idx) ret = None for offset in range(min_zero_idx, -1, -1): s1char = ZEXTEND(cpu.read_int(s1 + offset, 8), cpu.address_bit_size) s2char = ZEXTEND(cpu.read_int(s2 + offset, 8), cpu.address_bit_size) if issymbolic(s1char) or issymbolic(s2char): if ret is None or (not issymbolic(ret) and ret == 0): ret = s1char - s2char else: ret = ITEBV(cpu.address_bit_size, s1char != s2char, s1char - s2char, ret) else: if s1char != s2char: ret = s1char - s2char elif ret is None: ret = 0 return ret
def strlen(state, s): """ strlen symbolic model. Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic. :param State state: current program state :param int s: Address of string :return: Symbolic strlen result :rtype: Expression or int """ cpu = state.cpu if issymbolic(s): raise ConcretizeArgument(state.cpu, 1) zero_idx = _find_zero(cpu, state.constraints, s) ret = zero_idx for offset in range(zero_idx - 1, -1, -1): byt = cpu.read_int(s + offset, 8) if issymbolic(byt): ret = ITEBV(cpu.address_bit_size, byt == 0, offset, ret) return ret
def all_events(cls): """ Return all events that all subclasses have so far registered to publish. """ all_evts = set() for cls, evts in cls.__all_events__.items(): all_evts.update(evts) return all_evts
def forward_events_to(self, sink, include_source=False): """This forwards signal to sink""" assert isinstance(sink, Eventful), f'{sink.__class__.__name__} is not Eventful' self._forwards[sink] = include_source
def context(self): """ Convenient access to shared context """ if self._context is not None: return self._context else: logger.warning("Using shared context without a lock") return self._executor._shared_context
def locked_context(self, key=None, value_type=list): """ A context manager that provides safe parallel access to the global Manticore context. This should be used to access the global Manticore context when parallel analysis is activated. Code within the `with` block is executed atomically, so access of shared variables should occur within. Example use:: with m.locked_context() as context: visited = context['visited'] visited.append(state.cpu.PC) context['visited'] = visited Optionally, parameters can specify a key and type for the object paired to this key.:: with m.locked_context('feature_list', list) as feature_list: feature_list.append(1) :param object key: Storage key :param value_type: type of value associated with key :type value_type: list or dict or set """ @contextmanager def _real_context(): if self._context is not None: yield self._context else: with self._executor.locked_context() as context: yield context with _real_context() as context: if key is None: yield context else: assert value_type in (list, dict, set) ctx = context.get(key, value_type()) yield ctx context[key] = ctx
def get_profiling_stats(self): """ Returns a pstat.Stats instance with profiling results if `run` was called with `should_profile=True`. Otherwise, returns `None`. """ profile_file_path = os.path.join(self.workspace, 'profiling.bin') try: return pstats.Stats(profile_file_path) except Exception as e: logger.debug(f'Failed to get profiling stats: {e}') return None
def run(self, procs=1, timeout=None, should_profile=False): """ Runs analysis. :param int procs: Number of parallel worker processes :param timeout: Analysis timeout, in seconds """ assert not self.running, "Manticore is already running." self._start_run() self._last_run_stats['time_started'] = time.time() with self.shutdown_timeout(timeout): self._start_workers(procs, profiling=should_profile) self._join_workers() self._finish_run(profiling=should_profile)
def main(): """ Dispatches execution into one of Manticore's engines: evm or native. """ args = parse_arguments() if args.no_colors: log.disable_colors() sys.setrecursionlimit(consts.recursionlimit) ManticoreBase.verbosity(args.v) if args.argv[0].endswith('.sol'): ethereum_main(args, logger) else: install_helper.ensure_native_deps() native_main(args, logger)
def GetNBits(value, nbits): """ Get the first `nbits` from `value`. :param value: Source value from which to extract :type value: int or long or BitVec :param int nbits: How many bits to extract :return: Low `nbits` bits of `value`. :rtype int or long or BitVec """ # NOP if sizes are the same if isinstance(value, int): return Operators.EXTRACT(value, 0, nbits) elif isinstance(value, BitVec): if value.size < nbits: return Operators.ZEXTEND(value, nbits) else: return Operators.EXTRACT(value, 0, nbits)
def SInt(value, width): """ Convert a bitstring `value` of `width` bits to a signed integer representation. :param value: The value to convert. :type value: int or long or BitVec :param int width: The width of the bitstring to consider :return: The converted value :rtype int or long or BitVec """ return Operators.ITEBV(width, Bit(value, width - 1) == 1, GetNBits(value, width) - 2**width, GetNBits(value, width))
def LSL_C(value, amount, width): """ The ARM LSL_C (logical left shift with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value and the carry result :rtype tuple """ assert amount > 0 value = Operators.ZEXTEND(value, width * 2) shifted = value << amount result = GetNBits(shifted, width) carry = Bit(shifted, width) return (result, carry)
def LSL(value, amount, width): """ The ARM LSL (logical left shift) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ if amount == 0: return value result, _ = LSL_C(value, amount, width) return result
def LSR_C(value, amount, width): """ The ARM LSR_C (logical shift right with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value and carry result :rtype tuple """ assert amount > 0 result = GetNBits(value >> amount, width) carry = Bit(value >> (amount - 1), 0) return (result, carry)
def LSR(value, amount, width): """ The ARM LSR (logical shift right) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ if amount == 0: return value result, _ = LSR_C(value, amount, width) return result
def ASR_C(value, amount, width): """ The ARM ASR_C (arithmetic shift right with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value and carry result :rtype tuple """ assert amount <= width assert amount > 0 assert amount + width <= width * 2 value = Operators.SEXTEND(value, width, width * 2) result = GetNBits(value >> amount, width) carry = Bit(value, amount - 1) return (result, carry)
def ASR(value, amount, width): """ The ARM ASR (arithmetic shift right) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ if amount == 0: return value result, _ = ASR_C(value, amount, width) return result
def ROR_C(value, amount, width): """ The ARM ROR_C (rotate right with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value and carry result :rtype tuple """ assert amount <= width assert amount > 0 m = amount % width right, _ = LSR_C(value, m, width) left, _ = LSL_C(value, width - m, width) result = left | right carry = Bit(result, width - 1) return (result, carry)
def ROR(value, amount, width): """ The ARM ROR (rotate right) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ if amount == 0: return value result, _ = ROR_C(value, amount, width) return result
def RRX_C(value, carry, width): """ The ARM RRX (rotate right with extend and with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value and carry result :rtype tuple """ carry_out = Bit(value, 0) result = (value >> 1) | (carry << (width - 1)) return (result, carry_out)
def RRX(value, carry, width): """ The ARM RRX (rotate right with extend) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ result, _ = RRX_C(value, carry, width) return result
def locked_context(self, key=None, default=dict): """ Policy shared context dictionary """ keys = ['policy'] if key is not None: keys.append(key) with self._executor.locked_context('.'.join(keys), default) as policy_context: yield policy_context
def _add_state_callback(self, state_id, state): """ Save summarize(state) on policy shared context before the state is stored """ summary = self.summarize(state) if summary is None: return with self.locked_context('summaries', dict) as ctx: ctx[state_id] = summary
def _visited_callback(self, state, pc, instr): """ Maintain our own copy of the visited set """ with self.locked_context('visited', set) as ctx: ctx.add(pc)
def _visited_callback(self, state, pc, instr): """ Maintain our own copy of the visited set """ pc = state.platform.current.PC with self.locked_context('visited', dict) as ctx: ctx[pc] = ctx.get(pc, 0) + 1
def locked_context(self, key=None, default=dict): """ Executor context is a shared memory object. All workers share this. It needs a lock. Its used like this: with executor.context() as context: visited = context['visited'] visited.append(state.cpu.PC) context['visited'] = visited """ assert default in (list, dict, set) with self._lock: if key is None: yield self._shared_context else: sub_context = self._shared_context.get(key, None) if sub_context is None: sub_context = default() yield sub_context self._shared_context[key] = sub_context
def enqueue(self, state): """ Enqueue state. Save state on storage, assigns an id to it, then add it to the priority queue """ # save the state to secondary storage state_id = self._workspace.save_state(state) self.put(state_id) self._publish('did_enqueue_state', state_id, state) return state_id
def put(self, state_id): """ Enqueue it for processing """ self._states.append(state_id) self._lock.notify_all() return state_id
def get(self): """ Dequeue a state with the max priority """ # A shutdown has been requested if self.is_shutdown(): return None # if not more states in the queue, let's wait for some forks while len(self._states) == 0: # if no worker is running, bail out if self.running == 0: return None # if a shutdown has been requested, bail out if self.is_shutdown(): return None # if there ares actually some workers running, wait for state forks logger.debug("Waiting for available states") self._lock.wait() state_id = self._policy.choice(list(self._states)) if state_id is None: return None del self._states[self._states.index(state_id)] return state_id
def fork(self, state, expression, policy='ALL', setstate=None): """ Fork state on expression concretizations. Using policy build a list of solutions for expression. For the state on each solution setting the new state with setstate For example if expression is a Bool it may have 2 solutions. True or False. Parent (expression = ??) Child1 Child2 (expression = True) (expression = True) setstate(True) setstate(False) The optional setstate() function is supposed to set the concrete value in the child state. """ assert isinstance(expression, Expression) if setstate is None: setstate = lambda x, y: None # Find a set of solutions for expression solutions = state.concretize(expression, policy) if not solutions: raise ExecutorError("Forking on unfeasible constraint set") if len(solutions) == 1: setstate(state, solutions[0]) return state logger.info("Forking. Policy: %s. Values: %s", policy, ', '.join(f'0x{sol:x}' for sol in solutions)) self._publish('will_fork_state', state, expression, solutions, policy) # Build and enqueue a state for each solution children = [] for new_value in solutions: with state as new_state: new_state.constrain(expression == new_value) # and set the PC of the new state to the concrete pc-dest #(or other register or memory address to concrete) setstate(new_state, new_value) self._publish('did_fork_state', new_state, expression, new_value, policy) # enqueue new_state state_id = self.enqueue(new_state) # maintain a list of children for logging purpose children.append(state_id) logger.info("Forking current state into states %r", children) return None
def run(self): """ Entry point of the Executor; called by workers to start analysis. """ # policy_order=self.policy_order # policy=self.policy current_state = None current_state_id = None with WithKeyboardInterruptAs(self.shutdown): # notify siblings we are about to start a run self._notify_start_run() logger.debug("Starting Manticore Symbolic Emulator Worker (pid %d).", os.getpid()) solver = Z3Solver() while not self.is_shutdown(): try: # handle fatal errors: exceptions in Manticore try: # handle external (e.g. solver) errors, and executor control exceptions # select a suitable state to analyze if current_state is None: with self._lock: # notify siblings we are about to stop this run self._notify_stop_run() try: # Select a single state_id current_state_id = self.get() # load selected state from secondary storage if current_state_id is not None: self._publish('will_load_state', current_state_id) current_state = self._workspace.load_state(current_state_id) self.forward_events_from(current_state, True) self._publish('did_load_state', current_state, current_state_id) logger.info("load state %r", current_state_id) # notify siblings we have a state to play with finally: self._notify_start_run() # If current_state is still None. We are done. if current_state is None: logger.debug("No more states in the queue, byte bye!") break assert current_state is not None assert current_state.constraints is current_state.platform.constraints # Allows to terminate manticore worker on user request while not self.is_shutdown(): if not current_state.execute(): break else: # Notify this worker is done self._publish('will_terminate_state', current_state, current_state_id, TerminateState('Shutdown')) current_state = None # Handling Forking and terminating exceptions except Concretize as e: # expression # policy # setstate() logger.debug("Generic state fork on condition") current_state = self.fork(current_state, e.expression, e.policy, e.setstate) except TerminateState as e: # Notify this worker is done self._publish('will_terminate_state', current_state, current_state_id, e) logger.debug("Generic terminate state") if e.testcase: self._publish('internal_generate_testcase', current_state, message=str(e)) current_state = None except SolverError as e: # raise import traceback trace = traceback.format_exc() logger.error("Exception: %s\n%s", str(e), trace) # Notify this state is done self._publish('will_terminate_state', current_state, current_state_id, e) if solver.check(current_state.constraints): self._publish('internal_generate_testcase', current_state, message="Solver failed" + str(e)) current_state = None except (Exception, AssertionError) as e: # raise import traceback trace = traceback.format_exc() logger.error("Exception: %s\n%s", str(e), trace) # Notify this worker is done self._publish('will_terminate_state', current_state, current_state_id, e) current_state = None assert current_state is None or self.is_shutdown() # notify siblings we are about to stop this run self._notify_stop_run()
def linux(cls, path, argv=None, envp=None, entry_symbol=None, symbolic_files=None, concrete_start='', pure_symbolic=False, stdin_size=None, **kwargs): """ Constructor for Linux binary analysis. :param str path: Path to binary to analyze :param argv: Arguments to provide to the binary :type argv: list[str] :param envp: Environment to provide to the binary :type envp: dict[str, str] :param entry_symbol: Entry symbol to resolve to start execution :type envp: str :param symbolic_files: Filenames to mark as having symbolic input :type symbolic_files: list[str] :param str concrete_start: Concrete stdin to use before symbolic input :param int stdin_size: symbolic stdin size to use :param kwargs: Forwarded to the Manticore constructor :return: Manticore instance, initialized with a Linux State :rtype: Manticore """ if stdin_size is None: stdin_size = consts.stdin_size try: return cls(_make_linux(path, argv, envp, entry_symbol, symbolic_files, concrete_start, pure_symbolic, stdin_size), **kwargs) except elftools.common.exceptions.ELFError: raise Exception(f'Invalid binary: {path}')
def decree(cls, path, concrete_start='', **kwargs): """ Constructor for Decree binary analysis. :param str path: Path to binary to analyze :param str concrete_start: Concrete stdin to use before symbolic input :param kwargs: Forwarded to the Manticore constructor :return: Manticore instance, initialized with a Decree State :rtype: Manticore """ try: return cls(_make_decree(path, concrete_start), **kwargs) except KeyError: # FIXME(mark) magic parsing for DECREE should raise better error raise Exception(f'Invalid binary: {path}')
def init(self, f): """ A decorator used to register a hook function to run before analysis begins. Hook function takes one :class:`~manticore.core.state.State` argument. """ def callback(manticore_obj, state): f(state) self.subscribe('will_start_run', types.MethodType(callback, self)) return f
def hook(self, pc): """ A decorator used to register a hook function for a given instruction address. Equivalent to calling :func:`~add_hook`. :param pc: Address of instruction to hook :type pc: int or None """ def decorator(f): self.add_hook(pc, f) return f return decorator
def add_hook(self, pc, callback): """ Add a callback to be invoked on executing a program counter. Pass `None` for pc to invoke callback on every instruction. `callback` should be a callable that takes one :class:`~manticore.core.state.State` argument. :param pc: Address of instruction to hook :type pc: int or None :param callable callback: Hook function """ if not (isinstance(pc, int) or pc is None): raise TypeError(f"pc must be either an int or None, not {pc.__class__.__name__}") else: self._hooks.setdefault(pc, set()).add(callback) if self._hooks: self._executor.subscribe('will_execute_instruction', self._hook_callback)
def _hook_callback(self, state, pc, instruction): 'Invoke all registered generic hooks' # Ignore symbolic pc. # TODO(yan): Should we ask the solver if any of the hooks are possible, # and execute those that are? if issymbolic(pc): return # Invoke all pc-specific hooks for cb in self._hooks.get(pc, []): cb(state) # Invoke all pc-agnostic hooks for cb in self._hooks.get(None, []): cb(state)
def resolve(self, symbol): """ A helper method used to resolve a symbol name into a memory address when injecting hooks for analysis. :param symbol: function name to be resolved :type symbol: string :param line: if more functions present, optional line number can be included :type line: int or None """ with open(self.binary_path, 'rb') as f: elffile = ELFFile(f) # iterate over sections and identify symbol table section for section in elffile.iter_sections(): if not isinstance(section, SymbolTableSection): continue # get list of symbols by name symbols = section.get_symbol_by_name(symbol) if not symbols: continue # return first indexed memory address for the symbol, return symbols[0].entry['st_value'] raise ValueError(f"The {self.binary_path} ELFfile does not contain symbol {symbol}")
def binary_arch(binary): """ helper method for determining binary architecture :param binary: str for binary to introspect. :rtype bool: True for x86_64, False otherwise """ with open(binary, 'rb') as f: elffile = ELFFile(f) if elffile['e_machine'] == 'EM_X86_64': return True else: return False
def binary_symbols(binary): """ helper method for getting all binary symbols with SANDSHREW_ prepended. We do this in order to provide the symbols Manticore should hook on to perform main analysis. :param binary: str for binary to instrospect. :rtype list: list of symbols from binary """ def substr_after(string, delim): return string.partition(delim)[2] with open(binary, 'rb') as f: elffile = ELFFile(f) for section in elffile.iter_sections(): if not isinstance(section, SymbolTableSection): continue symbols = [sym.name for sym in section.iter_symbols() if sym] return [substr_after(name, PREPEND_SYM) for name in symbols if name.startswith(PREPEND_SYM)]
def get_group(name: str) -> _Group: """ Get a configuration variable group named |name| """ global _groups if name in _groups: return _groups[name] group = _Group(name) _groups[name] = group return group
def save(f): """ Save current config state to an yml file stream identified by |f| :param f: where to write the config file """ global _groups c = {} for group_name, group in _groups.items(): section = {var.name: var.value for var in group.updated_vars()} if not section: continue c[group_name] = section yaml.safe_dump(c, f, line_break=True)
def parse_config(f): """ Load an yml-formatted configuration from file stream |f| :param file f: Where to read the config. """ try: c = yaml.safe_load(f) for section_name, section in c.items(): group = get_group(section_name) for key, val in section.items(): group.update(key) setattr(group, key, val) # Any exception here should trigger the warning; from not being able to parse yaml # to reading poorly formatted values except Exception: raise ConfigError("Failed reading config file. Do you have a local [.]manticore.yml file?")
def load_overrides(path=None): """ Load config overrides from the yml file at |path|, or from default paths. If a path is provided and it does not exist, raise an exception Default paths: ./mcore.yml, ./.mcore.yml, ./manticore.yml, ./.manticore.yml. """ if path is not None: names = [path] else: possible_names = ['mcore.yml', 'manticore.yml'] names = [os.path.join('.', ''.join(x)) for x in product(['', '.'], possible_names)] for name in names: try: with open(name, 'r') as yml_f: logger.info(f'Reading configuration from {name}') parse_config(yml_f) break except FileNotFoundError: pass else: if path is not None: raise FileNotFoundError(f"'{path}' not found for config overrides")
def add_config_vars_to_argparse(args): """ Import all defined config vars into |args|, for parsing command line. :param args: A container for argparse vars :type args: argparse.ArgumentParser or argparse._ArgumentGroup :return: """ global _groups for group_name, group in _groups.items(): for key in group: obj = group._var_object(key) args.add_argument(f"--{group_name}.{key}", type=type(obj.default), default=obj.default, help=obj.description)
def process_config_values(parser: argparse.ArgumentParser, args: argparse.Namespace): """ Bring in provided config values to the args parser, and import entries to the config from all arguments that were actually passed on the command line :param parser: The arg parser :param args: The value that parser.parse_args returned """ # First, load a local config file, if passed or look for one in pwd if it wasn't. load_overrides(args.config) # Get a list of defined config vals. If these are passed on the command line, # update them in their correct group, not in the cli group defined_vars = list(get_config_keys()) command_line_args = vars(args) # Bring in the options keys into args config_cli_args = get_group('cli') # Place all command line args into the cli group (for saving in the workspace). If # the value is set on command line, then it takes precedence; otherwise we try to # read it from the config file's cli group. for k in command_line_args: default = parser.get_default(k) set_val = getattr(args, k) if default is not set_val: if k not in defined_vars: config_cli_args.update(k, value=set_val) else: # Update a var's native group group_name, key = k.split('.') group = get_group(group_name) setattr(group, key, set_val) else: if k in config_cli_args: setattr(args, k, getattr(config_cli_args, k))
def add(self, name: str, default=None, description: str=None): """ Add a variable named |name| to this value group, optionally giving it a default value and a description. Variables must be added with this method before they can be set or read. Reading a variable replaces the variable that was defined previously, but updates the description if a new one is set. """ if name in self._vars: raise ConfigError(f"{self.name}.{name} already defined.") if name == 'name': raise ConfigError("'name' is a reserved name for a group.") v = _Var(name, description=description, default=default) self._vars[name] = v
def update(self, name: str, value=None, default=None, description: str=None): """ Like add, but can tolerate existing values; also updates the value. Mostly used for setting fields from imported INI files and modified CLI flags. """ if name in self._vars: description = description or self._vars[name].description default = default or self._vars[name].default elif name == 'name': raise ConfigError("'name' is a reserved name for a group.") v = _Var(name, description=description, default=default, defined=False) v.value = value self._vars[name] = v
def get_description(self, name: str) -> str: """ Return the description, or a help string of variable identified by |name|. """ if name not in self._vars: raise ConfigError(f"{self.name}.{name} not defined.") return self._vars[name].description
def correspond(text): """Communicate with the child process without closing stdin.""" subproc.stdin.write(text) subproc.stdin.flush() return drain()
def function_signature_for_name_and_inputs(name: str, inputs: Sequence[Mapping[str, Any]]) -> str: """Returns the function signature for the specified name and Solidity JSON metadata inputs array. The ABI specification defines the function signature as the function name followed by the parenthesised list of parameter types separated by single commas and no spaces. See https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector """ return name + SolidityMetadata.tuple_signature_for_components(inputs)
def tuple_signature_for_components(components: Sequence[Mapping[str, Any]]) -> str: """Equivalent to ``function_signature_for_name_and_inputs('', components)``.""" ts = [] for c in components: t: str = c['type'] if t.startswith('tuple'): assert len(t) == 5 or t[5] == '[' t = SolidityMetadata.tuple_signature_for_components(c['components']) + t[5:] ts.append(t) return f'({",".join(ts)})'
def get_constructor_arguments(self) -> str: """Returns the tuple type signature for the arguments of the contract constructor.""" item = self._constructor_abi_item return '()' if item is None else self.tuple_signature_for_components(item['inputs'])
def get_source_for(self, asm_offset, runtime=True): """ Solidity source code snippet related to `asm_pos` evm bytecode offset. If runtime is False, initialization bytecode source map is used """ srcmap = self.get_srcmap(runtime) try: beg, size, _, _ = srcmap[asm_offset] except KeyError: #asm_offset pointing outside the known bytecode return '' output = '' nl = self.source_code[:beg].count('\n') + 1 snippet = self.source_code[beg:beg + size] for l in snippet.split('\n'): output += ' %s %s\n' % (nl, l) nl += 1 return output
def constructor_abi(self) -> Dict[str, Any]: """Returns a copy of the Solidity JSON ABI item for the contract constructor. The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_ """ item = self._constructor_abi_item if item: return dict(item) return {'inputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'constructor'}
def get_abi(self, hsh: bytes) -> Dict[str, Any]: """Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``. If no normal contract function has the specified selector, a dict describing the default or non-default fallback function is returned. The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_ """ if not isinstance(hsh, (bytes, bytearray)): raise TypeError('The selector argument must be a concrete byte array') sig = self._function_signatures_by_selector.get(hsh) if sig is not None: return dict(self._function_abi_items_by_signature[sig]) item = self._fallback_function_abi_item if item is not None: return dict(item) # An item describing the default fallback function. return {'payable': False, 'stateMutability': 'nonpayable', 'type': 'fallback'}
def get_func_argument_types(self, hsh: bytes): """Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``. If no normal contract function has the specified selector, the empty tuple type signature ``'()'`` is returned. """ if not isinstance(hsh, (bytes, bytearray)): raise TypeError('The selector argument must be a concrete byte array') sig = self._function_signatures_by_selector.get(hsh) return '()' if sig is None else sig[sig.find('('):]
def get_func_return_types(self, hsh: bytes) -> str: """Returns the tuple type signature for the output values of the function associated with the selector ``hsh``. If no normal contract function has the specified selector, the empty tuple type signature ``'()'`` is returned. """ if not isinstance(hsh, (bytes, bytearray)): raise TypeError('The selector argument must be a concrete byte array') abi = self.get_abi(hsh) outputs = abi.get('outputs') return '()' if outputs is None else SolidityMetadata.tuple_signature_for_components(outputs)
def get_func_name(self, hsh: bytes) -> str: """Returns the name of the normal function with the selector ``hsh``, or ``'{fallback}'`` if no such function exists. """ if not isinstance(hsh, (bytes, bytearray)): raise TypeError('The selector argument must be a concrete byte array') sig = self._function_signatures_by_selector.get(hsh) return '{fallback}' if sig is None else sig[:sig.find('(')]
def get_func_signature(self, hsh: bytes) -> Optional[str]: """Returns the signature of the normal function with the selector ``hsh``, or ``None`` if no such function exists. This function returns ``None`` for any selector that will be dispatched to a fallback function. """ if not isinstance(hsh, (bytes, bytearray)): raise TypeError('The selector argument must be a concrete byte array') return self._function_signatures_by_selector.get(hsh)
def function_selectors(self) -> Iterable[bytes]: """The selectors of all normal contract functions, plus ``self.fallback_function_selector`` if the contract has a non-default fallback function. """ selectors = self._function_signatures_by_selector.keys() if self._fallback_function_abi_item is None: return tuple(selectors) return (*selectors, self.fallback_function_selector)
def hashes(self) -> Tuple[bytes, ...]: """The selectors of all normal contract functions, plus ``self.fallback_function_selector``.""" selectors = self._function_signatures_by_selector.keys() return (*selectors, self.fallback_function_selector)
def convert_permissions(m_perms): """ Converts a Manticore permission string into a Unicorn permission :param m_perms: Manticore perm string ('rwx') :return: Unicorn Permissions """ permissions = UC_PROT_NONE if 'r' in m_perms: permissions |= UC_PROT_READ if 'w' in m_perms: permissions |= UC_PROT_WRITE if 'x' in m_perms: permissions |= UC_PROT_EXEC return permissions