if amount == <NUM_LIT:0>:<EOL><INDENT>return value<EOL><DEDENT>result, _ = LSL_C(value, amount, width)<EOL>return result<EOL>

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 == <NUM_LIT:0>:<EOL><INDENT>return value<EOL><DEDENT>result, _ = ROR_C(value, amount, width)<EOL>return result<EOL>

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


return (<NUM_LIT:1> << width) - <NUM_LIT:1><EOL>

Return a mask with the low `width` bits set.

:param int width: How many bits to set to 1
:return: int or long


return Operators.ITEBV(width, Bit(value, width - <NUM_LIT:1>) == <NUM_LIT:1>,<EOL>GetNBits(value, width) - <NUM_LIT:2>**width,<EOL>GetNBits(value, width))<EOL>

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


if amount == <NUM_LIT:0>:<EOL><INDENT>return value<EOL><DEDENT>result, _ = LSR_C(value, amount, width)<EOL>return result<EOL>

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


assert amount <= width<EOL>assert amount > <NUM_LIT:0><EOL>assert amount + width <= width * <NUM_LIT:2><EOL>value = Operators.SEXTEND(value, width, width * <NUM_LIT:2>)<EOL>result = GetNBits(value >> amount, width)<EOL>carry = Bit(value, amount - <NUM_LIT:1>)<EOL>return (result, carry)<EOL>

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


<EOL>if isinstance(value, int):<EOL><INDENT>return Operators.EXTRACT(value, <NUM_LIT:0>, nbits)<EOL><DEDENT>elif isinstance(value, BitVec):<EOL><INDENT>if value.size < nbits:<EOL><INDENT>return Operators.ZEXTEND(value, nbits)<EOL><DEDENT>else:<EOL><INDENT>return Operators.EXTRACT(value, <NUM_LIT:0>, nbits)<EOL><DEDENT><DEDENT>

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


@instruction<EOL><INDENT>def MOV(cpu, dest, src):<DEDENT>

if cpu.mode == cs.CS_MODE_ARM:<EOL><INDENT>result, carry_out = src.read(with_carry=True)<EOL>dest.write(result)<EOL>cpu.set_flags(C=carry_out, N=HighBit(result), Z=(result == <NUM_LIT:0>))<EOL><DEDENT>else:<EOL><INDENT>result = src.read()<EOL>dest.write(result)<EOL>cpu.set_flags(N=HighBit(result), Z=(result == <NUM_LIT:0>))<EOL><DEDENT>

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.


def _shift(cpu, value, _type, amount, carry):

assert(cs.arm.ARM_SFT_INVALID < _type <= cs.arm.ARM_SFT_RRX_REG)<EOL>if _type in (cs.arm.ARM_SFT_RRX, cs.arm.ARM_SFT_RRX_REG) and amount != <NUM_LIT:1>:<EOL><INDENT>amount = <NUM_LIT:1><EOL><DEDENT>elif _type in range(cs.arm.ARM_SFT_ASR_REG, cs.arm.ARM_SFT_RRX_REG + <NUM_LIT:1>):<EOL><INDENT>if cpu.mode == cs.CS_MODE_THUMB:<EOL><INDENT>src = amount.read()<EOL><DEDENT>else:<EOL><INDENT>src_reg = cpu.instruction.reg_name(amount).upper()<EOL>src = cpu.regfile.read(src_reg)<EOL><DEDENT>amount = Operators.EXTRACT(src, <NUM_LIT:0>, <NUM_LIT:8>)<EOL><DEDENT>if amount == <NUM_LIT:0>:<EOL><INDENT>return value, carry<EOL><DEDENT>width = cpu.address_bit_size<EOL>if _type in (cs.arm.ARM_SFT_ASR, cs.arm.ARM_SFT_ASR_REG):<EOL><INDENT>return ASR_C(value, amount, width)<EOL><DEDENT>elif _type in (cs.arm.ARM_SFT_LSL, cs.arm.ARM_SFT_LSL_REG):<EOL><INDENT>return LSL_C(value, amount, width)<EOL><DEDENT>elif _type in (cs.arm.ARM_SFT_LSR, cs.arm.ARM_SFT_LSR_REG):<EOL><INDENT>return LSR_C(value, amount, width)<EOL><DEDENT>elif _type in (cs.arm.ARM_SFT_ROR, cs.arm.ARM_SFT_ROR_REG):<EOL><INDENT>return ROR_C(value, amount, width)<EOL><DEDENT>elif _type in (cs.arm.ARM_SFT_RRX, cs.arm.ARM_SFT_RRX_REG):<EOL><INDENT>return RRX_C(value, carry, width)<EOL><DEDENT>raise NotImplementedError("<STR_LIT>")<EOL>

See Shift() and Shift_C() in the ARM manual


Occasionally used in glibc (longjmp in ld.so). Nop under our execution model.


@instruction<EOL><INDENT>def CBZ(cpu, op, dest):<DEDENT>

cpu.PC = Operators.ITEBV(cpu.address_bit_size,<EOL>op.read(), cpu.PC, dest.read())<EOL>

Compare and Branch on Zero compares the value in a register with zero, and conditionally branches forward
a constant value. It does not affect the condition flags.

:param ARMv7Operand op: Specifies the register that contains the first operand.
:param ARMv7Operand dest:
    Specifies the label of the instruction that is to be branched to. The assembler calculates the
    required value of the offset from the PC value of the CBZ instruction to this label, then
    selects an encoding that will set imm32 to that offset. Allowed offsets are even numbers in
    the range 0 to 126.


super().__init__({'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'})<EOL>self._regs = {}<EOL>for reg_name in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self._regs[reg_name] = Register(<NUM_LIT:32>)<EOL><DEDENT>for reg_name in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self._regs[reg_name] = Register(<NUM_LIT:64>)<EOL><DEDENT>self._regs['<STR_LIT>'] = Register(<NUM_LIT:1>)<EOL>self._regs['<STR_LIT>'] = Register(<NUM_LIT:1>)<EOL>self._regs['<STR_LIT>'] = Register(<NUM_LIT:1>)<EOL>self._regs['<STR_LIT>'] = Register(<NUM_LIT:1>)<EOL>self._regs['<STR_LIT>'] = Register(<NUM_LIT:4>)<EOL>self._regs['<STR_LIT>'] = Register(<NUM_LIT:32>)<EOL>

ARM Register file abstraction. GPRs use ints for read/write. APSR
flags allow writes of bool/{1, 0} but always read bools.


assert self.mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB)<EOL>if self.mode == cs.CS_MODE_ARM:<EOL><INDENT>self.mode = cs.CS_MODE_THUMB<EOL><DEDENT>else:<EOL><INDENT>self.mode = cs.CS_MODE_ARM<EOL><DEDENT>


@instruction<EOL><INDENT>def ADDW(cpu, dest, src, add):<DEDENT>

aligned_pc = (cpu.instruction.address + <NUM_LIT:4>) & <NUM_LIT><EOL>if src.type == '<STR_LIT>' and src.reg in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>src = aligned_pc<EOL><DEDENT>else:<EOL><INDENT>src = src.read()<EOL><DEDENT>dest.write(src + add.read())<EOL>

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.


val = GetNBits(src.read(), src_width)<EOL>word = Operators.ZEXTEND(val, cpu.address_bit_size)<EOL>dest.write(word)<EOL>

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


@instruction<EOL><INDENT>def STRD(cpu, src1, src2, dest, offset=None):<DEDENT>

assert src1.type == '<STR_LIT>'<EOL>assert src2.type == '<STR_LIT>'<EOL>assert dest.type == '<STR_LIT>'<EOL>val1 = src1.read()<EOL>val2 = src2.read()<EOL>writeback = cpu._compute_writeback(dest, offset)<EOL>cpu.write_int(dest.address(), val1, <NUM_LIT:32>)<EOL>cpu.write_int(dest.address() + <NUM_LIT:4>, val2, <NUM_LIT:32>)<EOL>cpu._cs_hack_ldr_str_writeback(dest, offset, writeback)<EOL>

Writes the contents of two registers to memory.


assert insn_id in (cs.arm.ARM_INS_ASR, cs.arm.ARM_INS_LSL, cs.arm.ARM_INS_LSR)<EOL>if insn_id == cs.arm.ARM_INS_ASR:<EOL><INDENT>if rest and rest[<NUM_LIT:0>].type == '<STR_LIT>':<EOL><INDENT>srtype = cs.arm.ARM_SFT_ASR<EOL><DEDENT>else:<EOL><INDENT>srtype = cs.arm.ARM_SFT_ASR_REG<EOL><DEDENT><DEDENT>elif insn_id == cs.arm.ARM_INS_LSL:<EOL><INDENT>if rest and rest[<NUM_LIT:0>].type == '<STR_LIT>':<EOL><INDENT>srtype = cs.arm.ARM_SFT_LSL<EOL><DEDENT>else:<EOL><INDENT>srtype = cs.arm.ARM_SFT_LSL_REG<EOL><DEDENT><DEDENT>elif insn_id == cs.arm.ARM_INS_LSR:<EOL><INDENT>if rest and rest[<NUM_LIT:0>].type == '<STR_LIT>':<EOL><INDENT>srtype = cs.arm.ARM_SFT_LSR<EOL><DEDENT>else:<EOL><INDENT>srtype = cs.arm.ARM_SFT_LSR_REG<EOL><DEDENT><DEDENT>carry = cpu.regfile.read('<STR_LIT>')<EOL>if rest and rest[<NUM_LIT:0>].type == '<STR_LIT>':<EOL><INDENT>result, carry = cpu._shift(op.read(), srtype, rest[<NUM_LIT:0>].op.reg, carry)<EOL><DEDENT>elif rest and rest[<NUM_LIT:0>].type == '<STR_LIT>':<EOL><INDENT>amount = rest[<NUM_LIT:0>].read()<EOL>result, carry = cpu._shift(op.read(), srtype, amount, carry)<EOL><DEDENT>elif cpu.mode == cs.CS_MODE_THUMB:<EOL><INDENT>result, carry = cpu._shift(dest.read(), srtype, op, carry)<EOL><DEDENT>else:<EOL><INDENT>result, carry = op.read(with_carry=True)<EOL><DEDENT>dest.write(result)<EOL>cpu.set_flags(N=HighBit(result), Z=(result == <NUM_LIT:0>), C=carry)<EOL>

Notes on Capstone behavior:
- In ARM mode, _SR reg has `rest`, but _SR imm does not, its baked into `op`.
- In ARM mode, `lsr r1, r2` will have a `rest[0]`
- In Thumb mode, `lsr r1, r2` will have an empty `rest`
- In ARM mode, something like `lsr r1, 3` will not have `rest` and op will be
    the immediate.


V = Operators.EXTRACT(apsr, <NUM_LIT>, <NUM_LIT:1>)<EOL>C = Operators.EXTRACT(apsr, <NUM_LIT>, <NUM_LIT:1>)<EOL>Z = Operators.EXTRACT(apsr, <NUM_LIT:30>, <NUM_LIT:1>)<EOL>N = Operators.EXTRACT(apsr, <NUM_LIT>, <NUM_LIT:1>)<EOL>self.write('<STR_LIT>', V)<EOL>self.write('<STR_LIT>', C)<EOL>self.write('<STR_LIT>', Z)<EOL>self.write('<STR_LIT>', N)<EOL>

Auxiliary function - Writes flags from a full APSR (only 4 msb used)


@instruction<EOL><INDENT>def STREX(cpu, status, *args):<DEDENT>

<EOL>status.write(<NUM_LIT:0>)<EOL>return cpu._STR(cpu.address_bit_size, *args)<EOL>

STREX performs a conditional store to memory.
:param Armv7Operand status: the destination register for the returned status; register


@instruction<EOL><INDENT>def LDRD(cpu, dest1, dest2, src, offset=None):<DEDENT>

assert dest1.type == '<STR_LIT>'<EOL>assert dest2.type == '<STR_LIT>'<EOL>assert src.type == '<STR_LIT>'<EOL>mem1 = cpu.read_int(src.address(), <NUM_LIT:32>)<EOL>mem2 = cpu.read_int(src.address() + <NUM_LIT:4>, <NUM_LIT:32>)<EOL>writeback = cpu._compute_writeback(src, offset)<EOL>dest1.write(mem1)<EOL>dest2.write(mem2)<EOL>cpu._cs_hack_ldr_str_writeback(src, offset, writeback)<EOL>


