Search is not available for this dataset
text
stringlengths
75
104k
def _ceil(self, address): """ Returns the smallest page boundary value not less than the address. :rtype: int :param address: the address to calculate its ceil. :return: the ceil of C{address}. """ return (((address - 1) + self.page_size) & ~self.page_mask) & self.memory_mask
def _search(self, size, start=None, counter=0): """ Recursively searches the address space for enough free space to allocate C{size} bytes. :param size: the size in bytes to allocate. :param start: an address from where to start the search. :param counter: internal parameter to know if all the memory was already scanned. :return: the address of an available space to map C{size} bytes. :raises MemoryException: if there is no space available to allocate the desired memory. :rtype: int todo: Document what happens when you try to allocate something that goes round the address 32/64 bit representation. """ assert size & self.page_mask == 0 if start is None: end = {32: 0xf8000000, 64: 0x0000800000000000}[self.memory_bit_size] start = end - size else: if start > self.memory_size - size: start = self.memory_size - size end = start + size consecutive_free = 0 for p in range(self._page(end - 1), -1, -1): if p not in self._page2map: consecutive_free += 0x1000 else: consecutive_free = 0 if consecutive_free >= size: return p << self.page_bit_size counter += 1 if counter >= self.memory_size // self.page_size: raise MemoryException('Not enough memory') return self._search(size, self.memory_size - size, counter)
def mmapFile(self, addr, size, perms, filename, offset=0): """ Creates a new file mapping in the memory address space. :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough chunk of memory will be selected as starting address. :param size: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file C{filename}. :param perms: the access permissions to this memory. :param filename: the pathname to the file to map. :param offset: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file C{filename}. :return: the starting address where the file was mapped. :rtype: int :raises error: - 'Address shall be concrete' if C{addr} is not an integer number. - 'Address too big' if C{addr} goes beyond the limit of the memory. - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free. """ # If addr is NULL, the system determines where to allocate the region. assert addr is None or isinstance(addr, int), 'Address shall be concrete' assert size > 0 self.cpu._publish('will_map_memory', addr, size, perms, filename, offset) # address is rounded down to the nearest multiple of the allocation granularity if addr is not None: assert addr < self.memory_size, 'Address too big' addr = self._floor(addr) # size value is rounded up to the next page boundary size = self._ceil(size) # If zero search for a spot addr = self._search(size, addr) # It should not be allocated for i in range(self._page(addr), self._page(addr + size)): assert i not in self._page2map, 'Map already used' # Create the map m = FileMap(addr, size, perms, filename, offset) # Okay, ready to alloc self._add(m) logger.debug('New file-memory map @%x size:%x', addr, size) self.cpu._publish('did_map_memory', addr, size, perms, filename, offset, addr) return addr
def mmap(self, addr, size, perms, data_init=None, name=None): """ Creates a new mapping in the memory address space. :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough chunk of memory will be selected as starting address. :param size: the length of the mapping. :param perms: the access permissions to this memory. :param data_init: optional data to initialize this memory. :param name: optional name to give to this mapping :return: the starting address where the memory was mapped. :raises error: - 'Address shall be concrete' if C{addr} is not an integer number. - 'Address too big' if C{addr} goes beyond the limit of the memory. - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free. :rtype: int """ # If addr is NULL, the system determines where to allocate the region. assert addr is None or isinstance(addr, int), 'Address shall be concrete' self.cpu._publish('will_map_memory', addr, size, perms, None, None) # address is rounded down to the nearest multiple of the allocation granularity if addr is not None: assert addr < self.memory_size, 'Address too big' addr = self._floor(addr) # size value is rounded up to the next page boundary size = self._ceil(size) # If zero search for a spot addr = self._search(size, addr) # It should not be allocated for i in range(self._page(addr), self._page(addr + size)): assert i not in self._page2map, 'Map already used' # Create the anonymous map m = AnonMap(start=addr, size=size, perms=perms, data_init=data_init, name=name) # Okay, ready to alloc self._add(m) logger.debug('New memory map @%x size:%x', addr, size) self.cpu._publish('did_map_memory', addr, size, perms, None, None, addr) return addr
def map_containing(self, address): """ Returns the L{MMap} object containing the address. :param address: the address to obtain its mapping. :rtype: L{MMap} @todo: symbolic address """ page_offset = self._page(address) if page_offset not in self._page2map: raise MemoryException("Page not mapped", address) return self._page2map[page_offset]
def mappings(self): """ Returns a sorted list of all the mappings for this memory. :return: a list of mappings. :rtype: list """ result = [] for m in self.maps: if isinstance(m, AnonMap): result.append((m.start, m.end, m.perms, 0, '')) elif isinstance(m, FileMap): result.append((m.start, m.end, m.perms, m._offset, m._filename)) else: result.append((m.start, m.end, m.perms, 0, m.name)) return sorted(result)
def _maps_in_range(self, start, end): """ Generates the list of maps that overlaps with the range [start:end] """ # Search for the first matching map addr = start while addr < end: if addr not in self: addr += self.page_size else: m = self._page2map[self._page(addr)] yield m addr = m.end
def munmap(self, start, size): """ Deletes the mappings for the specified address range and causes further references to addresses within the range to generate invalid memory references. :param start: the starting address to delete. :param size: the length of the unmapping. """ start = self._floor(start) end = self._ceil(start + size) self.cpu._publish('will_unmap_memory', start, size) for m in self._maps_in_range(start, end): self._del(m) head, tail = m.split(start) middle, tail = tail.split(end) assert middle is not None if head: self._add(head) if tail: self._add(tail) self.cpu._publish('did_unmap_memory', start, size) logger.debug(f'Unmap memory @{start:x} size:{size:x}')
def pop_record_writes(self): """ Stop recording trace and return a `list[(address, value)]` of all the writes that occurred, where `value` is of type list[str]. Can be called without intermediate `pop_record_writes()`. For example:: mem.push_record_writes() mem.write(1, 'a') mem.push_record_writes() mem.write(2, 'b') mem.pop_record_writes() # Will return [(2, 'b')] mem.pop_record_writes() # Will return [(1, 'a'), (2, 'b')] Multiple writes to the same address will all be included in the trace in the same order they occurred. :return: list[tuple] """ lst = self._recording_stack.pop() # Append the current list to a previously-started trace. if self._recording_stack: self._recording_stack[-1].extend(lst) return lst
def munmap(self, start, size): """ Deletes the mappings for the specified address range and causes further references to addresses within the range to generate invalid memory references. :param start: the starting address to delete. :param size: the length of the unmapping. """ for addr in range(start, start + size): if len(self._symbols) == 0: break if addr in self._symbols: del self._symbols[addr] super().munmap(start, size)
def read(self, address, size, force=False): """ Read a stream of potentially symbolic bytes from a potentially symbolic address :param address: Where to read from :param size: How many bytes :param force: Whether to ignore permissions :rtype: list """ size = self._get_size(size) assert not issymbolic(size) if issymbolic(address): assert solver.check(self.constraints) logger.debug(f'Reading {size} bytes from symbolic address {address}') try: solutions = self._try_get_solutions(address, size, 'r', force=force) assert len(solutions) > 0 except TooManySolutions as e: m, M = solver.minmax(self.constraints, address) logger.debug(f'Got TooManySolutions on a symbolic read. Range [{m:x}, {M:x}]. Not crashing!') # The force param shouldn't affect this, as this is checking for unmapped reads, not bad perms crashing_condition = True for start, end, perms, offset, name in self.mappings(): if start <= M + size and end >= m: if 'r' in perms: crashing_condition = Operators.AND(Operators.OR((address + size).ult(start), address.uge(end)), crashing_condition) if solver.can_be_true(self.constraints, crashing_condition): raise InvalidSymbolicMemoryAccess(address, 'r', size, crashing_condition) # INCOMPLETE Result! We could also fork once for every map logger.info('INCOMPLETE Result! Using the sampled solutions we have as result') condition = False for base in e.solutions: condition = Operators.OR(address == base, condition) from .state import ForkState raise ForkState("Forking state on incomplete result", condition) # So here we have all potential solutions to address condition = False for base in solutions: condition = Operators.OR(address == base, condition) result = [] # consider size ==1 to read following code for offset in range(size): # Given ALL solutions for the symbolic address for base in solutions: addr_value = base + offset byte = Operators.ORD(self.map_containing(addr_value)[addr_value]) if addr_value in self._symbols: for condition, value in self._symbols[addr_value]: byte = Operators.ITEBV(8, condition, Operators.ORD(value), byte) if len(result) > offset: result[offset] = Operators.ITEBV(8, address == base, byte, result[offset]) else: result.append(byte) assert len(result) == offset + 1 return list(map(Operators.CHR, result)) else: result = list(map(Operators.ORD, super().read(address, size, force))) for offset in range(size): if address + offset in self._symbols: for condition, value in self._symbols[address + offset]: if condition is True: result[offset] = Operators.ORD(value) else: result[offset] = Operators.ITEBV(8, condition, Operators.ORD(value), result[offset]) return list(map(Operators.CHR, result))
def write(self, address, value, force=False): """ Write a value at address. :param address: The address at which to write :type address: int or long or Expression :param value: Bytes to write :type value: str or list :param force: Whether to ignore permissions """ size = len(value) if issymbolic(address): solutions = self._try_get_solutions(address, size, 'w', force=force) for offset in range(size): for base in solutions: condition = base == address self._symbols.setdefault(base + offset, []).append((condition, value[offset])) else: for offset in range(size): if issymbolic(value[offset]): if not self.access_ok(address + offset, 'w', force): raise InvalidMemoryAccess(address + offset, 'w') self._symbols[address + offset] = [(True, value[offset])] else: # overwrite all previous items if address + offset in self._symbols: del self._symbols[address + offset] super().write(address + offset, [value[offset]], force)
def _try_get_solutions(self, address, size, access, max_solutions=0x1000, force=False): """ Try to solve for a symbolic address, checking permissions when reading/writing size bytes. :param Expression address: The address to solve for :param int size: How many bytes to check permissions for :param str access: 'r' or 'w' :param int max_solutions: Will raise if more solutions are found :param force: Whether to ignore permission failure :rtype: list """ assert issymbolic(address) solutions = solver.get_all_values(self.constraints, address, maxcnt=max_solutions) crashing_condition = False for base in solutions: if not self.access_ok(slice(base, base + size), access, force): crashing_condition = Operators.OR(address == base, crashing_condition) if solver.can_be_true(self.constraints, crashing_condition): raise InvalidSymbolicMemoryAccess(address, access, size, crashing_condition) return solutions
def mmapFile(self, addr, size, perms, filename, offset=0): """ Creates a new file mapping in the memory address space. :param addr: the starting address (took as hint). If C{addr} is C{0} the first big enough chunk of memory will be selected as starting address. :param size: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file C{filename}. :param perms: the access permissions to this memory. :param filename: the pathname to the file to map. :param offset: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file C{filename}. :return: the starting address where the file was mapped. :rtype: int :raises error: - 'Address shall be concrete' if C{addr} is not an integer number. - 'Address too big' if C{addr} goes beyond the limit of the memory. - 'Map already used' if the piece of memory starting in C{addr} and with length C{size} isn't free. """ # If addr is NULL, the system determines where to allocate the region. assert addr is None or isinstance(addr, int), 'Address shall be concrete' assert addr < self.memory_size, 'Address too big' assert size > 0 self.cpu._publish('will_map_memory', addr, size, perms, filename, offset) map = AnonMap(addr, size, perms) self._add(map) # address is rounded down to the nearest multiple of the allocation granularity if addr is not None: addr = self._floor(addr) # size value is rounded up to the next page boundary size = self._ceil(size) with open(filename, 'rb') as f: fdata = f.read() # fdata is a bytes now # this worked fdata = fdata[offset:] fdata = fdata.ljust(size, b'\0') for i in range(size): Memory.write(self, addr + i, chr(fdata[i]), force=True) logger.debug('New file-memory map @%x size:%x', addr, size) self.cpu._publish('did_map_memory', addr, size, perms, filename, offset, addr) return addr
def _import_concrete_memory(self, from_addr, to_addr): """ for each address in this range need to read from concrete and write to symbolic it's possible that there will be invalid/unmapped addresses in this range. need to skip to next map if so also need to mark all of these addresses as now in the symbolic store :param int from_addr: :param int to_addr: :return: """ logger.debug("Importing concrete memory: {:x} - {:x} ({} bytes)".format(from_addr, to_addr, to_addr - from_addr)) for m in self.maps: span = interval_intersection(m.start, m.end, from_addr, to_addr) if span is None: continue start, stop = span for addr in range(start, stop): if addr in self.backed_by_symbolic_store: continue self.backing_array[addr] = Memory.read(self, addr, 1)[0] self.backed_by_symbolic_store.add(addr)
def scan_mem(self, data_to_find): """ Scan for concrete bytes in all mapped memory. Successively yield addresses of all matches. :param bytes data_to_find: String to locate :return: """ # TODO: for the moment we just treat symbolic bytes as bytes that don't match. # for our simple test cases right now, the bytes we're interested in scanning # for will all just be there concretely # TODO: Can probably do something smarter here like Boyer-Moore, but unnecessary # if we're looking for short strings. # Querying mem with an index returns [bytes] if isinstance(data_to_find, bytes): data_to_find = [bytes([c]) for c in data_to_find] for mapping in sorted(self.maps): for ptr in mapping: if ptr + len(data_to_find) >= mapping.end: break candidate = mapping[ptr:ptr + len(data_to_find)] # TODO: treat symbolic bytes as bytes that don't match. for our simple tests right now, the # bytes will be there concretely if issymbolic(candidate[0]): break if candidate == data_to_find: yield ptr
def _reg_name(self, reg_id): """ Translates a register ID from the disassembler object into the register name based on manticore's alias in the register file :param int reg_id: Register ID """ if reg_id >= X86_REG_ENDING: logger.warning("Trying to get register name for a non-register") return None cs_reg_name = self.cpu.instruction.reg_name(reg_id) if cs_reg_name is None or cs_reg_name.lower() == '(invalid)': return None return self.cpu._regfile._alias(cs_reg_name.upper())
def values_from(self, base): """ A reusable generator for increasing pointer-sized values from an address (usually the stack). """ word_bytes = self._cpu.address_bit_size // 8 while True: yield base base += word_bytes
def get_argument_values(self, model, prefix_args): """ Extract arguments for model from the environment and return as a tuple that is ready to be passed to the model. :param callable model: Python model of the function :param tuple prefix_args: Parameters to pass to model before actual ones :return: Arguments to be passed to the model :rtype: tuple """ spec = inspect.getfullargspec(model) if spec.varargs: logger.warning("ABI: A vararg model must be a unary function.") nargs = len(spec.args) - len(prefix_args) # If the model is a method, we need to account for `self` if inspect.ismethod(model): nargs -= 1 def resolve_argument(arg): if isinstance(arg, str): return self._cpu.read_register(arg) else: return self._cpu.read_int(arg) # Create a stream of resolved arguments from argument descriptors descriptors = self.get_arguments() argument_iter = map(resolve_argument, descriptors) from ..models import isvariadic # prevent circular imports if isvariadic(model): arguments = prefix_args + (argument_iter,) else: arguments = prefix_args + tuple(islice(argument_iter, nargs)) return arguments
def invoke(self, model, prefix_args=None): """ Invoke a callable `model` as if it was a native function. If :func:`~manticore.models.isvariadic` returns true for `model`, `model` receives a single argument that is a generator for function arguments. Pass a tuple of arguments for `prefix_args` you'd like to precede the actual arguments. :param callable model: Python model of the function :param tuple prefix_args: Parameters to pass to model before actual ones :return: The result of calling `model` """ prefix_args = prefix_args or () arguments = self.get_argument_values(model, prefix_args) try: result = model(*arguments) except ConcretizeArgument as e: assert e.argnum >= len(prefix_args), "Can't concretize a constant arg" idx = e.argnum - len(prefix_args) # Arguments were lazily computed in case of variadic, so recompute here descriptors = self.get_arguments() src = next(islice(descriptors, idx, idx + 1)) msg = 'Concretizing due to model invocation' if isinstance(src, str): raise ConcretizeRegister(self._cpu, src, msg) else: raise ConcretizeMemory(self._cpu.memory, src, self._cpu.address_bit_size, msg) else: if result is not None: self.write_result(result) self.ret() return result
def write_register(self, register, value): """ Dynamic interface for writing cpu registers :param str register: register name (as listed in `self.all_registers`) :param value: register value :type value: int or long or Expression """ self._publish('will_write_register', register, value) value = self._regfile.write(register, value) self._publish('did_write_register', register, value) return value
def read_register(self, register): """ Dynamic interface for reading cpu registers :param str register: register name (as listed in `self.all_registers`) :return: register value :rtype: int or long or Expression """ self._publish('will_read_register', register) value = self._regfile.read(register) self._publish('did_read_register', register, value) return value
def emulate_until(self, target: int): """ Tells the CPU to set up a concrete unicorn emulator and use it to execute instructions until target is reached. :param target: Where Unicorn should hand control back to Manticore. Set to 0 for all instructions. """ self._concrete = True self._break_unicorn_at = target if self.emu: self.emu._stop_at = target
def write_int(self, where, expression, size=None, force=False): """ Writes int to memory :param int where: address to write to :param expr: value to write :type expr: int or BitVec :param size: bit size of `expr` :param force: whether to ignore memory permissions """ if size is None: size = self.address_bit_size assert size in SANE_SIZES self._publish('will_write_memory', where, expression, size) data = [Operators.CHR(Operators.EXTRACT(expression, offset, 8)) for offset in range(0, size, 8)] self._memory.write(where, data, force) self._publish('did_write_memory', where, expression, size)
def _raw_read(self, where: int, size=1) -> bytes: """ Selects bytes from memory. Attempts to do so faster than via read_bytes. :param where: address to read from :param size: number of bytes to read :return: the bytes in memory """ map = self.memory.map_containing(where) start = map._get_offset(where) mapType = type(map) if mapType is FileMap: end = map._get_offset(where + size) if end > map._mapped_size: logger.warning(f"Missing {end - map._mapped_size} bytes at the end of {map._filename}") raw_data = map._data[map._get_offset(where): min(end, map._mapped_size)] if len(raw_data) < end: raw_data += b'\x00' * (end - len(raw_data)) data = b'' for offset in sorted(map._overlay.keys()): data += raw_data[len(data):offset] data += map._overlay[offset] data += raw_data[len(data):] elif mapType is AnonMap: data = bytes(map._data[start:start + size]) else: data = b''.join(self.memory[where:where + size]) assert len(data) == size, 'Raw read resulted in wrong data read which should never happen' return data
def read_int(self, where, size=None, force=False): """ Reads int from memory :param int where: address to read from :param size: number of bits to read :return: the value read :rtype: int or BitVec :param force: whether to ignore memory permissions """ if size is None: size = self.address_bit_size assert size in SANE_SIZES self._publish('will_read_memory', where, size) data = self._memory.read(where, size // 8, force) assert (8 * len(data)) == size value = Operators.CONCAT(size, *map(Operators.ORD, reversed(data))) self._publish('did_read_memory', where, value, size) return value
def write_bytes(self, where, data, force=False): """ Write a concrete or symbolic (or mixed) buffer to memory :param int where: address to write to :param data: data to write :type data: str or list :param force: whether to ignore memory permissions """ mp = self.memory.map_containing(where) # TODO (ehennenfent) - fast write can have some yet-unstudied unintended side effects. # At the very least, using it in non-concrete mode will break the symbolic strcmp/strlen models. The 1024 byte # minimum is intended to minimize the potential effects of this by ensuring that if there _are_ any other # issues, they'll only crop up when we're doing very large writes, which are fairly uncommon. can_write_raw = type(mp) is AnonMap and \ isinstance(data, (str, bytes)) and \ (mp.end - mp.start + 1) >= len(data) >= 1024 and \ not issymbolic(data) and \ self._concrete if can_write_raw: logger.debug("Using fast write") offset = mp._get_offset(where) if isinstance(data, str): data = bytes(data.encode('utf-8')) mp._data[offset:offset + len(data)] = data self._publish('did_write_memory', where, data, 8 * len(data)) else: for i in range(len(data)): self.write_int(where + i, Operators.ORD(data[i]), 8, force)
def read_bytes(self, where, size, force=False): """ Read from memory. :param int where: address to read data from :param int size: number of bytes :param force: whether to ignore memory permissions :return: data :rtype: list[int or Expression] """ result = [] for i in range(size): result.append(Operators.CHR(self.read_int(where + i, 8, force))) return result
def write_string(self, where, string, max_length=None, force=False): """ Writes a string to memory, appending a NULL-terminator at the end. :param int where: Address to write the string to :param str string: The string to write to memory :param int max_length: The size in bytes to cap the string at, or None [default] for no limit. This includes the NULL terminator. :param force: whether to ignore memory permissions """ if max_length is not None: string = string[:max_length - 1] self.write_bytes(where, string + '\x00', force)
def read_string(self, where, max_length=None, force=False): """ Read a NUL-terminated concrete buffer from memory. Stops reading at first symbolic byte. :param int where: Address to read string from :param int max_length: The size in bytes to cap the string at, or None [default] for no limit. :param force: whether to ignore memory permissions :return: string read :rtype: str """ s = io.BytesIO() while True: c = self.read_int(where, 8, force) if issymbolic(c) or c == 0: break if max_length is not None: if max_length == 0: break max_length = max_length - 1 s.write(Operators.CHR(c)) where += 1 return s.getvalue().decode()
def push_bytes(self, data, force=False): """ Write `data` to the stack and decrement the stack pointer accordingly. :param str data: Data to write :param force: whether to ignore memory permissions """ self.STACK -= len(data) self.write_bytes(self.STACK, data, force) return self.STACK
def pop_bytes(self, nbytes, force=False): """ Read `nbytes` from the stack, increment the stack pointer, and return data. :param int nbytes: How many bytes to read :param force: whether to ignore memory permissions :return: Data read from the stack """ data = self.read_bytes(self.STACK, nbytes, force=force) self.STACK += nbytes return data
def push_int(self, value, force=False): """ Decrement the stack pointer and write `value` to the stack. :param int value: The value to write :param force: whether to ignore memory permissions :return: New stack pointer """ self.STACK -= self.address_bit_size // 8 self.write_int(self.STACK, value, force=force) return self.STACK
def pop_int(self, force=False): """ Read a value from the stack and increment the stack pointer. :param force: whether to ignore memory permissions :return: Value read """ value = self.read_int(self.STACK, force=force) self.STACK += self.address_bit_size // 8 return value
def decode_instruction(self, pc): """ This will decode an instruction from memory pointed by `pc` :param int pc: address of the instruction """ # No dynamic code!!! #TODO! # Check if instruction was already decoded if pc in self._instruction_cache: return self._instruction_cache[pc] text = b'' # Read Instruction from memory for address in range(pc, pc + self.max_instr_width): # This reads a byte from memory ignoring permissions # and concretize it if symbolic if not self.memory.access_ok(address, 'x'): break c = self.memory[address] if issymbolic(c): # In case of fully symbolic memory, eagerly get a valid ptr if isinstance(self.memory, LazySMemory): try: vals = visitors.simplify_array_select(c) c = bytes([vals[0]]) except visitors.ArraySelectSimplifier.ExpressionNotSimple: c = struct.pack('B', solver.get_value(self.memory.constraints, c)) elif isinstance(c, Constant): c = bytes([c.value]) else: logger.error('Concretize executable memory %r %r', c, text) raise ConcretizeMemory(self.memory, address=pc, size=8 * self.max_instr_width, policy='INSTRUCTION') text += c # Pad potentially incomplete instruction with zeroes code = text.ljust(self.max_instr_width, b'\x00') try: # decode the instruction from code insn = self.disasm.disassemble_instruction(code, pc) except StopIteration as e: raise DecodeException(pc, code) # Check that the decoded instruction is contained in executable memory if not self.memory.access_ok(slice(pc, pc + insn.size), 'x'): logger.info("Trying to execute instructions from non-executable memory") raise InvalidMemoryAccess(pc, 'x') insn.operands = self._wrap_operands(insn.operands) self._instruction_cache[pc] = insn return insn
def execute(self): """ Decode, and execute one instruction pointed by register PC """ if issymbolic(self.PC): raise ConcretizeRegister(self, 'PC', policy='ALL') if not self.memory.access_ok(self.PC, 'x'): raise InvalidMemoryAccess(self.PC, 'x') self._publish('will_decode_instruction', self.PC) insn = self.decode_instruction(self.PC) self._last_pc = self.PC self._publish('will_execute_instruction', self.PC, insn) # FIXME (theo) why just return here? if insn.address != self.PC: return name = self.canonicalize_instruction_name(insn) if logger.level == logging.DEBUG: logger.debug(self.render_instruction(insn)) for l in self.render_registers(): register_logger.debug(l) try: if self._concrete and 'SYSCALL' in name: self.emu.sync_unicorn_to_manticore() if self._concrete and 'SYSCALL' not in name: self.emulate(insn) if self.PC == self._break_unicorn_at: logger.debug("Switching from Unicorn to Manticore") self._break_unicorn_at = None self._concrete = False else: implementation = getattr(self, name, None) if implementation is not None: implementation(*insn.operands) else: text_bytes = ' '.join('%02x' % x for x in insn.bytes) logger.warning("Unimplemented instruction: 0x%016x:\t%s\t%s\t%s", insn.address, text_bytes, insn.mnemonic, insn.op_str) self.backup_emulate(insn) except (Interruption, Syscall) as e: e.on_handled = lambda: self._publish_instruction_as_executed(insn) raise e else: self._publish_instruction_as_executed(insn)
def _publish_instruction_as_executed(self, insn): """ Notify listeners that an instruction has been executed. """ self._icount += 1 self._publish('did_execute_instruction', self._last_pc, self.PC, insn)
def emulate(self, insn): """ Pick the right emulate function (maintains API compatiblity) :param insn: single instruction to emulate/start emulation from """ if self._concrete: self.concrete_emulate(insn) else: self.backup_emulate(insn)
def concrete_emulate(self, insn): """ Start executing in Unicorn from this point until we hit a syscall or reach break_unicorn_at :param capstone.CsInsn insn: The instruction object to emulate """ if not self.emu: self.emu = ConcreteUnicornEmulator(self) self.emu._stop_at = self._break_unicorn_at try: self.emu.emulate(insn) except unicorn.UcError as e: if e.errno == unicorn.UC_ERR_INSN_INVALID: text_bytes = ' '.join('%02x' % x for x in insn.bytes) logger.error("Unimplemented instruction: 0x%016x:\t%s\t%s\t%s", insn.address, text_bytes, insn.mnemonic, insn.op_str) raise InstructionEmulationError(str(e))
def backup_emulate(self, insn): """ If we could not handle emulating an instruction, use Unicorn to emulate it. :param capstone.CsInsn instruction: The instruction object to emulate """ if not hasattr(self, 'backup_emu'): self.backup_emu = UnicornEmulator(self) try: self.backup_emu.emulate(insn) except unicorn.UcError as e: if e.errno == unicorn.UC_ERR_INSN_INVALID: text_bytes = ' '.join('%02x' % x for x in insn.bytes) logger.error("Unimplemented instruction: 0x%016x:\t%s\t%s\t%s", insn.address, text_bytes, insn.mnemonic, insn.op_str) raise InstructionEmulationError(str(e)) finally: # We have been seeing occasional Unicorn issues with it not clearing # the backing unicorn instance. Saw fewer issues with the following # line present. del self.backup_emu
def viz_trace(view): """ Given a Manticore trace file, highlight the basic blocks. """ tv = TraceVisualizer(view, None) if tv.workspace is None: tv.workspace = get_workspace() tv.visualize()
def viz_live_trace(view): """ Given a Manticore trace file, highlight the basic blocks. """ tv = TraceVisualizer(view, None, live=True) if tv.workspace is None: tv.workspace = get_workspace() # update due to singleton in case we are called after a clear tv.live_update = True tv.visualize()
def visualize(self): """ Given a Manticore workspace, or trace file, highlight the basic blocks. """ if os.path.isfile(self.workspace): t = threading.Thread(target=self.highlight_from_file, args=(self.workspace,)) elif os.path.isdir(self.workspace): t = threading.Thread(target=self.highlight_from_dir, args=(self.workspace,)) t.start()
def t_TOKEN(t): '[a-zA-Z0-9]+' #print t.value,t.lexer.lexdata[t.lexer.lexpos-len(t.value):],re_TYPE.match(t.lexer.lexdata,t.lexer.lexpos-len(t.value)) if re_TYPE.match(t.value): t.type = 'TYPE' elif re_PTR.match(t.value): t.type = 'PTR' elif re_NUMBER.match(t.value): if t.value.startswith('0x'): t.value = t.value[2:] t.value = int(t.value, 16) t.type = 'NUMBER' elif re_REGISTER.match(t.value): t.type = 'REGISTER' elif re_SEGMENT.match(t.value): t.type = 'SEGMENT' else: raise Exception(f"Unknown:<{t.value}>") return t
def p_expression_deref(p): 'expression : TYPE PTR LBRAKET expression RBRAKET' size = sizes[p[1]] address = p[4] char_list = functions['read_memory'](address, size) value = Operators.CONCAT(8 * len(char_list), *reversed(map(Operators.ORD, char_list))) p[0] = value
def p_expression_derefseg(p): 'expression : TYPE PTR SEGMENT COLOM LBRAKET expression RBRAKET' size = sizes[p[1]] address = p[6] seg = functions['read_register'](p[3]) base, limit, _ = functions['get_descriptor'](seg) address = base + address char_list = functions['read_memory'](address, size) value = Operators.CONCAT(8 * len(char_list), *reversed(map(Operators.ORD, char_list))) p[0] = value
def _get_flags(self, reg): """ Build EFLAGS/RFLAGS from flags """ def make_symbolic(flag_expr): register_size = 32 if reg == 'EFLAGS' else 64 value, offset = flag_expr return Operators.ITEBV(register_size, value, BitVecConstant(register_size, 1 << offset), BitVecConstant(register_size, 0)) flags = [] for flag, offset in self._flags.items(): flags.append((self._registers[flag], offset)) if any(issymbolic(flag) for flag, offset in flags): res = reduce(operator.or_, map(make_symbolic, flags)) else: res = 0 for flag, offset in flags: res += flag << offset return res
def _set_flags(self, reg, res): """ Set individual flags from a EFLAGS/RFLAGS value """ #assert sizeof (res) == 32 if reg == 'EFLAGS' else 64 for flag, offset in self._flags.items(): self.write(flag, Operators.EXTRACT(res, offset, 1))
def push(cpu, value, size): """ Writes a value in the stack. :param value: the value to put in the stack. :param size: the size of the value. """ assert size in (8, 16, cpu.address_bit_size) cpu.STACK = cpu.STACK - size // 8 base, _, _ = cpu.get_descriptor(cpu.read_register('SS')) address = cpu.STACK + base cpu.write_int(address, value, size)
def pop(cpu, size): """ Gets a value from the stack. :rtype: int :param size: the size of the value to consume from the stack. :return: the value from the stack. """ assert size in (16, cpu.address_bit_size) base, _, _ = cpu.get_descriptor(cpu.SS) address = cpu.STACK + base value = cpu.read_int(address, size) cpu.STACK = cpu.STACK + size // 8 return value
def invalidate_cache(cpu, address, size): """ remove decoded instruction from instruction cache """ cache = cpu.instruction_cache for offset in range(size): if address + offset in cache: del cache[address + offset]
def CPUID(cpu): """ CPUID instruction. The ID flag (bit 21) in the EFLAGS register indicates support for the CPUID instruction. If a software procedure can set and clear this flag, the processor executing the procedure supports the CPUID instruction. This instruction operates the same in non-64-bit modes and 64-bit mode. CPUID returns processor identification and feature information in the EAX, EBX, ECX, and EDX registers. The instruction's output is dependent on the contents of the EAX register upon execution. :param cpu: current CPU. """ # FIXME Choose conservative values and consider returning some default when eax not here conf = {0x0: (0x0000000d, 0x756e6547, 0x6c65746e, 0x49656e69), 0x1: (0x000306c3, 0x05100800, 0x7ffafbff, 0xbfebfbff), 0x2: (0x76035a01, 0x00f0b5ff, 0x00000000, 0x00c10000), 0x4: {0x0: (0x1c004121, 0x01c0003f, 0x0000003f, 0x00000000), 0x1: (0x1c004122, 0x01c0003f, 0x0000003f, 0x00000000), 0x2: (0x1c004143, 0x01c0003f, 0x000001ff, 0x00000000), 0x3: (0x1c03c163, 0x03c0003f, 0x00000fff, 0x00000006)}, 0x7: (0x00000000, 0x00000000, 0x00000000, 0x00000000), 0x8: (0x00000000, 0x00000000, 0x00000000, 0x00000000), 0xb: {0x0: (0x00000001, 0x00000002, 0x00000100, 0x00000005), 0x1: (0x00000004, 0x00000004, 0x00000201, 0x00000003)}, 0xd: {0x0: (0x00000000, 0x00000000, 0x00000000, 0x00000000), 0x1: (0x00000000, 0x00000000, 0x00000000, 0x00000000)}, } if cpu.EAX not in conf: logger.warning('CPUID with EAX=%x not implemented @ %x', cpu.EAX, cpu.PC) cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = 0, 0, 0, 0 return if isinstance(conf[cpu.EAX], tuple): cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = conf[cpu.EAX] return if cpu.ECX not in conf[cpu.EAX]: logger.warning('CPUID with EAX=%x ECX=%x not implemented', cpu.EAX, cpu.ECX) cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = 0, 0, 0, 0 return cpu.EAX, cpu.EBX, cpu.ECX, cpu.EDX = conf[cpu.EAX][cpu.ECX]
def AND(cpu, dest, src): """ Logical AND. Performs a bitwise AND operation on the destination (first) and source (second) operands and stores the result in the destination operand location. Each bit of the result is set to 1 if both corresponding bits of the first and second operands are 1; otherwise, it is set to 0. The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result:: DEST = DEST AND SRC; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ # XXX bypass a capstone bug that incorrectly extends and computes operands sizes # the bug has been fixed since capstone 4.0.alpha2 (commit de8dd26) if src.size == 64 and src.type == 'immediate' and dest.size == 64: arg1 = Operators.SEXTEND(src.read(), 32, 64) else: arg1 = src.read() res = dest.write(dest.read() & arg1) # Defined Flags: szp cpu._calculate_logic_flags(dest.size, res)
def TEST(cpu, src1, src2): """ Logical compare. Computes the bit-wise logical AND of first operand (source 1 operand) and the second operand (source 2 operand) and sets the SF, ZF, and PF status flags according to the result. The result is then discarded:: TEMP = SRC1 AND SRC2; SF = MSB(TEMP); IF TEMP = 0 THEN ZF = 1; ELSE ZF = 0; FI: PF = BitwiseXNOR(TEMP[0:7]); CF = 0; OF = 0; (*AF is Undefined*) :param cpu: current CPU. :param src1: first operand. :param src2: second operand. """ # Defined Flags: szp temp = src1.read() & src2.read() cpu.SF = (temp & (1 << (src1.size - 1))) != 0 cpu.ZF = temp == 0 cpu.PF = cpu._calculate_parity_flag(temp) cpu.CF = False cpu.OF = False
def XOR(cpu, dest, src): """ Logical exclusive OR. Performs a bitwise exclusive Operators.OR(XOR) operation on the destination (first) and source (second) operands and stores the result in the destination operand location. Each bit of the result is 1 if the corresponding bits of the operands are different; each bit is 0 if the corresponding bits are the same. The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result:: DEST = DEST XOR SRC; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ if dest == src: # if the operands are the same write zero res = dest.write(0) else: res = dest.write(dest.read() ^ src.read()) # Defined Flags: szp cpu._calculate_logic_flags(dest.size, res)
def OR(cpu, dest, src): """ Logical inclusive OR. Performs a bitwise inclusive OR operation between the destination (first) and source (second) operands and stores the result in the destination operand location. Each bit of the result of the OR instruction is set to 0 if both corresponding bits of the first and second operands are 0; otherwise, each bit is set to 1. The OF and CF flags are cleared; the SF, ZF, and PF flags are set according to the result:: DEST = DEST OR SRC; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ res = dest.write(dest.read() | src.read()) # Defined Flags: szp cpu._calculate_logic_flags(dest.size, res)
def AAA(cpu): """ ASCII adjust after addition. Adjusts the sum of two unpacked BCD values to create an unpacked BCD result. The AL register is the implied source and destination operand for this instruction. The AAA instruction is only useful when it follows an ADD instruction that adds (binary addition) two unpacked BCD values and stores a byte result in the AL register. The AAA instruction then adjusts the contents of the AL register to contain the correct 1-digit unpacked BCD result. If the addition produces a decimal carry, the AH register is incremented by 1, and the CF and AF flags are set. If there was no decimal carry, the CF and AF flags are cleared and the AH register is unchanged. In either case, bits 4 through 7 of the AL register are cleared to 0. This instruction executes as described in compatibility mode and legacy mode. It is not valid in 64-bit mode. :: IF ((AL AND 0FH) > 9) Operators.OR(AF = 1) THEN AL = (AL + 6); AH = AH + 1; AF = 1; CF = 1; ELSE AF = 0; CF = 0; FI; AL = AL AND 0FH; :param cpu: current CPU. """ cpu.AF = Operators.OR(cpu.AL & 0x0F > 9, cpu.AF) cpu.CF = cpu.AF cpu.AH = Operators.ITEBV(8, cpu.AF, cpu.AH + 1, cpu.AH) cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL + 6, cpu.AL) """ if (cpu.AL & 0x0F > 9) or cpu.AF == 1: cpu.AL = cpu.AL + 6 cpu.AH = cpu.AH + 1 cpu.AF = True cpu.CF = True else: cpu.AF = False cpu.CF = False """ cpu.AL = cpu.AL & 0x0f
def AAD(cpu, imm=None): """ ASCII adjust AX before division. Adjusts two unpacked BCD digits (the least-significant digit in the AL register and the most-significant digit in the AH register) so that a division operation performed on the result will yield a correct unpacked BCD value. The AAD instruction is only useful when it precedes a DIV instruction that divides (binary division) the adjusted value in the AX register by an unpacked BCD value. The AAD instruction sets the value in the AL register to (AL + (10 * AH)), and then clears the AH register to 00H. The value in the AX register is then equal to the binary equivalent of the original unpacked two-digit (base 10) number in registers AH and AL. The SF, ZF, and PF flags are set according to the resulting binary value in the AL register. This instruction executes as described in compatibility mode and legacy mode. It is not valid in 64-bit mode.:: tempAL = AL; tempAH = AH; AL = (tempAL + (tempAH * 10)) AND FFH; AH = 0 :param cpu: current CPU. """ if imm is None: imm = 10 else: imm = imm.read() cpu.AL += cpu.AH * imm cpu.AH = 0 # Defined flags: ...sz.p. cpu._calculate_logic_flags(8, cpu.AL)
def AAM(cpu, imm=None): """ ASCII adjust AX after multiply. Adjusts the result of the multiplication of two unpacked BCD values to create a pair of unpacked (base 10) BCD values. The AX register is the implied source and destination operand for this instruction. The AAM instruction is only useful when it follows a MUL instruction that multiplies (binary multiplication) two unpacked BCD values and stores a word result in the AX register. The AAM instruction then adjusts the contents of the AX register to contain the correct 2-digit unpacked (base 10) BCD result. The SF, ZF, and PF flags are set according to the resulting binary value in the AL register. This instruction executes as described in compatibility mode and legacy mode. It is not valid in 64-bit mode.:: tempAL = AL; AH = tempAL / 10; AL = tempAL MOD 10; :param cpu: current CPU. """ if imm is None: imm = 10 else: imm = imm.read() cpu.AH = Operators.UDIV(cpu.AL, imm) cpu.AL = Operators.UREM(cpu.AL, imm) # Defined flags: ...sz.p. cpu._calculate_logic_flags(8, cpu.AL)
def AAS(cpu): """ ASCII Adjust AL after subtraction. Adjusts the result of the subtraction of two unpacked BCD values to create a unpacked BCD result. The AL register is the implied source and destination operand for this instruction. The AAS instruction is only useful when it follows a SUB instruction that subtracts (binary subtraction) one unpacked BCD value from another and stores a byte result in the AL register. The AAA instruction then adjusts the contents of the AL register to contain the correct 1-digit unpacked BCD result. If the subtraction produced a decimal carry, the AH register is decremented by 1, and the CF and AF flags are set. If no decimal carry occurred, the CF and AF flags are cleared, and the AH register is unchanged. In either case, the AL register is left with its top nibble set to 0. The AF and CF flags are set to 1 if there is a decimal borrow; otherwise, they are cleared to 0. This instruction executes as described in compatibility mode and legacy mode. It is not valid in 64-bit mode.:: IF ((AL AND 0FH) > 9) Operators.OR(AF = 1) THEN AX = AX - 6; AH = AH - 1; AF = 1; CF = 1; ELSE CF = 0; AF = 0; FI; AL = AL AND 0FH; :param cpu: current CPU. """ if (cpu.AL & 0x0F > 9) or cpu.AF == 1: cpu.AX = cpu.AX - 6 cpu.AH = cpu.AH - 1 cpu.AF = True cpu.CF = True else: cpu.AF = False cpu.CF = False cpu.AL = cpu.AL & 0x0f
def ADC(cpu, dest, src): """ Adds with carry. Adds the destination operand (first operand), the source operand (second operand), and the carry (CF) flag and stores the result in the destination operand. The state of the CF flag represents a carry from a previous addition. When an immediate value is used as an operand, it is sign-extended to the length of the destination operand format. The ADC instruction does not distinguish between signed or unsigned operands. Instead, the processor evaluates the result for both data types and sets the OF and CF flags to indicate a carry in the signed or unsigned result, respectively. The SF flag indicates the sign of the signed result. The ADC instruction is usually executed as part of a multibyte or multiword addition in which an ADD instruction is followed by an ADC instruction:: DEST = DEST + SRC + CF; The OF, SF, ZF, AF, CF, and PF flags are set according to the result. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ cpu._ADD(dest, src, carry=True)
def ADD(cpu, dest, src): """ Add. Adds the first operand (destination operand) and the second operand (source operand) and stores the result in the destination operand. When an immediate value is used as an operand, it is sign-extended to the length of the destination operand format. The ADD instruction does not distinguish between signed or unsigned operands. Instead, the processor evaluates the result for both data types and sets the OF and CF flags to indicate a carry in the signed or unsigned result, respectively. The SF flag indicates the sign of the signed result:: DEST = DEST + SRC; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ cpu._ADD(dest, src, carry=False)
def CMP(cpu, src1, src2): """ Compares two operands. Compares the first source operand with the second source operand and sets the status flags in the EFLAGS register according to the results. The comparison is performed by subtracting the second operand from the first operand and then setting the status flags in the same manner as the SUB instruction. When an immediate value is used as an operand, it is sign-extended to the length of the first operand:: temp = SRC1 - SignExtend(SRC2); ModifyStatusFlags; (* Modify status flags in the same manner as the SUB instruction*) The CF, OF, SF, ZF, AF, and PF flags are set according to the result. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ arg0 = src1.read() arg1 = Operators.SEXTEND(src2.read(), src2.size, src1.size) # Affected Flags o..szapc cpu._calculate_CMP_flags(src1.size, arg0 - arg1, arg0, arg1)
def CMPXCHG(cpu, dest, src): """ Compares and exchanges. Compares the value in the AL, AX, EAX or RAX register (depending on the size of the operand) with the first operand (destination operand). If the two values are equal, the second operand (source operand) is loaded into the destination operand. Otherwise, the destination operand is loaded into the AL, AX, EAX or RAX register. The ZF flag is set if the values in the destination operand and register AL, AX, or EAX are equal; otherwise it is cleared. The CF, PF, AF, SF, and OF flags are set according to the results of the comparison operation:: (* accumulator = AL, AX, EAX or RAX, depending on whether *) (* a byte, word, a doubleword or a 64bit comparison is being performed*) IF accumulator == DEST THEN ZF = 1 DEST = SRC ELSE ZF = 0 accumulator = DEST FI; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ size = dest.size reg_name = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size] accumulator = cpu.read_register(reg_name) sval = src.read() dval = dest.read() cpu.write_register(reg_name, dval) dest.write(Operators.ITEBV(size, accumulator == dval, sval, dval)) # Affected Flags o..szapc cpu._calculate_CMP_flags(size, accumulator - dval, accumulator, dval)
def CMPXCHG8B(cpu, dest): """ Compares and exchanges bytes. Compares the 64-bit value in EDX:EAX (or 128-bit value in RDX:RAX if operand size is 128 bits) with the operand (destination operand). If the values are equal, the 64-bit value in ECX:EBX (or 128-bit value in RCX:RBX) is stored in the destination operand. Otherwise, the value in the destination operand is loaded into EDX:EAX (or RDX:RAX):: IF (64-Bit Mode and OperandSize = 64) THEN IF (RDX:RAX = DEST) THEN ZF = 1; DEST = RCX:RBX; ELSE ZF = 0; RDX:RAX = DEST; FI ELSE IF (EDX:EAX = DEST) THEN ZF = 1; DEST = ECX:EBX; ELSE ZF = 0; EDX:EAX = DEST; FI; FI; :param cpu: current CPU. :param dest: destination operand. """ size = dest.size cmp_reg_name_l = {64: 'EAX', 128: 'RAX'}[size] cmp_reg_name_h = {64: 'EDX', 128: 'RDX'}[size] src_reg_name_l = {64: 'EBX', 128: 'RBX'}[size] src_reg_name_h = {64: 'ECX', 128: 'RCX'}[size] # EDX:EAX or RDX:RAX cmph = cpu.read_register(cmp_reg_name_h) cmpl = cpu.read_register(cmp_reg_name_l) srch = cpu.read_register(src_reg_name_h) srcl = cpu.read_register(src_reg_name_l) cmp0 = Operators.CONCAT(size, cmph, cmpl) src0 = Operators.CONCAT(size, srch, srcl) arg_dest = dest.read() cpu.ZF = arg_dest == cmp0 dest.write( Operators.ITEBV(size, cpu.ZF, Operators.CONCAT(size, srch, srcl), arg_dest) ) cpu.write_register(cmp_reg_name_l, Operators.ITEBV(size // 2, cpu.ZF, cmpl, Operators.EXTRACT(arg_dest, 0, size // 2))) cpu.write_register(cmp_reg_name_h, Operators.ITEBV(size // 2, cpu.ZF, cmph, Operators.EXTRACT(arg_dest, size // 2, size // 2)))
def DAA(cpu): """ Decimal adjusts AL after addition. Adjusts the sum of two packed BCD values to create a packed BCD result. The AL register is the implied source and destination operand. If a decimal carry is detected, the CF and AF flags are set accordingly. The CF and AF flags are set if the adjustment of the value results in a decimal carry in either digit of the result. The SF, ZF, and PF flags are set according to the result. This instruction is not valid in 64-bit mode.:: IF (((AL AND 0FH) > 9) or AF = 1) THEN AL = AL + 6; CF = CF OR CarryFromLastAddition; (* CF OR carry from AL = AL + 6 *) AF = 1; ELSE AF = 0; FI; IF ((AL AND F0H) > 90H) or CF = 1) THEN AL = AL + 60H; CF = 1; ELSE CF = 0; FI; :param cpu: current CPU. """ cpu.AF = Operators.OR((cpu.AL & 0x0f) > 9, cpu.AF) oldAL = cpu.AL cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL + 6, cpu.AL) cpu.CF = Operators.ITE(cpu.AF, Operators.OR(cpu.CF, cpu.AL < oldAL), cpu.CF) cpu.CF = Operators.OR((cpu.AL & 0xf0) > 0x90, cpu.CF) cpu.AL = Operators.ITEBV(8, cpu.CF, cpu.AL + 0x60, cpu.AL) """ #old not-symbolic aware version... if ((cpu.AL & 0x0f) > 9) or cpu.AF: oldAL = cpu.AL cpu.AL = cpu.AL + 6 cpu.CF = Operators.OR(cpu.CF, cpu.AL < oldAL) cpu.AF = True else: cpu.AF = False if ((cpu.AL & 0xf0) > 0x90) or cpu.CF: cpu.AL = cpu.AL + 0x60 cpu.CF = True else: cpu.CF = False """ cpu.ZF = cpu.AL == 0 cpu.SF = (cpu.AL & 0x80) != 0 cpu.PF = cpu._calculate_parity_flag(cpu.AL)
def DAS(cpu): """ Decimal adjusts AL after subtraction. Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result. The AL register is the implied source and destination operand. If a decimal borrow is detected, the CF and AF flags are set accordingly. This instruction is not valid in 64-bit mode. The SF, ZF, and PF flags are set according to the result.:: IF (AL AND 0FH) > 9 OR AF = 1 THEN AL = AL - 6; CF = CF OR BorrowFromLastSubtraction; (* CF OR borrow from AL = AL - 6 *) AF = 1; ELSE AF = 0; FI; IF ((AL > 99H) or OLD_CF = 1) THEN AL = AL - 60H; CF = 1; :param cpu: current CPU. """ oldAL = cpu.AL oldCF = cpu.CF cpu.AF = Operators.OR((cpu.AL & 0x0f) > 9, cpu.AF) cpu.AL = Operators.ITEBV(8, cpu.AF, cpu.AL - 6, cpu.AL) cpu.CF = Operators.ITE(cpu.AF, Operators.OR(oldCF, cpu.AL > oldAL), cpu.CF) cpu.CF = Operators.ITE(Operators.OR(oldAL > 0x99, oldCF), True, cpu.CF) cpu.AL = Operators.ITEBV(8, Operators.OR(oldAL > 0x99, oldCF), cpu.AL - 0x60, cpu.AL) # """ if (cpu.AL & 0x0f) > 9 or cpu.AF: cpu.AL = cpu.AL - 6; cpu.CF = Operators.OR(oldCF, cpu.AL > oldAL) cpu.AF = True else: cpu.AF = False if ((oldAL > 0x99) or oldCF): cpu.AL = cpu.AL - 0x60 cpu.CF = True """ cpu.ZF = cpu.AL == 0 cpu.SF = (cpu.AL & 0x80) != 0 cpu.PF = cpu._calculate_parity_flag(cpu.AL)
def DIV(cpu, src): """ Unsigned divide. Divides (unsigned) the value in the AX register, DX:AX register pair, or EDX:EAX or RDX:RAX register pair (dividend) by the source operand (divisor) and stores the result in the AX (AH:AL), DX:AX, EDX:EAX or RDX:RAX registers. The source operand can be a general-purpose register or a memory location. The action of this instruction depends of the operand size (dividend/divisor). Division using 64-bit operand is available only in 64-bit mode. Non-integral results are truncated (chopped) towards 0. The reminder is always less than the divisor in magnitude. Overflow is indicated with the #DE (divide error) exception rather than with the CF flag:: IF SRC = 0 THEN #DE; FI;(* divide error *) IF OperandSize = 8 (* word/byte operation *) THEN temp = AX / SRC; IF temp > FFH THEN #DE; (* divide error *) ; ELSE AL = temp; AH = AX MOD SRC; FI; ELSE IF OperandSize = 16 (* doubleword/word operation *) THEN temp = DX:AX / SRC; IF temp > FFFFH THEN #DE; (* divide error *) ; ELSE AX = temp; DX = DX:AX MOD SRC; FI; FI; ELSE If OperandSize = 32 (* quadword/doubleword operation *) THEN temp = EDX:EAX / SRC; IF temp > FFFFFFFFH THEN #DE; (* divide error *) ; ELSE EAX = temp; EDX = EDX:EAX MOD SRC; FI; FI; ELSE IF OperandSize = 64 (*Doublequadword/quadword operation*) THEN temp = RDX:RAX / SRC; IF temp > FFFFFFFFFFFFFFFFH THEN #DE; (* Divide error *) ELSE RAX = temp; RDX = RDX:RAX MOD SRC; FI; FI; FI; :param cpu: current CPU. :param src: source operand. """ size = src.size reg_name_h = {8: 'DL', 16: 'DX', 32: 'EDX', 64: 'RDX'}[size] reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[size] dividend = Operators.CONCAT(size * 2, cpu.read_register(reg_name_h), cpu.read_register(reg_name_l)) divisor = Operators.ZEXTEND(src.read(), size * 2) # TODO make symbol friendly if isinstance(divisor, int) and divisor == 0: raise DivideByZeroError() quotient = Operators.UDIV(dividend, divisor) MASK = (1 << size) - 1 # TODO make symbol friendly if isinstance(quotient, int) and quotient > MASK: raise DivideByZeroError() remainder = Operators.UREM(dividend, divisor) cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, size)) cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, size))
def IDIV(cpu, src): """ Signed divide. Divides (signed) the value in the AL, AX, or EAX register by the source operand and stores the result in the AX, DX:AX, or EDX:EAX registers. The source operand can be a general-purpose register or a memory location. The action of this instruction depends on the operand size.:: IF SRC = 0 THEN #DE; (* divide error *) FI; IF OpernadSize = 8 (* word/byte operation *) THEN temp = AX / SRC; (* signed division *) IF (temp > 7FH) Operators.OR(temp < 80H) (* if a positive result is greater than 7FH or a negative result is less than 80H *) THEN #DE; (* divide error *) ; ELSE AL = temp; AH = AX SignedModulus SRC; FI; ELSE IF OpernadSize = 16 (* doubleword/word operation *) THEN temp = DX:AX / SRC; (* signed division *) IF (temp > 7FFFH) Operators.OR(temp < 8000H) (* if a positive result is greater than 7FFFH *) (* or a negative result is less than 8000H *) THEN #DE; (* divide error *) ; ELSE AX = temp; DX = DX:AX SignedModulus SRC; FI; ELSE (* quadword/doubleword operation *) temp = EDX:EAX / SRC; (* signed division *) IF (temp > 7FFFFFFFH) Operators.OR(temp < 80000000H) (* if a positive result is greater than 7FFFFFFFH *) (* or a negative result is less than 80000000H *) THEN #DE; (* divide error *) ; ELSE EAX = temp; EDX = EDX:EAX SignedModulus SRC; FI; FI; FI; :param cpu: current CPU. :param src: source operand. """ reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[src.size] reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[src.size] dividend = Operators.CONCAT(src.size * 2, cpu.read_register(reg_name_h), cpu.read_register(reg_name_l)) divisor = src.read() if isinstance(divisor, int) and divisor == 0: raise DivideByZeroError() dst_size = src.size * 2 divisor = Operators.SEXTEND(divisor, src.size, dst_size) mask = (1 << dst_size) - 1 sign_mask = 1 << (dst_size - 1) dividend_sign = (dividend & sign_mask) != 0 divisor_sign = (divisor & sign_mask) != 0 if isinstance(divisor, int): if divisor_sign: divisor = ((~divisor) + 1) & mask divisor = -divisor if isinstance(dividend, int): if dividend_sign: dividend = ((~dividend) + 1) & mask dividend = -dividend quotient = Operators.SDIV(dividend, divisor) if (isinstance(dividend, int) and isinstance(dividend, int)): # handle the concrete case remainder = dividend - (quotient * divisor) else: # symbolic case -- optimize via SREM remainder = Operators.SREM(dividend, divisor) cpu.write_register(reg_name_l, Operators.EXTRACT(quotient, 0, src.size)) cpu.write_register(reg_name_h, Operators.EXTRACT(remainder, 0, src.size))
def IMUL(cpu, *operands): """ Signed multiply. Performs a signed multiplication of two operands. This instruction has three forms, depending on the number of operands. - One-operand form. This form is identical to that used by the MUL instruction. Here, the source operand (in a general-purpose register or memory location) is multiplied by the value in the AL, AX, or EAX register (depending on the operand size) and the product is stored in the AX, DX:AX, or EDX:EAX registers, respectively. - Two-operand form. With this form the destination operand (the first operand) is multiplied by the source operand (second operand). The destination operand is a general-purpose register and the source operand is an immediate value, a general-purpose register, or a memory location. The product is then stored in the destination operand location. - Three-operand form. This form requires a destination operand (the first operand) and two source operands (the second and the third operands). Here, the first source operand (which can be a general-purpose register or a memory location) is multiplied by the second source operand (an immediate value). The product is then stored in the destination operand (a general-purpose register). When an immediate value is used as an operand, it is sign-extended to the length of the destination operand format. The CF and OF flags are set when significant bits are carried into the upper half of the result. The CF and OF flags are cleared when the result fits exactly in the lower half of the result. The three forms of the IMUL instruction are similar in that the length of the product is calculated to twice the length of the operands. With the one-operand form, the product is stored exactly in the destination. With the two- and three- operand forms, however, result is truncated to the length of the destination before it is stored in the destination register. Because of this truncation, the CF or OF flag should be tested to ensure that no significant bits are lost. The two- and three-operand forms may also be used with unsigned operands because the lower half of the product is the same regardless if the operands are signed or unsigned. The CF and OF flags, however, cannot be used to determine if the upper half of the result is non-zero:: IF (NumberOfOperands == 1) THEN IF (OperandSize == 8) THEN AX = AL * SRC (* Signed multiplication *) IF AL == AX THEN CF = 0; OF = 0; ELSE CF = 1; OF = 1; FI; ELSE IF OperandSize == 16 THEN DX:AX = AX * SRC (* Signed multiplication *) IF sign_extend_to_32 (AX) == DX:AX THEN CF = 0; OF = 0; ELSE CF = 1; OF = 1; FI; ELSE IF OperandSize == 32 THEN EDX:EAX = EAX * SRC (* Signed multiplication *) IF EAX == EDX:EAX THEN CF = 0; OF = 0; ELSE CF = 1; OF = 1; FI; ELSE (* OperandSize = 64 *) RDX:RAX = RAX * SRC (* Signed multiplication *) IF RAX == RDX:RAX THEN CF = 0; OF = 0; ELSE CF = 1; OF = 1; FI; FI; FI; ELSE IF (NumberOfOperands = 2) THEN temp = DEST * SRC (* Signed multiplication; temp is double DEST size *) DEST = DEST * SRC (* Signed multiplication *) IF temp != DEST THEN CF = 1; OF = 1; ELSE CF = 0; OF = 0; FI; ELSE (* NumberOfOperands = 3 *) DEST = SRC1 * SRC2 (* Signed multiplication *) temp = SRC1 * SRC2 (* Signed multiplication; temp is double SRC1 size *) IF temp != DEST THEN CF = 1; OF = 1; ELSE CF = 0; OF = 0; FI; FI; FI; :param cpu: current CPU. :param operands: variable list of operands. """ dest = operands[0] OperandSize = dest.size reg_name_h = {8: 'AH', 16: 'DX', 32: 'EDX', 64: 'RDX'}[OperandSize] reg_name_l = {8: 'AL', 16: 'AX', 32: 'EAX', 64: 'RAX'}[OperandSize] arg0 = dest.read() arg1 = None arg2 = None res = None if len(operands) == 1: arg1 = cpu.read_register(reg_name_l) temp = (Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) * Operators.SEXTEND(arg1, OperandSize, OperandSize * 2)) temp = temp & ((1 << (OperandSize * 2)) - 1) cpu.write_register(reg_name_l, Operators.EXTRACT(temp, 0, OperandSize)) cpu.write_register(reg_name_h, Operators.EXTRACT(temp, OperandSize, OperandSize)) res = Operators.EXTRACT(temp, 0, OperandSize) elif len(operands) == 2: arg1 = operands[1].read() arg1 = Operators.SEXTEND(arg1, OperandSize, OperandSize * 2) temp = Operators.SEXTEND(arg0, OperandSize, OperandSize * 2) * arg1 temp = temp & ((1 << (OperandSize * 2)) - 1) res = dest.write(Operators.EXTRACT(temp, 0, OperandSize)) else: arg1 = operands[1].read() arg2 = operands[2].read() temp = (Operators.SEXTEND(arg1, OperandSize, OperandSize * 2) * Operators.SEXTEND(arg2, operands[2].size, OperandSize * 2)) temp = temp & ((1 << (OperandSize * 2)) - 1) res = dest.write(Operators.EXTRACT(temp, 0, OperandSize)) cpu.CF = (Operators.SEXTEND(res, OperandSize, OperandSize * 2) != temp) cpu.OF = cpu.CF
def INC(cpu, dest): """ Increments by 1. Adds 1 to the destination operand, while preserving the state of the CF flag. The destination operand can be a register or a memory location. This instruction allows a loop counter to be updated without disturbing the CF flag. (Use a ADD instruction with an immediate operand of 1 to perform an increment operation that does updates the CF flag.):: DEST = DEST +1; :param cpu: current CPU. :param dest: destination operand. """ arg0 = dest.read() res = dest.write(arg0 + 1) res &= (1 << dest.size) - 1 SIGN_MASK = 1 << (dest.size - 1) cpu.AF = ((arg0 ^ 1) ^ res) & 0x10 != 0 cpu.ZF = res == 0 cpu.SF = (res & SIGN_MASK) != 0 cpu.OF = res == SIGN_MASK cpu.PF = cpu._calculate_parity_flag(res)
def MUL(cpu, src): """ Unsigned multiply. Performs an unsigned multiplication of the first operand (destination operand) and the second operand (source operand) and stores the result in the destination operand. The destination operand is an implied operand located in register AL, AX or EAX (depending on the size of the operand); the source operand is located in a general-purpose register or a memory location. The result is stored in register AX, register pair DX:AX, or register pair EDX:EAX (depending on the operand size), with the high-order bits of the product contained in register AH, DX, or EDX, respectively. If the high-order bits of the product are 0, the CF and OF flags are cleared; otherwise, the flags are set:: IF byte operation THEN AX = AL * SRC ELSE (* word or doubleword operation *) IF OperandSize = 16 THEN DX:AX = AX * SRC ELSE (* OperandSize = 32 *) EDX:EAX = EAX * SRC FI; FI; :param cpu: current CPU. :param src: source operand. """ size = src.size reg_name_low, reg_name_high = {8: ('AL', 'AH'), 16: ('AX', 'DX'), 32: ('EAX', 'EDX'), 64: ('RAX', 'RDX')}[size] res = (Operators.ZEXTEND(cpu.read_register(reg_name_low), 256) * Operators.ZEXTEND(src.read(), 256)) cpu.write_register(reg_name_low, Operators.EXTRACT(res, 0, size)) cpu.write_register(reg_name_high, Operators.EXTRACT(res, size, size)) cpu.OF = Operators.EXTRACT(res, size, size) != 0 cpu.CF = cpu.OF
def NEG(cpu, dest): """ Two's complement negation. Replaces the value of operand (the destination operand) with its two's complement. (This operation is equivalent to subtracting the operand from 0.) The destination operand is located in a general-purpose register or a memory location:: IF DEST = 0 THEN CF = 0 ELSE CF = 1; FI; DEST = - (DEST) :param cpu: current CPU. :param dest: destination operand. """ source = dest.read() res = dest.write(-source) cpu._calculate_logic_flags(dest.size, res) cpu.CF = source != 0 cpu.AF = (res & 0x0f) != 0x00
def SBB(cpu, dest, src): """ Integer subtraction with borrow. Adds the source operand (second operand) and the carry (CF) flag, and subtracts the result from the destination operand (first operand). The result of the subtraction is stored in the destination operand. The destination operand can be a register or a memory location; the source operand can be an immediate, a register, or a memory location. (However, two memory operands cannot be used in one instruction.) The state of the CF flag represents a borrow from a previous subtraction. When an immediate value is used as an operand, it is sign-extended to the length of the destination operand format. The SBB instruction does not distinguish between signed or unsigned operands. Instead, the processor evaluates the result for both data types and sets the OF and CF flags to indicate a borrow in the signed or unsigned result, respectively. The SF flag indicates the sign of the signed result. The SBB instruction is usually executed as part of a multibyte or multiword subtraction in which a SUB instruction is followed by a SBB instruction:: DEST = DEST - (SRC + CF); :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ cpu._SUB(dest, src, carry=True)
def SUB(cpu, dest, src): """ Subtract. Subtracts the second operand (source operand) from the first operand (destination operand) and stores the result in the destination operand. The destination operand can be a register or a memory location; the source operand can be an immediate, register, or memory location. (However, two memory operands cannot be used in one instruction.) When an immediate value is used as an operand, it is sign-extended to the length of the destination operand format. The SUB instruction does not distinguish between signed or unsigned operands. Instead, the processor evaluates the result for both data types and sets the OF and CF flags to indicate a borrow in the signed or unsigned result, respectively. The SF flag indicates the sign of the signed result:: DEST = DEST - SRC; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ cpu._SUB(dest, src, carry=False)
def XADD(cpu, dest, src): """ Exchanges and adds. Exchanges the first operand (destination operand) with the second operand (source operand), then loads the sum of the two values into the destination operand. The destination operand can be a register or a memory location; the source operand is a register. This instruction can be used with a LOCK prefix:: TEMP = SRC + DEST SRC = DEST DEST = TEMP :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ MASK = (1 << dest.size) - 1 SIGN_MASK = 1 << (dest.size - 1) arg0 = dest.read() arg1 = src.read() temp = (arg1 + arg0) & MASK src.write(arg0) dest.write(temp) # Affected flags: oszapc tempCF = Operators.OR(Operators.ULT(temp, arg0), Operators.ULT(temp, arg1)) cpu.CF = tempCF cpu.AF = ((arg0 ^ arg1) ^ temp) & 0x10 != 0 cpu.ZF = temp == 0 cpu.SF = (temp & SIGN_MASK) != 0 cpu.OF = (((arg0 ^ arg1 ^ SIGN_MASK) & (temp ^ arg1)) & SIGN_MASK) != 0 cpu.PF = cpu._calculate_parity_flag(temp)
def BSWAP(cpu, dest): """ Byte swap. Reverses the byte order of a 32-bit (destination) register: bits 0 through 7 are swapped with bits 24 through 31, and bits 8 through 15 are swapped with bits 16 through 23. This instruction is provided for converting little-endian values to big-endian format and vice versa. To swap bytes in a word value (16-bit register), use the XCHG instruction. When the BSWAP instruction references a 16-bit register, the result is undefined:: TEMP = DEST DEST[7..0] = TEMP[31..24] DEST[15..8] = TEMP[23..16] DEST[23..16] = TEMP[15..8] DEST[31..24] = TEMP[7..0] :param cpu: current CPU. :param dest: destination operand. """ parts = [] arg0 = dest.read() for i in range(0, dest.size, 8): parts.append(Operators.EXTRACT(arg0, i, 8)) dest.write(Operators.CONCAT(8 * len(parts), *parts))
def CMOVB(cpu, dest, src): """ Conditional move - Below/not above or equal. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.CF, src.read(), dest.read()))
def CMOVA(cpu, dest, src): """ Conditional move - Above/not below or equal. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.CF == False, cpu.ZF == False), src.read(), dest.read()))
def CMOVAE(cpu, dest, src): """ Conditional move - Above or equal/not below. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.CF == False, src.read(), dest.read()))
def CMOVBE(cpu, dest, src): """ Conditional move - Below or equal/not above. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF), src.read(), dest.read()))
def CMOVZ(cpu, dest, src): """ Conditional move - Equal/zero. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.ZF, src.read(), dest.read()))
def CMOVNZ(cpu, dest, src): """ Conditional move - Not equal/not zero. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.ZF == False, src.read(), dest.read()))
def CMOVP(cpu, dest, src): """ Conditional move - Parity/parity even. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.PF, src.read(), dest.read()))
def CMOVNP(cpu, dest, src): """ Conditional move - Not parity/parity odd. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.PF == False, src.read(), dest.read()))
def CMOVG(cpu, dest, src): """ Conditional move - Greater. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, Operators.AND(cpu.ZF == 0, cpu.SF == cpu.OF), src.read(), dest.read()))
def CMOVGE(cpu, dest, src): """ Conditional move - Greater or equal/not less. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, (cpu.SF ^ cpu.OF) == 0, src.read(), dest.read()))
def CMOVLE(cpu, dest, src): """ Conditional move - Less or equal/not greater. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.SF ^ cpu.OF, cpu.ZF), src.read(), dest.read()))
def CMOVO(cpu, dest, src): """ Conditional move - Overflow. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.OF, src.read(), dest.read()))
def CMOVNO(cpu, dest, src): """ Conditional move - Not overflow. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.OF == False, src.read(), dest.read()))
def CMOVS(cpu, dest, src): """ Conditional move - Sign (negative). Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.SF, src.read(), dest.read()))
def CMOVNS(cpu, dest, src): """ Conditional move - Not sign (non-negative). Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.ITEBV(dest.size, cpu.SF == False, src.read(), dest.read()))
def LAHF(cpu): """ Loads status flags into AH register. Moves the low byte of the EFLAGS register (which includes status flags SF, ZF, AF, PF, and CF) to the AH register. Reserved bits 1, 3, and 5 of the EFLAGS register are set in the AH register:: AH = EFLAGS(SF:ZF:0:AF:0:PF:1:CF); :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ used_regs = (cpu.SF, cpu.ZF, cpu.AF, cpu.PF, cpu.CF) is_expression = any(issymbolic(x) for x in used_regs) def make_flag(val, offset): if is_expression: return Operators.ITEBV(8, val, BitVecConstant(8, 1 << offset), BitVecConstant(8, 0)) else: return val << offset cpu.AH = (make_flag(cpu.SF, 7) | make_flag(cpu.ZF, 6) | make_flag(0, 5) | make_flag(cpu.AF, 4) | make_flag(0, 3) | make_flag(cpu.PF, 2) | make_flag(1, 1) | make_flag(cpu.CF, 0))
def LEA(cpu, dest, src): """ Loads effective address. Computes the effective address of the second operand (the source operand) and stores it in the first operand (destination operand). The source operand is a memory address (offset part) specified with one of the processors addressing modes; the destination operand is a general-purpose register. The address-size and operand-size attributes affect the action performed by this instruction. The operand-size attribute of the instruction is determined by the chosen register; the address-size attribute is determined by the attribute of the code segment. :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ dest.write(Operators.EXTRACT(src.address(), 0, dest.size))
def MOVBE(cpu, dest, src): """ Moves data after swapping bytes. Performs a byte swap operation on the data copied from the second operand (source operand) and store the result in the first operand (destination operand). The source operand can be a general-purpose register, or memory location; the destination register can be a general-purpose register, or a memory location; however, both operands can not be registers, and only one operand can be a memory location. Both operands must be the same size, which can be a word, a doubleword or quadword. The MOVBE instruction is provided for swapping the bytes on a read from memory or on a write to memory; thus providing support for converting little-endian values to big-endian format and vice versa. In 64-bit mode, the instruction's default operation size is 32 bits. Use of the REX.R prefix permits access to additional registers (R8-R15). Use of the REX.W prefix promotes operation to 64 bits:: TEMP = SRC IF ( OperandSize = 16) THEN DEST[7:0] = TEMP[15:8]; DEST[15:8] = TEMP[7:0]; ELSE IF ( OperandSize = 32) DEST[7:0] = TEMP[31:24]; DEST[15:8] = TEMP[23:16]; DEST[23:16] = TEMP[15:8]; DEST[31:23] = TEMP[7:0]; ELSE IF ( OperandSize = 64) DEST[7:0] = TEMP[63:56]; DEST[15:8] = TEMP[55:48]; DEST[23:16] = TEMP[47:40]; DEST[31:24] = TEMP[39:32]; DEST[39:32] = TEMP[31:24]; DEST[47:40] = TEMP[23:16]; DEST[55:48] = TEMP[15:8]; DEST[63:56] = TEMP[7:0]; FI; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ size = dest.size arg0 = dest.read() temp = 0 for pos in range(0, size, 8): temp = (temp << 8) | (arg0 & 0xff) arg0 = arg0 >> 8 dest.write(arg0)
def SAHF(cpu): """ Stores AH into flags. Loads the SF, ZF, AF, PF, and CF flags of the EFLAGS register with values from the corresponding bits in the AH register (bits 7, 6, 4, 2, and 0, respectively). Bits 1, 3, and 5 of register AH are ignored; the corresponding reserved bits (1, 3, and 5) in the EFLAGS register remain as shown below:: EFLAGS(SF:ZF:0:AF:0:PF:1:CF) = AH; :param cpu: current CPU. :param dest: destination operand. :param src: source operand. """ eflags_size = 32 val = cpu.AH & 0xD5 | 0x02 cpu.EFLAGS = Operators.ZEXTEND(val, eflags_size)
def SETA(cpu, dest): """ Sets byte if above. Sets the destination operand to 0 or 1 depending on the settings of the status flags (CF, SF, OF, ZF, and PF, 1, 0) in the EFLAGS register. The destination operand points to a byte register or a byte in memory. The condition code suffix (cc, 1, 0) indicates the condition being tested for:: IF condition THEN DEST = 1; ELSE DEST = 0; FI; :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF) == False, 1, 0))
def SETB(cpu, dest): """ Sets byte if below. :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))
def SETBE(cpu, dest): """ Sets byte if below or equal. :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF), 1, 0))
def SETC(cpu, dest): """ Sets if carry. :param cpu: current CPU. :param dest: destination operand. """ dest.write(Operators.ITEBV(dest.size, cpu.CF, 1, 0))