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

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

Compile a Solidity contract, used internally

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


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

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

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


return self.get_world()<EOL>

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


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


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


return self._running_state_ids + self._terminated_state_ids<EOL>

IDs of the all states

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


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

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

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

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


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

Iterates over the terminated states.

See also `running_states`.


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

Iterates over the all states (running and terminated)

See also `running_states`.


return len(self._all_state_ids)<EOL>


return len(self._running_state_ids)<EOL>


return len(self._terminated_state_ids)<EOL>


if state_id != -<NUM_LIT:1>:<EOL><INDENT>with self.locked_context('<STR_LIT>') as eth_context:<EOL><INDENT>saved_states = eth_context['<STR_LIT>']<EOL>final_states = eth_context['<STR_LIT>']<EOL>if state_id in saved_states:<EOL><INDENT>saved_states.remove(state_id)<EOL>final_states.add(state_id)<EOL>eth_context['<STR_LIT>'] = saved_states  <EOL>eth_context['<STR_LIT>'] = final_states<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>assert state_id == -<NUM_LIT:1><EOL>state_id = self.save(self._initial_state, final=True)<EOL>self._initial_state = None<EOL><DEDENT>return state_id<EOL>

Manually terminates a states by state_id.
            Moves the state from the running list into the terminated list


<EOL>if state_id != -<NUM_LIT:1>:<EOL><INDENT>with self.locked_context('<STR_LIT>') as eth_context:<EOL><INDENT>saved_states = eth_context['<STR_LIT>']<EOL>final_states = eth_context['<STR_LIT>']<EOL>if state_id in final_states:<EOL><INDENT>final_states.remove(state_id)<EOL>saved_states.add(state_id)<EOL>eth_context['<STR_LIT>'] = saved_states<EOL>eth_context['<STR_LIT>'] = final_states<EOL><DEDENT><DEDENT><DEDENT>return state_id<EOL>

Manually revive a state by state_id.
            Moves the state from the final list into the running list


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

Returns the evm world of `state_id` state.


def get_balance(self, address, state_id=None):

if isinstance(address, EVMAccount):<EOL><INDENT>address = int(address)<EOL><DEDENT>return self.get_world(state_id).get_balance(address)<EOL>

Balance for account `address` on state `state_id`


def get_storage_data(self, address, offset, state_id=None):

if isinstance(address, EVMAccount):<EOL><INDENT>address = int(address)<EOL><DEDENT>return self.get_world(state_id).get_storage_data(address, offset)<EOL>

Storage data for `offset` on account `address` on state `state_id`


def get_code(self, address, state_id=None):

if isinstance(address, EVMAccount):<EOL><INDENT>address = int(address)<EOL><DEDENT>return self.get_world(state_id).get_code(address)<EOL>


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

Last returned buffer for state `state_id`


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


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


from . import abitypes<EOL>return self._make_symbolic_arguments(abitypes.parse(types))<EOL>

Make a reasonable serialization of the symbolic argument types


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

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


def json_create_contract(self, jfile, owner=None, name=None, contract_name=None, balance=<NUM_LIT:0>, gas=None, network_id=None, args=()):

