<EOL>base_addr = dest.get_mem_base_addr()<EOL>if dest.mem.base in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>base_addr = cpu.PC<EOL><DEDENT>offset = cpu.read_int(base_addr + dest.get_mem_offset(), <NUM_LIT:16>)<EOL>offset = Operators.ZEXTEND(offset, cpu.address_bit_size)<EOL>cpu.PC += (offset << <NUM_LIT:1>)<EOL>

Table Branch Halfword causes a PC-relative forward branch using a table of single halfword offsets. A base
register provides a pointer to the table, and a second register supplies an index into the table. The branch
length is twice the value of the halfword returned from the table.

:param ARMv7Operand dest: see below; register


if cpu.instruction.usermode:<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>increment = insn_id in (cs.arm.ARM_INS_LDM, cs.arm.ARM_INS_LDMIB)<EOL>after = insn_id in (cs.arm.ARM_INS_LDM, cs.arm.ARM_INS_LDMDA)<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>reg.write(cpu.read_int(address, reg.size))<EOL>if reg.reg in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>cpu._set_mode_by_val(cpu.PC)<EOL>cpu.PC = cpu.PC & ~<NUM_LIT:1><EOL><DEDENT>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>

LDM (Load Multiple) loads a non-empty subset, or possibly all, of the general-purpose registers from
sequential memory locations. It is useful for block loads, stack operations and procedure exit sequences.

:param int insn_id: should be one of ARM_INS_LDM, ARM_INS_LDMIB, ARM_INS_LDMDA, ARM_INS_LDMDB
:param Armv7Operand base: Specifies the base register.
:param list[Armv7Operand] regs:
    Is a list of registers. It specifies the set of registers to be loaded by the LDM instruction.
    The registers are loaded in sequence, the lowest-numbered register from the lowest memory
    address (start_address), through to the highest-numbered register from the highest memory
    address (end_address). If the PC is specified in the register list (opcode bit[15] is set),
    the instruction causes a branch to the address (data) loaded into the PC.

It's technically UNKNOWN if you writeback to a register you loaded into, but we let it slide.


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


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.


Used by the the __kuser_dmb ARM Linux user-space handler. This is a nop
under Manticore's memory and execution model.


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


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


if reg_id >= X86_REG_ENDING:<EOL><INDENT>logger.warning("<STR_LIT>")<EOL>return None<EOL><DEDENT>cs_reg_name = self.cpu.instruction.reg_name(reg_id)<EOL>if cs_reg_name is None or cs_reg_name.lower() == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>return self.cpu._regfile._alias(cs_reg_name.upper())<EOL>

Translates a register ID from the disassembler object into the
register name based on manticore's alias in the register file

:param int reg_id: Register ID


raise NotImplementedError<EOL>

This property encapsulates the operand type.
            It may be one of the following:
                register
                memory
                immediate


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

On a memory operand it returns the effective address


raise NotImplementedError<EOL>

It reads the operand value from the registers or memory


raise NotImplementedError<EOL>

It writes the value of specific type to the registers or memory


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

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

:param str register: The register name


raise NotImplementedError<EOL>

Write value to the specified register

:param str register: a register id. Must be listed on all_registers
:param value: a value of the expected type
:type value: int or long or Expression
:return: the value actually written to the register


raise NotImplementedError<EOL>

Read value from specified register

:param str register: a register name. Must be listed on all_registers
:return: the register value


return tuple(self._aliases)<EOL>

Lists all possible register names (Including aliases)


raise NotImplementedError<EOL>

List the minimal most beautiful set of registers needed


return self._alias(register) in self.all_registers<EOL>

Check for register validity

:param register: a register name


self._cpu = cpu<EOL>

:param manticore.core.cpu.Cpu cpu: CPU to initialize with


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


raise NotImplementedError<EOL>

Write the result of a model back to the environment.

:param result: result of the model implementation


return<EOL>

Handle the "ret" semantics of the ABI, i.e. reclaiming stack space,
popping PC, etc.

A null operation by default.


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


def get_argument_values(self, model, prefix_args):

spec = inspect.getfullargspec(model)<EOL>if spec.varargs:<EOL><INDENT>logger.warning("<STR_LIT>")<EOL><DEDENT>nargs = len(spec.args) - len(prefix_args)<EOL>if inspect.ismethod(model):<EOL><INDENT>nargs -= <NUM_LIT:1><EOL><DEDENT>def resolve_argument(arg):<EOL><INDENT>if isinstance(arg, str):<EOL><INDENT>return self._cpu.read_register(arg)<EOL><DEDENT>else:<EOL><INDENT>return self._cpu.read_int(arg)<EOL><DEDENT><DEDENT>descriptors = self.get_arguments()<EOL>argument_iter = map(resolve_argument, descriptors)<EOL>from ..models import isvariadic  <EOL>if isvariadic(model):<EOL><INDENT>arguments = prefix_args + (argument_iter,)<EOL><DEDENT>else:<EOL><INDENT>arguments = prefix_args + tuple(islice(argument_iter, nargs))<EOL><DEDENT>return arguments<EOL>

Extract arguments for model from the environment and return as a tuple that
is ready to be passed to the model.

:param callable model: Python model of the function
:param tuple prefix_args: Parameters to pass to model before actual ones
:return: Arguments to be passed to the model
:rtype: tuple


def invoke(self, model, prefix_args=None):

prefix_args = prefix_args or ()<EOL>arguments = self.get_argument_values(model, prefix_args)<EOL>try:<EOL><INDENT>result = model(*arguments)<EOL><DEDENT>except ConcretizeArgument as e:<EOL><INDENT>assert e.argnum >= len(prefix_args), "<STR_LIT>"<EOL>idx = e.argnum - len(prefix_args)<EOL>descriptors = self.get_arguments()<EOL>src = next(islice(descriptors, idx, idx + <NUM_LIT:1>))<EOL>msg = '<STR_LIT>'<EOL>if isinstance(src, str):<EOL><INDENT>raise ConcretizeRegister(self._cpu, src, msg)<EOL><DEDENT>else:<EOL><INDENT>raise ConcretizeMemory(self._cpu.memory, src, self._cpu.address_bit_size, msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if result is not None:<EOL><INDENT>self.write_result(result)<EOL><DEDENT>self.ret()<EOL><DEDENT>return result<EOL>

Invoke a callable `model` as if it was a native function. If
:func:`~manticore.models.isvariadic` returns true for `model`, `model` receives a single
argument that is a generator for function arguments. Pass a tuple of
arguments for `prefix_args` you'd like to precede the actual
arguments.

:param callable model: Python model of the function
:param tuple prefix_args: Parameters to pass to model before actual ones
:return: The result of calling `model`


raise NotImplementedError<EOL>

Extract the index of the invoked syscall.

:return: int


return self._regfile<EOL>


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]


return self._regfile.canonical_registers<EOL>

Returns the list of all register names  for this CPU.

:rtype: tuple
:return: the list of register names for this CPU.


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


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

Dynamic interface for reading cpu registers

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


if name != '<STR_LIT>':<EOL><INDENT>if name in self._regfile:<EOL><INDENT>return self.read_register(name)<EOL><DEDENT><DEDENT>raise AttributeError(name)<EOL>

A Pythonic version of read_register

:param str name: Name of the register


try:<EOL><INDENT>if name in self._regfile:<EOL><INDENT>return self.write_register(name, value)<EOL><DEDENT>object.__setattr__(self, name, value)<EOL><DEDENT>except AttributeError:<EOL><INDENT>object.__setattr__(self, name, value)<EOL><DEDENT>

A Pythonic version of write_register

:param str name: Name of the register to set
:param value: The value to set the register to
:type param: int or long or Expression


self._concrete = True<EOL>self._break_unicorn_at = target<EOL>if self.emu:<EOL><INDENT>self.emu._stop_at = target<EOL><DEDENT>

