2.HotSpot如何加载并解析class文件

向右看齐 2023-02-17 02:53 38阅读 0赞

文章目录

    • 2.1前言
    • 2.2 类如何加载
      • 第一步:双亲委派加载类,java顶层实现
      • 第二步:找到defneClass1的native方法,开始进入JVM源码
    • 常量池解析`parse_constant_pool`讲解

2.1前言

class文件在JVM整个生命周期包括了加载、验证、准备、解析、初始化、使用、卸载等7个阶段,Java层面通过ClassLoader.loadClass方法可以手动加载一个java类到虚拟机中,并返回Class类型的引用。

2.2 类如何加载

第一步:双亲委派加载类,java顶层实现

  1. protected Class<?> loadClass(String name, boolean resolve)
  2. throws ClassNotFoundException
  3. {
  4. synchronized (getClassLoadingLock(name)) {
  5. // First, check if the class has already been loaded
  6. // 首先检查是否这个类已经被加载(后续会讲是如何检查的)
  7. Class<?> c = findLoadedClass(name);
  8. if (c == null) {
  9. long t0 = System.nanoTime();
  10. try {
  11. //如果当前的ClassLoader的parent!=null,首先让parent进行加载。
  12. //如果想多进行了解,可以看双亲委派机制,这样做的目的是什么?
  13. if (parent != null) {
  14. c = parent.loadClass(name, false);
  15. } else {
  16. //如果parent则说明当前的parent是bootstrapClassLoader(是由C++实现的,所以为null)
  17. c = findBootstrapClassOrNull(name);
  18. }
  19. } catch (ClassNotFoundException e) {
  20. // ClassNotFoundException thrown if class not found
  21. // from the non-null parent class loader
  22. }
  23. // 如果类还是为null
  24. if (c == null) {
  25. // If still not found, then invoke findClass in order
  26. // to find the class.
  27. long t1 = System.nanoTime();
  28. // 一般我们继承classLoader 不会重写loadClass方法,不会打破双亲委派机制,一般都会重写findClass方法。
  29. c = findClass(name);
  30. // this is the defining class loader; record the stats
  31. sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
  32. sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
  33. sun.misc.PerfCounter.getFindClasses().increment();
  34. }
  35. }
  36. if (resolve) {
  37. resolveClass(c);
  38. }
  39. return c;
  40. }
  41. }

在findClass中调用了defineClass,顺着调用链去找,最终调用defineClass1的native方法。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aKejPEdO-1591858909752)(/Users/zhangwanyi/Library/Application Support/typora-user-images/image-20200610160840742.png)]

第二步:找到defneClass1的native方法,开始进入JVM源码

  1. NIEXPORT jclass JNICALL
  2. Java_java_lang_ClassLoader_defineClass1(JNIEnv *env,
  3. jobject loader,
  4. jstring name,
  5. jbyteArray data,
  6. jint offset,
  7. jint length,
  8. jobject pd,
  9. jstring source){
  10. //主要的方法,其余的判断赋值等省略
  11. result = JVM_DefineClassWithSource(env, utfName, loader, body, length, pd, utfSource);
  12. return result;
  13. }

JVM_DefineClassWithSource \JVM_DefineClass()\JVM_DefineClassWithSourceCond()统一实现方法:

jvm.cpp::jvm_define_class_common

  1. JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
  2. JVMWrapper2("JVM_DefineClassWithSource %s", name);
  3. //调用 jvm_define_class_common方法
  4. return jvm_define_class_common(env, name, loader, buf, len, pd, source, true, THREAD);
  5. JVM_END