if cpu.instruction.usermode:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>increment = insn_id in (cs.arm.ARM_INS_STM, cs.arm.ARM_INS_STMIB)<EOL>after = insn_id in (cs.arm.ARM_INS_STM, cs.arm.ARM_INS_STMDA)<EOL>address = base.read()<EOL>for reg in regs:<EOL><INDENT>if not after:<EOL><INDENT>address += (<NUM_LIT:1> if increment else -<NUM_LIT:1>) * (reg.size // <NUM_LIT:8>)<EOL><DEDENT>cpu.write_int(address, reg.read(), reg.size)<EOL>if after:<EOL><INDENT>address += (<NUM_LIT:1> if increment else -<NUM_LIT:1>) * (reg.size // <NUM_LIT:8>)<EOL><DEDENT><DEDENT>if cpu.instruction.writeback:<EOL><INDENT>base.writeback(address)<EOL><DEDENT>

STM (Store Multiple) stores a non-empty subset (or possibly all) of the general-purpose registers to
sequential memory locations.

:param int insn_id: should be one of ARM_INS_STM, ARM_INS_STMIB, ARM_INS_STMDA, ARM_INS_STMDB
:param Armv7Operand base: Specifies the base register.
:param list[Armv7Operand] regs:
    Is a list of registers. It specifies the set of registers to be stored by the STM instruction.
    The registers are stored in sequence, the lowest-numbered register to the lowest
    memory address (start_address), through to the highest-numbered register to the
    highest memory address (end_address).


return self.__type<EOL>

Corresponds to capstone's `operand.type` (cs.arm.ARM_OP_*).


if not self.emu:<EOL><INDENT>self.emu = ConcreteUnicornEmulator(self)<EOL>self.emu._stop_at = self._break_unicorn_at<EOL><DEDENT>try:<EOL><INDENT>self.emu.emulate(insn)<EOL><DEDENT>except unicorn.UcError as e:<EOL><INDENT>if e.errno == unicorn.UC_ERR_INSN_INVALID:<EOL><INDENT>text_bytes = '<STR_LIT:U+0020>'.join('<STR_LIT>' % x for x in insn.bytes)<EOL>logger.error("<STR_LIT>",<EOL>insn.address, text_bytes, insn.mnemonic, insn.op_str)<EOL><DEDENT>raise InstructionEmulationError(str(e))<EOL><DEDENT>

Start executing in Unicorn from this point until we hit a syscall or reach break_unicorn_at

:param capstone.CsInsn insn: The instruction object to emulate


def push_bytes(self, data, force=False):

self.STACK -= len(data)<EOL>self.write_bytes(self.STACK, data, force)<EOL>return self.STACK<EOL>

Write `data` to the stack and decrement the stack pointer accordingly.

:param str data: Data to write
:param force: whether to ignore memory permissions


raise NotImplemented<EOL>

Get the semantic name of an instruction.


if issymbolic(self.PC):<EOL><INDENT>raise ConcretizeRegister(self, '<STR_LIT>', policy='<STR_LIT>')<EOL><DEDENT>if not self.memory.access_ok(self.PC, '<STR_LIT:x>'):<EOL><INDENT>raise InvalidMemoryAccess(self.PC, '<STR_LIT:x>')<EOL><DEDENT>self._publish('<STR_LIT>', self.PC)<EOL>insn = self.decode_instruction(self.PC)<EOL>self._last_pc = self.PC<EOL>self._publish('<STR_LIT>', self.PC, insn)<EOL>if insn.address != self.PC:<EOL><INDENT>return<EOL><DEDENT>name = self.canonicalize_instruction_name(insn)<EOL>if logger.level == logging.DEBUG:<EOL><INDENT>logger.debug(self.render_instruction(insn))<EOL>for l in self.render_registers():<EOL><INDENT>register_logger.debug(l)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if self._concrete and '<STR_LIT>' in name:<EOL><INDENT>self.emu.sync_unicorn_to_manticore()<EOL><DEDENT>if self._concrete and '<STR_LIT>' not in name:<EOL><INDENT>self.emulate(insn)<EOL>if self.PC == self._break_unicorn_at:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self._break_unicorn_at = None<EOL>self._concrete = False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>implementation = getattr(self, name, None)<EOL>if implementation is not None:<EOL><INDENT>implementation(*insn.operands)<EOL><DEDENT>else:<EOL><INDENT>text_bytes = '<STR_LIT:U+0020>'.join('<STR_LIT>' % x for x in insn.bytes)<EOL>logger.warning("<STR_LIT>",<EOL>insn.address, text_bytes, insn.mnemonic, insn.op_str)<EOL>self.backup_emulate(insn)<EOL><DEDENT><DEDENT><DEDENT>except (Interruption, Syscall) as e:<EOL><INDENT>e.on_handled = lambda: self._publish_instruction_as_executed(insn)<EOL>raise e<EOL><DEDENT>else:<EOL><INDENT>self._publish_instruction_as_executed(insn)<EOL><DEDENT>

Decode, and execute one instruction pointed by register PC


def _raw_read(self, where: int, size=<NUM_LIT:1>) -> bytes:

map = self.memory.map_containing(where)<EOL>start = map._get_offset(where)<EOL>mapType = type(map)<EOL>if mapType is FileMap:<EOL><INDENT>end = map._get_offset(where + size)<EOL>if end > map._mapped_size:<EOL><INDENT>logger.warning(f"<STR_LIT>")<EOL><DEDENT>raw_data = map._data[map._get_offset(where): min(end, map._mapped_size)]<EOL>if len(raw_data) < end:<EOL><INDENT>raw_data += b'<STR_LIT:\x00>' * (end - len(raw_data))<EOL><DEDENT>data = b'<STR_LIT>'<EOL>for offset in sorted(map._overlay.keys()):<EOL><INDENT>data += raw_data[len(data):offset]<EOL>data += map._overlay[offset]<EOL><DEDENT>data += raw_data[len(data):]<EOL><DEDENT>elif mapType is AnonMap:<EOL><INDENT>data = bytes(map._data[start:start + size])<EOL><DEDENT>else:<EOL><INDENT>data = b'<STR_LIT>'.join(self.memory[where:where + size])<EOL><DEDENT>assert len(data) == size, '<STR_LIT>'<EOL>return data<EOL>

Selects bytes from memory. Attempts to do so faster than via read_bytes.

:param where: address to read from
:param size: number of bytes to read
:return: the bytes in memory


self.STACK -= self.address_bit_size // <NUM_LIT:8><EOL>self.write_int(self.STACK, value, force=force)<EOL>return self.STACK<EOL>

Decrement the stack pointer and write `value` to the stack.

:param int value: The value to write
:param force: whether to ignore memory permissions
:return: New stack pointer


raise NotImplementedError<EOL>

Extract the index of the invoked syscall.

:return: int


def write_int(self, where, expression, size=None, force=False):

if size is None:<EOL><INDENT>size = self.address_bit_size<EOL><DEDENT>assert size in SANE_SIZES<EOL>self._publish('<STR_LIT>', where, expression, size)<EOL>data = [Operators.CHR(Operators.EXTRACT(expression, offset, <NUM_LIT:8>)) for offset in range(<NUM_LIT:0>, size, <NUM_LIT:8>)]<EOL>self._memory.write(where, data, force)<EOL>self._publish('<STR_LIT>', where, expression, size)<EOL>

Writes int to memory

:param int where: address to write to
:param expr: value to write
:type expr: int or BitVec
:param size: bit size of `expr`
:param force: whether to ignore memory permissions


raise NotImplementedError<EOL>

Private method to decorate an Operand to our needs based on the
underlying architecture.
See :class:`~manticore.core.cpu.abstractcpu.Operand` class


return self._regfile.all_registers<EOL>

Returns all register names for this CPU. Any register returned can be
accessed via a `cpu.REG` convenience interface (e.g. `cpu.EAX`) for both
reading and writing.

:return: valid register names
:rtype: tuple[str]


raise NotImplementedError<EOL>

Extract model arguments conforming to `convention`. Produces an iterable
of argument descriptors following the calling convention. A descriptor
is either a string describing a register, or an address (concrete or
symbolic).

:return: iterable returning syscall arguments.
:rtype: iterable


self._icount += <NUM_LIT:1><EOL>self._publish('<STR_LIT>', self._last_pc, self.PC, insn)<EOL>

Notify listeners that an instruction has been executed.


raise NotImplementedError<EOL>

Write the result of a model back to the environment.

:param result: result of the model implementation


assert isinstance(cpu, Cpu)<EOL>self.cpu = cpu<EOL>self.op = op<EOL>self.mem = Operand.MemSpec(self)<EOL>

This encapsulates the arch-independent way to access instruction
operands and immediates based on the disassembler operand descriptor in
use. This class knows how to browse an operand and get its details.

It also knows how to access the specific Cpu to get the actual values
from memory and registers.

:param Cpu cpu: A Cpu instance
:param Operand op: An wrapped Instruction Operand
:type op: X86Op or ArmOp


word_bytes = self._cpu.address_bit_size // <NUM_LIT:8><EOL>while True:<EOL><INDENT>yield base<EOL>base += word_bytes<EOL><DEDENT>

A reusable generator for increasing pointer-sized values from an address
(usually the stack).


return self._aliases.get(register, register)<EOL>

Get register canonical alias. ex. PC->RIP or PC->R15

:param str register: The register name


def read_int(self, where, size=None, force=False):

if size is None:<EOL><INDENT>size = self.address_bit_size<EOL><DEDENT>assert size in SANE_SIZES<EOL>self._publish('<STR_LIT>', where, size)<EOL>data = self._memory.read(where, size // <NUM_LIT:8>, force)<EOL>assert (<NUM_LIT:8> * len(data)) == size<EOL>value = Operators.CONCAT(size, *map(Operators.ORD, reversed(data)))<EOL>self._publish('<STR_LIT>', where, value, size)<EOL>return value<EOL>

Reads int from memory

:param int where: address to read from
:param size: number of bits to read
:return: the value read
:rtype: int or BitVec
:param force: whether to ignore memory permissions


def write_register(self, register, value):

self._publish('<STR_LIT>', register, value)<EOL>value = self._regfile.write(register, value)<EOL>self._publish('<STR_LIT>', register, value)<EOL>return value<EOL>

Dynamic interface for writing cpu registers

:param str register: register name (as listed in `self.all_registers`)
:param value: register value
:type value: int or long or Expression


raise NotImplementedError<EOL>

List the minimal most beautiful set of registers needed


value = self.read_int(self.STACK, force=force)<EOL>self.STACK += self.address_bit_size // <NUM_LIT:8><EOL>return value<EOL>

Read a value from the stack and increment the stack pointer.

:param force: whether to ignore memory permissions
:return: Value read


def pop_bytes(self, nbytes, force=False):

data = self.read_bytes(self.STACK, nbytes, force=force)<EOL>self.STACK += nbytes<EOL>return data<EOL>

Read `nbytes` from the stack, increment the stack pointer, and return
data.

:param int nbytes: How many bytes to read
:param force: whether to ignore memory permissions
:return: Data read from the stack


@abstractmethod<EOL><INDENT>def disassemble_instruction(self, code, pc):<DEDENT>

Get next instruction based on the disassembler in use

        :param str code: binary blob to be disassembled
        :param long pc: program counter


self._platform.invoke_model(model, prefix_args=(self,))<EOL>

Invokes a `model`. Modelling can be used to override a function in the target program with a custom
implementation.

For more information on modelling see docs/models.rst

A `model` is a callable whose first argument is a `manticore.native.State` instance.
If the following arguments correspond to the arguments of the C function
being modeled. If the `model` models a variadic function, the following argument
is a generator object, which can be used to access function arguments dynamically.
The `model` callable should simply return the value that should be returned by the
native function being modeled.f

:param model: callable, model to invoke


return getattr(model, VARIADIC_FUNC_ATTR, False)<EOL>

:param callable model: Function model
:return: Whether `model` models a variadic function
:rtype: bool


cpu = state.cpu<EOL>if issymbolic(s):<EOL><INDENT>raise ConcretizeArgument(state.cpu, <NUM_LIT:1>)<EOL><DEDENT>zero_idx = _find_zero(cpu, state.constraints, s)<EOL>ret = zero_idx<EOL>for offset in range(zero_idx - <NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>byt = cpu.read_int(s + offset, <NUM_LIT:8>)<EOL>if issymbolic(byt):<EOL><INDENT>ret = ITEBV(cpu.address_bit_size, byt == <NUM_LIT:0>, offset, ret)<EOL><DEDENT><DEDENT>return ret<EOL>

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


log.set_verbosity(level)<EOL>logger.info(f'<STR_LIT>')<EOL>

Convenience interface for setting logging verbosity to one of
        several predefined logging presets. Valid values: 0-5.


Gracefully terminate the currently-executing run. Typically called from within
a :func:`~hook`.


return self._executor.is_shutdown()<EOL>


def migrate(self, expression, name_migration_map=None):

if name_migration_map is None:<EOL><INDENT>name_migration_map = {}<EOL><DEDENT>object_migration_map = {}<EOL>foreign_vars = itertools.filterfalse(self.is_declared, get_variables(expression))<EOL>for foreign_var in foreign_vars:<EOL><INDENT>if foreign_var.name in name_migration_map:<EOL><INDENT>migrated_name = name_migration_map[foreign_var.name]<EOL>native_var = self.get_variable(migrated_name)<EOL>assert native_var is not None, "<STR_LIT>"<EOL>object_migration_map[foreign_var] = native_var<EOL><DEDENT>else:<EOL><INDENT>migrated_name = foreign_var.name<EOL>if migrated_name in self._declarations:<EOL><INDENT>migrated_name = self._make_unique_name(f'<STR_LIT>')<EOL><DEDENT>if isinstance(foreign_var, Bool):<EOL><INDENT>new_var = self.new_bool(name=migrated_name)<EOL><DEDENT>elif isinstance(foreign_var, BitVec):<EOL><INDENT>new_var = self.new_bitvec(foreign_var.size, name=migrated_name)<EOL><DEDENT>elif isinstance(foreign_var, Array):<EOL><INDENT>new_var = self.new_array(index_max=foreign_var.index_max, index_bits=foreign_var.index_bits, value_bits=foreign_var.value_bits, name=migrated_name).array<EOL><DEDENT>else:<EOL><INDENT>raise NotImplemented(f"<STR_LIT>")<EOL><DEDENT>object_migration_map[foreign_var] = new_var<EOL>name_migration_map[foreign_var.name] = new_var.name<EOL><DEDENT><DEDENT>migrated_expression = replace(expression, object_migration_map)<EOL>return migrated_expression<EOL>

Migrate an expression created for a different constraint set to self.
            Returns an expression that can be used with this constraintSet

            All the foreign variables used in the expression are replaced by
            variables of this constraint set. If the variable was replaced before
            the replacement is taken from the provided migration map.

            The migration mapping is updated with new replacements.

            :param expression: the potentially foreign expression
            :param name_migration_map: mapping of already migrated variables. maps from string name of foreign variable to its currently existing migrated string name. this is updated during this migration.
            :return: a migrated expression where all the variables are local. name_migration_map is updated


return self._declarations.values()<EOL>

Returns the variable expressions of this constraint set


if not isinstance(expression_var, Variable):<EOL><INDENT>raise ValueError(f'<STR_LIT>')<EOL><DEDENT>return any(expression_var is x for x in self.get_declared_variables())<EOL>

True if expression_var is declared in this constraint set


return self.to_string()<EOL>

Returns a smtlib representation of the current state


def new_array(self, index_bits=<NUM_LIT:32>, name=None, index_max=None, value_bits=<NUM_LIT:8>, taint=frozenset(), avoid_collisions=False, default=None):

if name is None:<EOL><INDENT>name = '<STR_LIT:A>'<EOL>avoid_collisions = True<EOL><DEDENT>if avoid_collisions:<EOL><INDENT>name = self._make_unique_name(name)<EOL><DEDENT>if not avoid_collisions and name in self._declarations:<EOL><INDENT>raise ValueError(f'<STR_LIT>')<EOL><DEDENT>var = self._declare(ArrayVariable(index_bits, index_max, value_bits, name, taint=taint))<EOL>return ArrayProxy(var, default=default)<EOL>

Declares a free symbolic array of value_bits long bitvectors in the constraint store.
            :param index_bits: size in bits for the array indexes one of [32, 64]
            :param value_bits: size in bits for the array values
            :param name: try to assign name to internal variable representation,
                         if not unique, a numeric nonce will be appended
            :param index_max: upper limit for indexes on this array (#FIXME)
            :param avoid_collisions: potentially avoid_collisions the variable to avoid name collisions if True
            :param default: default for not initialized values
            :return: a fresh ArrayProxy


return self._declarations.get(name)<EOL>

Returns the variable declared under name or None if it does not exists


def min(self, constraints, X: BitVec, M=<NUM_LIT>):

assert isinstance(X, BitVec)<EOL>return self.optimize(constraints, X, '<STR_LIT>', M)<EOL>

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


super().__init__()<EOL>self._proc: Popen = None<EOL>self._command = f'<STR_LIT>'<EOL>self._init = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>]<EOL>self._get_value_fmt = (RE_GET_EXPR_VALUE_FMT, <NUM_LIT:16>)<EOL>self.debug = False<EOL>self._received_version = None<EOL>self.version = self._solver_version()<EOL>self.support_maximize = False<EOL>self.support_minimize = False<EOL>self.support_reset = True<EOL>logger.debug('<STR_LIT>', self.version)<EOL>if self.version >= Version(<NUM_LIT:4>, <NUM_LIT:5>, <NUM_LIT:0>):<EOL><INDENT>self.support_maximize = False<EOL>self.support_minimize = False<EOL>self.support_reset = False<EOL><DEDENT>elif self.version >= Version(<NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:1>):<EOL><INDENT>self.support_maximize = True<EOL>self.support_minimize = True<EOL>self.support_reset = False<EOL><DEDENT>else:<EOL><INDENT>logger.debug('<STR_LIT>')<EOL><DEDENT>

Build a Z3 solver instance.
This is implemented using an external z3 solver (via a subprocess).
See https://github.com/Z3Prover/z3


Pushes and save the current constraint store and state.


assert '<STR_LIT>' not in dir(self) or self._proc is None<EOL>try:<EOL><INDENT>self._proc = Popen(shlex.split(self._command), stdin=PIPE, stdout=PIPE, bufsize=<NUM_LIT:0>, universal_newlines=True)<EOL><DEDENT>except OSError as e:<EOL><INDENT>print(e, "<STR_LIT>")<EOL>raise Z3NotFoundError  <EOL><DEDENT>for cfg in self._init:<EOL><INDENT>self._send(cfg)<EOL><DEDENT>


def optimize(self, constraints, X, operation, M=<NUM_LIT>):

raise Exception("<STR_LIT>")<EOL>

Iteratively finds the maximum or minimal value for the operation
(Normally Operators.UGT or Operators.ULT)

:param constraints: the constraints set
:param X: a symbol or expression
:param M: maximum number of iterations allowed


def get_all_values(self, constraints, x, maxcnt=<NUM_LIT>, silent=False):

raise Exception("<STR_LIT>")<EOL>

Returns a list with all the possible values for the symbol x


if not issymbolic(expression):<EOL><INDENT>return expression<EOL><DEDENT>assert isinstance(expression, Variable)<EOL>if isinstance(expression, Array):<EOL><INDENT>result = bytearray()<EOL>for c in expression:<EOL><INDENT>expression_str = translate_to_smtlib(c)<EOL>self._send('<STR_LIT>' % expression_str)<EOL>response = self._recv()<EOL>result.append(int('<STR_LIT>'.format(response.split(expression_str)[<NUM_LIT:1>][<NUM_LIT:3>:-<NUM_LIT:2>]), <NUM_LIT:16>))<EOL><DEDENT>return bytes(result)<EOL><DEDENT>else:<EOL><INDENT>self._send('<STR_LIT>' % expression.name)<EOL>ret = self._recv()<EOL>assert ret.startswith('<STR_LIT>') and ret.endswith('<STR_LIT>'), ret<EOL>if isinstance(expression, Bool):<EOL><INDENT>return {'<STR_LIT:true>': True, '<STR_LIT:false>': False}[ret[<NUM_LIT:2>:-<NUM_LIT:2>].split('<STR_LIT:U+0020>')[<NUM_LIT:1>]]<EOL><DEDENT>elif isinstance(expression, BitVec):<EOL><INDENT>pattern, base = self._get_value_fmt<EOL>m = pattern.match(ret)<EOL>expr, value = m.group('<STR_LIT>'), m.group('<STR_LIT:value>')<EOL>return int(value, base)<EOL><DEDENT><DEDENT>raise NotImplementedError("<STR_LIT>")<EOL>

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!).


Recall the last pushed constraint store and state.


logger.debug('<STR_LIT>', cmd)<EOL>try:<EOL><INDENT>self._proc.stdout.flush()<EOL>self._proc.stdin.write(f'<STR_LIT>')<EOL><DEDENT>except IOError as e:<EOL><INDENT>raise SolverError(str(e))<EOL><DEDENT>

Send a string to the solver.

:param cmd: a SMTLIBv2 command (ex. (check-sat))


if self._proc is None:<EOL><INDENT>self._start_proc()<EOL><DEDENT>else:<EOL><INDENT>if self.support_reset:<EOL><INDENT>self._send("<STR_LIT>")<EOL>for cfg in self._init:<EOL><INDENT>self._send(cfg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._stop_proc()<EOL>self._start_proc()<EOL><DEDENT><DEDENT>if constraints is not None:<EOL><INDENT>self._send(constraints)<EOL><DEDENT>

Auxiliary method to reset the smtlib external solver to initial defaults


if self._proc is None:<EOL><INDENT>return<EOL><DEDENT>if self._proc.returncode is None:<EOL><INDENT>try:<EOL><INDENT>self._send("<STR_LIT>")<EOL><DEDENT>except (SolverError, IOError) as e:<EOL><INDENT>logger.debug(str(e))<EOL><DEDENT>finally:<EOL><INDENT>try:<EOL><INDENT>self._proc.stdin.close()<EOL><DEDENT>except IOError as e:<EOL><INDENT>logger.debug(str(e))<EOL><DEDENT>try:<EOL><INDENT>self._proc.stdout.close()<EOL><DEDENT>except IOError as e:<EOL><INDENT>logger.debug(str(e))<EOL><DEDENT>self._proc.kill()<EOL>self._proc.wait()<EOL><DEDENT><DEDENT>self._proc: Popen = None<EOL>

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)


self._reset()<EOL>if self._received_version is None:<EOL><INDENT>self._send('<STR_LIT>')<EOL>self._received_version = self._recv()<EOL><DEDENT>key, version = shlex.split(self._received_version[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL>return Version(*map(int, version.split('<STR_LIT:.>')))<EOL>

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'


def can_be_true(self, constraints, expression) -> bool:

raise Exception("<STR_LIT>")<EOL>

Check if given expression could be valid


def visit_ArraySelect(self, expression, *operands):

arr, index = operands<EOL>if isinstance(arr, ArrayVariable):<EOL><INDENT>return<EOL><DEDENT>if isinstance(index, BitVecConstant):<EOL><INDENT>ival = index.value<EOL>while isinstance(arr, ArrayStore) and isinstance(arr._operands[<NUM_LIT:1>], BitVecConstant) and arr._operands[<NUM_LIT:1>]._value != ival:<EOL><INDENT>arr = arr._operands[<NUM_LIT:0>]  <EOL><DEDENT><DEDENT>if isinstance(index, BitVecConstant) and isinstance(arr, ArrayStore) and isinstance(arr.index, BitVecConstant) and arr.index.value == index.value:<EOL><INDENT>return arr.value<EOL><DEDENT>else:<EOL><INDENT>if arr is not expression.array:<EOL><INDENT>return arr.select(index)<EOL><DEDENT><DEDENT>

ArraySelect (ArrayStore((ArrayStore(x0,v0) ...),xn, vn), x0)
                -> v0


def visit_BitVecOr(self, expression, *operands):

left = expression.operands[<NUM_LIT:0>]<EOL>right = expression.operands[<NUM_LIT:1>]<EOL>if isinstance(right, BitVecConstant):<EOL><INDENT>if right.value == <NUM_LIT:0>:<EOL><INDENT>return left<EOL><DEDENT>elif right.value == left.mask:<EOL><INDENT>return right<EOL><DEDENT>elif isinstance(left, BitVecOr):<EOL><INDENT>left_left = left.operands[<NUM_LIT:0>]<EOL>left_right = left.operands[<NUM_LIT:1>]<EOL>if isinstance(right, Constant):<EOL><INDENT>return BitVecOr(left_left, (left_right | right), taint=expression.taint)<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(left, BitVecConstant):<EOL><INDENT>return BitVecOr(right, left, taint=expression.taint)<EOL><DEDENT>

a | 0 => a
            0 | a => a
            0xffffffff & a => 0xffffffff
            a & 0xffffffff => 0xffffffff


assert expression.__class__.__mro__[-<NUM_LIT:1>] is object<EOL>for cls in expression.__class__.__mro__:<EOL><INDENT>sort = cls.__name__<EOL>methodname = '<STR_LIT>' % sort<EOL>method = getattr(self, methodname, None)<EOL>if method is not None:<EOL><INDENT>method(expression, *args)<EOL>return<EOL><DEDENT><DEDENT>return<EOL>

Overload Visitor._method because we want to stop to iterate over the
visit_ functions as soon as a valid visit_ function is found


def visit_BitVecShiftLeft(self, expression, *operands):

left = expression.operands[<NUM_LIT:0>]<EOL>right = expression.operands[<NUM_LIT:1>]<EOL>if isinstance(right, BitVecConstant):<EOL><INDENT>if right.value == <NUM_LIT:0>:<EOL><INDENT>return left<EOL><DEDENT>elif right.value >= right.size:<EOL><INDENT>return left<EOL><DEDENT><DEDENT>

a << 0 => a                       remove zero
            a << ct => 0 if ct > sizeof(a)    remove big constant shift


def visit_BitVecAnd(self, expression, *operands):

left = expression.operands[<NUM_LIT:0>]<EOL>right = expression.operands[<NUM_LIT:1>]<EOL>if isinstance(right, BitVecConstant):<EOL><INDENT>if right.value == <NUM_LIT:0>:<EOL><INDENT>return right<EOL><DEDENT>elif right.value == right.mask:<EOL><INDENT>return left<EOL><DEDENT>elif isinstance(left, BitVecAnd):<EOL><INDENT>left_left = left.operands[<NUM_LIT:0>]<EOL>left_right = left.operands[<NUM_LIT:1>]<EOL>if isinstance(right, Constant):<EOL><INDENT>return BitVecAnd(left_left, left_right & right, taint=expression.taint)<EOL><DEDENT><DEDENT>elif isinstance(left, BitVecOr):<EOL><INDENT>left_left = left.operands[<NUM_LIT:0>]<EOL>left_right = left.operands[<NUM_LIT:1>]<EOL>return BitVecOr(right & left_left, right & left_right, taint=expression.taint)<EOL><DEDENT><DEDENT>elif isinstance(left, BitVecConstant):<EOL><INDENT>return BitVecAnd(right, left, taint=expression.taint)<EOL><DEDENT>

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 |


@contextmanager<EOL><INDENT>def save_stream(self, key, binary=False):<DEDENT>

mode = '<STR_LIT:wb>' if binary else '<STR_LIT:w>'<EOL>with open(os.path.join(self.uri, key), mode) as f:<EOL><INDENT>yield f<EOL><DEDENT>

Yield a file object representing `key`

:param str key: The file to save to
:param bool binary: Whether we should treat it as binary
:return:


self._named_key_prefix = '<STR_LIT:test>'<EOL>self._descriptor = desc<EOL>self._store = Store.fromdescriptor(desc)<EOL>self._last_id = <NUM_LIT:0><EOL>self._id_gen = manager().Value('<STR_LIT:i>', self._last_id)<EOL>self._lock = manager().Condition(manager().RLock())<EOL>

Create an object capable of producing Manticore output.

:param desc: A descriptor ('type:uri') of where to write output.


return self._client.set(key, value)<EOL>

Save an arbitrary, serializable `value` under `key`.

:param str key: A string identifier under which to store the value.
:param value: A serializable value
:return:


path = os.path.join(self.uri, key)<EOL>os.remove(path)<EOL>

Remove file identified by `key`.

:param str key: The file to delete


return self._client.get(key)<EOL>

Load an arbitrary value identified by `key`.

:param str key: The key that identifies the value
:return: The loaded value


def new_function(self, *args, **kw):<EOL><INDENT>self._lock.acquire()<EOL>try:<EOL><INDENT>return f(self, *args, **kw)<EOL><DEDENT>finally:<EOL><INDENT>self._lock.release()<EOL><DEDENT><DEDENT>return new_function<EOL>


@contextmanager<EOL><INDENT>def _named_stream(self, name, binary=False):<DEDENT>

with self._store.save_stream(self._named_key(name), binary=binary) as s:<EOL><INDENT>yield s<EOL><DEDENT>

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.save_stream(key) as s:<EOL><INDENT>s.write(value)<EOL><DEDENT>


<EOL>import redis<EOL>hostname, port = uri.split('<STR_LIT::>')<EOL>self._client = redis.StrictRedis(host=hostname, port=int(port), db=<NUM_LIT:0>)<EOL>super().__init__(uri)<EOL>


@contextmanager<EOL><INDENT>def load_stream(self, key, binary=False):<DEDENT>

value = self.load_value(key, binary=binary)<EOL>yield io.BytesIO(value) if binary else io.StringIO(value)<EOL>

Return a managed file-like object from which the calling code can read
previously-serialized data.

:param key:
:return: A managed stream-like object


constraint = self.migrate_expression(constraint)<EOL>self._constraints.add(constraint)<EOL>

Constrain state.

        :param manticore.core.smtlib.Bool constraint: Constraint to add


if isinstance(expr, int):<EOL><INDENT>return expr<EOL><DEDENT>expr = self.migrate_expression(expr)<EOL>return self._solver.minmax(self._constraints, expr)<EOL>

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]


def solve_one(self, expr, constrain=False):

expr = self.migrate_expression(expr)<EOL>value = self._solver.get_value(self._constraints, expr)<EOL>if constrain:<EOL><INDENT>self.constrain(expr == value)<EOL><DEDENT>if isinstance(value, bytearray):<EOL><INDENT>value = bytes(value)<EOL><DEDENT>return value<EOL>

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


def symbolicate_buffer(self, data, label='<STR_LIT>', wildcard='<STR_LIT:+>', string=False, taint=frozenset()):

if wildcard in data:<EOL><INDENT>size = len(data)<EOL>symb = self._constraints.new_array(name=label, index_max=size, taint=taint, avoid_collisions=True)<EOL>self._input_symbols.append(symb)<EOL>tmp = []<EOL>for i in range(size):<EOL><INDENT>if data[i] == wildcard:<EOL><INDENT>tmp.append(symb[i])<EOL><DEDENT>else:<EOL><INDENT>tmp.append(data[i])<EOL><DEDENT><DEDENT>data = tmp<EOL><DEDENT>if string:<EOL><INDENT>for b in data:<EOL><INDENT>if issymbolic(b):<EOL><INDENT>self._constraints.add(b != <NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>assert b != <NUM_LIT:0><EOL><DEDENT><DEDENT><DEDENT>return data<EOL>

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.


expr = self.migrate_expression(expr)<EOL>return self._solver.get_all_values(self._constraints, expr, nsolves, silent=True)<EOL>

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]


Called once at the beginning of the run.
            state is the initial root state


pass<EOL>

Called by parent manticore on registration


super().__init__()<EOL>self.last_dict = {}<EOL>self.current_pc = None<EOL>self.context_key = '<STR_LIT>'<EOL>


d = {}<EOL>for key in set(d1).intersection(set(d2)):<EOL><INDENT>if d2[key] != d1[key]:<EOL><INDENT>d[key] = d2[key]<EOL><DEDENT><DEDENT>for key in set(d2).difference(set(d1)):<EOL><INDENT>d[key] = d2[key]<EOL><DEDENT>return d<EOL>

Produce a dict that includes all the keys in d2 that represent different values in d1, as well as values that
aren't in d1.

:param dict d1: First dict
:param dict d2: Dict to compare with
:rtype: dict


raise NotImplementedError<EOL>

Select a state id from state_ids.
            self.context has a dict mapping state_ids -> summarize(state)


<EOL>current_state = None<EOL>current_state_id = None<EOL>with WithKeyboardInterruptAs(self.shutdown):<EOL><INDENT>self._notify_start_run()<EOL>logger.debug("<STR_LIT>", os.getpid())<EOL>solver = Z3Solver()<EOL>while not self.is_shutdown():<EOL><INDENT>try:  <EOL><INDENT>try:  <EOL><INDENT>if current_state is None:<EOL><INDENT>with self._lock:<EOL><INDENT>self._notify_stop_run()<EOL>try:<EOL><INDENT>current_state_id = self.get()<EOL>if current_state_id is not None:<EOL><INDENT>self._publish('<STR_LIT>', current_state_id)<EOL>current_state = self._workspace.load_state(current_state_id)<EOL>self.forward_events_from(current_state, True)<EOL>self._publish('<STR_LIT>', current_state, current_state_id)<EOL>logger.info("<STR_LIT>", current_state_id)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self._notify_start_run()<EOL><DEDENT><DEDENT><DEDENT>if current_state is None:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>break<EOL><DEDENT>assert current_state is not None<EOL>assert current_state.constraints is current_state.platform.constraints<EOL>while not self.is_shutdown():<EOL><INDENT>if not current_state.execute():<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._publish('<STR_LIT>', current_state, current_state_id, TerminateState('<STR_LIT>'))<EOL>current_state = None<EOL><DEDENT><DEDENT>except Concretize as e:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>current_state = self.fork(current_state, e.expression, e.policy, e.setstate)<EOL><DEDENT>except TerminateState as e:<EOL><INDENT>self._publish('<STR_LIT>', current_state, current_state_id, e)<EOL>logger.debug("<STR_LIT>")<EOL>if e.testcase:<EOL><INDENT>self._publish('<STR_LIT>', current_state, message=str(e))<EOL><DEDENT>current_state = None<EOL><DEDENT>except SolverError as e:<EOL><INDENT>import traceback<EOL>trace = traceback.format_exc()<EOL>logger.error("<STR_LIT>", str(e), trace)<EOL>self._publish('<STR_LIT>', current_state, current_state_id, e)<EOL>if solver.check(current_state.constraints):<EOL><INDENT>self._publish('<STR_LIT>', current_state, message="<STR_LIT>" + str(e))<EOL><DEDENT>current_state = None<EOL><DEDENT><DEDENT>except (Exception, AssertionError) as e:<EOL><INDENT>import traceback<EOL>trace = traceback.format_exc()<EOL>logger.error("<STR_LIT>", str(e), trace)<EOL>self._publish('<STR_LIT>', current_state, current_state_id, e)<EOL>current_state = None<EOL><DEDENT><DEDENT>assert current_state is None or self.is_shutdown()<EOL>self._notify_stop_run()<EOL><DEDENT>

Entry point of the Executor; called by workers to start analysis.


return list(self._states)<EOL>

Returns the list of states ids currently queued


<EOL>state_id = self._workspace.save_state(state)<EOL>self.put(state_id)<EOL>self._publish('<STR_LIT>', state_id, state)<EOL>return state_id<EOL>

Enqueue state.
Save state on storage, assigns an id to it, then add it to the
priority queue


self._states.append(state_id)<EOL>self._lock.notify_all()<EOL>return state_id<EOL>


return self._shutdown.is_set()<EOL>


return self._running.value<EOL>

Report an estimate  of how many workers are currently running


<EOL>if self.is_shutdown():<EOL><INDENT>return None<EOL><DEDENT>while len(self._states) == <NUM_LIT:0>:<EOL><INDENT>if self.running == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>if self.is_shutdown():<EOL><INDENT>return None<EOL><DEDENT>logger.debug("<STR_LIT>")<EOL>self._lock.wait()<EOL><DEDENT>state_id = self._policy.choice(list(self._states))<EOL>if state_id is None:<EOL><INDENT>return None<EOL><DEDENT>del self._states[self._states.index(state_id)]<EOL>return state_id<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>]<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] & p[<NUM_LIT:3>]<EOL>


size = sizes[p[<NUM_LIT:1>]]<EOL>address = p[<NUM_LIT:6>]<EOL>seg = functions['<STR_LIT>'](p[<NUM_LIT:3>])<EOL>base, limit, _ = functions['<STR_LIT>'](seg)<EOL>address = base + address<EOL>char_list = functions['<STR_LIT>'](address, size)<EOL>value = Operators.CONCAT(<NUM_LIT:8> * len(char_list), *reversed(map(Operators.ORD, char_list)))<EOL>p[<NUM_LIT:0>] = value<EOL>

expression : TYPE PTR SEGMENT COLOM LBRAKET expression RBRAKET


size = sizes[p[<NUM_LIT:1>]]<EOL>address = p[<NUM_LIT:4>]<EOL>char_list = functions['<STR_LIT>'](address, size)<EOL>value = Operators.CONCAT(<NUM_LIT:8> * len(char_list), *reversed(map(Operators.ORD, char_list)))<EOL>p[<NUM_LIT:0>] = value<EOL>

expression : TYPE PTR LBRAKET expression RBRAKET


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] == p[<NUM_LIT:3>]<EOL>