Tells the CPU to set up a concrete unicorn emulator and use it to execute instructions
until target is reached.

:param target: Where Unicorn should hand control back to Manticore. Set to 0 for all instructions.


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


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


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_bytes(self, where, data, force=False):

mp = self.memory.map_containing(where)<EOL>can_write_raw = type(mp) is AnonMap andisinstance(data, (str, bytes)) and(mp.end - mp.start + <NUM_LIT:1>) >= len(data) >= <NUM_LIT> andnot issymbolic(data) andself._concrete<EOL>if can_write_raw:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>offset = mp._get_offset(where)<EOL>if isinstance(data, str):<EOL><INDENT>data = bytes(data.encode('<STR_LIT:utf-8>'))<EOL><DEDENT>mp._data[offset:offset + len(data)] = data<EOL>self._publish('<STR_LIT>', where, data, <NUM_LIT:8> * len(data))<EOL><DEDENT>else:<EOL><INDENT>for i in range(len(data)):<EOL><INDENT>self.write_int(where + i, Operators.ORD(data[i]), <NUM_LIT:8>, force)<EOL><DEDENT><DEDENT>

Write a concrete or symbolic (or mixed) buffer to memory

:param int where: address to write to
:param data: data to write
:type data: str or list
:param force: whether to ignore memory permissions


def read_bytes(self, where, size, force=False):

result = []<EOL>for i in range(size):<EOL><INDENT>result.append(Operators.CHR(self.read_int(where + i, <NUM_LIT:8>, force)))<EOL><DEDENT>return result<EOL>

Read from memory.

:param int where: address to read data from
:param int size: number of bytes
:param force: whether to ignore memory permissions
:return: data
:rtype: list[int or Expression]


def write_string(self, where, string, max_length=None, force=False):

if max_length is not None:<EOL><INDENT>string = string[:max_length - <NUM_LIT:1>]<EOL><DEDENT>self.write_bytes(where, string + '<STR_LIT:\x00>', force)<EOL>

Writes a string to memory, appending a NULL-terminator at the end.
:param int where: Address to write the string to
:param str string: The string to write to memory
:param int max_length:
    The size in bytes to cap the string at, or None [default] for no
    limit. This includes the NULL terminator.
:param force: whether to ignore memory permissions


def read_string(self, where, max_length=None, force=False):

s = io.BytesIO()<EOL>while True:<EOL><INDENT>c = self.read_int(where, <NUM_LIT:8>, force)<EOL>if issymbolic(c) or c == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>if max_length is not None:<EOL><INDENT>if max_length == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT>max_length = max_length - <NUM_LIT:1><EOL><DEDENT>s.write(Operators.CHR(c))<EOL>where += <NUM_LIT:1><EOL><DEDENT>return s.getvalue().decode()<EOL>

Read a NUL-terminated concrete buffer from memory. Stops reading at first symbolic byte.

:param int where: Address to read string from
:param int max_length:
    The size in bytes to cap the string at, or None [default] for no
    limit.
:param force: whether to ignore memory permissions
:return: string read
:rtype: str


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


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


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


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


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


<EOL>if pc in self._instruction_cache:<EOL><INDENT>return self._instruction_cache[pc]<EOL><DEDENT>text = b'<STR_LIT>'<EOL>for address in range(pc, pc + self.max_instr_width):<EOL><INDENT>if not self.memory.access_ok(address, '<STR_LIT:x>'):<EOL><INDENT>break<EOL><DEDENT>c = self.memory[address]<EOL>if issymbolic(c):<EOL><INDENT>if isinstance(self.memory, LazySMemory):<EOL><INDENT>try:<EOL><INDENT>vals = visitors.simplify_array_select(c)<EOL>c = bytes([vals[<NUM_LIT:0>]])<EOL><DEDENT>except visitors.ArraySelectSimplifier.ExpressionNotSimple:<EOL><INDENT>c = struct.pack('<STR_LIT:B>', solver.get_value(self.memory.constraints, c))<EOL><DEDENT><DEDENT>elif isinstance(c, Constant):<EOL><INDENT>c = bytes([c.value])<EOL><DEDENT>else:<EOL><INDENT>logger.error('<STR_LIT>', c, text)<EOL>raise ConcretizeMemory(self.memory,<EOL>address=pc,<EOL>size=<NUM_LIT:8> * self.max_instr_width,<EOL>policy='<STR_LIT>')<EOL><DEDENT><DEDENT>text += c<EOL><DEDENT>code = text.ljust(self.max_instr_width, b'<STR_LIT:\x00>')<EOL>try:<EOL><INDENT>insn = self.disasm.disassemble_instruction(code, pc)<EOL><DEDENT>except StopIteration as e:<EOL><INDENT>raise DecodeException(pc, code)<EOL><DEDENT>if not self.memory.access_ok(slice(pc, pc + insn.size), '<STR_LIT:x>'):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>raise InvalidMemoryAccess(pc, '<STR_LIT:x>')<EOL><DEDENT>insn.operands = self._wrap_operands(insn.operands)<EOL>self._instruction_cache[pc] = insn<EOL>return insn<EOL>

This will decode an instruction from memory pointed by `pc`

:param int pc: address of the instruction


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


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.


if self._concrete:<EOL><INDENT>self.concrete_emulate(insn)<EOL><DEDENT>else:<EOL><INDENT>self.backup_emulate(insn)<EOL><DEDENT>

Pick the right emulate function (maintains API compatiblity)

:param insn: single instruction to emulate/start emulation from


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


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.backup_emu = UnicornEmulator(self)<EOL><DEDENT>try:<EOL><INDENT>self.backup_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>finally:<EOL><INDENT>del self.backup_emu<EOL><DEDENT>

If we could not handle emulating an instruction, use Unicorn to emulate
it.

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


result = f'<STR_LIT>'<EOL>result += '<STR_LIT:\n>'.join(self.render_registers())<EOL>return result<EOL>

Returns a string representation of cpu state

:rtype: str
:return: name and current value for all the registers.


@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


def disassemble_instruction(self, code, pc):

return next(self.disasm.disasm(code, pc))<EOL>

Get next instruction using the Capstone disassembler

        :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


setattr(func, VARIADIC_FUNC_ATTR, True)<EOL>return func<EOL>

A decorator used to mark a function model as variadic. This function should
take two parameters: a :class:`~manticore.native.state.State` object, and
a generator object for the arguments.

:param callable func: Function model


offset = <NUM_LIT:0><EOL>while True:<EOL><INDENT>byt = cpu.read_int(ptr + offset, <NUM_LIT:8>)<EOL>if issymbolic(byt):<EOL><INDENT>if not solver.can_be_true(constrs, byt != <NUM_LIT:0>):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if byt == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>offset += <NUM_LIT:1><EOL><DEDENT>return offset<EOL>

Helper for finding the closest NULL or, effectively NULL byte from a starting address.

:param Cpu cpu:
:param ConstraintSet constrs: Constraints for current `State`
:param int ptr: Address to start searching for a zero from
:return: Offset from `ptr` to first byte that is 0 or an `Expression` that must be zero


