def write_method(self): acc = [] access = self.method.access self.constructor = 0x10000 in access for i in self.method.access: if i == 0x10000: continue acc.append(ACCESS_FLAGS_METHODS.get(i)) if self.constructor: name = get_type(self.method.method.class_name).split('.')[-1] proto = '%s %s(' % (' '.join(acc), name) else: name = self.method.name proto = '%s %s %s(' % (' '.join(acc), self.method.type, name) self.write('%s%s' % (self.space(), proto)) if 0x8 in self.method.access: params = self.method.lparams else: params = self.method.lparams[1:] proto = '' if self.method.params_type: proto = ', '.join([ '%s p%s' % (get_type(p_type), param) for p_type, param in zip(self.method.params_type, params) ]) self.write('%s)' % proto) if self.graph is None: return self.write(';') self.write('\n%s{\n' % self.space()) self.inc_ind() # for v, var in self.method.var_to_name.iteritems(): # var.visit_decl(self) self.visit_node(self.graph.get_entry()) self.dec_ind() self.write('%s}\n' % self.space())
def write_method(self): acc = [] access = self.method.access self.constructor = 0x10000 in access for i in self.method.access: if i == 0x10000: continue acc.append(ACCESS_FLAGS_METHODS.get(i)) if self.constructor: name = get_type(self.method.method.class_name).split(".")[-1] proto = "%s %s(" % (" ".join(acc), name) else: name = self.method.name proto = "%s %s %s(" % (" ".join(acc), self.method.type, name) self.write("%s%s" % (self.space(), proto)) if 0x8 in self.method.access: params = self.method.lparams else: params = self.method.lparams[1:] proto = "" if self.method.params_type: proto = ", ".join( ["%s p%s" % (get_type(p_type), param) for p_type, param in zip(self.method.params_type, params)] ) self.write("%s)" % proto) if self.graph is None: return self.write(";") self.write("\n%s{\n" % self.space()) self.inc_ind() # for v, var in self.method.var_to_name.iteritems(): # var.visit_decl(self) self.visit_node(self.graph.get_entry()) self.dec_ind() self.write("%s}\n" % self.space())
def link(self, source, target=None, stage=None): st = get_type(source) tt = get_type(target) if target is None: target = '' if os.path.basename(target) == '': target = target + os.path.basename(source) if st in ['shared'] and tt in ['unit']: source = source.replace('shared://', self.path_to_shared) target = target.replace('shared://', self.path_to_shared) return BashCommand('ln', ['-l', source, target]) elif st in ['staging'] and tt in ['unit']: stage = stage or rp.STAGING_INPUT return StagingCommand( { 'source': source, 'target': target, 'action': rp.LINK }, stage) else: raise NotImplementedError( 'linking from `%s` to `%s` is not implemented yet.' % (st, tt))
def check(name, prop, dst): stype, dtype = util.get_type(prop), util.get_type(dst.get(name)) valid = name not in dst if not valid: if stype == None: valid = True else: valid = util.matches(stype, dtype) if not valid: errors.append(MergeError('property "%s" type mismatch: %s and %s' % (name, stype, dtype))) return valid
def __to_annotated_disjunction(self, triple_mode): cb = ClauseBuilder(triple_mode) true = Term('true') name = get_type(self.__name) clauses = [] sub = get_type(self.__subj_name) dic = self.__distribution.get_parameters() values = dic.keys() for value in values: t_value = get_type(value) clauses.append(cb.get_clause(sub, name, t_value, prob=dic[value])) return AnnotatedDisjunction(clauses, true)
def to_examples(self, examples=[]): cb = ClauseBuilder(self.__triple_mode) term_dict = {} for possible_world in self.__data: example = [] for triple in possible_world: if term_dict.get(triple[1]) is None: term_dict[triple[1]] = get_type(triple[1]) if term_dict.get(triple[0]) is None: term_dict[triple[0]] = get_type(triple[0]) example.append( (cb.get_clause(term_dict[triple[0]], term_dict[triple[1]]), triple[2])) examples.append(example) return examples
def show_source(self): if not self.inner and self.package: print 'package %s;\n' % self.package if self.superclass is not None: self.superclass = self.superclass[1:-1].replace('/', '.') if self.superclass.split('.')[-1] == 'Object': self.superclass = None if self.superclass is not None: self.prototype += ' extends %s' % self.superclass if self.interfaces is not None: self.interfaces = self.interfaces[1:-1].split(' ') self.prototype += ' implements %s' % ', '.join( [n[1:-1].replace('/', '.') for n in self.interfaces]) print '%s {\n' % self.prototype for field in self.fields.values(): access = [util.ACCESS_FLAGS_FIELDS.get(flag) for flag in util.ACCESS_FLAGS_FIELDS if flag & field.get_access_flags()] f_type = util.get_type(field.get_descriptor()) name = field.get_name() print ' %s %s %s;\n' % (' '.join(access), f_type, name) for klass in self.subclasses.values(): klass.show_source() for num, method in self.methods.iteritems(): method.show_source() print '}\n'
def show_source(self): if not self.inner and self.package: print 'package %s;\n' % self.package if self.superclass is not None: self.superclass = self.superclass[1:-1].replace('/', '.') if self.superclass.split('.')[-1] == 'Object': self.superclass = None if self.superclass is not None: self.prototype += ' extends %s' % self.superclass if self.interfaces is not None: self.interfaces = self.interfaces[1:-1].split(' ') self.prototype += ' implements %s' % ', '.join( [n[1:-1].replace('/', '.') for n in self.interfaces]) print '%s {\n' % self.prototype for field in self.fields.values(): access = [ util.ACCESS_FLAGS_FIELDS.get(flag) for flag in util.ACCESS_FLAGS_FIELDS if flag & field.get_access_flags() ] f_type = util.get_type(field.get_descriptor()) name = field.get_name() print ' %s %s %s;\n' % (' '.join(access), f_type, name) for klass in self.subclasses.values(): klass.show_source() for num, method in self.methods.iteritems(): method.show_source() print '}\n'
def __init__(self, methanalysis): self.method = methanalysis.get_method() self.metha = methanalysis self.name = self.method.get_name() self.lparams = [] self.basic_blocks = [bb for bb in methanalysis.basic_blocks.get()] self.var_to_name = {} self.writer = None access = self.method.get_access_flags() self.access = [flag for flag in util.ACCESS_FLAGS_METHODS if flag & access] desc = self.method.get_descriptor() self.type = util.get_type(desc.split(')')[-1]) self.params_type = util.get_params_type(desc) self.exceptions = methanalysis.exceptions.exceptions code = self.method.get_code() if code is None: util.log('No code : %s %s' % (self.name, self.method.get_class_name()), 'debug') else: start = code.registers_size - code.ins_size if 0x8 not in self.access: self.var_to_name[start] = ThisParam(start, self.name) self.lparams.append(start) start += 1 num_param = 0 for ptype in self.params_type: param = start + num_param self.lparams.append(param) self.var_to_name.setdefault(param, Param(param, ptype)) num_param += util.get_type_size(ptype)
def parse(self, program=SimpleProgram()): cb = ClauseBuilder(self.__triple_mode) term_dict = dict() for row in self.__data: for triple in row: if term_dict.get(triple[1]) is None: term_dict[triple[1]] = get_type(triple[1]) if term_dict.get(triple[0]) is None: term_dict[triple[0]] = get_type(triple[0]) if term_dict.get(triple[2]) is None: term_dict[triple[2]] = get_type(triple[2]) pred = term_dict[triple[1]] subj = term_dict[triple[0]] obj = term_dict[triple[2]] program += cb.get_clause(subj, pred, obj) return program
def fwmkeys(self, prefix, max_=-1, as_raw=True): """Get forward matching string keys in a hash database object.""" (c_prefix, c_prefix_len) = util.serialize(prefix, as_raw) tclist_objs = tc.hdb_fwmkeys(self.db, c_prefix, c_prefix_len, max_) if not tclist_objs: raise tc.TCException(tc.hdb_errmsg(tc.hdb_ecode(self.db))) as_type = util.get_type(prefix, as_raw) return util.deserialize_tclist(tclist_objs, as_type)
def mv(self, source, target=None): st = get_type(source) tt = get_type(target) if target is None: target = '' if os.path.basename(target) == '': target = target + os.path.basename(source) if st in ['shared', 'unit'] and tt in ['shared', 'unit']: source = source.replace('shared://', self.path_to_shared) target = target.replace('shared://', self.path_to_shared) return BashCommand('cp', [source, target]) else: raise NotImplementedError( 'moving from `%s` to `%s` is not implemented yet.' % (st, tt))
def makedir(self, source): st = get_type(source) if st in ['shared', 'unit']: source = source.replace('shared://', self.path_to_shared) return BashCommand('mkdir', [source]) else: raise NotImplementedError( 'makedir in `%s` is not implemented yet.' % st)
def remove(self, source): st = get_type(source) if st in ['shared', 'unit']: source = source.replace('shared://', self.path_to_shared) return BashCommand('rm', [source]) else: raise NotImplementedError( 'deleting from `%s` is not implemented yet.' % st)
def fwmkeys(self, prefix, max_=-1, as_raw=True): """Get forward matching string keys in an abstract database object.""" (c_prefix, c_prefix_len) = util.serialize(prefix, as_raw) tclist_objs = tc.adb_fwmkeys(self.db, c_prefix, c_prefix_len, max_) if not tclist_objs: self._raise('Error forward matching string keys in an abstract ' \ 'database object.') as_type = util.get_type(prefix, as_raw) return util.deserialize_tclist(tclist_objs, as_type)
def has_key(self, key, raw_key=False): """Return True if B+ tree database object has the key.""" cursor = Cursor(self.db) result = False try: cursor.jump(key, raw_key) except KeyError: pass else: if cursor.key(util.get_type(key, raw_key)) == key: result = True finally: cursor.close() return result
def asm2mc(ops): machine_code = [] for i in range(len(ops)): # checking for hexa nums using int() which return an exception if not a number if (len(ops[i]) == 1): try: num = int(ops[i][0], 16) num = (32 - len(bin(num)) + 2) * '0' + bin(num).replace( "0b", "") machine_code.append(num[16:]) machine_code.append(num[:16]) except: # if it returns an exception then it's a no operand instruction opcode = util.get_opcode(ops[i][0]) if (len(op_types[opcode]) == 0): machine_code.append(opcode + '0' * (16 - len(opcode))) else: raise Exception( "Fatal Error: Operation \"{}\" has {} operands, {} was entered" .format(ops[i][0], len(op_types[opcode]), str(0))) else: # if it's more than one word if (ops[i][0].lower() == ".org"): # checking if it's a .org for i in range(int(ops[i][1], 16) - len(machine_code)): # fill the hole between the desired address and current address with zeros machine_code.append("0100000000000000") else: # else it's an instruction opcode = util.get_opcode(ops[i][0]) gt_types = op_types[opcode] if (len(gt_types) == len(ops[i]) - 1): for idx in range(len(ops[i]) - 1): if (util.get_type(ops[i][idx + 1]) != gt_types[idx]): raise Exception( "Fatal Error: Entered operand for operation \"{}\": \"{}\" is wrong" .format(ops[i][0], ops[i][idx + 1])) else: raise Exception( "Fatal Error: Operation \"{}\" has {} operands, {} was entered" .format(ops[i][0], len(op_types[opcode]), len(ops[i]) - 1)) mc = util.get_machine_code(ops[i]) if (len(mc) == 16): machine_code.append(mc) elif (len(mc) == 32): machine_code.append(mc[:16]) machine_code.append(mc[16:]) return machine_code
def initialize_parser(): session_parser.set_defaults(func=None, parser=session_parser) command_parsers = session_parser.add_subparsers() from sessionCommands import commands for command in commands: cmd_parser = command_parsers.add_parser(command["name"], **command["properties"]) if command.get("arguments"): for argument in command["arguments"]: prop_type = argument["properties"].get("type") if prop_type: argument["properties"]["type"] = util.get_type(prop_type) cmd_parser.add_argument(argument["name"], **argument["properties"]) cmd_parser.set_defaults( func=globals().get(command.get("function", command["name"])))
def range(self, keya=None, inca=True, keyb=None, incb=True, max_=-1, as_raw=True): """Get keys of ranged records in a B+ tree database object.""" (c_keya, c_keya_len) = util.serialize(keya, as_raw) (c_keyb, c_keyb_len) = util.serialize(keyb, as_raw) tclist_objs = tc.bdb_range(self.db, c_keya, c_keya_len, inca, c_keyb, c_keyb_len, incb, max_) if not tclist_objs: raise tc.TCException(tc.bdb_errmsg(tc.bdb_ecode(self.db))) as_type = util.get_type(keya, as_raw) return util.deserialize_tclist(tclist_objs, as_type)
def __init__(self, methanalysis): self.method = methanalysis.get_method() self.metha = methanalysis self.name = self.method.get_name() self.lparams = [] self.basic_blocks = [bb for bb in methanalysis.basic_blocks.get()] self.var_to_name = {} self.writer = None access = self.method.get_access_flags() self.access = [ flag for flag in util.ACCESS_FLAGS_METHODS if flag & access ] desc = self.method.get_descriptor() self.type = util.get_type(desc.split(')')[-1]) self.params_type = util.get_params_type(desc) self.exceptions = methanalysis.exceptions.exceptions code = self.method.get_code() if code is None: util.log( 'No code : %s %s' % (self.name, self.method.get_class_name()), 'debug') else: start = code.registers_size - code.ins_size if 0x8 not in self.access: self.var_to_name[start] = ThisParam(start, self.name) self.lparams.append(start) start += 1 num_param = 0 for ptype in self.params_type: param = start + num_param self.lparams.append(param) self.var_to_name.setdefault(param, Param(param, ptype)) num_param += util.get_type_size(ptype)
def visit_new_array(self, atype, size): self.write('new %s[' % get_type(atype[1:])) size.visit(self) self.write(']')
def path_on_resource(self): lt = get_type(self.location) if lt in ['unit', 'shared']: return self.location.replace('shared://', self.resource.path_to_shared)
def visit_new(self, atype): self.write("new %s" % get_type(atype))
def visit_new_array(self, atype, size): self.write("new %s[" % get_type(atype[1:])) size.visit(self) self.write("]")
def visit_new(self, atype): self.write('new %s' % get_type(atype))
def get_type(): response = jsonify({'type': util.get_type()}) response.headers.add('Access-Control-Allow-Origin', '*') return response