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