cpu = state.cpu<EOL>if issymbolic(s1):<EOL><INDENT>raise ConcretizeArgument(state.cpu, <NUM_LIT:1>)<EOL><DEDENT>if issymbolic(s2):<EOL><INDENT>raise ConcretizeArgument(state.cpu, <NUM_LIT:2>)<EOL><DEDENT>s1_zero_idx = _find_zero(cpu, state.constraints, s1)<EOL>s2_zero_idx = _find_zero(cpu, state.constraints, s2)<EOL>min_zero_idx = min(s1_zero_idx, s2_zero_idx)<EOL>ret = None<EOL>for offset in range(min_zero_idx, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>s1char = ZEXTEND(cpu.read_int(s1 + offset, <NUM_LIT:8>), cpu.address_bit_size)<EOL>s2char = ZEXTEND(cpu.read_int(s2 + offset, <NUM_LIT:8>), cpu.address_bit_size)<EOL>if issymbolic(s1char) or issymbolic(s2char):<EOL><INDENT>if ret is None or (not issymbolic(ret) and ret == <NUM_LIT:0>):<EOL><INDENT>ret = s1char - s2char<EOL><DEDENT>else:<EOL><INDENT>ret = ITEBV(cpu.address_bit_size, s1char != s2char, s1char - s2char, ret)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if s1char != s2char:<EOL><INDENT>ret = s1char - s2char<EOL><DEDENT>elif ret is None:<EOL><INDENT>ret = <NUM_LIT:0><EOL><DEDENT><DEDENT><DEDENT>return ret<EOL>

strcmp symbolic model.

Algorithm: Walks from end of string (minimum offset to NULL in either string)
to beginning building tree of ITEs each time either of the
bytes at current offset is symbolic.

Points of Interest:
- We've been building up a symbolic tree but then encounter two
  concrete bytes that differ. We can throw away the entire symbolic
  tree!
- If we've been encountering concrete bytes that match
  at the end of the string as we walk forward, and then we encounter
  a pair where one is symbolic, we can forget about that 0 `ret` we've
  been tracking and just replace it with the symbolic subtraction of
  the two

:param State state: Current program state
:param int s1: Address of string 1
:param int s2: Address of string 2
:return: Symbolic strcmp result
:rtype: Expression or int


cpu = state.cpu<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


def __init__(self, initial_state, workspace_url=None, policy='<STR_LIT>', **kwargs):

super().__init__()<EOL>if isinstance(workspace_url, str):<EOL><INDENT>if '<STR_LIT::>' not in workspace_url:<EOL><INDENT>ws_path = f'<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>ws_path = workspace_url<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if workspace_url is not None:<EOL><INDENT>raise TypeError(f'<STR_LIT>')<EOL><DEDENT>ws_path = None<EOL><DEDENT>self._output = ManticoreOutput(ws_path)<EOL>self._context = {}<EOL>self._last_run_stats = {}<EOL>self._hooks = {}<EOL>self._executor = Executor(store=self._output.store, policy=policy)<EOL>self._workers = []<EOL>self.plugins = set()<EOL>self.forward_events_from(self._executor)<EOL>if not isinstance(initial_state, StateBase):<EOL><INDENT>raise TypeError(f'<STR_LIT>')<EOL><DEDENT>self._initial_state = initial_state<EOL>self._executor.forward_events_from(self._initial_state, True)<EOL>self._assertions = {}<EOL>self._coverage_file = None<EOL>self.trace = None<EOL>self.subscribe('<STR_LIT>', self._did_finish_run_callback)<EOL>self.subscribe('<STR_LIT>', self._publish_generate_testcase)<EOL>

:param initial_state: State to start from.
:param workspace_url: workspace folder name
:param policy: scheduling policy
:param kwargs: other kwargs, e.g.


if self._context is not None:<EOL><INDENT>return self._context<EOL><DEDENT>else:<EOL><INDENT>logger.warning("<STR_LIT>")<EOL>return self._executor._shared_context<EOL><DEDENT>


@contextmanager<EOL><INDENT>def locked_context(self, key=None, value_type=list):<DEDENT>

@contextmanager<EOL>def _real_context():<EOL><INDENT>if self._context is not None:<EOL><INDENT>yield self._context<EOL><DEDENT>else:<EOL><INDENT>with self._executor.locked_context() as context:<EOL><INDENT>yield context<EOL><DEDENT><DEDENT><DEDENT>with _real_context() as context:<EOL><INDENT>if key is None:<EOL><INDENT>yield context<EOL><DEDENT>else:<EOL><INDENT>assert value_type in (list, dict, set)<EOL>ctx = context.get(key, value_type())<EOL>yield ctx<EOL>context[key] = ctx<EOL><DEDENT><DEDENT>

A context manager that provides safe parallel access to the global Manticore context.
This should be used to access the global Manticore context
when parallel analysis is activated. Code within the `with` block is executed
atomically, so access of shared variables should occur within.

Example use::

    with m.locked_context() as context:
        visited = context['visited']
        visited.append(state.cpu.PC)
        context['visited'] = visited

Optionally, parameters can specify a key and type for the object paired to this key.::

    with m.locked_context('feature_list', list) as feature_list:
        feature_list.append(1)

:param object key: Storage key
:param value_type: type of value associated with key
:type value_type: list or dict or set


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.


assert not self.running, "<STR_LIT>"<EOL>self._executor.enqueue(state)<EOL>

Dynamically enqueue states. Users should typically not need to do this


profile_file_path = os.path.join(self.workspace, '<STR_LIT>')<EOL>try:<EOL><INDENT>return pstats.Stats(profile_file_path)<EOL><DEDENT>except Exception as e:<EOL><INDENT>logger.debug(f'<STR_LIT>')<EOL>return None<EOL><DEDENT>

Returns a pstat.Stats instance with profiling results if `run` was called with `should_profile=True`.
Otherwise, returns `None`.


def run(self, procs=<NUM_LIT:1>, timeout=None, should_profile=False):

assert not self.running, "<STR_LIT>"<EOL>self._start_run()<EOL>self._last_run_stats['<STR_LIT>'] = time.time()<EOL>with self.shutdown_timeout(timeout):<EOL><INDENT>self._start_workers(procs, profiling=should_profile)<EOL>self._join_workers()<EOL><DEDENT>self._finish_run(profiling=should_profile)<EOL>

Runs analysis.

:param int procs: Number of parallel worker processes
:param timeout: Analysis timeout, in seconds


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


return self._executor.is_shutdown()<EOL>


if isinstance(constraint, bool):<EOL><INDENT>constraint = BoolConstant(constraint)<EOL><DEDENT>assert isinstance(constraint, Bool)<EOL>constraint = simplify(constraint)<EOL>if self._child is not None:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if isinstance(constraint, BoolConstant):<EOL><INDENT>if not constraint.value:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>self._constraints = [constraint]<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>self._constraints.append(constraint)<EOL>if check:<EOL><INDENT>from ...core.smtlib import solver<EOL>if not solver.check(self):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>

Add a constraint to the set

:param constraint: The constraint to add to the set.
:param check: Currently unused.
:return:


assert self._child is None<EOL>self._sid += <NUM_LIT:1><EOL>return self._sid<EOL>


if var.name in self._declarations:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._declarations[var.name] = var<EOL>return var<EOL>


return self._declarations.values()<EOL>

Returns the variable expressions of this constraint set


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

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


declarations = GetDeclarations()<EOL>for a in self.constraints:<EOL><INDENT>try:<EOL><INDENT>declarations.visit(a)<EOL><DEDENT>except RuntimeError:<EOL><INDENT>if sys.getrecursionlimit() >= PickleSerializer.MAX_RECURSION:<EOL><INDENT>raise Exception(f'<STR_LIT>')<EOL><DEDENT>new_limit = sys.getrecursionlimit() + PickleSerializer.DEFAULT_RECURSION<EOL>if new_limit <= PickleSerializer.DEFAULT_RECURSION:<EOL><INDENT>sys.setrecursionlimit(new_limit)<EOL>return self.declarations<EOL><DEDENT><DEDENT><DEDENT>return declarations.result<EOL>


if self._parent is not None:<EOL><INDENT>return tuple(self._constraints) + self._parent.constraints<EOL><DEDENT>return tuple(self._constraints)<EOL>

:rtype tuple
:return: All constraints represented by this and parent sets.


return self.to_string()<EOL>

Returns a smtlib representation of the current state


<EOL>while name in self._declarations:<EOL><INDENT>name = f'<STR_LIT>'<EOL><DEDENT>return name<EOL>


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


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


def new_bool(self, name=None, taint=frozenset(), avoid_collisions=False):

if name is None:<EOL><INDENT>name = '<STR_LIT:B>'<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 = BoolVariable(name, taint=taint)<EOL>return self._declare(var)<EOL>

Declares a free symbolic boolean in the constraint store
            :param name: try to assign name to internal variable representation,
                         if not unique, a numeric nonce will be appended
            :param avoid_collisions: potentially avoid_collisions the variable to avoid name collisions if True
            :return: a fresh BoolVariable


def new_bitvec(self, size, name=None, taint=frozenset(), avoid_collisions=False):

if not (size == <NUM_LIT:1> or size % <NUM_LIT:8> == <NUM_LIT:0>):<EOL><INDENT>raise Exception(f'<STR_LIT>')<EOL><DEDENT>if name is None:<EOL><INDENT>name = '<STR_LIT>'<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 = BitVecVariable(size, name, taint=taint)<EOL>return self._declare(var)<EOL>

Declares a free symbolic bitvector in the constraint store
            :param size: size in bits for the bitvector
            :param name: try to assign name to internal variable representation,
                         if not unique, a numeric nonce will be appended
            :param avoid_collisions: potentially avoid_collisions the variable to avoid name collisions if True
            :return: a fresh BitVecVariable


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


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


return self.can_be_true(constraints, True)<EOL>


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

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

Check if given expression could be valid


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

solutions = self.get_all_values(constraints, expression, maxcnt=<NUM_LIT:2>, silent=True)<EOL>return solutions == [True]<EOL>

Check if expression is True and that it can not be False with current constraints


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


def get_value(self, constraints, expression):

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

Ask the solver for one possible result of given expression using given set of constraints.


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

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

Iteratively finds the maximum value for a symbol within given constraints.
:param X: a symbol or expression
:param M: maximum number of iterations allowed


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

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


def minmax(self, constraints, x, iters=<NUM_LIT>):

if issymbolic(x):<EOL><INDENT>m = self.min(constraints, x, iters)<EOL>M = self.max(constraints, x, iters)<EOL>return m, M<EOL><DEDENT>else:<EOL><INDENT>return x, x<EOL><DEDENT>

Returns the min and max possible values for x within given constraints


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


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'


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>


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)


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


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


