def parse_file(self, filename): try: f = open(filename, 'r') for line in f: if line.startswith("#"): continue else: a = line.split("=") key = a[0].strip() value = a[1].strip() # print "read:", key, "->", value if cu.is_int(value): # handle ints self.parameters[key] = int(value) elif cu.is_float(value): # handle floats self.parameters[key] = float(value) elif cu.is_bool(value): # handle booleans if (value.lower() == "true"): self.parameters[key] = True else: self.parameters[key] = False else: # handle strings self.parameters[key] = value f.close() except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) except: print "Unexpected error in parameter reading:", sys.exc_info()[0] print "Reading parameters failed." print "" sys.exit()
def jumpdes_symb(self, s): if '+' in s or '-' in s: return Types.JumpDes(s.split()[0], 16) try: return Types.CallDes(self.calldes_symb(s)) except AttributeError: return None
def typesModuleData(self, typ): if typ < 2: return if self.getVal("firstModData") is None: self.findModuleData() fmd = self.getVal("firstModData") if fmd is None: return if self.typer is None: self.createTyper(typ) robase = None if typ == 4: beg, end, robase = Firstmoduledata.getTypeinfo17(fmd, self.bt_obj) self.processor = Types.TypeProcessing17(beg, end, self.bt_obj, self, robase) elif typ == 5: beg, end, robase = Firstmoduledata.getTypeinfo18(fmd, self.bt_obj) self.processor = Types.TypeProcessing17(beg, end, self.bt_obj, self, robase) elif typ == 6: beg, end, robase = Firstmoduledata.getTypeinfo18(fmd, self.bt_obj) self.processor = Types.TypeProcessing19(beg, end, self.bt_obj, self, robase) elif typ == 7: beg, end, robase = Firstmoduledata.getTypeinfo18(fmd, self.bt_obj) self.processor = Types.TypeProcessing19(beg, end, self.bt_obj, self, robase) else: beg, end = Firstmoduledata.getTypeinfo(fmd, self.bt_obj) self.processor = Types.TypeProcessing(beg, end, self.bt_obj, self) print "%x %x %x" % (beg, end, robase) for i in self.processor: pass return
def EqProperties(GRS): if GRS.GeomType != 4: GRS.LSum = 0 GRS.lmax = 0 LSigma = 0 GRS.Ncr = np.zeros(GRS.nbEl) for i in range(GRS.nbEl): sID = GRS.ls.sID[i] eID = GRS.ls.eID[i] sPt = tp.GSnodes(GRS.ns.x[sID], GRS.ns.y[sID], GRS.ns.z[sID]) ePt = tp.GSnodes(GRS.ns.x[eID], GRS.ns.y[eID], GRS.ns.z[eID]) wL = ((sPt.x - ePt.x)**2 + (sPt.y - ePt.y)**2 + (sPt.z - ePt.z)**2)**0.5 GRS.LSum = GRS.LSum + wL GRS.Ncr[i] = np.pi**2 * GRS.Es * GRS.secI / wL**2 if GRS.lmax < wL: GRS.lmax = wL GRS.Lav = GRS.LSum / GRS.nbEl # m for i in range(GRS.nbEl): wL = ((sPt.x - ePt.x)**2 + (sPt.y - ePt.y)**2 + (sPt.z - ePt.z)**2)**0.5 LSigma = LSigma + (GRS.Lav - wL)**2 LSigma = (LSigma / GRS.nbEl)**0.5 # standard deviation [m] GRS.covL = LSigma / GRS.Lav # coefficient of variation GRS.eqB = 3**0.5 / 4 / GRS.Lav * ( 3 * GRS.Es * GRS.secI + GRS.Gs * GRS.secIt) # kNm GRS.eqT = 3 * 3**0.5 / 4 * GRS.Es * GRS.secA / GRS.Lav # kN/m GRS.teq = 2 * ((3 * GRS.Es * GRS.secI + GRS.Gs * GRS.secIt) / (GRS.Es * GRS.secA))**0.5 # m GRS.Eeq = 2 / 3**0.5 * GRS.secA / GRS.Lav / GRS.teq * GRS.Es # kN/m2 rho = GRS.eqB / GRS.eqT / GRS.PlanArea # GRS.teq**2/GRS.span**2/3 #1.2566667*(GRS.secI/GRS.secA)/GRS.span**2 return rho
def test_newobj_no_parameters_initializes_int_field_to_zero(self): from VM import VM vm = VM() m = MethodDefinition() m.name = 'ctor' m.namespace = 'testnamespace.testclass' vm.methods.append(m) c = ClassDefinition() c.name = 'testclass' c.namespace = 'testnamespace' c.methods.append(m) v = Variable() v.name = 'xyz' v.type = Types.Int32 c.fieldDefinitions.append(v) t = Types.register_custom_type(c) n = newobj('instance void testnamespace.testclass::.ctor()') n.execute(vm) Types.unregister_custom_type(t) o = vm.stack.pop() self.assertEqual(o.type, t) self.assertEqual(len(o.fields), 1) self.assertEqual(o.fields[0].value, 0) self.assertEqual(len(o.fieldNames), 1) self.assertEqual(o.fieldNames[0], 'xyz')
def symbol_symb(self, s): s = s.strip() if s[0] == '*': return Types.StarDes(self.stardes_symb(s)) elif parse.call_des: return Types.CallDes(self.calldes_symb(s)) return self.jumpdes_symb(s)
def segref_symb(self, s): if ':' not in s: return None items = s.split(':') se = items[0].strip()[1:] if len(items) != 2 or se not in Types.Seg: return None return Types.SegRef( (Types.SegClass(se), self.exp_symb(items[1].strip())))
def test_execute_reference_type_parameter(self): from VM import VM vm = VM() foo = ClassDefinition() foo.namespace = 'ConsoleApplication1' foo.name = 'foo' fooType = Types.register_custom_type(foo) fooObject = ReferenceType() fooObject.name = 'f' fooObject.type = fooType fooObject.value = Variable(3333) bar = ClassDefinition() bar.namespace = 'ConsoleApplication1' bar.name = 'bar' barType = Types.register_custom_type(bar) barObject = ReferenceType() barObject.type = barType field = ReferenceType() field.name = 'f' field.type = fooType barObject.add_field(field) vm.stack.push(barObject) x = ldfld('class ConsoleApplication1.foo ConsoleApplication1.bar::f') x.execute(vm) self.assertEqual(vm.stack.count(), 1) self.assertEqual(barObject.fields[0], vm.stack.pop())
def update_track(i): if not isinstance(i, Types.TripleInstr): raise Exception('unsupported pic register pattern') lib32_helper.r = lib32_helper.index_of_reg(i[1]) lib32_helper.rv = lib32_helper.value_of_reg(i[2], i[3]) return Types.TripleInstr( (i[0], i[1], Types.Label('$_GLOBAL_OFFSET_TABLE_'), i[3], i[4]))
def Save(program, fname): data = [program.BasicStart.LowByte, program.BasicStart.HighByte] location = program.BasicStart.GetValue() for line in sorted(program.Code.keys()): linenum = Typ.Word(line) vals = [linenum.LowByte, linenum.HighByte] for tok in program.Code[line]: if tok[0] == "TOKEN": vals.append(int(tok[1])) elif tok[0] == "QUOTE": vals.append(34) elif tok[0] == "QCHAR": vals.append(int(CH.CharToNum(tok[1]))) else: for i in range(len(tok[1])): v = int(CH.CharToNum(tok[1][i])) if not 0 <= v <= 256: banana = 42 vals.append(v) vals.append(0) length = len(vals) location += length + 2 jump = Typ.Word(location) vals.insert(0, jump.HighByte) vals.insert(0, jump.LowByte) data += vals data += [0, 0] with open(fname, 'wb') as f: f.write(bytes(data)) f.close()
def const_symb(self, s): s = s.strip() if s[0] == '$': return Types.Normal(s[1:], 16) try: return Types.Point(s, 16) except ValueError: return None
def reduce_stack(self, stack, pre): sl = len(stack) stack = stack[:1] + stack[::-1][1:-1] + stack[-1:] + [pre] if sl == 2: return Types.SingleInstr(stack) elif sl == 3: return Types.DoubleInstr(stack) elif sl == 4: return Types.TripleInstr(stack) elif sl == 5: return Types.FourInstr(stack) raise Exception('Parsing error')
def SplitBeams(GRS): wn = GRS.Nb if wn == 1: wNs = GRS.nbNs - 1 wEl = 0 GRS.nbNsAll = GRS.nbNs GRS.nbElAll = GRS.nbEl GRS.nsAll.x = GRS.ns.x.copy() # copy the existing nodes GRS.nsAll.y = GRS.ns.y.copy() # copy the existing nodes GRS.nsAll.z = GRS.ns.z.copy() # copy the existing nodes GRS.lsAll.sID = GRS.ls.sID.copy() # copy the existing lines GRS.lsAll.eID = GRS.ls.eID.copy() # copy the existing lines else: wNs = GRS.nbNs wEl = 0 GRS.nbNsAll = GRS.nbNs + (wn - 1) * GRS.nbEl GRS.nbElAll = wn * GRS.nbEl wx = np.zeros(GRS.nbNsAll) wy = np.zeros(GRS.nbNsAll) wz = np.zeros(GRS.nbNsAll) wx[:GRS.nbNs:] = GRS.ns.x[::].copy( ) # first we copy the existing nodes wy[:GRS.nbNs:] = GRS.ns.y[::].copy( ) # first we copy the existing nodes wz[:GRS.nbNs:] = GRS.ns.z[::].copy( ) # first we copy the existing nodes #----------------------???????? GRS.lsAll.sID = np.zeros(GRS.nbElAll, dtype=np.int16) GRS.lsAll.eID = np.zeros(GRS.nbElAll, dtype=np.int16) for i in range(GRS.nbEl): sPtID = GRS.ls.sID[i] ePtID = GRS.ls.eID[i] sPt = tp.GSnodes(GRS.ns.x[sPtID], GRS.ns.y[sPtID], GRS.ns.z[sPtID]) ePt = tp.GSnodes(GRS.ns.x[ePtID], GRS.ns.y[ePtID], GRS.ns.z[ePtID]) for j in range(wn): if j != wn - 1: # in every step we create a new node (the new end node), except in the last step # new nodes wx[wNs] = sPt.x + (j + 1) * (ePt.x - sPt.x) / wn wy[wNs] = sPt.y + (j + 1) * (ePt.y - sPt.y) / wn wz[wNs] = sPt.z + (j + 1) * (ePt.z - sPt.z) / wn wNs += 1 # new lines if j == 0: GRS.lsAll.sID[wEl] = sPtID elif j == wn - 1: GRS.lsAll.sID[ wEl] = wNs - 1 # the node we created in the step before this else: GRS.lsAll.sID[ wEl] = wNs - 2 # the node we created in the step before this if j == wn - 1: GRS.lsAll.eID[wEl] = ePtID else: GRS.lsAll.eID[ wEl] = wNs - 1 # the node we have just created wEl += 1 GRS.nsAll.x = wx GRS.nsAll.y = wy GRS.nsAll.z = wz
def jumpdes_symb(self, s): """ Parse jump destination symbol (address or label) :param s: lexeme """ if '+' in s or '-' in s: return Types.JumpDes(s.split()[0], 16) try: return Types.CallDes(self.calldes_symb(s)) except AttributeError: return None
def pic_locating(self, i): if isinstance(i, Types.DoubleInstr): return Types.DoubleInstr((i[0], self.v_exp(i[1]), i[2], i[3])) elif isinstance(i, Types.TripleInstr): return Types.TripleInstr( (i[0], self.v_exp(i[1]), self.v_exp(i[2]), i[3], i[4])) elif isinstance(i, Types.FourInstr): return Types.FourInstr( (i[0], i[1], self.v_exp(i[2]), i[3], i[4], i[5])) return i
def const_symb(self, sym): """ Parse constant :param s: lexeme """ if self.jmp_des: return None try: if sym[0] == '#': return Types.Normal(sym[1:], 16) return Types.Point(sym, 16) except ValueError: return None
def __init__(self): self.found_entry = False self.skip_entry = False self.entry_loc = Types.Loc('', 0, True) self.last_loc = Types.Loc('', 0, True) self.entry_instr = Types.SingleInstr(('NOP', Types.Loc('', 0, True), None)) self.bb_list = [] self.bl = [] self.bl_sort = []
def __init__(self): self.looking_for_cfd = False self.text_secs = [] self.text_mem_addrs = [] self.text_mem_arr = [0] self.locs = [] # This could be a set self.up_bound = Types.Loc('', 0, True) self.low_bound = Types.Loc('', 0, True) self.trim_tbl = {} self.five_q = simple_queue()
def segref_symb(self, s): """ Parse addressing with segment register: %ds:0x10(%rax) :param s: lexeme """ if ':' not in s: return None items = s.split(':') se = items[0].strip()[1:] if len(items) != 2 or se not in Types.Seg: return None return Types.SegRef((Types.SegClass(se), self.exp_symb(items[1].strip())))
def const_symb(self, s): """ Parse constant :param s: lexeme """ s = s.strip() try: if s[0] == '$': return Types.Normal(s[1:], 16) return Types.Point(s, 16) except ValueError: return None
def symbol_symb(self, s): """ Parse branch destination symbol :param s: lexeme """ s = s.strip() if s[0] == '*': return Types.StarDes(self.stardes_symb(s)) elif self.call_des: return Types.CallDes(self.calldes_symb(s)) return self.jumpdes_symb(s)
def createTyper(self, typ): if typ == 0: self.typer = Types.Go12Types(self.structCreator) elif typ == 1: self.typer = Types.Go14Types(self.structCreator) elif typ == 2: self.typer = Types.Go15Types(self.structCreator) elif typ == 3: self.typer = Types.Go16Types(self.structCreator) elif typ == 4: self.typer = Types.Go17Types(self.structCreator)
def exp_symb(self, s): """ Parse expression symbol (constant, register, ...) :param s: lexeme """ if s[0] == '*': return Types.StarDes(self.stardes_symb(s)) symbf = [self.ptr_symb, self.reg_symb, self.assist_sym, self.const_symb, self.symbol_symb] for f in symbf: res = f(s) if res is not None: return res return Types.Label(s)
def jmpdes_symb(self, sym): """ Parse jump destination symbol (address or label): b #0x10010 :param s: lexeme """ if sym[0] == '#': if '.' in sym: return None addr = int(sym[1:], 16) & (-2) return Types.JumpDes(addr) try: return Types.CallDes(self.calldes_symb(sym)) except: return None
def binptr_symb(self, sym): """ Parse addressing with register and offset: [r1, #0x10] :param s: lexeme """ preind = sym[-1] == '!' items = sym[1:(-2 if preind else -1)].split(',') if len(items) == 2 and items[1][0] == '#': off = int(items[1][1:], 16) return Types.BinOP_PLUS((self.reg_symb(items[0]), off), preind) if off >= 0 else \ Types.BinOP_MINUS((self.reg_symb(items[0]), -off), preind) return None
def reg_symb(self, sym): """ Parse register :param s: lexeme """ if sym in Types.Reg: return Types.StarDes(Types.RegClass(sym)) \ if self.call_des or (self.indjmp_des and sym.upper() != 'LR') \ else Types.RegClass(sym) if sym[-1] == '!' and sym[:-1] in Types.Reg: # vldmia r2!, {s14} return Types.IncReg(sym) return None
def args_parsing_extracting_code(self, cpp_type, arg_name, defv, error_return, namer): reference_type = self.reference_type(cpp_type) should_write_back = reference_type in ("REF", "PTR",) py_var_name = "py__" + arg_name block = CodeBlock.CodeBlock() if cpp_type.is_ptr(): conditions = [] if defv is not None: conditions.append(py_var_name) conditions.append(py_var_name + " != Py_None") conditions.append(self.negative_checker(cpp_type, py_var_name)) block.write_error_check(" && ".join(conditions), error_return) container_type = Types.Type((cpp_type.intrinsic_type(),), 0, "Class") extractor = self.T.get_extractor_code("item", "py_item", "return false;", namer) extractor = Types.declaring_to_assigning(self.T, "item", extractor) extractor += "\nreturn true;" pyobject_type = Types.Type(("PyObject", "*",), 0, "PointerType") if should_write_back: builder = self.T.get_build_value_idecl("item", "py_item", namer) builder = Types.declaring_to_assigning(pyobject_type, "py_item", builder) builder += "\nreturn true;" else: builder = "return false;" if defv is not None: set_defv = "%s.SetDefault(%s);\n" % (arg_name, defv) else: set_defv = "" block.write_code(Code.Snippets.extract_container % { "CONTAINER_TYPE": container_type.decl(), "ITEM_TYPE": self.T.decl(), "SPACE": "" if self.T.is_ptr() else " ", "VAR_NAME": arg_name, "PY_VAR_NAME": py_var_name, "REFERENCE_TYPE": reference_type, "BUILDER": builder, "EXTRACTOR": extractor, "SET_DEFAULT_VALUE": set_defv, "ERROR_RETURN": error_return, }) return block.flush()
def process(self): try: dPB = {} dPB["result"] = {"success": True, "comment": ""} if (not self.__form.has_key("command")): raise Types.pbException("command not specified") # get dynamically discovered command map commandMap = PBcommand.__getCommandMap() # check for command handler class if (not commandMap.has_key(self.__form["command"])): raise Types.pbException("unknown command: " + self.__form["command"]) # validate existance of all required constructor parameters missingParamters = [] constructorParameters = [] if (commandMap[self.__form["command"]].requiredParameters()): for p in commandMap[ self.__form["command"]].requiredParameters(): if (not self.__form.has_key(p)): missingParamters.append(p) else: constructorParameters.append(self.__form[p]) if (len(missingParamters) > 0): raise Types.pbException("missing parameters for %s command: %s" % \ (self.__form["command"], string.join(missingParamters, ", "))) commandHandler = commandMap[self.__form["command"]]( *constructorParameters) commandHandler.setFormData(self.__form) commandParameters = {"commandName": self.__form["command"]} if (commandMap[self.__form["command"]].requiredParameters()): for p in commandMap[ self.__form["command"]].requiredParameters(): commandParameters[p] = self.__form[p] dPB["command"] = commandParameters commandRes = commandHandler.process() if (commandRes): for k in commandRes.keys(): dPB[k] = commandRes[k] # except Types.pbException,pbe: # dPB["result"]["success"] = False # dPB["result"]["comment"] = str(pbe) except Exception, e: dPB["result"]["success"] = False dPB["result"]["comment"] = str(e)
def vinst2(self, f, instr): if isinstance(instr, Types.SingleInstr): return instr elif isinstance(instr, Types.DoubleInstr): return Types.DoubleInstr( (instr[0], self.v_exp2(instr[1], instr, f, False), instr[2], instr[3])) elif isinstance(instr, Types.TripleInstr): is_test = instr[0].upper() in ['TEST', 'TESTL', 'TESTW', 'TESTB'] return Types.TripleInstr( (instr[0], self.v_exp2(instr[1], instr, f, is_test), self.v_exp2(instr[2], instr, f, is_test), instr[3], instr[4])) elif isinstance(instr, Types.FourInstr): return Types.FourInstr( (instr[0], instr[1], self.v_exp2(instr[2], instr, f, False), instr[3], instr[4], instr[5]))
def test_execute_multiple_fields(self): from VM import VM vm = VM() c = ClassDefinition() c.namespace = 'a' c.name = 'b' v = Variable() v.name = 'abc' v.type = Types.Int32 v2 = Variable() v2.name = 'def' v2.type = Types.Int32 c.fieldDefinitions.append(v2) r = ReferenceType() t = Types.register_custom_type(c) r.type = t r.add_field(v) r.add_field(v2) vm.stack.push(r) x = ldfld('int32 ConsoleApplication1.foo::def') x.execute(vm) self.assertEqual(vm.stack.count(), 1) self.assertEqual(r.fields[1], vm.stack.pop())
def __init__(self, method): self.name = "callvirt " + method parts = method.split() if parts[0] == "instance": self.instance = True parts.pop(0) else: self.instance = False self.method_type = Types.BuiltInTypes[parts[0]] self.method_namespace, self.method_name = parts[1].split("::") self.method_parameters = [] if self.method_name[0] == ".": self.method_name = self.method_name[1:] if len(parts) > 2 and parts[2] == "(": index = 3 while index < len(parts) and parts[index] != ")": type = Types.resolve_type(parts[index]) self.method_parameters.append(type) index += 1 # if not self.method_name.find('()') != -1: # if we have parameters... # parts = self.method_name.split('(') # self.method_name = parts[0] # if len(parts) > 1: # parameters = parts[1][:-1] # self.method_parameters.append(Types.resolve_type(parameters)) # self.method_name = method_name # self.method_type = method_type self.opcode = 0x28 self.value = None
def test_execute_int_parameter(self): from VM import VM vm = VM() c = ClassDefinition() c.namespace = 'a' c.name = 'b' v = Variable() v.name = 'xyz' v.type = Types.Int32 r = ReferenceType() t = Types.register_custom_type(c) r.type = t r.add_field(v) vm.stack.push(r) vm.stack.push(Variable(9876)) x = stfld('int32 a.b::xyz') x.execute(vm) self.assertEqual(vm.stack.count(), 0) self.assertEqual(r.fields[0].value, 9876)
def _fields(self): for fnode in self.root.findall("Field[@context='%s']" % self.node.attrib["id"]): access_type = Access.access_type(fnode) if access_type == Access.PRIVATE: continue if access_type == Access.PROTECTED and not self.allows_subclassing(): continue name = fnode.attrib["name"] # union if not name: continue if self.blacklist.field(self.full_name, name): full_name = self.full_name + "::" + name Session.ignored_fields.add(full_name) continue t = Types.get_type_by_id(fnode.attrib["type"], self.root) f = Argument.Argument(t, name) self.fields.append(f) if access_type == Access.PROTECTED: self.protected_nonvirtual_members.add("using %s::%s;" % ( self.full_name, f.raw_name ))
def __init__(self, method): self.name = 'call ' + method parts = method.split() if parts[0] == 'instance': self.instance = True parts.pop(0) else: self.instance = False self.method_type = Types.BuiltInTypes[parts[0]] self.method_namespace, self.method_name = parts[1].split('::') self.method_parameters = [] if self.method_name[0] == '.': self.method_name = self.method_name[1:] if len(parts) > 2 and parts[2] == '(': index = 3 while index < len(parts) and parts[index] != ')': v = Variable() v.type = Types.resolve_type(parts[index]) self.method_parameters.append(v) index += 1 # if not self.method_name.find('()') != -1: # if we have parameters... # parts = self.method_name.split('(') # self.method_name = parts[0] # if len(parts) > 1: # parameters = parts[1][:-1] # self.method_parameters.append(Types.resolve_type(parameters)) #self.method_name = method_name #self.method_type = method_type self.opcode = 0x28 self.value = None
def vinst(self, i): loc = get_loc(i) if self.skip_entry: if loc.loc_addr == self.end_loc.loc_addr: bn = 'BB_' + str(cfg.counter) cfg.counter += 1 b = Types.Bblock('', bn, loc, loc, i) self.bb_list.insert(0, b) else: self.entry_loc = loc self.entry_instr = i self.found_entry = True self.skip_entry = False self.last_loc = loc return self.help_exit( i) if Opcode_utils.is_control_transfer_op(i[0]) else i elif loc.loc_addr == self.end_loc.loc_addr: return self.help_exit(i) elif self.bb_entry(i): self.help_entry(i) return self.help_exit(i) if Opcode_utils.is_control_transfer_op( i[0]) else i elif isinstance( i, (Types.DoubleInstr, Types.SingleInstr)) and self.bb_exit(i[0]): return self.help_exit(i) self.last_loc = loc return i
def _test_fundamental(): tk = TupleAndKeywords() tk.add_parameter( Argument.Argument(Types.Type(("int", ), 1, "FundamentalType"), "foo", 10)) tk.add_parameter( Argument.Argument(Types.Type(("long int", ), 2, "FundamentalType"), "bar", 20)) tk.add_parameter( Argument.Argument(Types.Type(("int", ), 3, "FundamentalType"), "mit", 30)) print(tk.get_fmt_specifier()) print(tk.get_keywords()) print(tk.build_parser_idecl()) print(tk.build_function_signature_parameter_list())
def test_parse_class_with_class_field(self): from ParserContext import ParserContext s = ''' .class private auto ansi beforefieldinit ConsoleApplication1.bar extends [mscorlib]System.Object { .field public class ConsoleApplication1.foo f .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method bar::.ctor } // end of class ConsoleApplication1.bar''' p = ParserContext(s) cp = ClassParser() c = cp.parse(p) self.assertEqual(c.methods[0].name, 'ctor') self.assertEqual(c.methods[0].namespace, 'ConsoleApplication1.bar' ) self.assertEquals(len(c.fieldDefinitions), 1) f = c.fieldDefinitions[0] self.assertEqual(f.name, 'f') self.assertEqual(f.type, Types.resolve_type('ConsoleApplication1.foo'))
def _filter_by_return_type(mnode, blacklist, root, logset): ret = Types.get_type_by_id(mnode.attrib["returns"], root) if blacklist.return_type(ret): logset.add("[%s]" % ret.decl() + mnode.attrib["demangled"]) return True return False
def _unparse_dict(element, x): try: for key, value in x.items(): SubElement(element, 'key').text = key sub = SubElement(element, Types.get_name(value)) _unparse_value(sub, value) except: # print('dict', element, value) raise
def test_parse_class_local_with_alias(self): from ParserContext import ParserContext s = 'init ([0] class NS.C f)' p = ParserContext(s) mp = MethodParser() c = ClassDefinition() c.name = 'C' c.namespace = 'NS' Types.register_custom_type(c) locals = mp.parse_locals(p) self.assertEqual(len(locals), 1) self.assertTrue(isinstance(locals[0], ReferenceType)) self.assertEqual(locals[0].name, 'f') self.assertEqual(locals[0].alias, '0') self.assertEqual(locals[0].type.name, 'C') self.assertEqual(locals[0].type.namespace, 'NS')
def parse(self, parserContext): self.context = parserContext method = MethodDefinition() token = self.context.get_next_token() while token != BlockStart: if token == '(': self.parse_parameters(method) elif token in MethodDefinition.AttributeTypes.keys(): method.attributes.append(token) elif token in Types.BuiltInTypes: method.returnType = Types.BuiltInTypes[token] elif token == '.method': pass else: try: type = Types.resolve_type(token) method.returnType = type except: # If the type isn't found it must be the name of the method parts = token.rpartition('.') method.namespace = parts[0] method.name = parts[2] self.parse_parameters(method) token = self.context.get_next_token() token = self.context.get_next_token() while token != BlockEnd or len(self.end_block_instructions) > 0: if token == '.maxstack': method.maxStack = int(self.context.get_next_token()) elif token == '.entrypoint': method.attributes.append(token) elif token == '.locals': method.locals = self.parse_locals(self.context) elif token == '.try': self.parse_try_block(method) elif token == 'catch': self.parse_catch_block(method) elif token == BlockEnd: self.parse_end_block(method) else: from InstructionParser import InstructionParser instruction = InstructionParser().parse_instruction(token, self.context) method.instructions.append(instruction) if token == 'ret': break token = self.context.get_next_token() return method
def parse_parameters(self, method): token = self.context.get_next_token() while token != ')' and token != '': if token != '(': type = Types.resolve_type(token) name = self.context.get_next_token() v = Variable() v.type = type v.name = name method.parameters.append(v) token = self.context.get_next_token()
def parse(self, parserContext): c = ClassDefinition() while True: token = parserContext.get_next_token() if token in ClassFlags: c.flags.append(token) elif token == 'extends': c.base = parserContext.get_next_token() elif token == '.method': m = MethodParser().parse(parserContext) m.namespace = c.namespace + '.' + c.name c.methods.append(m) parserContext.methods.append(m) # fixme - should i add to both? elif token == '.field': v = Variable() visibility = parserContext.get_next_token() type = parserContext.get_next_token() # fixme - type, visibility if type == 'class': type = parserContext.get_next_token() if Types.BuiltInTypes.has_key(type): v.type = Types.BuiltInTypes[type] else: v.type = Types.resolve_type(type) name = parserContext.get_next_token() v.name = name c.fieldDefinitions.append(v) elif token == '}': break elif token != '{': fullyQualifiedName = token.split('.') c.name = fullyQualifiedName[-1] c.namespace = '.'.join(fullyQualifiedName[:-1]) Types.register_custom_type(c) return c
def parse_locals(self, context): from ParserContext import ParseException locals = [] token = context.get_next_token() if token != 'init': raise ParseException('Expected init, found ' + token) # fixme - only required for verifiable methods token = context.get_next_token() if token != '(': raise ParseException('Expected (, found' + token) token = context.get_next_token() lastToken = '' while not token.endswith(')'): v = Variable() if token.startswith('['): v.alias = token[1:-1] lastToken = token token = context.get_next_token() if token == 'class': v2 = ReferenceType() v2.alias = v.alias v2.type = Types.resolve_type(context.get_next_token()) v = v2 elif token.endswith('[]'): # array v.type = Types.Array v.arrayType = Types.resolve_type(token[:-2]) else: v.type = Types.BuiltInTypes[token] # fixme - non-builtin types locals.append(v) lastToken = token token = context.get_next_token() #if token.endswith(')'): # v.name = token[:-1] # token = ')' #else: v.name = token lastToken= token token = context.get_next_token() return locals
def __init__(self, root, node, free_function): self.name = node.attrib["name"] self.raw_sig = node.attrib["demangled"] self.free_function = free_function if not free_function: self.access = Access.access_type(node) self.virtual = node.attrib.get("virtual") == "1" self.final = node.attrib.get("final") == "1" self.pure_virtual = node.attrib.get("pure_virtual") == "1" self.static = node.attrib.get("static") == "1" self.args = TupleAndKeywords.TupleAndKeywords() for arg_node in node.findall("Argument"): self.args.add_parameter(Argument.from_xml(root, arg_node)) self.returns = Types.get_type_by_id(node.attrib["returns"], root)
def test_parse_class_registers_type(self): from ParserContext import ParserContext s = ('.class private auto ansi beforefieldinit ConsoleApplication1.bar\n' ' extends [mscorlib]System.Object\n' '{\n' '.method public hidebysig specialname rtspecialname\n' ' instance void .ctor() cil managed\n' '{\n' ' // Code size 7 (0x7)\n' ' .maxstack 8\n' ' IL_0000: ldarg.0\n' ' IL_0001: call instance void [mscorlib]System.Object::.ctor()\n' ' IL_0006: ret\n' '} // end of method foo::.ctor\n' '} // end of class ConsoleApplication1.bar\n') p = ParserContext(s) cp = ClassParser() c = cp.parse(p) self.assertEqual(Types.resolve_type('ConsoleApplication1.bar').classRef, c)
def test_execute_single_field(self): from VM import VM vm = VM() c = ClassDefinition() c.namespace = 'ConsoleApplication1' c.name = 'foo' v = Variable() v.name = 'z' v.type = Types.Int32 r = ReferenceType() t = Types.register_custom_type(c) r.type = t r.add_field(v) vm.stack.push(r) x = ldfld('int32 ConsoleApplication1.foo::z') x.execute(vm) self.assertEqual(vm.stack.count(), 1) self.assertEqual(r.fields[0], vm.stack.pop())
def __init__(self, arguments): self.name = 'newarr' self.opcode = 0x28 # fixme self.arguments = arguments self.type = Types.resolve_type(arguments)
def parse_xml(self, root, node): self.type = Types.get_type_by_id(node.attrib["type"], root) self._set_name(self._name_from_xml(node)) self.defv = self._defv_from_xml(node)
def write_args_parsing_code(self, block, namer, enable_kw, err_return, pyside_debug_name): error_handler_label = "PBPP__ARGS_PARSING_ERROR_HANDLER_" + str(block.size()) require_error_handler_label = False to_cxx = [] count0 = 0 for arg in self.args: if arg.type.cvt: block.write_code(arg.type.cvt.args_parsing_declare_vars(arg.type, arg.name, arg.defv)) goto_error_return = "goto %s;" % error_handler_label if arg.type.cvt.args_parsing_require_error_handling(arg.type): require_error_handler_label = True extracting_code = arg.type.cvt.args_parsing_extracting_code( arg.type, arg.name, arg.defv, goto_error_return, namer ) if len(extracting_code) > 0: to_cxx += extracting_code.split('\n') Session.header_jar().add_headers(arg.type.cvt.additional_headers(arg.type)) elif arg.type.is_built_in(): if arg.type.is_bool(): block.write_code("PyObject *py__%s = nullptr;" % arg.name) if arg.defv is None: extracting_code = Types.extract_as_bool("py__%s" % arg.name) to_cxx.append(arg.type.declare_var(arg.name, extracting_code)) else: to_cxx.append(arg.type.declare_var(arg.name, arg.defv)) extracting_code = (Code.Snippets.check_and_extract_as_bool % { "VAR_NAME": arg.name }).split('\n') to_cxx += extracting_code else: block.write_code(arg.type.declare_var(arg.name, arg.defv)) elif arg.type.is_ref(): if not arg.type.is_trivial(): pytype = namer.pytype(arg.type.intrinsic_type()) block.write_code("extern PyTypeObject %s;" % pytype) block.write_code("PyObject *py__%s = nullptr;" % arg.name) cpp_ptr_type = arg.type.ref_to_ptr() if arg.type.is_trivial(): capsule_ensure_reference = (Code.Snippets.capsule_ensure_reference % { "VAR_NAME": arg.name, "CAP_NAME": arg.type.decl_no_const(), "ERROR_RETURN": "goto %s;" % error_handler_label, }).split('\n') require_error_handler_label = True if arg.defv is None: to_cxx += capsule_ensure_reference init_expr = '*((%s) PyCapsule_GetPointer(py__%s, "%s"))' % ( (cpp_ptr_type.decl(), arg.name, arg.type.decl_no_const(),) ) to_cxx.append(arg.type.declare_var(arg.name, init_expr)) else: var_ptr = "py_cxx_%s_ptr" % arg.name to_cxx.append(cpp_ptr_type.declare_var(var_ptr, "&(%s)" % arg.defv)) to_cxx.append("if (py__%s) {" % arg.name) to_cxx.append(">>>") to_cxx += capsule_ensure_reference to_cxx.append(var_ptr + ' = (%s) PyCapsule_GetPointer(py__%s, "%s")' % ( cpp_ptr_type, arg.name, arg.type.decl_no_const(), )) to_cxx.append("<<<") to_cxx.append("}") to_cxx.append(arg.type.declare_var(arg.name, '*' + var_ptr)) else: # reference to class if arg.defv is None: init_expr = '*' + Code.Snippets.external_type_real_ptr % { "CLASS": arg.type.intrinsic_type(), "PYOBJ_PTR": "py__" + arg.name } to_cxx.append(arg.type.declare_var(arg.name, init_expr)) else: defv_rv = "py_cxx_%s_defv_rv" % arg.name var_ptr = "py_cxx_%s_ref2ptr" % arg.name to_cxx.append("auto &&%s = %s;" % (defv_rv, arg.defv)) to_cxx.append(cpp_ptr_type.declare_var(var_ptr, '&' + defv_rv)) to_cxx.append("if (py__%s) {" % arg.name) to_cxx.append(">>>") to_cxx.append(var_ptr + ' = ' + Code.Snippets.external_type_real_ptr % { "CLASS": arg.type.intrinsic_type(), "PYOBJ_PTR": "py__" + arg.name } + ';') to_cxx.append("<<<") to_cxx.append("}") to_cxx.append(arg.type.declare_var(arg.name, '*' + var_ptr)) elif arg.type.decl_no_const() == "PyObject *": init_expr = "nullptr" if arg.defv is not None: init_expr = arg.defv block.write_code(arg.type.declare_var(arg.name, init_expr)) else: # pointer or argument pass by value if arg.type.is_trivial(): # trivial pointer pytype = "PyCapsule_Type" block.write_code("PyObject *py__%s = nullptr;" % arg.name) extracting_code = '(%s) PyCapsule_GetPointer(py__%s, "%s")' % ( (arg.type.decl(), arg.name, arg.type.decl_no_const(),) ) to_cxx.append(arg.type.declare_var(arg.name, arg.defv if arg.defv else "nullptr")) else: pytype = namer.pytype(arg.type.intrinsic_type()) block.write_code("extern PyTypeObject %s;" % pytype) block.write_code("PyObject *py__%s = nullptr;" % arg.name) extracting_code = Code.Snippets.external_type_real_ptr % { "CLASS": arg.type.intrinsic_type(), "PYOBJ_PTR": "py__" + arg.name } if not arg.type.is_ptr(): # args pass by value extracting_code = '*' + extracting_code if not arg.defv: init_expr = extracting_code extracting_code = None # DONE processing else: init_expr = arg.defv to_cxx.append(arg.type.declare_var(arg.name, init_expr)) else: to_cxx.append(arg.type.declare_var(arg.name, "nullptr")) if arg.type.is_ptr() or arg.defv is not None: memblock = CodeBlock.CodeBlock() if arg.defv is not None: memblock.write_code("if (py__%s) {" % arg.name) memblock.indent() if arg.type.is_ptr(): memblock.write_code("if (py__%s != Py_None) {" % arg.name) memblock.indent() memblock.write_code(Code.Snippets.extract_pointer % { "VAR_NAME": arg.name, "PYTYPE": pytype, "POINTER_TYPE": arg.type.intrinsic_type(), "EXTRACTING_CODE": extracting_code, "ERROR_HANDLER": "goto %s;" % error_handler_label, }) require_error_handler_label = True memblock.unindent() memblock.write_code("}") else: memblock.write_code("%s = %s;" % (arg.name, extracting_code)) if arg.defv is not None: memblock.unindent() memblock.write_code('}') to_cxx += memblock.lines if count0 < len(to_cxx): to_cxx.append("") count0 = len(to_cxx) if enable_kw: kws = "nullptr" if not self.empty(): kws = ", ".join(['"%s"' % kw for kw in self.get_keywords()] + ["nullptr"]) block.write_code("const char *py_keywords[] = { %s };" % kws) block.append_blank_line() parser_idecl = self.build_parser_idecl(namer=namer, enable_kw=enable_kw, func_name=pyside_debug_name) block.write_error_check("!" + parser_idecl, handler=err_return, handler_label=error_handler_label if require_error_handler_label else None) block.append_blank_line() if len(to_cxx) > 0: block.write_lines(to_cxx)