INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Human - readable data size From https:// stackoverflow. com/ a/ 1094933: param num: number of bytes: param suffix: Optional size specifier: return: Formatted string
def hr_size(num, suffix='B') -> str: """ Human-readable data size From https://stackoverflow.com/a/1094933 :param num: number of bytes :param suffix: Optional size specifier :return: Formatted string """ for unit in ' KMGTPEZ': if abs(num) < 1024.0: return "%3.1f%s%s"...
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 copy_memory(self, address, size): """ 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 """ start_time = time.time() map_bytes = s...
Catches did_map_memory and copies the mapping into Manticore
def map_memory_callback(self, address, size, perms, name, offset, result): """ Catches did_map_memory and copies the mapping into Manticore """ logger.info(' '.join(("Mapping Memory @", hex(address) if type(address) is int else "0x??", ...
Unmap Unicorn maps when Manticore unmaps them
def unmap_memory_callback(self, start, size): """Unmap Unicorn maps when Manticore unmaps them""" logger.info(f"Unmapping memory from {hex(start)} to {hex(start + size)}") mask = (1 << 12) - 1 if (start & mask) != 0: logger.error("Memory to be unmapped is not aligned to a pa...
Set memory protections in Unicorn correctly
def protect_memory_callback(self, start, size, perms): """ Set memory protections in Unicorn correctly """ logger.info(f"Changing permissions on {hex(start)}:{hex(start + size)} to {perms}") self._emu.mem_protect(start, size, convert_permissions(perms))
Unicorn hook that transfers control to Manticore so it can execute the syscall
def _hook_syscall(self, uc, data): """ Unicorn hook that transfers control to Manticore so it can execute the syscall """ logger.debug(f"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall") self.sync_unicorn_to_manticore() from ..nativ...
Captures memory written by Unicorn
def _hook_write_mem(self, uc, access, address, size, value, data): """ Captures memory written by Unicorn """ self._mem_delta[address] = (value, size) return True
We hit an unmapped region ; map it into unicorn.
def _hook_unmapped(self, uc, access, address, size, value, data): """ We hit an unmapped region; map it into unicorn. """ try: self.sync_unicorn_to_manticore() logger.warning(f"Encountered an operation on unmapped memory at {hex(address)}") m = self._c...
Wrapper that runs the _step function in a loop while handling exceptions
def emulate(self, instruction): """ Wrapper that runs the _step function in a loop while handling exceptions """ # The emulation might restart if Unicorn needs to bring in a memory map # or bring a value from Manticore state. while True: # Try emulation ...
Execute a chunk fo instructions starting from instruction: param instruction: Where to start: param chunksize: max number of instructions to execute. Defaults to infinite.
def _step(self, instruction, chunksize=0): """ Execute a chunk fo instructions starting from instruction :param instruction: Where to start :param chunksize: max number of instructions to execute. Defaults to infinite. """ try: pc = self._cpu.PC m...
Copy registers and written memory back into Manticore
def sync_unicorn_to_manticore(self): """ Copy registers and written memory back into Manticore """ self.write_backs_disabled = True for reg in self.registers: val = self._emu.reg_read(self._to_unicorn_id(reg)) self._cpu.write_register(reg, val) if ...
Copy memory writes from Manticore back into Unicorn in real - time
def write_back_memory(self, where, expr, size): """ Copy memory writes from Manticore back into Unicorn in real-time """ if self.write_backs_disabled: return if type(expr) is bytes: self._emu.mem_write(where, expr) else: if issymbolic(expr): ...
Sync register state from Manticore - > Unicorn
def write_back_register(self, reg, val): """ Sync register state from Manticore -> Unicorn""" if self.write_backs_disabled: return if issymbolic(val): logger.warning("Skipping Symbolic write-back") return if reg in self.flag_registers: self...
Only useful for setting FS right now.
def update_segment(self, selector, base, size, perms): """ Only useful for setting FS right now. """ logger.info("Updating selector %s to 0x%02x (%s bytes) (%s)", selector, base, size, perms) if selector == 99: self.set_fs(base) else: logger.error("No way to write...
A decorator for marking functions as deprecated.
def deprecated(message: str): """A decorator for marking functions as deprecated. """ assert isinstance(message, str), "The deprecated decorator requires a message string argument." def decorator(func): @wraps(func) def wrapper(*args, **kwargs): warnings.warn(f"`{func.__qualname...
flips a constraint ( Equal )
def flip(constraint): ''' flips a constraint (Equal) (Equal (BitVecITE Cond IfC ElseC) IfC) -> (Equal (BitVecITE Cond IfC ElseC) ElseC) ''' equal = copy.copy(constraint) assert len(equal.operands) == 2 # assume they are the equal -> ite form that we produce on standard branches...
Produce permutations of lst where permutations are mutated by func. Used for flipping constraints. highly possible that returned constraints can be unsat this does it blindly without any attention to the constraints themselves
def perm(lst, func): ''' Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly possible that returned constraints can be unsat this does it blindly, without any attention to the constraints themselves Considering lst as a list of constraints, e.g...
solve bytes in |datas| based on
def input_from_cons(constupl, datas): ' solve bytes in |datas| based on ' def make_chr(c): try: return chr(c) except Exception: return c newset = constraints_to_constraintset(constupl) ret = '' for data in datas: for c in data: ret += make...
Execute a symbolic run that follows a concrete run ; return constraints generated and the stdin data produced
def symbolic_run_get_cons(trace): ''' Execute a symbolic run that follows a concrete run; return constraints generated and the stdin data produced ''' m2 = Manticore.linux(prog, workspace_url='mem:') f = Follower(trace) m2.verbosity(VERBOSITY) m2.register_plugin(f) def on_term_test...
Repositions the file C { offset } according to C { whence }. Returns the resulting offset or - 1 in case of error.: rtype: int: return: the file offset.
def seek(self, offset, whence=os.SEEK_SET): """ Repositions the file C{offset} according to C{whence}. Returns the resulting offset or -1 in case of error. :rtype: int :return: the file offset. """ assert isinstance(offset, int) assert whence in (os.SEEK_S...
Reads up to C { count } bytes from the file.: rtype: list: return: the list of symbolic bytes read
def read(self, count): """ Reads up to C{count} bytes from the file. :rtype: list :return: the list of symbolic bytes read """ if self.pos > self.max_size: return [] else: size = min(count, self.max_size - self.pos) ret = [self....
Writes the symbolic bytes in C { data } onto the file.
def write(self, data): """ Writes the symbolic bytes in C{data} onto the file. """ size = min(len(data), self.max_size - self.pos) for i in range(self.pos, self.pos + size): self.array[i] = data[i - self.pos]
Create a platform without an ELF loaded.
def empty_platform(cls, arch): """ Create a platform without an ELF loaded. :param str arch: The architecture of the new platform :rtype: Linux """ platform = cls(None) platform._init_cpu(arch) platform._init_std_fds() return platform
Load program and establish program state such as stack and arguments.
def _execve(self, program, argv, envp): """ Load `program` and establish program state, such as stack and arguments. :param program str: The ELF binary to load :param argv list: argv array :param envp list: envp array """ argv = [] if argv is None else argv ...
ARM kernel helpers
def _init_arm_kernel_helpers(self): """ ARM kernel helpers https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt """ page_data = bytearray(b'\xf1\xde\xfd\xe7' * 1024) # Extracted from a RPi2 preamble = binascii.unhexlify( 'ff0300ea' +...
: param Cpu cpu: The cpu instance: param argv: list of parameters for the program to execute.: param envp: list of environment variables for the program to execute.
def setup_stack(self, argv, envp): """ :param Cpu cpu: The cpu instance :param argv: list of parameters for the program to execute. :param envp: list of environment variables for the program to execute. http://www.phrack.org/issues.html?issue=58&id=5#article position ...
Loads and an ELF program in memory and prepares the initial CPU state. Creates the stack and loads the environment variables and the arguments in it.
def load(self, filename, env): """ Loads and an ELF program in memory and prepares the initial CPU state. Creates the stack and loads the environment variables and the arguments in it. :param filename: pathname of the file to be executed. (used for auxv) :param list env: A list ...
Adds a file descriptor to the current file descriptor list
def _open(self, f): """ Adds a file descriptor to the current file descriptor list :rtype: int :param f: the file descriptor to add. :return: the index of the file descriptor in the file descr. list """ if None in self.files: fd = self.files.index(Non...
Removes a file descriptor from the file descriptor list: rtype: int: param fd: the file descriptor to close.: return: C { 0 } on success.
def _close(self, fd): """ Removes a file descriptor from the file descriptor list :rtype: int :param fd: the file descriptor to close. :return: C{0} on success. """ try: self.files[fd].close() self._closed_files.append(self.files[fd]) # Ke...
Determines if the fd is within range and in the file descr. list: param fd: the file descriptor to check.
def _is_fd_open(self, fd): """ Determines if the fd is within range and in the file descr. list :param fd: the file descriptor to check. """ return fd >= 0 and fd < len(self.files) and self.files[fd] is not None
chdir - Change current working directory: param int path: Pointer to path
def sys_chdir(self, path): """ chdir - Change current working directory :param int path: Pointer to path """ path_str = self.current.read_string(path) logger.debug(f"chdir({path_str})") try: os.chdir(path_str) return 0 except OSErro...
getcwd - Get the current working directory: param int buf: Pointer to dest array: param size: size in bytes of the array pointed to by the buf: return: buf ( Success ) or 0
def sys_getcwd(self, buf, size): """ getcwd - Get the current working directory :param int buf: Pointer to dest array :param size: size in bytes of the array pointed to by the buf :return: buf (Success), or 0 """ try: current_dir = os.getcwd() ...
lseek - reposition read/ write file offset
def sys_lseek(self, fd, offset, whence): """ lseek - reposition read/write file offset The lseek() function repositions the file offset of the open file description associated with the file descriptor fd to the argument offset according to the directive whence :param fd: a val...
write - send bytes through a file descriptor The write system call writes up to count bytes from the buffer pointed to by buf to the file descriptor fd. If count is zero write returns 0 and optionally sets * tx_bytes to zero.
def sys_write(self, fd, buf, count): """ write - send bytes through a file descriptor The write system call writes up to count bytes from the buffer pointed to by buf to the file descriptor fd. If count is zero, write returns 0 and optionally sets *tx_bytes to zero. :par...
Checks real user s permissions for a file: rtype: int
def sys_access(self, buf, mode): """ Checks real user's permissions for a file :rtype: int :param buf: a buffer containing the pathname to the file to check its permissions. :param mode: the access permissions to check. :return: - C{0} if the calling process...
Writes system information in the variable C { old_utsname }.: rtype: int: param old_utsname: the buffer to write the system info.: return: C { 0 } on success
def sys_newuname(self, old_utsname): """ Writes system information in the variable C{old_utsname}. :rtype: int :param old_utsname: the buffer to write the system info. :return: C{0} on success """ from datetime import datetime def pad(s): retu...
Changes data segment size ( moves the C { brk } to the new address ): rtype: int: param brk: the new address for C { brk }.: return: the value of the new C { brk }.: raises error: - Error in brk! if there is any error allocating the memory
def sys_brk(self, brk): """ Changes data segment size (moves the C{brk} to the new address) :rtype: int :param brk: the new address for C{brk}. :return: the value of the new C{brk}. :raises error: - "Error in brk!" if there is any error allocating the ...
Sets architecture - specific thread state: rtype: int
def sys_arch_prctl(self, code, addr): """ Sets architecture-specific thread state :rtype: int :param code: must be C{ARCH_SET_FS}. :param addr: the base address of the FS segment. :return: C{0} on success :raises error: - if C{code} is different to C{...
: param buf: address of zero - terminated pathname: param flags: file access bits: param mode: file permission mode
def sys_open(self, buf, flags, mode): """ :param buf: address of zero-terminated pathname :param flags: file access bits :param mode: file permission mode """ filename = self.current.read_string(buf) try: f = self._sys_open_get_file(filename, flags) ...
Openat SystemCall - Similar to open system call except dirfd argument when path contained in buf is relative dirfd is referred to set the relative path Special value AT_FDCWD set for dirfd to set path relative to current directory
def sys_openat(self, dirfd, buf, flags, mode): """ Openat SystemCall - Similar to open system call except dirfd argument when path contained in buf is relative, dirfd is referred to set the relative path Special value AT_FDCWD set for dirfd to set path relative to current directory ...
Rename filename oldnamep to newnamep.
def sys_rename(self, oldnamep, newnamep): """ Rename filename `oldnamep` to `newnamep`. :param int oldnamep: pointer to oldname :param int newnamep: pointer to newname """ oldname = self.current.read_string(oldnamep) newname = self.current.read_string(newnamep) ...
Synchronize a file s in - core state with that on disk.
def sys_fsync(self, fd): """ Synchronize a file's in-core state with that on disk. """ ret = 0 try: self.files[fd].sync() except IndexError: ret = -errno.EBADF except FdError: ret = -errno.EINVAL return ret
Wrapper for sys_sigaction
def sys_rt_sigaction(self, signum, act, oldact): """Wrapper for sys_sigaction""" return self.sys_sigaction(signum, act, oldact)
Wrapper for sys_sigprocmask
def sys_rt_sigprocmask(self, cpu, how, newset, oldset): """Wrapper for sys_sigprocmask""" return self.sys_sigprocmask(cpu, how, newset, oldset)
Duplicates an open file descriptor: rtype: int: param fd: the open file descriptor to duplicate.: return: the new file descriptor.
def sys_dup(self, fd): """ Duplicates an open file descriptor :rtype: int :param fd: the open file descriptor to duplicate. :return: the new file descriptor. """ if not self._is_fd_open(fd): logger.info("DUP: Passed fd is not open. Returning EBADF") ...
Duplicates an open fd to newfd. If newfd is open it is first closed: rtype: int: param fd: the open file descriptor to duplicate.: param newfd: the file descriptor to alias the file described by fd.: return: newfd.
def sys_dup2(self, fd, newfd): """ Duplicates an open fd to newfd. If newfd is open, it is first closed :rtype: int :param fd: the open file descriptor to duplicate. :param newfd: the file descriptor to alias the file described by fd. :return: newfd. """ t...
An implementation of chroot that does perform some basic error checking but does not actually chroot.
def sys_chroot(self, path): """ An implementation of chroot that does perform some basic error checking, but does not actually chroot. :param path: Path to chroot """ if path not in self.current.memory: return -errno.EFAULT path_s = self.current.read...
Closes a file descriptor: rtype: int: param fd: the file descriptor to close.: return: C { 0 } on success.
def sys_close(self, fd): """ Closes a file descriptor :rtype: int :param fd: the file descriptor to close. :return: C{0} on success. """ if self._is_fd_open(fd): self._close(fd) else: return -errno.EBADF logger.debug(f'sys_c...
Read: rtype: int
def sys_readlink(self, path, buf, bufsize): """ Read :rtype: int :param path: the "link path id" :param buf: the buffer where the bytes will be putted. :param bufsize: the max size for read the link. :todo: Out eax number of bytes actually sent | EAGAIN | EBADF |...
Wrapper for mmap2
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset): """Wrapper for mmap2""" return self.sys_mmap2(address, size, prot, flags, fd, offset)
Creates a new mapping in the virtual address space of the calling process.: rtype: int
def sys_mmap(self, address, size, prot, flags, fd, offset): """ Creates a new mapping in the virtual address space of the calling process. :rtype: int :param address: the starting address for the new mapping. This address is used as hint unless the flag contains ...
Sets protection on a region of memory. Changes protection for the calling process s memory page ( s ) containing any part of the address range in the interval [ C { start } C { start } + C { size } - 1 ].: rtype: int
def sys_mprotect(self, start, size, prot): """ Sets protection on a region of memory. Changes protection for the calling process's memory page(s) containing any part of the address range in the interval [C{start}, C{start}+C{size}-1]. :rtype: int :param start: the starting addre...
Unmaps a file from memory. It deletes the mappings for the specified address range: rtype: int
def sys_munmap(self, addr, size): """ Unmaps a file from memory. It deletes the mappings for the specified address range :rtype: int :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return: C{0} on success. """ s...
Works just like C { sys_read } except that data is read into multiple buffers.: rtype: int
def sys_readv(self, fd, iov, count): """ Works just like C{sys_read} except that data is read into multiple buffers. :rtype: int :param fd: the file descriptor of the file to read. :param iov: the buffer where the the bytes to read are stored. :param count: amount of C{i...
Works just like C { sys_write } except that multiple buffers are written out.: rtype: int
def sys_writev(self, fd, iov, count): """ Works just like C{sys_write} except that multiple buffers are written out. :rtype: int :param fd: the file descriptor of the file to write. :param iov: the buffer where the the bytes to write are taken. :param count: amount of C{...
Sets a thread local storage ( TLS ) area. Sets the base address of the GS segment.: rtype: int
def sys_set_thread_area(self, user_info): """ Sets a thread local storage (TLS) area. Sets the base address of the GS segment. :rtype: int :param user_info: the TLS array entry set corresponds to the value of C{u_info->entry_number}. :return: C{0} on success. """ ...
The getrandom system call fills the buffer with random bytes of buflen. The source of random (/ dev/ random or/ dev/ urandom ) is decided based on the flags value.
def sys_getrandom(self, buf, size, flags): """ The getrandom system call fills the buffer with random bytes of buflen. The source of random (/dev/random or /dev/urandom) is decided based on the flags value. Manticore's implementation simply fills a buffer with zeroes -- choosing...
Syscall dispatcher.
def syscall(self): """ Syscall dispatcher. """ index = self._syscall_abi.syscall_number() try: table = getattr(linux_syscalls, self.current.machine) name = table.get(index, None) implementation = getattr(self, name) except (AttributeE...
Yield CPU. This will choose another process from the running list and change current running process. May give the same cpu if only one running process.
def sched(self): """ Yield CPU. This will choose another process from the running list and change current running process. May give the same cpu if only one running process. """ if len(self.procs) > 1: logger.debug("SCHED:") logger.debu...
Wait for file descriptors or timeout. Adds the current process in the correspondent waiting list and yield the cpu to another running process.
def wait(self, readfds, writefds, timeout): """ Wait for file descriptors or timeout. Adds the current process in the correspondent waiting list and yield the cpu to another running process. """ logger.debug("WAIT:") logger.debug(f"\tProcess {self._current} is goi...
Remove procid from waitlists and reestablish it in the running list
def awake(self, procid): """ Remove procid from waitlists and reestablish it in the running list """ logger.debug(f"Remove procid:{procid} from waitlists and reestablish it in the running list") for wait_list in self.rwait: if procid in wait_list: wait_list.remove(pro...
Awake one process waiting to receive data on fd
def signal_receive(self, fd): """ Awake one process waiting to receive data on fd """ connections = self.connections if connections(fd) and self.twait[connections(fd)]: procid = random.sample(self.twait[connections(fd)], 1)[0] self.awake(procid)
Awake one process waiting to transmit data on fd
def signal_transmit(self, fd): """ Awake one process waiting to transmit data on fd """ connection = self.connections(fd) if connection is None or connection >= len(self.rwait): return procs = self.rwait[connection] if procs: procid = random.sample(procs,...
Awake process if timer has expired
def check_timers(self): """ Awake process if timer has expired """ if self._current is None: # Advance the clocks. Go to future!! advance = min([self.clocks] + [x for x in self.timers if x is not None]) + 1 logger.debug(f"Advancing the clock from {self.clocks} to {adv...
Execute one cpu instruction in the current thread ( only one supported ).: rtype: bool: return: C { True }
def execute(self): """ Execute one cpu instruction in the current thread (only one supported). :rtype: bool :return: C{True} :todo: This is where we could implement a simple schedule. """ try: self.current.execute() self.clocks += 1 ...
Determines information about a file based on its file descriptor ( for Linux 64 bits ).: rtype: int: param fd: the file descriptor of the file that is being inquired.: param buf: a buffer where data about the file will be stored.: return: C { 0 } on success EBADF when called with bad fd: todo: Fix device number.
def sys_fstat64(self, fd, buf): """ Determines information about a file based on its file descriptor (for Linux 64 bits). :rtype: int :param fd: the file descriptor of the file that is being inquired. :param buf: a buffer where data about the file will be stored. :return:...
Compute total load size of interpreter.
def _interp_total_size(interp): """ Compute total load size of interpreter. :param ELFFile interp: interpreter ELF .so :return: total load size of interpreter, not aligned :rtype: int """ load_segs = [x for x in interp.iter_segments() if x.header.p_type == 'PT_LO...
A version of open ( 2 ) that includes a special case for a symbolic path. When given a symbolic path it will create a temporary file with 64 bytes of symbolic bytes as contents and return that instead.
def sys_open(self, buf, flags, mode): """ A version of open(2) that includes a special case for a symbolic path. When given a symbolic path, it will create a temporary file with 64 bytes of symbolic bytes as contents and return that instead. :param buf: address of zero-terminate...
A version of openat that includes a symbolic path and symbolic directory file descriptor
def sys_openat(self, dirfd, buf, flags, mode): """ A version of openat that includes a symbolic path and symbolic directory file descriptor :param dirfd: directory file descriptor :param buf: address of zero-terminated pathname :param flags: file access bits :param mode:...
The getrandom system call fills the buffer with random bytes of buflen. The source of random (/ dev/ random or/ dev/ urandom ) is decided based on the flags value.
def sys_getrandom(self, buf, size, flags): """ The getrandom system call fills the buffer with random bytes of buflen. The source of random (/dev/random or /dev/urandom) is decided based on the flags value. :param buf: address of buffer to be filled with random bytes :param size...
Reads a null terminated concrete buffer form memory: todo: FIX. move to cpu or memory
def _read_string(self, cpu, buf): """ Reads a null terminated concrete buffer form memory :todo: FIX. move to cpu or memory """ filename = "" for i in range(0, 1024): c = Operators.CHR(cpu.read_int(buf + i, 8)) if c == '\x00': break...
Loads a CGC - ELF program in memory and prepares the initial CPU state and the stack.
def load(self, filename): """ Loads a CGC-ELF program in memory and prepares the initial CPU state and the stack. :param filename: pathname of the file to be executed. """ CGC_MIN_PAGE_SIZE = 4096 CGC_MIN_ALIGN = CGC_MIN_PAGE_SIZE TASK_SIZE = 0x80000000 ...
allocate - allocate virtual memory
def sys_allocate(self, cpu, length, isX, addr): """ allocate - allocate virtual memory The allocate system call creates a new allocation in the virtual address space of the calling process. The length argument specifies the length of the allocation in bytes which will be rou...
random - fill a buffer with random data
def sys_random(self, cpu, buf, count, rnd_bytes): """ random - fill a buffer with random data The random system call populates the buffer referenced by buf with up to count bytes of random data. If count is zero, random returns 0 and optionally sets *rx_bytes to zero. If coun...
receive - receive bytes from a file descriptor
def sys_receive(self, cpu, fd, buf, count, rx_bytes): """ receive - receive bytes from a file descriptor The receive system call reads up to count bytes from file descriptor fd to the buffer pointed to by buf. If count is zero, receive returns 0 and optionally sets *rx_bytes...
transmit - send bytes through a file descriptor The transmit system call writes up to count bytes from the buffer pointed to by buf to the file descriptor fd. If count is zero transmit returns 0 and optionally sets * tx_bytes to zero.
def sys_transmit(self, cpu, fd, buf, count, tx_bytes): """ transmit - send bytes through a file descriptor The transmit system call writes up to count bytes from the buffer pointed to by buf to the file descriptor fd. If count is zero, transmit returns 0 and optionally sets *tx_by...
Exits all threads in a process: param cpu: current CPU.: raises Exception: Finished
def sys_terminate(self, cpu, error_code): """ Exits all threads in a process :param cpu: current CPU. :raises Exception: 'Finished' """ procid = self.procs.index(cpu) self.sched() self.running.remove(procid) # self.procs[procid] = None #let it ther...
deallocate - remove allocations The deallocate system call deletes the allocations for the specified address range and causes further references to the addresses within the range to generate invalid memory accesses. The region is also automatically deallocated when the process is terminated.
def sys_deallocate(self, cpu, addr, size): """ deallocate - remove allocations The deallocate system call deletes the allocations for the specified address range, and causes further references to the addresses within the range to generate invalid memory accesses. The region is also ...
fdwait - wait for file descriptors to become ready
def sys_fdwait(self, cpu, nfds, readfds, writefds, timeout, readyfds): """ fdwait - wait for file descriptors to become ready """ logger.debug("FDWAIT(%d, 0x%08x, 0x%08x, 0x%08x, 0x%08x)" % (nfds, readfds, writefds, timeout, readyfds)) if timeout: if timeout not in cpu.memor...
32 bit dispatcher.: param cpu: current CPU. _terminate transmit receive fdwait allocate deallocate and random
def int80(self, cpu): """ 32 bit dispatcher. :param cpu: current CPU. _terminate, transmit, receive, fdwait, allocate, deallocate and random """ syscalls = {0x00000001: self.sys_terminate, 0x00000002: self.sys_transmit, 0x00000003: ...
Yield CPU. This will choose another process from the RUNNNIG list and change current running process. May give the same cpu if only one running process.
def sched(self): """ Yield CPU. This will choose another process from the RUNNNIG list and change current running process. May give the same cpu if only one running process. """ if len(self.procs) > 1: logger.info("SCHED:") logger.info(...
Wait for filedescriptors or timeout. Adds the current process to the corresponding waiting list and yields the cpu to another running process.
def wait(self, readfds, writefds, timeout): """ Wait for filedescriptors or timeout. Adds the current process to the corresponding waiting list and yields the cpu to another running process. """ logger.info("WAIT:") logger.info("\tProcess %d is going to wait for [...
Awake one process waiting to transmit data on fd
def signal_transmit(self, fd): """ Awake one process waiting to transmit data on fd """ connections = self.connections if connections(fd) and self.rwait[connections(fd)]: procid = random.sample(self.rwait[connections(fd)], 1)[0] self.awake(procid)
Execute one cpu instruction in the current thread ( only one supported ).: rtype: bool: return: C { True }
def execute(self): """ Execute one cpu instruction in the current thread (only one supported). :rtype: bool :return: C{True} :todo: This is where we could implement a simple schedule. """ try: self.current.execute() self.clocks += 1 ...
Symbolic version of Decree. sys_receive
def sys_receive(self, cpu, fd, buf, count, rx_bytes): """ Symbolic version of Decree.sys_receive """ if issymbolic(fd): logger.info("Ask to read from a symbolic file descriptor!!") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cp...
Symbolic version of Decree. sys_transmit
def sys_transmit(self, cpu, fd, buf, count, tx_bytes): """ Symbolic version of Decree.sys_transmit """ if issymbolic(fd): logger.info("Ask to write to a symbolic file descriptor!!") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(c...
Synchronization decorator.
def sync(f): """ Synchronization decorator. """ def new_function(self, *args, **kw): self._lock.acquire() try: return f(self, *args, **kw) finally: self._lock.release() return new_function
Create a: class: ~manticore. core. workspace. Store instance depending on the descriptor.
def fromdescriptor(cls, desc): """ Create a :class:`~manticore.core.workspace.Store` instance depending on the descriptor. Valid descriptors: * fs:<path> * redis:<hostname>:<port> * mem: :param str desc: Store descriptor :return: Store instance ...
Save an arbitrary serializable value under key.
def save_value(self, key, value): """ Save an arbitrary, serializable `value` under `key`. :param str key: A string identifier under which to store the value. :param value: A serializable value :return: """ with self.save_stream(key) as s: s.write(val...
Load an arbitrary value identified by key.
def load_value(self, key, binary=False): """ Load an arbitrary value identified by `key`. :param str key: The key that identifies the value :return: The loaded value """ with self.load_stream(key, binary=binary) as s: return s.read()
Return a managed file - like object into which the calling code can write arbitrary data.
def save_stream(self, key, binary=False): """ Return a managed file-like object into which the calling code can write arbitrary data. :param key: :return: A managed stream-like object """ s = io.BytesIO() if binary else io.StringIO() yield s self....
Return a managed file - like object from which the calling code can read previously - serialized data.
def load_stream(self, key, binary=False): """ Return a managed file-like object from which the calling code can read previously-serialized data. :param key: :return: A managed stream-like object """ value = self.load_value(key, binary=binary) yield io.Byt...
Save a state to storage.
def save_state(self, state, key): """ Save a state to storage. :param manticore.core.StateBase state: :param str key: :return: """ with self.save_stream(key, binary=True) as f: self._serializer.serialize(state, f)
Load a state from storage.
def load_state(self, key, delete=True): """ Load a state from storage. :param key: key that identifies state :rtype: manticore.core.StateBase """ with self.load_stream(key, binary=True) as f: state = self._serializer.deserialize(f) if delete: ...
Yield a file object representing key
def save_stream(self, key, binary=False): """ Yield a file object representing `key` :param str key: The file to save to :param bool binary: Whether we should treat it as binary :return: """ mode = 'wb' if binary else 'w' with open(os.path.join(self.uri, ...
: param str key: name of stream to load: param bool binary: Whether we should treat it as binary: return:
def load_stream(self, key, binary=False): """ :param str key: name of stream to load :param bool binary: Whether we should treat it as binary :return: """ with open(os.path.join(self.uri, key), 'rb' if binary else 'r') as f: yield f
Remove file identified by key.
def rm(self, key): """ Remove file identified by `key`. :param str key: The file to delete """ path = os.path.join(self.uri, key) os.remove(path)
Return just the filenames that match glob_str inside the store directory.
def ls(self, glob_str): """ Return just the filenames that match `glob_str` inside the store directory. :param str glob_str: A glob string, i.e. 'state_*' :return: list of matched keys """ path = os.path.join(self.uri, glob_str) return [os.path.split(s)[1] for s ...
Get a unique state id.
def _get_id(self): """ Get a unique state id. :rtype: int """ id_ = self._last_id.value self._last_id.value += 1 return id_
Load a state from storage identified by state_id.
def load_state(self, state_id, delete=True): """ Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State """ return self._store.load_state(f'{self._prefix}{state_id:08x...