buf, left, right = self.__readline_and_count()<EOL>bufl = [buf]<EOL>while left != right:<EOL><INDENT>buf, l, r = self.__readline_and_count()<EOL>bufl.append(buf)<EOL>left += l<EOL>right += r<EOL><DEDENT>buf = '<STR_LIT>'.join(bufl).strip()<EOL>logger.debug('<STR_LIT>', buf)<EOL>if '<STR_LIT>' in bufl[<NUM_LIT:0>]:<EOL><INDENT>raise Exception(f"<STR_LIT>")<EOL><DEDENT>return buf<EOL>


logger.debug("<STR_LIT>")<EOL>start = time.time()<EOL>self._send('<STR_LIT>')<EOL>status = self._recv()<EOL>logger.debug("<STR_LIT>", time.time() - start, status)<EOL>if status not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise SolverError(status)<EOL><DEDENT>if consider_unknown_as_unsat:<EOL><INDENT>if status == '<STR_LIT>':<EOL><INDENT>logger.info('<STR_LIT>')<EOL>status = '<STR_LIT>'<EOL><DEDENT><DEDENT>if status == '<STR_LIT>':<EOL><INDENT>raise SolverUnknown(status)<EOL><DEDENT>return status == '<STR_LIT>'<EOL>

Check the satisfiability of the current state

:return: whether current state is satisfiable or not.


assert isinstance(expression, Bool)<EOL>smtlib = translate_to_smtlib(expression)<EOL>self._send('<STR_LIT>' % smtlib)<EOL>


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


Pushes and save the current constraint store and state.


Recall the last pushed constraint store and state.


def can_be_true(self, constraints, expression):

if isinstance(expression, bool):<EOL><INDENT>if not expression:<EOL><INDENT>return expression<EOL><DEDENT>else:<EOL><INDENT>self._reset(constraints)<EOL>return self._is_sat()<EOL><DEDENT><DEDENT>assert isinstance(expression, Bool)<EOL>with constraints as temp_cs:<EOL><INDENT>temp_cs.add(expression)<EOL>self._reset(temp_cs.to_string(related_to=expression))<EOL>return self._is_sat()<EOL><DEDENT>

Check if two potentially symbolic values can be equal


def get_all_values(self, constraints, expression, maxcnt=None, silent=False):

if not isinstance(expression, Expression):<EOL><INDENT>return [expression]<EOL><DEDENT>assert isinstance(constraints, ConstraintSet)<EOL>assert isinstance(expression, Expression)<EOL>expression = simplify(expression)<EOL>if maxcnt is None:<EOL><INDENT>maxcnt = consts.maxsolutions<EOL><DEDENT>with constraints as temp_cs:<EOL><INDENT>if isinstance(expression, Bool):<EOL><INDENT>var = temp_cs.new_bool()<EOL><DEDENT>elif isinstance(expression, BitVec):<EOL><INDENT>var = temp_cs.new_bitvec(expression.size)<EOL><DEDENT>elif isinstance(expression, Array):<EOL><INDENT>var = temp_cs.new_array(index_max=expression.index_max, value_bits=expression.value_bits, taint=expression.taint).array<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError(f"<STR_LIT>")<EOL><DEDENT>temp_cs.add(var == expression)<EOL>self._reset(temp_cs.to_string(related_to=var))<EOL>result = []<EOL>while self._is_sat():<EOL><INDENT>value = self._getvalue(var)<EOL>result.append(value)<EOL>self._assert(var != value)<EOL>if len(result) >= maxcnt:<EOL><INDENT>if silent:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>raise TooManySolutions(result)<EOL><DEDENT><DEDENT><DEDENT>return result<EOL><DEDENT>


def optimize(self, constraints: ConstraintSet, x: BitVec, goal: str, M=<NUM_LIT>):

assert goal in ('<STR_LIT>', '<STR_LIT>')<EOL>assert isinstance(x, BitVec)<EOL>operation = {'<STR_LIT>': Operators.UGE, '<STR_LIT>': Operators.ULE}[goal]<EOL>with constraints as temp_cs:<EOL><INDENT>X = temp_cs.new_bitvec(x.size)<EOL>temp_cs.add(X == x)<EOL>aux = temp_cs.new_bitvec(X.size, name='<STR_LIT>')<EOL>self._reset(temp_cs.to_string(related_to=X))<EOL>self._send(aux.declaration)<EOL>if getattr(self, f'<STR_LIT>'):<EOL><INDENT>self._push()<EOL>try:<EOL><INDENT>self._assert(operation(X, aux))<EOL>self._send('<STR_LIT>' % (goal, aux.name))<EOL>self._send('<STR_LIT>')<EOL>_status = self._recv()<EOL>if _status not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>maybe_sat = self._recv()<EOL>if maybe_sat == '<STR_LIT>':<EOL><INDENT>m = RE_MIN_MAX_OBJECTIVE_EXPR_VALUE.match(_status)<EOL>expr, value = m.group('<STR_LIT>'), m.group('<STR_LIT:value>')<EOL>assert expr == aux.name<EOL>return int(value)<EOL><DEDENT><DEDENT>elif _status == '<STR_LIT>':<EOL><INDENT>ret = self._recv()<EOL>if not (ret.startswith('<STR_LIT:(>') and ret.endswith('<STR_LIT:)>')):<EOL><INDENT>raise SolverError('<STR_LIT>')<EOL><DEDENT>m = RE_OBJECTIVES_EXPR_VALUE.match(ret)<EOL>expr, value = m.group('<STR_LIT>'), m.group('<STR_LIT:value>')<EOL>assert expr == aux.name<EOL>return int(value)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self._pop()<EOL>self._reset(temp_cs)<EOL>self._send(aux.declaration)<EOL><DEDENT><DEDENT>operation = {'<STR_LIT>': Operators.UGT, '<STR_LIT>': Operators.ULT}[goal]<EOL>self._assert(aux == X)<EOL>last_value = None<EOL>i = <NUM_LIT:0><EOL>while self._is_sat():<EOL><INDENT>last_value = self._getvalue(aux)<EOL>self._assert(operation(aux, last_value))<EOL>i = i + <NUM_LIT:1><EOL>if i > M:<EOL><INDENT>raise SolverError("<STR_LIT>")<EOL><DEDENT><DEDENT>if last_value is not None:<EOL><INDENT>return last_value<EOL><DEDENT>raise SolverError("<STR_LIT>")<EOL><DEDENT>

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