<EOL>p[<NUM_LIT:0>] = Operators.UGT(p[<NUM_LIT:1>], p[<NUM_LIT:3>])<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] | p[<NUM_LIT:3>]<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] * p[<NUM_LIT:3>]<EOL>

expression : expression TIMES expression


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] // p[<NUM_LIT:3>]<EOL>

expression : expression DIVIDE expression


p[<NUM_LIT:0>] = p[<NUM_LIT:2>]<EOL>


<EOL>p[<NUM_LIT:0>] = Operators.ULT(p[<NUM_LIT:1>], p[<NUM_LIT:3>])<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] - p[<NUM_LIT:3>]<EOL>

expression : expression MINUS expression


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] + p[<NUM_LIT:3>]<EOL>


t.lexer.lineno += len(t.value)<EOL>


<EOL>p[<NUM_LIT:0>] = Operators.UGE(p[<NUM_LIT:1>], p[<NUM_LIT:3>])<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] or p[<NUM_LIT:3>]<EOL>


p[<NUM_LIT:0>] = not p[<NUM_LIT:1>]<EOL>


all_addresses = self._all_addresses()<EOL>while True:<EOL><INDENT>new_address = random.randint(<NUM_LIT:100>, pow(<NUM_LIT:2>, <NUM_LIT>))<EOL>if new_address not in all_addresses:<EOL><INDENT>return new_address<EOL><DEDENT><DEDENT>


