1 /* 2 * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 26 #include "cds/aotClassFilter.hpp" 27 #include "cds/aotClassLocation.hpp" 28 #include "cds/aotLogging.hpp" 29 #include "cds/aotMetaspace.hpp" 30 #include "cds/archiveBuilder.hpp" 31 #include "cds/archiveUtils.hpp" 32 #include "cds/cdsConfig.hpp" 33 #include "cds/cdsProtectionDomain.hpp" 34 #include "cds/classListParser.hpp" 35 #include "cds/classListWriter.hpp" 36 #include "cds/dumpTimeClassInfo.inline.hpp" 37 #include "cds/dynamicArchive.hpp" 38 #include "cds/filemap.hpp" 39 #include "cds/heapShared.hpp" 40 #include "cds/lambdaFormInvokers.inline.hpp" 41 #include "cds/lambdaProxyClassDictionary.hpp" 42 #include "cds/runTimeClassInfo.hpp" 43 #include "cds/unregisteredClasses.hpp" 44 #include "classfile/classFileStream.hpp" 45 #include "classfile/classLoader.hpp" 46 #include "classfile/classLoaderData.inline.hpp" 47 #include "classfile/classLoaderDataGraph.hpp" 48 #include "classfile/dictionary.hpp" 49 #include "classfile/javaClasses.inline.hpp" 50 #include "classfile/symbolTable.hpp" 51 #include "classfile/systemDictionary.hpp" 52 #include "classfile/systemDictionaryShared.hpp" 53 #include "classfile/verificationType.hpp" 54 #include "classfile/vmClasses.hpp" 55 #include "classfile/vmSymbols.hpp" 56 #include "jfr/jfrEvents.hpp" 57 #include "logging/log.hpp" 58 #include "logging/logStream.hpp" 59 #include "memory/allocation.hpp" 60 #include "memory/metadataFactory.hpp" 61 #include "memory/metaspaceClosure.hpp" 62 #include "memory/oopFactory.hpp" 63 #include "memory/resourceArea.hpp" 64 #include "memory/universe.hpp" 65 #include "oops/compressedKlass.inline.hpp" 66 #include "oops/instanceKlass.hpp" 67 #include "oops/klass.inline.hpp" 68 #include "oops/objArrayKlass.hpp" 69 #include "oops/objArrayOop.inline.hpp" 70 #include "oops/oop.inline.hpp" 71 #include "oops/oopHandle.inline.hpp" 72 #include "oops/typeArrayOop.inline.hpp" 73 #include "runtime/arguments.hpp" 74 #include "runtime/handles.inline.hpp" 75 #include "runtime/java.hpp" 76 #include "runtime/javaCalls.hpp" 77 #include "runtime/mutexLocker.hpp" 78 #include "utilities/hashTable.hpp" 79 #include "utilities/stringUtils.hpp" 80 81 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_static_archive; 82 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_dynamic_archive; 83 84 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr; 85 86 // Used by NoClassLoadingMark 87 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;) 88 89 #ifdef ASSERT 90 static void check_klass_after_loading(const Klass* k) { 91 #ifdef _LP64 92 if (k != nullptr && UseCompressedClassPointers) { 93 CompressedKlassPointers::check_encodable(k); 94 } 95 #endif 96 } 97 #endif 98 99 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader( 100 Symbol* class_name, Handle class_loader, TRAPS) { 101 assert(CDSConfig::is_using_archive(), "must be"); 102 InstanceKlass* ik = find_builtin_class(class_name); 103 104 if (ik != nullptr && !ik->shared_loading_failed()) { 105 if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->defined_by_app_loader()) || 106 (SystemDictionary::is_platform_class_loader(class_loader()) && ik->defined_by_platform_loader())) { 107 SharedClassLoadingMark slm(THREAD, ik); 108 PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader); 109 Handle protection_domain = 110 CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL); 111 return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD); 112 } 113 } 114 return nullptr; 115 } 116 117 // This function is called for loading only UNREGISTERED classes 118 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name, 119 Handle class_loader, 120 Handle protection_domain, 121 const ClassFileStream* cfs, 122 TRAPS) { 123 if (!CDSConfig::is_using_archive()) { 124 return nullptr; 125 } 126 if (class_name == nullptr) { // don't do this for hidden classes 127 return nullptr; 128 } 129 if (class_loader.is_null() || 130 SystemDictionary::is_system_class_loader(class_loader()) || 131 SystemDictionary::is_platform_class_loader(class_loader())) { 132 // Do nothing for the BUILTIN loaders. 133 return nullptr; 134 } 135 136 const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary, 137 &_dynamic_archive._unregistered_dictionary, 138 class_name); 139 if (record == nullptr) { 140 return nullptr; 141 } 142 143 int clsfile_size = cfs->length(); 144 int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length()); 145 146 if (!record->matches(clsfile_size, clsfile_crc32)) { 147 return nullptr; 148 } 149 150 return acquire_class_for_current_thread(record->klass(), class_loader, 151 protection_domain, cfs, 152 THREAD); 153 } 154 155 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread( 156 InstanceKlass *ik, 157 Handle class_loader, 158 Handle protection_domain, 159 const ClassFileStream *cfs, 160 TRAPS) { 161 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 162 163 { 164 MutexLocker mu(THREAD, SharedDictionary_lock); 165 if (ik->class_loader_data() != nullptr) { 166 // ik is already loaded (by this loader or by a different loader) 167 // or ik is being loaded by a different thread (by this loader or by a different loader) 168 return nullptr; 169 } 170 171 // No other thread has acquired this yet, so give it to *this thread* 172 ik->set_class_loader_data(loader_data); 173 } 174 175 // No longer holding SharedDictionary_lock 176 // No need to lock, as <ik> can be held only by a single thread. 177 loader_data->add_class(ik); 178 179 // Get the package entry. 180 PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader); 181 182 // Load and check super/interfaces, restore unshareable info 183 InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain, 184 cfs, pkg_entry, THREAD); 185 if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) { 186 // TODO: clean up <ik> so it can be used again 187 return nullptr; 188 } 189 190 return shared_klass; 191 } 192 193 // Guaranteed to return non-null value for non-shared classes. 194 // k must not be a shared class. 195 DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) { 196 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 197 return get_info_locked(k); 198 } 199 200 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) { 201 assert_lock_strong(DumpTimeTable_lock); 202 DumpTimeClassInfo* info = _dumptime_table->get_info(k); 203 assert(info != nullptr, "must be"); 204 return info; 205 } 206 207 bool SystemDictionaryShared::should_be_excluded_impl(InstanceKlass* k, DumpTimeClassInfo* info) { 208 assert_lock_strong(DumpTimeTable_lock); 209 210 if (!info->has_checked_exclusion()) { 211 check_exclusion_for_self_and_dependencies(k); 212 assert(info->has_checked_exclusion(), "must be"); 213 } 214 215 return info->is_excluded(); 216 } 217 218 // <func> returns bool and takes a single parameter of Symbol* 219 // The return value indicates whether we want to keep on iterating or not. 220 template<typename Function> 221 void SystemDictionaryShared::iterate_verification_constraint_names(InstanceKlass* k, DumpTimeClassInfo* info, Function func) { 222 int n = info->num_verifier_constraints(); 223 bool cont; // continue iterating? 224 for (int i = 0; i < n; i++) { 225 cont = func(info->verifier_constraint_name_at(i)); 226 if (!cont) { 227 return; // early termination 228 } 229 Symbol* from_name = info->verifier_constraint_from_name_at(i); 230 if (from_name != nullptr) { 231 cont = func(from_name); 232 if (!cont) { 233 return; // early termination 234 } 235 } 236 } 237 } 238 239 // This is a table of classes that need to be checked for exclusion. 240 class SystemDictionaryShared::ExclusionCheckCandidates 241 : public HashTable<InstanceKlass*, DumpTimeClassInfo*, 15889> { 242 void add_candidate(InstanceKlass* k) { 243 if (contains(k)) { 244 return; 245 } 246 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(k)) { 247 return; 248 } 249 250 DumpTimeClassInfo* info = SystemDictionaryShared::get_info_locked(k); 251 if (info->has_checked_exclusion()) { 252 // We have check exclusion of k and all of its dependencies, so there's no need to check again. 253 return; 254 } 255 256 put(k, info); 257 258 if (!k->is_loaded()) { 259 // super types are not yet initialized for k. 260 return; 261 } 262 263 InstanceKlass* super = k->java_super(); 264 if (super != nullptr) { 265 add_candidate(super); 266 } 267 268 Array<InstanceKlass*>* interfaces = k->local_interfaces(); 269 int len = interfaces->length(); 270 for (int i = 0; i < len; i++) { 271 add_candidate(interfaces->at(i)); 272 } 273 274 InstanceKlass* nest_host = k->nest_host_or_null(); 275 if (nest_host != nullptr && nest_host != k) { 276 add_candidate(nest_host); 277 } 278 279 if (CDSConfig::is_preserving_verification_constraints()) { 280 SystemDictionaryShared::iterate_verification_constraint_names(k, info, [&] (Symbol* constraint_class_name) { 281 Klass* constraint_bottom_class = find_verification_constraint_bottom_class(k, constraint_class_name); 282 if (constraint_bottom_class != nullptr && constraint_bottom_class->is_instance_klass()) { 283 add_candidate(InstanceKlass::cast(constraint_bottom_class)); 284 } 285 return true; // Keep iterating. 286 }); 287 } 288 } 289 290 public: 291 ExclusionCheckCandidates(InstanceKlass* k) { 292 add_candidate(k); 293 } 294 }; 295 296 // A class X is excluded if check_self_exclusion() returns true for X or any of 297 // X's "exclusion dependency" classes, which include: 298 // - ik's super types 299 // - ik's nest host (if any) 300 // 301 // plus, if CDSConfig::is_preserving_verification_constraints()==true: 302 // - ik's verification constraints. These are the classes used in assignability checks 303 // when verifying ik's bytecodes. 304 // 305 // This method ensure that exclusion check is performed on X and all of its exclusion dependencies. 306 void SystemDictionaryShared::check_exclusion_for_self_and_dependencies(InstanceKlass* ik) { 307 assert_lock_strong(DumpTimeTable_lock); 308 ResourceMark rm; 309 310 // This will recursively find ik and all of its exclusion dependencies that have not yet been checked. 311 ExclusionCheckCandidates candidates(ik); 312 313 // (1) Check each class to see if it should be excluded due to its own problems 314 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) { 315 if (check_self_exclusion(k)) { 316 info->set_excluded(); 317 } 318 }); 319 320 // (2) Check each class to see if it should be excluded because of problems in a depeendency class 321 while (true) { 322 bool found_new_exclusion = false; 323 324 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) { 325 if (!info->is_excluded() && check_dependencies_exclusion(k, info)) { 326 info->set_excluded(); 327 found_new_exclusion = true; 328 } 329 }); 330 331 // Algorithm notes: 332 // 333 // The dependencies form a directed graph, possibly cyclic. Class X is excluded 334 // if it has at least one directed path that reaches class Y, where 335 // check_self_exclusion(Y) returns true. 336 // 337 // Because of the possibility of cycles in the graph, we cannot use simple 338 // recursion. Otherwise we will either never terminate, or will miss some paths. 339 // 340 // Hence, we keep doing a linear scan of the candidates until we stop finding 341 // new exclusions. 342 // 343 // In the worst case, we find one exclusion per iteration of the while loop, 344 // so the while loop gets executed O(N^2) times. However, in reality we have 345 // very few exclusions, so in most cases the while loop executes only once, and we 346 // walk each edge in the dependencies graph exactly once. 347 if (!found_new_exclusion) { 348 break; 349 } 350 } 351 candidates.iterate_all([&] (InstanceKlass* k, DumpTimeClassInfo* info) { 352 // All candidates have been fully checked, so we don't need to check them again. 353 info->set_has_checked_exclusion(); 354 }); 355 } 356 357 // Returns true so the caller can do: return warn_excluded("....."); 358 bool SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) { 359 ResourceMark rm; 360 aot_log_warning(aot)("Skipping %s: %s", k->name()->as_C_string(), reason); 361 return true; 362 } 363 364 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) { 365 while (k) { 366 if (k->name()->equals("jdk/internal/event/Event")) { 367 return true; 368 } 369 k = k->super(); 370 } 371 return false; 372 } 373 374 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) { 375 DumpTimeClassInfo* info = _dumptime_table->get(ik); 376 return (info != nullptr) ? info->is_early_klass() : false; 377 } 378 379 bool SystemDictionaryShared::check_self_exclusion(InstanceKlass* k) { 380 assert_lock_strong(DumpTimeTable_lock); 381 if (CDSConfig::is_dumping_final_static_archive() && k->defined_by_other_loaders() 382 && k->in_aot_cache()) { 383 return false; // Do not exclude: unregistered classes are passed from preimage to final image. 384 } 385 386 if (k->is_in_error_state()) { 387 return warn_excluded(k, "In error state"); 388 } 389 if (k->is_scratch_class()) { 390 return warn_excluded(k, "A scratch class"); 391 } 392 if (!k->is_loaded()) { 393 return warn_excluded(k, "Not in loaded state"); 394 } 395 if (has_been_redefined(k)) { 396 return warn_excluded(k, "Has been redefined"); 397 } 398 if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) { 399 if (k->name()->starts_with("java/lang/invoke/BoundMethodHandle$Species_")) { 400 // This class is dynamically generated by the JDK 401 if (CDSConfig::is_dumping_method_handles()) { 402 k->set_shared_classpath_index(0); 403 } else { 404 ResourceMark rm; 405 aot_log_info(aot)("Skipping %s because it is dynamically generated", k->name()->as_C_string()); 406 return true; // exclude without warning 407 } 408 } else { 409 // These are classes loaded from unsupported locations (such as those loaded by JVMTI native 410 // agent during dump time). 411 return warn_excluded(k, "Unsupported location"); 412 } 413 } 414 if (k->signers() != nullptr) { 415 // We cannot include signed classes in the archive because the certificates 416 // used during dump time may be different than those used during 417 // runtime (due to expiration, etc). 418 return warn_excluded(k, "Signed JAR"); 419 } 420 if (is_jfr_event_class(k)) { 421 // We cannot include JFR event classes because they need runtime-specific 422 // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false. 423 // There are only a small number of these classes, so it's not worthwhile to 424 // support them and make CDS more complicated. 425 return warn_excluded(k, "JFR event class"); 426 } 427 428 if (!k->is_linked()) { 429 if (has_class_failed_verification(k)) { 430 return warn_excluded(k, "Failed verification"); 431 } else if (CDSConfig::is_dumping_aot_linked_classes()) { 432 // Most loaded classes should have been speculatively linked by AOTMetaspace::link_class_for_cds(). 433 // Old classes may not be linked if CDSConfig::is_preserving_verification_constraints()==false. 434 // An unlinked class may fail to verify in AOTLinkedClassBulkLoader::init_required_classes_for_loader(), 435 // causing the JVM to fail at bootstrap. 436 return warn_excluded(k, "Unlinked class not supported by AOTClassLinking"); 437 } else if (CDSConfig::is_dumping_preimage_static_archive()) { 438 // When dumping the final static archive, we will unconditionally load and link all 439 // classes from the preimage. We don't want to get a VerifyError when linking this class. 440 return warn_excluded(k, "Unlinked class not supported by AOTConfiguration"); 441 } 442 } else { 443 if (!k->can_be_verified_at_dumptime()) { 444 // We have an old class that has been linked (e.g., it's been executed during 445 // dump time). This class has been verified using the old verifier, which 446 // doesn't save the verification constraints, so check_verification_constraints() 447 // won't work at runtime. 448 // As a result, we cannot store this class. It must be loaded and fully verified 449 // at runtime. 450 return warn_excluded(k, "Old class has been linked"); 451 } 452 } 453 454 if (UnregisteredClasses::check_for_exclusion(k)) { 455 ResourceMark rm; 456 aot_log_info(aot)("Skipping %s: used only when dumping CDS archive", k->name()->as_C_string()); 457 return true; 458 } 459 460 return false; 461 } 462 463 // Returns true if DumpTimeClassInfo::is_excluded() is true for at least one of k's exclusion dependencies. 464 bool SystemDictionaryShared::check_dependencies_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) { 465 InstanceKlass* super = k->java_super(); 466 if (super != nullptr && is_dependency_excluded(k, super, "super")) { 467 return true; 468 } 469 470 Array<InstanceKlass*>* interfaces = k->local_interfaces(); 471 int len = interfaces->length(); 472 for (int i = 0; i < len; i++) { 473 InstanceKlass* intf = interfaces->at(i); 474 if (is_dependency_excluded(k, intf, "interface")) { 475 return true; 476 } 477 } 478 479 InstanceKlass* nest_host = k->nest_host_or_null(); 480 if (nest_host != nullptr && nest_host != k && is_dependency_excluded(k, nest_host, "nest host class")) { 481 return true; 482 } 483 484 if (CDSConfig::is_preserving_verification_constraints()) { 485 bool excluded = false; 486 487 iterate_verification_constraint_names(k, info, [&] (Symbol* constraint_class_name) { 488 if (check_verification_constraint_exclusion(k, constraint_class_name)) { 489 // If one of the verification constraint class has been excluded, the assignability checks 490 // by the verifier may no longer be valid in the production run. For safety, exclude this class. 491 excluded = true; 492 return false; // terminate iteration; k will be excluded 493 } else { 494 return true; // keep iterating 495 } 496 }); 497 498 if (excluded) { 499 // At least one verification constraint class has been excluded 500 return true; 501 } 502 } 503 504 return false; 505 } 506 507 bool SystemDictionaryShared::is_dependency_excluded(InstanceKlass* k, InstanceKlass* dependency, const char* type) { 508 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(dependency)) { 509 return false; 510 } 511 DumpTimeClassInfo* dependency_info = get_info_locked(dependency); 512 if (dependency_info->is_excluded()) { 513 ResourceMark rm; 514 aot_log_warning(aot)("Skipping %s: %s %s is excluded", k->name()->as_C_string(), type, dependency->name()->as_C_string()); 515 return true; 516 } 517 return false; 518 } 519 520 bool SystemDictionaryShared::check_verification_constraint_exclusion(InstanceKlass* k, Symbol* constraint_class_name) { 521 Klass* constraint_bottom_class = find_verification_constraint_bottom_class(k, constraint_class_name); 522 if (constraint_bottom_class == nullptr) { 523 // We don't have a bottom class (constraint_class_name is a type array), or constraint_class_name 524 // has not been loaded. The latter case happens when the new verifier was checking 525 // if constraint_class_name is assignable to an interface, and found the answer without resolving 526 // constraint_class_name. 527 // 528 // Since this class is not even loaded, it surely cannot be excluded. 529 return false; 530 } else if (constraint_bottom_class->is_instance_klass()) { 531 if (is_dependency_excluded(k, InstanceKlass::cast(constraint_bottom_class), "verification constraint")) { 532 return true; 533 } 534 } else { 535 assert(constraint_bottom_class->is_typeArray_klass(), "must be"); 536 } 537 538 return false; 539 } 540 541 Klass* SystemDictionaryShared::find_verification_constraint_bottom_class(InstanceKlass* k, Symbol* constraint_class_name) { 542 Thread* current = Thread::current(); 543 Handle loader(current, k->class_loader()); 544 Klass* constraint_class = SystemDictionary::find_instance_or_array_klass(current, constraint_class_name, loader); 545 if (constraint_class == nullptr) { 546 return nullptr; 547 } 548 549 if (constraint_class->is_objArray_klass()) { 550 constraint_class = ObjArrayKlass::cast(constraint_class)->bottom_klass(); 551 } 552 553 precond(constraint_class->is_typeArray_klass() || constraint_class->is_instance_klass()); 554 return constraint_class; 555 } 556 557 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) { 558 oop class_loader = loader_data->class_loader(); 559 return (class_loader == nullptr || 560 SystemDictionary::is_system_class_loader(class_loader) || 561 SystemDictionary::is_platform_class_loader(class_loader)); 562 } 563 564 bool SystemDictionaryShared::has_platform_or_app_classes() { 565 if (FileMapInfo::current_info()->has_platform_or_app_classes()) { 566 return true; 567 } 568 if (DynamicArchive::is_mapped() && 569 FileMapInfo::dynamic_info()->has_platform_or_app_classes()) { 570 return true; 571 } 572 return false; 573 } 574 575 // The following stack shows how this code is reached: 576 // 577 // [0] SystemDictionaryShared::find_or_load_shared_class() 578 // [1] JVM_FindLoadedClass 579 // [2] java.lang.ClassLoader.findLoadedClass0() 580 // [3] java.lang.ClassLoader.findLoadedClass() 581 // [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull() 582 // [5] jdk.internal.loader.BuiltinClassLoader.loadClass() 583 // [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or 584 // jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass() 585 // 586 // AppCDS supports fast class loading for these 2 built-in class loaders: 587 // jdk.internal.loader.ClassLoaders$PlatformClassLoader 588 // jdk.internal.loader.ClassLoaders$AppClassLoader 589 // with the following assumptions (based on the JDK core library source code): 590 // 591 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to 592 // load the named class. 593 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name). 594 // [c] At this point, if we can find the named class inside the 595 // shared_dictionary, we can perform further checks (see 596 // SystemDictionary::is_shared_class_visible) to ensure that this class 597 // was loaded by the same class loader during dump time. 598 // 599 // Given these assumptions, we intercept the findLoadedClass() call to invoke 600 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from 601 // the archive for the 2 built-in class loaders. This way, 602 // we can improve start-up because we avoid decoding the classfile, 603 // and avoid delegating to the parent loader. 604 // 605 // NOTE: there's a lot of assumption about the Java code. If any of that change, this 606 // needs to be redesigned. 607 608 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class( 609 Symbol* name, Handle class_loader, TRAPS) { 610 InstanceKlass* k = nullptr; 611 if (CDSConfig::is_using_archive()) { 612 if (!has_platform_or_app_classes()) { 613 return nullptr; 614 } 615 616 if (SystemDictionary::is_system_class_loader(class_loader()) || 617 SystemDictionary::is_platform_class_loader(class_loader())) { 618 ClassLoaderData *loader_data = register_loader(class_loader); 619 Dictionary* dictionary = loader_data->dictionary(); 620 621 // Note: currently, find_or_load_shared_class is called only from 622 // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader, 623 // which are parallel-capable loaders, so a lock here is NOT taken. 624 assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required"); 625 { 626 MutexLocker mu(THREAD, SystemDictionary_lock); 627 InstanceKlass* check = dictionary->find_class(THREAD, name); 628 if (check != nullptr) { 629 return check; 630 } 631 } 632 633 k = load_shared_class_for_builtin_loader(name, class_loader, THREAD); 634 if (k != nullptr) { 635 SharedClassLoadingMark slm(THREAD, k); 636 k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL); 637 } 638 } 639 } 640 641 DEBUG_ONLY(check_klass_after_loading(k);) 642 643 return k; 644 } 645 646 class UnregisteredClassesTable : public HashTable< 647 Symbol*, InstanceKlass*, 648 15889, // prime number 649 AnyObj::C_HEAP> {}; 650 651 static UnregisteredClassesTable* _unregistered_classes_table = nullptr; 652 653 // true == class was successfully added; false == a duplicated class (with the same name) already exists. 654 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) { 655 // We don't allow duplicated unregistered classes with the same name. 656 // We only archive the first class with that name that succeeds putting 657 // itself into the table. 658 assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity"); 659 MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag); 660 Symbol* name = klass->name(); 661 if (_unregistered_classes_table == nullptr) { 662 _unregistered_classes_table = new (mtClass)UnregisteredClassesTable(); 663 } 664 bool created; 665 InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created); 666 if (created) { 667 name->increment_refcount(); 668 } 669 return (klass == *v); 670 } 671 672 InstanceKlass* SystemDictionaryShared::get_unregistered_class(Symbol* name) { 673 assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity"); 674 if (_unregistered_classes_table == nullptr) { 675 return nullptr; 676 } 677 InstanceKlass** k = _unregistered_classes_table->get(name); 678 return k != nullptr ? *k : nullptr; 679 } 680 681 void SystemDictionaryShared::copy_unregistered_class_size_and_crc32(InstanceKlass* klass) { 682 precond(CDSConfig::is_dumping_final_static_archive()); 683 precond(klass->in_aot_cache()); 684 685 // A shared class must have a RunTimeClassInfo record 686 const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary, 687 nullptr, klass->name()); 688 precond(record != nullptr); 689 precond(record->klass() == klass); 690 691 DumpTimeClassInfo* info = get_info(klass); 692 info->_clsfile_size = record->crc()->_clsfile_size; 693 info->_clsfile_crc32 = record->crc()->_clsfile_crc32; 694 } 695 696 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) { 697 assert(CDSConfig::is_dumping_archive(), "sanity"); 698 assert(!is_builtin(k), "must be unregistered class"); 699 DumpTimeClassInfo* info = get_info(k); 700 info->_clsfile_size = cfs->length(); 701 info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length()); 702 } 703 704 void SystemDictionaryShared::initialize() { 705 if (CDSConfig::is_dumping_archive()) { 706 _dumptime_table = new (mtClass) DumpTimeSharedClassTable; 707 LambdaProxyClassDictionary::dumptime_init(); 708 if (CDSConfig::is_dumping_heap()) { 709 HeapShared::init_dumping(); 710 } 711 } 712 } 713 714 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) { 715 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 716 assert(SystemDictionaryShared::class_loading_may_happen(), "sanity"); 717 DumpTimeClassInfo* info = _dumptime_table->allocate_info(k); 718 if (AOTClassFilter::is_aot_tooling_class(k)) { 719 info->set_is_aot_tooling_class(); 720 } 721 } 722 723 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) { 724 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 725 _dumptime_table->remove(k); 726 } 727 728 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) { 729 if (CDSConfig::is_dumping_archive()) { 730 remove_dumptime_info(klass); 731 } 732 733 if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) { 734 MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag); 735 if (_unregistered_classes_table != nullptr) { 736 // Remove the class from _unregistered_classes_table: keep the entry but 737 // set it to null. This ensure no classes with the same name can be 738 // added again. 739 InstanceKlass** v = _unregistered_classes_table->get(klass->name()); 740 if (v != nullptr) { 741 *v = nullptr; 742 } 743 } 744 } else { 745 assert(_unregistered_classes_table == nullptr, "must not be used"); 746 } 747 748 if (ClassListWriter::is_enabled()) { 749 ClassListWriter cw; 750 cw.handle_class_unloading((const InstanceKlass*)klass); 751 } 752 } 753 754 void SystemDictionaryShared::init_dumptime_info_from_preimage(InstanceKlass* k) { 755 init_dumptime_info(k); 756 copy_verification_info_from_preimage(k); 757 copy_linking_constraints_from_preimage(k); 758 759 if (SystemDictionary::is_platform_class_loader(k->class_loader())) { 760 AOTClassLocationConfig::dumptime_set_has_platform_classes(); 761 } else if (SystemDictionary::is_system_class_loader(k->class_loader())) { 762 AOTClassLocationConfig::dumptime_set_has_app_classes(); 763 } 764 } 765 766 // Check if a class or any of its supertypes has been redefined. 767 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) { 768 if (k->has_been_redefined()) { 769 return true; 770 } 771 if (k->super() != nullptr && has_been_redefined(k->super())) { 772 return true; 773 } 774 Array<InstanceKlass*>* interfaces = k->local_interfaces(); 775 int len = interfaces->length(); 776 for (int i = 0; i < len; i++) { 777 if (has_been_redefined(interfaces->at(i))) { 778 return true; 779 } 780 } 781 return false; 782 } 783 784 // k is a class before relocating by ArchiveBuilder 785 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) { 786 ResourceMark rm; 787 const char* name = k->name()->as_C_string(); 788 DumpTimeClassInfo* info = _dumptime_table->get(k); 789 assert(!class_loading_may_happen(), "class loading must be disabled"); 790 guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name); 791 guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name); 792 if (is_builtin(k)) { 793 if (k->is_hidden()) { 794 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) { 795 assert(LambdaProxyClassDictionary::is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name); 796 } 797 } 798 guarantee(!k->defined_by_other_loaders(), 799 "Class loader type must be set for BUILTIN class %s", name); 800 801 } else { 802 guarantee(k->defined_by_other_loaders(), 803 "Class loader type must not be set for UNREGISTERED class %s", name); 804 } 805 } 806 807 class UnregisteredClassesDuplicationChecker : StackObj { 808 GrowableArray<InstanceKlass*> _list; 809 Thread* _thread; 810 public: 811 UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {} 812 813 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) { 814 if (!SystemDictionaryShared::is_builtin(k)) { 815 _list.append(k); 816 } 817 } 818 819 static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) { 820 ClassLoaderData* loader_a = a[0]->class_loader_data(); 821 ClassLoaderData* loader_b = b[0]->class_loader_data(); 822 823 if (loader_a != loader_b) { 824 return primitive_compare(loader_a, loader_b); 825 } else { 826 return primitive_compare(a[0], b[0]); 827 } 828 } 829 830 void mark_duplicated_classes() { 831 // Two loaders may load two identical or similar hierarchies of classes. If we 832 // check for duplication in random order, we may end up excluding important base classes 833 // in both hierarchies, causing most of the classes to be excluded. 834 // We sort the classes by their loaders. This way we're likely to archive 835 // all classes in the one of the two hierarchies. 836 _list.sort(compare_by_loader); 837 for (int i = 0; i < _list.length(); i++) { 838 InstanceKlass* k = _list.at(i); 839 bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k); 840 if (!i_am_first) { 841 SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class"); 842 SystemDictionaryShared::set_excluded_locked(k); 843 } 844 } 845 } 846 }; 847 848 // Returns true if the class should be excluded. This can be called by 849 // AOTConstantPoolResolver before or after we enter the CDS safepoint. 850 // When called before the safepoint, we need to link the class so that 851 // it can be checked by should_be_excluded_impl(). 852 bool SystemDictionaryShared::should_be_excluded(Klass* k) { 853 assert(CDSConfig::is_dumping_archive(), "sanity"); 854 assert(CDSConfig::current_thread_is_vm_or_dumper(), "sanity"); 855 856 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(k)) { 857 // We have reached a super type that's already in the base archive. Treat it 858 // as "not excluded". 859 return false; 860 } 861 862 if (k->is_objArray_klass()) { 863 return should_be_excluded(ObjArrayKlass::cast(k)->bottom_klass()); 864 } else if (!k->is_instance_klass()) { 865 assert(k->is_typeArray_klass(), "must be"); 866 return false; 867 } else { 868 InstanceKlass* ik = InstanceKlass::cast(k); 869 870 if (!SafepointSynchronize::is_at_safepoint()) { 871 if (!ik->is_linked()) { 872 // should_be_excluded_impl() below doesn't link unlinked classes. We come 873 // here only when we are trying to aot-link constant pool entries, so 874 // we'd better link the class. 875 JavaThread* THREAD = JavaThread::current(); 876 ik->link_class(THREAD); 877 if (HAS_PENDING_EXCEPTION) { 878 CLEAR_PENDING_EXCEPTION; 879 return true; // linking failed -- let's exclude it 880 } 881 882 // Also link any classes that were loaded for the verification of ik or its supertypes. 883 // Otherwise we might miss the verification constraints of those classes. 884 AOTMetaspace::link_all_loaded_classes(THREAD); 885 } 886 887 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 888 DumpTimeClassInfo* p = get_info_locked(ik); 889 if (p->is_excluded()) { 890 return true; 891 } 892 return should_be_excluded_impl(ik, p); 893 } else { 894 // When called within the CDS safepoint, the correctness of this function 895 // relies on the call to AOTMetaspace::link_all_loaded_classes() 896 // that happened right before we enter the CDS safepoint. 897 // 898 // Do not call this function in other types of safepoints. For example, if this 899 // is called in a GC safepoint, a klass may be improperly excluded because some 900 // of its verification constraints have not yet been linked. 901 assert(CDSConfig::is_at_aot_safepoint(), "Do not call this function in any other safepoint"); 902 903 // No need to check for is_linked() as all eligible classes should have 904 // already been linked in AOTMetaspace::link_class_for_cds(). 905 // Can't take the lock as we are in safepoint. 906 DumpTimeClassInfo* p = _dumptime_table->get(ik); 907 if (p->is_excluded()) { 908 return true; 909 } 910 return should_be_excluded_impl(ik, p); 911 } 912 } 913 } 914 915 void SystemDictionaryShared::finish_exclusion_checks() { 916 assert_at_safepoint(); 917 if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) { 918 // Do this first -- if a base class is excluded due to duplication, 919 // all of its subclasses will also be excluded. 920 ResourceMark rm; 921 UnregisteredClassesDuplicationChecker dup_checker; 922 _dumptime_table->iterate_all_live_classes(&dup_checker); 923 dup_checker.mark_duplicated_classes(); 924 } 925 926 _dumptime_table->iterate_all_live_classes([&] (InstanceKlass* k, DumpTimeClassInfo& info) { 927 SystemDictionaryShared::should_be_excluded_impl(k, &info); 928 }); 929 930 _dumptime_table->update_counts(); 931 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) { 932 LambdaProxyClassDictionary::cleanup_dumptime_table(); 933 } 934 } 935 936 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) { 937 assert(!class_loading_may_happen(), "class loading must be disabled"); 938 assert_lock_strong(DumpTimeTable_lock); 939 assert(CDSConfig::is_dumping_archive(), "sanity"); 940 DumpTimeClassInfo* p = get_info_locked(k); 941 return p->is_excluded(); 942 } 943 944 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) { 945 assert_lock_strong(DumpTimeTable_lock); 946 assert(CDSConfig::is_dumping_archive(), "sanity"); 947 DumpTimeClassInfo* info = get_info_locked(k); 948 info->set_excluded(); 949 } 950 951 void SystemDictionaryShared::set_excluded(InstanceKlass* k) { 952 assert(CDSConfig::is_dumping_archive(), "sanity"); 953 DumpTimeClassInfo* info = get_info(k); 954 info->set_excluded(); 955 } 956 957 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) { 958 assert(CDSConfig::is_dumping_archive(), "sanity"); 959 DumpTimeClassInfo* p = get_info(ik); 960 p->set_failed_verification(); 961 } 962 963 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) { 964 assert(CDSConfig::is_dumping_archive(), "sanity"); 965 DumpTimeClassInfo* p = _dumptime_table->get(ik); 966 return (p == nullptr) ? false : p->failed_verification(); 967 } 968 969 void SystemDictionaryShared::set_from_class_file_load_hook(InstanceKlass* ik) { 970 warn_excluded(ik, "From ClassFileLoadHook"); 971 set_excluded(ik); 972 } 973 974 void SystemDictionaryShared::dumptime_classes_do(MetaspaceClosure* it) { 975 assert_lock_strong(DumpTimeTable_lock); 976 977 auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) { 978 if (CDSConfig::is_dumping_final_static_archive() && !k->is_loaded()) { 979 assert(k->defined_by_other_loaders(), "must be"); 980 info.metaspace_pointers_do(it); 981 } else if (k->is_loader_alive() && !info.is_excluded()) { 982 info.metaspace_pointers_do(it); 983 } 984 }; 985 _dumptime_table->iterate_all_live_classes(do_klass); 986 987 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) { 988 LambdaProxyClassDictionary::dumptime_classes_do(it); 989 } 990 } 991 992 // Called from VerificationType::is_reference_assignable_from() before performing the assignability check of 993 // T1 must be assignable from T2 994 // Where: 995 // L is the class loader of <k> 996 // T1 is the type resolved by L using the name <name> 997 // T2 is the type resolved by L using the name <from_name> 998 // 999 // The meaning of (*skip_assignability_check): 1000 // true: is_reference_assignable_from() should SKIP the assignability check 1001 // false: is_reference_assignable_from() should COMPLETE the assignability check 1002 void SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name, 1003 Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object, 1004 bool* skip_assignability_check) { 1005 assert(CDSConfig::is_dumping_archive(), "sanity"); 1006 DumpTimeClassInfo* info = get_info(k); 1007 info->add_verification_constraint(name, from_name, from_field_is_protected, 1008 from_is_array, from_is_object); 1009 1010 if (CDSConfig::is_dumping_classic_static_archive() && !is_builtin(k)) { 1011 // This applies ONLY to the "classic" CDS static dump, which reads the list of 1012 // unregistered classes (those intended for custom class loaders) from the classlist 1013 // and loads them using jdk.internal.misc.CDS$UnregisteredClassLoader. 1014 // 1015 // When the classlist contains an unregistered class k, the supertypes of k are also 1016 // recorded in the classlist. However, the classlist does not contain information about 1017 // any class X that's not a supertype of k but is needed in the verification of k. 1018 // As a result, CDS$UnregisteredClassLoader will not know how to resolve X. 1019 // 1020 // Therefore, we tell the verifier to refrain from resolving X. Instead, X is recorded 1021 // (symbolically) in the verification constraints of k. In the production run, 1022 // when k is loaded, we will go through its verification constraints and resolve X to complete 1023 // the is_reference_assignable_from() checks. 1024 *skip_assignability_check = true; 1025 } else { 1026 // In all other cases, we are using an *actual* class loader to load k, so it should be able 1027 // to resolve any types that are needed for the verification of k. 1028 *skip_assignability_check = false; 1029 } 1030 } 1031 1032 // When the old verifier is verifying the class <ik> at dump time, it tries to resolve a 1033 // class with the given <name>. For the verification result to be valid at run time, we must 1034 // ensure that <name> resolves to the exact same Klass as in dump time. 1035 void SystemDictionaryShared::add_old_verification_constraint(Thread* current, InstanceKlass* ik, Symbol* name) { 1036 precond(CDSConfig::is_preserving_verification_constraints()); 1037 DumpTimeClassInfo* info = get_info(ik); 1038 info->add_verification_constraint(name); 1039 } 1040 1041 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) { 1042 assert(CDSConfig::is_dumping_heap(), "sanity"); 1043 DumpTimeClassInfo* info = get_info_locked(ik); 1044 info->add_enum_klass_static_field(root_index); 1045 } 1046 1047 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass, 1048 TRAPS) { 1049 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only"); 1050 RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass); 1051 1052 int length = record->num_verifier_constraints(); 1053 if (length > 0) { 1054 for (int i = 0; i < length; i++) { 1055 RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i); 1056 Symbol* name = vc->name(); 1057 Symbol* from_name = vc->from_name(); 1058 1059 if (from_name == nullptr) { 1060 // This is for old verifier. No need to check, as we can guarantee that all classes checked by 1061 // the old verifier during AOT training phase cannot be replaced in the asembly phase. 1062 precond(CDSConfig::is_dumping_final_static_archive()); 1063 continue; 1064 } 1065 1066 if (log_is_enabled(Trace, aot, verification)) { 1067 ResourceMark rm(THREAD); 1068 log_trace(aot, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]", 1069 klass->external_name(), from_name->as_klass_external_name(), 1070 name->as_klass_external_name(), record->verifier_constraint_flag(i)); 1071 } 1072 1073 bool ok = VerificationType::resolve_and_check_assignability(klass, name, from_name, 1074 record->from_field_is_protected(i), record->from_is_array(i), record->from_is_object(i), CHECK); 1075 if (!ok) { 1076 ResourceMark rm(THREAD); 1077 stringStream ss; 1078 1079 ss.print_cr("Bad type on operand stack"); 1080 ss.print_cr("Exception Details:"); 1081 ss.print_cr(" Location:\n %s", klass->name()->as_C_string()); 1082 ss.print_cr(" Reason:\n Type '%s' is not assignable to '%s'", 1083 from_name->as_quoted_ascii(), name->as_quoted_ascii()); 1084 THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string()); 1085 } 1086 } 1087 } 1088 } 1089 1090 void SystemDictionaryShared::copy_verification_info_from_preimage(InstanceKlass* klass) { 1091 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only"); 1092 DumpTimeClassInfo* dt_info = get_info(klass); 1093 RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage 1094 1095 int length = rt_info->num_verifier_constraints(); 1096 if (length > 0) { 1097 for (int i = 0; i < length; i++) { 1098 RunTimeClassInfo::RTVerifierConstraint* vc = rt_info->verifier_constraint_at(i); 1099 Symbol* name = vc->name(); 1100 Symbol* from_name = vc->from_name(); 1101 1102 dt_info->add_verification_constraint(name, from_name, 1103 rt_info->from_field_is_protected(i), rt_info->from_is_array(i), rt_info->from_is_object(i)); 1104 } 1105 } 1106 } 1107 1108 static oop get_class_loader_by(char type) { 1109 if (type == (char)ClassLoader::BOOT_LOADER) { 1110 return (oop)nullptr; 1111 } else if (type == (char)ClassLoader::PLATFORM_LOADER) { 1112 return SystemDictionary::java_platform_loader(); 1113 } else { 1114 assert (type == (char)ClassLoader::APP_LOADER, "Sanity"); 1115 return SystemDictionary::java_system_loader(); 1116 } 1117 } 1118 1119 // Record class loader constraints that are checked inside 1120 // InstanceKlass::link_class(), so that these can be checked quickly 1121 // at runtime without laying out the vtable/itables. 1122 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass, 1123 Handle loader1, Handle loader2) { 1124 // A linking constraint check is executed when: 1125 // - klass extends or implements type S 1126 // - klass overrides method S.M(...) with X.M 1127 // - If klass defines the method M, X is 1128 // the same as klass. 1129 // - If klass does not define the method M, 1130 // X must be a supertype of klass and X.M is 1131 // a default method defined by X. 1132 // - loader1 = X->class_loader() 1133 // - loader2 = S->class_loader() 1134 // - loader1 != loader2 1135 // - M's parameter(s) include an object type T 1136 // We require that 1137 // - whenever loader1 and loader2 try to 1138 // resolve the type T, they must always resolve to 1139 // the same InstanceKlass. 1140 // NOTE: type T may or may not be currently resolved in 1141 // either of these two loaders. The check itself does not 1142 // try to resolve T. 1143 oop klass_loader = klass->class_loader(); 1144 1145 if (!is_system_class_loader(klass_loader) && 1146 !is_platform_class_loader(klass_loader)) { 1147 // If klass is loaded by system/platform loaders, we can 1148 // guarantee that klass and S must be loaded by the same 1149 // respective loader between dump time and run time, and 1150 // the exact same check on (name, loader1, loader2) will 1151 // be executed. Hence, we can cache this check and execute 1152 // it at runtime without walking the vtable/itables. 1153 // 1154 // This cannot be guaranteed for classes loaded by other 1155 // loaders, so we bail. 1156 return; 1157 } 1158 1159 assert(is_builtin(klass), "must be"); 1160 assert(klass_loader != nullptr, "should not be called for boot loader"); 1161 assert(loader1 != loader2, "must be"); 1162 1163 if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) { 1164 // We are re-laying out the vtable/itables of the *copy* of 1165 // a class during the final stage of dynamic dumping. The 1166 // linking constraints for this class has already been recorded. 1167 return; 1168 } 1169 assert(!Thread::current()->is_VM_thread(), "must be"); 1170 1171 assert(CDSConfig::is_dumping_archive(), "sanity"); 1172 DumpTimeClassInfo* info = get_info(klass); 1173 info->record_linking_constraint(name, loader1, loader2); 1174 } 1175 1176 // returns true IFF there's no need to re-initialize the i/v-tables for klass for 1177 // the purpose of checking class loader constraints. 1178 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) { 1179 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only"); 1180 LogTarget(Info, class, loader, constraints) log; 1181 if (klass->defined_by_boot_loader()) { 1182 // No class loader constraint check performed for boot classes. 1183 return true; 1184 } 1185 if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) { 1186 RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass); 1187 assert(info != nullptr, "Sanity"); 1188 if (info->num_loader_constraints() > 0) { 1189 HandleMark hm(current); 1190 for (int i = 0; i < info->num_loader_constraints(); i++) { 1191 RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i); 1192 Symbol* name = lc->constraint_name(); 1193 Handle loader1(current, get_class_loader_by(lc->_loader_type1)); 1194 Handle loader2(current, get_class_loader_by(lc->_loader_type2)); 1195 if (log.is_enabled()) { 1196 ResourceMark rm(current); 1197 log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s", 1198 klass->external_name(), name->as_C_string(), 1199 ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(), 1200 ClassLoaderData::class_loader_data(loader2())->loader_name_and_id()); 1201 } 1202 if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) { 1203 // Loader constraint violation has been found. The caller 1204 // will re-layout the vtable/itables to produce the correct 1205 // exception. 1206 if (log.is_enabled()) { 1207 log.print(" failed]"); 1208 } 1209 return false; 1210 } 1211 if (log.is_enabled()) { 1212 log.print(" succeeded]"); 1213 } 1214 } 1215 return true; // for all recorded constraints added successfully. 1216 } 1217 } 1218 if (log.is_enabled()) { 1219 ResourceMark rm(current); 1220 log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name()); 1221 } 1222 return false; 1223 } 1224 1225 void SystemDictionaryShared::copy_linking_constraints_from_preimage(InstanceKlass* klass) { 1226 assert(CDSConfig::is_using_archive(), "called at run time with CDS enabled only"); 1227 JavaThread* current = JavaThread::current(); 1228 if (klass->defined_by_platform_loader() || klass->defined_by_app_loader()) { 1229 RunTimeClassInfo* rt_info = RunTimeClassInfo::get_for(klass); // from preimage 1230 1231 if (rt_info->num_loader_constraints() > 0) { 1232 for (int i = 0; i < rt_info->num_loader_constraints(); i++) { 1233 RunTimeClassInfo::RTLoaderConstraint* lc = rt_info->loader_constraint_at(i); 1234 Symbol* name = lc->constraint_name(); 1235 Handle loader1(current, get_class_loader_by(lc->_loader_type1)); 1236 Handle loader2(current, get_class_loader_by(lc->_loader_type2)); 1237 record_linking_constraint(name, klass, loader1, loader2); 1238 } 1239 } 1240 } 1241 } 1242 1243 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) { 1244 if (ArchiveBuilder::is_active() && ArchiveBuilder::current()->is_in_buffer_space(ptr)) { 1245 uintx offset = ArchiveBuilder::current()->any_to_offset(ptr); 1246 unsigned int hash = primitive_hash<uintx>(offset); 1247 DEBUG_ONLY({ 1248 if (MetaspaceObj::in_aot_cache((const MetaspaceObj*)ptr)) { 1249 assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be"); 1250 } 1251 }); 1252 return hash; 1253 } else { 1254 return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr); 1255 } 1256 } 1257 1258 class CopySharedClassInfoToArchive : StackObj { 1259 CompactHashtableWriter* _writer; 1260 bool _is_builtin; 1261 ArchiveBuilder *_builder; 1262 public: 1263 CopySharedClassInfoToArchive(CompactHashtableWriter* writer, 1264 bool is_builtin) 1265 : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {} 1266 1267 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) { 1268 if (!info.is_excluded() && info.is_builtin() == _is_builtin) { 1269 size_t byte_size = info.runtime_info_bytesize(); 1270 RunTimeClassInfo* record; 1271 record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size); 1272 record->init(info); 1273 1274 unsigned int hash; 1275 Symbol* name = info._klass->name(); 1276 name = ArchiveBuilder::current()->get_buffered_addr(name); 1277 hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name); 1278 u4 delta = _builder->buffer_to_offset_u4((address)record); 1279 if (_is_builtin && info._klass->is_hidden()) { 1280 // skip 1281 } else { 1282 _writer->add(hash, delta); 1283 } 1284 if (log_is_enabled(Trace, aot, hashtables)) { 1285 ResourceMark rm; 1286 log_trace(aot, hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name()); 1287 } 1288 1289 // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo* 1290 InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass); 1291 RunTimeClassInfo::set_for(buffered_klass, record); 1292 } 1293 } 1294 }; 1295 1296 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary, 1297 bool is_builtin) { 1298 CompactHashtableStats stats; 1299 dictionary->reset(); 1300 CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats); 1301 CopySharedClassInfoToArchive copy(&writer, is_builtin); 1302 assert_lock_strong(DumpTimeTable_lock); 1303 _dumptime_table->iterate_all_live_classes(©); 1304 writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary"); 1305 } 1306 1307 void SystemDictionaryShared::write_to_archive(bool is_static_archive) { 1308 ArchiveInfo* archive = get_archive(is_static_archive); 1309 1310 write_dictionary(&archive->_builtin_dictionary, true); 1311 write_dictionary(&archive->_unregistered_dictionary, false); 1312 if (CDSConfig::is_dumping_lambdas_in_legacy_mode()) { 1313 LambdaProxyClassDictionary::write_dictionary(is_static_archive); 1314 } else { 1315 LambdaProxyClassDictionary::reset_dictionary(is_static_archive); 1316 } 1317 } 1318 1319 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc, 1320 bool is_static_archive) { 1321 ArchiveInfo* archive = get_archive(is_static_archive); 1322 1323 archive->_builtin_dictionary.serialize_header(soc); 1324 archive->_unregistered_dictionary.serialize_header(soc); 1325 LambdaProxyClassDictionary::serialize(soc, is_static_archive); 1326 } 1327 1328 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) { 1329 for (auto id : EnumRange<vmClassID>{}) { 1330 soc->do_ptr(vmClasses::klass_addr_at(id)); 1331 } 1332 } 1333 1334 const RunTimeClassInfo* 1335 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) { 1336 if (!CDSConfig::is_using_archive() || !name->in_aot_cache()) { 1337 // The names of all shared classes must also be a shared Symbol. 1338 return nullptr; 1339 } 1340 1341 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name); 1342 const RunTimeClassInfo* record = nullptr; 1343 if (DynamicArchive::is_mapped()) { 1344 // Use the regenerated holder classes in the dynamic archive as they 1345 // have more methods than those in the base archive. 1346 if (LambdaFormInvokers::may_be_regenerated_class(name)) { 1347 record = dynamic_dict->lookup(name, hash, 0); 1348 if (record != nullptr) { 1349 return record; 1350 } 1351 } 1352 } 1353 1354 if (!AOTMetaspace::in_aot_cache_dynamic_region(name)) { 1355 // The names of all shared classes in the static dict must also be in the 1356 // static archive 1357 record = static_dict->lookup(name, hash, 0); 1358 } 1359 1360 if (record == nullptr && DynamicArchive::is_mapped()) { 1361 record = dynamic_dict->lookup(name, hash, 0); 1362 } 1363 1364 return record; 1365 } 1366 1367 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) { 1368 const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary, 1369 &_dynamic_archive._builtin_dictionary, 1370 name); 1371 if (record != nullptr) { 1372 assert(!record->klass()->is_hidden(), "hidden class cannot be looked up by name"); 1373 DEBUG_ONLY(check_klass_after_loading(record->klass());) 1374 // We did not save the classfile data of the generated LambdaForm invoker classes, 1375 // so we cannot support CLFH for such classes. 1376 if (record->klass()->is_aot_generated_class() && JvmtiExport::should_post_class_file_load_hook()) { 1377 return nullptr; 1378 } 1379 return record->klass(); 1380 } else { 1381 return nullptr; 1382 } 1383 } 1384 1385 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) { 1386 assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)"); 1387 DumpTimeClassInfo* info = get_info(k); 1388 info->_id = id; 1389 } 1390 1391 const char* SystemDictionaryShared::loader_type_for_shared_class(Klass* k) { 1392 assert(k != nullptr, "Sanity"); 1393 assert(k->in_aot_cache(), "Must be"); 1394 assert(k->is_instance_klass(), "Must be"); 1395 InstanceKlass* ik = InstanceKlass::cast(k); 1396 if (ik->defined_by_boot_loader()) { 1397 return "boot_loader"; 1398 } else if (ik->defined_by_platform_loader()) { 1399 return "platform_loader"; 1400 } else if (ik->defined_by_app_loader()) { 1401 return "app_loader"; 1402 } else if (ik->defined_by_other_loaders()) { 1403 return "unregistered_loader"; 1404 } else { 1405 return "unknown loader"; 1406 } 1407 } 1408 1409 void SystemDictionaryShared::get_all_archived_classes(bool is_static_archive, GrowableArray<Klass*>* classes) { 1410 get_archive(is_static_archive)->_builtin_dictionary.iterate([&] (const RunTimeClassInfo* record) { 1411 classes->append(record->klass()); 1412 }); 1413 } 1414 1415 class SharedDictionaryPrinter : StackObj { 1416 outputStream* _st; 1417 int _index; 1418 public: 1419 SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {} 1420 1421 void do_value(const RunTimeClassInfo* record) { 1422 ResourceMark rm; 1423 _st->print_cr("%4d: %s %s", _index++, record->klass()->external_name(), 1424 SystemDictionaryShared::loader_type_for_shared_class(record->klass())); 1425 if (record->klass()->array_klasses() != nullptr) { 1426 record->klass()->array_klasses()->cds_print_value_on(_st); 1427 _st->cr(); 1428 } 1429 } 1430 int index() const { return _index; } 1431 }; 1432 1433 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix, 1434 outputStream* st, 1435 bool is_static_archive) { 1436 st->print_cr("%sShared Dictionary", prefix); 1437 SharedDictionaryPrinter p(st); 1438 st->print_cr("%sShared Builtin Dictionary", prefix); 1439 _builtin_dictionary.iterate(&p); 1440 st->print_cr("%sShared Unregistered Dictionary", prefix); 1441 _unregistered_dictionary.iterate(&p); 1442 LambdaProxyClassDictionary::print_on(prefix, st, p.index(), is_static_archive); 1443 } 1444 1445 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix, 1446 outputStream* st, 1447 bool is_static_archive) { 1448 st->print_cr("%sArchve Statistics", prefix); 1449 _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary"); 1450 _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary"); 1451 LambdaProxyClassDictionary::print_statistics(st, is_static_archive); 1452 } 1453 1454 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) { 1455 if (CDSConfig::is_using_archive()) { 1456 if (is_static) { 1457 _static_archive.print_on("", st, true); 1458 } else { 1459 if (DynamicArchive::is_mapped()) { 1460 _dynamic_archive.print_on("Dynamic ", st, false); 1461 } 1462 } 1463 } 1464 } 1465 1466 void SystemDictionaryShared::print_on(outputStream* st) { 1467 print_shared_archive(st, true); 1468 print_shared_archive(st, false); 1469 } 1470 1471 void SystemDictionaryShared::print_table_statistics(outputStream* st) { 1472 if (CDSConfig::is_using_archive()) { 1473 _static_archive.print_table_statistics("Static ", st, true); 1474 if (DynamicArchive::is_mapped()) { 1475 _dynamic_archive.print_table_statistics("Dynamic ", st, false); 1476 } 1477 } 1478 } 1479 1480 bool SystemDictionaryShared::is_dumptime_table_empty() { 1481 assert_lock_strong(DumpTimeTable_lock); 1482 _dumptime_table->update_counts(); 1483 if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){ 1484 return true; 1485 } 1486 return false; 1487 }