:param constraints: constraints to take into account
:param x: a symbol or expression
:param goal: goal to achieve, either 'maximize' or 'minimize'
:param M: maximum number of iterations allowed


if not issymbolic(expression):<EOL><INDENT>return expression<EOL><DEDENT>assert isinstance(expression, (Bool, BitVec, Array))<EOL>with constraints as temp_cs:<EOL><INDENT>if isinstance(expression, Bool):<EOL><INDENT>var = temp_cs.new_bool()<EOL><DEDENT>elif isinstance(expression, BitVec):<EOL><INDENT>var = temp_cs.new_bitvec(expression.size)<EOL><DEDENT>elif isinstance(expression, Array):<EOL><INDENT>var = []<EOL>result = []<EOL>for i in range(expression.index_max):<EOL><INDENT>subvar = temp_cs.new_bitvec(expression.value_bits)<EOL>var.append(subvar)<EOL>temp_cs.add(subvar == simplify(expression[i]))<EOL><DEDENT>self._reset(temp_cs)<EOL>if not self._is_sat():<EOL><INDENT>raise SolverError('<STR_LIT>')<EOL><DEDENT>for i in range(expression.index_max):<EOL><INDENT>self._send('<STR_LIT>' % var[i].name)<EOL>ret = self._recv()<EOL>assert ret.startswith('<STR_LIT>') and ret.endswith('<STR_LIT>')<EOL>pattern, base = self._get_value_fmt<EOL>m = pattern.match(ret)<EOL>expr, value = m.group('<STR_LIT>'), m.group('<STR_LIT:value>')<EOL>result.append(int(value, base))<EOL><DEDENT>return bytes(result)<EOL><DEDENT>temp_cs.add(var == expression)<EOL>self._reset(temp_cs)<EOL><DEDENT>if not self._is_sat():<EOL><INDENT>raise SolverError('<STR_LIT>')<EOL><DEDENT>self._send('<STR_LIT>' % var.name)<EOL>ret = self._recv()<EOL>if not (ret.startswith('<STR_LIT>') and ret.endswith('<STR_LIT>')):<EOL><INDENT>raise SolverError('<STR_LIT>' % ret)<EOL><DEDENT>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>if 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>raise NotImplementedError("<STR_LIT>")<EOL>


value = simplify(expression)<EOL>if isinstance(value, Expression) and value.taint:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if isinstance(value, Constant):<EOL><INDENT>return value.value<EOL><DEDENT>elif isinstance(value, Array):<EOL><INDENT>if expression.index_max:<EOL><INDENT>ba = bytearray()<EOL>for i in range(expression.index_max):<EOL><INDENT>value_i = simplify(value[i])<EOL>if not isinstance(value_i, Constant):<EOL><INDENT>break<EOL><DEDENT>ba.append(value_i.value)<EOL><DEDENT>else:<EOL><INDENT>return bytes(ba)<EOL><DEDENT>return expression<EOL><DEDENT><DEDENT>return value<EOL>

Iff the expression can be simplified to a Constant get the actual concrete value.
This discards/ignore any taint


def visit(self, node, use_fixed_point=False):

cache = self._cache<EOL>visited = set()<EOL>stack = []<EOL>stack.append(node)<EOL>while stack:<EOL><INDENT>node = stack.pop()<EOL>if node in cache:<EOL><INDENT>self.push(cache[node])<EOL><DEDENT>elif isinstance(node, Operation):<EOL><INDENT>if node in visited:<EOL><INDENT>operands = [self.pop() for _ in range(len(node.operands))]<EOL>value = self._method(node, *operands)<EOL>visited.remove(node)<EOL>self.push(value)<EOL>cache[node] = value<EOL><DEDENT>else:<EOL><INDENT>visited.add(node)<EOL>stack.append(node)<EOL>stack.extend(node.operands)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.push(self._method(node))<EOL><DEDENT><DEDENT>if use_fixed_point:<EOL><INDENT>old_value = None<EOL>new_value = self.pop()<EOL>while old_value is not new_value:<EOL><INDENT>self.visit(new_value)<EOL>old_value = new_value<EOL>new_value = self.pop()<EOL><DEDENT>self.push(new_value)<EOL><DEDENT>

The entry point of the visitor.
The exploration algorithm is a DFS post-order traversal
The implementation used two stacks instead of a recursion
The final result is store in self.result

:param node: Node to explore
:type node: Expression
:param use_fixed_point: if True, it runs _methods until a fixed point is found
:type use_fixed_point: Bool


Overload Visitor.visit because:
- We need a pre-order traversal
- We use a recursion as it makes it easier to keep track of the indentation


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_Operation(self, expression, *operands):

operation = self.operations.get(type(expression), None)<EOL>if operation is not None andall(isinstance(o, Constant) for o in operands):<EOL><INDENT>value = operation(*(x.value for x in operands))<EOL>if isinstance(expression, BitVec):<EOL><INDENT>return BitVecConstant(expression.size, value, taint=expression.taint)<EOL><DEDENT>else:<EOL><INDENT>isinstance(expression, Bool)<EOL>return BoolConstant(value, taint=expression.taint)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if any(operands[i] is not expression.operands[i] for i in range(len(operands))):<EOL><INDENT>expression = self._rebuild(expression, operands)<EOL><DEDENT><DEDENT>return expression<EOL>

constant folding, if all operands of an expression are a Constant do the math


if all(isinstance(o, Constant) for o in operands):<EOL><INDENT>expression = constant_folder(expression)<EOL><DEDENT>if self._changed(expression, operands):<EOL><INDENT>expression = self._rebuild(expression, operands)<EOL><DEDENT>return expression<EOL>


def visit_BitVecConcat(self, expression, *operands):

op = expression.operands[<NUM_LIT:0>]<EOL>value = None<EOL>end = None<EOL>begining = None<EOL>for o in operands:<EOL><INDENT>if not isinstance(o, BitVecExtract):<EOL><INDENT>return None<EOL><DEDENT>if value is None:<EOL><INDENT>value = o.value<EOL>begining = o.begining<EOL>end = o.end<EOL><DEDENT>else:<EOL><INDENT>if value is not o.value:<EOL><INDENT>return None<EOL><DEDENT>if begining != o.end + <NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>begining = o.begining<EOL><DEDENT><DEDENT>if value is not None:<EOL><INDENT>if end + <NUM_LIT:1> == value.size and begining == <NUM_LIT:0>:<EOL><INDENT>return value<EOL><DEDENT>else:<EOL><INDENT>return BitVecExtract(value, begining, end - begining + <NUM_LIT:1>, taint=expression.taint)<EOL><DEDENT><DEDENT>

concat( extract(k1, 0, a), extract(sizeof(a)-k1, k1, a))  ==> a
            concat( extract(k1, beg, a), extract(end, k1, a))  ==> extract(beg, end, a)


def visit_BitVecExtract(self, expression, *operands):

