code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.lock.acquire() text = output_db('', self.db) self.lock.release() return text
def output(self)
output() Return the resource database in text representation.
14.524952
7.72577
1.880065
while argv and argv[0] and argv[0][0] == '-': try: argv = opts[argv[0]].parse(name, self, argv) except KeyError: raise OptionError('unknown option: %s' % argv[0]) except IndexError: raise OptionError('missing argument ...
def getopt(self, name, argv, opts)
getopt(name, argv, opts) Parse X command line options, inserting the recognised options into the resource database. NAME is the application name, and will be prepended to all specifiers. ARGV is the list of command line arguments, typically sys.argv[1:]. OPTS is a map...
2.907653
3.052107
0.952671
return GetScreenSize(display=self.display, opcode=self.display.get_extension_major(extname), window=self.id, screen=screen_no, )
def get_screen_size(self, screen_no)
Returns the size of the given screen number
9.681508
10.192192
0.949895
sql, params = compiler.as_sql() check_parameter_types(params) cache_key = '%s:%s:%s' % (compiler.using, sql, [text_type(p) for p in params]) return sha1(cache_key.encode('utf-8')).hexdigest()
def get_query_cache_key(compiler)
Generates a cache key from a SQLCompiler. This cache key is specific to the SQL query and its context (which database is used). The same query in the same context (= the same database) must generate the same cache key. :arg compiler: A SQLCompiler that will generate the SQL query :type compiler: ...
3.660772
4.049006
0.904116
cache_key = '%s:%s' % (db_alias, table) return sha1(cache_key.encode('utf-8')).hexdigest()
def get_table_cache_key(db_alias, table)
Generates a cache key from a SQL table. :arg db_alias: Alias of the used database :type db_alias: str or unicode :arg table: Name of the SQL table :type table: str or unicode :return: A cache key :rtype: int
2.590055
3.440794
0.752749
# TODO: Replace with positional arguments when we drop Python 2 support. cache_alias = kwargs.pop('cache_alias', None) db_alias = kwargs.pop('db_alias', None) for k in kwargs: raise TypeError( "invalidate() got an unexpected keyword argument '%s'" % k) send_signal = False ...
def invalidate(*tables_or_models, **kwargs)
Clears what was cached by django-cachalot implying one or more SQL tables or models from ``tables_or_models``. If ``tables_or_models`` is not specified, all tables found in the database (including those outside Django) are invalidated. If ``cache_alias`` is specified, it only clears the SQL queries sto...
3.140903
3.079865
1.019819
# TODO: Replace with positional arguments when we drop Python 2 support. cache_alias = kwargs.pop('cache_alias', None) db_alias = kwargs.pop('db_alias', None) for k in kwargs: raise TypeError("get_last_invalidation() got an unexpected " "keyword argument '%s'" % k) ...
def get_last_invalidation(*tables_or_models, **kwargs)
Returns the timestamp of the most recent invalidation of the given ``tables_or_models``. If ``tables_or_models`` is not specified, all tables found in the database (including those outside Django) are used. If ``cache_alias`` is specified, it only fetches invalidations in this cache, otherwise invalid...
2.795157
2.67415
1.045251
# Setup I2C interface for device 0x00 to talk to all of them. if i2c is None: import Adafruit_GPIO.I2C as I2C i2c = I2C self._device = i2c.get_i2c_device(0x00, **kwargs) self._device.writeRaw8(0x06)
def software_reset(i2c=None, **kwargs)
Sends a software reset (SWRST) command to all servo drivers on the bus.
3.398043
3.227817
1.052737
try: translator = self._instr_translators[instr.mnemonic] return translator(*instr.operands) except Exception: logger.error("Failed to translate instruction: %s", instr, exc_info=True) raise
def translate(self, instr)
Return the SMT representation of a REIL instruction.
4.240307
3.528046
1.201885
self._register_name(name) return self._var_name_mappers[name].get_init()
def get_name_init(self, name)
Get initial name of symbol.
9.821714
9.537698
1.029778
self._register_name(name) return self._var_name_mappers[name].get_current()
def get_name_curr(self, name)
Get current name of symbol.
11.294043
11.26211
1.002835
self._solver.reset() # Memory versioning. self._mem_instance = 0 self._mem_init = smtsymbol.BitVecArray(self._address_size, 8, "MEM_{}".format(self._mem_instance)) self._mem_curr = self.make_array(self._address_size, "MEM_{}".format(self._mem_instance)) self._...
def reset(self)
Reset internal state.
8.935477
8.034305
1.112166
if name not in self._var_name_mappers: self._var_name_mappers[name] = VariableNamer(name)
def _register_name(self, name)
Get register name.
4.42169
4.217071
1.048522
if name not in self._var_name_mappers: self._var_name_mappers[name] = VariableNamer(name) if fresh: var_name = self._var_name_mappers[name].get_next() else: var_name = self._var_name_mappers[name].get_current() return var_name
def _get_var_name(self, name, fresh=False)
Get variable name.
2.13176
2.068967
1.03035
if isinstance(operand, ReilRegisterOperand): return self._translate_src_register_oprnd(operand) elif isinstance(operand, ReilImmediateOperand): return smtsymbol.Constant(operand.size, operand.immediate) else: raise Exception("Invalid operand type")
def _translate_src_oprnd(self, operand)
Translate source operand to a SMT expression.
4.487352
3.952489
1.135323
if isinstance(operand, ReilRegisterOperand): return self._translate_dst_register_oprnd(operand) else: raise Exception("Invalid operand type")
def _translate_dst_oprnd(self, operand)
Translate destination operand to a SMT expression.
4.701736
4.381926
1.072984
reg_info = self._arch_alias_mapper.get(operand.name, None) if reg_info: var_base_name, offset = reg_info var_size = self._arch_regs_size[var_base_name] else: var_base_name = operand.name var_size = operand.size var_name = self._...
def _translate_src_register_oprnd(self, operand)
Translate source register operand to SMT expr.
3.527351
3.363893
1.048592
reg_info = self._arch_alias_mapper.get(operand.name, None) parent_reg_constrs = [] if reg_info: var_base_name, offset = reg_info var_name_old = self._get_var_name(var_base_name, fresh=False) var_name_new = self._get_var_name(var_base_name, fresh=Tr...
def _translate_dst_register_oprnd(self, operand)
Translate destination register operand to SMT expr.
1.829724
1.793924
1.019956
assert oprnd1.size and oprnd2.size and oprnd3.size assert oprnd1.size == oprnd2.size op1_var = self._translate_src_oprnd(oprnd1) op2_var = self._translate_src_oprnd(oprnd2) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) if oprnd3.size > oprnd1.siz...
def _translate_add(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of an ADD instruction.
2.291541
2.197638
1.042729
assert oprnd1.size and oprnd2.size and oprnd3.size assert oprnd1.size == oprnd2.size op1_var = self._translate_src_oprnd(oprnd1) op2_var = self._translate_src_oprnd(oprnd2) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) if oprnd3.size > oprnd1.siz...
def _translate_div(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of an DIV instruction.
2.262116
2.172708
1.041151
assert oprnd1.size and oprnd2.size and oprnd3.size assert oprnd1.size == oprnd2.size op1_var = self._translate_src_oprnd(oprnd1) op2_var = self._translate_src_oprnd(oprnd2) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) if oprnd3.size > oprnd1.siz...
def _translate_bsh(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of a BSH instruction.
2.08613
2.045895
1.019666
assert oprnd1.size and oprnd3.size assert oprnd1.size == self._address_size op1_var = self._translate_src_oprnd(oprnd1) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) exprs = [] for i in reversed(range(0, oprnd3.size, 8)): exprs += [s...
def _translate_ldm(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of a LDM instruction.
4.545134
4.287098
1.060189
assert oprnd1.size and oprnd3.size assert oprnd3.size == self._address_size op1_var = self._translate_src_oprnd(oprnd1) op3_var = self._translate_src_oprnd(oprnd3) for i in range(0, oprnd1.size, 8): self._mem_curr[op3_var + i//8] = smtfunction.extract(op1_v...
def _translate_stm(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of a STM instruction.
4.159306
4.121418
1.009193
assert oprnd1.size and oprnd3.size op1_var = self._translate_src_oprnd(oprnd1) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) if oprnd3.size > oprnd1.size: result = smtfunction.zero_extend(op1_var, op3_var.size) elif oprnd3.size < oprnd1.size:...
def _translate_str(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of a STR instruction.
3.014113
2.897404
1.04028
assert oprnd1.size and oprnd3.size op1_var = self._translate_src_oprnd(oprnd1) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) result = smtfunction.ite(oprnd3.size, op1_var == 0x0, smtsymbol.Constant(oprnd3.size, 0x1), smtsymbol...
def _translate_bisz(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of a BISZ instruction.
4.89083
4.689516
1.042929
assert oprnd1.size and oprnd3.size op1_var = self._translate_src_oprnd(oprnd1) return [op1_var != 0x0]
def _translate_jcc(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of a JCC instruction.
8.629982
7.543938
1.143962
assert oprnd1.size and oprnd3.size op1_var = self._translate_src_oprnd(oprnd1) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) if oprnd3.size > oprnd1.size: result = smtfunction.sign_extend(op1_var, op3_var.size) elif oprnd3.size < oprnd1.size:...
def _translate_sext(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of a SEXT instruction.
3.644752
3.494549
1.042982
assert oprnd1.size and oprnd2.size and oprnd3.size assert oprnd1.size == oprnd2.size op1_var = self._translate_src_oprnd(oprnd1) op2_var = self._translate_src_oprnd(oprnd2) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) if oprnd3.size > oprnd1.siz...
def _translate_sdiv(self, oprnd1, oprnd2, oprnd3)
Return a formula representation of an DIV instruction.
2.265635
2.18263
1.03803
for nseg, section in enumerate(elffile.iter_sections()): request = sect_req.get(section.name, None) if request: request.set_found(True) request.set_sect_properties(section.header.sh_addr, section.header....
def _extract_section(sect_req, elffile, mem=None)
:sect_req dictionary of section names as strings and SectionRequest objects :mem if mem is not null, it serves as an accumulator rather than using the memory in SectionRequests :returns nothing
3.225128
3.223758
1.000425
# Add instructions to the analyzer self.analyzer.reset() for reil_instr in gadget.ir_instrs: self.analyzer.add_instruction(reil_instr) # Generate constraints for the gadgets type. constrs = self._constraints_generators[gadget.type](gadget) # Check ...
def verify(self, gadget)
Verify gadgets.
4.581433
4.365942
1.049357
# Constraints on memory locations. # mem_constrs = [self.analyzer.get_memory("pre") != self.analyzer.get_memory("post")] mem_constrs = [self.analyzer.get_memory_curr("pre").__neq__(self.analyzer.get_memory_curr("post"))] # Constraints on flags. flags_constrs = [] ...
def _get_constrs_no_operation(self, gadget)
Verify NoOperation gadgets.
2.820589
2.752377
1.024783
# *src* register has to have the same value of *dst* for all # possibles assignments of *dst*. dst = self.analyzer.get_register_expr(gadget.destination[0].name, mode="post") src = self.analyzer.get_register_expr(gadget.sources[0].name, mode="pre") # Check all non-modif...
def _get_constrs_move_register(self, gadget)
Generate constraints for the MoveRegister gadgets: dst <- src
4.508186
4.447397
1.013668
# *dst* register has to have the value of *src1 op src2* for all # possibles assignments of *src1* and *src2*. dst = self.analyzer.get_register_expr(gadget.destination[0].name, mode="post") src1 = self.analyzer.get_register_expr(gadget.sources[0].name, mode="pre") src2 ...
def _get_constrs_arithmetic(self, gadget)
Generate constraints for the BinaryOperation gadgets: dst <- src1 OP src2
3.874709
3.675768
1.054122
dst = self.analyzer.get_register_expr(gadget.destination[0].name, mode="post") size = gadget.destination[0].size if isinstance(gadget.sources[0], ReilRegisterOperand): base_addr = self.analyzer.get_register_expr(gadget.sources[0].name, mode="pre") offset = gadge...
def _get_constrs_load_memory(self, gadget)
Generate constraints for the LoadMemory gadgets: dst_reg <- mem[src_reg + offset]
3.512033
3.391
1.035692
size = None for oprnd in operands: if oprnd.size: size = oprnd.size break if size: for oprnd in operands: if not oprnd.size: oprnd.size = size else: for oprnd in operands: if isinstance(oprnd, X86ImmediateOper...
def infer_operands_size(operands)
Infer x86 instruction operand size based on other operands.
2.706483
2.433896
1.111996
mod = " ".join(tokens.get("modifier", "")) if "immediate" in tokens: imm = parse_immediate("".join(tokens["immediate"])) size = modifier_size.get(mod, None) oprnd = X86ImmediateOperand(imm, size) if "register" in tokens: name = tokens["register"] size = arch_i...
def parse_operand(string, location, tokens)
Parse an x86 instruction operand.
2.680001
2.57088
1.042445
prefix_str = tokens.get("prefix", None) mnemonic_str = tokens.get("mnemonic") operands = [op for op in tokens.get("operands", [])] infer_operands_size(operands) # Quick hack: Capstone returns rep instead of repe for cmps and scas # instructions. if prefix_str == "rep" and (mnemonic_st...
def parse_instruction(string, location, tokens)
Parse an x86 instruction.
6.248214
5.699998
1.096178
try: instr_lower = instr.lower() if instr_lower not in self._cache: instr_asm = instruction.parseString(instr_lower)[0] self._cache[instr_lower] = instr_asm instr_asm = copy.deepcopy(self._cache[instr_lower]) # self._ch...
def parse(self, instr)
Parse an x86 instruction.
3.365191
3.169825
1.061633
# TODO: Improve this code! if architecture_mode is None: if self._arch_mode is None: architecture_mode = ARCH_ARM_MODE_THUMB else: architecture_mode = self._arch_mode self._disassembler = self._available_disassemblers[architecture...
def disassemble(self, data, address, architecture_mode=None)
Disassemble the data into an instruction.
3.704936
3.608119
1.026833
disasm = list(self._disassembler.disasm(bytes(data), address)) # TODO: Improve this check. if len(disasm) > 0: return disasm[0] else: cs_arm = Cs(CS_ARCH_ARM, CS_MODE_ARM) cs_arm.detail = True disasm = list(cs_arm.disasm(bytes(dat...
def _cs_disassemble_one(self, data, address)
Disassemble the data into an instruction in string form.
3.171833
3.186775
0.995311
if registers: self.__cpu.registers = dict(registers) ip = start if start else container[0].address while ip and ip != end: try: instr = container.fetch(ip) except ReilContainerInvalidAddressError: logger.info("Invalid...
def execute(self, container, start=None, end=None, registers=None)
Execute instructions.
5.039539
4.960677
1.015897
if context: self.__cpu.registers = dict(context) for instr in instructions: self.__execute_one(instr) return dict(self.__cpu.registers), self.__mem
def execute_lite(self, instructions, context=None)
Execute a list of instructions. It does not support loops.
6.626013
5.867216
1.129328
self.__mem.reset() self.__cpu.reset() self.__tainter.reset() # Instructions pre and post handlers. self.__instr_handler_pre = None, None self.__instr_handler_post = None, None self.__set_default_handlers()
def reset(self)
Reset emulator. All registers and memory are reset.
7.41992
6.109887
1.214412
op0_val = self.read_operand(instr.operands[0]) op1_val = self.read_operand(instr.operands[1]) op1_size = instr.operands[1].size # Check sign bit. if extract_sign_bit(op1_val, op1_size) == 0: op2_val = op0_val << op1_val else: op2_val = o...
def __execute_bsh(self, instr)
Execute BSH instruction.
2.773457
2.618085
1.059346
assert instr.operands[0].size == self.__mem.address_size assert instr.operands[2].size in [8, 16, 32, 64, 128, 256] # Memory address. op0_val = self.read_operand(instr.operands[0]) # Data. op2_val = self.read_memory(op0_val, instr.operands[2].size // 8) ...
def __execute_ldm(self, instr)
Execute LDM instruction.
3.197792
3.027298
1.056319
assert instr.operands[0].size in [8, 16, 32, 64, 128, 256] assert instr.operands[2].size == self.__mem.address_size op0_val = self.read_operand(instr.operands[0]) # Data. op2_val = self.read_operand(instr.operands[2]) # Memory address. op0_size = instr.operands[0].si...
def __execute_stm(self, instr)
Execute STM instruction.
3.170422
3.065687
1.034164
op0_val = self.read_operand(instr.operands[0]) self.write_operand(instr.operands[2], op0_val) return None
def __execute_str(self, instr)
Execute STR instruction.
5.800018
5.124227
1.131882
op0_val = self.read_operand(instr.operands[0]) op2_val = 1 if op0_val == 0 else 0 self.write_operand(instr.operands[2], op2_val) return None
def __execute_bisz(self, instr)
Execute BISZ instruction.
3.66948
3.292864
1.114374
op0_val = self.read_operand(instr.operands[0]) # Branch condition. op2_val = self.read_operand(instr.operands[2]) # Target address. return op2_val if op0_val != 0 else None
def __execute_jcc(self, instr)
Execute JCC instruction.
4.332729
3.887773
1.11445
op2_val = random.randint(0, instr.operands[2].size) self.write_operand(instr.operands[2], op2_val) return None
def __execute_undef(self, instr)
Execute UNDEF instruction.
7.322674
6.690959
1.094413
op0_size = instr.operands[0].size op2_size = instr.operands[2].size op0_val = self.read_operand(instr.operands[0]) op0_msb = extract_sign_bit(op0_val, op0_size) op2_mask = (2**op2_size-1) & ~(2**op0_size-1) if op0_msb == 1 else 0x0 op2_val = op0_val | op2_mask...
def __execute_sext(self, instr)
Execute SEXT instruction.
2.649579
2.605281
1.017003
suffix = self._separator + "%s" % str(self._counter_init) return self._base_name + suffix
def get_init(self)
Return initial name.
13.543474
10.131909
1.336715
suffix = self._separator + "%s" % str(self._counter_curr) return self._base_name + suffix
def get_current(self)
Return current name.
15.105955
11.62247
1.29972
self._counter_curr += 1 suffix = self._separator + "%s" % str(self._counter_curr) return self._base_name + suffix
def get_next(self)
Return next name.
8.287896
6.394904
1.296016
start_instr_found = False sat = False # Traverse basic blocks, translate its instructions to SMT # expressions and add them as assertions. for bb_curr, bb_next in zip(path[:-1], path[1:]): logger.info("BB @ {:#x}".format(bb_curr.address)) # For ...
def check_path_satisfiability(code_analyzer, path, start_address)
Check satisfiability of a basic block path.
3.609281
3.557916
1.014437
strings = { # Arithmetic Instructions ReilMnemonic.ADD: "add", ReilMnemonic.SUB: "sub", ReilMnemonic.MUL: "mul", ReilMnemonic.DIV: "div", ReilMnemonic.MOD: "mod", ReilMnemonic.BSH: "bsh", # Bitwise Instruct...
def to_string(mnemonic)
Return the string representation of the given mnemonic.
1.912879
1.864934
1.025709
mnemonics = { # Arithmetic Instructions "add": ReilMnemonic.ADD, "sub": ReilMnemonic.SUB, "mul": ReilMnemonic.MUL, "div": ReilMnemonic.DIV, "mod": ReilMnemonic.MOD, "bsh": ReilMnemonic.BSH, # Bitwise Instru...
def from_string(string)
Return the mnemonic represented by the given string.
2.045316
1.95115
1.048262
if value not in REIL_MNEMONICS: raise Exception("Invalid instruction mnemonic : %s" % str(value)) self._mnemonic = value
def mnemonic(self, value)
Set instruction mnemonic.
5.449051
4.44539
1.225776
if len(value) != 3: raise Exception("Invalid instruction operands : %s" % str(value)) self._operands = value
def operands(self, value)
Set instruction operands.
5.598708
4.16153
1.345349
# Get memory address. op0_val = self.__emu.read_operand(instr.operands[0]) # Get taint information. op0_taint = self.get_memory_taint(op0_val, instr.operands[2].size // 8) # Propagate taint. self.set_operand_taint(instr.operands[2], op0_taint)
def __taint_load(self, instr)
Taint LDM instruction.
4.633486
4.277704
1.083171
# Get memory address. op2_val = self.__emu.read_operand(instr.operands[2]) # Get taint information. op0_size = instr.operands[0].size op0_taint = self.get_operand_taint(instr.operands[0]) # Propagate taint. self.set_memory_taint(op2_val, op0_size // 8, ...
def __taint_store(self, instr)
Taint STM instruction.
4.492052
4.11353
1.092019
# Get taint information. op0_taint = self.get_operand_taint(instr.operands[0]) # Propagate taint. self.set_operand_taint(instr.operands[2], op0_taint)
def __taint_move(self, instr)
Taint registers move instruction.
4.285505
3.765822
1.138
# Update the instruction pointer. self.ir_emulator.registers[self.ip] = asm_instr.address + asm_instr.size # Process syscall. if self.arch_info.instr_is_syscall(asm_instr): raise Syscall() # Process instruction and return next address instruction to execute...
def execute(self, asm_instr)
Execute an assembler instruction. Args: asm_instr (X86Instruction): A instruction to execute. Returns: A int. The address of the next instruction to execute.
8.178929
8.325212
0.982429
ir_instrs = [] for asm_instr in self._instrs: ir_instrs += asm_instr.ir_instrs return ir_instrs
def ir_instrs(self)
Get gadgets IR instructions.
3.433017
3.010494
1.14035
f = open(filename, 'rb') elffile = ELFFile(f) symbols = [] for section in elffile.iter_sections(): if not isinstance(section, SymbolTableSection): continue if section['sh_entsize'] == 0: logger.warn("Symbol table {} has a sh_entsize of zero.".format(secti...
def load_symbols_elf(filename)
Load the symbol tables contained in the file
2.737644
2.713233
1.008997
typed_gadgets = [] for g_type, g_classifier in self._classifiers.items(): try: typed_gadgets += self._classify(gadget, g_classifier, g_type, self._emu_iters) except: import traceback print("[-] Error classifying gadgets :...
def classify(self, gadget)
Classify gadgets.
4.866705
4.557569
1.067829
# TODO: Flags should be taken into account matches = [] # Check that registers didn't change their value. regs_changed = any(regs_init[r] != regs_fini[r] for r in regs_init) # Check that flags didn't change their value. flags_changed = False # Check t...
def _classify_no_operation(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify no-operation gadgets.
3.738079
3.597548
1.039063
matches = [] regs_init_inv = self._invert_dictionary(regs_init) # Check for "dst_reg <- src_reg" pattern. for dst_reg, dst_val in regs_fini.items(): # Make sure the *dst* register was written. if dst_reg not in written_regs: continue ...
def _classify_move_register(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify move-register gadgets.
2.581752
2.513206
1.027275
matches = [] # Check for "dst_reg <- constant" pattern. for dst_reg, dst_val in regs_fini.items(): # Make sure the *dst* register was written. if dst_reg not in written_regs: continue # Check restrictions... if dst_val ==...
def _classify_load_constant(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify load-constant gadgets.
3.483295
3.317486
1.04998
matches = [] # TODO: Review these restrictions. op_restrictions = { "+": lambda x, y: False, "-": lambda x, y: x == y, "|": lambda x, y: x == y, "&": lambda x, y: x == y, "^": lambda x, y: x == y, } # Check fo...
def _classify_arithmetic(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify binary-operation gadgets.
2.217676
2.168001
1.022913
matches = [] regs_init_inv = self._invert_dictionary(regs_init) # Check for "dst_reg <- mem[src_reg + offset]" pattern. for dst_reg, dst_val in regs_fini.items(): # Make sure the *dst* register was written. if dst_reg not in written_regs: ...
def _classify_load_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify load-memory gadgets.
2.150565
2.106107
1.021109
matches = [] regs_init_inv = self._invert_dictionary(regs_init) # Check for "mem[dst_reg + offset] <- src_reg" pattern. for src_reg, src_val in regs_init.items(): # Make sure the *src* register was read. if src_reg not in read_regs: cont...
def _classify_store_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify store-memory gadgets.
2.069424
2.021793
1.023559
matches = [] # Check for "dst_reg <- dst_reg OP mem[src_reg + offset]" pattern. for op_name, op_fn in self._binary_ops.items(): for dst_reg, dst_val in regs_fini.items(): # Make sure the *dst* register was read and written. if dst_reg not in ...
def _classify_arithmetic_load(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify arithmetic-load gadgets.
1.947855
1.936017
1.006114
matches = [] # Check for "m[dst_reg + offset] <- m[dst_reg + offset] OP src_reg" pattern. for op_name, op_fn in self._binary_ops.items(): for size in [8, 16, 32, 64]: for addr in mem_fini.get_addresses(): success_read_curr, val_curr = mem...
def _classify_arithmetic_store(self, regs_init, regs_fini, mem_fini, written_regs, read_regs)
Classify arithmetic-store gadgets.
1.897171
1.881291
1.008441
# Collect REIL instructions of the gadgets. instrs = [ir_instr for asm_instr in gadget.instrs for ir_instr in asm_instr.ir_instrs] # Repeat classification. results = [] for _ in range(iters): # Reset emulator. self._ir_emulator.reset() ...
def _classify(self, gadget, classifier, gadget_type, iters)
Classify gadgets.
3.908448
3.843929
1.016785
# Generate random values and make sure they are all different. values = set() while len(values) != len(self._arch_regs_parent): values.add(random.randint(0, 2**self._arch_info.operand_size - 1)) values = list(values) # Assign random values to registers. ...
def _init_regs_random(self)
Initialize register with random values.
3.673739
3.477812
1.056336
assert regs_init.keys() == regs_fini.keys() modified_regs = [] for reg in regs_init: if regs_init[reg] != regs_fini[reg]: modified_regs.append(reg) return modified_regs
def _compute_mod_regs(self, regs_init, regs_fini)
Compute modified registers.
2.436118
2.338186
1.041884
inv_dict = {} for k, v in d.items(): inv_dict[v] = inv_dict.get(v, []) inv_dict[v] += [k] return inv_dict
def _invert_dictionary(self, d)
Invert a dictionary.
2.330048
2.192957
1.062514
for addr, value in memory.items(): print(" 0x%08x : 0x%08x (%d)" % (addr, value, value))
def _print_memory(self, memory)
Print memory.
3.553267
3.187662
1.114694
for reg, value in registers.items(): print(" %s : 0x%08x (%d)" % (reg, value, value))
def _print_registers(self, registers)
Print registers.
3.49099
3.06362
1.139498
asm, size = self._cs_disassemble_one(data, address) instr = self._parser.parse(asm) if asm else None if instr: instr.address = address instr.size = size instr.bytes = data[0:size] else: raise DisassemblerError() return i...
def disassemble(self, data, address, architecture_mode=ARCH_X86_MODE_32)
Disassemble the data into an instruction.
4.901484
4.548444
1.077618
asm, size = "", 0 disasm = list(self._disassembler.disasm_lite(bytes(data), address)) if len(disasm) > 0: address, size, mnemonic, op_str = disasm[0] asm = str(mnemonic + " " + op_str).strip() # Quick fix for Capstone 'bug'. if asm in ["repne"...
def _cs_disassemble_one(self, data, address)
Disassemble the data into an instruction in string form.
5.29466
5.274034
1.003911
size = self.__get_memory_access_size(x86_mem_operand) addr = None if x86_mem_operand.base: addr = ReilRegisterOperand(x86_mem_operand.base, size) if x86_mem_operand.index and x86_mem_operand.scale != 0x0: index = ReilRegisterOperand(x86_mem_operand.ind...
def resolve_memory_access(self, tb, x86_mem_operand)
Return operand memory access translation.
1.97735
1.949938
1.014058
asm_mnemonic_max_width = 0 for instr in basic_block: if len(instr.mnemonic) > asm_mnemonic_max_width: asm_mnemonic_max_width = len(instr.mnemonic) return asm_mnemonic_max_width
def bb_get_instr_max_width(basic_block)
Get maximum instruction mnemonic width
2.113728
1.852033
1.141302
if self._instrs is []: return None return self._instrs[-1].address + self._instrs[-1].size - 1
def end_address(self)
Get basic block end address.
5.92635
4.020679
1.473967
if self._instrs is []: return None return sum([instr.size for instr in self._instrs])
def size(self)
Get basic block size.
8.591901
5.719366
1.502247
branches = [] if self._taken_branch: branches += [(self._taken_branch, 'taken')] if self._not_taken_branch: branches += [(self._not_taken_branch, 'not-taken')] if self._direct_branch: branches += [(self._direct_branch, 'direct')] r...
def branches(self)
Get basic block branches.
2.900491
2.677837
1.083147
base = ReilRegisterOperand(mem_operand.base_reg.name, mem_operand.size) if mem_operand.displacement: address = self.temporal(mem_operand.size) if isinstance(mem_operand.displacement, ArmRegisterOperand): disp = ReilRegisterOperand(mem_operand.displaceme...
def _compute_memory_address(self, mem_operand)
Return operand memory access translation.
1.929378
1.917058
1.006427
ret = [] for reg_range in operand.reg_list: if len(reg_range) == 1: ret.append(ReilRegisterOperand(reg_range[0].name, reg_range[0].size)) else: reg_num = int(reg_range[0].name[1:]) # Assuming the register is named with one letter + num...
def _compute_register_list(self, operand)
Return operand register list.
2.838403
2.734255
1.03809
try: trans_instrs = self.__translate(instruction) except NotImplementedError: unkn_instr = self._builder.gen_unkn() unkn_instr.address = instruction.address << 8 | (0x0 & 0xff) trans_instrs = [unkn_instr] self._log_not_supported_instr...
def translate(self, instruction)
Return IR representation of an instruction.
4.883796
4.561004
1.070772
value = 0x0 for i in range(0, size): value |= self._read_byte(address + i) << (i * 8) return value
def read(self, address, size)
Read arbitrary size content from memory.
3.083988
2.912755
1.058787
# Initialize memory location with a random value. if address not in self._memory: self._memory[address] = random.randint(0x00, 0xff) return self._memory[address]
def _read_byte(self, address)
Read a byte from memory.
4.118266
3.937178
1.045994
for i in range(0, size): self.__write_byte(address + i, (value >> (i * 8)) & 0xff)
def write(self, address, size, value)
Write arbitrary size content to memory.
2.877593
2.812356
1.023197
addr_candidates = [addr for addr, val in self._memory.items() if val == (value & 0xff)] addr_matches = [] for addr in addr_candidates: match = True for i in range(0, size): byte_curr = (value >> (i * 8)) & 0xff try: ...
def read_inverse(self, value, size)
Return a list of memory addresses that contain the specified value.
3.122638
2.857435
1.092811
value = 0x0 for i in range(0, size): addr = address + i if addr in self._memory: value |= self._read_byte(addr) << (i * 8) else: return False, None return True, value
def try_read(self, address, size)
Try to read memory content at specified address. If any location was not written before, it returns a tuple (False, None). Otherwise, it returns (True, memory content).
3.414436
3.404735
1.002849
value = 0x0 for i in range(0, size): addr = address + i if addr in self.__memory_prev: _, val_byte = self.__try_read_byte_prev(addr) value |= val_byte << (i * 8) else: return False, None return True, ...
def try_read_prev(self, address, size)
Try to read previous memory content at specified address. If any location was not written before, it returns a tuple (False, None). Otherwise, it returns (True, memory content).
4.23089
4.193028
1.00903
# Initialize memory location with a random value if address not in self.__memory_prev: return False, None return True, self.__memory_prev[address]
def __try_read_byte_prev(self, address)
Read previous value for memory location. Return a tuple (True, Byte) in case of successful read, (False, None) otherwise.
8.40969
7.022254
1.197577
# Save previous address content. if address in self._memory: self.__memory_prev[address] = self._memory[address] self._memory[address] = value & 0xff
def __write_byte(self, address, value)
Write byte in memory.
5.960748
5.676858
1.050008
assert src1.size == src2.size return ReilBuilder.build(ReilMnemonic.ADD, src1, src2, dst)
def gen_add(src1, src2, dst)
Return an ADD instruction.
7.262206
5.292074
1.37228
assert src1.size == src2.size return ReilBuilder.build(ReilMnemonic.SUB, src1, src2, dst)
def gen_sub(src1, src2, dst)
Return a SUB instruction.
8.364141
5.780708
1.446906