def calc_static_field_slot_ids(clazz: Class): slot_id = 0 for field in clazz.fields: if field.is_static(): field.slot_id = slot_id slot_id += 1 clazz.static_slot_count = slot_id
def parse_class(data): from classfile.ClassFile import ClassFile class_file = ClassFile() cf, err = class_file.parse(data) if err: print(err) raise RuntimeError("java.lang.ClassFormatError!") else: return Class.new_class(cf)
def calc_instantce_field_slot_ids(clazz: Class): slot_id = 0 if clazz.super_class: slot_id = clazz.super_class.instance_slot_count for field in clazz.fields: if not field.is_static(): field.slot_id = slot_id slot_id += 1 # 不需要判断long和double,每一个slot可设置为一个对象 clazz.instance_slot_count = slot_id
def load_array_class(self, name): clazz = Class() clazz.access_flags = AccessFlags.ACC_PUBLIC clazz.name = name clazz.loader = self # 数组类不需要初始化,把init_started字段设置成True clazz.init_started = True # 数组类的超类是java.lang.Object clazz.super_class = self.load_class("java/lang/Object") # 并实现了java.lang.Cloneable和java.io.Serializable接口 clazz.interfaces = [ self.load_class("java/lang/Cloneable"), self.load_class("java/io/Serializable") ] self.class_map[name] = clazz return clazz
def load_primitive_class(self, class_name): """ 有3点说明:1. void和基本类型的类名就是void、int、float等。 2. 基本类型的类没有超类,也没有实现任何接口。 3. 非基本类型的类对象是通过ldc指令加载到操作数栈中的。 而基本类型的类对象,虽然在Java代码中看起来是通过字面量获取的,但是编译之后的指令并不是ldc,而是getstatic。 :param class_name: :return: """ clazz = Class() clazz.access_flags = AccessFlags.ACC_PUBLIC clazz.name = class_name clazz.loader = self clazz.init_started = True clazz.j_class = self.class_map.get('java/lang/Class').new_object() clazz.j_class.extra = clazz self.class_map[class_name] = clazz
def alloc_and_init_static_vars(clazz: Class): clazz.static_vars = Slots(clazz.static_slot_count) for field in clazz.fields: if field.is_static() and field.is_final(): ClassLoader.init_static_final_var(clazz, field)
def resolve_super_class(clazz: Class): if clazz.name != "java/lang/object" and clazz.super_class_name: clazz.super_class = clazz.loader.load_class(clazz.super_class_name)
def is_instance_of(self, clazz: Class) -> bool: return clazz.is_assignable_from(self._class)