op = expression.operands[<NUM_LIT:0>]<EOL>begining = expression.begining<EOL>end = expression.end<EOL>size = end - begining + <NUM_LIT:1><EOL>if begining == <NUM_LIT:0> and end + <NUM_LIT:1> == op.size:<EOL><INDENT>return op<EOL><DEDENT>elif isinstance(op, BitVecExtract):<EOL><INDENT>return BitVecExtract(op.value, op.begining + begining, size, taint=expression.taint)<EOL><DEDENT>elif isinstance(op, BitVecConcat):<EOL><INDENT>new_operands = []<EOL>bitcount = <NUM_LIT:0><EOL>for item in reversed(op.operands):<EOL><INDENT>if begining >= item.size:<EOL><INDENT>begining -= item.size<EOL><DEDENT>else:<EOL><INDENT>if bitcount < expression.size:<EOL><INDENT>new_operands.append(item)<EOL><DEDENT>bitcount += item.size<EOL><DEDENT><DEDENT>if begining != expression.begining:<EOL><INDENT>return BitVecExtract(BitVecConcat(sum([x.size for x in new_operands]), *reversed(new_operands)),<EOL>begining, expression.size, taint=expression.taint)<EOL><DEDENT><DEDENT>if isinstance(op, (BitVecAnd, BitVecOr, BitVecXor)):<EOL><INDENT>bitoperand_a, bitoperand_b = op.operands<EOL>return op.__class__(BitVecExtract(bitoperand_a, begining, expression.size), BitVecExtract(bitoperand_b, begining, expression.size), taint=expression.taint)<EOL><DEDENT>