if isinstance(jfile, io.IOBase):<EOL><INDENT>jfile = jfile.read()<EOL><DEDENT>elif isinstance(jfile, bytes):<EOL><INDENT>jfile = str(jfile, '<STR_LIT:utf-8>')<EOL><DEDENT>elif not isinstance(jfile, str):<EOL><INDENT>raise TypeError(f'<STR_LIT>')<EOL><DEDENT>truffle = json.loads(jfile)<EOL>hashes = {}<EOL>for item in truffle['<STR_LIT>']:<EOL><INDENT>item_type = item['<STR_LIT:type>']<EOL>if item_type in ('<STR_LIT>'):<EOL><INDENT>signature = SolidityMetadata.function_signature_for_name_and_inputs(item['<STR_LIT:name>'], item['<STR_LIT>'])<EOL>hashes[signature] = sha3.keccak_256(signature.encode()).hexdigest()[:<NUM_LIT:8>]<EOL>if '<STR_LIT>' in item:<EOL><INDENT>if item['<STR_LIT>'] != f'<STR_LIT>':<EOL><INDENT>raise Exception(f"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if contract_name is None:<EOL><INDENT>contract_name = truffle["<STR_LIT>"]<EOL><DEDENT>if network_id is None:<EOL><INDENT>if len(truffle['<STR_LIT>']) > <NUM_LIT:1>:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>if len(truffle['<STR_LIT>']) == <NUM_LIT:1>:<EOL><INDENT>network_id = list(truffle['<STR_LIT>'].keys())[<NUM_LIT:0>]<EOL><DEDENT><DEDENT>if network_id in truffle['<STR_LIT>']:<EOL><INDENT>temp_dict = truffle['<STR_LIT>'][network_id]['<STR_LIT>']<EOL>links = dict((k, int(v['<STR_LIT:address>'], <NUM_LIT:0>)) for k, v in temp_dict.items())<EOL><DEDENT>else:<EOL><INDENT>links = ()<EOL><DEDENT>source_code = truffle["<STR_LIT:source>"]<EOL>bytecode = self._link(truffle["<STR_LIT>"][<NUM_LIT:2>:], links)<EOL>runtime = self._link(truffle["<STR_LIT>"][<NUM_LIT:2>:], links)<EOL>if "<STR_LIT>" in truffle:<EOL><INDENT>srcmap = truffle["<STR_LIT>"].split('<STR_LIT:;>')<EOL><DEDENT>else:<EOL><INDENT>srcmap_runtime = []<EOL><DEDENT>if "<STR_LIT>" in truffle:<EOL><INDENT>srcmap_runtime = truffle["<STR_LIT>"].split('<STR_LIT:;>')<EOL><DEDENT>else:<EOL><INDENT>srcmap_runtime = []<EOL><DEDENT>abi = truffle['<STR_LIT>']<EOL>md = SolidityMetadata(contract_name, source_code, bytecode, runtime, srcmap, srcmap_runtime, hashes, abi, b'<STR_LIT>')<EOL>constructor_types = md.get_constructor_arguments()<EOL>if constructor_types != '<STR_LIT>':<EOL><INDENT>if args is None:<EOL><INDENT>args = self.make_symbolic_arguments(constructor_types)<EOL><DEDENT>constructor_data = ABI.serialize(constructor_types, *args)<EOL><DEDENT>else:<EOL><INDENT>constructor_data = b'<STR_LIT>'<EOL><DEDENT>contract_account = self.create_contract(owner=owner,<EOL>balance=balance,<EOL>init=md._init_bytecode + constructor_data,<EOL>gas=gas)<EOL>if contract_account is None:<EOL><INDENT>raise EthereumError(f"<STR_LIT>")<EOL><DEDENT>self.metadata[int(contract_account)] = md<EOL>if not self.count_running_states() or len(self.get_code(contract_account)) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return contract_account<EOL>

Creates a solidity contract based on a truffle json artifact.
            https://github.com/trufflesuite/truffle/tree/develop/packages/truffle-contract-schema
            :param jfile: truffle json artifact
            :type jfile: str or IOBase
            :param owner: owner account (will be default caller in any transactions)
            :type owner: int or EVMAccount
            :param contract_name: Name of the contract to analyze (optional if there is a single one in the source code)
            :type contract_name: str
            :param balance: balance to be transferred on creation
            :type balance: int or BitVecVariable
            :param gas: gas budget for each contract creation needed (may be more than one if several related contracts defined in the solidity source)
            :type gas: int
            :param network_id: Truffle network id to instantiate
            :param tuple args: constructor arguments
            :rtype: EVMAccount


def solidity_create_contract(self, source_code, owner, name=None, contract_name=None, libraries=None,<EOL>balance=<NUM_LIT:0>, address=None, args=(), solc_bin=None, solc_remaps=[],<EOL>working_dir=None, gas=None):

if libraries is None:<EOL><INDENT>deps = {}<EOL><DEDENT>else:<EOL><INDENT>deps = dict(libraries)<EOL><DEDENT>contract_names = [contract_name]<EOL>while contract_names:<EOL><INDENT>contract_name_i = contract_names.pop()<EOL>try:<EOL><INDENT>compile_results = self._compile(source_code, contract_name_i,<EOL>libraries=deps, solc_bin=solc_bin, solc_remaps=solc_remaps,<EOL>working_dir=working_dir)<EOL>md = SolidityMetadata(*compile_results)<EOL>if contract_name_i == contract_name:<EOL><INDENT>constructor_types = md.get_constructor_arguments()<EOL>if constructor_types != '<STR_LIT>':<EOL><INDENT>if args is None:<EOL><INDENT>args = self.make_symbolic_arguments(constructor_types)<EOL><DEDENT>constructor_data = ABI.serialize(constructor_types, *args)<EOL><DEDENT>else:<EOL><INDENT>constructor_data = b'<STR_LIT>'<EOL><DEDENT>if balance != <NUM_LIT:0>:<EOL><INDENT>if not md.constructor_abi['<STR_LIT>']:<EOL><INDENT>raise EthereumError(f"<STR_LIT>"<EOL>f"<STR_LIT>")<EOL><DEDENT>elif self.world.get_balance(owner.address) < balance:<EOL><INDENT>raise EthereumError(f"<STR_LIT>"<EOL>f"<STR_LIT>"<EOL>f"<STR_LIT>")<EOL><DEDENT><DEDENT>contract_account = self.create_contract(owner=owner,<EOL>balance=balance,<EOL>address=address,<EOL>init=md._init_bytecode + constructor_data,<EOL>name=name,<EOL>gas=gas)<EOL><DEDENT>else:<EOL><INDENT>contract_account = self.create_contract(owner=owner, init=md._init_bytecode)<EOL><DEDENT>if contract_account is None:<EOL><INDENT>raise EthereumError("<STR_LIT>" % contract_name_i)<EOL><DEDENT>self.metadata[int(contract_account)] = md<EOL>deps[contract_name_i] = contract_account<EOL><DEDENT>except DependencyError as e:<EOL><INDENT>contract_names.append(contract_name_i)<EOL>for lib_name in e.lib_names:<EOL><INDENT>if lib_name not in deps:<EOL><INDENT>contract_names.append(lib_name)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not self.count_running_states() or len(self.get_code(contract_account)) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return contract_account<EOL>

Creates a solidity contract and library dependencies

            :param str source_code: solidity source code
            :param owner: owner account (will be default caller in any transactions)
            :type owner: int or EVMAccount
            :param contract_name: Name of the contract to analyze (optional if there is a single one in the source code)
            :type contract_name: str
            :param balance: balance to be transferred on creation
            :type balance: int or BitVecVariable
            :param address: the address for the new contract (optional)
            :type address: int or EVMAccount
            :param tuple args: constructor arguments
            :param solc_bin: path to solc binary
            :type solc_bin: str
            :param solc_remaps: solc import remaps
            :type solc_remaps: list of str
            :param working_dir: working directory for solc compilation (defaults to current)
            :type working_dir: str
            :param gas: gas budget for each contract creation needed (may be more than one if several related contracts defined in the solidity source)
            :type gas: int
            :rtype: EVMAccount


def create_contract(self, owner, balance=<NUM_LIT:0>, address=None, init=None, name=None, gas=None):

if not self.count_running_states():<EOL><INDENT>raise NoAliveStates<EOL><DEDENT>nonce = self.get_nonce(owner)<EOL>expected_address = evm.EVMWorld.calculate_new_address(int(owner), nonce=nonce)<EOL>if address is None:<EOL><INDENT>address = expected_address<EOL><DEDENT>elif address != expected_address:<EOL><INDENT>raise EthereumError("<STR_LIT>" % (expected_address, address))<EOL><DEDENT>if name is None:<EOL><INDENT>name = self._get_uniq_name("<STR_LIT>")<EOL><DEDENT>if name in self._accounts:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>self._transaction('<STR_LIT>', owner, balance, address, data=init, gaslimit=gas)<EOL>self._accounts[name] = EVMContract(address=address, manticore=self, default_caller=owner, name=name)<EOL>return self.accounts[name]<EOL>

Creates a contract

            :param owner: owner account (will be default caller in any transactions)
            :type owner: int or EVMAccount
            :param balance: balance to be transferred on creation
            :type balance: int or BitVecVariable
            :param int address: the address for the new contract (optional)
            :param str init: initializing evm bytecode and arguments
            :param str name: a unique name for reference
            :param gas: gas budget for the creation/initialization of the contract
            :rtype: EVMAccount


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

Returns all addresses in all running states


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


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

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

Issue a symbolic transaction in all running states

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


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

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

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

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


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

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

Initiates a transaction

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


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

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

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


<EOL>with self.locked_context('<STR_LIT>') as context:<EOL><INDENT>assert len(self._executor.list()) == <NUM_LIT:0><EOL>for state_id in context['<STR_LIT>']:<EOL><INDENT>self._executor.put(state_id)<EOL><DEDENT>context['<STR_LIT>'] = set()<EOL><DEDENT>super().run(**kwargs)<EOL>with self.locked_context('<STR_LIT>') as context:<EOL><INDENT>if len(context['<STR_LIT>']) == <NUM_LIT:1>:<EOL><INDENT>self._initial_state = self._executor._workspace.load_state(context['<STR_LIT>'].pop(), delete=True)<EOL>self._executor.forward_events_from(self._initial_state, True)<EOL>context['<STR_LIT>'] = set()<EOL>assert self._running_state_ids == (-<NUM_LIT:1>,)<EOL><DEDENT><DEDENT>

Run any pending transaction on any running state


def save(self, state, state_id=None, final=False):

<EOL>if state_id is not None:<EOL><INDENT>if state_id not in self._all_state_ids:<EOL><INDENT>raise EthereumError("<STR_LIT>")<EOL><DEDENT>with self.locked_context('<STR_LIT>') as context:<EOL><INDENT>context['<STR_LIT>'].discard(state_id)<EOL>context['<STR_LIT>'].discard(state_id)<EOL><DEDENT><DEDENT>if state_id != -<NUM_LIT:1>:<EOL><INDENT>state_id = self._executor._workspace.save_state(state, state_id=state_id)<EOL>with self.locked_context('<STR_LIT>') as context:<EOL><INDENT>if final:<EOL><INDENT>context['<STR_LIT>'].add(state_id)<EOL><DEDENT>else:<EOL><INDENT>context['<STR_LIT>'].add(state_id)<EOL><DEDENT><DEDENT><DEDENT>return state_id<EOL>

Save a state in secondary storage and add it to running or final lists

            :param state: A manticore State
            :param state_id: if not None force state_id (overwrite)
            :param final: True if state is final
            :returns: a state id


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

Load one of the running or final states.

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


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

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


def _on_concrete_sha3_callback(self, state, buf, value):

with self.locked_context('<STR_LIT>', dict) as ethereum_context:<EOL><INDENT>known_sha3 = ethereum_context.get('<STR_LIT>', None)<EOL>if known_sha3 is None:<EOL><INDENT>known_sha3 = set()<EOL><DEDENT>known_sha3.add((buf, value))<EOL>ethereum_context['<STR_LIT>'] = known_sha3<EOL><DEDENT>


def _terminate_state_callback(self, state, state_id, e):

if isinstance(e, AbandonState):<EOL><INDENT>return<EOL><DEDENT>world = state.platform<EOL>state.context['<STR_LIT>'] = e<EOL>e.testcase = False  <EOL>if not world.all_transactions:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL>self.save(state, final=True)<EOL>return<EOL><DEDENT>tx = world.all_transactions[-<NUM_LIT:1>]<EOL>if tx.is_human:<EOL><INDENT>if tx.sort == '<STR_LIT>':<EOL><INDENT>if tx.result == '<STR_LIT>':<EOL><INDENT>world.set_code(tx.address, tx.return_data)<EOL><DEDENT>else:<EOL><INDENT>world.delete_account(tx.address)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>logger.info("<STR_LIT>")<EOL><DEDENT>if tx.result in {'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>self.save(state, final=True)<EOL><DEDENT>elif tx.result in {'<STR_LIT>', '<STR_LIT>'}:<EOL><INDENT>self.save(state)  <EOL><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>")<EOL><DEDENT>

INTERNAL USE
            Every time a state finishes executing the last transaction, we save it in
            our private list


def _load_state_callback(self, state, state_id):

if '<STR_LIT>' not in state.context:<EOL><INDENT>return<EOL><DEDENT>world = state.platform<EOL>ty, caller, address, value, data, gaslimit, price = state.context['<STR_LIT>']<EOL>del state.context['<STR_LIT>']<EOL>if ty == '<STR_LIT>':<EOL><INDENT>world.transaction(address=address, caller=caller, data=data, value=value, price=price, gas=gaslimit)<EOL><DEDENT>else:<EOL><INDENT>assert ty == '<STR_LIT>'<EOL>world.create_contract(caller=caller, address=address, balance=value, init=data, price=price, gas=gaslimit)<EOL><DEDENT>

INTERNAL USE
            If a state was just loaded from storage, we do the pending transaction


def _did_evm_execute_instruction_callback(self, state, instruction, arguments, result):

<EOL>at_init = state.platform.current_transaction.sort == '<STR_LIT>'<EOL>if at_init:<EOL><INDENT>coverage_context_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>coverage_context_name = '<STR_LIT>'<EOL><DEDENT>with self.locked_context(coverage_context_name, set) as coverage:<EOL><INDENT>coverage.add((state.platform.current_vm.address, instruction.pc))<EOL><DEDENT>state.context.setdefault('<STR_LIT>', []).append((state.platform.current_vm.address, instruction.pc, at_init))<EOL>


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

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


def get_metadata(self, address) -> Optional[SolidityMetadata]:

return self.metadata.get(int(address))<EOL>

Gets the solidity metadata for address.
            This is available only if address is a contract created from solidity


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

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


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

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


for contract, pc, at_init in trace:<EOL><INDENT>if pc == <NUM_LIT:0>:<EOL><INDENT>filestream.write('<STR_LIT>')<EOL><DEDENT>ln = '<STR_LIT>'.format(contract, pc, '<STR_LIT:*>' if at_init else '<STR_LIT>')<EOL>filestream.write(ln)<EOL><DEDENT>

:param filestream: file object for the workspace trace file
:param trace: list of (contract address, pc) tuples
:type trace: list[tuple(int, int)]


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

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


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

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


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

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

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

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

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

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


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

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

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


def add_finding_here(self, state, finding, constraint=True):

address = state.platform.current_vm.address<EOL>pc = state.platform.current_vm.pc<EOL>if isinstance(pc, Constant):<EOL><INDENT>pc = pc.value<EOL><DEDENT>if not isinstance(pc, int):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>at_init = state.platform.current_transaction.sort == '<STR_LIT>'<EOL>self.add_finding(state, address, pc, finding, at_init, constraint)<EOL>

Logs a finding in current contract and assembler line.
:param state: current state
:param finding: textual description of the finding
:param constraint: finding is considered reproducible only when constraint is True


def _save_current_location(self, state, finding, condition=True):

address = state.platform.current_vm.address<EOL>pc = state.platform.current_vm.pc<EOL>at_init = state.platform.current_transaction.sort == '<STR_LIT>'<EOL>location = (address, pc, finding, at_init, condition)<EOL>hash_id = hashlib.sha1(str(location).encode()).hexdigest()<EOL>state.context.setdefault('<STR_LIT>'.format(self.name), {})[hash_id] = location<EOL>return hash_id<EOL>

Save current location in the internal locations list and returns a textual id for it.
This is used to save locations that could later be promoted to a finding if other conditions hold
See _get_location()
:param state: current state
:param finding: textual description of the finding
:param condition: general purpose constraint


def _get_location(self, state, hash_id):

return state.context.setdefault('<STR_LIT>'.format(self.name), {})[hash_id]<EOL>

Get previously saved location
A location is composed of: address, pc, finding, at_init, condition


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

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

Detects INVALID instructions.

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

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


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

sub = Operators.SEXTEND(a, <NUM_LIT>, <NUM_LIT>) - Operators.SEXTEND(b, <NUM_LIT>, <NUM_LIT>)<EOL>cond = Operators.OR(sub < -(<NUM_LIT:1> << <NUM_LIT:255>), sub >= (<NUM_LIT:1> << <NUM_LIT:255>))<EOL>return cond<EOL>

Sign extend the value to 512 bits and check the result can be represented
 in 256. Following there is a 32 bit excerpt of this condition:
a  -  b   -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff
+80000000    False    False    False    False     True     True     True
+c0000001    False    False    False    False    False    False     True
+ffffffff    False    False    False    False    False    False    False
+00000000     True    False    False    False    False    False    False
+00000001     True    False    False    False    False    False    False
+3fffffff     True    False    False    False    False    False    False
+7fffffff     True     True     True    False    False    False    False


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

add = Operators.SEXTEND(a, <NUM_LIT>, <NUM_LIT>) + Operators.SEXTEND(b, <NUM_LIT>, <NUM_LIT>)<EOL>cond = Operators.OR(add < -(<NUM_LIT:1> << <NUM_LIT:255>), add >= (<NUM_LIT:1> << <NUM_LIT:255>))<EOL>return cond<EOL>

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

a  +  b   -80000000 -3fffffff -00000001 +00000000 +00000001 +3fffffff +7fffffff
+80000000     True     True     True    False    False    False    False
+c0000001     True    False    False    False    False    False    False
+ffffffff     True    False    False    False    False    False    False
+00000000    False    False    False    False    False    False    False
+00000001    False    False    False    False    False    False     True
+3fffffff    False    False    False    False    False    False     True
+7fffffff    False    False    False    False     True     True     True


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

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

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

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


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

add = Operators.ZEXTEND(a, <NUM_LIT>) + Operators.ZEXTEND(b, <NUM_LIT>)<EOL>cond = Operators.UGE(add, <NUM_LIT:1> << <NUM_LIT>)<EOL>return cond<EOL>

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

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


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

mul = Operators.SEXTEND(a, <NUM_LIT>, <NUM_LIT>) * Operators.SEXTEND(b, <NUM_LIT>, <NUM_LIT>)<EOL>cond = Operators.OR(mul < -(<NUM_LIT:1> << <NUM_LIT:255>), mul >= (<NUM_LIT:1> << <NUM_LIT:255>))<EOL>return cond<EOL>


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

mul = Operators.SEXTEND(a, <NUM_LIT>, <NUM_LIT>) * Operators.SEXTEND(b, <NUM_LIT>, <NUM_LIT>)<EOL>cond = Operators.UGE(mul, <NUM_LIT:1> << <NUM_LIT>)<EOL>return cond<EOL>


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

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

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

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

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

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

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


@staticmethod<EOL><INDENT>def function_signature_for_name_and_inputs(name: str, inputs: Sequence[Mapping[str, Any]]) -> str:<DEDENT>

return name + SolidityMetadata.tuple_signature_for_components(inputs)<EOL>

Returns the function signature for the specified name and Solidity JSON metadata inputs array.

        The ABI specification defines the function signature as the function name followed by the parenthesised list of
        parameter types separated by single commas and no spaces.
        See https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector


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

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

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


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

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

Contract metadata for Solidity-based contracts


def get_constructor_arguments(self) -> str:

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

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


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

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

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


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

return dict(self._function_signatures_by_selector)<EOL>

Returns a new dict mapping contract function selectors to the function signatures.

        The dict does not include an item for the default or non-default fallback function.


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

return self._fallback_function_abi_item is not None<EOL>

Indicates whether the contract has an explicitly defined constructor.


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

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

Returns a copy of the Solidity JSON ABI item for the contract constructor.

        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_


def get_abi(self, hsh: bytes) -> Dict[str, Any]:

if not isinstance(hsh, (bytes, bytearray)):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>sig = self._function_signatures_by_selector.get(hsh)<EOL>if sig is not None:<EOL><INDENT>return dict(self._function_abi_items_by_signature[sig])<EOL><DEDENT>item = self._fallback_function_abi_item<EOL>if item is not None:<EOL><INDENT>return dict(item)<EOL><DEDENT>return {'<STR_LIT>': False, '<STR_LIT>': '<STR_LIT>', '<STR_LIT:type>': '<STR_LIT>'}<EOL>

Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``.

        If no normal contract function has the specified selector, a dict describing the default or non-default
        fallback function is returned.

        The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_


def get_func_argument_types(self, hsh: bytes):

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

Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``.

        If no normal contract function has the specified selector,
        the empty tuple type signature ``'()'`` is returned.


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

if not isinstance(hsh, (bytes, bytearray)):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>abi = self.get_abi(hsh)<EOL>outputs = abi.get('<STR_LIT>')<EOL>return '<STR_LIT>' if outputs is None else SolidityMetadata.tuple_signature_for_components(outputs)<EOL>

Returns the tuple type signature for the output values of the function
        associated with the selector ``hsh``.

        If no normal contract function has the specified selector,
        the empty tuple type signature ``'()'`` is returned.


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

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

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


def get_func_signature(self, hsh: bytes) -> Optional[str]:

if not isinstance(hsh, (bytes, bytearray)):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>return self._function_signatures_by_selector.get(hsh)<EOL>

Returns the signature of the normal function with the selector ``hsh``,
        or ``None`` if no such function exists.

        This function returns ``None`` for any selector that will be dispatched to a fallback function.


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

return self._function_signatures_by_selector.values()<EOL>

The signatures of all normal contract functions.


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

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

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


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

Indicates whether the contract has an explicitly defined fallback function.


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

return self._fallback_function_selector<EOL>

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

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


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

selectors = self._function_signatures_by_selector.keys()<EOL>if self._fallback_function_abi_item is None:<EOL><INDENT>return tuple(selectors)<EOL><DEDENT>return (*selectors, self.fallback_function_selector)<EOL>

The selectors of all normal contract functions,
        plus ``self.fallback_function_selector`` if the contract has a non-default fallback function.


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

selectors = self._function_signatures_by_selector.keys()<EOL>return (*selectors, self.fallback_function_selector)<EOL>

The selectors of all normal contract functions, plus ``self.fallback_function_selector``.


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

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

Encapsulates an account.

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


return self._name<EOL>

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


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

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

Encapsulates a contract account.

:param default_caller: the default caller address for any transaction


if not self.__initialized:<EOL><INDENT>self.__init_hashes()<EOL><DEDENT>if name in self.__hashes:<EOL><INDENT>def f(*args, signature: Optional[str]=None, caller=None, value=<NUM_LIT:0>, gas=<NUM_LIT>, **kwargs):<EOL><INDENT>try:<EOL><INDENT>if signature:<EOL><INDENT>if f'<STR_LIT>' not in {entry.signature for entries in self.__hashes.values() for entry in entries}:<EOL><INDENT>raise EthereumError(<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>')<EOL><DEDENT>tx_data = ABI.function_call(f'<STR_LIT>', *args)<EOL><DEDENT>else:<EOL><INDENT>entries = self.__hashes[name]<EOL>if len(entries) > <NUM_LIT:1>:<EOL><INDENT>sig = entries[<NUM_LIT:0>].signature[len(name):]<EOL>raise EthereumError(<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>')<EOL><DEDENT>tx_data = ABI.function_call(str(entries[<NUM_LIT:0>].signature), *args)<EOL><DEDENT><DEDENT>except KeyError as e:<EOL><INDENT>raise e<EOL><DEDENT>if caller is None:<EOL><INDENT>caller = self.__default_caller<EOL><DEDENT>self._manticore.transaction(caller=caller,<EOL>address=self._address,<EOL>value=value,<EOL>data=tx_data,<EOL>gas=gas)<EOL><DEDENT>return f<EOL><DEDENT>raise AttributeError(f"<STR_LIT>")<EOL>

If this is a contract account of which we know the functions hashes,
this will build the transaction for the function call.

Example use:
    # call function `add` on contract_account with argument `1000`
    contract_account.add(1000)


t.value = int(t.value)<EOL>return t<EOL>


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


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


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


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


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


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


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


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


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


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


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

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


p[<NUM_LIT:0>] = (p[<NUM_LIT:1>],)<EOL>


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


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


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


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


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


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


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

Build transaction data from function signature and arguments


@staticmethod<EOL><INDENT>def serialize(ty, *values, **kwargs):<DEDENT>

try:<EOL><INDENT>parsed_ty = abitypes.parse(ty)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise EthereumError(str(e))<EOL><DEDENT>if parsed_ty[<NUM_LIT:0>] != '<STR_LIT>':<EOL><INDENT>if len(values) > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>values = values[<NUM_LIT:0>]<EOL>if isinstance(values, str):<EOL><INDENT>values = values.encode()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>values = tuple(val.encode() if isinstance(val, str) else val for val in values)<EOL><DEDENT>result, dyn_result = ABI._serialize(parsed_ty, values)<EOL>return result + dyn_result<EOL>

Serialize value using type specification in ty.
ABI.serialize('int256', 1000)
ABI.serialize('(int, int256)', 1000, 2000)


return value + bytearray(b'<STR_LIT:\x00>' * (<NUM_LIT:32> - len(value)))<EOL>

Serializes the value and pads to multiple of 32 bytes

:param value:
:type value: str or bytearray or Array


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

Makes a function hash id from a method signature


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

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

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


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

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

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


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

start = offset<EOL>size = nbytes<EOL>if padding:<EOL><INDENT>start += <NUM_LIT:32> - nbytes<EOL><DEDENT>pos = start<EOL>values = []<EOL>while pos < start + size:<EOL><INDENT>if pos >= len(data):<EOL><INDENT>values.append(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>values.append(data[pos])<EOL><DEDENT>pos += <NUM_LIT:1><EOL><DEDENT>return Operators.CONCAT(nbytes * <NUM_LIT:8>, *values)<EOL>

:param data:
:param nbytes:
:param padding: If True, treat data as padded at the beginning to multiple of 32
:param offset:
:return:


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

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

Read a `nbytes` bytes long big endian unsigned integer from `data` starting at `offset`

:param data: sliceable buffer; symbolic buffer of Eth ABI encoded data
:param nbytes: number of bytes to read starting from least significant byte
:rtype: int or Expression


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

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

Read a `nbytes` bytes long big endian signed integer from `data` starting at `offset`

:param data: sliceable buffer; symbolic buffer of Eth ABI encoded data
:param nbytes: number of bytes to read starting from least significant byte
:rtype: int or Expression


global _groups<EOL>if name in _groups:<EOL><INDENT>return _groups[name]<EOL><DEDENT>group = _Group(name)<EOL>_groups[name] = group<EOL>return group<EOL>

Get a configuration variable group named |name|


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

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

:param f: where to write the config file


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

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

:param file f: Where to read the config.


if path is not None:<EOL><INDENT>names = [path]<EOL><DEDENT>else:<EOL><INDENT>possible_names = ['<STR_LIT>', '<STR_LIT>']<EOL>names = [os.path.join('<STR_LIT:.>', '<STR_LIT>'.join(x)) for x in product(['<STR_LIT>', '<STR_LIT:.>'], possible_names)]<EOL><DEDENT>for name in names:<EOL><INDENT>try:<EOL><INDENT>with open(name, '<STR_LIT:r>') as yml_f:<EOL><INDENT>logger.info(f'<STR_LIT>')<EOL>parse_config(yml_f)<EOL><DEDENT>break<EOL><DEDENT>except FileNotFoundError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if path is not None:<EOL><INDENT>raise FileNotFoundError(f"<STR_LIT>")<EOL><DEDENT><DEDENT>

Load config overrides from the yml file at |path|, or from default paths. If a path
is provided and it does not exist, raise an exception

Default paths: ./mcore.yml, ./.mcore.yml, ./manticore.yml, ./.manticore.yml.


global _groups<EOL>for group_name, group in _groups.items():<EOL><INDENT>for key in group:<EOL><INDENT>obj = group._var_object(key)<EOL>args.add_argument(f"<STR_LIT>", type=type(obj.default),<EOL>default=obj.default, help=obj.description)<EOL><DEDENT><DEDENT>

Import all defined config vars into |args|, for parsing command line.
:param args: A container for argparse vars
:type args: argparse.ArgumentParser or argparse._ArgumentGroup
:return:


def process_config_values(parser: argparse.ArgumentParser, args: argparse.Namespace):

<EOL>load_overrides(args.config)<EOL>defined_vars = list(get_config_keys())<EOL>command_line_args = vars(args)<EOL>config_cli_args = get_group('<STR_LIT>')<EOL>for k in command_line_args:<EOL><INDENT>default = parser.get_default(k)<EOL>set_val = getattr(args, k)<EOL>if default is not set_val:<EOL><INDENT>if k not in defined_vars:<EOL><INDENT>config_cli_args.update(k, value=set_val)<EOL><DEDENT>else:<EOL><INDENT>group_name, key = k.split('<STR_LIT:.>')<EOL>group = get_group(group_name)<EOL>setattr(group, key, set_val)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if k in config_cli_args:<EOL><INDENT>setattr(args, k, getattr(config_cli_args, k))<EOL><DEDENT><DEDENT><DEDENT>

Bring in provided config values to the args parser, and import entries to the config
from all arguments that were actually passed on the command line

:param parser: The arg parser
:param args: The value that parser.parse_args returned


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

Return an iterable covering all defined keys so far


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

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

Add a variable named |name| to this value group, optionally giving it a
default value and a description.

Variables must be added with this method before they can be set or read.
Reading a variable replaces the variable that was defined previously, but
updates the description if a new one is set.


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

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

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

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


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

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

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


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

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


return _TemporaryGroup(self)<EOL>

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

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

# group.var is back to 123


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


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

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


if self.colors_disabled:<EOL><INDENT>return self.plain_levelname_format.format(levelname)<EOL><DEDENT>else:<EOL><INDENT>return self.colored_levelname_format.format(self.color_map[levelname], levelname)<EOL><DEDENT>

Colors the logging level in the logging record


if item is None or item == <NUM_LIT:0>:<EOL><INDENT>ret = b'<STR_LIT>'<EOL><DEDENT>elif isinstance(item, str):<EOL><INDENT>ret = rlp_encode(item.encode('<STR_LIT:utf8>'))<EOL><DEDENT>elif isinstance(item, (bytearray, bytes)):<EOL><INDENT>if len(item) == <NUM_LIT:1> and item[<NUM_LIT:0>] < <NUM_LIT>:<EOL><INDENT>ret = item<EOL><DEDENT>else:<EOL><INDENT>ret = encode_length(len(item), <NUM_LIT>) + item<EOL><DEDENT><DEDENT>elif isinstance(item, collections.abc.Sequence):<EOL><INDENT>output = b'<STR_LIT>'.join(map(rlp_encode, item))<EOL>ret = encode_length(len(output), <NUM_LIT>) + output<EOL><DEDENT>elif isinstance(item, int):<EOL><INDENT>ret = rlp_encode(int_to_bytes(item))<EOL><DEDENT>else:<EOL><INDENT>raise Exception("<STR_LIT>" % type(item).__name__)<EOL><DEDENT>return ret<EOL>

r""" Recursive Length Prefix Encoding
        :param item: the object to encode, either a string, bytes, bytearray, int, long, or sequence

    https://github.com/ethereum/wiki/wiki/RLP

    >>> rlp_encode('dog')
    b'\x83dog'

    >>> rlp_encode([ 'cat', 'dog' ])
    b'\xc8\x83cat\x83dog'

    >>> rlp_encode('')
    b'\x80'

    >>> rlp_encode([])
    b'\xc0'

    >>> rlp_encode(0)
    b'\x80'

    >>> rlp_encode('\x00')
    b'\x00'

    >>> rlp_encode(15)
    b'\x0f'

    >>> rlp_encode(1024)
    b'\x82\x04\x00'

    >>> rlp_encode([ [], [[]], [ [], [[]] ] ])
    b'\xc7\xc0\xc1\xc0\xc3\xc0\xc1\xc0'


from ..core.smtlib import Expression  <EOL>return isinstance(value, Expression)<EOL>

Helper to determine whether an object is symbolic (e.g checking
if data read from memory is symbolic)

:param object value: object to check
:return: whether `value` is symbolic
:rtype: bool


if not issymbolic(arg):<EOL><INDENT>return False<EOL><DEDENT>if taint is None:<EOL><INDENT>return len(arg.taint) != <NUM_LIT:0><EOL><DEDENT>for arg_taint in arg.taint:<EOL><INDENT>m = re.match(taint, arg_taint, re.DOTALL | re.IGNORECASE)<EOL>if m:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Helper to determine whether an object if tainted.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.


if not issymbolic(arg):<EOL><INDENT>return<EOL><DEDENT>for arg_taint in arg.taint:<EOL><INDENT>if taint is not None:<EOL><INDENT>m = re.match(taint, arg_taint, re.DOTALL | re.IGNORECASE)<EOL>if m:<EOL><INDENT>yield arg_taint<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield arg_taint<EOL><DEDENT><DEDENT>return<EOL>

Helper to list an object taints.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.


def taint_with(arg, taint, value_bits=<NUM_LIT>, index_bits=<NUM_LIT>):

from ..core.smtlib import BitVecConstant  <EOL>tainted_fset = frozenset((taint,))<EOL>if not issymbolic(arg):<EOL><INDENT>if isinstance(arg, int):<EOL><INDENT>arg = BitVecConstant(value_bits, arg)<EOL>arg._taint = tainted_fset<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>arg = copy.copy(arg)<EOL>arg._taint |= tainted_fset<EOL><DEDENT>return arg<EOL>

Helper to taint a value.
:param arg: a value or Expression
:param taint: a regular expression matching a taint value (eg. 'IMPORTANT.*'). If None, this function checks for any taint value.


def interval_intersection(min1, max1, min2, max2):

left, right = max(min1, min2), min(max1, max2)<EOL>if left < right:<EOL><INDENT>return left, right<EOL><DEDENT>return None<EOL>

Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval,
or None if they do not overlap.


def _create_emulated_mapping(self, uc, address):

m = self._cpu.memory.map_containing(address)<EOL>permissions = UC_PROT_NONE<EOL>if '<STR_LIT:r>' in m.perms:<EOL><INDENT>permissions |= UC_PROT_READ<EOL><DEDENT>if '<STR_LIT:w>' in m.perms:<EOL><INDENT>permissions |= UC_PROT_WRITE<EOL><DEDENT>if '<STR_LIT:x>' in m.perms:<EOL><INDENT>permissions |= UC_PROT_EXEC<EOL><DEDENT>uc.mem_map(m.start, len(m), permissions)<EOL>self._should_be_mapped[m.start] = (len(m), permissions)<EOL>return m<EOL>

Create a mapping in Unicorn and note that we'll need it if we retry.
:param uc: The Unicorn instance.
:param address: The address which is contained by the mapping.
:rtype Map


def _hook_xfer_mem(self, uc, access, address, size, value, data):

assert access in (UC_MEM_WRITE, UC_MEM_READ, UC_MEM_FETCH)<EOL>if access == UC_MEM_WRITE:<EOL><INDENT>self._cpu.write_int(address, value, size * <NUM_LIT:8>)<EOL><DEDENT>elif access == UC_MEM_READ:<EOL><INDENT>value = self._cpu.read_bytes(address, size)<EOL>if address in self._should_be_written:<EOL><INDENT>return True<EOL><DEDENT>self._should_be_written[address] = value<EOL>self._should_try_again = True<EOL>return False<EOL><DEDENT>return True<EOL>


def _hook_unmapped(self, uc, access, address, size, value, data):

try:<EOL><INDENT>m = self._create_emulated_mapping(uc, address)<EOL><DEDENT>except MemoryException as e:<EOL><INDENT>self._to_raise = e<EOL>self._should_try_again = False<EOL>return False<EOL><DEDENT>self._should_try_again = True<EOL>return False<EOL>

We hit an unmapped region; map it into unicorn.


from ..native.cpu.abstractcpu import Interruption  <EOL>self._to_raise = Interruption(number)<EOL>return True<EOL>


<EOL>while True:<EOL><INDENT>self.reset()<EOL>for base in self._should_be_mapped:<EOL><INDENT>size, perms = self._should_be_mapped[base]<EOL>self._emu.mem_map(base, size, perms)<EOL><DEDENT>for address, values in self._should_be_written.items():<EOL><INDENT>for offset, byte in enumerate(values, start=address):<EOL><INDENT>if issymbolic(byte):<EOL><INDENT>from ..native.cpu.abstractcpu import ConcretizeMemory<EOL>raise ConcretizeMemory(self._cpu.memory, offset, <NUM_LIT:8>,<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>self._emu.mem_write(address, b'<STR_LIT>'.join(values))<EOL><DEDENT>self._should_try_again = False<EOL>self._step(instruction)<EOL>if not self._should_try_again:<EOL><INDENT>break<EOL><DEDENT><DEDENT>


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

A single attempt at executing an instruction.


assert isinstance(message, str), "<STR_LIT>"<EOL>def decorator(func):<EOL><INDENT>@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>warnings.warn(f"<STR_LIT>",<EOL>category=ManticoreDeprecationWarning, stacklevel=<NUM_LIT:2>)<EOL>return func(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>

A decorator for marking functions as deprecated.


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

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


self._signals = dict()<EOL>self._forwards = WeakKeyDictionary()<EOL>return True<EOL>

It wont get serialized by design, user is responsible to reconnect


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

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


permissions = UC_PROT_NONE<EOL>if '<STR_LIT:r>' in m_perms:<EOL><INDENT>permissions |= UC_PROT_READ<EOL><DEDENT>if '<STR_LIT:w>' in m_perms:<EOL><INDENT>permissions |= UC_PROT_WRITE<EOL><DEDENT>if '<STR_LIT:x>' in m_perms:<EOL><INDENT>permissions |= UC_PROT_EXEC<EOL><DEDENT>return permissions<EOL>

Converts a Manticore permission string into a Unicorn permission
:param m_perms: Manticore perm string ('rwx')
:return: Unicorn Permissions


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

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

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


start_time = time.time()<EOL>map_bytes = self._cpu._raw_read(address, size)<EOL>self._emu.mem_write(address, map_bytes)<EOL>if time.time() - start_time > <NUM_LIT:3>:<EOL><INDENT>logger.info(f"<STR_LIT>")<EOL><DEDENT>

Copy the bytes from address to address+size into Unicorn
Used primarily for copying memory maps
:param address: start of buffer to copy
:param size: How many bytes to copy


def map_memory_callback(self, address, size, perms, name, offset, result):

logger.info('<STR_LIT:U+0020>'.join(("<STR_LIT>",<EOL>hex(address) if type(address) is int else "<STR_LIT>",<EOL>hr_size(size), "<STR_LIT:->",<EOL>perms, "<STR_LIT:->",<EOL>f"<STR_LIT>", "<STR_LIT>",<EOL>hex(result))))<EOL>self._emu.mem_map(address, size, convert_permissions(perms))<EOL>self.copy_memory(address, size)<EOL>

Catches did_map_memory and copies the mapping into Manticore


def unmap_memory_callback(self, start, size):

logger.info(f"<STR_LIT>")<EOL>mask = (<NUM_LIT:1> << <NUM_LIT:12>) - <NUM_LIT:1><EOL>if (start & mask) != <NUM_LIT:0>:<EOL><INDENT>logger.error("<STR_LIT>")<EOL><DEDENT>if (size & mask) != <NUM_LIT:0>:<EOL><INDENT>size = ((size >> <NUM_LIT:12>) + <NUM_LIT:1>) << <NUM_LIT:12><EOL>logger.warning("<STR_LIT>")<EOL><DEDENT>self._emu.mem_unmap(start, size)<EOL>

Unmap Unicorn maps when Manticore unmaps them


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

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

Set memory protections in Unicorn correctly


if self._cpu.arch == CS_ARCH_ARM:<EOL><INDENT>return self._emu.reg_read(UC_ARM_REG_R15)<EOL><DEDENT>elif self._cpu.arch == CS_ARCH_X86:<EOL><INDENT>if self._cpu.mode == CS_MODE_32:<EOL><INDENT>return self._emu.reg_read(UC_X86_REG_EIP)<EOL><DEDENT>elif self._cpu.mode == CS_MODE_64:<EOL><INDENT>return self._emu.reg_read(UC_X86_REG_RIP)<EOL><DEDENT><DEDENT>

Get the program counter from Unicorn regardless of architecture.
        Legacy method, since this module only works on x86.


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

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


def _hook_write_mem(self, uc, access, address, size, value, data):

self._mem_delta[address] = (value, size)<EOL>return True<EOL>


try:<EOL><INDENT>self.sync_unicorn_to_manticore()<EOL>logger.warning(f"<STR_LIT>")<EOL>m = self._cpu.memory.map_containing(address)<EOL>self.copy_memory(m.start, m.end - m.start)<EOL><DEDENT>except MemoryException as e:<EOL><INDENT>logger.error("<STR_LIT>".format(hex(address), hex(address + size), access, e))<EOL>self._to_raise = e<EOL>self._should_try_again = False<EOL>return False<EOL><DEDENT>self._should_try_again = True<EOL>return False<EOL>


logger.info("<STR_LIT>" % number)<EOL>from ..native.cpu.abstractcpu import Interruption  <EOL>self._to_raise = Interruption(number)<EOL>return True<EOL>


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

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


def _step(self, instruction, chunksize=<NUM_LIT:0>):

try:<EOL><INDENT>pc = self._cpu.PC<EOL>m = self._cpu.memory.map_containing(pc)<EOL>if self._stop_at:<EOL><INDENT>logger.info(f"<STR_LIT>")<EOL><DEDENT>self._emu.emu_start(pc, m.end if not self._stop_at else self._stop_at, count=chunksize)<EOL><DEDENT>except UcError:<EOL><INDENT>if not self._should_try_again:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>if self._should_try_again:<EOL><INDENT>return<EOL><DEDENT>self._cpu.PC = self.get_unicorn_pc()<EOL>if self._cpu.PC == self._stop_at:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>self.sync_unicorn_to_manticore()<EOL>self._stop_at = None<EOL><DEDENT>if self._to_raise:<EOL><INDENT>from ..native.cpu.abstractcpu import Syscall<EOL>if type(self._to_raise) is not Syscall:<EOL><INDENT>logger.info("<STR_LIT>", self._to_raise)<EOL><DEDENT>raise self._to_raise<EOL><DEDENT>logger.info(f"<STR_LIT>")<EOL>return<EOL>

Execute a chunk fo instructions starting from instruction
:param instruction: Where to start
:param chunksize: max number of instructions to execute. Defaults to infinite.


self.write_backs_disabled = True<EOL>for reg in self.registers:<EOL><INDENT>val = self._emu.reg_read(self._to_unicorn_id(reg))<EOL>self._cpu.write_register(reg, val)<EOL><DEDENT>if len(self._mem_delta) > <NUM_LIT:0>:<EOL><INDENT>logger.debug(f"<STR_LIT>")<EOL><DEDENT>for location in self._mem_delta:<EOL><INDENT>value, size = self._mem_delta[location]<EOL>self._cpu.write_int(location, value, size * <NUM_LIT:8>)<EOL><DEDENT>self.write_backs_disabled = False<EOL>self._mem_delta = {}<EOL>

Copy registers and written memory back into Manticore


def write_back_memory(self, where, expr, size):

if self.write_backs_disabled:<EOL><INDENT>return<EOL><DEDENT>if type(expr) is bytes:<EOL><INDENT>self._emu.mem_write(where, expr)<EOL><DEDENT>else:<EOL><INDENT>if issymbolic(expr):<EOL><INDENT>data = [Operators.CHR(Operators.EXTRACT(expr, offset, <NUM_LIT:8>)) for offset in range(<NUM_LIT:0>, size, <NUM_LIT:8>)]<EOL>concrete_data = []<EOL>for c in data:<EOL><INDENT>if issymbolic(c):<EOL><INDENT>c = chr(solver.get_value(self._cpu.memory.constraints, c))<EOL><DEDENT>concrete_data.append(c)<EOL><DEDENT>data = concrete_data<EOL><DEDENT>else:<EOL><INDENT>data = [Operators.CHR(Operators.EXTRACT(expr, offset, <NUM_LIT:8>)) for offset in range(<NUM_LIT:0>, size, <NUM_LIT:8>)]<EOL><DEDENT>logger.debug(f"<STR_LIT>")<EOL>self._emu.mem_write(where, b'<STR_LIT>'.join(b.encode('<STR_LIT:utf-8>') if type(b) is str else b for b in data))<EOL><DEDENT>

Copy memory writes from Manticore back into Unicorn in real-time


def write_back_register(self, reg, val):

if self.write_backs_disabled:<EOL><INDENT>return<EOL><DEDENT>if issymbolic(val):<EOL><INDENT>logger.warning("<STR_LIT>")<EOL>return<EOL><DEDENT>if reg in self.flag_registers:<EOL><INDENT>self._emu.reg_write(self._to_unicorn_id('<STR_LIT>'), self._cpu.read_register('<STR_LIT>'))<EOL>return<EOL><DEDENT>self._emu.reg_write(self._to_unicorn_id(reg), val)<EOL>

Sync register state from Manticore -> Unicorn


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

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


FSMSR = <NUM_LIT><EOL>return self._emu.msr_write(FSMSR, addr)<EOL>

set the FS.base hidden descriptor-register field to the given address.
this enables referencing the fs segment on x86-64.


def concretizer(func):<EOL><INDENT>@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>spec = inspect.getfullargspec(func)<EOL>for arg, policy in policies.items():<EOL><INDENT>assert arg in spec.args, "<STR_LIT>"<EOL>index = spec.args.index(arg)<EOL>if not issymbolic(args[index]):<EOL><INDENT>continue<EOL><DEDENT>if not policy:<EOL><INDENT>policy = '<STR_LIT>'<EOL><DEDENT>if policy == "<STR_LIT>":<EOL><INDENT>value = args[index]<EOL>world = args[<NUM_LIT:0>].world<EOL>cond = world._constraint_to_accounts(value, ty='<STR_LIT>', include_zero=True)<EOL>world.constraints.add(cond)<EOL>policy = '<STR_LIT>'<EOL><DEDENT>raise ConcretizeArgument(index, policy=policy)<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>wrapper.__signature__ = inspect.signature(func)<EOL>return wrapper<EOL><DEDENT>return concretizer<EOL>

Make sure an EVM instruction has all of its arguments concretized according to
provided policies.

Example decoration:

    @concretized_args(size='ONE', address='')
    def LOG(self, address, size, *topics):
        ...

The above will make sure that the |size| parameter to LOG is Concretized when symbolic
according to the 'ONE' policy and concretize |address| with the default policy.

:param policies: A kwargs list of argument names and their respective policies.
                     Provide None or '' as policy to use default.
:return: A function decorator


Only meant to be used with concrete Transaction objects! (after calling .concretize())


def dump(self, stream, state, mevm, conc_tx=None):

from ..ethereum import ABI  <EOL>from ..ethereum.manticore import flagged<EOL>is_something_symbolic = False<EOL>if conc_tx is None:<EOL><INDENT>conc_tx = self.concretize(state)<EOL><DEDENT>stream.write("<STR_LIT>" % (self.sort, self.depth))<EOL>caller_solution = conc_tx.caller<EOL>caller_name = mevm.account_name(caller_solution)<EOL>stream.write("<STR_LIT>" % (caller_name, caller_solution, flagged(issymbolic(self.caller))))<EOL>address_solution = conc_tx.address<EOL>address_name = mevm.account_name(address_solution)<EOL>stream.write("<STR_LIT>" % (address_name, address_solution, flagged(issymbolic(self.address))))<EOL>stream.write("<STR_LIT>" % (conc_tx.value, flagged(issymbolic(self.value))))<EOL>stream.write("<STR_LIT>" % (conc_tx.gas, flagged(issymbolic(self.gas))))<EOL>tx_data = conc_tx.data<EOL>stream.write("<STR_LIT>".format(binascii.hexlify(tx_data).decode(), flagged(issymbolic(self.data))))<EOL>if self.return_data is not None:<EOL><INDENT>return_data = conc_tx.return_data<EOL>stream.write("<STR_LIT>".format(binascii.hexlify(return_data).decode(), flagged(issymbolic(self.return_data))))<EOL><DEDENT>metadata = mevm.get_metadata(self.address)<EOL>if self.sort == '<STR_LIT>':<EOL><INDENT>if metadata is not None:<EOL><INDENT>conc_args_data = conc_tx.data[len(metadata._init_bytecode):]<EOL>arguments = ABI.deserialize(metadata.get_constructor_arguments(), conc_args_data)<EOL>is_argument_symbolic = any(map(issymbolic, arguments))  <EOL>stream.write('<STR_LIT>')<EOL>stream.write("<STR_LIT>")<EOL>stream.write('<STR_LIT:U+002C>'.join(map(repr, map(state.solve_one, arguments))))  <EOL>stream.write('<STR_LIT>' % (self.result, flagged(is_argument_symbolic)))<EOL><DEDENT><DEDENT>if self.sort == '<STR_LIT>':<EOL><INDENT>if metadata is not None:<EOL><INDENT>calldata = conc_tx.data<EOL>is_calldata_symbolic = issymbolic(self.data)<EOL>function_id = calldata[:<NUM_LIT:4>]  <EOL>signature = metadata.get_func_signature(function_id)<EOL>function_name = metadata.get_func_name(function_id)<EOL>if signature:<EOL><INDENT>_, arguments = ABI.deserialize(signature, calldata)<EOL><DEDENT>else:<EOL><INDENT>arguments = (calldata,)<EOL><DEDENT>return_data = None<EOL>if self.result == '<STR_LIT>':<EOL><INDENT>ret_types = metadata.get_func_return_types(function_id)<EOL>return_data = conc_tx.return_data<EOL>return_values = ABI.deserialize(ret_types, return_data)  <EOL><DEDENT>is_return_symbolic = issymbolic(self.return_data)<EOL>stream.write('<STR_LIT:\n>')<EOL>stream.write("<STR_LIT>")<EOL>stream.write("<STR_LIT>" % function_name)<EOL>stream.write('<STR_LIT:U+002C>'.join(map(repr, arguments)))<EOL>stream.write('<STR_LIT>' % (self.result, flagged(is_calldata_symbolic)))<EOL>if return_data is not None:<EOL><INDENT>if len(return_values) == <NUM_LIT:1>:<EOL><INDENT>return_values = return_values[<NUM_LIT:0>]<EOL><DEDENT>stream.write('<STR_LIT>' % (return_values, flagged(is_return_symbolic)))<EOL><DEDENT>is_something_symbolic = is_calldata_symbolic or is_return_symbolic<EOL><DEDENT><DEDENT>stream.write('<STR_LIT>')<EOL>return is_something_symbolic<EOL>

Concretize and write a human readable version of the transaction into the stream. Used during testcase
generation.

:param stream: Output stream to write to. Typically a file.
:param manticore.ethereum.State state: state that the tx exists in
:param manticore.ethereum.ManticoreEVM mevm: manticore instance
:return:


return self.depth == <NUM_LIT:0><EOL>

Returns whether this is a transaction made by human (in a script).

As an example for:
    contract A { function a(B b) { b.b(); } }
    contract B { function b() {} }

Calling `B.b()` makes a human transaction.
Calling `A.a(B)` makes a human transaction which makes an internal transaction (b.b()).


return (self.__class__, (self.sort, self.address, self.price, self.data, self.caller, self.value, self.gas, self.depth, self.result, self.return_data))<EOL>