`jvm.cpp::jvm_define_class_common

  1. static jclass jvm_define_class_common(JNIEnv *env,
  2. const char *name , //类名
  3. jobject loader, //
  4. const jbyte *buf,
  5. jsize len, jobject pd, const char *source,
  6. jboolean verify, TRAPS) {
  7. if (source == NULL) source = "__JVM_DefineClass__";
  8. ///部分代码省略
  9. JavaThread* jt = (JavaThread*) THREAD;
  10. if (UsePerfData) {
  11. ClassLoader::perf_app_classfile_bytes_read()->inc(len);
  12. }
  13. // Since exceptions can be thrown, class initialization can take place
  14. // if name is NULL no check for class name in .class stream has to be made.
  15. // 检查name为null,则可以初始化,因此无需检查.class中的类名
  16. TempNewSymbol class_name = NULL;
  17. if (name != NULL) {
  18. const int str_len = (int)strlen(name);
  19. // 检查str_len长度大于(1 << 16)-1 =>65535 主要是全限定名不支持大于65535,超过则 抛出NoClassDefFoundError
  20. if (str_len > Symbol::max_length()) {
  21. // It's impossible to create this class; the name cannot fit
  22. // into the constant pool.
  23. THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
  24. }
  25. // 创建一个Symbol用于存储全限定名
  26. class_name = SymbolTable::new_symbol(name, str_len, CHECK_NULL);
  27. }
  28. ResourceMark rm(THREAD);
  29. //类流文件指向source地址,读取相关信息
  30. ClassFileStream st((u1*) buf, len, (char *)source);
  31. Handle class_loader (THREAD, JNIHandles::resolve(loader));
  32. if (UsePerfData) {
  33. is_lock_held_by_thread(class_loader,
  34. ClassLoader::sync_JVMDefineClassLockFreeCounter(),
  35. THREAD);
  36. }
  37. Handle protection_domain (THREAD, JNIHandles::resolve(pd));
  38. //解析类文件并验证 重点方法,并生成Kiass文件
  39. Klass* k = SystemDictionary::resolve_from_stream(class_name, class_loader,
  40. protection_domain, &st,
  41. verify != 0,
  42. CHECK_NULL);
  43. return (jclass) JNIHandles::make_local(env, k->java_mirror());
  44. }

进一步进入 SystemDictionary::resolve_from_stream ,里面最后调用了ClassFileParser::parseClassFile,该方法用于解析class文件,里面代码非常长,我们重点讲解,要有耐心看完!

以下要对class类结构十分熟悉,如果不清楚,请先看文章:

https://blog.csdn.net/qq\_31430665/article/details/106281119 文章讲解《class文件解析,官方直译》

  1. instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name,
  2. ClassLoaderData* loader_data,
  3. Handle protection_domain,
  4. KlassHandle host_klass,
  5. GrowableArray<Handle>* cp_patches,
  6. TempNewSymbol& parsed_name,
  7. bool verify,
  8. TRAPS) {
  9. JvmtiCachedClassFileData *cached_class_file = NULL;
  10. Handle class_loader(THREAD, loader_data->class_loader());
  11. bool has_default_methods = false;
  12. bool declares_default_methods = false;
  13. ResourceMark rm(THREAD);
  14. ClassFileStream* cfs = stream();
  15. JavaThread* jt = (JavaThread*) THREAD;
  16. PerfClassTraceTime ctimer(ClassLoader::perf_class_parse_time(),
  17. ClassLoader::perf_class_parse_selftime(),
  18. NULL,
  19. jt->get_thread_stat()->perf_recursion_counts_addr(),
  20. jt->get_thread_stat()->perf_timers_addr(),
  21. PerfClassTraceTime::PARSE_CLASS);
  22. init_parsed_class_attributes(loader_data);
  23. if (JvmtiExport::should_post_class_file_load_hook()) {
  24. // Get the cached class file bytes (if any) from the class that
  25. // is being redefined or retransformed. We use jvmti_thread_state()
  26. // instead of JvmtiThreadState::state_for(jt) so we don't allocate
  27. // a JvmtiThreadState any earlier than necessary. This will help
  28. // avoid the bug described by 7126851.
  29. JvmtiThreadState *state = jt->jvmti_thread_state();
  30. if (state != NULL) {
  31. KlassHandle *h_class_being_redefined =
  32. state->get_class_being_redefined();
  33. if (h_class_being_redefined != NULL) {
  34. instanceKlassHandle ikh_class_being_redefined =
  35. instanceKlassHandle(THREAD, (*h_class_being_redefined)());
  36. cached_class_file = ikh_class_being_redefined->get_cached_class_file();
  37. }
  38. }
  39. unsigned char* ptr = cfs->buffer();
  40. unsigned char* end_ptr = cfs->buffer() + cfs->length();
  41. JvmtiExport::post_class_file_load_hook(name, class_loader(), protection_domain,
  42. &ptr, &end_ptr, &cached_class_file);
  43. if (ptr != cfs->buffer()) {
  44. // JVMTI agent has modified class file data.
  45. // Set new class file stream using JVMTI agent modified
  46. // class file data.
  47. cfs = new ClassFileStream(ptr, end_ptr - ptr, cfs->source());
  48. set_stream(cfs);
  49. }
  50. }
  51. _host_klass = host_klass;
  52. _cp_patches = cp_patches;
  53. instanceKlassHandle nullHandle;
  54. // Figure out whether we can skip format checking (matching classic VM behavior)
  55. // 是否可以跳过验证,DumpSharedSpaces:共享的Metaspace空间dump到一个文件中
  56. if (DumpSharedSpaces) {
  57. // verify == true means it's a 'remote' class (i.e., non-boot class)
  58. // Verification decision is based on BytecodeVerificationRemote flag
  59. // for those classes.
  60. // BytecodeVerificationRemote 为 true
  61. // BytecodeVerificationLocal 为 false
  62. _need_verify = (verify) ? BytecodeVerificationRemote :
  63. BytecodeVerificationLocal;
  64. } else {
  65. // 如果 class_loader==null 或者verify=false 的时候 则不需要验证,即_need_verify=false
  66. _need_verify = Verifier::should_verify_for(class_loader(), verify=false 的时候 );
  67. }
  68. // Set the verify flag in stream
  69. cfs->set_verify(_need_verify);
  70. // Save the class file name for easier error message printing.
  71. // 保存类文件名,以便更轻松地打印错误消息。
  72. _class_name = (name != NULL) ? name : vmSymbols::unknown_class_name();
  73. cfs->guarantee_more(8, CHECK_(nullHandle)); // magic, major, minor
  74. // Magic value
  75. // 获取magic 固定值:0xCAFEBABE
  76. u4 magic = cfs->get_u4_fast();
  77. guarantee_property(magic == JAVA_CLASSFILE_MAGIC,//0xCAFEBABE
  78. "Incompatible magic value %u in class file %s",
  79. magic, CHECK_(nullHandle));
  80. // Version numbers
  81. // 获取版本 minor_version=0,暂时没用到这个值
  82. // major_version 为jdk版本,如jdk8 表示0X0034->52 jdk7->51 jdk6 ->50 jdk5->49
  83. u2 minor_version = cfs->get_u2_fast();
  84. u2 major_version = cfs->get_u2_fast();
  85. if (DumpSharedSpaces && major_version < JAVA_1_5_VERSION) {
  86. ResourceMark rm;
  87. warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
  88. major_version, minor_version, name->as_C_string());
  89. Exceptions::fthrow(
  90. THREAD_AND_LOCATION,
  91. vmSymbols::java_lang_UnsupportedClassVersionError(),
  92. "Unsupported major.minor version for dump time %u.%u",
  93. major_version,
  94. minor_version);
  95. }
  96. // Check version numbers - we check this even with verifier off
  97. // 检查版本,
  98. if (!is_supported_version(major_version, minor_version)) {
  99. if (name == NULL) {
  100. Exceptions::fthrow(
  101. THREAD_AND_LOCATION,
  102. vmSymbols::java_lang_UnsupportedClassVersionError(),
  103. "Unsupported class file version %u.%u, "
  104. "this version of the Java Runtime only recognizes class file versions up to %u.%u",
  105. major_version,
  106. minor_version,
  107. JAVA_MAX_SUPPORTED_VERSION,
  108. JAVA_MAX_SUPPORTED_MINOR_VERSION);
  109. } else {
  110. ResourceMark rm(THREAD);
  111. Exceptions::fthrow(
  112. THREAD_AND_LOCATION,
  113. vmSymbols::java_lang_UnsupportedClassVersionError(),
  114. "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
  115. "this version of the Java Runtime only recognizes class file versions up to %u.%u",
  116. name->as_C_string(),
  117. major_version,
  118. minor_version,
  119. JAVA_MAX_SUPPORTED_VERSION,
  120. JAVA_MAX_SUPPORTED_MINOR_VERSION);
  121. }
  122. return nullHandle;
  123. }
  124. _major_version = major_version;
  125. _minor_version = minor_version;
  126. // Check if verification needs to be relaxed for this class file
  127. // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
  128. // 是否放松验证?
  129. _relax_verify = Verifier::relax_verify_for(class_loader());
  130. // Constant pool
  131. // 解析常量池,常量池中有14种常量,后面仔细讲解,这里分别对常量进行进行流解析,并且分配空间
  132. constantPoolHandle cp = parse_constant_pool(CHECK_(nullHandle));
  133. //获取常量池中的length
  134. int cp_size = cp->length();
  135. cfs->guarantee_more(8, CHECK_(nullHandle)); // flags, this_class, super_class, infs_len
  136. // Access flags
  137. AccessFlags access_flags;
  138. // 获取到类访问修饰符,比如作用域/可变性/继承/接口类型/是否用户代码生成等
  139. // 看代码可知 JVM_RECOGNIZED_CLASS_MODIFIERS = 二进制 0111 0110 0011 0001 16进制7631
  140. jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
  141. // 如果有JVM_ACC_INTERFACE 修饰,
  142. // 版本小于6 并且 有 JVM_ACC_INTERFACE状态
  143. if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
  144. // Set abstract bit for old class files for backward compatibility
  145. // 6版本以前没有INTERFACE 中都是采用 ABSTRACT 类的形式
  146. flags |= JVM_ACC_ABSTRACT;
  147. }
  148. verify_legal_class_modifiers(flags, CHECK_(nullHandle));
  149. access_flags.set_flags(flags);
  150. // This class and superclass
  151. // 获取 this_class_index 的index
  152. u2 this_class_index = cfs->get_u2_fast();
  153. check_property(
  154. valid_cp_range(this_class_index, cp_size) &&
  155. cp->tag_at(this_class_index).is_unresolved_klass(),
  156. "Invalid this class index %u in constant pool in class file %s",
  157. this_class_index, CHECK_(nullHandle));
  158. Symbol* class_name = cp->unresolved_klass_at(this_class_index);
  159. assert(class_name != NULL, "class_name can't be null");
  160. // It's important to set parsed_name *before* resolving the super class.
  161. // (it's used for cleanup by the caller if parsing fails)
  162. parsed_name = class_name;
  163. // parsed_name is returned and can be used if there's an error, so add to
  164. // its reference count. Caller will decrement the refcount.
  165. // 自增引用数
  166. parsed_name->increment_refcount();
  167. // Update _class_name which could be null previously to be class_name
  168. _class_name = class_name;
  169. // Don't need to check whether this class name is legal or not.
  170. // It has been checked when constant pool is parsed.
  171. // However, make sure it is not an array type.
  172. // 无需检查其他的,只要保证不是数组就可以。其他项在常量池的时候已经被解析过了
  173. if (_need_verify) {
  174. guarantee_property(class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
  175. "Bad class name in class file %s",
  176. CHECK_(nullHandle));
  177. }
  178. Klass* preserve_this_klass; // for storing result across HandleMark
  179. -------------------------------可忽略-------------------------------
  180. // release all handles when parsing is done
  181. { HandleMark hm(THREAD);
  182. // Checks if name in class file matches requested name
  183. if (name != NULL && class_name != name) {
  184. ResourceMark rm(THREAD);
  185. Exceptions::fthrow(
  186. THREAD_AND_LOCATION,
  187. vmSymbols::java_lang_NoClassDefFoundError(),
  188. "%s (wrong name: %s)",
  189. name->as_C_string(),
  190. class_name->as_C_string()
  191. );
  192. return nullHandle;
  193. }
  194. if (TraceClassLoadingPreorder) {
  195. tty->print("[Loading %s", (name != NULL) ? name->as_klass_external_name() : "NoName");
  196. if (cfs->source() != NULL) tty->print(" from %s", cfs->source());
  197. tty->print_cr("]");
  198. }
  199. #if INCLUDE_CDS
  200. if (DumpLoadedClassList != NULL && cfs->source() != NULL && classlist_file->is_open()) {
  201. // Only dump the classes that can be stored into CDS archive
  202. if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
  203. if (name != NULL) {
  204. ResourceMark rm(THREAD);
  205. classlist_file->print_cr("%s", name->as_C_string());
  206. classlist_file->flush();
  207. }
  208. }
  209. }
  210. #endif
  211. -------------------------------可忽略-------------------------------
  212. //获取super_class
  213. u2 super_class_index = cfs->get_u2_fast();
  214. //从 JVM_CONSTANT_Class 常量池里获取
  215. instanceKlassHandle super_klass = parse_super_class(super_class_index,
  216. CHECK_NULL);
  217. // Interfaces count
  218. u2 itfs_len = cfs->get_u2_fast();
  219. // 开始解析interfaces 后面会仔细讲解
  220. Array<Klass*>* local_interfaces =parse_interfaces(itfs_len, protection_domain, _class_name, &has_default_methods, CHECK_(nullHandle));
  221. u2 java_fields_count = 0;
  222. // Fields (offsets are filled in later)
  223. FieldAllocationCount fac;
  224. // 开始解析fields 后面会仔细讲解
  225. Array<u2>* fields = parse_fields(class_name,
  226. access_flags.is_interface(),
  227. &fac, &java_fields_count,
  228. CHECK_(nullHandle));
  229. // Methods
  230. // 进行Methods解析 后面会仔细讲解
  231. bool has_final_method = false;
  232. AccessFlags promoted_flags;
  233. promoted_flags.set_flags(0);
  234. Array<Method*>* methods = parse_methods(access_flags.is_interface(),
  235. &promoted_flags,
  236. &has_final_method,
  237. &declares_default_methods,
  238. CHECK_(nullHandle));
  239. // 是否声明了默认的方法 (default 关键字,接口里支持)
  240. if (declares_default_methods) {
  241. has_default_methods = true;
  242. }
  243. // Additional attributes
  244. // 属性解析 后面会仔细讲解
  245. ClassAnnotationCollector parsed_annotations;
  246. parse_classfile_attributes(&parsed_annotations, CHECK_(nullHandle));
  247. // Finalize the Annotations metadata object,
  248. // now that all annotation arrays have been created.
  249. // 创建注解
  250. create_combined_annotations(CHECK_(nullHandle));
  251. // Make sure this is the end of class file stream
  252. guarantee_property(cfs->at_eos(), "Extra bytes at the end of class file %s", CHECK_(nullHandle));
  253. // We check super class after class file is parsed and format is checked
  254. if (super_class_index > 0 && super_klass.is_null()) {
  255. Symbol* sk = cp->klass_name_at(super_class_index);
  256. if (access_flags.is_interface()) {
  257. // Before attempting to resolve the superclass, check for class format
  258. // errors not checked yet.
  259. guarantee_property(sk == vmSymbols::java_lang_Object(),
  260. "Interfaces must have java.lang.Object as superclass in class file %s",
  261. CHECK_(nullHandle));
  262. }
  263. Klass* k = SystemDictionary::resolve_super_or_fail(class_name, sk,
  264. class_loader,
  265. protection_domain,
  266. true,
  267. CHECK_(nullHandle));
  268. KlassHandle kh (THREAD, k);
  269. super_klass = instanceKlassHandle(THREAD, kh());
  270. }
  271. if (super_klass.not_null()) {
  272. if (super_klass->has_default_methods()) {
  273. has_default_methods = true;
  274. }
  275. if (super_klass->is_interface()) {
  276. ResourceMark rm(THREAD);
  277. Exceptions::fthrow(
  278. THREAD_AND_LOCATION,
  279. vmSymbols::java_lang_IncompatibleClassChangeError(),
  280. "class %s has interface %s as super class",
  281. class_name->as_klass_external_name(),
  282. super_klass->external_name()
  283. );
  284. return nullHandle;
  285. }
  286. // Make sure super class is not final
  287. if (super_klass->is_final()) {
  288. THROW_MSG_(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class", nullHandle);
  289. }
  290. }
  291. // save super klass for error handling.
  292. // 保存super类,为了做错误处理
  293. _super_klass = super_klass;
  294. // Compute the transitive list of all unique interfaces implemented by this class
  295. // 通过super_klass 和 local_interfaces接口传递的接口
  296. _transitive_interfaces =
  297. compute_transitive_interfaces(super_klass, local_interfaces, CHECK_(nullHandle));
  298. // sort methods
  299. // 对类进行排序
  300. intArray* method_ordering = sort_methods(methods);
  301. // promote flags from parse_methods() to the klass' flags
  302. access_flags.add_promoted_flags(promoted_flags.as_int());
  303. // Size of Java vtable (in words)
  304. int vtable_size = 0;
  305. int itable_size = 0;
  306. int num_miranda_methods = 0;
  307. GrowableArray<Method*> all_mirandas(20);
  308. klassVtable::compute_vtable_size_and_num_mirandas(
  309. &vtable_size, &num_miranda_methods, &all_mirandas, super_klass(), methods,
  310. access_flags, class_loader, class_name, local_interfaces,
  311. CHECK_(nullHandle));
  312. // Size of Java itable (in words)
  313. itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(_transitive_interfaces);
  314. FieldLayoutInfo info;
  315. layout_fields(class_loader, &fac, &parsed_annotations, &info, CHECK_NULL);
  316. int total_oop_map_size2 =
  317. InstanceKlass::nonstatic_oop_map_size(info.total_oop_map_count);
  318. // Compute reference type
  319. ReferenceType rt;
  320. if (super_klass() == NULL) {
  321. rt = REF_NONE;
  322. } else {
  323. rt = super_klass->reference_type();
  324. }
  325. // We can now create the basic Klass* for this klass
  326. // 开始根据classLoader创建klass对象
  327. _klass = InstanceKlass::allocate_instance_klass(loader_data,
  328. vtable_size,
  329. itable_size,
  330. info.static_field_size,
  331. total_oop_map_size2,
  332. rt,
  333. access_flags,
  334. name,
  335. super_klass(),
  336. !host_klass.is_null(),
  337. CHECK_(nullHandle));
  338. instanceKlassHandle this_klass (THREAD, _klass);
  339. assert(this_klass->static_field_size() == info.static_field_size, "sanity");
  340. assert(this_klass->nonstatic_oop_map_count() == info.total_oop_map_count,
  341. "sanity");
  342. // Fill in information already parsed
  343. this_klass->set_should_verify_class(verify);
  344. jint lh = Klass::instance_layout_helper(info.instance_size, false);
  345. this_klass->set_layout_helper(lh);
  346. assert(this_klass->oop_is_instance(), "layout is correct");
  347. assert(this_klass->size_helper() == info.instance_size, "correct size_helper");
  348. // Not yet: supers are done below to support the new subtype-checking fields
  349. //this_klass->set_super(super_klass());
  350. this_klass->set_class_loader_data(loader_data);
  351. this_klass->set_nonstatic_field_size(info.nonstatic_field_size);
  352. this_klass->set_has_nonstatic_fields(info.has_nonstatic_fields);
  353. this_klass->set_static_oop_field_count(fac.count[STATIC_OOP]);
  354. //将类加载的信息赋值给元数据
  355. /**
  356. //cp位常量池
  357. _cp->set_pool_holder(this_klass());
  358. //设置klass的常量池
  359. this_klass->set_constants(_cp);
  360. //设置该类的field字段
  361. this_klass->set_fields(_fields, java_fields_count);
  362. //设置该类的方法
  363. this_klass->set_methods(_methods);
  364. //设置该类的内部类
  365. this_klass->set_inner_classes(_inner_classes);
  366. //设置该类的接口
  367. this_klass->set_local_interfaces(_local_interfaces);
  368. this_klass->set_transitive_interfaces(_transitive_interfaces);
  369. //设置该类的注解
  370. this_klass->set_annotations(_combined_annotations);
  371. //清除_cp,_fields,_methods,_inner_classes
  372. clear_class_metadata();
  373. */
  374. apply_parsed_class_metadata(this_klass, java_fields_count, CHECK_NULL);
  375. if (has_final_method) {
  376. this_klass->set_has_final_method();
  377. }
  378. this_klass->copy_method_ordering(method_ordering, CHECK_NULL);
  379. // The InstanceKlass::_methods_jmethod_ids cache
  380. // is managed on the assumption that the initial cache
  381. // size is equal to the number of methods in the class. If
  382. // that changes, then InstanceKlass::idnum_can_increment()
  383. // has to be changed accordingly.
  384. this_klass->set_initial_method_idnum(methods->length());
  385. this_klass->set_name(cp->klass_name_at(this_class_index));
  386. if (is_anonymous()) // I am well known to myself
  387. cp->klass_at_put(this_class_index, this_klass()); // eagerly resolve
  388. // 相关数据 赋值给klass
  389. this_klass->set_minor_version(minor_version);
  390. this_klass->set_major_version(major_version);
  391. this_klass->set_has_default_methods(has_default_methods);
  392. this_klass->set_declares_default_methods(declares_default_methods);
  393. if (!host_klass.is_null()) {
  394. assert (this_klass->is_anonymous(), "should be the same");
  395. this_klass->set_host_klass(host_klass());
  396. }
  397. // Set up Method*::intrinsic_id as soon as we know the names of methods.
  398. // (We used to do this lazily, but now we query it in Rewriter,
  399. // which is eagerly done for every method, so we might as well do it now,
  400. // when everything is fresh in memory.)
  401. if (Method::klass_id_for_intrinsics(this_klass()) != vmSymbols::NO_SID) {
  402. for (int j = 0; j < methods->length(); j++) {
  403. methods->at(j)->init_intrinsic_id();
  404. }
  405. }
  406. if (cached_class_file != NULL) {
  407. // JVMTI: we have an InstanceKlass now, tell it about the cached bytes
  408. this_klass->set_cached_class_file(cached_class_file);
  409. }
  410. // Fill in field values obtained by parse_classfile_attributes
  411. if (parsed_annotations.has_any_annotations())
  412. parsed_annotations.apply_to(this_klass);
  413. apply_parsed_class_attributes(this_klass);
  414. // Miranda methods
  415. if ((num_miranda_methods > 0) ||
  416. // if this class introduced new miranda methods or
  417. (super_klass.not_null() && (super_klass->has_miranda_methods()))
  418. // super class exists and this class inherited miranda methods
  419. ) {
  420. this_klass->set_has_miranda_methods(); // then set a flag
  421. }
  422. // Fill in information needed to compute superclasses.
  423. // 初始化super类的信息
  424. this_klass->initialize_supers(super_klass(), CHECK_(nullHandle));
  425. // Initialize itable offset tables
  426. klassItable::setup_itable_offset_table(this_klass);
  427. // Compute transitive closure of interfaces this class implements
  428. // Do final class setup
  429. fill_oop_maps(this_klass, info.nonstatic_oop_map_count, info.nonstatic_oop_offsets, info.nonstatic_oop_counts);
  430. // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
  431. set_precomputed_flags(this_klass);
  432. // reinitialize modifiers, using the InnerClasses attribute
  433. int computed_modifiers = this_klass->compute_modifier_flags(CHECK_(nullHandle));
  434. this_klass->set_modifier_flags(computed_modifiers);
  435. // check if this class can access its super class
  436. // 检查是否有super类的访问权限
  437. check_super_class_access(this_klass, CHECK_(nullHandle));
  438. // check if this class can access its superinterfaces
  439. // 检查接口是否有访问权限
  440. check_super_interface_access(this_klass, CHECK_(nullHandle));
  441. // check if this class overrides any final method
  442. // 检查是否重写了super的final方法
  443. check_final_method_override(this_klass, CHECK_(nullHandle));
  444. // check that if this class is an interface then it doesn't have static methods
  445. // 检查是否this_klass是接口,它不能有静态方法
  446. if (this_klass->is_interface()) {
  447. /* An interface in a JAVA 8 classfile can be static */
  448. // java8之后接口可以有静态方法(方法是静态&&方法名不是<cinit>)
  449. if (_major_version < JAVA_8_VERSION) {
  450. check_illegal_static_method(this_klass, CHECK_(nullHandle));
  451. }
  452. }
  453. // Allocate mirror and initialize static fields
  454. // 分配初始化的static字段
  455. // 1.必须加载Class对象实例(mirror),它用于分配空间
  456. // 2.创建java.lang.Class instance并分配空间
  457. // 3.建立 mirror(java.lang.Class instance)-》klass的关系(对应Metadata中的klass关系)
  458. // 4.判断是否是数组(普通数组/object数组)
  459. // 5.初始化mirror的field
  460. // 5.1 获取到该类的field,找到静态的变量,并初始化
  461. java_lang_Class::create_mirror(this_klass, class_loader, protection_domain,
  462. CHECK_(nullHandle));
  463. // Generate any default methods - default methods are interface methods
  464. // that have a default implementation. This is new with Lambda project.
  465. // 对default方法进行处理,有兴趣的可以看一看
  466. if (has_default_methods ) {
  467. DefaultMethods::generate_default_methods(
  468. this_klass(), &all_mirandas, CHECK_(nullHandle));
  469. }
  470. // Update the loader_data graph.
  471. // 记录this_klass的类中依赖,以便后续进行GC(这块没看明白,后续仔细讲解)
  472. record_defined_class_dependencies(this_klass, CHECK_NULL);
  473. ClassLoadingService::notify_class_loaded(InstanceKlass::cast(this_klass()),
  474. false /* not shared class */);
  475. // preserve result across HandleMark
  476. preserve_this_klass = this_klass();
  477. }
  478. // Create new handle outside HandleMark (might be needed for
  479. // Extended Class Redefinition)
  480. instanceKlassHandle this_klass (THREAD, preserve_this_klass);
  481. debug_only(this_klass->verify();)
  482. // Clear class if no error has occurred so destructor doesn't deallocate it
  483. _klass = NULL;
  484. return this_klass;
  485. }

常量池解析parse_constant_pool讲解

  1. constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) {
  2. //加载文件流
  3. ClassFileStream* cfs = stream();
  4. constantPoolHandle nullHandle;
  5. cfs->guarantee_more(3, CHECK_(nullHandle)); // length, first cp tag
  6. //获取常量池长度
  7. u2 length = cfs->get_u2_fast();
  8. guarantee_property(
  9. length >= 1, "Illegal constant pool size %u in class file %s",
  10. length, CHECK_(nullHandle));
  11. ConstantPool* constant_pool = ConstantPool::allocate(_loader_data, length,
  12. CHECK_(nullHandle));
  13. //存储constant_pool->_cp
  14. _cp = constant_pool; // save in case of errors
  15. constantPoolHandle cp (THREAD, constant_pool);
  16. // parsing constant pool entries
  17. // 重点,解析常量池中的entity
  18. // 主要是给_cp赋值,获取流中的数据
  19. parse_constant_pool_entries(length, CHECK_(nullHandle));
  20. int index = 1; // declared outside of loops for portability
  21. // first verification pass - validate cross references and fixup class and string constants
  22. // 遍历_cp中的值,分别进行校验
  23. for (index = 1; index < length; index++) { // Index 0 is unused
  24. jbyte tag = cp->tag_at(index).value();
  25. switch (tag) {
  26. case JVM_CONSTANT_Class :
  27. ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
  28. break;
  29. case JVM_CONSTANT_Fieldref :
  30. // fall through
  31. case JVM_CONSTANT_Methodref :
  32. // fall through
  33. //这块表明 JVM_CONSTANT_Fieldref、JVM_CONSTANT_Methodref、JVM_CONSTANT_InterfaceMethodref都先验证 nameAndType常量池和class_index,因为他们的结构是一样的
  34. case JVM_CONSTANT_InterfaceMethodref : {
  35. if (!_need_verify) break;
  36. int klass_ref_index = cp->klass_ref_index_at(index);
  37. int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
  38. check_property(valid_klass_reference_at(klass_ref_index),
  39. "Invalid constant pool index %u in class file %s",
  40. klass_ref_index,
  41. CHECK_(nullHandle));
  42. check_property(valid_cp_range(name_and_type_ref_index, length) &&
  43. cp->tag_at(name_and_type_ref_index).is_name_and_type(),
  44. "Invalid constant pool index %u in class file %s",
  45. name_and_type_ref_index,
  46. CHECK_(nullHandle));
  47. break;
  48. }
  49. case JVM_CONSTANT_String :
  50. ShouldNotReachHere(); // Only JVM_CONSTANT_StringIndex should be present
  51. break;
  52. case JVM_CONSTANT_Integer :
  53. break;
  54. case JVM_CONSTANT_Float :
  55. break;
  56. case JVM_CONSTANT_Long :
  57. case JVM_CONSTANT_Double :
  58. index++;
  59. // 跨过两位 index++ 因为 long和double都占用8字节,high_bytes,low_types
  60. check_property(
  61. (index < length && cp->tag_at(index).is_invalid()),
  62. "Improper constant pool long/double index %u in class file %s",
  63. index, CHECK_(nullHandle));
  64. break;
  65. case JVM_CONSTANT_NameAndType : {
  66. if (!_need_verify) break;
  67. //验证descriptor/name_index
  68. int name_ref_index = cp->name_ref_index_at(index);
  69. int signature_ref_index = cp->signature_ref_index_at(index);
  70. check_property(valid_symbol_at(name_ref_index),
  71. "Invalid constant pool index %u in class file %s",
  72. name_ref_index, CHECK_(nullHandle));
  73. check_property(valid_symbol_at(signature_ref_index),
  74. "Invalid constant pool index %u in class file %s",
  75. signature_ref_index, CHECK_(nullHandle));
  76. break;
  77. }
  78. case JVM_CONSTANT_Utf8 :
  79. break;
  80. case JVM_CONSTANT_UnresolvedClass : // fall-through
  81. case JVM_CONSTANT_UnresolvedClassInError:
  82. ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present
  83. break;
  84. case JVM_CONSTANT_ClassIndex :
  85. {
  86. int class_index = cp->klass_index_at(index);
  87. check_property(valid_symbol_at(class_index),
  88. "Invalid constant pool index %u in class file %s",
  89. class_index, CHECK_(nullHandle));
  90. cp->unresolved_klass_at_put(index, cp->symbol_at(class_index));
  91. }
  92. break;
  93. case JVM_CONSTANT_StringIndex :
  94. {
  95. int string_index = cp->string_index_at(index);
  96. check_property(valid_symbol_at(string_index),
  97. "Invalid constant pool index %u in class file %s",
  98. string_index, CHECK_(nullHandle));
  99. Symbol* sym = cp->symbol_at(string_index);
  100. cp->unresolved_string_at_put(index, sym);
  101. }
  102. break;
  103. case JVM_CONSTANT_MethodHandle :
  104. {
  105. int ref_index = cp->method_handle_index_at(index);
  106. check_property(
  107. valid_cp_range(ref_index, length) &&
  108. EnableInvokeDynamic,
  109. "Invalid constant pool index %u in class file %s",
  110. ref_index, CHECK_(nullHandle));
  111. constantTag tag = cp->tag_at(ref_index);
  112. int ref_kind = cp->method_handle_ref_kind_at(index);
  113. //reference_kind=1||2||3||4,指向CONSTANT_Fieldref_info索引,后面就这块就不细讲了,在class类结构里有
  114. switch (ref_kind) {
  115. case JVM_REF_getField:
  116. case JVM_REF_getStatic:
  117. case JVM_REF_putField:
  118. case JVM_REF_putStatic:
  119. check_property(
  120. tag.is_field(),
  121. "Invalid constant pool index %u in class file %s (not a field)",
  122. ref_index, CHECK_(nullHandle));
  123. break;
  124. case JVM_REF_invokeVirtual:
  125. case JVM_REF_newInvokeSpecial:
  126. check_property(
  127. tag.is_method(),
  128. "Invalid constant pool index %u in class file %s (not a method)",
  129. ref_index, CHECK_(nullHandle));
  130. break;
  131. case JVM_REF_invokeStatic:
  132. case JVM_REF_invokeSpecial:
  133. check_property(tag.is_method() ||
  134. ((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),
  135. "Invalid constant pool index %u in class file %s (not a method)",
  136. ref_index, CHECK_(nullHandle));
  137. break;
  138. case JVM_REF_invokeInterface:
  139. check_property(
  140. tag.is_interface_method(),
  141. "Invalid constant pool index %u in class file %s (not an interface method)",
  142. ref_index, CHECK_(nullHandle));
  143. break;
  144. default:
  145. classfile_parse_error(
  146. "Bad method handle kind at constant pool index %u in class file %s",
  147. index, CHECK_(nullHandle));
  148. }
  149. // Keep the ref_index unchanged. It will be indirected at link-time.
  150. }
  151. break;
  152. case JVM_CONSTANT_MethodType :
  153. {
  154. int ref_index = cp->method_type_index_at(index);
  155. check_property(valid_symbol_at(ref_index) && EnableInvokeDynamic,
  156. "Invalid constant pool index %u in class file %s",
  157. ref_index, CHECK_(nullHandle));
  158. }
  159. break;
  160. case JVM_CONSTANT_InvokeDynamic :
  161. {
  162. int name_and_type_ref_index = cp->invoke_dynamic_name_and_type_ref_index_at(index);
  163. check_property(valid_cp_range(name_and_type_ref_index, length) &&
  164. cp->tag_at(name_and_type_ref_index).is_name_and_type(),
  165. "Invalid constant pool index %u in class file %s",
  166. name_and_type_ref_index,
  167. CHECK_(nullHandle));
  168. // bootstrap specifier index must be checked later, when BootstrapMethods attr is available
  169. break;
  170. }
  171. default:
  172. fatal(err_msg("bad constant pool tag value %u",
  173. cp->tag_at(index).value()));
  174. ShouldNotReachHere();
  175. break;
  176. } // end of switch
  177. } // end of for
  178. if (_cp_patches != NULL) {
  179. // need to treat this_class specially...
  180. assert(EnableInvokeDynamic, "");
  181. int this_class_index;
  182. {
  183. cfs->guarantee_more(8, CHECK_(nullHandle)); // flags, this_class, super_class, infs_len
  184. u1* mark = cfs->current();
  185. u2 flags = cfs->get_u2_fast();
  186. this_class_index = cfs->get_u2_fast();
  187. cfs->set_current(mark); // revert to mark
  188. }
  189. for (index = 1; index < length; index++) { // Index 0 is unused
  190. if (has_cp_patch_at(index)) {
  191. guarantee_property(index != this_class_index,
  192. "Illegal constant pool patch to self at %d in class file %s",
  193. index, CHECK_(nullHandle));
  194. patch_constant_pool(cp, index, cp_patch_at(index), CHECK_(nullHandle));
  195. }
  196. }
  197. }
  198. if (!_need_verify) {
  199. return cp;
  200. }
  201. // second verification pass - checks the strings are of the right format.
  202. // but not yet to the other entries
  203. // 第二步验证通过,检查string的格式
  204. for (index = 1; index < length; index++) {
  205. jbyte tag = cp->tag_at(index).value();
  206. switch (tag) {
  207. case JVM_CONSTANT_UnresolvedClass: {
  208. Symbol* class_name = cp->unresolved_klass_at(index);
  209. // check the name, even if _cp_patches will overwrite it
  210. verify_legal_class_name(class_name, CHECK_(nullHandle));
  211. break;
  212. }
  213. case JVM_CONSTANT_NameAndType: {
  214. if (_need_verify && _major_version >= JAVA_7_VERSION) {
  215. int sig_index = cp->signature_ref_index_at(index);
  216. int name_index = cp->name_ref_index_at(index);
  217. Symbol* name = cp->symbol_at(name_index);
  218. Symbol* sig = cp->symbol_at(sig_index);
  219. if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {
  220. verify_legal_method_signature(name, sig, CHECK_(nullHandle));
  221. } else {
  222. verify_legal_field_signature(name, sig, CHECK_(nullHandle));
  223. }
  224. }
  225. break;
  226. }
  227. case JVM_CONSTANT_InvokeDynamic:
  228. case JVM_CONSTANT_Fieldref:
  229. case JVM_CONSTANT_Methodref:
  230. case JVM_CONSTANT_InterfaceMethodref: {
  231. int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
  232. // already verified to be utf8
  233. int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
  234. // already verified to be utf8
  235. int signature_ref_index = cp->signature_ref_index_at(name_and_type_ref_index);
  236. Symbol* name = cp->symbol_at(name_ref_index);
  237. Symbol* signature = cp->symbol_at(signature_ref_index);
  238. if (tag == JVM_CONSTANT_Fieldref) {
  239. verify_legal_field_name(name, CHECK_(nullHandle));
  240. if (_need_verify && _major_version >= JAVA_7_VERSION) {
  241. // Signature is verified above, when iterating NameAndType_info.
  242. // Need only to be sure it's the right type.
  243. if (signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
  244. throwIllegalSignature(
  245. "Field", name, signature, CHECK_(nullHandle));
  246. }
  247. } else {
  248. verify_legal_field_signature(name, signature, CHECK_(nullHandle));
  249. }
  250. } else {
  251. verify_legal_method_name(name, CHECK_(nullHandle));
  252. if (_need_verify && _major_version >= JAVA_7_VERSION) {
  253. // Signature is verified above, when iterating NameAndType_info.
  254. // Need only to be sure it's the right type.
  255. if (signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
  256. throwIllegalSignature(
  257. "Method", name, signature, CHECK_(nullHandle));
  258. }
  259. } else {
  260. verify_legal_method_signature(name, signature, CHECK_(nullHandle));
  261. }
  262. if (tag == JVM_CONSTANT_Methodref) {
  263. // 4509014: If a class method name begins with '<', it must be "<init>".
  264. assert(name != NULL, "method name in constant pool is null");
  265. unsigned int name_len = name->utf8_length();
  266. assert(name_len > 0, "bad method name"); // already verified as legal name
  267. if (name->byte_at(0) == '<') {
  268. if (name != vmSymbols::object_initializer_name()) {
  269. classfile_parse_error(
  270. "Bad method name at constant pool index %u in class file %s",
  271. name_ref_index, CHECK_(nullHandle));
  272. }
  273. }
  274. }
  275. }
  276. break;
  277. }
  278. case JVM_CONSTANT_MethodHandle: {
  279. int ref_index = cp->method_handle_index_at(index);
  280. int ref_kind = cp->method_handle_ref_kind_at(index);
  281. switch (ref_kind) {
  282. case JVM_REF_invokeVirtual:
  283. case JVM_REF_invokeStatic:
  284. case JVM_REF_invokeSpecial:
  285. case JVM_REF_newInvokeSpecial:
  286. {
  287. int name_and_type_ref_index = cp->name_and_type_ref_index_at(ref_index);
  288. int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
  289. Symbol* name = cp->symbol_at(name_ref_index);
  290. if (ref_kind == JVM_REF_newInvokeSpecial) {
  291. if (name != vmSymbols::object_initializer_name()) {
  292. classfile_parse_error(
  293. "Bad constructor name at constant pool index %u in class file %s",
  294. name_ref_index, CHECK_(nullHandle));
  295. }
  296. } else {
  297. if (name == vmSymbols::object_initializer_name()) {
  298. classfile_parse_error(
  299. "Bad method name at constant pool index %u in class file %s",
  300. name_ref_index, CHECK_(nullHandle));
  301. }
  302. }
  303. }
  304. break;
  305. // Other ref_kinds are already fully checked in previous pass.
  306. }
  307. break;
  308. }
  309. case JVM_CONSTANT_MethodType: {
  310. Symbol* no_name = vmSymbols::type_name(); // place holder
  311. Symbol* signature = cp->method_type_signature_at(index);
  312. verify_legal_method_signature(no_name, signature, CHECK_(nullHandle));
  313. break;
  314. }
  315. case JVM_CONSTANT_Utf8: {
  316. assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
  317. }
  318. } // end of switch
  319. } // end of for
  320. return cp;
  321. }

发表评论

表情:
评论列表 (有 0 条评论,38人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JVMclass文件的原理

    类加载的主要步骤分为以下3步: 1).装载.根据查找路径找到相对应的class文件,然后导入. 2).链接.链接又可以分为3个小的步骤,具体如下.     1.检查.检查

    相关 class文件过程

    1、在加载class文件的时候,JVM会先加载类中的所有静态成员( 方法,变量,静态代码块 )都加载到方法区class文件的所处静态区中 2、当把所有的静态成员加载完成之后,