extract(sizeof(a), 0)(a)  ==> a
            extract(16, 0)( concat(a,b,c,d) ) => concat(c, d)
            extract(m,M)(and/or/xor a b ) => and/or/xor((extract(m,M) a) (extract(m,M) a)


def visit_BitVecAdd(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><DEDENT>if isinstance(left, BitVecConstant):<EOL><INDENT>if left.value == <NUM_LIT:0>:<EOL><INDENT>return right<EOL><DEDENT><DEDENT>


def visit_BitVecSub(self, expression, *operands):

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


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


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 |


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_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


stop, start = index.stop, index.start<EOL>if start is None:<EOL><INDENT>start = <NUM_LIT:0><EOL><DEDENT>if stop is None:<EOL><INDENT>stop = len(self)<EOL><DEDENT>return start, stop<EOL>


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>


type_, uri = ('<STR_LIT>', None) if desc is None else desc.split('<STR_LIT::>', <NUM_LIT:1>)<EOL>for subclass in cls.__subclasses__():<EOL><INDENT>if subclass.store_type == type_:<EOL><INDENT>return subclass(uri)<EOL><DEDENT><DEDENT>raise NotImplementedError(f"<STR_LIT>")<EOL>

Create a :class:`~manticore.core.workspace.Store` instance depending on the descriptor.

Valid descriptors:
  * fs:<path>
  * redis:<hostname>:<port>
  * mem:

:param str desc: Store descriptor
:return: Store instance


with self.save_stream(key) as s:<EOL><INDENT>s.write(value)<EOL><DEDENT>

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:


def load_value(self, key, binary=False):

with self.load_stream(key, binary=binary) as s:<EOL><INDENT>return s.read()<EOL><DEDENT>

Load an arbitrary value identified by `key`.

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


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

s = io.BytesIO() if binary else io.StringIO()<EOL>yield s<EOL>self.save_value(key, s.getvalue())<EOL>

Return a managed file-like object into which the calling code can write
arbitrary data.

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


@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


with self.save_stream(key, binary=True) as f:<EOL><INDENT>self._serializer.serialize(state, f)<EOL><DEDENT>

Save a state to storage.

:param manticore.core.StateBase state:
:param str key:
:return:


with self.load_stream(key, binary=True) as f:<EOL><INDENT>state = self._serializer.deserialize(f)<EOL>if delete:<EOL><INDENT>self.rm(key)<EOL><DEDENT>return state<EOL><DEDENT>

Load a state from storage.

:param key: key that identifies state
:rtype: manticore.core.StateBase


raise NotImplementedError<EOL>

Remove value identified by `key` from storage.

:param str key: What to remove


raise NotImplementedError<EOL>


if not uri:<EOL><INDENT>uri = os.path.abspath(tempfile.mkdtemp(prefix=consts.prefix, dir=consts.dir))<EOL><DEDENT>if os.path.exists(uri):<EOL><INDENT>assert os.path.isdir(uri), '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>os.mkdir(uri)<EOL><DEDENT>super().__init__(uri)<EOL>

:param uri: The path to on-disk workspace, or None.


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:


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

:param str key: name of stream to load
:param bool binary: Whether we should treat it as binary
: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


path = os.path.join(self.uri, glob_str)<EOL>return [os.path.split(s)[<NUM_LIT:1>] for s in glob.glob(path)]<EOL>

Return just the filenames that match `glob_str` inside the store directory.

:param str glob_str: A glob string, i.e. 'state_*'
:return: list of matched keys


<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>


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


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


id_ = self._last_id.value<EOL>self._last_id.value += <NUM_LIT:1><EOL>return id_<EOL>


def load_state(self, state_id, delete=True):

return self._store.load_state(f'<STR_LIT>', delete=delete)<EOL>

Load a state from storage identified by `state_id`.

:param state_id: The state reference of what to load
:return: The deserialized state
:rtype: State


def save_state(self, state, state_id=None):

assert isinstance(state, StateBase)<EOL>if state_id is None:<EOL><INDENT>state_id = self._get_id()<EOL><DEDENT>else:<EOL><INDENT>self.rm_state(state_id)<EOL><DEDENT>self._store.save_state(state, f'<STR_LIT>')<EOL>return state_id<EOL>

Save a state to storage, return identifier.

:param state: The state to save
:param int state_id: If not None force the state id potentially overwriting old states
:return: New state id
:rtype: int


return self._store.rm(f'<STR_LIT>')<EOL>

Remove a state from storage identified by `state_id`.

:param state_id: The state reference of what to load


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.


if self._descriptor is None:<EOL><INDENT>self._descriptor = f'<STR_LIT>'<EOL><DEDENT>return self._descriptor<EOL>

Return a descriptor that created this workspace. Descriptors are of the
format <type>:<uri>, where type signifies the medium. For example,
  fs:/tmp/workspace
  redis:127.0.0.1:6379

:rtype: str


@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


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

Constrain state.

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


raise AbandonState<EOL>

Abandon the currently-active state.

        Note: This must be called from the Executor loop, or a :func:`~manticore.Manticore.hook`.


def new_symbolic_buffer(self, nbytes, **options):

label = options.get('<STR_LIT:label>')<EOL>avoid_collisions = False<EOL>if label is None:<EOL><INDENT>label = '<STR_LIT>'<EOL>avoid_collisions = True<EOL><DEDENT>taint = options.get('<STR_LIT>', frozenset())<EOL>expr = self._constraints.new_array(name=label, index_max=nbytes, value_bits=<NUM_LIT:8>, taint=taint, avoid_collisions=avoid_collisions)<EOL>self._input_symbols.append(expr)<EOL>if options.get('<STR_LIT>', False):<EOL><INDENT>for i in range(nbytes - <NUM_LIT:1>):<EOL><INDENT>self._constraints.add(expr[i] != <NUM_LIT:0>)<EOL><DEDENT><DEDENT>return expr<EOL>

Create and return a symbolic buffer of length `nbytes`. The buffer is
        not written into State's memory; write it to the state's memory to
        introduce it into the program state.

        :param int nbytes: Length of the new buffer
        :param str label: (keyword arg only) The label to assign to the buffer
        :param bool cstring: (keyword arg only) Whether or not to enforce that the buffer is a cstring
                 (i.e. no NULL bytes, except for the last byte). (bool)
        :param taint: Taint identifier of the new buffer
        :type taint: tuple or frozenset

        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the buffer.


def new_symbolic_value(self, nbits, label=None, taint=frozenset()):

assert nbits in (<NUM_LIT:1>, <NUM_LIT:4>, <NUM_LIT:8>, <NUM_LIT:16>, <NUM_LIT:32>, <NUM_LIT:64>, <NUM_LIT>, <NUM_LIT>)<EOL>avoid_collisions = False<EOL>if label is None:<EOL><INDENT>label = '<STR_LIT>'<EOL>avoid_collisions = True<EOL><DEDENT>expr = self._constraints.new_bitvec(nbits, name=label, taint=taint, avoid_collisions=avoid_collisions)<EOL>self._input_symbols.append(expr)<EOL>return expr<EOL>

Create and return a symbolic value that is `nbits` bits wide. Assign
        the value to a register or write it into the address space to introduce
        it into the program state.

        :param int nbits: The bitwidth of the value returned
        :param str label: The label to assign to the value
        :param taint: Taint identifier of this value
        :type taint: tuple or frozenset
        :return: :class:`~manticore.core.smtlib.expression.Expression` representing the value


def concretize(self, symbolic, policy, maxcount=<NUM_LIT:7>):

assert self.constraints == self.platform.constraints<EOL>symbolic = self.migrate_expression(symbolic)<EOL>vals = []<EOL>if policy == '<STR_LIT>':<EOL><INDENT>vals = self._solver.minmax(self._constraints, symbolic)<EOL><DEDENT>elif policy == '<STR_LIT>':<EOL><INDENT>vals = self._solver.max(self._constraints, symbolic)<EOL><DEDENT>elif policy == '<STR_LIT>':<EOL><INDENT>vals = self._solver.min(self._constraints, symbolic)<EOL><DEDENT>elif policy == '<STR_LIT>':<EOL><INDENT>m, M = self._solver.minmax(self._constraints, symbolic)<EOL>vals += [m, M]<EOL>if M - m > <NUM_LIT:3>:<EOL><INDENT>if self._solver.can_be_true(self._constraints, symbolic == (m + M) // <NUM_LIT:2>):<EOL><INDENT>vals.append((m + M) // <NUM_LIT:2>)<EOL><DEDENT><DEDENT>if M - m > <NUM_LIT:100>:<EOL><INDENT>for i in (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:5>, <NUM_LIT:32>, <NUM_LIT:64>, <NUM_LIT>, <NUM_LIT>):<EOL><INDENT>if self._solver.can_be_true(self._constraints, symbolic == m + i):<EOL><INDENT>vals.append(m + i)<EOL><DEDENT>if maxcount <= len(vals):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if M - m > <NUM_LIT:1000> and maxcount > len(vals):<EOL><INDENT>vals += self._solver.get_all_values(self._constraints, symbolic,<EOL>maxcnt=maxcount - len(vals), silent=True)<EOL><DEDENT><DEDENT>elif policy == '<STR_LIT>':<EOL><INDENT>vals = [self._solver.get_value(self._constraints, symbolic)]<EOL><DEDENT>else:<EOL><INDENT>assert policy == '<STR_LIT>'<EOL>vals = solver.get_all_values(self._constraints, symbolic, maxcnt=maxcount, silent=True)<EOL><DEDENT>return tuple(set(vals))<EOL>

This finds a set of solutions for symbolic using policy.
            This raises TooManySolutions if more solutions than maxcount


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


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]


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

Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into
its maximum solution

:param manticore.core.smtlib.Expression expr: Symbolic value to solve
:return: Concrete value
:rtype: list[int]


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

Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into
its minimum solution

:param manticore.core.smtlib.Expression expr: Symbolic value to solve
:return: Concrete value
:rtype: list[int]


if isinstance(expr, int):<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_buffer(self, addr, nbytes, constrain=False):

buffer = self.cpu.read_bytes(addr, nbytes)<EOL>result = []<EOL>with self._constraints as temp_cs:<EOL><INDENT>cs_to_use = self.constraints if constrain else temp_cs<EOL>for c in buffer:<EOL><INDENT>result.append(self._solver.get_value(cs_to_use, c))<EOL>cs_to_use.add(c == result[-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>return result<EOL>

Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to
concretize it

:param int address: Address of buffer to concretize
:param int nbytes: Size of buffer to concretize
:param bool constrain: If True, constrain the buffer to the concretized value
:return: Concrete contents of buffer
:rtype: list[int]


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.


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


@contextmanager<EOL><INDENT>def locked_context(self, key=None, value_type=list):<DEDENT>

plugin_context_name = str(type(self))<EOL>with self.manticore.locked_context(plugin_context_name, dict) as context:<EOL><INDENT>assert value_type in (list, dict, set)<EOL>ctx = context.get(key, value_type())<EOL>yield ctx<EOL>context[key] = ctx<EOL><DEDENT>

A context manager that provides safe parallel access to the global Manticore context.
This should be used to access the global Manticore context
when parallel analysis is activated. Code within the `with` block is executed
atomically, so access of shared variables should occur within.


plugin_context_name = str(type(self))<EOL>if plugin_context_name not in self.manticore.context:<EOL><INDENT>self.manticore.context[plugin_context_name] = {}<EOL><DEDENT>return self.manticore.context[plugin_context_name]<EOL>


pass<EOL>

Called by parent manticore on registration


pass<EOL>

Called be parent manticore on un-registration


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


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


def newFunction(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 newFunction<EOL>


@contextmanager<EOL><INDENT>def locked_context(self, key=None, default=dict):<DEDENT>

keys = ['<STR_LIT>']<EOL>if key is not None:<EOL><INDENT>keys.append(key)<EOL><DEDENT>with self._executor.locked_context('<STR_LIT:.>'.join(keys), default) as policy_context:<EOL><INDENT>yield policy_context<EOL><DEDENT>


def _add_state_callback(self, state_id, state):

summary = self.summarize(state)<EOL>if summary is None:<EOL><INDENT>return<EOL><DEDENT>with self.locked_context('<STR_LIT>', dict) as ctx:<EOL><INDENT>ctx[state_id] = summary<EOL><DEDENT>

Save summarize(state) on policy shared context before
            the state is stored


return None<EOL>

Extract the relevant information from a state for later
prioritization


raise NotImplementedError<EOL>

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


def _visited_callback(self, state, pc, instr):

with self.locked_context('<STR_LIT>', set) as ctx:<EOL><INDENT>ctx.add(pc)<EOL><DEDENT>

Maintain our own copy of the visited set


return state.platform.PC<EOL>

Save the last pc before storing the state


pc = state.platform.current.PC<EOL>with self.locked_context('<STR_LIT>', dict) as ctx:<EOL><INDENT>ctx[pc] = ctx.get(pc, <NUM_LIT:0>) + <NUM_LIT:1><EOL><DEDENT>


assert default in (list, dict, set)<EOL>with self._lock:<EOL><INDENT>if key is None:<EOL><INDENT>yield self._shared_context<EOL><DEDENT>else:<EOL><INDENT>sub_context = self._shared_context.get(key, None)<EOL>if sub_context is None:<EOL><INDENT>sub_context = default()<EOL><DEDENT>yield sub_context<EOL>self._shared_context[key] = sub_context<EOL><DEDENT><DEDENT>

Executor context is a shared memory object. All workers share this.
            It needs a lock. Its used like this:

            with executor.context() as context:
                visited = context['visited']
                visited.append(state.cpu.PC)
                context['visited'] = visited


def _register_state_callbacks(self, state, state_id):

<EOL>self.forward_events_from(state, True)<EOL>

Install forwarding callbacks in state so the events can go up.
Going up, we prepend state in the arguments.


<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


return self._running.value<EOL>

Report an estimate  of how many workers are currently running


return self._shutdown.is_set()<EOL>


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


<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>


return list(self._states)<EOL>

Returns the list of states ids currently queued


def fork(self, state, expression, policy='<STR_LIT>', setstate=None):

assert isinstance(expression, Expression)<EOL>if setstate is None:<EOL><INDENT>setstate = lambda x, y: None<EOL><DEDENT>solutions = state.concretize(expression, policy)<EOL>if not solutions:<EOL><INDENT>raise ExecutorError("<STR_LIT>")<EOL><DEDENT>if len(solutions) == <NUM_LIT:1>:<EOL><INDENT>setstate(state, solutions[<NUM_LIT:0>])<EOL>return state<EOL><DEDENT>logger.info("<STR_LIT>",<EOL>policy,<EOL>'<STR_LIT:U+002CU+0020>'.join(f'<STR_LIT>' for sol in solutions))<EOL>self._publish('<STR_LIT>', state, expression, solutions, policy)<EOL>children = []<EOL>for new_value in solutions:<EOL><INDENT>with state as new_state:<EOL><INDENT>new_state.constrain(expression == new_value)<EOL>setstate(new_state, new_value)<EOL>self._publish('<STR_LIT>', new_state, expression, new_value, policy)<EOL>state_id = self.enqueue(new_state)<EOL>children.append(state_id)<EOL><DEDENT><DEDENT>logger.info("<STR_LIT>", children)<EOL>return None<EOL>

Fork state on expression concretizations.
Using policy build a list of solutions for expression.
For the state on each solution setting the new state with setstate

For example if expression is a Bool it may have 2 solutions. True or False.

                         Parent
                    (expression = ??)

           Child1                         Child2
    (expression = True)             (expression = True)
       setstate(True)                   setstate(False)

The optional setstate() function is supposed to set the concrete value
in the child state.


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


<EOL>if re_TYPE.match(t.value):<EOL><INDENT>t.type = '<STR_LIT>'<EOL><DEDENT>elif re_PTR.match(t.value):<EOL><INDENT>t.type = '<STR_LIT>'<EOL><DEDENT>elif re_NUMBER.match(t.value):<EOL><INDENT>if t.value.startswith('<STR_LIT>'):<EOL><INDENT>t.value = t.value[<NUM_LIT:2>:]<EOL><DEDENT>t.value = int(t.value, <NUM_LIT:16>)<EOL>t.type = '<STR_LIT>'<EOL><DEDENT>elif re_REGISTER.match(t.value):<EOL><INDENT>t.type = '<STR_LIT>'<EOL><DEDENT>elif re_SEGMENT.match(t.value):<EOL><INDENT>t.type = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>raise Exception(f"<STR_LIT>")<EOL><DEDENT>return t<EOL>


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


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

expression : expression DIVIDE expression


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>


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>


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


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


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

expression : expression LSHIFT expression


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

expression : expression RSHIFT expression


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


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


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


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


p[<NUM_LIT:0>] = functions['<STR_LIT>'](p[<NUM_LIT:1>])<EOL>


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


p[<NUM_LIT:0>] = p[<NUM_LIT:1>] and 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>


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


<EOL>p[<NUM_LIT:0>] = Operators.ULE(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>


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


Dispatches execution into one of Manticore's engines: evm or native.


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

Return special character denoting concretization happened.


def write_findings(method, lead_space, address, pc, at_init="<STR_LIT>"):

method.write(f'<STR_LIT>')<EOL>method.write(f'<STR_LIT>')<EOL>

Writes contract address and EVM program counter indicating whether counter was read at constructor
:param method: pointer to the object with the write method
:param lead_space: leading white space
:param address: contract address
:param pc: program counter
:param at_init: Boolean
:return: pass


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


def make_symbolic_buffer(self, size, name=None, avoid_collisions=False):

if name is None:<EOL><INDENT>name = '<STR_LIT>'<EOL>avoid_collisions = True<EOL><DEDENT>return self.constraints.new_array(index_bits=<NUM_LIT>, name=name, index_max=size, value_bits=<NUM_LIT:8>, taint=frozenset(), avoid_collisions=avoid_collisions)<EOL>

Creates a symbolic buffer of size bytes 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_data = m.make_symbolic_buffer(320)
                m.constrain(symbolic_data[0] == 0x65)
                m.transaction(caller=attacker_account,
                                address=contract_account,
                                data=symbolic_data,
                                value=100000 )


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 )


def make_symbolic_address(self, name=None, select='<STR_LIT>'):

if select not in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise EthereumError('<STR_LIT>')<EOL><DEDENT>if select in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise NotImplemented<EOL><DEDENT>avoid_collisions = False<EOL>if name is None:<EOL><INDENT>name = '<STR_LIT>'<EOL>avoid_collisions = True<EOL><DEDENT>symbolic_address = self.constraints.new_bitvec(<NUM_LIT>, name=name, avoid_collisions=avoid_collisions)<EOL>constraint = symbolic_address == <NUM_LIT:0><EOL>for account in self._accounts.values():<EOL><INDENT>constraint = Operators.OR(symbolic_address == int(account), constraint)<EOL><DEDENT>self.constrain(constraint)<EOL>return symbolic_address<EOL>

Creates a symbolic address and constrains it to pre-existing addresses or the 0 address.

:param name: Name of the symbolic variable. Defaults to 'TXADDR' and later to 'TXADDR_<number>'
:param select: Whether to select contracts or normal accounts. Not implemented for now.
:return: Symbolic address in form of a BitVecVariable.


@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


@staticmethod<EOL><INDENT>def _run_solc(source_file, solc_bin=None, solc_remaps=[], working_dir=None):<DEDENT>

if solc_bin is not None:<EOL><INDENT>solc = solc_bin<EOL><DEDENT>else:<EOL><INDENT>solc = "<STR_LIT>"<EOL><DEDENT>supported_versions = ('<STR_LIT>', '<STR_LIT>')<EOL>try:<EOL><INDENT>installed_version_output = check_output([solc, "<STR_LIT>"])<EOL><DEDENT>except OSError:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>m = re.match(r"<STR_LIT>", installed_version_output.decode(), re.DOTALL | re.IGNORECASE)<EOL>if not m or m.groupdict()['<STR_LIT:version>'] not in supported_versions:<EOL><INDENT>pass<EOL><DEDENT>relative_filepath = source_file.name<EOL>if not working_dir:<EOL><INDENT>working_dir = os.getcwd()<EOL><DEDENT>if relative_filepath.startswith(working_dir):<EOL><INDENT>relative_filepath = relative_filepath[len(working_dir) + <NUM_LIT:1>:]<EOL><DEDENT>additional_kwargs = {'<STR_LIT>': working_dir} if working_dir else {}<EOL>solc_invocation = [solc] + list(solc_remaps) + [<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:.>',<EOL>relative_filepath<EOL>]<EOL>logger.debug(f"<STR_LIT>")<EOL>p = Popen(solc_invocation, stdout=PIPE, stderr=PIPE, **additional_kwargs)<EOL>stdout, stderr = p.communicate()<EOL>stdout, stderr = stdout.decode(), stderr.decode()<EOL>if stdout == '<STR_LIT>' and f'<STR_LIT>' in stderr:<EOL><INDENT>raise EthereumError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>"<STR_LIT>"<EOL>'<STR_LIT:\n>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(stderr)<EOL>)<EOL><DEDENT>try:<EOL><INDENT>return json.loads(stdout), stderr<EOL><DEDENT>except ValueError:<EOL><INDENT>raise EthereumError('<STR_LIT>'.format(stderr))<EOL><DEDENT>

Compile a source file with the Solidity compiler

            :param source_file: a file object for the source file
            :param solc_bin: path to solc binary
            :param solc_remaps: solc import remaps
            :return: output, warnings