`
xieyj
  • 浏览: 102678 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

ClassFileParser::parseClassFile阅读

阅读更多

     instanceKlassHandle ClassFileParser::parseClassFile(symbolHandle name,
                                                    Handle class_loader,
                                                    Handle protection_domain,
                                                    symbolHandle& parsed_name,
                                                    TRAPS)

     是一个非常复杂的方法。

     unsigned char *cached_class_file_bytes = NULL;
     jint cached_class_file_length;

     //加载的类文件流

     ClassFileStream* cfs = stream();
     // Timing
     PerfTraceTime vmtimer(ClassLoader::perf_accumulated_time());

     _has_finalizer = _has_empty_finalizer = _has_vanilla_constructor = false;

     if (JvmtiExport::should_post_class_file_load_hook()) {
                     unsigned char* ptr = cfs->buffer();
                     unsigned char* end_ptr = cfs->buffer() + cfs->length();

                     JvmtiExport::post_class_file_load_hook(name, class_loader, protection_domain,
                                           &ptr, &end_ptr,
                                           &cached_class_file_bytes,
                                           &cached_class_file_length);

                    if (ptr != cfs->buffer()) {
                             cfs = new ClassFileStream(ptr, end_ptr - ptr, cfs->source());
                             set_stream(cfs);
                     }
      }


  instanceKlassHandle nullHandle;

  // Figure out whether we can skip format checking (matching classic VM behavior)
  _need_verify = Verifier::should_verify_for(class_loader());

  // Set the verify flag in stream
  cfs->set_verify(_need_verify);

  // 类名不能为空
  _class_name = name.not_null()? name : vmSymbolHandles::unknown_class_name();

  cfs->guarantee_more(8, CHECK_(nullHandle));  // magic, major, minor
  // 文件模数,看是否java文件格式
  u4 magic = cfs->get_u4_fast();
  guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
                     "Incompatible magic value %u in class file %s",
                     magic, CHECK_(nullHandle));

  // jdk的版本号
  u2 minor_version = cfs->get_u2_fast();
  u2 major_version = cfs->get_u2_fast();

  // Check version numbers - we check this even with verifier off
  if (!is_supported_version(major_version, minor_version)) {
    if (name.is_null()) {
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
        vmSymbolHandles::java_lang_UnsupportedClassVersionError(),
        "Unsupported major.minor version %u.%u",
        major_version,
        minor_version);
    } else {
      ResourceMark rm(THREAD);
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
        vmSymbolHandles::java_lang_UnsupportedClassVersionError(),
        "%s : Unsupported major.minor version %u.%u",
        name->as_C_string(),
        major_version,
        minor_version);
    }
    return nullHandle;
  }

  _major_version = major_version;
  _minor_version = minor_version;


  // Check if verification needs to be relaxed for this class file
  // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
  _relax_verify = Verifier::relax_verify_for(class_loader());

  // 对常量池进行解析,常量池存放文件字符串、final变量值、类名、方法名等常量。
  constantPoolHandle cp = parse_constant_pool(CHECK_(nullHandle));
  int cp_size = cp->length();

  cfs->guarantee_more(8, CHECK_(nullHandle));  // flags, this_class, super_class, infs_len

  // Access flags
  AccessFlags access_flags;
 ...

    u2 super_class_index = cfs->get_u2_fast();

    //只有java.lang.Object没有超类
    if (super_class_index == 0) {
      check_property(class_name() == vmSymbols::java_lang_Object(),
                     "Invalid superclass index %u in class file %s",
                     super_class_index,
                     CHECK_(nullHandle));
    } else {
      check_property(valid_cp_range(super_class_index, cp_size) &&
                     cp->tag_at(super_class_index).is_unresolved_klass(),
                     "Invalid superclass index %u in class file %s",
                     super_class_index,
                     CHECK_(nullHandle));
      // The class name should be legal because it is checked when parsing constant pool.
      // However, make sure it is not an array type.
      if (_need_verify) {
        guarantee_property(cp->unresolved_klass_at(super_class_index)->byte_at(0) != JVM_SIGNATURE_ARRAY,
                          "Bad superclass name in class file %s", CHECK_(nullHandle));
      }
    }

    //先解析类的接口

    u2 itfs_len = cfs->get_u2_fast();
    objArrayHandle local_interfaces;
    if (itfs_len == 0) {
      local_interfaces = objArrayHandle(THREAD, Universe::the_empty_system_obj_array());
    } else {
      local_interfaces = parse_interfaces(cp, itfs_len, class_loader, protection_domain, &vmtimer, _class_name, CHECK_(nullHandle));
    }

    // Fields (offsets are filled in later)
    struct FieldAllocationCount fac = {0,0,0,0,0,0,0,0,0,0};
    objArrayHandle fields_annotations;
    typeArrayHandle fields = parse_fields(cp, access_flags.is_interface(), &fac, &fields_annotations, CHECK_(nullHandle));
    // Methods
    bool has_final_method = false;
    AccessFlags promoted_flags;
    promoted_flags.set_flags(0);
    // These need to be oop pointers because they are allocated lazily
    // inside parse_methods inside a nested HandleMark
    objArrayOop methods_annotations_oop = NULL;
    objArrayOop methods_parameter_annotations_oop = NULL;
    objArrayOop methods_default_annotations_oop = NULL;
    objArrayHandle methods = parse_methods(cp, access_flags.is_interface(),
                                           &promoted_flags,
                                           &has_final_method,
                                           &methods_annotations_oop,
                                           &methods_parameter_annotations_oop,
                                           &methods_default_annotations_oop,
                                           CHECK_(nullHandle));

    objArrayHandle methods_annotations(THREAD, methods_annotations_oop);
    objArrayHandle methods_parameter_annotations(THREAD, methods_parameter_annotations_oop);
    objArrayHandle methods_default_annotations(THREAD, methods_default_annotations_oop);

    // We check super class after class file is parsed and format is checked
    if (super_class_index > 0) {
      symbolHandle sk (THREAD, cp->klass_name_at(super_class_index));
      if (access_flags.is_interface()) {
        // Before attempting to resolve the superclass, check for class format
        // errors not checked yet.
        guarantee_property(sk() == vmSymbols::java_lang_Object(),
                           "Interfaces must have java.lang.Object as superclass in class file %s",
                           CHECK_(nullHandle));
      }

      //解析超类
      klassOop k = SystemDictionary::resolve_super_or_fail(class_name,
                                                           sk,
                                                           class_loader,
                                                           protection_domain,
                                                           true,
                                                           CHECK_(nullHandle));
      KlassHandle kh (THREAD, k);
      super_klass = instanceKlassHandle(THREAD, kh());
      if (super_klass->is_interface()) {
        ResourceMark rm(THREAD);
        Exceptions::fthrow(
          THREAD_AND_LOCATION,
          vmSymbolHandles::java_lang_IncompatibleClassChangeError(),
          "class %s has interface %s as super class",
          class_name->as_klass_external_name(),
          super_klass->external_name()
        );
        return nullHandle;
      }
      // Make sure super class is not final
      if (super_klass->is_final()) {
        THROW_MSG_(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class", nullHandle);
      }
    }

    // Compute the transitive list of all unique interfaces implemented by this class
    objArrayHandle transitive_interfaces = compute_transitive_interfaces(super_klass, local_interfaces, CHECK_(nullHandle));

    // sort methods,这里主要是用于vtable的构造和快速查找吧
    typeArrayHandle method_ordering = sort_methods(methods,
                                                   methods_annotations,
                                                   methods_parameter_annotations,
                                                   methods_default_annotations,
                                                   CHECK_(nullHandle));

    // promote flags from parse_methods() to the klass' flags
    access_flags.add_promoted_flags(promoted_flags.as_int());

    // Size of Java vtable (in words)
    int vtable_size = 0;
    int itable_size = 0;
    int num_miranda_methods = 0;

    klassVtable::compute_vtable_size_and_num_mirandas(vtable_size,
                                                      num_miranda_methods,
                                                      super_klass(),
                                                      methods(),
                                                      access_flags,
                                                      class_loader(),
                                                      class_name(),
                                                      local_interfaces());

    // Size of Java itable (in words)
    itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(transitive_interfaces);

    // Field size and offset computation
    int nonstatic_field_size = super_klass() == NULL ? 0 : super_klass->nonstatic_field_size();
    ....
    next_static_oop_offset      = (instanceKlass::header_size() +
                                  align_object_offset(vtable_size) +
                                  align_object_offset(itable_size)) * wordSize;
    next_static_double_offset   = next_static_oop_offset +
                                  (fac.static_oop_count * heapOopSize);
    ...

    //在上面进行实例大小的计算
    int instance_size;

    instance_size = align_object_size(next_nonstatic_type_offset / wordSize);

    assert(instance_size == align_object_size(instanceOopDesc::header_size() + nonstatic_field_size), "consistent layout helper value");

    // Size of non-static oop map blocks (in words) allocated at end of klass

    //oop map block主要用于gc操作
    int nonstatic_oop_map_size = compute_oop_map_size(super_klass, nonstatic_oop_map_count, first_nonstatic_oop_offset);

    // Compute reference type
    ReferenceType rt;
    if (super_klass() == NULL) {
      rt = REF_NONE;
    } else {
      rt = super_klass->reference_type();
    }

    // We can now create the basic klassOop for this klass,在这里面就有Object header

    //垃圾回收会用到的标志,都在里面,粗略来看,一个java对象在jvm里面还涉及Oject header、oop map 大小

    //vtable\itable、静态域等
    klassOop ik = oopFactory::new_instanceKlass(
                                    vtable_size, itable_size,
                                    static_field_size, nonstatic_oop_map_size,
                                    rt, CHECK_(nullHandle));
    instanceKlassHandle this_klass (THREAD, ik);

    assert(this_klass->static_field_size() == static_field_size &&
           this_klass->nonstatic_oop_map_size() == nonstatic_oop_map_size, "sanity check");

    // 填充解析好的各项值

    this_klass->set_access_flags(access_flags);
    jint lh = Klass::instance_layout_helper(instance_size, false);
    this_klass->set_layout_helper(lh);
    ...

    // 解析类的属性
    parse_classfile_attributes(cp, this_klass, CHECK_(nullHandle));

    // Make sure this is the end of class file stream
    guarantee_property(cfs->at_eos(), "Extra bytes at the end of class file %s", CHECK_(nullHandle));

    // Initialize static fields
    this_klass->do_local_static_fields(&initialize_static_field, CHECK_(nullHandle));

    // VerifyOops believes that once this has been set, the object is completely loaded.
    // Compute transitive closure of interfaces this class implements
    this_klass->set_transitive_interfaces(transitive_interfaces());

    // Fill in information needed to compute superclasses.
    this_klass->initialize_supers(super_klass(), CHECK_(nullHandle));

    // Initialize itable offset tables
    klassItable::setup_itable_offset_table(this_klass);

    // Do final class setup
    fill_oop_maps(this_klass, nonstatic_oop_map_count, nonstatic_oop_offsets, nonstatic_oop_length);

    set_precomputed_flags(this_klass);

    // reinitialize modifiers, using the InnerClasses attribute
    int computed_modifiers = this_klass->compute_modifier_flags(CHECK_(nullHandle));
    this_klass->set_modifier_flags(computed_modifiers);

    // check if this class can access its super class
    check_super_class_access(this_klass, CHECK_(nullHandle));

    // check if this class can access its superinterfaces
    check_super_interface_access(this_klass, CHECK_(nullHandle));

    // check if this class overrides any final method
    check_final_method_override(this_klass, CHECK_(nullHandle));

    // check that if this class is an interface then it doesn't have static methods
    if (this_klass->is_interface()) {
      check_illegal_static_method(this_klass, CHECK_(nullHandle));
    }

     ...

     instanceKlassHandle this_klass (THREAD, preserve_this_klass);
    return this_klass;

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics