partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
hr_size
Human-readable data size From https://stackoverflow.com/a/1094933 :param num: number of bytes :param suffix: Optional size specifier :return: Formatted string
manticore/utils/emulate.py
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" % (num, unit if unit != ' ' else '', suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Y', suffix)
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" % (num, unit if unit != ' ' else '', suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Y', suffix)
[ "Human", "-", "readable", "data", "size", "From", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "1094933", ":", "param", "num", ":", "number", "of", "bytes", ":", "param", "suffix", ":", "Optional", "size", "specifier", ":", "return", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L36-L48
[ "def", "hr_size", "(", "num", ",", "suffix", "=", "'B'", ")", "->", "str", ":", "for", "unit", "in", "' KMGTPEZ'", ":", "if", "abs", "(", "num", ")", "<", "1024.0", ":", "return", "\"%3.1f%s%s\"", "%", "(", "num", ",", "unit", "if", "unit", "!=", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.copy_memory
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
manticore/utils/emulate.py
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 = self._cpu._raw_read(address, size) self._emu.mem_write(address, map_bytes) if time.time() - start_time > 3: logger.info(f"Copying {hr_size(size)} map at {hex(address)} took {time.time() - start_time} seconds")
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 = self._cpu._raw_read(address, size) self._emu.mem_write(address, map_bytes) if time.time() - start_time > 3: logger.info(f"Copying {hr_size(size)} map at {hex(address)} took {time.time() - start_time} seconds")
[ "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", "m...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L123-L134
[ "def", "copy_memory", "(", "self", ",", "address", ",", "size", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "map_bytes", "=", "self", ".", "_cpu", ".", "_raw_read", "(", "address", ",", "size", ")", "self", ".", "_emu", ".", "mem_writ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.map_memory_callback
Catches did_map_memory and copies the mapping into Manticore
manticore/utils/emulate.py
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??", hr_size(size), "-", perms, "-", f"{name}:{hex(offset) if name else ''}", "->", hex(result)))) self._emu.mem_map(address, size, convert_permissions(perms)) self.copy_memory(address, size)
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??", hr_size(size), "-", perms, "-", f"{name}:{hex(offset) if name else ''}", "->", hex(result)))) self._emu.mem_map(address, size, convert_permissions(perms)) self.copy_memory(address, size)
[ "Catches", "did_map_memory", "and", "copies", "the", "mapping", "into", "Manticore" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L136-L147
[ "def", "map_memory_callback", "(", "self", ",", "address", ",", "size", ",", "perms", ",", "name", ",", "offset", ",", "result", ")", ":", "logger", ".", "info", "(", "' '", ".", "join", "(", "(", "\"Mapping Memory @\"", ",", "hex", "(", "address", ")"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.unmap_memory_callback
Unmap Unicorn maps when Manticore unmaps them
manticore/utils/emulate.py
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 page") if (size & mask) != 0: size = ((size >> 12) + 1) << 12 logger.warning("Forcing unmap size to align to a page") self._emu.mem_unmap(start, size)
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 page") if (size & mask) != 0: size = ((size >> 12) + 1) << 12 logger.warning("Forcing unmap size to align to a page") self._emu.mem_unmap(start, size)
[ "Unmap", "Unicorn", "maps", "when", "Manticore", "unmaps", "them" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L149-L161
[ "def", "unmap_memory_callback", "(", "self", ",", "start", ",", "size", ")", ":", "logger", ".", "info", "(", "f\"Unmapping memory from {hex(start)} to {hex(start + size)}\"", ")", "mask", "=", "(", "1", "<<", "12", ")", "-", "1", "if", "(", "start", "&", "m...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.protect_memory_callback
Set memory protections in Unicorn correctly
manticore/utils/emulate.py
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))
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))
[ "Set", "memory", "protections", "in", "Unicorn", "correctly" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L163-L166
[ "def", "protect_memory_callback", "(", "self", ",", "start", ",", "size", ",", "perms", ")", ":", "logger", ".", "info", "(", "f\"Changing permissions on {hex(start)}:{hex(start + size)} to {perms}\"", ")", "self", ".", "_emu", ".", "mem_protect", "(", "start", ",",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator._hook_syscall
Unicorn hook that transfers control to Manticore so it can execute the syscall
manticore/utils/emulate.py
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 ..native.cpu.abstractcpu import Syscall self._to_raise = Syscall() uc.emu_stop()
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 ..native.cpu.abstractcpu import Syscall self._to_raise = Syscall() uc.emu_stop()
[ "Unicorn", "hook", "that", "transfers", "control", "to", "Manticore", "so", "it", "can", "execute", "the", "syscall" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L179-L187
[ "def", "_hook_syscall", "(", "self", ",", "uc", ",", "data", ")", ":", "logger", ".", "debug", "(", "f\"Stopping emulation at {hex(uc.reg_read(self._to_unicorn_id('RIP')))} to perform syscall\"", ")", "self", ".", "sync_unicorn_to_manticore", "(", ")", "from", ".", ".",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator._hook_write_mem
Captures memory written by Unicorn
manticore/utils/emulate.py
def _hook_write_mem(self, uc, access, address, size, value, data): """ Captures memory written by Unicorn """ self._mem_delta[address] = (value, size) return True
def _hook_write_mem(self, uc, access, address, size, value, data): """ Captures memory written by Unicorn """ self._mem_delta[address] = (value, size) return True
[ "Captures", "memory", "written", "by", "Unicorn" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L189-L194
[ "def", "_hook_write_mem", "(", "self", ",", "uc", ",", "access", ",", "address", ",", "size", ",", "value", ",", "data", ")", ":", "self", ".", "_mem_delta", "[", "address", "]", "=", "(", "value", ",", "size", ")", "return", "True" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator._hook_unmapped
We hit an unmapped region; map it into unicorn.
manticore/utils/emulate.py
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._cpu.memory.map_containing(address) self.copy_memory(m.start, m.end - m.start) except MemoryException as e: logger.error("Failed to map memory {}-{}, ({}): {}".format(hex(address), hex(address + size), access, e)) self._to_raise = e self._should_try_again = False return False self._should_try_again = True return False
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._cpu.memory.map_containing(address) self.copy_memory(m.start, m.end - m.start) except MemoryException as e: logger.error("Failed to map memory {}-{}, ({}): {}".format(hex(address), hex(address + size), access, e)) self._to_raise = e self._should_try_again = False return False self._should_try_again = True return False
[ "We", "hit", "an", "unmapped", "region", ";", "map", "it", "into", "unicorn", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L196-L212
[ "def", "_hook_unmapped", "(", "self", ",", "uc", ",", "access", ",", "address", ",", "size", ",", "value", ",", "data", ")", ":", "try", ":", "self", ".", "sync_unicorn_to_manticore", "(", ")", "logger", ".", "warning", "(", "f\"Encountered an operation on u...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.emulate
Wrapper that runs the _step function in a loop while handling exceptions
manticore/utils/emulate.py
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 self._should_try_again = False self._to_raise = None self._step(instruction) if not self._should_try_again: break
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 self._should_try_again = False self._to_raise = None self._step(instruction) if not self._should_try_again: break
[ "Wrapper", "that", "runs", "the", "_step", "function", "in", "a", "loop", "while", "handling", "exceptions" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L239-L255
[ "def", "emulate", "(", "self", ",", "instruction", ")", ":", "# The emulation might restart if Unicorn needs to bring in a memory map", "# or bring a value from Manticore state.", "while", "True", ":", "# Try emulation", "self", ".", "_should_try_again", "=", "False", "self", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator._step
Execute a chunk fo instructions starting from instruction :param instruction: Where to start :param chunksize: max number of instructions to execute. Defaults to infinite.
manticore/utils/emulate.py
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 = self._cpu.memory.map_containing(pc) if self._stop_at: logger.info(f"Emulating from {hex(pc)} to {hex(self._stop_at)}") self._emu.emu_start(pc, m.end if not self._stop_at else self._stop_at, count=chunksize) except UcError: # We request re-execution by signaling error; if we we didn't set # _should_try_again, it was likely an actual error if not self._should_try_again: raise if self._should_try_again: return # self.sync_unicorn_to_manticore() self._cpu.PC = self.get_unicorn_pc() if self._cpu.PC == self._stop_at: logger.info("Reached emulation target, switching to Manticore mode") self.sync_unicorn_to_manticore() self._stop_at = None # Raise the exception from a hook that Unicorn would have eaten if self._to_raise: from ..native.cpu.abstractcpu import Syscall if type(self._to_raise) is not Syscall: logger.info("Raising %s", self._to_raise) raise self._to_raise logger.info(f"Exiting Unicorn Mode at {hex(self._cpu.PC)}") return
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 = self._cpu.memory.map_containing(pc) if self._stop_at: logger.info(f"Emulating from {hex(pc)} to {hex(self._stop_at)}") self._emu.emu_start(pc, m.end if not self._stop_at else self._stop_at, count=chunksize) except UcError: # We request re-execution by signaling error; if we we didn't set # _should_try_again, it was likely an actual error if not self._should_try_again: raise if self._should_try_again: return # self.sync_unicorn_to_manticore() self._cpu.PC = self.get_unicorn_pc() if self._cpu.PC == self._stop_at: logger.info("Reached emulation target, switching to Manticore mode") self.sync_unicorn_to_manticore() self._stop_at = None # Raise the exception from a hook that Unicorn would have eaten if self._to_raise: from ..native.cpu.abstractcpu import Syscall if type(self._to_raise) is not Syscall: logger.info("Raising %s", self._to_raise) raise self._to_raise logger.info(f"Exiting Unicorn Mode at {hex(self._cpu.PC)}") return
[ "Execute", "a", "chunk", "fo", "instructions", "starting", "from", "instruction", ":", "param", "instruction", ":", "Where", "to", "start", ":", "param", "chunksize", ":", "max", "number", "of", "instructions", "to", "execute", ".", "Defaults", "to", "infinite...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L257-L294
[ "def", "_step", "(", "self", ",", "instruction", ",", "chunksize", "=", "0", ")", ":", "try", ":", "pc", "=", "self", ".", "_cpu", ".", "PC", "m", "=", "self", ".", "_cpu", ".", "memory", ".", "map_containing", "(", "pc", ")", "if", "self", ".", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.sync_unicorn_to_manticore
Copy registers and written memory back into Manticore
manticore/utils/emulate.py
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 len(self._mem_delta) > 0: logger.debug(f"Syncing {len(self._mem_delta)} writes back into Manticore") for location in self._mem_delta: value, size = self._mem_delta[location] self._cpu.write_int(location, value, size * 8) self.write_backs_disabled = False self._mem_delta = {}
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 len(self._mem_delta) > 0: logger.debug(f"Syncing {len(self._mem_delta)} writes back into Manticore") for location in self._mem_delta: value, size = self._mem_delta[location] self._cpu.write_int(location, value, size * 8) self.write_backs_disabled = False self._mem_delta = {}
[ "Copy", "registers", "and", "written", "memory", "back", "into", "Manticore" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L296-L310
[ "def", "sync_unicorn_to_manticore", "(", "self", ")", ":", "self", ".", "write_backs_disabled", "=", "True", "for", "reg", "in", "self", ".", "registers", ":", "val", "=", "self", ".", "_emu", ".", "reg_read", "(", "self", ".", "_to_unicorn_id", "(", "reg"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.write_back_memory
Copy memory writes from Manticore back into Unicorn in real-time
manticore/utils/emulate.py
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): data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)] concrete_data = [] for c in data: if issymbolic(c): c = chr(solver.get_value(self._cpu.memory.constraints, c)) concrete_data.append(c) data = concrete_data else: data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)] logger.debug(f"Writing back {hr_size(size // 8)} to {hex(where)}: {data}") # TODO - the extra encoding is to handle null bytes output as strings when we concretize. That's probably a bug. self._emu.mem_write(where, b''.join(b.encode('utf-8') if type(b) is str else b for b in data))
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): data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)] concrete_data = [] for c in data: if issymbolic(c): c = chr(solver.get_value(self._cpu.memory.constraints, c)) concrete_data.append(c) data = concrete_data else: data = [Operators.CHR(Operators.EXTRACT(expr, offset, 8)) for offset in range(0, size, 8)] logger.debug(f"Writing back {hr_size(size // 8)} to {hex(where)}: {data}") # TODO - the extra encoding is to handle null bytes output as strings when we concretize. That's probably a bug. self._emu.mem_write(where, b''.join(b.encode('utf-8') if type(b) is str else b for b in data))
[ "Copy", "memory", "writes", "from", "Manticore", "back", "into", "Unicorn", "in", "real", "-", "time" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L312-L331
[ "def", "write_back_memory", "(", "self", ",", "where", ",", "expr", ",", "size", ")", ":", "if", "self", ".", "write_backs_disabled", ":", "return", "if", "type", "(", "expr", ")", "is", "bytes", ":", "self", ".", "_emu", ".", "mem_write", "(", "where"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.write_back_register
Sync register state from Manticore -> Unicorn
manticore/utils/emulate.py
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._emu.reg_write(self._to_unicorn_id('EFLAGS'), self._cpu.read_register('EFLAGS')) return self._emu.reg_write(self._to_unicorn_id(reg), val)
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._emu.reg_write(self._to_unicorn_id('EFLAGS'), self._cpu.read_register('EFLAGS')) return self._emu.reg_write(self._to_unicorn_id(reg), val)
[ "Sync", "register", "state", "from", "Manticore", "-", ">", "Unicorn" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L333-L343
[ "def", "write_back_register", "(", "self", ",", "reg", ",", "val", ")", ":", "if", "self", ".", "write_backs_disabled", ":", "return", "if", "issymbolic", "(", "val", ")", ":", "logger", ".", "warning", "(", "\"Skipping Symbolic write-back\"", ")", "return", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
ConcreteUnicornEmulator.update_segment
Only useful for setting FS right now.
manticore/utils/emulate.py
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 segment: %d", selector)
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 segment: %d", selector)
[ "Only", "useful", "for", "setting", "FS", "right", "now", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/emulate.py#L345-L351
[ "def", "update_segment", "(", "self", ",", "selector", ",", "base", ",", "size", ",", "perms", ")", ":", "logger", ".", "info", "(", "\"Updating selector %s to 0x%02x (%s bytes) (%s)\"", ",", "selector", ",", "base", ",", "size", ",", "perms", ")", "if", "se...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
deprecated
A decorator for marking functions as deprecated.
manticore/utils/deprecated.py
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__}` is deprecated. {message}", category=ManticoreDeprecationWarning, stacklevel=2) return func(*args, **kwargs) return wrapper return decorator
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__}` is deprecated. {message}", category=ManticoreDeprecationWarning, stacklevel=2) return func(*args, **kwargs) return wrapper return decorator
[ "A", "decorator", "for", "marking", "functions", "as", "deprecated", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/deprecated.py#L17-L30
[ "def", "deprecated", "(", "message", ":", "str", ")", ":", "assert", "isinstance", "(", "message", ",", "str", ")", ",", "\"The deprecated decorator requires a message string argument.\"", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
flip
flips a constraint (Equal) (Equal (BitVecITE Cond IfC ElseC) IfC) -> (Equal (BitVecITE Cond IfC ElseC) ElseC)
examples/script/concolic.py
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 ite, forcepc = equal.operands assert isinstance(ite, BitVecITE) and isinstance(forcepc, BitVecConstant) assert len(ite.operands) == 3 cond, iifpc, eelsepc = ite.operands assert isinstance(iifpc, BitVecConstant) and isinstance(eelsepc, BitVecConstant) equal._operands= (equal.operands[0], eelsepc if forcepc.value == iifpc.value else iifpc) return 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 ite, forcepc = equal.operands assert isinstance(ite, BitVecITE) and isinstance(forcepc, BitVecConstant) assert len(ite.operands) == 3 cond, iifpc, eelsepc = ite.operands assert isinstance(iifpc, BitVecConstant) and isinstance(eelsepc, BitVecConstant) equal._operands= (equal.operands[0], eelsepc if forcepc.value == iifpc.value else iifpc) return equal
[ "flips", "a", "constraint", "(", "Equal", ")" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L55-L75
[ "def", "flip", "(", "constraint", ")", ":", "equal", "=", "copy", ".", "copy", "(", "constraint", ")", "assert", "len", "(", "equal", ".", "operands", ")", "==", "2", "# assume they are the equal -> ite form that we produce on standard branches", "ite", ",", "forc...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
perm
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. [ C1, C2, C3 ] we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list. So we'd like to generate: [ func(C1), C2 , C3 ], [ C1 , func(C2), C3 ], [ func(C1), func(C2), C3 ], [ C1 , C2 , func(C3)], .. etc This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the 0th element (unmodified array). The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to 2**len(lst) and applying func to all the set bit offsets.
examples/script/concolic.py
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. [ C1, C2, C3 ] we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list. So we'd like to generate: [ func(C1), C2 , C3 ], [ C1 , func(C2), C3 ], [ func(C1), func(C2), C3 ], [ C1 , C2 , func(C3)], .. etc This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the 0th element (unmodified array). The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to 2**len(lst) and applying func to all the set bit offsets. ''' for i in range(1, 2**len(lst)): yield [func(item) if (1<<j)&i else item for (j, item) in enumerate(lst)]
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. [ C1, C2, C3 ] we'd like to consider scenarios of all possible permutations of flipped constraints, excluding the original list. So we'd like to generate: [ func(C1), C2 , C3 ], [ C1 , func(C2), C3 ], [ func(C1), func(C2), C3 ], [ C1 , C2 , func(C3)], .. etc This is effectively treating the list of constraints as a bitmask of width len(lst) and counting up, skipping the 0th element (unmodified array). The code below yields lists of constraints permuted as above by treating list indeces as bitmasks from 1 to 2**len(lst) and applying func to all the set bit offsets. ''' for i in range(1, 2**len(lst)): yield [func(item) if (1<<j)&i else item for (j, item) in enumerate(lst)]
[ "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", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L97-L123
[ "def", "perm", "(", "lst", ",", "func", ")", ":", "for", "i", "in", "range", "(", "1", ",", "2", "**", "len", "(", "lst", ")", ")", ":", "yield", "[", "func", "(", "item", ")", "if", "(", "1", "<<", "j", ")", "&", "i", "else", "item", "fo...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
input_from_cons
solve bytes in |datas| based on
examples/script/concolic.py
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_chr(solver.get_value(newset, c)) return ret
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_chr(solver.get_value(newset, c)) return ret
[ "solve", "bytes", "in", "|datas|", "based", "on" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L130-L143
[ "def", "input_from_cons", "(", "constupl", ",", "datas", ")", ":", "def", "make_chr", "(", "c", ")", ":", "try", ":", "return", "chr", "(", "c", ")", "except", "Exception", ":", "return", "c", "newset", "=", "constraints_to_constraintset", "(", "constupl",...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
symbolic_run_get_cons
Execute a symbolic run that follows a concrete run; return constraints generated and the stdin data produced
examples/script/concolic.py
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_testcase(mcore, state, stateid, err): with m2.locked_context() as ctx: readdata = [] for name, fd, data in state.platform.syscall_trace: if name in ('_receive', '_read') and fd == 0: readdata.append(data) ctx['readdata'] = readdata ctx['constraints'] = list(state.constraints.constraints) m2.subscribe('will_terminate_state', on_term_testcase) m2.run() constraints = m2.context['constraints'] datas = m2.context['readdata'] return constraints, datas
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_testcase(mcore, state, stateid, err): with m2.locked_context() as ctx: readdata = [] for name, fd, data in state.platform.syscall_trace: if name in ('_receive', '_read') and fd == 0: readdata.append(data) ctx['readdata'] = readdata ctx['constraints'] = list(state.constraints.constraints) m2.subscribe('will_terminate_state', on_term_testcase) m2.run() constraints = m2.context['constraints'] datas = m2.context['readdata'] return constraints, datas
[ "Execute", "a", "symbolic", "run", "that", "follows", "a", "concrete", "run", ";", "return", "constraints", "generated", "and", "the", "stdin", "data", "produced" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/examples/script/concolic.py#L157-L184
[ "def", "symbolic_run_get_cons", "(", "trace", ")", ":", "m2", "=", "Manticore", ".", "linux", "(", "prog", ",", "workspace_url", "=", "'mem:'", ")", "f", "=", "Follower", "(", "trace", ")", "m2", ".", "verbosity", "(", "VERBOSITY", ")", "m2", ".", "reg...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SymbolicFile.seek
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.
manticore/platforms/linux.py
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_SET, os.SEEK_CUR, os.SEEK_END) new_position = 0 if whence == os.SEEK_SET: new_position = offset elif whence == os.SEEK_CUR: new_position = self.pos + offset elif whence == os.SEEK_END: new_position = self.max_size + offset if new_position < 0: return -1 self.pos = new_position return self.pos
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_SET, os.SEEK_CUR, os.SEEK_END) new_position = 0 if whence == os.SEEK_SET: new_position = offset elif whence == os.SEEK_CUR: new_position = self.pos + offset elif whence == os.SEEK_END: new_position = self.max_size + offset if new_position < 0: return -1 self.pos = new_position return self.pos
[ "Repositions", "the", "file", "C", "{", "offset", "}", "according", "to", "C", "{", "whence", "}", ".", "Returns", "the", "resulting", "offset", "or", "-", "1", "in", "case", "of", "error", ".", ":", "rtype", ":", "int", ":", "return", ":", "the", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L265-L288
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "os", ".", "SEEK_SET", ")", ":", "assert", "isinstance", "(", "offset", ",", "int", ")", "assert", "whence", "in", "(", "os", ".", "SEEK_SET", ",", "os", ".", "SEEK_CUR", ",", "os", "."...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SymbolicFile.read
Reads up to C{count} bytes from the file. :rtype: list :return: the list of symbolic bytes read
manticore/platforms/linux.py
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.array[i] for i in range(self.pos, self.pos + size)] self.pos += size return ret
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.array[i] for i in range(self.pos, self.pos + size)] self.pos += size return ret
[ "Reads", "up", "to", "C", "{", "count", "}", "bytes", "from", "the", "file", ".", ":", "rtype", ":", "list", ":", "return", ":", "the", "list", "of", "symbolic", "bytes", "read" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L290-L302
[ "def", "read", "(", "self", ",", "count", ")", ":", "if", "self", ".", "pos", ">", "self", ".", "max_size", ":", "return", "[", "]", "else", ":", "size", "=", "min", "(", "count", ",", "self", ".", "max_size", "-", "self", ".", "pos", ")", "ret...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SymbolicFile.write
Writes the symbolic bytes in C{data} onto the file.
manticore/platforms/linux.py
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]
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]
[ "Writes", "the", "symbolic", "bytes", "in", "C", "{", "data", "}", "onto", "the", "file", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L304-L310
[ "def", "write", "(", "self", ",", "data", ")", ":", "size", "=", "min", "(", "len", "(", "data", ")", ",", "self", ".", "max_size", "-", "self", ".", "pos", ")", "for", "i", "in", "range", "(", "self", ".", "pos", ",", "self", ".", "pos", "+"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.empty_platform
Create a platform without an ELF loaded. :param str arch: The architecture of the new platform :rtype: Linux
manticore/platforms/linux.py
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
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
[ "Create", "a", "platform", "without", "an", "ELF", "loaded", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L452-L462
[ "def", "empty_platform", "(", "cls", ",", "arch", ")", ":", "platform", "=", "cls", "(", "None", ")", "platform", ".", "_init_cpu", "(", "arch", ")", "platform", ".", "_init_std_fds", "(", ")", "return", "platform" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux._execve
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
manticore/platforms/linux.py
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 envp = [] if envp is None else envp logger.debug(f"Loading {program} as a {self.arch} elf") self.load(program, envp) self._arch_specific_init() self._stack_top = self.current.STACK self.setup_stack([program] + argv, envp) nprocs = len(self.procs) nfiles = len(self.files) assert nprocs > 0 self.running = list(range(nprocs)) # Each process can wait for one timeout self.timers = [None] * nprocs # each fd has a waitlist self.rwait = [set() for _ in range(nfiles)] self.twait = [set() for _ in range(nfiles)] # Install event forwarders for proc in self.procs: self.forward_events_from(proc)
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 envp = [] if envp is None else envp logger.debug(f"Loading {program} as a {self.arch} elf") self.load(program, envp) self._arch_specific_init() self._stack_top = self.current.STACK self.setup_stack([program] + argv, envp) nprocs = len(self.procs) nfiles = len(self.files) assert nprocs > 0 self.running = list(range(nprocs)) # Each process can wait for one timeout self.timers = [None] * nprocs # each fd has a waitlist self.rwait = [set() for _ in range(nfiles)] self.twait = [set() for _ in range(nfiles)] # Install event forwarders for proc in self.procs: self.forward_events_from(proc)
[ "Load", "program", "and", "establish", "program", "state", "such", "as", "stack", "and", "arguments", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L511-L543
[ "def", "_execve", "(", "self", ",", "program", ",", "argv", ",", "envp", ")", ":", "argv", "=", "[", "]", "if", "argv", "is", "None", "else", "argv", "envp", "=", "[", "]", "if", "envp", "is", "None", "else", "envp", "logger", ".", "debug", "(", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux._init_arm_kernel_helpers
ARM kernel helpers https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
manticore/platforms/linux.py
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' + '650400ea' + 'f0ff9fe5' + '430400ea' + '220400ea' + '810400ea' + '000400ea' + '870400ea' ) # XXX(yan): The following implementations of cmpxchg and cmpxchg64 were # handwritten to not use any exclusive instructions (e.g. ldrexd) or # locking. For actual implementations, refer to # arch/arm64/kernel/kuser32.S in the Linux source code. __kuser_cmpxchg64 = binascii.unhexlify( '30002de9' + # push {r4, r5} '08c09de5' + # ldr ip, [sp, #8] '30009ce8' + # ldm ip, {r4, r5} '010055e1' + # cmp r5, r1 '00005401' + # cmpeq r4, r0 '0100a013' + # movne r0, #1 '0000a003' + # moveq r0, #0 '0c008c08' + # stmeq ip, {r2, r3} '3000bde8' + # pop {r4, r5} '1eff2fe1' # bx lr ) __kuser_dmb = binascii.unhexlify( '5bf07ff5' + # dmb ish '1eff2fe1' # bx lr ) __kuser_cmpxchg = binascii.unhexlify( '003092e5' + # ldr r3, [r2] '000053e1' + # cmp r3, r0 '0000a003' + # moveq r0, #0 '00108205' + # streq r1, [r2] '0100a013' + # movne r0, #1 '1eff2fe1' # bx lr ) # Map a TLS segment self._arm_tls_memory = self.current.memory.mmap(None, 4, 'rw ') __kuser_get_tls = binascii.unhexlify( '04009FE5' + # ldr r0, [pc, #4] '010090e8' + # ldm r0, {r0} '1eff2fe1' # bx lr ) + struct.pack('<I', self._arm_tls_memory) tls_area = b'\x00' * 12 version = struct.pack('<I', 5) def update(address, code): page_data[address:address + len(code)] = code # Offsets from Documentation/arm/kernel_user_helpers.txt in Linux update(0x000, preamble) update(0xf60, __kuser_cmpxchg64) update(0xfa0, __kuser_dmb) update(0xfc0, __kuser_cmpxchg) update(0xfe0, __kuser_get_tls) update(0xff0, tls_area) update(0xffc, version) self.current.memory.mmap(0xffff0000, len(page_data), 'r x', page_data)
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' + '650400ea' + 'f0ff9fe5' + '430400ea' + '220400ea' + '810400ea' + '000400ea' + '870400ea' ) # XXX(yan): The following implementations of cmpxchg and cmpxchg64 were # handwritten to not use any exclusive instructions (e.g. ldrexd) or # locking. For actual implementations, refer to # arch/arm64/kernel/kuser32.S in the Linux source code. __kuser_cmpxchg64 = binascii.unhexlify( '30002de9' + # push {r4, r5} '08c09de5' + # ldr ip, [sp, #8] '30009ce8' + # ldm ip, {r4, r5} '010055e1' + # cmp r5, r1 '00005401' + # cmpeq r4, r0 '0100a013' + # movne r0, #1 '0000a003' + # moveq r0, #0 '0c008c08' + # stmeq ip, {r2, r3} '3000bde8' + # pop {r4, r5} '1eff2fe1' # bx lr ) __kuser_dmb = binascii.unhexlify( '5bf07ff5' + # dmb ish '1eff2fe1' # bx lr ) __kuser_cmpxchg = binascii.unhexlify( '003092e5' + # ldr r3, [r2] '000053e1' + # cmp r3, r0 '0000a003' + # moveq r0, #0 '00108205' + # streq r1, [r2] '0100a013' + # movne r0, #1 '1eff2fe1' # bx lr ) # Map a TLS segment self._arm_tls_memory = self.current.memory.mmap(None, 4, 'rw ') __kuser_get_tls = binascii.unhexlify( '04009FE5' + # ldr r0, [pc, #4] '010090e8' + # ldm r0, {r0} '1eff2fe1' # bx lr ) + struct.pack('<I', self._arm_tls_memory) tls_area = b'\x00' * 12 version = struct.pack('<I', 5) def update(address, code): page_data[address:address + len(code)] = code # Offsets from Documentation/arm/kernel_user_helpers.txt in Linux update(0x000, preamble) update(0xf60, __kuser_cmpxchg64) update(0xfa0, __kuser_dmb) update(0xfc0, __kuser_cmpxchg) update(0xfe0, __kuser_get_tls) update(0xff0, tls_area) update(0xffc, version) self.current.memory.mmap(0xffff0000, len(page_data), 'r x', page_data)
[ "ARM", "kernel", "helpers" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L654-L731
[ "def", "_init_arm_kernel_helpers", "(", "self", ")", ":", "page_data", "=", "bytearray", "(", "b'\\xf1\\xde\\xfd\\xe7'", "*", "1024", ")", "# Extracted from a RPi2", "preamble", "=", "binascii", ".", "unhexlify", "(", "'ff0300ea'", "+", "'650400ea'", "+", "'f0ff9fe5...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.setup_stack
: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 content size (bytes) + comment ---------------------------------------------------------------------- stack pointer -> [ argc = number of args ] 4 [ argv[0] (pointer) ] 4 (program name) [ argv[1] (pointer) ] 4 [ argv[..] (pointer) ] 4 * x [ argv[n - 1] (pointer) ] 4 [ argv[n] (pointer) ] 4 (= NULL) [ envp[0] (pointer) ] 4 [ envp[1] (pointer) ] 4 [ envp[..] (pointer) ] 4 [ envp[term] (pointer) ] 4 (= NULL) [ auxv[0] (Elf32_auxv_t) ] 8 [ auxv[1] (Elf32_auxv_t) ] 8 [ auxv[..] (Elf32_auxv_t) ] 8 [ auxv[term] (Elf32_auxv_t) ] 8 (= AT_NULL vector) [ padding ] 0 - 16 [ argument ASCIIZ strings ] >= 0 [ environment ASCIIZ str. ] >= 0 (0xbffffffc) [ end marker ] 4 (= NULL) (0xc0000000) < top of stack > 0 (virtual) ----------------------------------------------------------------------
manticore/platforms/linux.py
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 content size (bytes) + comment ---------------------------------------------------------------------- stack pointer -> [ argc = number of args ] 4 [ argv[0] (pointer) ] 4 (program name) [ argv[1] (pointer) ] 4 [ argv[..] (pointer) ] 4 * x [ argv[n - 1] (pointer) ] 4 [ argv[n] (pointer) ] 4 (= NULL) [ envp[0] (pointer) ] 4 [ envp[1] (pointer) ] 4 [ envp[..] (pointer) ] 4 [ envp[term] (pointer) ] 4 (= NULL) [ auxv[0] (Elf32_auxv_t) ] 8 [ auxv[1] (Elf32_auxv_t) ] 8 [ auxv[..] (Elf32_auxv_t) ] 8 [ auxv[term] (Elf32_auxv_t) ] 8 (= AT_NULL vector) [ padding ] 0 - 16 [ argument ASCIIZ strings ] >= 0 [ environment ASCIIZ str. ] >= 0 (0xbffffffc) [ end marker ] 4 (= NULL) (0xc0000000) < top of stack > 0 (virtual) ---------------------------------------------------------------------- """ cpu = self.current # In case setup_stack() is called again, we make sure we're growing the # stack from the original top cpu.STACK = self._stack_top auxv = self.auxv logger.debug("Setting argv, envp and auxv.") logger.debug(f"\tArguments: {argv!r}") if envp: logger.debug("\tEnvironment:") for e in envp: logger.debug(f"\t\t{e!r}") logger.debug("\tAuxv:") for name, val in auxv.items(): logger.debug(f"\t\t{name}: 0x{val:x}") # We save the argument and environment pointers argvlst = [] envplst = [] # end envp marker empty string for evar in envp: cpu.push_bytes('\x00') envplst.append(cpu.push_bytes(evar)) for arg in argv: cpu.push_bytes('\x00') argvlst.append(cpu.push_bytes(arg)) # Put all auxv strings into the string stack area. # And replace the value be its pointer for name, value in auxv.items(): if hasattr(value, '__len__'): cpu.push_bytes(value) auxv[name] = cpu.STACK # The "secure execution" mode of secure_getenv() is controlled by the # AT_SECURE flag contained in the auxiliary vector passed from the # kernel to user space. auxvnames = { 'AT_IGNORE': 1, # Entry should be ignored 'AT_EXECFD': 2, # File descriptor of program 'AT_PHDR': 3, # Program headers for program 'AT_PHENT': 4, # Size of program header entry 'AT_PHNUM': 5, # Number of program headers 'AT_PAGESZ': 6, # System page size 'AT_BASE': 7, # Base address of interpreter 'AT_FLAGS': 8, # Flags 'AT_ENTRY': 9, # Entry point of program 'AT_NOTELF': 10, # Program is not ELF 'AT_UID': 11, # Real uid 'AT_EUID': 12, # Effective uid 'AT_GID': 13, # Real gid 'AT_EGID': 14, # Effective gid 'AT_CLKTCK': 17, # Frequency of times() 'AT_PLATFORM': 15, # String identifying platform. 'AT_HWCAP': 16, # Machine-dependent hints about processor capabilities. 'AT_FPUCW': 18, # Used FPU control word. 'AT_SECURE': 23, # Boolean, was exec setuid-like? 'AT_BASE_PLATFORM': 24, # String identifying real platforms. 'AT_RANDOM': 25, # Address of 16 random bytes. 'AT_EXECFN': 31, # Filename of executable. 'AT_SYSINFO': 32, # Pointer to the global system page used for system calls and other nice things. 'AT_SYSINFO_EHDR': 33, # Pointer to the global system page used for system calls and other nice things. } # AT_NULL cpu.push_int(0) cpu.push_int(0) for name, val in auxv.items(): cpu.push_int(val) cpu.push_int(auxvnames[name]) # NULL ENVP cpu.push_int(0) for var in reversed(envplst): # ENVP n cpu.push_int(var) envp = cpu.STACK # NULL ARGV cpu.push_int(0) for arg in reversed(argvlst): # Argv n cpu.push_int(arg) argv = cpu.STACK # ARGC cpu.push_int(len(argvlst))
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 content size (bytes) + comment ---------------------------------------------------------------------- stack pointer -> [ argc = number of args ] 4 [ argv[0] (pointer) ] 4 (program name) [ argv[1] (pointer) ] 4 [ argv[..] (pointer) ] 4 * x [ argv[n - 1] (pointer) ] 4 [ argv[n] (pointer) ] 4 (= NULL) [ envp[0] (pointer) ] 4 [ envp[1] (pointer) ] 4 [ envp[..] (pointer) ] 4 [ envp[term] (pointer) ] 4 (= NULL) [ auxv[0] (Elf32_auxv_t) ] 8 [ auxv[1] (Elf32_auxv_t) ] 8 [ auxv[..] (Elf32_auxv_t) ] 8 [ auxv[term] (Elf32_auxv_t) ] 8 (= AT_NULL vector) [ padding ] 0 - 16 [ argument ASCIIZ strings ] >= 0 [ environment ASCIIZ str. ] >= 0 (0xbffffffc) [ end marker ] 4 (= NULL) (0xc0000000) < top of stack > 0 (virtual) ---------------------------------------------------------------------- """ cpu = self.current # In case setup_stack() is called again, we make sure we're growing the # stack from the original top cpu.STACK = self._stack_top auxv = self.auxv logger.debug("Setting argv, envp and auxv.") logger.debug(f"\tArguments: {argv!r}") if envp: logger.debug("\tEnvironment:") for e in envp: logger.debug(f"\t\t{e!r}") logger.debug("\tAuxv:") for name, val in auxv.items(): logger.debug(f"\t\t{name}: 0x{val:x}") # We save the argument and environment pointers argvlst = [] envplst = [] # end envp marker empty string for evar in envp: cpu.push_bytes('\x00') envplst.append(cpu.push_bytes(evar)) for arg in argv: cpu.push_bytes('\x00') argvlst.append(cpu.push_bytes(arg)) # Put all auxv strings into the string stack area. # And replace the value be its pointer for name, value in auxv.items(): if hasattr(value, '__len__'): cpu.push_bytes(value) auxv[name] = cpu.STACK # The "secure execution" mode of secure_getenv() is controlled by the # AT_SECURE flag contained in the auxiliary vector passed from the # kernel to user space. auxvnames = { 'AT_IGNORE': 1, # Entry should be ignored 'AT_EXECFD': 2, # File descriptor of program 'AT_PHDR': 3, # Program headers for program 'AT_PHENT': 4, # Size of program header entry 'AT_PHNUM': 5, # Number of program headers 'AT_PAGESZ': 6, # System page size 'AT_BASE': 7, # Base address of interpreter 'AT_FLAGS': 8, # Flags 'AT_ENTRY': 9, # Entry point of program 'AT_NOTELF': 10, # Program is not ELF 'AT_UID': 11, # Real uid 'AT_EUID': 12, # Effective uid 'AT_GID': 13, # Real gid 'AT_EGID': 14, # Effective gid 'AT_CLKTCK': 17, # Frequency of times() 'AT_PLATFORM': 15, # String identifying platform. 'AT_HWCAP': 16, # Machine-dependent hints about processor capabilities. 'AT_FPUCW': 18, # Used FPU control word. 'AT_SECURE': 23, # Boolean, was exec setuid-like? 'AT_BASE_PLATFORM': 24, # String identifying real platforms. 'AT_RANDOM': 25, # Address of 16 random bytes. 'AT_EXECFN': 31, # Filename of executable. 'AT_SYSINFO': 32, # Pointer to the global system page used for system calls and other nice things. 'AT_SYSINFO_EHDR': 33, # Pointer to the global system page used for system calls and other nice things. } # AT_NULL cpu.push_int(0) cpu.push_int(0) for name, val in auxv.items(): cpu.push_int(val) cpu.push_int(auxvnames[name]) # NULL ENVP cpu.push_int(0) for var in reversed(envplst): # ENVP n cpu.push_int(var) envp = cpu.STACK # NULL ARGV cpu.push_int(0) for arg in reversed(argvlst): # Argv n cpu.push_int(arg) argv = cpu.STACK # ARGC cpu.push_int(len(argvlst))
[ ":", "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",...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L745-L869
[ "def", "setup_stack", "(", "self", ",", "argv", ",", "envp", ")", ":", "cpu", "=", "self", ".", "current", "# In case setup_stack() is called again, we make sure we're growing the", "# stack from the original top", "cpu", ".", "STACK", "=", "self", ".", "_stack_top", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.load
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 of env variables. (used for extracting vars that control ld behavior) :raises error: - 'Not matching cpu': if the program is compiled for a different architecture - 'Not matching memory': if the program is compiled for a different address size :todo: define va_randomize and read_implies_exec personality
manticore/platforms/linux.py
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 of env variables. (used for extracting vars that control ld behavior) :raises error: - 'Not matching cpu': if the program is compiled for a different architecture - 'Not matching memory': if the program is compiled for a different address size :todo: define va_randomize and read_implies_exec personality """ # load elf See binfmt_elf.c # read the ELF object file cpu = self.current elf = self.elf arch = self.arch env = dict(var.split('=') for var in env if '=' in var) addressbitsize = {'x86': 32, 'x64': 64, 'ARM': 32}[elf.get_machine_arch()] logger.debug("Loading %s as a %s elf", filename, arch) assert elf.header.e_type in ['ET_DYN', 'ET_EXEC', 'ET_CORE'] # Get interpreter elf interpreter = None for elf_segment in elf.iter_segments(): if elf_segment.header.p_type != 'PT_INTERP': continue interpreter_filename = elf_segment.data()[:-1] logger.info(f'Interpreter filename: {interpreter_filename}') if os.path.exists(interpreter_filename.decode('utf-8')): interpreter = ELFFile(open(interpreter_filename, 'rb')) elif 'LD_LIBRARY_PATH' in env: for mpath in env['LD_LIBRARY_PATH'].split(":"): interpreter_path_filename = os.path.join(mpath, os.path.basename(interpreter_filename)) logger.info(f"looking for interpreter {interpreter_path_filename}") if os.path.exists(interpreter_path_filename): interpreter = ELFFile(open(interpreter_path_filename, 'rb')) break break if interpreter is not None: assert interpreter.get_machine_arch() == elf.get_machine_arch() assert interpreter.header.e_type in ['ET_DYN', 'ET_EXEC'] # Stack Executability executable_stack = False for elf_segment in elf.iter_segments(): if elf_segment.header.p_type != 'PT_GNU_STACK': continue if elf_segment.header.p_flags & 0x01: executable_stack = True else: executable_stack = False break base = 0 elf_bss = 0 end_code = 0 end_data = 0 elf_brk = 0 self.load_addr = 0 for elf_segment in elf.iter_segments(): if elf_segment.header.p_type != 'PT_LOAD': continue align = 0x1000 # elf_segment.header.p_align ELF_PAGEOFFSET = elf_segment.header.p_vaddr & (align - 1) flags = elf_segment.header.p_flags memsz = elf_segment.header.p_memsz + ELF_PAGEOFFSET offset = elf_segment.header.p_offset - ELF_PAGEOFFSET filesz = elf_segment.header.p_filesz + ELF_PAGEOFFSET vaddr = elf_segment.header.p_vaddr - ELF_PAGEOFFSET memsz = cpu.memory._ceil(memsz) if base == 0 and elf.header.e_type == 'ET_DYN': assert vaddr == 0 if addressbitsize == 32: base = 0x56555000 else: base = 0x555555554000 perms = perms_from_elf(flags) hint = base + vaddr if hint == 0: hint = None logger.debug(f"Loading elf offset: {offset:08x} addr:{base + vaddr:08x} {base + vaddr + memsz:08x} {perms}") base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset) - vaddr if self.load_addr == 0: self.load_addr = base + vaddr k = base + vaddr + filesz if k > elf_bss: elf_bss = k if (flags & 4) and end_code < k: # PF_X end_code = k if end_data < k: end_data = k k = base + vaddr + memsz if k > elf_brk: elf_brk = k elf_entry = elf.header.e_entry if elf.header.e_type == 'ET_DYN': elf_entry += self.load_addr entry = elf_entry real_elf_brk = elf_brk # We need to explicitly clear bss, as fractional pages will have data from the file bytes_to_clear = elf_brk - elf_bss if bytes_to_clear > 0: logger.debug(f"Zeroing main elf fractional pages. From bss({elf_bss:x}) to brk({elf_brk:x}), {bytes_to_clear} bytes.") cpu.write_bytes(elf_bss, '\x00' * bytes_to_clear, force=True) stack_size = 0x21000 if addressbitsize == 32: stack_top = 0xc0000000 else: stack_top = 0x800000000000 stack_base = stack_top - stack_size stack = cpu.memory.mmap(stack_base, stack_size, 'rwx', name='stack') + stack_size assert stack_top == stack reserved = cpu.memory.mmap(base + vaddr + memsz, 0x1000000, ' ') interpreter_base = 0 if interpreter is not None: base = 0 elf_bss = 0 end_code = 0 end_data = 0 elf_brk = 0 entry = interpreter.header.e_entry for elf_segment in interpreter.iter_segments(): if elf_segment.header.p_type != 'PT_LOAD': continue align = 0x1000 # elf_segment.header.p_align vaddr = elf_segment.header.p_vaddr filesz = elf_segment.header.p_filesz flags = elf_segment.header.p_flags offset = elf_segment.header.p_offset memsz = elf_segment.header.p_memsz ELF_PAGEOFFSET = (vaddr & (align - 1)) memsz = memsz + ELF_PAGEOFFSET offset = offset - ELF_PAGEOFFSET filesz = filesz + ELF_PAGEOFFSET vaddr = vaddr - ELF_PAGEOFFSET memsz = cpu.memory._ceil(memsz) if base == 0 and interpreter.header.e_type == 'ET_DYN': assert vaddr == 0 total_size = self._interp_total_size(interpreter) base = stack_base - total_size if base == 0: assert vaddr == 0 perms = perms_from_elf(flags) hint = base + vaddr if hint == 0: hint = None base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset) base -= vaddr logger.debug( f"Loading interpreter offset: {offset:08x} " f"addr:{base + vaddr:08x} " f"{base + vaddr + memsz:08x} " f"{(flags & 1 and 'r' or ' ')}" f"{(flags & 2 and 'w' or ' ')}" f"{(flags & 4 and 'x' or ' ')}" ) k = base + vaddr + filesz if k > elf_bss: elf_bss = k if (flags & 4) and end_code < k: # PF_X end_code = k if end_data < k: end_data = k k = base + vaddr + memsz if k > elf_brk: elf_brk = k if interpreter.header.e_type == 'ET_DYN': entry += base interpreter_base = base bytes_to_clear = elf_brk - elf_bss if bytes_to_clear > 0: logger.debug(f"Zeroing interpreter elf fractional pages. From bss({elf_bss:x}) to brk({elf_brk:x}), {bytes_to_clear} bytes.") cpu.write_bytes(elf_bss, '\x00' * bytes_to_clear, force=True) # free reserved brk space cpu.memory.munmap(reserved, 0x1000000) # load vdso #vdso_addr = load_vdso(addressbitsize) cpu.STACK = stack cpu.PC = entry logger.debug(f"Entry point: {entry:016x}") logger.debug(f"Stack start: {stack:016x}") logger.debug(f"Brk: {real_elf_brk:016x}") logger.debug(f"Mappings:") for m in str(cpu.memory).split('\n'): logger.debug(f" {m}") self.base = base self.elf_bss = elf_bss self.end_code = end_code self.end_data = end_data self.elf_brk = real_elf_brk self.brk = real_elf_brk at_random = cpu.push_bytes('A' * 16) at_execfn = cpu.push_bytes(f'{filename}\x00') self.auxv = { 'AT_PHDR': self.load_addr + elf.header.e_phoff, # Program headers for program 'AT_PHENT': elf.header.e_phentsize, # Size of program header entry 'AT_PHNUM': elf.header.e_phnum, # Number of program headers 'AT_PAGESZ': cpu.memory.page_size, # System page size 'AT_BASE': interpreter_base, # Base address of interpreter 'AT_FLAGS': elf.header.e_flags, # Flags 'AT_ENTRY': elf_entry, # Entry point of program 'AT_UID': 1000, # Real uid 'AT_EUID': 1000, # Effective uid 'AT_GID': 1000, # Real gid 'AT_EGID': 1000, # Effective gid 'AT_CLKTCK': 100, # Frequency of times() 'AT_HWCAP': 0, # Machine-dependent hints about processor capabilities. 'AT_RANDOM': at_random, # Address of 16 random bytes. 'AT_EXECFN': at_execfn, # Filename of executable. }
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 of env variables. (used for extracting vars that control ld behavior) :raises error: - 'Not matching cpu': if the program is compiled for a different architecture - 'Not matching memory': if the program is compiled for a different address size :todo: define va_randomize and read_implies_exec personality """ # load elf See binfmt_elf.c # read the ELF object file cpu = self.current elf = self.elf arch = self.arch env = dict(var.split('=') for var in env if '=' in var) addressbitsize = {'x86': 32, 'x64': 64, 'ARM': 32}[elf.get_machine_arch()] logger.debug("Loading %s as a %s elf", filename, arch) assert elf.header.e_type in ['ET_DYN', 'ET_EXEC', 'ET_CORE'] # Get interpreter elf interpreter = None for elf_segment in elf.iter_segments(): if elf_segment.header.p_type != 'PT_INTERP': continue interpreter_filename = elf_segment.data()[:-1] logger.info(f'Interpreter filename: {interpreter_filename}') if os.path.exists(interpreter_filename.decode('utf-8')): interpreter = ELFFile(open(interpreter_filename, 'rb')) elif 'LD_LIBRARY_PATH' in env: for mpath in env['LD_LIBRARY_PATH'].split(":"): interpreter_path_filename = os.path.join(mpath, os.path.basename(interpreter_filename)) logger.info(f"looking for interpreter {interpreter_path_filename}") if os.path.exists(interpreter_path_filename): interpreter = ELFFile(open(interpreter_path_filename, 'rb')) break break if interpreter is not None: assert interpreter.get_machine_arch() == elf.get_machine_arch() assert interpreter.header.e_type in ['ET_DYN', 'ET_EXEC'] # Stack Executability executable_stack = False for elf_segment in elf.iter_segments(): if elf_segment.header.p_type != 'PT_GNU_STACK': continue if elf_segment.header.p_flags & 0x01: executable_stack = True else: executable_stack = False break base = 0 elf_bss = 0 end_code = 0 end_data = 0 elf_brk = 0 self.load_addr = 0 for elf_segment in elf.iter_segments(): if elf_segment.header.p_type != 'PT_LOAD': continue align = 0x1000 # elf_segment.header.p_align ELF_PAGEOFFSET = elf_segment.header.p_vaddr & (align - 1) flags = elf_segment.header.p_flags memsz = elf_segment.header.p_memsz + ELF_PAGEOFFSET offset = elf_segment.header.p_offset - ELF_PAGEOFFSET filesz = elf_segment.header.p_filesz + ELF_PAGEOFFSET vaddr = elf_segment.header.p_vaddr - ELF_PAGEOFFSET memsz = cpu.memory._ceil(memsz) if base == 0 and elf.header.e_type == 'ET_DYN': assert vaddr == 0 if addressbitsize == 32: base = 0x56555000 else: base = 0x555555554000 perms = perms_from_elf(flags) hint = base + vaddr if hint == 0: hint = None logger.debug(f"Loading elf offset: {offset:08x} addr:{base + vaddr:08x} {base + vaddr + memsz:08x} {perms}") base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset) - vaddr if self.load_addr == 0: self.load_addr = base + vaddr k = base + vaddr + filesz if k > elf_bss: elf_bss = k if (flags & 4) and end_code < k: # PF_X end_code = k if end_data < k: end_data = k k = base + vaddr + memsz if k > elf_brk: elf_brk = k elf_entry = elf.header.e_entry if elf.header.e_type == 'ET_DYN': elf_entry += self.load_addr entry = elf_entry real_elf_brk = elf_brk # We need to explicitly clear bss, as fractional pages will have data from the file bytes_to_clear = elf_brk - elf_bss if bytes_to_clear > 0: logger.debug(f"Zeroing main elf fractional pages. From bss({elf_bss:x}) to brk({elf_brk:x}), {bytes_to_clear} bytes.") cpu.write_bytes(elf_bss, '\x00' * bytes_to_clear, force=True) stack_size = 0x21000 if addressbitsize == 32: stack_top = 0xc0000000 else: stack_top = 0x800000000000 stack_base = stack_top - stack_size stack = cpu.memory.mmap(stack_base, stack_size, 'rwx', name='stack') + stack_size assert stack_top == stack reserved = cpu.memory.mmap(base + vaddr + memsz, 0x1000000, ' ') interpreter_base = 0 if interpreter is not None: base = 0 elf_bss = 0 end_code = 0 end_data = 0 elf_brk = 0 entry = interpreter.header.e_entry for elf_segment in interpreter.iter_segments(): if elf_segment.header.p_type != 'PT_LOAD': continue align = 0x1000 # elf_segment.header.p_align vaddr = elf_segment.header.p_vaddr filesz = elf_segment.header.p_filesz flags = elf_segment.header.p_flags offset = elf_segment.header.p_offset memsz = elf_segment.header.p_memsz ELF_PAGEOFFSET = (vaddr & (align - 1)) memsz = memsz + ELF_PAGEOFFSET offset = offset - ELF_PAGEOFFSET filesz = filesz + ELF_PAGEOFFSET vaddr = vaddr - ELF_PAGEOFFSET memsz = cpu.memory._ceil(memsz) if base == 0 and interpreter.header.e_type == 'ET_DYN': assert vaddr == 0 total_size = self._interp_total_size(interpreter) base = stack_base - total_size if base == 0: assert vaddr == 0 perms = perms_from_elf(flags) hint = base + vaddr if hint == 0: hint = None base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset) base -= vaddr logger.debug( f"Loading interpreter offset: {offset:08x} " f"addr:{base + vaddr:08x} " f"{base + vaddr + memsz:08x} " f"{(flags & 1 and 'r' or ' ')}" f"{(flags & 2 and 'w' or ' ')}" f"{(flags & 4 and 'x' or ' ')}" ) k = base + vaddr + filesz if k > elf_bss: elf_bss = k if (flags & 4) and end_code < k: # PF_X end_code = k if end_data < k: end_data = k k = base + vaddr + memsz if k > elf_brk: elf_brk = k if interpreter.header.e_type == 'ET_DYN': entry += base interpreter_base = base bytes_to_clear = elf_brk - elf_bss if bytes_to_clear > 0: logger.debug(f"Zeroing interpreter elf fractional pages. From bss({elf_bss:x}) to brk({elf_brk:x}), {bytes_to_clear} bytes.") cpu.write_bytes(elf_bss, '\x00' * bytes_to_clear, force=True) # free reserved brk space cpu.memory.munmap(reserved, 0x1000000) # load vdso #vdso_addr = load_vdso(addressbitsize) cpu.STACK = stack cpu.PC = entry logger.debug(f"Entry point: {entry:016x}") logger.debug(f"Stack start: {stack:016x}") logger.debug(f"Brk: {real_elf_brk:016x}") logger.debug(f"Mappings:") for m in str(cpu.memory).split('\n'): logger.debug(f" {m}") self.base = base self.elf_bss = elf_bss self.end_code = end_code self.end_data = end_data self.elf_brk = real_elf_brk self.brk = real_elf_brk at_random = cpu.push_bytes('A' * 16) at_execfn = cpu.push_bytes(f'{filename}\x00') self.auxv = { 'AT_PHDR': self.load_addr + elf.header.e_phoff, # Program headers for program 'AT_PHENT': elf.header.e_phentsize, # Size of program header entry 'AT_PHNUM': elf.header.e_phnum, # Number of program headers 'AT_PAGESZ': cpu.memory.page_size, # System page size 'AT_BASE': interpreter_base, # Base address of interpreter 'AT_FLAGS': elf.header.e_flags, # Flags 'AT_ENTRY': elf_entry, # Entry point of program 'AT_UID': 1000, # Real uid 'AT_EUID': 1000, # Effective uid 'AT_GID': 1000, # Real gid 'AT_EGID': 1000, # Effective gid 'AT_CLKTCK': 100, # Frequency of times() 'AT_HWCAP': 0, # Machine-dependent hints about processor capabilities. 'AT_RANDOM': at_random, # Address of 16 random bytes. 'AT_EXECFN': at_execfn, # Filename of executable. }
[ "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", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L878-L1115
[ "def", "load", "(", "self", ",", "filename", ",", "env", ")", ":", "# load elf See binfmt_elf.c", "# read the ELF object file", "cpu", "=", "self", ".", "current", "elf", "=", "self", ".", "elf", "arch", "=", "self", ".", "arch", "env", "=", "dict", "(", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux._open
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
manticore/platforms/linux.py
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(None) self.files[fd] = f else: fd = len(self.files) self.files.append(f) return fd
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(None) self.files[fd] = f else: fd = len(self.files) self.files.append(f) return fd
[ "Adds", "a", "file", "descriptor", "to", "the", "current", "file", "descriptor", "list" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1127-L1141
[ "def", "_open", "(", "self", ",", "f", ")", ":", "if", "None", "in", "self", ".", "files", ":", "fd", "=", "self", ".", "files", ".", "index", "(", "None", ")", "self", ".", "files", "[", "fd", "]", "=", "f", "else", ":", "fd", "=", "len", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux._close
Removes a file descriptor from the file descriptor list :rtype: int :param fd: the file descriptor to close. :return: C{0} on success.
manticore/platforms/linux.py
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]) # Keep track for SymbolicFile testcase generation self.files[fd] = None except IndexError: raise FdError(f"Bad file descriptor ({fd})")
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]) # Keep track for SymbolicFile testcase generation self.files[fd] = None except IndexError: raise FdError(f"Bad file descriptor ({fd})")
[ "Removes", "a", "file", "descriptor", "from", "the", "file", "descriptor", "list", ":", "rtype", ":", "int", ":", "param", "fd", ":", "the", "file", "descriptor", "to", "close", ".", ":", "return", ":", "C", "{", "0", "}", "on", "success", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1143-L1155
[ "def", "_close", "(", "self", ",", "fd", ")", ":", "try", ":", "self", ".", "files", "[", "fd", "]", ".", "close", "(", ")", "self", ".", "_closed_files", ".", "append", "(", "self", ".", "files", "[", "fd", "]", ")", "# Keep track for SymbolicFile t...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux._is_fd_open
Determines if the fd is within range and in the file descr. list :param fd: the file descriptor to check.
manticore/platforms/linux.py
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
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
[ "Determines", "if", "the", "fd", "is", "within", "range", "and", "in", "the", "file", "descr", ".", "list", ":", "param", "fd", ":", "the", "file", "descriptor", "to", "check", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1166-L1171
[ "def", "_is_fd_open", "(", "self", ",", "fd", ")", ":", "return", "fd", ">=", "0", "and", "fd", "<", "len", "(", "self", ".", "files", ")", "and", "self", ".", "files", "[", "fd", "]", "is", "not", "None" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_chdir
chdir - Change current working directory :param int path: Pointer to path
manticore/platforms/linux.py
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 OSError as e: return e.errno
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 OSError as e: return e.errno
[ "chdir", "-", "Change", "current", "working", "directory", ":", "param", "int", "path", ":", "Pointer", "to", "path" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1201-L1212
[ "def", "sys_chdir", "(", "self", ",", "path", ")", ":", "path_str", "=", "self", ".", "current", ".", "read_string", "(", "path", ")", "logger", ".", "debug", "(", "f\"chdir({path_str})\"", ")", "try", ":", "os", ".", "chdir", "(", "path_str", ")", "re...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_getcwd
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
manticore/platforms/linux.py
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() length = len(current_dir) + 1 if size > 0 and size < length: logger.info("GETCWD: size is greater than 0, but is smaller than the length" "of the path + 1. Returning ERANGE") return -errno.ERANGE if not self.current.memory.access_ok(slice(buf, buf + length), 'w'): logger.info("GETCWD: buf within invalid memory. Returning EFAULT") return -errno.EFAULT self.current.write_string(buf, current_dir) logger.debug(f"getcwd(0x{buf:08x}, {size}) -> <{current_dir}> (Size {length})") return length except OSError as e: return -e.errno
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() length = len(current_dir) + 1 if size > 0 and size < length: logger.info("GETCWD: size is greater than 0, but is smaller than the length" "of the path + 1. Returning ERANGE") return -errno.ERANGE if not self.current.memory.access_ok(slice(buf, buf + length), 'w'): logger.info("GETCWD: buf within invalid memory. Returning EFAULT") return -errno.EFAULT self.current.write_string(buf, current_dir) logger.debug(f"getcwd(0x{buf:08x}, {size}) -> <{current_dir}> (Size {length})") return length except OSError as e: return -e.errno
[ "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...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1214-L1240
[ "def", "sys_getcwd", "(", "self", ",", "buf", ",", "size", ")", ":", "try", ":", "current_dir", "=", "os", ".", "getcwd", "(", ")", "length", "=", "len", "(", "current_dir", ")", "+", "1", "if", "size", ">", "0", "and", "size", "<", "length", ":"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_lseek
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 valid file descriptor :param offset: the offset in bytes :param whence: SEEK_SET: The file offset is set to offset bytes. SEEK_CUR: The file offset is set to its current location plus offset bytes. SEEK_END: The file offset is set to the size of the file plus offset bytes. :return: offset from file beginning, or EBADF (fd is not a valid file descriptor or is not open)
manticore/platforms/linux.py
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 valid file descriptor :param offset: the offset in bytes :param whence: SEEK_SET: The file offset is set to offset bytes. SEEK_CUR: The file offset is set to its current location plus offset bytes. SEEK_END: The file offset is set to the size of the file plus offset bytes. :return: offset from file beginning, or EBADF (fd is not a valid file descriptor or is not open) """ signed_offset = self._to_signed_dword(offset) try: return self._get_fd(fd).seek(signed_offset, whence) except FdError as e: logger.info(("LSEEK: Not valid file descriptor on lseek." "Fd not seekable. Returning EBADF")) return -e.err
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 valid file descriptor :param offset: the offset in bytes :param whence: SEEK_SET: The file offset is set to offset bytes. SEEK_CUR: The file offset is set to its current location plus offset bytes. SEEK_END: The file offset is set to the size of the file plus offset bytes. :return: offset from file beginning, or EBADF (fd is not a valid file descriptor or is not open) """ signed_offset = self._to_signed_dword(offset) try: return self._get_fd(fd).seek(signed_offset, whence) except FdError as e: logger.info(("LSEEK: Not valid file descriptor on lseek." "Fd not seekable. Returning EBADF")) return -e.err
[ "lseek", "-", "reposition", "read", "/", "write", "file", "offset" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1242-L1265
[ "def", "sys_lseek", "(", "self", ",", "fd", ",", "offset", ",", "whence", ")", ":", "signed_offset", "=", "self", ".", "_to_signed_dword", "(", "offset", ")", "try", ":", "return", "self", ".", "_get_fd", "(", "fd", ")", ".", "seek", "(", "signed_offse...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_write
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. :param fd a valid file descriptor :param buf a memory buffer :param count number of bytes to send :return: 0 Success EBADF fd is not a valid file descriptor or is not open. EFAULT buf or tx_bytes points to an invalid address.
manticore/platforms/linux.py
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. :param fd a valid file descriptor :param buf a memory buffer :param count number of bytes to send :return: 0 Success EBADF fd is not a valid file descriptor or is not open. EFAULT buf or tx_bytes points to an invalid address. """ data: bytes = bytes() cpu = self.current if count != 0: try: write_fd = self._get_fd(fd) except FdError as e: logger.error(f"WRITE: Not valid file descriptor ({fd}). Returning -{e.err}") return -e.err # TODO check count bytes from buf if buf not in cpu.memory or buf + count not in cpu.memory: logger.debug("WRITE: buf points to invalid address. Returning EFAULT") return -errno.EFAULT if fd > 2 and write_fd.is_full(): cpu.PC -= cpu.instruction.size self.wait([], [fd], None) raise RestartSyscall() data: MixedSymbolicBuffer = cpu.read_bytes(buf, count) data: bytes = self._transform_write_data(data) write_fd.write(data) for line in data.split(b'\n'): line = line.decode('latin-1') # latin-1 encoding will happily decode any byte (0x00-0xff) logger.debug(f"WRITE({fd}, 0x{buf:08x}, {count}) -> <{repr(line):48s}>") self.syscall_trace.append(("_write", fd, data)) self.signal_transmit(fd) return len(data)
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. :param fd a valid file descriptor :param buf a memory buffer :param count number of bytes to send :return: 0 Success EBADF fd is not a valid file descriptor or is not open. EFAULT buf or tx_bytes points to an invalid address. """ data: bytes = bytes() cpu = self.current if count != 0: try: write_fd = self._get_fd(fd) except FdError as e: logger.error(f"WRITE: Not valid file descriptor ({fd}). Returning -{e.err}") return -e.err # TODO check count bytes from buf if buf not in cpu.memory or buf + count not in cpu.memory: logger.debug("WRITE: buf points to invalid address. Returning EFAULT") return -errno.EFAULT if fd > 2 and write_fd.is_full(): cpu.PC -= cpu.instruction.size self.wait([], [fd], None) raise RestartSyscall() data: MixedSymbolicBuffer = cpu.read_bytes(buf, count) data: bytes = self._transform_write_data(data) write_fd.write(data) for line in data.split(b'\n'): line = line.decode('latin-1') # latin-1 encoding will happily decode any byte (0x00-0xff) logger.debug(f"WRITE({fd}, 0x{buf:08x}, {count}) -> <{repr(line):48s}>") self.syscall_trace.append(("_write", fd, data)) self.signal_transmit(fd) return len(data)
[ "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", "cou...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1287-L1329
[ "def", "sys_write", "(", "self", ",", "fd", ",", "buf", ",", "count", ")", ":", "data", ":", "bytes", "=", "bytes", "(", ")", "cpu", "=", "self", ".", "current", "if", "count", "!=", "0", ":", "try", ":", "write_fd", "=", "self", ".", "_get_fd", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_access
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 can access the file in the desired mode. - C{-1} if the calling process can not access the file in the desired mode.
manticore/platforms/linux.py
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 can access the file in the desired mode. - C{-1} if the calling process can not access the file in the desired mode. """ filename = b'' for i in range(0, 255): c = Operators.CHR(self.current.read_int(buf + i, 8)) if c == b'\x00': break filename += c if os.access(filename, mode): return 0 else: return -1
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 can access the file in the desired mode. - C{-1} if the calling process can not access the file in the desired mode. """ filename = b'' for i in range(0, 255): c = Operators.CHR(self.current.read_int(buf + i, 8)) if c == b'\x00': break filename += c if os.access(filename, mode): return 0 else: return -1
[ "Checks", "real", "user", "s", "permissions", "for", "a", "file", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1337-L1358
[ "def", "sys_access", "(", "self", ",", "buf", ",", "mode", ")", ":", "filename", "=", "b''", "for", "i", "in", "range", "(", "0", ",", "255", ")", ":", "c", "=", "Operators", ".", "CHR", "(", "self", ".", "current", ".", "read_int", "(", "buf", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_newuname
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
manticore/platforms/linux.py
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): return s + '\x00' * (65 - len(s)) now = datetime(2017, 8, 0o1).strftime("%a %b %d %H:%M:%S ART %Y") info = (('sysname', 'Linux'), ('nodename', 'ubuntu'), ('release', '4.4.0-77-generic'), ('version', '#98 SMP ' + now), ('machine', self._uname_machine), ('domainname', '')) uname_buf = ''.join(pad(pair[1]) for pair in info) self.current.write_bytes(old_utsname, uname_buf) return 0
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): return s + '\x00' * (65 - len(s)) now = datetime(2017, 8, 0o1).strftime("%a %b %d %H:%M:%S ART %Y") info = (('sysname', 'Linux'), ('nodename', 'ubuntu'), ('release', '4.4.0-77-generic'), ('version', '#98 SMP ' + now), ('machine', self._uname_machine), ('domainname', '')) uname_buf = ''.join(pad(pair[1]) for pair in info) self.current.write_bytes(old_utsname, uname_buf) return 0
[ "Writes", "system", "information", "in", "the", "variable", "C", "{", "old_utsname", "}", ".", ":", "rtype", ":", "int", ":", "param", "old_utsname", ":", "the", "buffer", "to", "write", "the", "system", "info", ".", ":", "return", ":", "C", "{", "0", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1360-L1382
[ "def", "sys_newuname", "(", "self", ",", "old_utsname", ")", ":", "from", "datetime", "import", "datetime", "def", "pad", "(", "s", ")", ":", "return", "s", "+", "'\\x00'", "*", "(", "65", "-", "len", "(", "s", ")", ")", "now", "=", "datetime", "("...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_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 memory
manticore/platforms/linux.py
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 memory """ if brk != 0 and brk > self.elf_brk: mem = self.current.memory size = brk - self.brk if brk > mem._ceil(self.brk): perms = mem.perms(self.brk - 1) addr = mem.mmap(mem._ceil(self.brk), size, perms) if not mem._ceil(self.brk) == addr: logger.error(f"Error in brk: ceil: {hex(mem._ceil(self.brk))} brk: {hex(brk)} self.brk: {hex(self.brk)} addr: {hex(addr)}") return self.brk self.brk += size return self.brk
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 memory """ if brk != 0 and brk > self.elf_brk: mem = self.current.memory size = brk - self.brk if brk > mem._ceil(self.brk): perms = mem.perms(self.brk - 1) addr = mem.mmap(mem._ceil(self.brk), size, perms) if not mem._ceil(self.brk) == addr: logger.error(f"Error in brk: ceil: {hex(mem._ceil(self.brk))} brk: {hex(brk)} self.brk: {hex(self.brk)} addr: {hex(addr)}") return self.brk self.brk += size return 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", ":"...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1384-L1403
[ "def", "sys_brk", "(", "self", ",", "brk", ")", ":", "if", "brk", "!=", "0", "and", "brk", ">", "self", ".", "elf_brk", ":", "mem", "=", "self", ".", "current", ".", "memory", "size", "=", "brk", "-", "self", ".", "brk", "if", "brk", ">", "mem"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_arch_prctl
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{ARCH_SET_FS}
manticore/platforms/linux.py
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{ARCH_SET_FS} """ ARCH_SET_GS = 0x1001 ARCH_SET_FS = 0x1002 ARCH_GET_FS = 0x1003 ARCH_GET_GS = 0x1004 if code not in {ARCH_SET_GS, ARCH_SET_FS, ARCH_GET_FS, ARCH_GET_GS}: logger.debug("code not in expected options ARCH_GET/SET_FS/GS") return -errno.EINVAL if code != ARCH_SET_FS: raise NotImplementedError("Manticore supports only arch_prctl with code=ARCH_SET_FS (0x1002) for now") self.current.FS = 0x63 self.current.set_descriptor(self.current.FS, addr, 0x4000, 'rw') return 0
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{ARCH_SET_FS} """ ARCH_SET_GS = 0x1001 ARCH_SET_FS = 0x1002 ARCH_GET_FS = 0x1003 ARCH_GET_GS = 0x1004 if code not in {ARCH_SET_GS, ARCH_SET_FS, ARCH_GET_FS, ARCH_GET_GS}: logger.debug("code not in expected options ARCH_GET/SET_FS/GS") return -errno.EINVAL if code != ARCH_SET_FS: raise NotImplementedError("Manticore supports only arch_prctl with code=ARCH_SET_FS (0x1002) for now") self.current.FS = 0x63 self.current.set_descriptor(self.current.FS, addr, 0x4000, 'rw') return 0
[ "Sets", "architecture", "-", "specific", "thread", "state", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1405-L1427
[ "def", "sys_arch_prctl", "(", "self", ",", "code", ",", "addr", ")", ":", "ARCH_SET_GS", "=", "0x1001", "ARCH_SET_FS", "=", "0x1002", "ARCH_GET_FS", "=", "0x1003", "ARCH_GET_GS", "=", "0x1004", "if", "code", "not", "in", "{", "ARCH_SET_GS", ",", "ARCH_SET_FS...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_open
:param buf: address of zero-terminated pathname :param flags: file access bits :param mode: file permission mode
manticore/platforms/linux.py
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) logger.debug(f"Opening file {filename} for real fd {f.fileno()}") except IOError as e: logger.warning(f"Could not open file {filename}. Reason: {e!s}") return -e.errno if e.errno is not None else -errno.EINVAL return self._open(f)
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) logger.debug(f"Opening file {filename} for real fd {f.fileno()}") except IOError as e: logger.warning(f"Could not open file {filename}. Reason: {e!s}") return -e.errno if e.errno is not None else -errno.EINVAL return self._open(f)
[ ":", "param", "buf", ":", "address", "of", "zero", "-", "terminated", "pathname", ":", "param", "flags", ":", "file", "access", "bits", ":", "param", "mode", ":", "file", "permission", "mode" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1450-L1464
[ "def", "sys_open", "(", "self", ",", "buf", ",", "flags", ",", "mode", ")", ":", "filename", "=", "self", ".", "current", ".", "read_string", "(", "buf", ")", "try", ":", "f", "=", "self", ".", "_sys_open_get_file", "(", "filename", ",", "flags", ")"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_openat
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 :param dirfd: directory file descriptor to refer in case of relative path at buf :param buf: address of zero-terminated pathname :param flags: file access bits :param mode: file permission mode
manticore/platforms/linux.py
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 :param dirfd: directory file descriptor to refer in case of relative path at buf :param buf: address of zero-terminated pathname :param flags: file access bits :param mode: file permission mode """ filename = self.current.read_string(buf) dirfd = ctypes.c_int32(dirfd).value if os.path.isabs(filename) or dirfd == self.FCNTL_FDCWD: return self.sys_open(buf, flags, mode) try: dir_entry = self._get_fd(dirfd) except FdError as e: logger.info("openat: Not valid file descriptor. Returning EBADF") return -e.err if not isinstance(dir_entry, Directory): logger.info("openat: Not directory descriptor. Returning ENOTDIR") return -errno.ENOTDIR dir_path = dir_entry.name filename = os.path.join(dir_path, filename) try: f = self._sys_open_get_file(filename, flags) logger.debug(f"Opening file {filename} for real fd {f.fileno()}") except IOError as e: logger.info(f"Could not open file {filename}. Reason: {e!s}") return -e.errno if e.errno is not None else -errno.EINVAL return self._open(f)
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 :param dirfd: directory file descriptor to refer in case of relative path at buf :param buf: address of zero-terminated pathname :param flags: file access bits :param mode: file permission mode """ filename = self.current.read_string(buf) dirfd = ctypes.c_int32(dirfd).value if os.path.isabs(filename) or dirfd == self.FCNTL_FDCWD: return self.sys_open(buf, flags, mode) try: dir_entry = self._get_fd(dirfd) except FdError as e: logger.info("openat: Not valid file descriptor. Returning EBADF") return -e.err if not isinstance(dir_entry, Directory): logger.info("openat: Not directory descriptor. Returning ENOTDIR") return -errno.ENOTDIR dir_path = dir_entry.name filename = os.path.join(dir_path, filename) try: f = self._sys_open_get_file(filename, flags) logger.debug(f"Opening file {filename} for real fd {f.fileno()}") except IOError as e: logger.info(f"Could not open file {filename}. Reason: {e!s}") return -e.errno if e.errno is not None else -errno.EINVAL return self._open(f)
[ "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"...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1466-L1504
[ "def", "sys_openat", "(", "self", ",", "dirfd", ",", "buf", ",", "flags", ",", "mode", ")", ":", "filename", "=", "self", ".", "current", ".", "read_string", "(", "buf", ")", "dirfd", "=", "ctypes", ".", "c_int32", "(", "dirfd", ")", ".", "value", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_rename
Rename filename `oldnamep` to `newnamep`. :param int oldnamep: pointer to oldname :param int newnamep: pointer to newname
manticore/platforms/linux.py
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) ret = 0 try: os.rename(oldname, newname) except OSError as e: ret = -e.errno return ret
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) ret = 0 try: os.rename(oldname, newname) except OSError as e: ret = -e.errno return ret
[ "Rename", "filename", "oldnamep", "to", "newnamep", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1506-L1522
[ "def", "sys_rename", "(", "self", ",", "oldnamep", ",", "newnamep", ")", ":", "oldname", "=", "self", ".", "current", ".", "read_string", "(", "oldnamep", ")", "newname", "=", "self", ".", "current", ".", "read_string", "(", "newnamep", ")", "ret", "=", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_fsync
Synchronize a file's in-core state with that on disk.
manticore/platforms/linux.py
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
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
[ "Synchronize", "a", "file", "s", "in", "-", "core", "state", "with", "that", "on", "disk", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1524-L1537
[ "def", "sys_fsync", "(", "self", ",", "fd", ")", ":", "ret", "=", "0", "try", ":", "self", ".", "files", "[", "fd", "]", ".", "sync", "(", ")", "except", "IndexError", ":", "ret", "=", "-", "errno", ".", "EBADF", "except", "FdError", ":", "ret", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_rt_sigaction
Wrapper for sys_sigaction
manticore/platforms/linux.py
def sys_rt_sigaction(self, signum, act, oldact): """Wrapper for sys_sigaction""" return self.sys_sigaction(signum, act, oldact)
def sys_rt_sigaction(self, signum, act, oldact): """Wrapper for sys_sigaction""" return self.sys_sigaction(signum, act, oldact)
[ "Wrapper", "for", "sys_sigaction" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1558-L1560
[ "def", "sys_rt_sigaction", "(", "self", ",", "signum", ",", "act", ",", "oldact", ")", ":", "return", "self", ".", "sys_sigaction", "(", "signum", ",", "act", ",", "oldact", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_rt_sigprocmask
Wrapper for sys_sigprocmask
manticore/platforms/linux.py
def sys_rt_sigprocmask(self, cpu, how, newset, oldset): """Wrapper for sys_sigprocmask""" return self.sys_sigprocmask(cpu, how, newset, oldset)
def sys_rt_sigprocmask(self, cpu, how, newset, oldset): """Wrapper for sys_sigprocmask""" return self.sys_sigprocmask(cpu, how, newset, oldset)
[ "Wrapper", "for", "sys_sigprocmask" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1566-L1568
[ "def", "sys_rt_sigprocmask", "(", "self", ",", "cpu", ",", "how", ",", "newset", ",", "oldset", ")", ":", "return", "self", ".", "sys_sigprocmask", "(", "cpu", ",", "how", ",", "newset", ",", "oldset", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_dup
Duplicates an open file descriptor :rtype: int :param fd: the open file descriptor to duplicate. :return: the new file descriptor.
manticore/platforms/linux.py
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") return -errno.EBADF newfd = self._dup(fd) return newfd
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") return -errno.EBADF newfd = self._dup(fd) return newfd
[ "Duplicates", "an", "open", "file", "descriptor", ":", "rtype", ":", "int", ":", "param", "fd", ":", "the", "open", "file", "descriptor", "to", "duplicate", ".", ":", "return", ":", "the", "new", "file", "descriptor", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1574-L1587
[ "def", "sys_dup", "(", "self", ",", "fd", ")", ":", "if", "not", "self", ".", "_is_fd_open", "(", "fd", ")", ":", "logger", ".", "info", "(", "\"DUP: Passed fd is not open. Returning EBADF\"", ")", "return", "-", "errno", ".", "EBADF", "newfd", "=", "self"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_dup2
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.
manticore/platforms/linux.py
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. """ try: file = self._get_fd(fd) except FdError as e: logger.info("DUP2: Passed fd is not open. Returning EBADF") return -e.err soft_max, hard_max = self._rlimits[self.RLIMIT_NOFILE] if newfd >= soft_max: logger.info("DUP2: newfd is above max descriptor table size") return -errno.EBADF if self._is_fd_open(newfd): self._close(newfd) if newfd >= len(self.files): self.files.extend([None] * (newfd + 1 - len(self.files))) self.files[newfd] = self.files[fd] logger.debug('sys_dup2(%d,%d) -> %d', fd, newfd, newfd) 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. """ try: file = self._get_fd(fd) except FdError as e: logger.info("DUP2: Passed fd is not open. Returning EBADF") return -e.err soft_max, hard_max = self._rlimits[self.RLIMIT_NOFILE] if newfd >= soft_max: logger.info("DUP2: newfd is above max descriptor table size") return -errno.EBADF if self._is_fd_open(newfd): self._close(newfd) if newfd >= len(self.files): self.files.extend([None] * (newfd + 1 - len(self.files))) self.files[newfd] = self.files[fd] logger.debug('sys_dup2(%d,%d) -> %d', fd, newfd, newfd) return 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", "...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1589-L1617
[ "def", "sys_dup2", "(", "self", ",", "fd", ",", "newfd", ")", ":", "try", ":", "file", "=", "self", ".", "_get_fd", "(", "fd", ")", "except", "FdError", "as", "e", ":", "logger", ".", "info", "(", "\"DUP2: Passed fd is not open. Returning EBADF\"", ")", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_chroot
An implementation of chroot that does perform some basic error checking, but does not actually chroot. :param path: Path to chroot
manticore/platforms/linux.py
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_string(path) if not os.path.exists(path_s): return -errno.ENOENT if not os.path.isdir(path_s): return -errno.ENOTDIR return -errno.EPERM
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_string(path) if not os.path.exists(path_s): return -errno.ENOENT if not os.path.isdir(path_s): return -errno.ENOTDIR return -errno.EPERM
[ "An", "implementation", "of", "chroot", "that", "does", "perform", "some", "basic", "error", "checking", "but", "does", "not", "actually", "chroot", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1619-L1636
[ "def", "sys_chroot", "(", "self", ",", "path", ")", ":", "if", "path", "not", "in", "self", ".", "current", ".", "memory", ":", "return", "-", "errno", ".", "EFAULT", "path_s", "=", "self", ".", "current", ".", "read_string", "(", "path", ")", "if", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_close
Closes a file descriptor :rtype: int :param fd: the file descriptor to close. :return: C{0} on success.
manticore/platforms/linux.py
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_close({fd})') return 0
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_close({fd})') return 0
[ "Closes", "a", "file", "descriptor", ":", "rtype", ":", "int", ":", "param", "fd", ":", "the", "file", "descriptor", "to", "close", ".", ":", "return", ":", "C", "{", "0", "}", "on", "success", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1638-L1650
[ "def", "sys_close", "(", "self", ",", "fd", ")", ":", "if", "self", ".", "_is_fd_open", "(", "fd", ")", ":", "self", ".", "_close", "(", "fd", ")", "else", ":", "return", "-", "errno", ".", "EBADF", "logger", ".", "debug", "(", "f'sys_close({fd})'", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_readlink
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 | EFAULT | EINTR | errno.EINVAL | EIO | ENOSPC | EPIPE
manticore/platforms/linux.py
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 | EFAULT | EINTR | errno.EINVAL | EIO | ENOSPC | EPIPE """ if bufsize <= 0: return -errno.EINVAL filename = self.current.read_string(path) if filename == '/proc/self/exe': data = os.path.abspath(self.program) else: data = os.readlink(filename)[:bufsize] self.current.write_bytes(buf, data) return len(data)
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 | EFAULT | EINTR | errno.EINVAL | EIO | ENOSPC | EPIPE """ if bufsize <= 0: return -errno.EINVAL filename = self.current.read_string(path) if filename == '/proc/self/exe': data = os.path.abspath(self.program) else: data = os.readlink(filename)[:bufsize] self.current.write_bytes(buf, data) return len(data)
[ "Read", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1652-L1670
[ "def", "sys_readlink", "(", "self", ",", "path", ",", "buf", ",", "bufsize", ")", ":", "if", "bufsize", "<=", "0", ":", "return", "-", "errno", ".", "EINVAL", "filename", "=", "self", ".", "current", ".", "read_string", "(", "path", ")", "if", "filen...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_mmap_pgoff
Wrapper for mmap2
manticore/platforms/linux.py
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset): """Wrapper for mmap2""" return self.sys_mmap2(address, size, prot, flags, fd, offset)
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset): """Wrapper for mmap2""" return self.sys_mmap2(address, size, prot, flags, fd, offset)
[ "Wrapper", "for", "mmap2" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1672-L1674
[ "def", "sys_mmap_pgoff", "(", "self", ",", "address", ",", "size", ",", "prot", ",", "flags", ",", "fd", ",", "offset", ")", ":", "return", "self", ".", "sys_mmap2", "(", "address", ",", "size", ",", "prot", ",", "flags", ",", "fd", ",", "offset", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_mmap
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 C{MAP_FIXED}. :param size: the length of the mapping. :param prot: the desired memory protection of the mapping. :param flags: determines whether updates to the mapping are visible to other processes mapping the same region, and whether updates are carried through to the underlying file. :param fd: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file referred to by the file descriptor C{fd}. :param offset: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file referred to by the file descriptor C{fd}. :return: - C{-1} in case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address. - the address of the new mapping (that must be the same as address in case you included C{MAP_FIXED} in flags). :todo: handle exception.
manticore/platforms/linux.py
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 C{MAP_FIXED}. :param size: the length of the mapping. :param prot: the desired memory protection of the mapping. :param flags: determines whether updates to the mapping are visible to other processes mapping the same region, and whether updates are carried through to the underlying file. :param fd: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file referred to by the file descriptor C{fd}. :param offset: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file referred to by the file descriptor C{fd}. :return: - C{-1} in case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address. - the address of the new mapping (that must be the same as address in case you included C{MAP_FIXED} in flags). :todo: handle exception. """ if address == 0: address = None cpu = self.current if flags & 0x10: cpu.memory.munmap(address, size) perms = perms_from_protflags(prot) if flags & 0x20: result = cpu.memory.mmap(address, size, perms) elif fd == 0: assert offset == 0 result = cpu.memory.mmap(address, size, perms) data = self.files[fd].read(size) cpu.write_bytes(result, data) else: # FIXME Check if file should be symbolic input and do as with fd0 result = cpu.memory.mmapFile(address, size, perms, self.files[fd].name, offset) actually_mapped = f'0x{result:016x}' if address is None or result != address: address = address or 0 actually_mapped += f' [requested: 0x{address:016x}]' if flags & 0x10 != 0 and result != address: cpu.memory.munmap(result, size) result = -1 return result
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 C{MAP_FIXED}. :param size: the length of the mapping. :param prot: the desired memory protection of the mapping. :param flags: determines whether updates to the mapping are visible to other processes mapping the same region, and whether updates are carried through to the underlying file. :param fd: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file referred to by the file descriptor C{fd}. :param offset: the contents of a file mapping are initialized using C{size} bytes starting at offset C{offset} in the file referred to by the file descriptor C{fd}. :return: - C{-1} in case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address. - the address of the new mapping (that must be the same as address in case you included C{MAP_FIXED} in flags). :todo: handle exception. """ if address == 0: address = None cpu = self.current if flags & 0x10: cpu.memory.munmap(address, size) perms = perms_from_protflags(prot) if flags & 0x20: result = cpu.memory.mmap(address, size, perms) elif fd == 0: assert offset == 0 result = cpu.memory.mmap(address, size, perms) data = self.files[fd].read(size) cpu.write_bytes(result, data) else: # FIXME Check if file should be symbolic input and do as with fd0 result = cpu.memory.mmapFile(address, size, perms, self.files[fd].name, offset) actually_mapped = f'0x{result:016x}' if address is None or result != address: address = address or 0 actually_mapped += f' [requested: 0x{address:016x}]' if flags & 0x10 != 0 and result != address: cpu.memory.munmap(result, size) result = -1 return result
[ "Creates", "a", "new", "mapping", "in", "the", "virtual", "address", "space", "of", "the", "calling", "process", ".", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1697-L1748
[ "def", "sys_mmap", "(", "self", ",", "address", ",", "size", ",", "prot", ",", "flags", ",", "fd", ",", "offset", ")", ":", "if", "address", "==", "0", ":", "address", "=", "None", "cpu", "=", "self", ".", "current", "if", "flags", "&", "0x10", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_mprotect
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 address to change the permissions. :param size: the size of the portion of memory to change the permissions. :param prot: the new access permission for the memory. :return: C{0} on success.
manticore/platforms/linux.py
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 address to change the permissions. :param size: the size of the portion of memory to change the permissions. :param prot: the new access permission for the memory. :return: C{0} on success. """ perms = perms_from_protflags(prot) ret = self.current.memory.mprotect(start, size, perms) return 0
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 address to change the permissions. :param size: the size of the portion of memory to change the permissions. :param prot: the new access permission for the memory. :return: C{0} on success. """ perms = perms_from_protflags(prot) ret = self.current.memory.mprotect(start, size, perms) return 0
[ "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", "[", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1750-L1763
[ "def", "sys_mprotect", "(", "self", ",", "start", ",", "size", ",", "prot", ")", ":", "perms", "=", "perms_from_protflags", "(", "prot", ")", "ret", "=", "self", ".", "current", ".", "memory", ".", "mprotect", "(", "start", ",", "size", ",", "perms", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_munmap
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.
manticore/platforms/linux.py
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. """ self.current.memory.munmap(addr, size) return 0
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. """ self.current.memory.munmap(addr, size) return 0
[ "Unmaps", "a", "file", "from", "memory", ".", "It", "deletes", "the", "mappings", "for", "the", "specified", "address", "range", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1765-L1775
[ "def", "sys_munmap", "(", "self", ",", "addr", ",", "size", ")", ":", "self", ".", "current", ".", "memory", ".", "munmap", "(", "addr", ",", "size", ")", "return", "0" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_readv
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{iov} buffers to read from the file. :return: the amount of bytes read in total.
manticore/platforms/linux.py
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{iov} buffers to read from the file. :return: the amount of bytes read in total. """ cpu = self.current ptrsize = cpu.address_bit_size sizeof_iovec = 2 * (ptrsize // 8) total = 0 for i in range(0, count): buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize) size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2), ptrsize) data = self.files[fd].read(size) total += len(data) cpu.write_bytes(buf, data) self.syscall_trace.append(("_read", fd, data)) return total
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{iov} buffers to read from the file. :return: the amount of bytes read in total. """ cpu = self.current ptrsize = cpu.address_bit_size sizeof_iovec = 2 * (ptrsize // 8) total = 0 for i in range(0, count): buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize) size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2), ptrsize) data = self.files[fd].read(size) total += len(data) cpu.write_bytes(buf, data) self.syscall_trace.append(("_read", fd, data)) return total
[ "Works", "just", "like", "C", "{", "sys_read", "}", "except", "that", "data", "is", "read", "into", "multiple", "buffers", ".", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1813-L1836
[ "def", "sys_readv", "(", "self", ",", "fd", ",", "iov", ",", "count", ")", ":", "cpu", "=", "self", ".", "current", "ptrsize", "=", "cpu", ".", "address_bit_size", "sizeof_iovec", "=", "2", "*", "(", "ptrsize", "//", "8", ")", "total", "=", "0", "f...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_writev
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{iov} buffers to write into the file. :return: the amount of bytes written in total.
manticore/platforms/linux.py
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{iov} buffers to write into the file. :return: the amount of bytes written in total. """ cpu = self.current ptrsize = cpu.address_bit_size sizeof_iovec = 2 * (ptrsize // 8) total = 0 try: write_fd = self._get_fd(fd) except FdError as e: logger.error(f"writev: Not a valid file descriptor ({fd})") return -e.err for i in range(0, count): buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize) size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2), ptrsize) data = [Operators.CHR(cpu.read_int(buf + i, 8)) for i in range(size)] data = self._transform_write_data(data) write_fd.write(data) self.syscall_trace.append(("_write", fd, data)) total += size return total
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{iov} buffers to write into the file. :return: the amount of bytes written in total. """ cpu = self.current ptrsize = cpu.address_bit_size sizeof_iovec = 2 * (ptrsize // 8) total = 0 try: write_fd = self._get_fd(fd) except FdError as e: logger.error(f"writev: Not a valid file descriptor ({fd})") return -e.err for i in range(0, count): buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize) size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2), ptrsize) data = [Operators.CHR(cpu.read_int(buf + i, 8)) for i in range(size)] data = self._transform_write_data(data) write_fd.write(data) self.syscall_trace.append(("_write", fd, data)) total += size return total
[ "Works", "just", "like", "C", "{", "sys_write", "}", "except", "that", "multiple", "buffers", "are", "written", "out", ".", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1838-L1867
[ "def", "sys_writev", "(", "self", ",", "fd", ",", "iov", ",", "count", ")", ":", "cpu", "=", "self", ".", "current", "ptrsize", "=", "cpu", ".", "address_bit_size", "sizeof_iovec", "=", "2", "*", "(", "ptrsize", "//", "8", ")", "total", "=", "0", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_set_thread_area
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.
manticore/platforms/linux.py
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. """ n = self.current.read_int(user_info, 32) pointer = self.current.read_int(user_info + 4, 32) m = self.current.read_int(user_info + 8, 32) flags = self.current.read_int(user_info + 12, 32) assert n == 0xffffffff assert flags == 0x51 # TODO: fix self.current.GS = 0x63 self.current.set_descriptor(self.current.GS, pointer, 0x4000, 'rw') self.current.write_int(user_info, (0x63 - 3) // 8, 32) return 0
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. """ n = self.current.read_int(user_info, 32) pointer = self.current.read_int(user_info + 4, 32) m = self.current.read_int(user_info + 8, 32) flags = self.current.read_int(user_info + 12, 32) assert n == 0xffffffff assert flags == 0x51 # TODO: fix self.current.GS = 0x63 self.current.set_descriptor(self.current.GS, pointer, 0x4000, 'rw') self.current.write_int(user_info, (0x63 - 3) // 8, 32) return 0
[ "Sets", "a", "thread", "local", "storage", "(", "TLS", ")", "area", ".", "Sets", "the", "base", "address", "of", "the", "GS", "segment", ".", ":", "rtype", ":", "int" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L1869-L1886
[ "def", "sys_set_thread_area", "(", "self", ",", "user_info", ")", ":", "n", "=", "self", ".", "current", ".", "read_int", "(", "user_info", ",", "32", ")", "pointer", "=", "self", ".", "current", ".", "read_int", "(", "user_info", "+", "4", ",", "32", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_getrandom
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 determinism over true randomness. :param buf: address of buffer to be filled with random bytes :param size: number of random bytes :param flags: source of random (/dev/random or /dev/urandom) :return: number of bytes copied to buf
manticore/platforms/linux.py
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 determinism over true randomness. :param buf: address of buffer to be filled with random bytes :param size: number of random bytes :param flags: source of random (/dev/random or /dev/urandom) :return: number of bytes copied to buf """ GRND_NONBLOCK = 0x0001 GRND_RANDOM = 0x0002 if size == 0: return 0 if buf not in self.current.memory: logger.info("getrandom: Provided an invalid address. Returning EFAULT") return -errno.EFAULT if flags & ~(GRND_NONBLOCK | GRND_RANDOM): return -errno.EINVAL self.current.write_bytes(buf, '\x00' * size) return size
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 determinism over true randomness. :param buf: address of buffer to be filled with random bytes :param size: number of random bytes :param flags: source of random (/dev/random or /dev/urandom) :return: number of bytes copied to buf """ GRND_NONBLOCK = 0x0001 GRND_RANDOM = 0x0002 if size == 0: return 0 if buf not in self.current.memory: logger.info("getrandom: Provided an invalid address. Returning EFAULT") return -errno.EFAULT if flags & ~(GRND_NONBLOCK | GRND_RANDOM): return -errno.EINVAL self.current.write_bytes(buf, '\x00' * size) return size
[ "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...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2090-L2120
[ "def", "sys_getrandom", "(", "self", ",", "buf", ",", "size", ",", "flags", ")", ":", "GRND_NONBLOCK", "=", "0x0001", "GRND_RANDOM", "=", "0x0002", "if", "size", "==", "0", ":", "return", "0", "if", "buf", "not", "in", "self", ".", "current", ".", "m...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.syscall
Syscall dispatcher.
manticore/platforms/linux.py
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 (AttributeError, KeyError): if name is not None: raise SyscallNotImplemented(index, name) else: raise Exception(f"Bad syscall index, {index}") return self._syscall_abi.invoke(implementation)
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 (AttributeError, KeyError): if name is not None: raise SyscallNotImplemented(index, name) else: raise Exception(f"Bad syscall index, {index}") return self._syscall_abi.invoke(implementation)
[ "Syscall", "dispatcher", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2123-L2140
[ "def", "syscall", "(", "self", ")", ":", "index", "=", "self", ".", "_syscall_abi", ".", "syscall_number", "(", ")", "try", ":", "table", "=", "getattr", "(", "linux_syscalls", ",", "self", ".", "current", ".", "machine", ")", "name", "=", "table", "."...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sched
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.
manticore/platforms/linux.py
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.debug(f"\tProcess: {self.procs!r}") logger.debug(f"\tRunning: {self.running!r}") logger.debug(f"\tRWait: {self.rwait!r}") logger.debug(f"\tTWait: {self.twait!r}") logger.debug(f"\tTimers: {self.timers!r}") logger.debug(f"\tCurrent clock: {self.clocks}") logger.debug(f"\tCurrent cpu: {self._current}") if len(self.running) == 0: logger.debug("None running checking if there is some process waiting for a timeout") if all([x is None for x in self.timers]): raise Deadlock() self.clocks = min(x for x in self.timers if x is not None) + 1 self.check_timers() assert len(self.running) != 0, "DEADLOCK!" self._current = self.running[0] return next_index = (self.running.index(self._current) + 1) % len(self.running) next_running_idx = self.running[next_index] if len(self.procs) > 1: logger.debug(f"\tTransfer control from process {self._current} to {next_running_idx}") self._current = next_running_idx
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.debug(f"\tProcess: {self.procs!r}") logger.debug(f"\tRunning: {self.running!r}") logger.debug(f"\tRWait: {self.rwait!r}") logger.debug(f"\tTWait: {self.twait!r}") logger.debug(f"\tTimers: {self.timers!r}") logger.debug(f"\tCurrent clock: {self.clocks}") logger.debug(f"\tCurrent cpu: {self._current}") if len(self.running) == 0: logger.debug("None running checking if there is some process waiting for a timeout") if all([x is None for x in self.timers]): raise Deadlock() self.clocks = min(x for x in self.timers if x is not None) + 1 self.check_timers() assert len(self.running) != 0, "DEADLOCK!" self._current = self.running[0] return next_index = (self.running.index(self._current) + 1) % len(self.running) next_running_idx = self.running[next_index] if len(self.procs) > 1: logger.debug(f"\tTransfer control from process {self._current} to {next_running_idx}") self._current = next_running_idx
[ "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", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2156-L2185
[ "def", "sched", "(", "self", ")", ":", "if", "len", "(", "self", ".", "procs", ")", ">", "1", ":", "logger", ".", "debug", "(", "\"SCHED:\"", ")", "logger", ".", "debug", "(", "f\"\\tProcess: {self.procs!r}\"", ")", "logger", ".", "debug", "(", "f\"\\t...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.wait
Wait for file descriptors or timeout. Adds the current process in the correspondent waiting list and yield the cpu to another running process.
manticore/platforms/linux.py
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 going to wait for [ {readfds!r} {writefds!r} {timeout!r} ]") logger.debug(f"\tProcess: {self.procs!r}") logger.debug(f"\tRunning: {self.running!r}") logger.debug(f"\tRWait: {self.rwait!r}") logger.debug(f"\tTWait: {self.twait!r}") logger.debug(f"\tTimers: {self.timers!r}") for fd in readfds: self.rwait[fd].add(self._current) for fd in writefds: self.twait[fd].add(self._current) if timeout is not None: self.timers[self._current] = self.clocks + timeout procid = self._current # self.sched() next_index = (self.running.index(procid) + 1) % len(self.running) self._current = self.running[next_index] logger.debug(f"\tTransfer control from process {procid} to {self._current}") logger.debug(f"\tREMOVING {procid!r} from {self.running!r}. Current: {self._current!r}") self.running.remove(procid) if self._current not in self.running: logger.debug("\tCurrent not running. Checking for timers...") self._current = None self.check_timers()
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 going to wait for [ {readfds!r} {writefds!r} {timeout!r} ]") logger.debug(f"\tProcess: {self.procs!r}") logger.debug(f"\tRunning: {self.running!r}") logger.debug(f"\tRWait: {self.rwait!r}") logger.debug(f"\tTWait: {self.twait!r}") logger.debug(f"\tTimers: {self.timers!r}") for fd in readfds: self.rwait[fd].add(self._current) for fd in writefds: self.twait[fd].add(self._current) if timeout is not None: self.timers[self._current] = self.clocks + timeout procid = self._current # self.sched() next_index = (self.running.index(procid) + 1) % len(self.running) self._current = self.running[next_index] logger.debug(f"\tTransfer control from process {procid} to {self._current}") logger.debug(f"\tREMOVING {procid!r} from {self.running!r}. Current: {self._current!r}") self.running.remove(procid) if self._current not in self.running: logger.debug("\tCurrent not running. Checking for timers...") self._current = None self.check_timers()
[ "Wait", "for", "file", "descriptors", "or", "timeout", ".", "Adds", "the", "current", "process", "in", "the", "correspondent", "waiting", "list", "and", "yield", "the", "cpu", "to", "another", "running", "process", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2187-L2216
[ "def", "wait", "(", "self", ",", "readfds", ",", "writefds", ",", "timeout", ")", ":", "logger", ".", "debug", "(", "\"WAIT:\"", ")", "logger", ".", "debug", "(", "f\"\\tProcess {self._current} is going to wait for [ {readfds!r} {writefds!r} {timeout!r} ]\"", ")", "lo...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.awake
Remove procid from waitlists and reestablish it in the running list
manticore/platforms/linux.py
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(procid) for wait_list in self.twait: if procid in wait_list: wait_list.remove(procid) self.timers[procid] = None self.running.append(procid) if self._current is None: self._current = procid
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(procid) for wait_list in self.twait: if procid in wait_list: wait_list.remove(procid) self.timers[procid] = None self.running.append(procid) if self._current is None: self._current = procid
[ "Remove", "procid", "from", "waitlists", "and", "reestablish", "it", "in", "the", "running", "list" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2218-L2230
[ "def", "awake", "(", "self", ",", "procid", ")", ":", "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", ":", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.signal_receive
Awake one process waiting to receive data on fd
manticore/platforms/linux.py
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)
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", "receive", "data", "on", "fd" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2244-L2249
[ "def", "signal_receive", "(", "self", ",", "fd", ")", ":", "connections", "=", "self", ".", "connections", "if", "connections", "(", "fd", ")", "and", "self", ".", "twait", "[", "connections", "(", "fd", ")", "]", ":", "procid", "=", "random", ".", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.signal_transmit
Awake one process waiting to transmit data on fd
manticore/platforms/linux.py
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, 1)[0] self.awake(procid)
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, 1)[0] self.awake(procid)
[ "Awake", "one", "process", "waiting", "to", "transmit", "data", "on", "fd" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2251-L2260
[ "def", "signal_transmit", "(", "self", ",", "fd", ")", ":", "connection", "=", "self", ".", "connections", "(", "fd", ")", "if", "connection", "is", "None", "or", "connection", ">=", "len", "(", "self", ".", "rwait", ")", ":", "return", "procs", "=", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.check_timers
Awake process if timer has expired
manticore/platforms/linux.py
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 {advance}") self.clocks = advance for procid in range(len(self.timers)): if self.timers[procid] is not None: if self.clocks > self.timers[procid]: self.procs[procid].PC += self.procs[procid].instruction.size self.awake(procid)
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 {advance}") self.clocks = advance for procid in range(len(self.timers)): if self.timers[procid] is not None: if self.clocks > self.timers[procid]: self.procs[procid].PC += self.procs[procid].instruction.size self.awake(procid)
[ "Awake", "process", "if", "timer", "has", "expired" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2262-L2273
[ "def", "check_timers", "(", "self", ")", ":", "if", "self", ".", "_current", "is", "None", ":", "# Advance the clocks. Go to future!!", "advance", "=", "min", "(", "[", "self", ".", "clocks", "]", "+", "[", "x", "for", "x", "in", "self", ".", "timers", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.execute
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.
manticore/platforms/linux.py
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 if self.clocks % 10000 == 0: self.check_timers() self.sched() except (Interruption, Syscall) as e: try: self.syscall() if hasattr(e, 'on_handled'): e.on_handled() except RestartSyscall: pass return 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 if self.clocks % 10000 == 0: self.check_timers() self.sched() except (Interruption, Syscall) as e: try: self.syscall() if hasattr(e, 'on_handled'): e.on_handled() except RestartSyscall: pass return True
[ "Execute", "one", "cpu", "instruction", "in", "the", "current", "thread", "(", "only", "one", "supported", ")", ".", ":", "rtype", ":", "bool", ":", "return", ":", "C", "{", "True", "}" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2275-L2297
[ "def", "execute", "(", "self", ")", ":", "try", ":", "self", ".", "current", ".", "execute", "(", ")", "self", ".", "clocks", "+=", "1", "if", "self", ".", "clocks", "%", "10000", "==", "0", ":", "self", ".", "check_timers", "(", ")", "self", "."...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux.sys_fstat64
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.
manticore/platforms/linux.py
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: C{0} on success, EBADF when called with bad fd :todo: Fix device number. """ try: stat = self._get_fd(fd).stat() except FdError as e: logger.info("Calling fstat with invalid fd, returning EBADF") return -e.err def add(width, val): fformat = {2: 'H', 4: 'L', 8: 'Q'}[width] return struct.pack('<' + fformat, val) def to_timespec(ts): return struct.pack('<LL', int(ts), int(ts % 1 * 1e9)) bufstat = add(8, stat.st_dev) # unsigned long long st_dev; bufstat += add(8, stat.st_ino) # unsigned long long __st_ino; bufstat += add(4, stat.st_mode) # unsigned int st_mode; bufstat += add(4, stat.st_nlink) # unsigned int st_nlink; bufstat += add(4, stat.st_uid) # unsigned long st_uid; bufstat += add(4, stat.st_gid) # unsigned long st_gid; bufstat += add(8, stat.st_rdev) # unsigned long long st_rdev; bufstat += add(8, 0) # unsigned long long __pad1; bufstat += add(8, stat.st_size) # long long st_size; bufstat += add(4, stat.st_blksize) # int st_blksize; bufstat += add(4, 0) # int __pad2; bufstat += add(8, stat.st_blocks) # unsigned long long st_blocks; bufstat += to_timespec(stat.st_atime) # unsigned long st_atime; bufstat += to_timespec(stat.st_mtime) # unsigned long st_mtime; bufstat += to_timespec(stat.st_ctime) # unsigned long st_ctime; bufstat += add(4, 0) # unsigned int __unused4; bufstat += add(4, 0) # unsigned int __unused5; self.current.write_bytes(buf, bufstat) return 0
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: C{0} on success, EBADF when called with bad fd :todo: Fix device number. """ try: stat = self._get_fd(fd).stat() except FdError as e: logger.info("Calling fstat with invalid fd, returning EBADF") return -e.err def add(width, val): fformat = {2: 'H', 4: 'L', 8: 'Q'}[width] return struct.pack('<' + fformat, val) def to_timespec(ts): return struct.pack('<LL', int(ts), int(ts % 1 * 1e9)) bufstat = add(8, stat.st_dev) # unsigned long long st_dev; bufstat += add(8, stat.st_ino) # unsigned long long __st_ino; bufstat += add(4, stat.st_mode) # unsigned int st_mode; bufstat += add(4, stat.st_nlink) # unsigned int st_nlink; bufstat += add(4, stat.st_uid) # unsigned long st_uid; bufstat += add(4, stat.st_gid) # unsigned long st_gid; bufstat += add(8, stat.st_rdev) # unsigned long long st_rdev; bufstat += add(8, 0) # unsigned long long __pad1; bufstat += add(8, stat.st_size) # long long st_size; bufstat += add(4, stat.st_blksize) # int st_blksize; bufstat += add(4, 0) # int __pad2; bufstat += add(8, stat.st_blocks) # unsigned long long st_blocks; bufstat += to_timespec(stat.st_atime) # unsigned long st_atime; bufstat += to_timespec(stat.st_mtime) # unsigned long st_mtime; bufstat += to_timespec(stat.st_ctime) # unsigned long st_ctime; bufstat += add(4, 0) # unsigned int __unused4; bufstat += add(4, 0) # unsigned int __unused5; self.current.write_bytes(buf, bufstat) return 0
[ "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...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2388-L2430
[ "def", "sys_fstat64", "(", "self", ",", "fd", ",", "buf", ")", ":", "try", ":", "stat", "=", "self", ".", "_get_fd", "(", "fd", ")", ".", "stat", "(", ")", "except", "FdError", "as", "e", ":", "logger", ".", "info", "(", "\"Calling fstat with invalid...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Linux._interp_total_size
Compute total load size of interpreter. :param ELFFile interp: interpreter ELF .so :return: total load size of interpreter, not aligned :rtype: int
manticore/platforms/linux.py
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_LOAD'] last = load_segs[-1] return last.header.p_vaddr + last.header.p_memsz
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_LOAD'] last = load_segs[-1] return last.header.p_vaddr + last.header.p_memsz
[ "Compute", "total", "load", "size", "of", "interpreter", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2480-L2490
[ "def", "_interp_total_size", "(", "interp", ")", ":", "load_segs", "=", "[", "x", "for", "x", "in", "interp", ".", "iter_segments", "(", ")", "if", "x", ".", "header", ".", "p_type", "==", "'PT_LOAD'", "]", "last", "=", "load_segs", "[", "-", "1", "]...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SLinux.sys_open
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-terminated pathname :param flags: file access bits :param mode: file permission mode
manticore/platforms/linux.py
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-terminated pathname :param flags: file access bits :param mode: file permission mode """ offset = 0 symbolic_path = issymbolic(self.current.read_int(buf, 8)) if symbolic_path: import tempfile fd, path = tempfile.mkstemp() with open(path, 'wb+') as f: f.write('+' * 64) self.symbolic_files.append(path) buf = self.current.memory.mmap(None, 1024, 'rw ', data_init=path) rv = super().sys_open(buf, flags, mode) if symbolic_path: self.current.memory.munmap(buf, 1024) return rv
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-terminated pathname :param flags: file access bits :param mode: file permission mode """ offset = 0 symbolic_path = issymbolic(self.current.read_int(buf, 8)) if symbolic_path: import tempfile fd, path = tempfile.mkstemp() with open(path, 'wb+') as f: f.write('+' * 64) self.symbolic_files.append(path) buf = self.current.memory.mmap(None, 1024, 'rw ', data_init=path) rv = super().sys_open(buf, flags, mode) if symbolic_path: self.current.memory.munmap(buf, 1024) return rv
[ "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", "symb...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2663-L2688
[ "def", "sys_open", "(", "self", ",", "buf", ",", "flags", ",", "mode", ")", ":", "offset", "=", "0", "symbolic_path", "=", "issymbolic", "(", "self", ".", "current", ".", "read_int", "(", "buf", ",", "8", ")", ")", "if", "symbolic_path", ":", "import...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SLinux.sys_openat
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: file permission mode
manticore/platforms/linux.py
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: file permission mode """ if issymbolic(dirfd): logger.debug("Ask to read from a symbolic directory file descriptor!!") # Constrain to a valid fd and one past the end of fds self.constraints.add(dirfd >= 0) self.constraints.add(dirfd <= len(self.files)) raise ConcretizeArgument(self, 0) if issymbolic(buf): logger.debug("Ask to read to a symbolic buffer") raise ConcretizeArgument(self, 1) return super().sys_openat(dirfd, buf, flags, mode)
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: file permission mode """ if issymbolic(dirfd): logger.debug("Ask to read from a symbolic directory file descriptor!!") # Constrain to a valid fd and one past the end of fds self.constraints.add(dirfd >= 0) self.constraints.add(dirfd <= len(self.files)) raise ConcretizeArgument(self, 0) if issymbolic(buf): logger.debug("Ask to read to a symbolic buffer") raise ConcretizeArgument(self, 1) return super().sys_openat(dirfd, buf, flags, mode)
[ "A", "version", "of", "openat", "that", "includes", "a", "symbolic", "path", "and", "symbolic", "directory", "file", "descriptor" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2690-L2711
[ "def", "sys_openat", "(", "self", ",", "dirfd", ",", "buf", ",", "flags", ",", "mode", ")", ":", "if", "issymbolic", "(", "dirfd", ")", ":", "logger", ".", "debug", "(", "\"Ask to read from a symbolic directory file descriptor!!\"", ")", "# Constrain to a valid fd...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SLinux.sys_getrandom
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: number of random bytes :param flags: source of random (/dev/random or /dev/urandom) :return: number of bytes copied to buf
manticore/platforms/linux.py
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: number of random bytes :param flags: source of random (/dev/random or /dev/urandom) :return: number of bytes copied to buf """ if issymbolic(buf): logger.debug("sys_getrandom: Asked to generate random to a symbolic buffer address") raise ConcretizeArgument(self, 0) if issymbolic(size): logger.debug("sys_getrandom: Asked to generate random of symbolic number of bytes") raise ConcretizeArgument(self, 1) if issymbolic(flags): logger.debug("sys_getrandom: Passed symbolic flags") raise ConcretizeArgument(self, 2) return super().sys_getrandom(buf, size, flags)
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: number of random bytes :param flags: source of random (/dev/random or /dev/urandom) :return: number of bytes copied to buf """ if issymbolic(buf): logger.debug("sys_getrandom: Asked to generate random to a symbolic buffer address") raise ConcretizeArgument(self, 0) if issymbolic(size): logger.debug("sys_getrandom: Asked to generate random of symbolic number of bytes") raise ConcretizeArgument(self, 1) if issymbolic(flags): logger.debug("sys_getrandom: Passed symbolic flags") raise ConcretizeArgument(self, 2) return super().sys_getrandom(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...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2713-L2736
[ "def", "sys_getrandom", "(", "self", ",", "buf", ",", "size", ",", "flags", ")", ":", "if", "issymbolic", "(", "buf", ")", ":", "logger", ".", "debug", "(", "\"sys_getrandom: Asked to generate random to a symbolic buffer address\"", ")", "raise", "ConcretizeArgument...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree._read_string
Reads a null terminated concrete buffer form memory :todo: FIX. move to cpu or memory
manticore/platforms/decree.py
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 filename += c return filename
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 filename += c return filename
[ "Reads", "a", "null", "terminated", "concrete", "buffer", "form", "memory", ":", "todo", ":", "FIX", ".", "move", "to", "cpu", "or", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L224-L235
[ "def", "_read_string", "(", "self", ",", "cpu", ",", "buf", ")", ":", "filename", "=", "\"\"", "for", "i", "in", "range", "(", "0", ",", "1024", ")", ":", "c", "=", "Operators", ".", "CHR", "(", "cpu", ".", "read_int", "(", "buf", "+", "i", ","...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.load
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.
manticore/platforms/decree.py
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 def CGC_PAGESTART(_v): return ((_v) & ~ (CGC_MIN_ALIGN - 1)) def CGC_PAGEOFFSET(_v): return ((_v) & (CGC_MIN_ALIGN - 1)) def CGC_PAGEALIGN(_v): return (((_v) + CGC_MIN_ALIGN - 1) & ~(CGC_MIN_ALIGN - 1)) def BAD_ADDR(x): return ((x) >= TASK_SIZE) # load elf See https://github.com/CyberdyneNYC/linux-source-3.13.2-cgc/blob/master/fs/binfmt_cgc.c # read the ELF object file cgc = CGCElf(filename) logger.info("Loading %s as a %s elf" % (filename, cgc.arch)) # make cpu and memory (Only 1 thread in Decree) cpu = self._mk_proc() bss = brk = 0 start_code = 0xffffffff end_code = start_data = end_data = 0 for (vaddr, memsz, perms, name, offset, filesz) in cgc.maps(): if vaddr < start_code: start_code = vaddr if start_data < vaddr: start_data = vaddr if vaddr > TASK_SIZE or filesz > memsz or \ memsz > TASK_SIZE or TASK_SIZE - memsz < vaddr: raise Exception("Set_brk can never work. avoid overflows") # CGCMAP-- addr = None if filesz > 0: hint = CGC_PAGESTART(vaddr) size = CGC_PAGEALIGN(filesz + CGC_PAGEOFFSET(vaddr)) offset = CGC_PAGESTART(offset) addr = cpu.memory.mmapFile(hint, size, perms, name, offset) assert not BAD_ADDR(addr) lo = CGC_PAGEALIGN(vaddr + filesz) hi = CGC_PAGEALIGN(vaddr + memsz) else: # for 0 filesz, we have to include the first page as bss. lo = CGC_PAGESTART(vaddr + filesz) hi = CGC_PAGEALIGN(vaddr + memsz) # map anon pages for the rest (no prefault) if hi - lo > 0: zaddr = cpu.memory.mmap(lo, hi - lo, perms) assert not BAD_ADDR(zaddr) lo = vaddr + filesz hi = CGC_PAGEALIGN(vaddr + memsz) if hi - lo > 0: old_perms = cpu.memory.perms(lo) cpu.memory.mprotect(lo, hi - lo, 'rw') try: cpu.memory[lo:hi] = '\x00' * (hi - lo) except Exception as e: logger.debug("Exception zeroing main elf fractional pages: %s" % str(e)) cpu.memory.mprotect(lo, hi, old_perms) if addr is None: addr = zaddr assert addr is not None k = vaddr + filesz if k > bss: bss = k if 'x' in perms and end_code < k: end_code = k if end_data < k: end_data = k k = vaddr + memsz if k > brk: brk = k bss = brk stack_base = 0xbaaaaffc stack_size = 0x800000 stack = cpu.memory.mmap(0xbaaab000 - stack_size, stack_size, 'rwx') + stack_size - 4 assert (stack_base) in cpu.memory and (stack_base - stack_size + 4) in cpu.memory # Only one thread in Decree status, thread = next(cgc.threads()) assert status == 'Running' logger.info("Setting initial cpu state") # set initial CPU state cpu.write_register('EAX', 0x0) cpu.write_register('ECX', cpu.memory.mmap(CGC_PAGESTART(0x4347c000), CGC_PAGEALIGN(4096 + CGC_PAGEOFFSET(0x4347c000)), 'rwx')) cpu.write_register('EDX', 0x0) cpu.write_register('EBX', 0x0) cpu.write_register('ESP', stack) cpu.write_register('EBP', 0x0) cpu.write_register('ESI', 0x0) cpu.write_register('EDI', 0x0) cpu.write_register('EIP', thread['EIP']) cpu.write_register('RFLAGS', 0x202) cpu.write_register('CS', 0x0) cpu.write_register('SS', 0x0) cpu.write_register('DS', 0x0) cpu.write_register('ES', 0x0) cpu.write_register('FS', 0x0) cpu.write_register('GS', 0x0) cpu.memory.mmap(0x4347c000, 0x1000, 'r') # cpu.memory[0x4347c000:0x4347d000] = 'A' 0x1000 logger.info("Entry point: %016x", cpu.EIP) logger.info("Stack start: %016x", cpu.ESP) logger.info("Brk: %016x", brk) logger.info("Mappings:") for m in str(cpu.memory).split('\n'): logger.info(" %s", m) return [cpu]
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 def CGC_PAGESTART(_v): return ((_v) & ~ (CGC_MIN_ALIGN - 1)) def CGC_PAGEOFFSET(_v): return ((_v) & (CGC_MIN_ALIGN - 1)) def CGC_PAGEALIGN(_v): return (((_v) + CGC_MIN_ALIGN - 1) & ~(CGC_MIN_ALIGN - 1)) def BAD_ADDR(x): return ((x) >= TASK_SIZE) # load elf See https://github.com/CyberdyneNYC/linux-source-3.13.2-cgc/blob/master/fs/binfmt_cgc.c # read the ELF object file cgc = CGCElf(filename) logger.info("Loading %s as a %s elf" % (filename, cgc.arch)) # make cpu and memory (Only 1 thread in Decree) cpu = self._mk_proc() bss = brk = 0 start_code = 0xffffffff end_code = start_data = end_data = 0 for (vaddr, memsz, perms, name, offset, filesz) in cgc.maps(): if vaddr < start_code: start_code = vaddr if start_data < vaddr: start_data = vaddr if vaddr > TASK_SIZE or filesz > memsz or \ memsz > TASK_SIZE or TASK_SIZE - memsz < vaddr: raise Exception("Set_brk can never work. avoid overflows") # CGCMAP-- addr = None if filesz > 0: hint = CGC_PAGESTART(vaddr) size = CGC_PAGEALIGN(filesz + CGC_PAGEOFFSET(vaddr)) offset = CGC_PAGESTART(offset) addr = cpu.memory.mmapFile(hint, size, perms, name, offset) assert not BAD_ADDR(addr) lo = CGC_PAGEALIGN(vaddr + filesz) hi = CGC_PAGEALIGN(vaddr + memsz) else: # for 0 filesz, we have to include the first page as bss. lo = CGC_PAGESTART(vaddr + filesz) hi = CGC_PAGEALIGN(vaddr + memsz) # map anon pages for the rest (no prefault) if hi - lo > 0: zaddr = cpu.memory.mmap(lo, hi - lo, perms) assert not BAD_ADDR(zaddr) lo = vaddr + filesz hi = CGC_PAGEALIGN(vaddr + memsz) if hi - lo > 0: old_perms = cpu.memory.perms(lo) cpu.memory.mprotect(lo, hi - lo, 'rw') try: cpu.memory[lo:hi] = '\x00' * (hi - lo) except Exception as e: logger.debug("Exception zeroing main elf fractional pages: %s" % str(e)) cpu.memory.mprotect(lo, hi, old_perms) if addr is None: addr = zaddr assert addr is not None k = vaddr + filesz if k > bss: bss = k if 'x' in perms and end_code < k: end_code = k if end_data < k: end_data = k k = vaddr + memsz if k > brk: brk = k bss = brk stack_base = 0xbaaaaffc stack_size = 0x800000 stack = cpu.memory.mmap(0xbaaab000 - stack_size, stack_size, 'rwx') + stack_size - 4 assert (stack_base) in cpu.memory and (stack_base - stack_size + 4) in cpu.memory # Only one thread in Decree status, thread = next(cgc.threads()) assert status == 'Running' logger.info("Setting initial cpu state") # set initial CPU state cpu.write_register('EAX', 0x0) cpu.write_register('ECX', cpu.memory.mmap(CGC_PAGESTART(0x4347c000), CGC_PAGEALIGN(4096 + CGC_PAGEOFFSET(0x4347c000)), 'rwx')) cpu.write_register('EDX', 0x0) cpu.write_register('EBX', 0x0) cpu.write_register('ESP', stack) cpu.write_register('EBP', 0x0) cpu.write_register('ESI', 0x0) cpu.write_register('EDI', 0x0) cpu.write_register('EIP', thread['EIP']) cpu.write_register('RFLAGS', 0x202) cpu.write_register('CS', 0x0) cpu.write_register('SS', 0x0) cpu.write_register('DS', 0x0) cpu.write_register('ES', 0x0) cpu.write_register('FS', 0x0) cpu.write_register('GS', 0x0) cpu.memory.mmap(0x4347c000, 0x1000, 'r') # cpu.memory[0x4347c000:0x4347d000] = 'A' 0x1000 logger.info("Entry point: %016x", cpu.EIP) logger.info("Stack start: %016x", cpu.ESP) logger.info("Brk: %016x", brk) logger.info("Mappings:") for m in str(cpu.memory).split('\n'): logger.info(" %s", m) return [cpu]
[ "Loads", "a", "CGC", "-", "ELF", "program", "in", "memory", "and", "prepares", "the", "initial", "CPU", "state", "and", "the", "stack", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L237-L369
[ "def", "load", "(", "self", ",", "filename", ")", ":", "CGC_MIN_PAGE_SIZE", "=", "4096", "CGC_MIN_ALIGN", "=", "CGC_MIN_PAGE_SIZE", "TASK_SIZE", "=", "0x80000000", "def", "CGC_PAGESTART", "(", "_v", ")", ":", "return", "(", "(", "_v", ")", "&", "~", "(", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sys_allocate
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 rounded up to the hardware page size. The kernel chooses the address at which to create the allocation; the address of the new allocation is returned in *addr as the result of the call. All newly allocated memory is readable and writeable. In addition, the is_X argument is a boolean that allows newly allocated memory to be marked as executable (non-zero) or non-executable (zero). The allocate function is invoked through system call number 5. :param cpu: current CPU :param length: the length of the allocation in bytes :param isX: boolean that allows newly allocated memory to be marked as executable :param addr: the address of the new allocation is returned in *addr :return: On success, allocate returns zero and a pointer to the allocated area is returned in *addr. Otherwise, an error code is returned and *addr is undefined. EINVAL length is zero. EINVAL length is too large. EFAULT addr points to an invalid address. ENOMEM No memory is available or the process' maximum number of allocations would have been exceeded.
manticore/platforms/decree.py
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 rounded up to the hardware page size. The kernel chooses the address at which to create the allocation; the address of the new allocation is returned in *addr as the result of the call. All newly allocated memory is readable and writeable. In addition, the is_X argument is a boolean that allows newly allocated memory to be marked as executable (non-zero) or non-executable (zero). The allocate function is invoked through system call number 5. :param cpu: current CPU :param length: the length of the allocation in bytes :param isX: boolean that allows newly allocated memory to be marked as executable :param addr: the address of the new allocation is returned in *addr :return: On success, allocate returns zero and a pointer to the allocated area is returned in *addr. Otherwise, an error code is returned and *addr is undefined. EINVAL length is zero. EINVAL length is too large. EFAULT addr points to an invalid address. ENOMEM No memory is available or the process' maximum number of allocations would have been exceeded. """ # TODO: check 4 bytes from addr if addr not in cpu.memory: logger.info("ALLOCATE: addr points to invalid address. Returning EFAULT") return Decree.CGC_EFAULT perms = ['rw ', 'rwx'][bool(isX)] try: result = cpu.memory.mmap(None, length, perms) except Exception as e: logger.info("ALLOCATE exception %s. Returning ENOMEM %r", str(e), length) return Decree.CGC_ENOMEM cpu.write_int(addr, result, 32) logger.info("ALLOCATE(%d, %s, 0x%08x) -> 0x%08x" % (length, perms, addr, result)) self.syscall_trace.append(("_allocate", -1, length)) return 0
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 rounded up to the hardware page size. The kernel chooses the address at which to create the allocation; the address of the new allocation is returned in *addr as the result of the call. All newly allocated memory is readable and writeable. In addition, the is_X argument is a boolean that allows newly allocated memory to be marked as executable (non-zero) or non-executable (zero). The allocate function is invoked through system call number 5. :param cpu: current CPU :param length: the length of the allocation in bytes :param isX: boolean that allows newly allocated memory to be marked as executable :param addr: the address of the new allocation is returned in *addr :return: On success, allocate returns zero and a pointer to the allocated area is returned in *addr. Otherwise, an error code is returned and *addr is undefined. EINVAL length is zero. EINVAL length is too large. EFAULT addr points to an invalid address. ENOMEM No memory is available or the process' maximum number of allocations would have been exceeded. """ # TODO: check 4 bytes from addr if addr not in cpu.memory: logger.info("ALLOCATE: addr points to invalid address. Returning EFAULT") return Decree.CGC_EFAULT perms = ['rw ', 'rwx'][bool(isX)] try: result = cpu.memory.mmap(None, length, perms) except Exception as e: logger.info("ALLOCATE exception %s. Returning ENOMEM %r", str(e), length) return Decree.CGC_ENOMEM cpu.write_int(addr, result, 32) logger.info("ALLOCATE(%d, %s, 0x%08x) -> 0x%08x" % (length, perms, addr, result)) self.syscall_trace.append(("_allocate", -1, length)) return 0
[ "allocate", "-", "allocate", "virtual", "memory" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L401-L445
[ "def", "sys_allocate", "(", "self", ",", "cpu", ",", "length", ",", "isX", ",", "addr", ")", ":", "# TODO: check 4 bytes from addr", "if", "addr", "not", "in", "cpu", ".", "memory", ":", "logger", ".", "info", "(", "\"ALLOCATE: addr points to invalid address. Re...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sys_random
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 count is greater than SSIZE_MAX, the result is unspecified. :param cpu: current CPU :param buf: a memory buffer :param count: max number of bytes to receive :param rnd_bytes: if valid, points to the actual number of random bytes :return: 0 On success EINVAL count is invalid. EFAULT buf or rnd_bytes points to an invalid address.
manticore/platforms/decree.py
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 count is greater than SSIZE_MAX, the result is unspecified. :param cpu: current CPU :param buf: a memory buffer :param count: max number of bytes to receive :param rnd_bytes: if valid, points to the actual number of random bytes :return: 0 On success EINVAL count is invalid. EFAULT buf or rnd_bytes points to an invalid address. """ ret = 0 if count != 0: if count > Decree.CGC_SSIZE_MAX or count < 0: ret = Decree.CGC_EINVAL else: # TODO check count bytes from buf if buf not in cpu.memory or (buf + count) not in cpu.memory: logger.info("RANDOM: buf points to invalid address. Returning EFAULT") return Decree.CGC_EFAULT with open("/dev/urandom", "rb") as f: data = f.read(count) self.syscall_trace.append(("_random", -1, data)) cpu.write_bytes(buf, data) # TODO check 4 bytes from rx_bytes if rnd_bytes: if rnd_bytes not in cpu.memory: logger.info("RANDOM: Not valid rnd_bytes. Returning EFAULT") return Decree.CGC_EFAULT cpu.write_int(rnd_bytes, len(data), 32) logger.info("RANDOM(0x%08x, %d, 0x%08x) -> <%s>)" % (buf, count, rnd_bytes, repr(data[:10]))) return ret
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 count is greater than SSIZE_MAX, the result is unspecified. :param cpu: current CPU :param buf: a memory buffer :param count: max number of bytes to receive :param rnd_bytes: if valid, points to the actual number of random bytes :return: 0 On success EINVAL count is invalid. EFAULT buf or rnd_bytes points to an invalid address. """ ret = 0 if count != 0: if count > Decree.CGC_SSIZE_MAX or count < 0: ret = Decree.CGC_EINVAL else: # TODO check count bytes from buf if buf not in cpu.memory or (buf + count) not in cpu.memory: logger.info("RANDOM: buf points to invalid address. Returning EFAULT") return Decree.CGC_EFAULT with open("/dev/urandom", "rb") as f: data = f.read(count) self.syscall_trace.append(("_random", -1, data)) cpu.write_bytes(buf, data) # TODO check 4 bytes from rx_bytes if rnd_bytes: if rnd_bytes not in cpu.memory: logger.info("RANDOM: Not valid rnd_bytes. Returning EFAULT") return Decree.CGC_EFAULT cpu.write_int(rnd_bytes, len(data), 32) logger.info("RANDOM(0x%08x, %d, 0x%08x) -> <%s>)" % (buf, count, rnd_bytes, repr(data[:10]))) return ret
[ "random", "-", "fill", "a", "buffer", "with", "random", "data" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L447-L488
[ "def", "sys_random", "(", "self", ",", "cpu", ",", "buf", ",", "count", ",", "rnd_bytes", ")", ":", "ret", "=", "0", "if", "count", "!=", "0", ":", "if", "count", ">", "Decree", ".", "CGC_SSIZE_MAX", "or", "count", "<", "0", ":", "ret", "=", "Dec...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sys_receive
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 to zero. :param cpu: current CPU. :param fd: a valid file descriptor :param buf: a memory buffer :param count: max number of bytes to receive :param rx_bytes: if valid, points to the actual number of bytes received :return: 0 Success EBADF fd is not a valid file descriptor or is not open EFAULT buf or rx_bytes points to an invalid address.
manticore/platforms/decree.py
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 to zero. :param cpu: current CPU. :param fd: a valid file descriptor :param buf: a memory buffer :param count: max number of bytes to receive :param rx_bytes: if valid, points to the actual number of bytes received :return: 0 Success EBADF fd is not a valid file descriptor or is not open EFAULT buf or rx_bytes points to an invalid address. """ data = '' if count != 0: if not self._is_open(fd): logger.info("RECEIVE: Not valid file descriptor on receive. Returning EBADF") return Decree.CGC_EBADF # TODO check count bytes from buf if buf not in cpu.memory: # or not buf+count in cpu.memory: logger.info("RECEIVE: buf points to invalid address. Returning EFAULT") return Decree.CGC_EFAULT #import random #count = random.randint(1,count) if fd > 2 and self.files[fd].is_empty(): cpu.PC -= cpu.instruction.size self.wait([fd], [], None) raise RestartSyscall() # get some potential delay # if random.randint(5) == 0 and count > 1: # count = count/2 # Read the data and put it in memory data = self.files[fd].receive(count) self.syscall_trace.append(("_receive", fd, data)) cpu.write_bytes(buf, data) self.signal_receive(fd) # TODO check 4 bytes from rx_bytes if rx_bytes: if rx_bytes not in cpu.memory: logger.info("RECEIVE: Not valid file descriptor on receive. Returning EFAULT") return Decree.CGC_EFAULT cpu.write_int(rx_bytes, len(data), 32) logger.info("RECEIVE(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)" % (fd, buf, count, rx_bytes, repr(data)[:min(count, 10)], len(data))) return 0
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 to zero. :param cpu: current CPU. :param fd: a valid file descriptor :param buf: a memory buffer :param count: max number of bytes to receive :param rx_bytes: if valid, points to the actual number of bytes received :return: 0 Success EBADF fd is not a valid file descriptor or is not open EFAULT buf or rx_bytes points to an invalid address. """ data = '' if count != 0: if not self._is_open(fd): logger.info("RECEIVE: Not valid file descriptor on receive. Returning EBADF") return Decree.CGC_EBADF # TODO check count bytes from buf if buf not in cpu.memory: # or not buf+count in cpu.memory: logger.info("RECEIVE: buf points to invalid address. Returning EFAULT") return Decree.CGC_EFAULT #import random #count = random.randint(1,count) if fd > 2 and self.files[fd].is_empty(): cpu.PC -= cpu.instruction.size self.wait([fd], [], None) raise RestartSyscall() # get some potential delay # if random.randint(5) == 0 and count > 1: # count = count/2 # Read the data and put it in memory data = self.files[fd].receive(count) self.syscall_trace.append(("_receive", fd, data)) cpu.write_bytes(buf, data) self.signal_receive(fd) # TODO check 4 bytes from rx_bytes if rx_bytes: if rx_bytes not in cpu.memory: logger.info("RECEIVE: Not valid file descriptor on receive. Returning EFAULT") return Decree.CGC_EFAULT cpu.write_int(rx_bytes, len(data), 32) logger.info("RECEIVE(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)" % (fd, buf, count, rx_bytes, repr(data)[:min(count, 10)], len(data))) return 0
[ "receive", "-", "receive", "bytes", "from", "a", "file", "descriptor" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L490-L543
[ "def", "sys_receive", "(", "self", ",", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "rx_bytes", ")", ":", "data", "=", "''", "if", "count", "!=", "0", ":", "if", "not", "self", ".", "_is_open", "(", "fd", ")", ":", "logger", ".", "info", "...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sys_transmit
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. :param cpu current CPU :param fd a valid file descriptor :param buf a memory buffer :param count number of bytes to send :param tx_bytes if valid, points to the actual number of bytes transmitted :return: 0 Success EBADF fd is not a valid file descriptor or is not open. EFAULT buf or tx_bytes points to an invalid address.
manticore/platforms/decree.py
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_bytes to zero. :param cpu current CPU :param fd a valid file descriptor :param buf a memory buffer :param count number of bytes to send :param tx_bytes if valid, points to the actual number of bytes transmitted :return: 0 Success EBADF fd is not a valid file descriptor or is not open. EFAULT buf or tx_bytes points to an invalid address. """ data = [] if count != 0: if not self._is_open(fd): logger.error("TRANSMIT: Not valid file descriptor. Returning EBADFD %d", fd) return Decree.CGC_EBADF # TODO check count bytes from buf if buf not in cpu.memory or (buf + count) not in cpu.memory: logger.debug("TRANSMIT: buf points to invalid address. Rerurning EFAULT") return Decree.CGC_EFAULT if fd > 2 and self.files[fd].is_full(): cpu.PC -= cpu.instruction.size self.wait([], [fd], None) raise RestartSyscall() for i in range(0, count): value = Operators.CHR(cpu.read_int(buf + i, 8)) if not isinstance(value, str): logger.debug("TRANSMIT: Writing symbolic values to file %d", fd) #value = str(value) data.append(value) self.files[fd].transmit(data) logger.info("TRANSMIT(%d, 0x%08x, %d, 0x%08x) -> <%.24r>" % (fd, buf, count, tx_bytes, ''.join([str(x) for x in data]))) self.syscall_trace.append(("_transmit", fd, data)) self.signal_transmit(fd) # TODO check 4 bytes from tx_bytes if tx_bytes: if tx_bytes not in cpu.memory: logger.debug("TRANSMIT: Not valid tx_bytes pointer on transmit. Returning EFAULT") return Decree.CGC_EFAULT cpu.write_int(tx_bytes, len(data), 32) return 0
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_bytes to zero. :param cpu current CPU :param fd a valid file descriptor :param buf a memory buffer :param count number of bytes to send :param tx_bytes if valid, points to the actual number of bytes transmitted :return: 0 Success EBADF fd is not a valid file descriptor or is not open. EFAULT buf or tx_bytes points to an invalid address. """ data = [] if count != 0: if not self._is_open(fd): logger.error("TRANSMIT: Not valid file descriptor. Returning EBADFD %d", fd) return Decree.CGC_EBADF # TODO check count bytes from buf if buf not in cpu.memory or (buf + count) not in cpu.memory: logger.debug("TRANSMIT: buf points to invalid address. Rerurning EFAULT") return Decree.CGC_EFAULT if fd > 2 and self.files[fd].is_full(): cpu.PC -= cpu.instruction.size self.wait([], [fd], None) raise RestartSyscall() for i in range(0, count): value = Operators.CHR(cpu.read_int(buf + i, 8)) if not isinstance(value, str): logger.debug("TRANSMIT: Writing symbolic values to file %d", fd) #value = str(value) data.append(value) self.files[fd].transmit(data) logger.info("TRANSMIT(%d, 0x%08x, %d, 0x%08x) -> <%.24r>" % (fd, buf, count, tx_bytes, ''.join([str(x) for x in data]))) self.syscall_trace.append(("_transmit", fd, data)) self.signal_transmit(fd) # TODO check 4 bytes from tx_bytes if tx_bytes: if tx_bytes not in cpu.memory: logger.debug("TRANSMIT: Not valid tx_bytes pointer on transmit. Returning EFAULT") return Decree.CGC_EFAULT cpu.write_int(tx_bytes, len(data), 32) return 0
[ "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", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L545-L596
[ "def", "sys_transmit", "(", "self", ",", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "tx_bytes", ")", ":", "data", "=", "[", "]", "if", "count", "!=", "0", ":", "if", "not", "self", ".", "_is_open", "(", "fd", ")", ":", "logger", ".", "err...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sys_terminate
Exits all threads in a process :param cpu: current CPU. :raises Exception: 'Finished'
manticore/platforms/decree.py
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 there so we can report? if issymbolic(error_code): logger.info("TERMINATE PROC_%02d with symbolic exit code [%d,%d]", procid, solver.minmax(self.constraints, error_code)) else: logger.info("TERMINATE PROC_%02d %x", procid, error_code) if len(self.running) == 0: raise TerminateState(f'Process exited correctly. Code: {error_code}') return error_code
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 there so we can report? if issymbolic(error_code): logger.info("TERMINATE PROC_%02d with symbolic exit code [%d,%d]", procid, solver.minmax(self.constraints, error_code)) else: logger.info("TERMINATE PROC_%02d %x", procid, error_code) if len(self.running) == 0: raise TerminateState(f'Process exited correctly. Code: {error_code}') return error_code
[ "Exits", "all", "threads", "in", "a", "process", ":", "param", "cpu", ":", "current", "CPU", ".", ":", "raises", "Exception", ":", "Finished" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L598-L614
[ "def", "sys_terminate", "(", "self", ",", "cpu", ",", "error_code", ")", ":", "procid", "=", "self", ".", "procs", ".", "index", "(", "cpu", ")", "self", ".", "sched", "(", ")", "self", ".", "running", ".", "remove", "(", "procid", ")", "# self.procs...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sys_deallocate
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. The address addr must be a multiple of the page size. The length parameter specifies the size of the region to be deallocated in bytes. All pages containing a part of the indicated range are deallocated, and subsequent references will terminate the process. It is not an error if the indicated range does not contain any allocated pages. The deallocate function is invoked through system call number 6. :param cpu: current CPU :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return 0 On success EINVAL addr is not page aligned. EINVAL length is zero. EINVAL any part of the region being deallocated is outside the valid address range of the process. :param cpu: current CPU. :return: C{0} on success.
manticore/platforms/decree.py
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 automatically deallocated when the process is terminated. The address addr must be a multiple of the page size. The length parameter specifies the size of the region to be deallocated in bytes. All pages containing a part of the indicated range are deallocated, and subsequent references will terminate the process. It is not an error if the indicated range does not contain any allocated pages. The deallocate function is invoked through system call number 6. :param cpu: current CPU :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return 0 On success EINVAL addr is not page aligned. EINVAL length is zero. EINVAL any part of the region being deallocated is outside the valid address range of the process. :param cpu: current CPU. :return: C{0} on success. """ logger.info("DEALLOCATE(0x%08x, %d)" % (addr, size)) if addr & 0xfff != 0: logger.info("DEALLOCATE: addr is not page aligned") return Decree.CGC_EINVAL if size == 0: logger.info("DEALLOCATE:length is zero") return Decree.CGC_EINVAL # unlikely AND WRONG!!! # if addr > Decree.CGC_SSIZE_MAX or addr+size > Decree.CGC_SSIZE_MAX: # logger.info("DEALLOCATE: part of the region being deallocated is outside the valid address range of the process") # return Decree.CGC_EINVAL cpu.memory.munmap(addr, size) self.syscall_trace.append(("_deallocate", -1, size)) return 0
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 automatically deallocated when the process is terminated. The address addr must be a multiple of the page size. The length parameter specifies the size of the region to be deallocated in bytes. All pages containing a part of the indicated range are deallocated, and subsequent references will terminate the process. It is not an error if the indicated range does not contain any allocated pages. The deallocate function is invoked through system call number 6. :param cpu: current CPU :param addr: the starting address to unmap. :param size: the size of the portion to unmap. :return 0 On success EINVAL addr is not page aligned. EINVAL length is zero. EINVAL any part of the region being deallocated is outside the valid address range of the process. :param cpu: current CPU. :return: C{0} on success. """ logger.info("DEALLOCATE(0x%08x, %d)" % (addr, size)) if addr & 0xfff != 0: logger.info("DEALLOCATE: addr is not page aligned") return Decree.CGC_EINVAL if size == 0: logger.info("DEALLOCATE:length is zero") return Decree.CGC_EINVAL # unlikely AND WRONG!!! # if addr > Decree.CGC_SSIZE_MAX or addr+size > Decree.CGC_SSIZE_MAX: # logger.info("DEALLOCATE: part of the region being deallocated is outside the valid address range of the process") # return Decree.CGC_EINVAL cpu.memory.munmap(addr, size) self.syscall_trace.append(("_deallocate", -1, size)) return 0
[ "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", ...
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L616-L658
[ "def", "sys_deallocate", "(", "self", ",", "cpu", ",", "addr", ",", "size", ")", ":", "logger", ".", "info", "(", "\"DEALLOCATE(0x%08x, %d)\"", "%", "(", "addr", ",", "size", ")", ")", "if", "addr", "&", "0xfff", "!=", "0", ":", "logger", ".", "info"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sys_fdwait
fdwait - wait for file descriptors to become ready
manticore/platforms/decree.py
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.memory: # todo: size logger.info("FDWAIT: timeout is pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT if readyfds: if readyfds not in cpu.memory: logger.info("FDWAIT: readyfds pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT writefds_wait = set() writefds_ready = set() fds_bitsize = (nfds + 7) & ~7 if writefds: if writefds not in cpu.memory: logger.info("FDWAIT: writefds pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT bits = cpu.read_int(writefds, fds_bitsize) for fd in range(nfds): if (bits & 1 << fd): if self.files[fd].is_full(): writefds_wait.add(fd) else: writefds_ready.add(fd) readfds_wait = set() readfds_ready = set() if readfds: if readfds not in cpu.memory: logger.info("FDWAIT: readfds pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT bits = cpu.read_int(readfds, fds_bitsize) for fd in range(nfds): if (bits & 1 << fd): if self.files[fd].is_empty(): readfds_wait.add(fd) else: readfds_ready.add(fd) n = len(readfds_ready) + len(writefds_ready) if n == 0: # TODO FIX timeout symbolic if timeout != 0: seconds = cpu.read_int(timeout, 32) microseconds = cpu.read_int(timeout + 4, 32) logger.info("FDWAIT: waiting for read on fds: {%s} and write to: {%s} timeout: %d", repr( list(readfds_wait)), repr(list(writefds_wait)), microseconds + 1000 * seconds) to = microseconds + 1000 * seconds # no ready file, wait else: to = None logger.info("FDWAIT: waiting for read on fds: {%s} and write to: {%s} timeout: INDIFENITELY", repr(list(readfds_wait)), repr(list(writefds_wait))) cpu.PC -= cpu.instruction.size self.wait(readfds_wait, writefds_wait, to) raise RestartSyscall() # When coming back from a timeout remember # not to backtrack instruction and set EAX to 0! :( ugliness alert! if readfds: bits = 0 for fd in readfds_ready: bits |= 1 << fd for byte in range(0, nfds, 8): cpu.write_int(readfds, (bits >> byte) & 0xff, 8) if writefds: bits = 0 for fd in writefds_ready: bits |= 1 << fd for byte in range(0, nfds, 8): cpu.write_int(writefds, (bits >> byte) & 0xff, 8) logger.info("FDWAIT: continuing. Some file is ready Readyfds: %08x", readyfds) if readyfds: cpu.write_int(readyfds, n, 32) self.syscall_trace.append(("_fdwait", -1, None)) return 0
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.memory: # todo: size logger.info("FDWAIT: timeout is pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT if readyfds: if readyfds not in cpu.memory: logger.info("FDWAIT: readyfds pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT writefds_wait = set() writefds_ready = set() fds_bitsize = (nfds + 7) & ~7 if writefds: if writefds not in cpu.memory: logger.info("FDWAIT: writefds pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT bits = cpu.read_int(writefds, fds_bitsize) for fd in range(nfds): if (bits & 1 << fd): if self.files[fd].is_full(): writefds_wait.add(fd) else: writefds_ready.add(fd) readfds_wait = set() readfds_ready = set() if readfds: if readfds not in cpu.memory: logger.info("FDWAIT: readfds pointing to invalid memory. Returning EFAULT") return Decree.CGC_EFAULT bits = cpu.read_int(readfds, fds_bitsize) for fd in range(nfds): if (bits & 1 << fd): if self.files[fd].is_empty(): readfds_wait.add(fd) else: readfds_ready.add(fd) n = len(readfds_ready) + len(writefds_ready) if n == 0: # TODO FIX timeout symbolic if timeout != 0: seconds = cpu.read_int(timeout, 32) microseconds = cpu.read_int(timeout + 4, 32) logger.info("FDWAIT: waiting for read on fds: {%s} and write to: {%s} timeout: %d", repr( list(readfds_wait)), repr(list(writefds_wait)), microseconds + 1000 * seconds) to = microseconds + 1000 * seconds # no ready file, wait else: to = None logger.info("FDWAIT: waiting for read on fds: {%s} and write to: {%s} timeout: INDIFENITELY", repr(list(readfds_wait)), repr(list(writefds_wait))) cpu.PC -= cpu.instruction.size self.wait(readfds_wait, writefds_wait, to) raise RestartSyscall() # When coming back from a timeout remember # not to backtrack instruction and set EAX to 0! :( ugliness alert! if readfds: bits = 0 for fd in readfds_ready: bits |= 1 << fd for byte in range(0, nfds, 8): cpu.write_int(readfds, (bits >> byte) & 0xff, 8) if writefds: bits = 0 for fd in writefds_ready: bits |= 1 << fd for byte in range(0, nfds, 8): cpu.write_int(writefds, (bits >> byte) & 0xff, 8) logger.info("FDWAIT: continuing. Some file is ready Readyfds: %08x", readyfds) if readyfds: cpu.write_int(readyfds, n, 32) self.syscall_trace.append(("_fdwait", -1, None)) return 0
[ "fdwait", "-", "wait", "for", "file", "descriptors", "to", "become", "ready" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L660-L743
[ "def", "sys_fdwait", "(", "self", ",", "cpu", ",", "nfds", ",", "readfds", ",", "writefds", ",", "timeout", ",", "readyfds", ")", ":", "logger", ".", "debug", "(", "\"FDWAIT(%d, 0x%08x, 0x%08x, 0x%08x, 0x%08x)\"", "%", "(", "nfds", ",", "readfds", ",", "writ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.int80
32 bit dispatcher. :param cpu: current CPU. _terminate, transmit, receive, fdwait, allocate, deallocate and random
manticore/platforms/decree.py
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: self.sys_receive, 0x00000004: self.sys_fdwait, 0x00000005: self.sys_allocate, 0x00000006: self.sys_deallocate, 0x00000007: self.sys_random, } if cpu.EAX not in syscalls.keys(): raise TerminateState(f"32 bit DECREE system call number {cpu.EAX} Not Implemented") func = syscalls[cpu.EAX] logger.debug("SYSCALL32: %s (nargs: %d)", func.__name__, func.__code__.co_argcount) nargs = func.__code__.co_argcount args = [cpu, cpu.EBX, cpu.ECX, cpu.EDX, cpu.ESI, cpu.EDI, cpu.EBP] cpu.EAX = func(*args[:nargs - 1])
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: self.sys_receive, 0x00000004: self.sys_fdwait, 0x00000005: self.sys_allocate, 0x00000006: self.sys_deallocate, 0x00000007: self.sys_random, } if cpu.EAX not in syscalls.keys(): raise TerminateState(f"32 bit DECREE system call number {cpu.EAX} Not Implemented") func = syscalls[cpu.EAX] logger.debug("SYSCALL32: %s (nargs: %d)", func.__name__, func.__code__.co_argcount) nargs = func.__code__.co_argcount args = [cpu, cpu.EBX, cpu.ECX, cpu.EDX, cpu.ESI, cpu.EDI, cpu.EBP] cpu.EAX = func(*args[:nargs - 1])
[ "32", "bit", "dispatcher", ".", ":", "param", "cpu", ":", "current", "CPU", ".", "_terminate", "transmit", "receive", "fdwait", "allocate", "deallocate", "and", "random" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L745-L765
[ "def", "int80", "(", "self", ",", "cpu", ")", ":", "syscalls", "=", "{", "0x00000001", ":", "self", ".", "sys_terminate", ",", "0x00000002", ":", "self", ".", "sys_transmit", ",", "0x00000003", ":", "self", ".", "sys_receive", ",", "0x00000004", ":", "se...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.sched
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.
manticore/platforms/decree.py
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("\tProcess: %r", self.procs) logger.info("\tRunning: %r", self.running) logger.info("\tRWait: %r", self.rwait) logger.info("\tTWait: %r", self.twait) logger.info("\tTimers: %r", self.timers) logger.info("\tCurrent clock: %d", self.clocks) logger.info("\tCurrent cpu: %d", self._current) if len(self.running) == 0: logger.info("None running checking if there is some process waiting for a timeout") if all([x is None for x in self.timers]): raise Deadlock() self.clocks = min([x for x in self.timers if x is not None]) + 1 self.check_timers() assert len(self.running) != 0, "DEADLOCK!" self._current = self.running[0] return next_index = (self.running.index(self._current) + 1) % len(self.running) next = self.running[next_index] if len(self.procs) > 1: logger.info("\tTransfer control from process %d to %d", self._current, next) self._current = next
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("\tProcess: %r", self.procs) logger.info("\tRunning: %r", self.running) logger.info("\tRWait: %r", self.rwait) logger.info("\tTWait: %r", self.twait) logger.info("\tTimers: %r", self.timers) logger.info("\tCurrent clock: %d", self.clocks) logger.info("\tCurrent cpu: %d", self._current) if len(self.running) == 0: logger.info("None running checking if there is some process waiting for a timeout") if all([x is None for x in self.timers]): raise Deadlock() self.clocks = min([x for x in self.timers if x is not None]) + 1 self.check_timers() assert len(self.running) != 0, "DEADLOCK!" self._current = self.running[0] return next_index = (self.running.index(self._current) + 1) % len(self.running) next = self.running[next_index] if len(self.procs) > 1: logger.info("\tTransfer control from process %d to %d", self._current, next) self._current = next
[ "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", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L767-L796
[ "def", "sched", "(", "self", ")", ":", "if", "len", "(", "self", ".", "procs", ")", ">", "1", ":", "logger", ".", "info", "(", "\"SCHED:\"", ")", "logger", ".", "info", "(", "\"\\tProcess: %r\"", ",", "self", ".", "procs", ")", "logger", ".", "info...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.wait
Wait for filedescriptors or timeout. Adds the current process to the corresponding waiting list and yields the cpu to another running process.
manticore/platforms/decree.py
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 [ %r %r %r ]", self._current, readfds, writefds, timeout) logger.info("\tProcess: %r", self.procs) logger.info("\tRunning: %r", self.running) logger.info("\tRWait: %r", self.rwait) logger.info("\tTWait: %r", self.twait) logger.info("\tTimers: %r", self.timers) for fd in readfds: self.rwait[fd].add(self._current) for fd in writefds: self.twait[fd].add(self._current) if timeout is not None: self.timers[self._current] = self.clocks + timeout else: self.timers[self._current] = None procid = self._current # self.sched() next_index = (self.running.index(procid) + 1) % len(self.running) self._current = self.running[next_index] logger.info("\tTransfer control from process %d to %d", procid, self._current) logger.info("\tREMOVING %r from %r. Current: %r", procid, self.running, self._current) self.running.remove(procid) if self._current not in self.running: logger.info("\tCurrent not running. Checking for timers...") self._current = None if all([x is None for x in self.timers]): raise Deadlock() self.check_timers()
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 [ %r %r %r ]", self._current, readfds, writefds, timeout) logger.info("\tProcess: %r", self.procs) logger.info("\tRunning: %r", self.running) logger.info("\tRWait: %r", self.rwait) logger.info("\tTWait: %r", self.twait) logger.info("\tTimers: %r", self.timers) for fd in readfds: self.rwait[fd].add(self._current) for fd in writefds: self.twait[fd].add(self._current) if timeout is not None: self.timers[self._current] = self.clocks + timeout else: self.timers[self._current] = None procid = self._current # self.sched() next_index = (self.running.index(procid) + 1) % len(self.running) self._current = self.running[next_index] logger.info("\tTransfer control from process %d to %d", procid, self._current) logger.info("\tREMOVING %r from %r. Current: %r", procid, self.running, self._current) self.running.remove(procid) if self._current not in self.running: logger.info("\tCurrent not running. Checking for timers...") self._current = None if all([x is None for x in self.timers]): raise Deadlock() self.check_timers()
[ "Wait", "for", "filedescriptors", "or", "timeout", ".", "Adds", "the", "current", "process", "to", "the", "corresponding", "waiting", "list", "and", "yields", "the", "cpu", "to", "another", "running", "process", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L798-L831
[ "def", "wait", "(", "self", ",", "readfds", ",", "writefds", ",", "timeout", ")", ":", "logger", ".", "info", "(", "\"WAIT:\"", ")", "logger", ".", "info", "(", "\"\\tProcess %d is going to wait for [ %r %r %r ]\"", ",", "self", ".", "_current", ",", "readfds"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.signal_transmit
Awake one process waiting to transmit data on fd
manticore/platforms/decree.py
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)
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)
[ "Awake", "one", "process", "waiting", "to", "transmit", "data", "on", "fd" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L862-L867
[ "def", "signal_transmit", "(", "self", ",", "fd", ")", ":", "connections", "=", "self", ".", "connections", "if", "connections", "(", "fd", ")", "and", "self", ".", "rwait", "[", "connections", "(", "fd", ")", "]", ":", "procid", "=", "random", ".", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Decree.execute
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.
manticore/platforms/decree.py
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 if self.clocks % 10000 == 0: self.check_timers() self.sched() except Interruption as e: if e.N != 0x80: raise try: self.int80(self.current) except RestartSyscall: pass return 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 if self.clocks % 10000 == 0: self.check_timers() self.sched() except Interruption as e: if e.N != 0x80: raise try: self.int80(self.current) except RestartSyscall: pass return True
[ "Execute", "one", "cpu", "instruction", "in", "the", "current", "thread", "(", "only", "one", "supported", ")", ".", ":", "rtype", ":", "bool", ":", "return", ":", "C", "{", "True", "}" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L882-L904
[ "def", "execute", "(", "self", ")", ":", "try", ":", "self", ".", "current", ".", "execute", "(", ")", "self", ".", "clocks", "+=", "1", "if", "self", ".", "clocks", "%", "10000", "==", "0", ":", "self", ".", "check_timers", "(", ")", "self", "."...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SDecree.sys_receive
Symbolic version of Decree.sys_receive
manticore/platforms/decree.py
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(cpu, 0) if issymbolic(buf): logger.info("Ask to read to a symbolic buffer") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 1) if issymbolic(count): logger.info("Ask to read a symbolic number of bytes ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 2) if issymbolic(rx_bytes): logger.info("Ask to return size to a symbolic address ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 3) return super().sys_receive(cpu, fd, buf, count, rx_bytes)
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(cpu, 0) if issymbolic(buf): logger.info("Ask to read to a symbolic buffer") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 1) if issymbolic(count): logger.info("Ask to read a symbolic number of bytes ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 2) if issymbolic(rx_bytes): logger.info("Ask to return size to a symbolic address ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 3) return super().sys_receive(cpu, fd, buf, count, rx_bytes)
[ "Symbolic", "version", "of", "Decree", ".", "sys_receive" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L951-L975
[ "def", "sys_receive", "(", "self", ",", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "rx_bytes", ")", ":", "if", "issymbolic", "(", "fd", ")", ":", "logger", ".", "info", "(", "\"Ask to read from a symbolic file descriptor!!\"", ")", "cpu", ".", "PC", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
SDecree.sys_transmit
Symbolic version of Decree.sys_transmit
manticore/platforms/decree.py
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(cpu, 0) if issymbolic(buf): logger.info("Ask to write to a symbolic buffer") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 1) if issymbolic(count): logger.info("Ask to write a symbolic number of bytes ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 2) if issymbolic(tx_bytes): logger.info("Ask to return size to a symbolic address ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 3) return super().sys_transmit(cpu, fd, buf, count, tx_bytes)
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(cpu, 0) if issymbolic(buf): logger.info("Ask to write to a symbolic buffer") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 1) if issymbolic(count): logger.info("Ask to write a symbolic number of bytes ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 2) if issymbolic(tx_bytes): logger.info("Ask to return size to a symbolic address ") cpu.PC = cpu.PC - cpu.instruction.size raise SymbolicSyscallArgument(cpu, 3) return super().sys_transmit(cpu, fd, buf, count, tx_bytes)
[ "Symbolic", "version", "of", "Decree", ".", "sys_transmit" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/decree.py#L977-L1001
[ "def", "sys_transmit", "(", "self", ",", "cpu", ",", "fd", ",", "buf", ",", "count", ",", "tx_bytes", ")", ":", "if", "issymbolic", "(", "fd", ")", ":", "logger", ".", "info", "(", "\"Ask to write to a symbolic file descriptor!!\"", ")", "cpu", ".", "PC", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
sync
Synchronization decorator.
manticore/core/workspace.py
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
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
[ "Synchronization", "decorator", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L322-L331
[ "def", "sync", "(", "f", ")", ":", "def", "new_function", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "return", "f", "(", "self", ",", "*", "args", ",", "*", "*", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Store.fromdescriptor
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
manticore/core/workspace.py
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 """ type_, uri = ('fs', None) if desc is None else desc.split(':', 1) for subclass in cls.__subclasses__(): if subclass.store_type == type_: return subclass(uri) raise NotImplementedError(f"Storage type '{type_}' not supported.")
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 """ type_, uri = ('fs', None) if desc is None else desc.split(':', 1) for subclass in cls.__subclasses__(): if subclass.store_type == type_: return subclass(uri) raise NotImplementedError(f"Storage type '{type_}' not supported.")
[ "Create", "a", ":", "class", ":", "~manticore", ".", "core", ".", "workspace", ".", "Store", "instance", "depending", "on", "the", "descriptor", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L66-L82
[ "def", "fromdescriptor", "(", "cls", ",", "desc", ")", ":", "type_", ",", "uri", "=", "(", "'fs'", ",", "None", ")", "if", "desc", "is", "None", "else", "desc", ".", "split", "(", "':'", ",", "1", ")", "for", "subclass", "in", "cls", ".", "__subc...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Store.save_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:
manticore/core/workspace.py
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(value)
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(value)
[ "Save", "an", "arbitrary", "serializable", "value", "under", "key", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L97-L106
[ "def", "save_value", "(", "self", ",", "key", ",", "value", ")", ":", "with", "self", ".", "save_stream", "(", "key", ")", "as", "s", ":", "s", ".", "write", "(", "value", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Store.load_value
Load an arbitrary value identified by `key`. :param str key: The key that identifies the value :return: The loaded value
manticore/core/workspace.py
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()
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()
[ "Load", "an", "arbitrary", "value", "identified", "by", "key", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L108-L116
[ "def", "load_value", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "with", "self", ".", "load_stream", "(", "key", ",", "binary", "=", "binary", ")", "as", "s", ":", "return", "s", ".", "read", "(", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Store.save_stream
Return a managed file-like object into which the calling code can write arbitrary data. :param key: :return: A managed stream-like object
manticore/core/workspace.py
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.save_value(key, s.getvalue())
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.save_value(key, s.getvalue())
[ "Return", "a", "managed", "file", "-", "like", "object", "into", "which", "the", "calling", "code", "can", "write", "arbitrary", "data", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L119-L129
[ "def", "save_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "s", "=", "io", ".", "BytesIO", "(", ")", "if", "binary", "else", "io", ".", "StringIO", "(", ")", "yield", "s", "self", ".", "save_value", "(", "key", ",", "s"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Store.load_stream
Return a managed file-like object from which the calling code can read previously-serialized data. :param key: :return: A managed stream-like object
manticore/core/workspace.py
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.BytesIO(value) if binary else io.StringIO(value)
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.BytesIO(value) if binary else io.StringIO(value)
[ "Return", "a", "managed", "file", "-", "like", "object", "from", "which", "the", "calling", "code", "can", "read", "previously", "-", "serialized", "data", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L132-L141
[ "def", "load_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "value", "=", "self", ".", "load_value", "(", "key", ",", "binary", "=", "binary", ")", "yield", "io", ".", "BytesIO", "(", "value", ")", "if", "binary", "else", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Store.save_state
Save a state to storage. :param manticore.core.StateBase state: :param str key: :return:
manticore/core/workspace.py
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)
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)
[ "Save", "a", "state", "to", "storage", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L143-L152
[ "def", "save_state", "(", "self", ",", "state", ",", "key", ")", ":", "with", "self", ".", "save_stream", "(", "key", ",", "binary", "=", "True", ")", "as", "f", ":", "self", ".", "_serializer", ".", "serialize", "(", "state", ",", "f", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Store.load_state
Load a state from storage. :param key: key that identifies state :rtype: manticore.core.StateBase
manticore/core/workspace.py
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: self.rm(key) return state
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: self.rm(key) return state
[ "Load", "a", "state", "from", "storage", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L154-L165
[ "def", "load_state", "(", "self", ",", "key", ",", "delete", "=", "True", ")", ":", "with", "self", ".", "load_stream", "(", "key", ",", "binary", "=", "True", ")", "as", "f", ":", "state", "=", "self", ".", "_serializer", ".", "deserialize", "(", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
FilesystemStore.save_stream
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:
manticore/core/workspace.py
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, key), mode) as f: yield f
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, key), mode) as f: yield f
[ "Yield", "a", "file", "object", "representing", "key" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L205-L215
[ "def", "save_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "mode", "=", "'wb'", "if", "binary", "else", "'w'", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "uri", ",", "key", ")", ",", "mode", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
FilesystemStore.load_stream
:param str key: name of stream to load :param bool binary: Whether we should treat it as binary :return:
manticore/core/workspace.py
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
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
[ ":", "param", "str", "key", ":", "name", "of", "stream", "to", "load", ":", "param", "bool", "binary", ":", "Whether", "we", "should", "treat", "it", "as", "binary", ":", "return", ":" ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L218-L225
[ "def", "load_stream", "(", "self", ",", "key", ",", "binary", "=", "False", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "uri", ",", "key", ")", ",", "'rb'", "if", "binary", "else", "'r'", ")", "as", "f", ":"...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
FilesystemStore.rm
Remove file identified by `key`. :param str key: The file to delete
manticore/core/workspace.py
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)
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)
[ "Remove", "file", "identified", "by", "key", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L227-L234
[ "def", "rm", "(", "self", ",", "key", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "uri", ",", "key", ")", "os", ".", "remove", "(", "path", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
FilesystemStore.ls
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
manticore/core/workspace.py
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 in glob.glob(path)]
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 in glob.glob(path)]
[ "Return", "just", "the", "filenames", "that", "match", "glob_str", "inside", "the", "store", "directory", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L236-L244
[ "def", "ls", "(", "self", ",", "glob_str", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "uri", ",", "glob_str", ")", "return", "[", "os", ".", "path", ".", "split", "(", "s", ")", "[", "1", "]", "for", "s", "in", ...
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Workspace._get_id
Get a unique state id. :rtype: int
manticore/core/workspace.py
def _get_id(self): """ Get a unique state id. :rtype: int """ id_ = self._last_id.value self._last_id.value += 1 return id_
def _get_id(self): """ Get a unique state id. :rtype: int """ id_ = self._last_id.value self._last_id.value += 1 return id_
[ "Get", "a", "unique", "state", "id", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L366-L374
[ "def", "_get_id", "(", "self", ")", ":", "id_", "=", "self", ".", "_last_id", ".", "value", "self", ".", "_last_id", ".", "value", "+=", "1", "return", "id_" ]
54c5a15b1119c523ae54c09972413e8b97f11629
valid
Workspace.load_state
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
manticore/core/workspace.py
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}{self._suffix}', delete=delete)
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}{self._suffix}', delete=delete)
[ "Load", "a", "state", "from", "storage", "identified", "by", "state_id", "." ]
trailofbits/manticore
python
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L376-L384
[ "def", "load_state", "(", "self", ",", "state_id", ",", "delete", "=", "True", ")", ":", "return", "self", ".", "_store", ".", "load_state", "(", "f'{self._prefix}{state_id:08x}{self._suffix}'", ",", "delete", "=", "delete", ")" ]
54c5a15b1119c523ae54c09972413e8b97f11629