def preconstraint_for_call_transaction(self, address: Union[int, EVMAccount], data: Array,<EOL>value: Optional[Union[int, Expression]] = None,<EOL>contract_metadata: Optional[SolidityMetadata] = None) -> BoolOperation:

if isinstance(address, EVMAccount):<EOL><INDENT>address = int(address)<EOL><DEDENT>if not isinstance(address, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not issymbolic(data):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if contract_metadata is None:<EOL><INDENT>contract_metadata = self.metadata.get(address)<EOL>if contract_metadata is None:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>selectors = contract_metadata.function_selectors<EOL>if not selectors or len(data) <= <NUM_LIT:4>:<EOL><INDENT>return BoolConstant(True)<EOL><DEDENT>symbolic_selector = data[:<NUM_LIT:4>]<EOL>value_is_symbolic = issymbolic(value)<EOL>constraint = None<EOL>for selector in selectors:<EOL><INDENT>c = symbolic_selector == selector<EOL>if value_is_symbolic and not contract_metadata.get_abi(selector)['<STR_LIT>']:<EOL><INDENT>c = Operators.AND(c, value == <NUM_LIT:0>)<EOL><DEDENT>if constraint is None:<EOL><INDENT>constraint = c<EOL><DEDENT>else:<EOL><INDENT>constraint = Operators.OR(constraint, c)<EOL><DEDENT><DEDENT>return constraint<EOL>

Returns a constraint that excludes combinations of value and data that would cause an exception in the EVM
            contract dispatcher.
            :param address: address of the contract to call
            :param value: balance to be transferred (optional)
            :param data: symbolic transaction data
            :param contract_metadata: SolidityMetadata for the contract (optional)


def __init__(self, procs=<NUM_LIT:10>, workspace_url: str=None, policy: str='<STR_LIT>'):

self._accounts = dict()<EOL>self._serializer = PickleSerializer()<EOL>self._config_procs = procs<EOL>constraints = ConstraintSet()<EOL>world = evm.EVMWorld(constraints)<EOL>initial_state = State(constraints, world)<EOL>super().__init__(initial_state, workspace_url=workspace_url, policy=policy)<EOL>self.constraints = ConstraintSet()<EOL>self.detectors = {}<EOL>self.metadata: Dict[int, SolidityMetadata] = {}<EOL>self.context['<STR_LIT>'] = {}<EOL>self.context['<STR_LIT>']['<STR_LIT>'] = set()<EOL>self.context['<STR_LIT>']['<STR_LIT>'] = set()<EOL>self.context['<STR_LIT>']['<STR_LIT>'] = <NUM_LIT:0><EOL>self.context['<STR_LIT>']['<STR_LIT>'] = dict()<EOL>self.context['<STR_LIT>']['<STR_LIT>'] = set()<EOL>self._executor.subscribe('<STR_LIT>', self._load_state_callback)<EOL>self._executor.subscribe('<STR_LIT>', self._terminate_state_callback)<EOL>self._executor.subscribe('<STR_LIT>', self._did_evm_execute_instruction_callback)<EOL>self._executor.subscribe('<STR_LIT>', self._did_evm_read_code)<EOL>self._executor.subscribe('<STR_LIT>', self._on_symbolic_sha3_callback)<EOL>self._executor.subscribe('<STR_LIT>', self._on_concrete_sha3_callback)<EOL>self.subscribe('<STR_LIT>', self._generate_testcase_callback)<EOL>

A Manticore EVM manager
:param procs:, number of workers to use in the exploration
:param workspace_url: workspace folder name
:param policy: scheduling priority


return len(self._terminated_state_ids)<EOL>


<EOL>default_string_size = <NUM_LIT:32><EOL>default_array_size = <NUM_LIT:32><EOL>if ty[<NUM_LIT:0>] in ('<STR_LIT:int>', '<STR_LIT>'):<EOL><INDENT>result = self.make_symbolic_value()<EOL><DEDENT>elif ty[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>result = self.make_symbolic_buffer(size=ty[<NUM_LIT:1>])<EOL><DEDENT>elif ty[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>address = self.make_symbolic_value()<EOL>func_id = self.make_symbolic_buffer(size=<NUM_LIT:4>)<EOL>result = (address, func_id)<EOL><DEDENT>elif ty[<NUM_LIT:0>] in ('<STR_LIT>', '<STR_LIT:string>'):<EOL><INDENT>result = self.make_symbolic_buffer(size=default_string_size)<EOL><DEDENT>elif ty[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>result = ()<EOL>for ty_i in ty[<NUM_LIT:1>]:<EOL><INDENT>result += (self._make_symbolic_arguments(ty_i), )<EOL><DEDENT><DEDENT>elif ty[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>result = []<EOL>rep = ty[<NUM_LIT:1>]<EOL>if rep is None:<EOL><INDENT>rep = default_array_size<EOL><DEDENT>for _ in range(rep):<EOL><INDENT>result.append(self._make_symbolic_arguments(ty[<NUM_LIT:2>]))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise NotImplemented<EOL><DEDENT>return result<EOL>

This makes a tuple of symbols to be used as arguments of type ty


with self.locked_context('<STR_LIT>') as context:<EOL><INDENT>if self.initial_state is not None:<EOL><INDENT>return (-<NUM_LIT:1>,) + tuple(context['<STR_LIT>'])<EOL><DEDENT>else:<EOL><INDENT>return tuple(context['<STR_LIT>'])<EOL><DEDENT><DEDENT>


return len(self._running_state_ids)<EOL>


state = self.load(state_id)<EOL>return state.platform.human_transactions<EOL>


if not isinstance(d, (Detector, str)):<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>name = d<EOL>if isinstance(d, Detector):<EOL><INDENT>name = d.name<EOL><DEDENT>if name not in self.detectors:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>d = self.detectors[name]<EOL>del self.detectors[name]<EOL>self.unregister_plugin(d)<EOL>

Unregisters a detector. This will invoke detector's `on_unregister` callback.
Shall be called after `.finalize` - otherwise, finalize won't add detector's finding to `global.findings`.


return '<STR_LIT>' if flag else '<STR_LIT>'<EOL>

Return special character denoting concretization happened.


@staticmethod<EOL><INDENT>def _compile(source_code, contract_name, libraries=None, solc_bin=None, solc_remaps=[], working_dir=None):<DEDENT>

if isinstance(source_code, str):<EOL><INDENT>with tempfile.NamedTemporaryFile('<STR_LIT>') as temp:<EOL><INDENT>temp.write(source_code)<EOL>temp.flush()<EOL>output, warnings = ManticoreEVM._run_solc(temp, solc_bin, solc_remaps, working_dir=working_dir)<EOL><DEDENT><DEDENT>elif isinstance(source_code, io.IOBase):<EOL><INDENT>output, warnings = ManticoreEVM._run_solc(source_code, solc_bin, solc_remaps, working_dir=working_dir)<EOL>source_code.seek(<NUM_LIT:0>)<EOL>source_code = source_code.read()<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(f'<STR_LIT>')<EOL><DEDENT>contracts = output.get('<STR_LIT>', [])<EOL>if len(contracts) != <NUM_LIT:1> and contract_name is None:<EOL><INDENT>raise EthereumError(f'<STR_LIT>')<EOL><DEDENT>name, contract = None, None<EOL>if contract_name is None:<EOL><INDENT>name, contract = list(contracts.items())[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>for n, c in contracts.items():<EOL><INDENT>if n == contract_name or n.split("<STR_LIT::>")[<NUM_LIT:1>] == contract_name:<EOL><INDENT>name, contract = n, c<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if name is None:<EOL><INDENT>raise ValueError(f'<STR_LIT>')<EOL><DEDENT>name = name.split('<STR_LIT::>')[<NUM_LIT:1>]<EOL>if contract['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>raise EthereumError('<STR_LIT>')<EOL><DEDENT>bytecode = ManticoreEVM._link(contract['<STR_LIT>'], libraries)<EOL>srcmap = contract['<STR_LIT>'].split('<STR_LIT:;>')<EOL>srcmap_runtime = contract['<STR_LIT>'].split('<STR_LIT:;>')<EOL>hashes = {str(x): str(y) for x, y in contract['<STR_LIT>'].items()}<EOL>abi = json.loads(contract['<STR_LIT>'])<EOL>runtime = ManticoreEVM._link(contract['<STR_LIT>'], libraries)<EOL>return name, source_code, bytecode, runtime, srcmap, srcmap_runtime, hashes, abi, warnings<EOL>

Compile a Solidity contract, used internally

            :param source_code: solidity source as either a string or a file handle
            :param contract_name: a string with the name of the contract to analyze
            :param libraries: an itemizable of pairs (library_name, address)
            :param solc_bin: path to solc binary
            :param solc_remaps: solc import remaps
            :param working_dir: working directory for solc compilation (defaults to current)
            :return: name, source_code, bytecode, srcmap, srcmap_runtime, hashes
            :return: name, source_code, bytecode, runtime, srcmap, srcmap_runtime, hashes, abi, warnings


return self.get_world()<EOL>

The world instance or None if there is more than one state


def create_account(self, balance=<NUM_LIT:0>, address=None, code=None, name=None):

<EOL>if not self.count_running_states():<EOL><INDENT>raise NoAliveStates<EOL><DEDENT>if name is None:<EOL><INDENT>if code is None:<EOL><INDENT>name = self._get_uniq_name("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>name = self._get_uniq_name("<STR_LIT>")<EOL><DEDENT><DEDENT>if name in self._accounts:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>if not isinstance(balance, int):<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>if isinstance(code, str):<EOL><INDENT>code = bytes(code, "<STR_LIT:utf-8>")<EOL><DEDENT>if code is not None and not isinstance(code, (bytes, Array)):<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>if address is None:<EOL><INDENT>address = self.new_address()<EOL><DEDENT>if not isinstance(address, int):<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>assert address is not None<EOL>if address in map(int, self.accounts.values()):<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>for state in self.running_states:<EOL><INDENT>world = state.platform<EOL>if '<STR_LIT>' in state.context:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>if address in world.accounts:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>world.create_account(address, balance, code=code, storage=None)<EOL><DEDENT>self._accounts[name] = EVMAccount(address, manticore=self, name=name)<EOL>return self.accounts[name]<EOL>

Low level creates an account. This won't generate a transaction.

            :param balance: balance to be set on creation (optional)
            :type balance: int or BitVecVariable
            :param address: the address for the new account (optional)
            :type address: int
            :param code: the runtime code for the new account (None means normal account), str or bytes (optional)
            :param name: a global account name eg. for use as reference in the reports (optional)
            :return: an EVMAccount


account_address = int(account)<EOL>runtime_bytecode = None<EOL>for state in self.all_states:<EOL><INDENT>world = state.platform<EOL>if account_address in world:<EOL><INDENT>code = world.get_code(account_address)<EOL>runtime_bytecode = state.solve_one(code)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>with self.locked_context('<STR_LIT>') as coverage:<EOL><INDENT>seen = {off for addr, off in coverage if addr == account_address}<EOL><DEDENT>return calculate_coverage(runtime_bytecode, seen)<EOL>

Returns code coverage for the contract on `account_address`.
            This sums up all the visited code lines from any of the explored
            states.


logger.debug("<STR_LIT>", self.count_states())<EOL>def finalizer(state_id):<EOL><INDENT>state_id = self._terminate_state_id(state_id)<EOL>st = self.load(state_id)<EOL>logger.debug("<STR_LIT>", state_id)<EOL>last_tx = st.platform.last_transaction<EOL>message = last_tx.result if last_tx else '<STR_LIT>'<EOL>self._publish_generate_testcase(st, message=message)<EOL><DEDENT>def worker_finalize(q):<EOL><INDENT>try:<EOL><INDENT>while True:<EOL><INDENT>finalizer(q.get_nowait())<EOL><DEDENT><DEDENT>except EmptyQueue:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>q = Queue()<EOL>for state_id in self._all_state_ids:<EOL><INDENT>if state_id == -<NUM_LIT:1>:<EOL><INDENT>finalizer(-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>q.put(state_id)<EOL><DEDENT><DEDENT>report_workers = []<EOL>for _ in range(self._config_procs):<EOL><INDENT>proc = Process(target=worker_finalize, args=(q,))<EOL>proc.start()<EOL>report_workers.append(proc)<EOL><DEDENT>for proc in report_workers:<EOL><INDENT>proc.join()<EOL><DEDENT>if len(self.global_findings):<EOL><INDENT>with self._output.save_stream('<STR_LIT>') as global_findings:<EOL><INDENT>for address, pc, finding, at_init in self.global_findings:<EOL><INDENT>global_findings.write('<STR_LIT>' % finding)<EOL>write_findings(global_findings, '<STR_LIT:U+0020>', address, pc, at_init)<EOL>md = self.get_metadata(address)<EOL>if md is not None:<EOL><INDENT>source_code_snippet = md.get_source_for(pc, runtime=not at_init)<EOL>global_findings.write('<STR_LIT>')<EOL>global_findings.write('<STR_LIT:U+0020>'.join(source_code_snippet.splitlines(True)))<EOL>global_findings.write('<STR_LIT:\n>')<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self._save_run_data()<EOL>with self._output.save_stream('<STR_LIT>') as global_summary:<EOL><INDENT>global_summary.write("<STR_LIT>")<EOL>for address in self.contract_accounts.values():<EOL><INDENT>global_summary.write("<STR_LIT>".format(int(address), self.global_coverage(address)))<EOL>md = self.get_metadata(address)<EOL>if md is not None and len(md.warnings) > <NUM_LIT:0>:<EOL><INDENT>global_summary.write('<STR_LIT>' % md.name)<EOL>global_summary.write(md.warnings)<EOL><DEDENT><DEDENT><DEDENT>for address, md in self.metadata.items():<EOL><INDENT>with self._output.save_stream('<STR_LIT>' % md.name) as global_src:<EOL><INDENT>global_src.write(md.source_code)<EOL><DEDENT>with self._output.save_stream('<STR_LIT>' % md.name, binary=True) as global_runtime_bytecode:<EOL><INDENT>global_runtime_bytecode.write(md.runtime_bytecode)<EOL><DEDENT>with self._output.save_stream('<STR_LIT>' % md.name, binary=True) as global_init_bytecode:<EOL><INDENT>global_init_bytecode.write(md.init_bytecode)<EOL><DEDENT>with self._output.save_stream('<STR_LIT>' % md.name) as global_runtime_asm:<EOL><INDENT>runtime_bytecode = md.runtime_bytecode<EOL>with self.locked_context('<STR_LIT>') as seen:<EOL><INDENT>count, total = <NUM_LIT:0>, <NUM_LIT:0><EOL>for i in EVMAsm.disassemble_all(runtime_bytecode):<EOL><INDENT>if (address, i.pc) in seen:<EOL><INDENT>count += <NUM_LIT:1><EOL>global_runtime_asm.write('<STR_LIT:*>')<EOL><DEDENT>else:<EOL><INDENT>global_runtime_asm.write('<STR_LIT:U+0020>')<EOL><DEDENT>global_runtime_asm.write('<STR_LIT>' % (i.pc, i))<EOL>total += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>with self._output.save_stream('<STR_LIT>' % md.name) as global_init_asm:<EOL><INDENT>with self.locked_context('<STR_LIT>') as seen:<EOL><INDENT>count, total = <NUM_LIT:0>, <NUM_LIT:0><EOL>for i in EVMAsm.disassemble_all(md.init_bytecode):<EOL><INDENT>if (address, i.pc) in seen:<EOL><INDENT>count += <NUM_LIT:1><EOL>global_init_asm.write('<STR_LIT:*>')<EOL><DEDENT>else:<EOL><INDENT>global_init_asm.write('<STR_LIT:U+0020>')<EOL><DEDENT>global_init_asm.write('<STR_LIT>' % (i.pc, i))<EOL>total += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>with self._output.save_stream('<STR_LIT>' % md.name) as f:<EOL><INDENT>with self.locked_context('<STR_LIT>') as seen:<EOL><INDENT>visited = set((o for (a, o) in seen if a == address))<EOL>for o in sorted(visited):<EOL><INDENT>f.write('<STR_LIT>' % o)<EOL><DEDENT><DEDENT><DEDENT>with self._output.save_stream('<STR_LIT>' % md.name) as f:<EOL><INDENT>with self.locked_context('<STR_LIT>') as seen:<EOL><INDENT>visited = set()<EOL>for (a, o) in seen:<EOL><INDENT>if a == address:<EOL><INDENT>visited.add(o)<EOL><DEDENT><DEDENT>for o in sorted(visited):<EOL><INDENT>f.write('<STR_LIT>' % o)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for state_id in self._all_state_ids:<EOL><INDENT>if state_id != -<NUM_LIT:1>:<EOL><INDENT>self._executor._workspace.rm_state(state_id)<EOL><DEDENT><DEDENT>with self.locked_context('<STR_LIT>') as eth_context:<EOL><INDENT>eth_context['<STR_LIT>'] = set()<EOL>eth_context['<STR_LIT>'] = set()<EOL><DEDENT>

Terminate and generate testcases for all currently alive states (contract states that cleanly executed
to a STOP or RETURN in the last symbolic transaction).


def _did_evm_read_code(self, state, offset, size):

with self.locked_context('<STR_LIT>', set) as code_data:<EOL><INDENT>for i in range(offset, offset + size):<EOL><INDENT>code_data.add((state.platform.current_vm.address, i))<EOL><DEDENT><DEDENT>


def _on_symbolic_sha3_callback(self, state, data, known_hashes):

assert issymbolic(data), '<STR_LIT>'<EOL>with self.locked_context('<STR_LIT>') as context:<EOL><INDENT>known_sha3 = context.get('<STR_LIT>', None)<EOL>if known_sha3 is None:<EOL><INDENT>known_sha3 = set()<EOL><DEDENT>sha3_states = context.get('<STR_LIT>', [])<EOL>results = []<EOL>known_hashes_cond = False<EOL>for key, value in known_sha3:<EOL><INDENT>assert not issymbolic(key), "<STR_LIT>"<EOL>cond = key == data<EOL>if not state.can_be_true(cond):<EOL><INDENT>continue<EOL><DEDENT>results.append((key, value))<EOL>known_hashes_cond = Operators.OR(cond, known_hashes_cond)<EOL><DEDENT>if not results:<EOL><INDENT>data_concrete = state.solve_one(data)<EOL>s = sha3.keccak_256(data_concrete)<EOL>data_hash = int(s.hexdigest(), <NUM_LIT:16>)<EOL>results.append((data_concrete, data_hash))<EOL>known_hashes_cond = data_concrete == data<EOL>known_sha3.add((data_concrete, data_hash))<EOL><DEDENT>not_known_hashes_cond = Operators.NOT(known_hashes_cond)<EOL>with state as temp_state:<EOL><INDENT>if temp_state.can_be_true(not_known_hashes_cond):<EOL><INDENT>temp_state.constrain(not_known_hashes_cond)<EOL>state_id = self._executor._workspace.save_state(temp_state)<EOL>sha3_states[state_id] = [hsh for buf, hsh in known_sha3]<EOL><DEDENT><DEDENT>context['<STR_LIT>'] = sha3_states<EOL>if not state.can_be_true(known_hashes_cond):<EOL><INDENT>raise TerminateState("<STR_LIT>")<EOL><DEDENT>state.constrain(known_hashes_cond)<EOL>known_hashes.update(results)<EOL><DEDENT>


for state_id in self._terminated_state_ids:<EOL><INDENT>state = self.load(state_id)<EOL>yield state<EOL>self.save(state, state_id=state_id, final=True)<EOL><DEDENT>

Iterates over the terminated states.

See also `running_states`.


with self.locked_context('<STR_LIT>') as context:<EOL><INDENT>return tuple(context['<STR_LIT>'])<EOL><DEDENT>


ret = set()<EOL>for state in self.running_states:<EOL><INDENT>ret |= set(state.platform.accounts)<EOL><DEDENT>return ret<EOL>

Returns all addresses in all running states


for state_id in self._running_state_ids:<EOL><INDENT>state = self.load(state_id)<EOL>yield state<EOL>self.save(state, state_id=state_id)<EOL><DEDENT>

Iterates over running states giving the possibility to change state data.

The state data change must be done in a loop, e.g. `for state in running_states: ...`
as we re-save the state when the generator comes back to the function.

This means it is not possible to change the state used by Manticore with `states = list(m.running_states)`.


return len(self._all_state_ids)<EOL>


def make_symbolic_value(self, nbits=<NUM_LIT>, name=None):

avoid_collisions = False<EOL>if name is None:<EOL><INDENT>name = '<STR_LIT>'<EOL>avoid_collisions = True<EOL><DEDENT>return self.constraints.new_bitvec(nbits, name=name, avoid_collisions=avoid_collisions)<EOL>

Creates a symbolic value, normally a uint256, to be used in transactions.
            You can operate on it normally and add constraints to manticore.constraints
            via manticore.constrain(constraint_expression)

            Example use::

                symbolic_value = m.make_symbolic_value()
                m.constrain(symbolic_value > 100)
                m.constrain(symbolic_value < 1000)
                m.transaction(caller=attacker_account,
                                address=contract_account,
                                data=data,
                                value=symbolic_value )


count, total = <NUM_LIT:0>, <NUM_LIT:0><EOL>bytecode = SolidityMetadata._without_metadata(runtime_bytecode)<EOL>for i in EVMAsm.disassemble_all(bytecode):<EOL><INDENT>if i.pc in seen:<EOL><INDENT>count += <NUM_LIT:1><EOL><DEDENT>total += <NUM_LIT:1><EOL><DEDENT>if total == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>return count * <NUM_LIT> / total<EOL>

Calculates what percentage of runtime_bytecode has been seen


return self._running_state_ids + self._terminated_state_ids<EOL>

IDs of the all states

            Note: state with id -1 is already in memory and it is not backed on the storage


state = self.load(state_id)<EOL>if state is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return state.platform<EOL><DEDENT>

Returns the evm world of `state_id` state.


if not isinstance(d, Detector):<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>if d.name in self.detectors:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>self.detectors[d.name] = d<EOL>self.register_plugin(d)<EOL>return d.name<EOL>

Unregisters a plugin. This will invoke detector's `on_unregister` callback.
Shall be called after `.finalize`.


@staticmethod<EOL><INDENT>def compile(source_code, contract_name=None, libraries=None, runtime=False, solc_bin=None, solc_remaps=[]):<DEDENT>

name, source_code, init_bytecode, runtime_bytecode, srcmap, srcmap_runtime, hashes, abi, warnings = ManticoreEVM._compile(source_code, contract_name, libraries, solc_bin, solc_remaps)<EOL>if runtime:<EOL><INDENT>return runtime_bytecode<EOL><DEDENT>return init_bytecode<EOL>

Get initialization bytecode from a Solidity source code


state = None<EOL>if state_id is None:<EOL><INDENT>state_count = self.count_running_states()<EOL>if state_count == <NUM_LIT:1>:<EOL><INDENT>state_id = self._running_state_ids[<NUM_LIT:0>]<EOL><DEDENT>elif state_count == <NUM_LIT:0>:<EOL><INDENT>raise NoAliveStates<EOL><DEDENT>else:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT><DEDENT>if state_id == -<NUM_LIT:1>:<EOL><INDENT>state = self.initial_state<EOL><DEDENT>else:<EOL><INDENT>state = self._executor._workspace.load_state(state_id, delete=False)<EOL>self._executor.forward_events_from(state, True)<EOL><DEDENT>return state<EOL>

Load one of the running or final states.

            :param state_id: If None it assumes there is a single running state
            :type state_id: int or None


def _transaction(self, sort, caller, value=<NUM_LIT:0>, address=None, data=None, gaslimit=None, price=<NUM_LIT:1>):

if gaslimit is None:<EOL><INDENT>gaslimit = cfg.defaultgas<EOL><DEDENT>if isinstance(address, EVMAccount):<EOL><INDENT>address = int(address)<EOL><DEDENT>if isinstance(caller, EVMAccount):<EOL><INDENT>caller = int(caller)<EOL><DEDENT>if data is None:<EOL><INDENT>data = bytearray(b"<STR_LIT>")<EOL><DEDENT>if isinstance(data, (str, bytes)):<EOL><INDENT>data = bytearray(data)<EOL><DEDENT>if not isinstance(data, (bytearray, Array)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(caller, (int, BitVec)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(value, (int, BitVec)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(address, (int, BitVec)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(price, int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if sort not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if sort == '<STR_LIT>':<EOL><INDENT>if len(data) == <NUM_LIT:0>:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT><DEDENT>assert address is not None<EOL>assert caller is not None<EOL>if not self.count_running_states():<EOL><INDENT>raise NoAliveStates<EOL><DEDENT>for state in self.running_states:<EOL><INDENT>world = state.platform<EOL>if '<STR_LIT>' in state.context:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>if address is None:<EOL><INDENT>if issymbolic(caller):<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>address = world.new_address(caller)<EOL><DEDENT>caller_migrated, address_migrated, value_migrated, data_migrated = self._migrate_tx_expressions(state, caller, address, value, data)<EOL>if sort == '<STR_LIT>':<EOL><INDENT>if address in world.accounts:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT><DEDENT>state.context['<STR_LIT>'] = (sort, caller_migrated, address_migrated, value_migrated, data_migrated, gaslimit, price)<EOL><DEDENT>self.run(procs=self._config_procs)<EOL>return address<EOL>

Initiates a transaction

            :param caller: caller account
            :type caller: int or EVMAccount
            :param int address: the address for the transaction (optional)
            :param value: value to be transferred
            :param price: the price of gas for this transaction. Mostly unused.
            :type value: int or BitVecVariable
            :param str data: initializing evm bytecode and arguments or transaction call data
            :param gaslimit: gas budget
            :rtype: EVMAccount


state = self.load(state_id)<EOL>return state.platform.last_transaction.return_data<EOL>

Last returned buffer for state `state_id`


def transaction(self, caller, address, value, data, gas=None):

self._transaction('<STR_LIT>', caller, value=value, address=address, data=data, gaslimit=gas)<EOL>

Issue a symbolic transaction in all running states

            :param caller: the address of the account sending the transaction
            :type caller: int or EVMAccount
            :param address: the address of the contract to call
            :type address: int or EVMAccount
            :param value: balance to be transfered on creation
            :type value: int or BitVecVariable
            :param data: initial data
            :param gas: gas budget
            :raises NoAliveStates: if there are no alive states to execute


def __init__(self, regexp=r'<STR_LIT>', mutability='<STR_LIT>', depth='<STR_LIT>', fallback=False, include=True, **kwargs):

super().__init__(**kwargs)<EOL>depth = depth.lower()<EOL>if depth not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError<EOL><DEDENT>mutability = mutability.lower()<EOL>if mutability not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError<EOL><DEDENT>self._regexp = regexp<EOL>self._mutability = mutability<EOL>self._depth = depth<EOL>self._fallback = fallback<EOL>self._include = include<EOL>

Constrain input based on function metadata. Include or avoid functions selected by the specified criteria.

Examples:
#Do not explore any human transactions that end up calling a constant function
no_human_constant = FilterFunctions(depth='human', mutability='constant', include=False)

#At human tx depth only accept synthetic check functions
only_tests = FilterFunctions(regexp=r'mcore_.*', depth='human', include=False)

:param regexp: a regular expression over the name of the function '.*' will match all functions
:param mutability: mutable, constant or both will match functions declared in the abi to be of such class
:param depth: match functions in internal transactions, in human initiated transactions or in both types
:param fallback: if True include the fallback function. Hash will be 00000000 for it
:param include: if False exclude the selected functions, if True include them


def __init__(self, only_human=True, **kwargs):

super().__init__(**kwargs)<EOL>self._only_human = only_human<EOL>

Detects INVALID instructions.

INVALID instructions are originally designated to signal exceptional code.
As in practice the INVALID instruction is used in different ways this
detector may Generate a great deal of false positives.

:param only_human: if True report only INVALID at depth 0 transactions


def add_finding(self, state, address, pc, finding, at_init, constraint=True):

if issymbolic(pc):<EOL><INDENT>pc = simplify(pc)<EOL><DEDENT>if isinstance(pc, Constant):<EOL><INDENT>pc = pc.value<EOL><DEDENT>if not isinstance(pc, int):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.get_findings(state).add((address, pc, finding, at_init, constraint))<EOL>with self.locked_global_findings() as gf:<EOL><INDENT>gf.add((address, pc, finding, at_init))<EOL><DEDENT>logger.warning(finding)<EOL>

Logs a finding at specified contract and assembler line.
:param state: current state
:param address: contract address of the finding
:param pc: program counter of the finding
:param at_init: true if executing the constructor
:param finding: textual description of the finding
:param constraint: finding is considered reproducible only when constraint is True


@staticmethod<EOL><INDENT>def _unsigned_sub_overflow(state, a, b):<DEDENT>

cond = Operators.UGT(b, a)<EOL>return cond<EOL>

Sign extend the value to 512 bits and check the result can be represented
 in 256. Following there is a 32 bit excerpt of this condition:

a  -  b   ffffffff bfffffff 80000001 00000000 00000001 3ffffffff 7fffffff
ffffffff     True     True     True    False     True     True     True
bfffffff     True     True     True    False    False     True     True
80000001     True     True     True    False    False     True     True
00000000    False    False    False    False    False     True    False
00000001     True    False    False    False    False     True    False
ffffffff     True     True     True     True     True     True     True
7fffffff     True     True     True    False    False     True    False


<EOL>in_function = state.context.get('<STR_LIT>', False)<EOL>prev_tx_count = state.context.get('<STR_LIT>', <NUM_LIT:0>)<EOL>curr_tx_count = len(state.platform.transactions)<EOL>new_human_tx = prev_tx_count != curr_tx_count<EOL>if in_function and not new_human_tx:<EOL><INDENT>return True<EOL><DEDENT>in_function = len(state.solve_n(state.platform.current_transaction.data[:<NUM_LIT:4>], <NUM_LIT:2>)) == <NUM_LIT:1><EOL>state.context['<STR_LIT>'] = in_function<EOL>state.context['<STR_LIT>'] = curr_tx_count<EOL>return in_function<EOL>

:param state: current state
:return: whether the current execution is in a user-defined function or not.

NOTE / TODO / FIXME: As this may produce false postives, this is not in the base `Detector` class.
It should be fixed at some point and moved there. See below.

The first 4 bytes of tx data is keccak256 hash of the function signature that is called by given tx.

All transactions start within Solidity dispatcher function: it takes passed hash and dispatches
the execution to given function based on it.

So: if we are in the dispatcher, *and contract have some functions* one of the first four tx data bytes
will effectively have more than one solutions.

BUT if contract have only a fallback function, the equation below may return more solutions when we are
in a dispatcher function.  <--- because of that, we warn that the detector is not that stable
for contracts with only a fallback function.


@property<EOL><INDENT>def function_signatures(self) -> Iterable[str]:<DEDENT>

return self._function_signatures_by_selector.values()<EOL>

The signatures of all normal contract functions.


@property<EOL><INDENT>def fallback_function_selector(self) -> bytes:<DEDENT>

return self._fallback_function_selector<EOL>

A function selector not associated with any of the non-fallback contract functions.

        This selector is almost always ``b'\0\0\0\0'``.


def get_constructor_arguments(self) -> str:

item = self._constructor_abi_item<EOL>return '<STR_LIT>' if item is None else self.tuple_signature_for_components(item['<STR_LIT>'])<EOL>

Returns the tuple type signature for the arguments of the contract constructor.


def get_source_for(self, asm_offset, runtime=True):

srcmap = self.get_srcmap(runtime)<EOL>try:<EOL><INDENT>beg, size, _, _ = srcmap[asm_offset]<EOL><DEDENT>except KeyError:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>output = '<STR_LIT>'<EOL>nl = self.source_code[:beg].count('<STR_LIT:\n>') + <NUM_LIT:1><EOL>snippet = self.source_code[beg:beg + size]<EOL>for l in snippet.split('<STR_LIT:\n>'):<EOL><INDENT>output += '<STR_LIT>' % (nl, l)<EOL>nl += <NUM_LIT:1><EOL><DEDENT>return output<EOL>

Solidity source code snippet related to `asm_pos` evm bytecode offset.
            If runtime is False, initialization bytecode source map is used


def get_func_name(self, hsh: bytes) -> str:

if not isinstance(hsh, (bytes, bytearray)):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>sig = self._function_signatures_by_selector.get(hsh)<EOL>return '<STR_LIT>' if sig is None else sig[:sig.find('<STR_LIT:(>')]<EOL>

Returns the name of the normal function with the selector ``hsh``,
        or ``'{fallback}'`` if no such function exists.


@property<EOL><INDENT>def has_non_default_fallback_function(self) -> bool:<DEDENT>

return self._fallback_function_abi_item is not None<EOL>

Indicates whether the contract has an explicitly defined fallback function.


def __init__(self, name, source_code, init_bytecode, runtime_bytecode, srcmap, srcmap_runtime, hashes, abi, warnings):

self.name = name<EOL>if isinstance(source_code, bytes):<EOL><INDENT>source_code = source_code.decode()<EOL><DEDENT>self.source_code = source_code<EOL>self._init_bytecode = init_bytecode<EOL>self._runtime_bytecode = runtime_bytecode<EOL>self._function_signatures_by_selector = {bytes.fromhex(sel): sig for sig, sel in hashes.items()}<EOL>fallback_selector = b'<STR_LIT>'<EOL>while fallback_selector in self._function_signatures_by_selector:<EOL><INDENT>fallback_selector = (int.from_bytes(fallback_selector, '<STR_LIT>') + <NUM_LIT:1>).to_bytes(<NUM_LIT:4>, '<STR_LIT>')<EOL><DEDENT>self._fallback_function_selector = fallback_selector<EOL>self._constructor_abi_item = None<EOL>self._fallback_function_abi_item = None<EOL>function_items = {}<EOL>event_items = {}<EOL>for item in abi:<EOL><INDENT>type = item['<STR_LIT:type>']<EOL>if type == '<STR_LIT>':<EOL><INDENT>signature = self.function_signature_for_name_and_inputs(item['<STR_LIT:name>'], item['<STR_LIT>'])<EOL>function_items[signature] = item<EOL><DEDENT>elif type == '<STR_LIT>':<EOL><INDENT>signature = self.function_signature_for_name_and_inputs(item['<STR_LIT:name>'], item['<STR_LIT>'])<EOL>event_items[signature] = item<EOL><DEDENT>elif type == '<STR_LIT>':<EOL><INDENT>assert not self._constructor_abi_item, "<STR_LIT>"<EOL>self._constructor_abi_item = item<EOL><DEDENT>elif type == '<STR_LIT>':<EOL><INDENT>assert not self._fallback_function_abi_item, "<STR_LIT>"<EOL>self._fallback_function_abi_item = item<EOL><DEDENT><DEDENT>self._function_abi_items_by_signature = function_items<EOL>self._event_abi_items_by_signature = event_items<EOL>self.warnings = warnings<EOL>self.srcmap_runtime = self.__build_source_map(self.runtime_bytecode, srcmap_runtime)<EOL>self.srcmap = self.__build_source_map(self.init_bytecode, srcmap)<EOL>

Contract metadata for Solidity-based contracts


def get_func_argument_types(self, hsh: bytes):

if not isinstance(hsh, (bytes, bytearray)):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>sig = self._function_signatures_by_selector.get(hsh)<EOL>return '<STR_LIT>' if sig is None else sig[sig.find('<STR_LIT:(>'):]<EOL>

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.


@property<EOL><INDENT>@deprecated("<STR_LIT>")<EOL>def functions(self) -> Tuple[str, ...]:<DEDENT>

return (*self._function_signatures_by_selector.values(), '<STR_LIT>')<EOL>

The signatures of all normal contract functions, plus the ``'{fallback}()'`` pseudo-signature.


@property<EOL><INDENT>def constructor_abi(self) -> Dict[str, Any]:<DEDENT>

item = self._constructor_abi_item<EOL>if item:<EOL><INDENT>return dict(item)<EOL><DEDENT>return {'<STR_LIT>': [], '<STR_LIT>': False, '<STR_LIT>': '<STR_LIT>', '<STR_LIT:type>': '<STR_LIT>'}<EOL>

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_


@staticmethod<EOL><INDENT>def tuple_signature_for_components(components: Sequence[Mapping[str, Any]]) -> str:<DEDENT>

ts = []<EOL>for c in components:<EOL><INDENT>t: str = c['<STR_LIT:type>']<EOL>if t.startswith('<STR_LIT>'):<EOL><INDENT>assert len(t) == <NUM_LIT:5> or t[<NUM_LIT:5>] == '<STR_LIT:[>'<EOL>t = SolidityMetadata.tuple_signature_for_components(c['<STR_LIT>']) + t[<NUM_LIT:5>:]<EOL><DEDENT>ts.append(t)<EOL><DEDENT>return f'<STR_LIT>'<EOL>

Equivalent to ``function_signature_for_name_and_inputs('', components)``.


@property<EOL><INDENT>def has_non_default_constructor(self) -> bool:<DEDENT>

Indicates whether the contract has an explicitly defined constructor.


return self._name<EOL>

This is named this way to avoid naming collisions with Solidity functions/data,
since EVMContract inherits this.


def __init__(self, default_caller=None, **kwargs):

super().__init__(**kwargs)<EOL>self.__default_caller = default_caller<EOL>self.__hashes = {}<EOL>self.__initialized = False<EOL>

Encapsulates a contract account.

:param default_caller: the default caller address for any transaction


def __init__(self, address=None, manticore=None, name=None):

self._manticore = manticore<EOL>self._address = address<EOL>self._name = name<EOL>

Encapsulates an account.

:param address: the address of this account
:type address: 160 bit long integer
:param manticore: the controlling Manticore


t.value = ('<STR_LIT>', <NUM_LIT>)<EOL>return t<EOL>


p[<NUM_LIT:0>] = ('<STR_LIT>', p[<NUM_LIT:2>])<EOL>


reps = None<EOL>base_type = p[<NUM_LIT:1>]<EOL>p[<NUM_LIT:0>] = ('<STR_LIT>', reps, base_type)<EOL>


t.value = ('<STR_LIT>', <NUM_LIT:8>)<EOL>return t<EOL>


size = int(t.lexer.lexmatch.group('<STR_LIT:size>'))<EOL>t.value = ('<STR_LIT:int>', size)<EOL>return t<EOL>


reps = int(p[<NUM_LIT:3>])<EOL>base_type = p[<NUM_LIT:1>]<EOL>p[<NUM_LIT:0>] = ('<STR_LIT>', reps, base_type)<EOL>


t.value = ('<STR_LIT>',)<EOL>return t<EOL>


t.value = ('<STR_LIT:int>', <NUM_LIT>)<EOL>return t<EOL>


M = int(t.lexer.lexmatch.group('<STR_LIT:M>'))<EOL>N = int(t.lexer.lexmatch.group('<STR_LIT:N>'))<EOL>t.value = ("<STR_LIT>", M, N)<EOL>return t<EOL>


t.value = ('<STR_LIT>', <NUM_LIT>, <NUM_LIT>)<EOL>return t<EOL>


size = int(t.lexer.lexmatch.group('<STR_LIT:size>'))<EOL>t.value = ('<STR_LIT>', size)<EOL>return t<EOL>


size = int(t.lexer.lexmatch.group('<STR_LIT>'))<EOL>t.value = ('<STR_LIT>', size)<EOL>return t<EOL>


p[<NUM_LIT:0>] = p[<NUM_LIT:1>]<EOL>

T : UINTN
T : UINT
T : INTN
T : INT
T : ADDRESS
T : BOOL
T : FIXEDMN
T : UFIXEDMN
T : FIXED
T : UFIXED
T : BYTESM
T : FUNCTION
T : BYTES
T : STRING


s = sha3.keccak_256()<EOL>s.update(method_name_and_signature.encode())<EOL>return bytes(s.digest()[:<NUM_LIT:4>])<EOL>

Makes a function hash id from a method signature


@staticmethod<EOL><INDENT>def _serialize_uint(value, size=<NUM_LIT:32>, padding=<NUM_LIT:0>):<DEDENT>

if size <= <NUM_LIT:0> or size > <NUM_LIT:32>:<EOL><INDENT>raise ValueError<EOL><DEDENT>from .account import EVMAccount  <EOL>if not isinstance(value, (int, BitVec, EVMAccount)):<EOL><INDENT>raise ValueError<EOL><DEDENT>if issymbolic(value):<EOL><INDENT>bytes = ArrayVariable(index_bits=<NUM_LIT>, index_max=<NUM_LIT:32>, value_bits=<NUM_LIT:8>, name='<STR_LIT>'.format(uuid.uuid1()))<EOL>if value.size <= size * <NUM_LIT:8>:<EOL><INDENT>value = Operators.ZEXTEND(value, size * <NUM_LIT:8>)<EOL><DEDENT>else:<EOL><INDENT>value = Operators.EXTRACT(value, <NUM_LIT:0>, size * <NUM_LIT:8>)<EOL><DEDENT>bytes = ArrayProxy(bytes.write_BE(padding, value, size))<EOL><DEDENT>else:<EOL><INDENT>value = int(value)<EOL>bytes = bytearray()<EOL>for _ in range(padding):<EOL><INDENT>bytes.append(<NUM_LIT:0>)<EOL><DEDENT>for position in reversed(range(size)):<EOL><INDENT>bytes.append(Operators.EXTRACT(value, position * <NUM_LIT:8>, <NUM_LIT:8>))<EOL><DEDENT><DEDENT>assert len(bytes) == size + padding<EOL>return bytes<EOL>

Translates a python integral or a BitVec into a 32 byte string, MSB first


@staticmethod<EOL><INDENT>def _deserialize_uint(data, nbytes=<NUM_LIT:32>, padding=<NUM_LIT:0>, offset=<NUM_LIT:0>):<DEDENT>

assert isinstance(data, (bytearray, Array))<EOL>value = ABI._readBE(data, nbytes, padding=True, offset=offset)<EOL>value = Operators.ZEXTEND(value, (nbytes + padding) * <NUM_LIT:8>)<EOL>return value<EOL>

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


if ty[<NUM_LIT:0>] in ('<STR_LIT:int>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>return <NUM_LIT:32><EOL><DEDENT>elif ty[<NUM_LIT:0>] in ('<STR_LIT>'):<EOL><INDENT>result = <NUM_LIT:0><EOL>for ty_i in ty[<NUM_LIT:1>]:<EOL><INDENT>result += ABI._type_size(ty_i)<EOL><DEDENT>return result<EOL><DEDENT>elif ty[<NUM_LIT:0>] in ('<STR_LIT>'):<EOL><INDENT>rep = ty[<NUM_LIT:1>]<EOL>result = <NUM_LIT:32>  <EOL>return result<EOL><DEDENT>elif ty[<NUM_LIT:0>] in ('<STR_LIT>', '<STR_LIT:string>'):<EOL><INDENT>result = <NUM_LIT:32>  <EOL>return result<EOL><DEDENT>raise ValueError<EOL>


m = re.match(r"<STR_LIT>", type_spec)<EOL>if not m:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>ABI._check_and_warn_num_args(type_spec, *args)<EOL>result = ABI.function_selector(type_spec)  <EOL>result += ABI.serialize(m.group('<STR_LIT:type>'), *args)<EOL>return result<EOL>

Build transaction data from function signature and arguments


@staticmethod<EOL><INDENT>def _deserialize_int(data, nbytes=<NUM_LIT:32>, padding=<NUM_LIT:0>):<DEDENT>

assert isinstance(data, (bytearray, Array))<EOL>value = ABI._readBE(data, nbytes, padding=True)<EOL>value = Operators.SEXTEND(value, nbytes * <NUM_LIT:8>, (nbytes + padding) * <NUM_LIT:8>)<EOL>if not issymbolic(value):<EOL><INDENT>if value & (<NUM_LIT:1> << (nbytes * <NUM_LIT:8> - <NUM_LIT:1>)):<EOL><INDENT>value = -(((~value) + <NUM_LIT:1>) & ((<NUM_LIT:1> << (nbytes * <NUM_LIT:8>)) - <NUM_LIT:1>))<EOL><DEDENT><DEDENT>return value<EOL>

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


global _groups<EOL>for group_name, group in _groups.items():<EOL><INDENT>for key in group:<EOL><INDENT>yield f"<STR_LIT>"<EOL><DEDENT><DEDENT>

Return an iterable covering all defined keys so far


try:<EOL><INDENT>c = yaml.safe_load(f)<EOL>for section_name, section in c.items():<EOL><INDENT>group = get_group(section_name)<EOL>for key, val in section.items():<EOL><INDENT>group.update(key)<EOL>setattr(group, key, val)<EOL><DEDENT><DEDENT><DEDENT>except Exception:<EOL><INDENT>raise ConfigError("<STR_LIT>")<EOL><DEDENT>

Load an yml-formatted configuration from file stream |f|

:param file f: Where to read the config.


def update(self, name: str, value=None, default=None, description: str=None):

if name in self._vars:<EOL><INDENT>description = description or self._vars[name].description<EOL>default = default or self._vars[name].default<EOL><DEDENT>elif name == '<STR_LIT:name>':<EOL><INDENT>raise ConfigError("<STR_LIT>")<EOL><DEDENT>v = _Var(name, description=description, default=default, defined=False)<EOL>v.value = value<EOL>self._vars[name] = v<EOL>

Like add, but can tolerate existing values; also updates the value.

Mostly used for setting fields from imported INI files and modified CLI flags.


return _TemporaryGroup(self)<EOL>

Returns a contextmanager that can be used to set temporary config variables.
E.g.:
group.var = 123

with group.temp_vals():
    group.var = 456
    # var is 456

# group.var is back to 123


return filter(lambda x: x.was_set, self._vars.values())<EOL>

Return all vars that were explicitly set or updated with new values.


def get_description(self, name: str) -> str:

if name not in self._vars:<EOL><INDENT>raise ConfigError(f"<STR_LIT>")<EOL><DEDENT>return self._vars[name].description<EOL>

Return the description, or a help string of variable identified by |name|.


global _groups<EOL>c = {}<EOL>for group_name, group in _groups.items():<EOL><INDENT>section = {var.name: var.value for var in group.updated_vars()}<EOL>if not section:<EOL><INDENT>continue<EOL><DEDENT>c[group_name] = section<EOL><DEDENT>yaml.safe_dump(c, f, line_break=True)<EOL>

Save current config state to an yml file stream identified by |f|

:param f: where to write the config file


detectors_list = []<EOL>for detector in detector_classes:<EOL><INDENT>argument = detector.ARGUMENT<EOL>help_info = detector.HELP<EOL>impact = detector.IMPACT<EOL>confidence = classification_txt[detector.CONFIDENCE]<EOL>detectors_list.append((argument, help_info, impact, confidence))<EOL><DEDENT>table = PrettyTable(["<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"])<EOL>detectors_list = sorted(detectors_list, key=lambda element: (element[<NUM_LIT:2>], element[<NUM_LIT:3>], element[<NUM_LIT:0>]))<EOL>idx = <NUM_LIT:1><EOL>for (argument, help_info, impact, confidence) in detectors_list:<EOL><INDENT>table.add_row([idx, argument, help_info, classification_txt[impact], confidence])<EOL>idx = idx + <NUM_LIT:1><EOL><DEDENT>print(table)<EOL>


components = name.split('<STR_LIT:.>')<EOL>prefix = '<STR_LIT:.>'.join(c[<NUM_LIT:0>] for c in components[:-<NUM_LIT:1>])<EOL>return f'<STR_LIT>'<EOL>

Produce a summarized record name
  i.e. manticore.core.executor -> m.c.executor


logger.debug("<STR_LIT>"<EOL>% (instruction.address, instruction.mnemonic, instruction.op_str))<EOL>registers = set(self._cpu.canonical_registers)<EOL>if self._cpu.arch == CS_ARCH_X86:<EOL><INDENT>registers -= set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>registers.add('<STR_LIT>')<EOL>registers -= set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>registers |= set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL><DEDENT>for reg in registers:<EOL><INDENT>val = self._cpu.read_register(reg)<EOL>if issymbolic(val):<EOL><INDENT>from ..native.cpu.abstractcpu import ConcretizeRegister<EOL>raise ConcretizeRegister(self._cpu, reg, "<STR_LIT>",<EOL>policy='<STR_LIT>')<EOL><DEDENT>self._emu.reg_write(self._to_unicorn_id(reg), val)<EOL><DEDENT>instruction = self._cpu.decode_instruction(self._cpu.PC)<EOL>text_bytes = self._cpu.read_bytes(self._cpu.PC, instruction.size)<EOL>self._emu.mem_write(self._cpu.PC, b'<STR_LIT>'.join(text_bytes))<EOL>self._emu.hook_add(UC_HOOK_MEM_READ_UNMAPPED, self._hook_unmapped)<EOL>self._emu.hook_add(UC_HOOK_MEM_WRITE_UNMAPPED, self._hook_unmapped)<EOL>self._emu.hook_add(UC_HOOK_MEM_FETCH_UNMAPPED, self._hook_unmapped)<EOL>self._emu.hook_add(UC_HOOK_MEM_READ, self._hook_xfer_mem)<EOL>self._emu.hook_add(UC_HOOK_MEM_WRITE, self._hook_xfer_mem)<EOL>self._emu.hook_add(UC_HOOK_INTR, self._interrupt)<EOL>saved_PC = self._cpu.PC<EOL>try:<EOL><INDENT>pc = self._cpu.PC<EOL>if self._cpu.arch == CS_ARCH_ARM and self._uc_mode == UC_MODE_THUMB:<EOL><INDENT>pc |= <NUM_LIT:1><EOL><DEDENT>self._emu.emu_start(pc, self._cpu.PC + instruction.size, count=<NUM_LIT:1>)<EOL><DEDENT>except UcError as e:<EOL><INDENT>if not self._should_try_again:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>if self._should_try_again:<EOL><INDENT>return<EOL><DEDENT>if logger.isEnabledFor(logging.DEBUG):<EOL><INDENT>logger.debug("<STR_LIT:=>" * <NUM_LIT:10>)<EOL>for register in self._cpu.canonical_registers:<EOL><INDENT>logger.debug(<EOL>f"<STR_LIT>"<EOL>f"<STR_LIT>"<EOL>f"<STR_LIT>"<EOL>)<EOL><DEDENT>logger.debug("<STR_LIT:>>" * <NUM_LIT:10>)<EOL><DEDENT>for reg in registers:<EOL><INDENT>val = self._emu.reg_read(self._to_unicorn_id(reg))<EOL>self._cpu.write_register(reg, val)<EOL><DEDENT>mu_pc = self.get_unicorn_pc()<EOL>if saved_PC == mu_pc:<EOL><INDENT>self._cpu.PC = saved_PC + instruction.size<EOL><DEDENT>if self._to_raise:<EOL><INDENT>raise self._to_raise<EOL><DEDENT>return<EOL>

A single attempt at executing an instruction.


def forward_events_to(self, sink, include_source=False):

assert isinstance(sink, Eventful), f'<STR_LIT>'<EOL>self._forwards[sink] = include_source<EOL>


all_evts = set()<EOL>for cls, evts in cls.__all_events__.items():<EOL><INDENT>all_evts.update(evts)<EOL><DEDENT>return all_evts<EOL>

Return all events that all subclasses have so far registered to publish.


<EOL>while True:<EOL><INDENT>self._should_try_again = False<EOL>self._to_raise = None<EOL>self._step(instruction)<EOL>if not self._should_try_again:<EOL><INDENT>break<EOL><DEDENT><DEDENT>

Wrapper that runs the _step function in a loop while handling exceptions


def update_segment(self, selector, base, size, perms):

logger.info("<STR_LIT>", selector, base, size, perms)<EOL>if selector == <NUM_LIT>:<EOL><INDENT>self.set_fs(base)<EOL><DEDENT>else:<EOL><INDENT>logger.error("<STR_LIT>", selector)<EOL><DEDENT>


logger.debug(f"<STR_LIT>")<EOL>self.sync_unicorn_to_manticore()<EOL>from ..native.cpu.abstractcpu import Syscall<EOL>self._to_raise = Syscall()<EOL>uc.emu_stop()<EOL>

Unicorn hook that transfers control to Manticore so it can execute the syscall


def protect_memory_callback(self, start, size, perms):

logger.info(f"<STR_LIT>")<EOL>self._emu.mem_protect(start, size, convert_permissions(perms))<EOL>

Set memory protections in Unicorn correctly


def hr_size(num, suffix='<STR_LIT:B>') -> str:

for unit in '<STR_LIT>':<EOL><INDENT>if abs(num) < <NUM_LIT>:<EOL><INDENT>return "<STR_LIT>" % (num, unit if unit != '<STR_LIT:U+0020>' else '<STR_LIT>', suffix)<EOL><DEDENT>num /= <NUM_LIT><EOL><DEDENT>return "<STR_LIT>" % (num, '<STR_LIT:Y>', suffix)<EOL>

Human-readable data size
From https://stackoverflow.com/a/1094933
:param num: number of bytes
:param suffix: Optional size specifier
:return: Formatted string