1 /* 2 * Copyright (c) 2014, 2024, 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 #include "precompiled.hpp" 26 #include "cds/archiveBuilder.hpp" 27 #include "cds/archiveHeapLoader.hpp" 28 #include "cds/archiveUtils.hpp" 29 #include "cds/cdsConfig.hpp" 30 #include "cds/classListParser.hpp" 31 #include "cds/classListWriter.hpp" 32 #include "cds/dynamicArchive.hpp" 33 #include "cds/filemap.hpp" 34 #include "cds/cdsProtectionDomain.hpp" 35 #include "cds/dumpTimeClassInfo.inline.hpp" 36 #include "cds/metaspaceShared.hpp" 37 #include "cds/runTimeClassInfo.hpp" 38 #include "classfile/classFileStream.hpp" 39 #include "classfile/classLoader.hpp" 40 #include "classfile/classLoaderData.inline.hpp" 41 #include "classfile/classLoaderDataGraph.hpp" 42 #include "classfile/classLoaderExt.hpp" 43 #include "classfile/dictionary.hpp" 44 #include "classfile/javaClasses.hpp" 45 #include "classfile/javaClasses.inline.hpp" 46 #include "classfile/symbolTable.hpp" 47 #include "classfile/systemDictionary.hpp" 48 #include "classfile/systemDictionaryShared.hpp" 49 #include "classfile/verificationType.hpp" 50 #include "classfile/vmClasses.hpp" 51 #include "classfile/vmSymbols.hpp" 52 #include "interpreter/bootstrapInfo.hpp" 53 #include "jfr/jfrEvents.hpp" 54 #include "logging/log.hpp" 55 #include "logging/logStream.hpp" 56 #include "memory/allocation.hpp" 57 #include "memory/metadataFactory.hpp" 58 #include "memory/metaspaceClosure.hpp" 59 #include "memory/oopFactory.hpp" 60 #include "memory/resourceArea.hpp" 61 #include "memory/universe.hpp" 62 #include "oops/compressedKlass.inline.hpp" 63 #include "oops/instanceKlass.hpp" 64 #include "oops/klass.inline.hpp" 65 #include "oops/objArrayKlass.hpp" 66 #include "oops/objArrayOop.inline.hpp" 67 #include "oops/oop.inline.hpp" 68 #include "oops/oopHandle.inline.hpp" 69 #include "oops/typeArrayOop.inline.hpp" 70 #include "runtime/arguments.hpp" 71 #include "runtime/handles.inline.hpp" 72 #include "runtime/java.hpp" 73 #include "runtime/javaCalls.hpp" 74 #include "runtime/mutexLocker.hpp" 75 #include "utilities/resourceHash.hpp" 76 #include "utilities/stringUtils.hpp" 77 78 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_static_archive; 79 SystemDictionaryShared::ArchiveInfo SystemDictionaryShared::_dynamic_archive; 80 81 DumpTimeSharedClassTable* SystemDictionaryShared::_dumptime_table = nullptr; 82 DumpTimeLambdaProxyClassDictionary* SystemDictionaryShared::_dumptime_lambda_proxy_class_dictionary = nullptr; 83 84 // Used by NoClassLoadingMark 85 DEBUG_ONLY(bool SystemDictionaryShared::_class_loading_may_happen = true;) 86 87 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader( 88 Symbol* class_name, Handle class_loader, TRAPS) { 89 assert(CDSConfig::is_using_archive(), "must be"); 90 InstanceKlass* ik = find_builtin_class(class_name); 91 92 if (ik != nullptr && !ik->shared_loading_failed()) { 93 if ((SystemDictionary::is_system_class_loader(class_loader()) && ik->is_shared_app_class()) || 94 (SystemDictionary::is_platform_class_loader(class_loader()) && ik->is_shared_platform_class())) { 95 SharedClassLoadingMark slm(THREAD, ik); 96 PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader); 97 Handle protection_domain = 98 CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL); 99 return load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, THREAD); 100 } 101 } 102 return nullptr; 103 } 104 105 // This function is called for loading only UNREGISTERED classes 106 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name, 107 Handle class_loader, 108 Handle protection_domain, 109 const ClassFileStream* cfs, 110 TRAPS) { 111 if (!CDSConfig::is_using_archive()) { 112 return nullptr; 113 } 114 if (class_name == nullptr) { // don't do this for hidden classes 115 return nullptr; 116 } 117 if (class_loader.is_null() || 118 SystemDictionary::is_system_class_loader(class_loader()) || 119 SystemDictionary::is_platform_class_loader(class_loader())) { 120 // Do nothing for the BUILTIN loaders. 121 return nullptr; 122 } 123 124 const RunTimeClassInfo* record = find_record(&_static_archive._unregistered_dictionary, 125 &_dynamic_archive._unregistered_dictionary, 126 class_name); 127 if (record == nullptr) { 128 return nullptr; 129 } 130 131 int clsfile_size = cfs->length(); 132 int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length()); 133 134 if (!record->matches(clsfile_size, clsfile_crc32)) { 135 return nullptr; 136 } 137 138 return acquire_class_for_current_thread(record->_klass, class_loader, 139 protection_domain, cfs, 140 THREAD); 141 } 142 143 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread( 144 InstanceKlass *ik, 145 Handle class_loader, 146 Handle protection_domain, 147 const ClassFileStream *cfs, 148 TRAPS) { 149 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 150 151 { 152 MutexLocker mu(THREAD, SharedDictionary_lock); 153 if (ik->class_loader_data() != nullptr) { 154 // ik is already loaded (by this loader or by a different loader) 155 // or ik is being loaded by a different thread (by this loader or by a different loader) 156 return nullptr; 157 } 158 159 // No other thread has acquired this yet, so give it to *this thread* 160 ik->set_class_loader_data(loader_data); 161 } 162 163 // No longer holding SharedDictionary_lock 164 // No need to lock, as <ik> can be held only by a single thread. 165 loader_data->add_class(ik); 166 167 // Get the package entry. 168 PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader); 169 170 // Load and check super/interfaces, restore unshareable info 171 InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain, 172 cfs, pkg_entry, THREAD); 173 if (shared_klass == nullptr || HAS_PENDING_EXCEPTION) { 174 // TODO: clean up <ik> so it can be used again 175 return nullptr; 176 } 177 178 return shared_klass; 179 } 180 181 // Guaranteed to return non-null value for non-shared classes. 182 // k must not be a shared class. 183 DumpTimeClassInfo* SystemDictionaryShared::get_info(InstanceKlass* k) { 184 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 185 assert(!k->is_shared(), "sanity"); 186 return get_info_locked(k); 187 } 188 189 DumpTimeClassInfo* SystemDictionaryShared::get_info_locked(InstanceKlass* k) { 190 assert_lock_strong(DumpTimeTable_lock); 191 assert(!k->is_shared(), "sanity"); 192 DumpTimeClassInfo* info = _dumptime_table->get_info(k); 193 assert(info != nullptr, "must be"); 194 return info; 195 } 196 197 bool SystemDictionaryShared::check_for_exclusion(InstanceKlass* k, DumpTimeClassInfo* info) { 198 if (MetaspaceShared::is_in_shared_metaspace(k)) { 199 // We have reached a super type that's already in the base archive. Treat it 200 // as "not excluded". 201 assert(CDSConfig::is_dumping_dynamic_archive(), "must be"); 202 return false; 203 } 204 205 if (info == nullptr) { 206 info = _dumptime_table->get(k); 207 assert(info != nullptr, "supertypes of any classes in _dumptime_table must either be shared, or must also be in _dumptime_table"); 208 } 209 210 if (!info->has_checked_exclusion()) { 211 if (check_for_exclusion_impl(k)) { 212 info->set_excluded(); 213 } 214 info->set_has_checked_exclusion(); 215 } 216 217 return info->is_excluded(); 218 } 219 220 // Returns true so the caller can do: return warn_excluded("....."); 221 bool SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) { 222 ResourceMark rm; 223 log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason); 224 return true; 225 } 226 227 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) { 228 while (k) { 229 if (k->name()->equals("jdk/internal/event/Event")) { 230 return true; 231 } 232 k = k->java_super(); 233 } 234 return false; 235 } 236 237 bool SystemDictionaryShared::is_registered_lambda_proxy_class(InstanceKlass* ik) { 238 DumpTimeClassInfo* info = _dumptime_table->get(ik); 239 return (info != nullptr) ? info->_is_archived_lambda_proxy : false; 240 } 241 242 void SystemDictionaryShared::reset_registered_lambda_proxy_class(InstanceKlass* ik) { 243 DumpTimeClassInfo* info = _dumptime_table->get(ik); 244 if (info != nullptr) { 245 info->_is_archived_lambda_proxy = false; 246 info->set_excluded(); 247 } 248 } 249 250 bool SystemDictionaryShared::is_early_klass(InstanceKlass* ik) { 251 DumpTimeClassInfo* info = _dumptime_table->get(ik); 252 return (info != nullptr) ? info->is_early_klass() : false; 253 } 254 255 bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) { 256 assert(ik->is_shared(), "applicable to only a shared class"); 257 if (ik->is_hidden()) { 258 return true; 259 } else { 260 return false; 261 } 262 } 263 264 bool SystemDictionaryShared::check_for_exclusion_impl(InstanceKlass* k) { 265 if (k->is_in_error_state()) { 266 return warn_excluded(k, "In error state"); 267 } 268 if (k->is_scratch_class()) { 269 return warn_excluded(k, "A scratch class"); 270 } 271 if (!k->is_loaded()) { 272 return warn_excluded(k, "Not in loaded state"); 273 } 274 if (has_been_redefined(k)) { 275 return warn_excluded(k, "Has been redefined"); 276 } 277 if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) { 278 // These are classes loaded from unsupported locations (such as those loaded by JVMTI native 279 // agent during dump time). 280 return warn_excluded(k, "Unsupported location"); 281 } 282 if (k->signers() != nullptr) { 283 // We cannot include signed classes in the archive because the certificates 284 // used during dump time may be different than those used during 285 // runtime (due to expiration, etc). 286 return warn_excluded(k, "Signed JAR"); 287 } 288 if (is_jfr_event_class(k)) { 289 // We cannot include JFR event classes because they need runtime-specific 290 // instrumentation in order to work with -XX:FlightRecorderOptions:retransform=false. 291 // There are only a small number of these classes, so it's not worthwhile to 292 // support them and make CDS more complicated. 293 return warn_excluded(k, "JFR event class"); 294 } 295 296 if (!k->is_linked()) { 297 if (has_class_failed_verification(k)) { 298 return warn_excluded(k, "Failed verification"); 299 } 300 } else { 301 if (!k->can_be_verified_at_dumptime()) { 302 // We have an old class that has been linked (e.g., it's been executed during 303 // dump time). This class has been verified using the old verifier, which 304 // doesn't save the verification constraints, so check_verification_constraints() 305 // won't work at runtime. 306 // As a result, we cannot store this class. It must be loaded and fully verified 307 // at runtime. 308 return warn_excluded(k, "Old class has been linked"); 309 } 310 } 311 312 if (k->is_hidden() && !is_registered_lambda_proxy_class(k)) { 313 ResourceMark rm; 314 log_debug(cds)("Skipping %s: Hidden class", k->name()->as_C_string()); 315 return true; 316 } 317 318 InstanceKlass* super = k->java_super(); 319 if (super != nullptr && check_for_exclusion(super, nullptr)) { 320 ResourceMark rm; 321 log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string()); 322 return true; 323 } 324 325 Array<InstanceKlass*>* interfaces = k->local_interfaces(); 326 int len = interfaces->length(); 327 for (int i = 0; i < len; i++) { 328 InstanceKlass* intf = interfaces->at(i); 329 if (check_for_exclusion(intf, nullptr)) { 330 ResourceMark rm; 331 log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string()); 332 return true; 333 } 334 } 335 336 return false; // false == k should NOT be excluded 337 } 338 339 bool SystemDictionaryShared::is_builtin_loader(ClassLoaderData* loader_data) { 340 oop class_loader = loader_data->class_loader(); 341 return (class_loader == nullptr || 342 SystemDictionary::is_system_class_loader(class_loader) || 343 SystemDictionary::is_platform_class_loader(class_loader)); 344 } 345 346 bool SystemDictionaryShared::has_platform_or_app_classes() { 347 if (FileMapInfo::current_info()->has_platform_or_app_classes()) { 348 return true; 349 } 350 if (DynamicArchive::is_mapped() && 351 FileMapInfo::dynamic_info()->has_platform_or_app_classes()) { 352 return true; 353 } 354 return false; 355 } 356 357 // The following stack shows how this code is reached: 358 // 359 // [0] SystemDictionaryShared::find_or_load_shared_class() 360 // [1] JVM_FindLoadedClass 361 // [2] java.lang.ClassLoader.findLoadedClass0() 362 // [3] java.lang.ClassLoader.findLoadedClass() 363 // [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull() 364 // [5] jdk.internal.loader.BuiltinClassLoader.loadClass() 365 // [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or 366 // jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass() 367 // 368 // AppCDS supports fast class loading for these 2 built-in class loaders: 369 // jdk.internal.loader.ClassLoaders$PlatformClassLoader 370 // jdk.internal.loader.ClassLoaders$AppClassLoader 371 // with the following assumptions (based on the JDK core library source code): 372 // 373 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to 374 // load the named class. 375 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name). 376 // [c] At this point, if we can find the named class inside the 377 // shared_dictionary, we can perform further checks (see 378 // SystemDictionary::is_shared_class_visible) to ensure that this class 379 // was loaded by the same class loader during dump time. 380 // 381 // Given these assumptions, we intercept the findLoadedClass() call to invoke 382 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from 383 // the archive for the 2 built-in class loaders. This way, 384 // we can improve start-up because we avoid decoding the classfile, 385 // and avoid delegating to the parent loader. 386 // 387 // NOTE: there's a lot of assumption about the Java code. If any of that change, this 388 // needs to be redesigned. 389 390 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class( 391 Symbol* name, Handle class_loader, TRAPS) { 392 InstanceKlass* k = nullptr; 393 if (CDSConfig::is_using_archive()) { 394 if (!has_platform_or_app_classes()) { 395 return nullptr; 396 } 397 398 if (SystemDictionary::is_system_class_loader(class_loader()) || 399 SystemDictionary::is_platform_class_loader(class_loader())) { 400 // Fix for 4474172; see evaluation for more details 401 class_loader = Handle( 402 THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 403 ClassLoaderData *loader_data = register_loader(class_loader); 404 Dictionary* dictionary = loader_data->dictionary(); 405 406 // Note: currently, find_or_load_shared_class is called only from 407 // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader, 408 // which are parallel-capable loaders, so a lock here is NOT taken. 409 assert(get_loader_lock_or_null(class_loader) == nullptr, "ObjectLocker not required"); 410 { 411 MutexLocker mu(THREAD, SystemDictionary_lock); 412 InstanceKlass* check = dictionary->find_class(THREAD, name); 413 if (check != nullptr) { 414 return check; 415 } 416 } 417 418 k = load_shared_class_for_builtin_loader(name, class_loader, THREAD); 419 if (k != nullptr) { 420 SharedClassLoadingMark slm(THREAD, k); 421 k = find_or_define_instance_class(name, class_loader, k, CHECK_NULL); 422 } 423 } 424 } 425 426 #ifdef ASSERT 427 if (UseCompressedClassPointers && k != nullptr) { 428 CompressedKlassPointers::check_valid_klass(k); 429 } 430 #endif 431 432 return k; 433 } 434 435 class UnregisteredClassesTable : public ResourceHashtable< 436 Symbol*, InstanceKlass*, 437 15889, // prime number 438 AnyObj::C_HEAP> {}; 439 440 static UnregisteredClassesTable* _unregistered_classes_table = nullptr; 441 442 // true == class was successfully added; false == a duplicated class (with the same name) already exists. 443 bool SystemDictionaryShared::add_unregistered_class(Thread* current, InstanceKlass* klass) { 444 // We don't allow duplicated unregistered classes with the same name. 445 // We only archive the first class with that name that succeeds putting 446 // itself into the table. 447 assert(CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled(), "sanity"); 448 MutexLocker ml(current, UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag); 449 Symbol* name = klass->name(); 450 if (_unregistered_classes_table == nullptr) { 451 _unregistered_classes_table = new (mtClass)UnregisteredClassesTable(); 452 } 453 bool created; 454 InstanceKlass** v = _unregistered_classes_table->put_if_absent(name, klass, &created); 455 if (created) { 456 name->increment_refcount(); 457 } 458 return (klass == *v); 459 } 460 461 // This function is called to lookup the super/interfaces of shared classes for 462 // unregistered loaders. E.g., SharedClass in the below example 463 // where "super:" (and optionally "interface:") have been specified. 464 // 465 // java/lang/Object id: 0 466 // Interface id: 2 super: 0 source: cust.jar 467 // SharedClass id: 4 super: 0 interfaces: 2 source: cust.jar 468 InstanceKlass* SystemDictionaryShared::lookup_super_for_unregistered_class( 469 Symbol* class_name, Symbol* super_name, bool is_superclass) { 470 471 assert(CDSConfig::is_dumping_static_archive(), "only when static dumping"); 472 473 if (!ClassListParser::is_parsing_thread()) { 474 // Unregistered classes can be created only by ClassListParser::_parsing_thread. 475 476 return nullptr; 477 } 478 479 ClassListParser* parser = ClassListParser::instance(); 480 if (parser == nullptr) { 481 // We're still loading the well-known classes, before the ClassListParser is created. 482 return nullptr; 483 } 484 if (class_name->equals(parser->current_class_name())) { 485 // When this function is called, all the numbered super and interface types 486 // must have already been loaded. Hence this function is never recursively called. 487 if (is_superclass) { 488 return parser->lookup_super_for_current_class(super_name); 489 } else { 490 return parser->lookup_interface_for_current_class(super_name); 491 } 492 } else { 493 // The VM is not trying to resolve a super type of parser->current_class_name(). 494 // Instead, it's resolving an error class (because parser->current_class_name() has 495 // failed parsing or verification). Don't do anything here. 496 return nullptr; 497 } 498 } 499 500 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) { 501 assert(CDSConfig::is_dumping_archive(), "sanity"); 502 assert(!is_builtin(k), "must be unregistered class"); 503 DumpTimeClassInfo* info = get_info(k); 504 info->_clsfile_size = cfs->length(); 505 info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length()); 506 } 507 508 void SystemDictionaryShared::initialize() { 509 if (CDSConfig::is_dumping_archive()) { 510 _dumptime_table = new (mtClass) DumpTimeSharedClassTable; 511 _dumptime_lambda_proxy_class_dictionary = 512 new (mtClass) DumpTimeLambdaProxyClassDictionary; 513 } 514 } 515 516 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) { 517 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 518 assert(SystemDictionaryShared::class_loading_may_happen(), "sanity"); 519 _dumptime_table->allocate_info(k); 520 } 521 522 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) { 523 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 524 _dumptime_table->remove(k); 525 } 526 527 void SystemDictionaryShared::handle_class_unloading(InstanceKlass* klass) { 528 if (CDSConfig::is_dumping_archive()) { 529 remove_dumptime_info(klass); 530 } 531 532 if (CDSConfig::is_dumping_archive() || ClassListWriter::is_enabled()) { 533 MutexLocker ml(Thread::current(), UnregisteredClassesTable_lock, Mutex::_no_safepoint_check_flag); 534 if (_unregistered_classes_table != nullptr) { 535 // Remove the class from _unregistered_classes_table: keep the entry but 536 // set it to null. This ensure no classes with the same name can be 537 // added again. 538 InstanceKlass** v = _unregistered_classes_table->get(klass->name()); 539 if (v != nullptr) { 540 *v = nullptr; 541 } 542 } 543 } else { 544 assert(_unregistered_classes_table == nullptr, "must not be used"); 545 } 546 547 if (ClassListWriter::is_enabled()) { 548 ClassListWriter cw; 549 cw.handle_class_unloading((const InstanceKlass*)klass); 550 } 551 } 552 553 // Check if a class or any of its supertypes has been redefined. 554 bool SystemDictionaryShared::has_been_redefined(InstanceKlass* k) { 555 if (k->has_been_redefined()) { 556 return true; 557 } 558 if (k->java_super() != nullptr && has_been_redefined(k->java_super())) { 559 return true; 560 } 561 Array<InstanceKlass*>* interfaces = k->local_interfaces(); 562 int len = interfaces->length(); 563 for (int i = 0; i < len; i++) { 564 if (has_been_redefined(interfaces->at(i))) { 565 return true; 566 } 567 } 568 return false; 569 } 570 571 // k is a class before relocating by ArchiveBuilder 572 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) { 573 ResourceMark rm; 574 const char* name = k->name()->as_C_string(); 575 DumpTimeClassInfo* info = _dumptime_table->get(k); 576 assert(!class_loading_may_happen(), "class loading must be disabled"); 577 guarantee(info != nullptr, "Class %s must be entered into _dumptime_table", name); 578 guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name); 579 if (is_builtin(k)) { 580 if (k->is_hidden()) { 581 assert(is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name); 582 } 583 guarantee(!k->is_shared_unregistered_class(), 584 "Class loader type must be set for BUILTIN class %s", name); 585 586 } else { 587 guarantee(k->is_shared_unregistered_class(), 588 "Class loader type must not be set for UNREGISTERED class %s", name); 589 } 590 } 591 592 class UnregisteredClassesDuplicationChecker : StackObj { 593 GrowableArray<InstanceKlass*> _list; 594 Thread* _thread; 595 public: 596 UnregisteredClassesDuplicationChecker() : _thread(Thread::current()) {} 597 598 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) { 599 if (!SystemDictionaryShared::is_builtin(k)) { 600 _list.append(k); 601 } 602 } 603 604 static int compare_by_loader(InstanceKlass** a, InstanceKlass** b) { 605 ClassLoaderData* loader_a = a[0]->class_loader_data(); 606 ClassLoaderData* loader_b = b[0]->class_loader_data(); 607 608 if (loader_a != loader_b) { 609 return primitive_compare(loader_a, loader_b); 610 } else { 611 return primitive_compare(a[0], b[0]); 612 } 613 } 614 615 void mark_duplicated_classes() { 616 // Two loaders may load two identical or similar hierarchies of classes. If we 617 // check for duplication in random order, we may end up excluding important base classes 618 // in both hierarchies, causing most of the classes to be excluded. 619 // We sort the classes by their loaders. This way we're likely to archive 620 // all classes in the one of the two hierarchies. 621 _list.sort(compare_by_loader); 622 for (int i = 0; i < _list.length(); i++) { 623 InstanceKlass* k = _list.at(i); 624 bool i_am_first = SystemDictionaryShared::add_unregistered_class(_thread, k); 625 if (!i_am_first) { 626 SystemDictionaryShared::warn_excluded(k, "Duplicated unregistered class"); 627 SystemDictionaryShared::set_excluded_locked(k); 628 } 629 } 630 } 631 }; 632 633 void SystemDictionaryShared::check_excluded_classes() { 634 assert(!class_loading_may_happen(), "class loading must be disabled"); 635 assert_lock_strong(DumpTimeTable_lock); 636 637 if (CDSConfig::is_dumping_dynamic_archive()) { 638 // Do this first -- if a base class is excluded due to duplication, 639 // all of its subclasses will also be excluded. 640 ResourceMark rm; 641 UnregisteredClassesDuplicationChecker dup_checker; 642 _dumptime_table->iterate_all_live_classes(&dup_checker); 643 dup_checker.mark_duplicated_classes(); 644 } 645 646 auto check_for_exclusion = [&] (InstanceKlass* k, DumpTimeClassInfo& info) { 647 SystemDictionaryShared::check_for_exclusion(k, &info); 648 }; 649 _dumptime_table->iterate_all_live_classes(check_for_exclusion); 650 _dumptime_table->update_counts(); 651 652 cleanup_lambda_proxy_class_dictionary(); 653 } 654 655 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) { 656 assert(!class_loading_may_happen(), "class loading must be disabled"); 657 assert_lock_strong(DumpTimeTable_lock); 658 assert(CDSConfig::is_dumping_archive(), "sanity"); 659 DumpTimeClassInfo* p = get_info_locked(k); 660 return p->is_excluded(); 661 } 662 663 void SystemDictionaryShared::set_excluded_locked(InstanceKlass* k) { 664 assert_lock_strong(DumpTimeTable_lock); 665 assert(CDSConfig::is_dumping_archive(), "sanity"); 666 DumpTimeClassInfo* info = get_info_locked(k); 667 info->set_excluded(); 668 } 669 670 void SystemDictionaryShared::set_excluded(InstanceKlass* k) { 671 assert(CDSConfig::is_dumping_archive(), "sanity"); 672 DumpTimeClassInfo* info = get_info(k); 673 info->set_excluded(); 674 } 675 676 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) { 677 assert(CDSConfig::is_dumping_archive(), "sanity"); 678 DumpTimeClassInfo* p = get_info(ik); 679 p->set_failed_verification(); 680 } 681 682 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) { 683 assert(CDSConfig::is_dumping_archive(), "sanity"); 684 DumpTimeClassInfo* p = _dumptime_table->get(ik); 685 return (p == nullptr) ? false : p->failed_verification(); 686 } 687 688 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) { 689 assert_lock_strong(DumpTimeTable_lock); 690 691 auto do_klass = [&] (InstanceKlass* k, DumpTimeClassInfo& info) { 692 if (k->is_loader_alive() && !info.is_excluded()) { 693 info.metaspace_pointers_do(it); 694 } 695 }; 696 _dumptime_table->iterate_all_live_classes(do_klass); 697 698 auto do_lambda = [&] (LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) { 699 if (key.caller_ik()->is_loader_alive()) { 700 info.metaspace_pointers_do(it); 701 key.metaspace_pointers_do(it); 702 } 703 }; 704 _dumptime_lambda_proxy_class_dictionary->iterate_all(do_lambda); 705 } 706 707 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name, 708 Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) { 709 assert(CDSConfig::is_dumping_archive(), "sanity"); 710 DumpTimeClassInfo* info = get_info(k); 711 info->add_verification_constraint(k, name, from_name, from_field_is_protected, 712 from_is_array, from_is_object); 713 714 if (CDSConfig::is_dumping_dynamic_archive()) { 715 // For dynamic dumping, we can resolve all the constraint classes for all class loaders during 716 // the initial run prior to creating the archive before vm exit. We will also perform verification 717 // check when running with the archive. 718 return false; 719 } else { 720 if (is_builtin(k)) { 721 // For builtin class loaders, we can try to complete the verification check at dump time, 722 // because we can resolve all the constraint classes. We will also perform verification check 723 // when running with the archive. 724 return false; 725 } else { 726 // For non-builtin class loaders, we cannot complete the verification check at dump time, 727 // because at dump time we don't know how to resolve classes for such loaders. 728 return true; 729 } 730 } 731 } 732 733 void SystemDictionaryShared::add_enum_klass_static_field(InstanceKlass* ik, int root_index) { 734 assert(CDSConfig::is_dumping_heap(), "sanity"); 735 DumpTimeClassInfo* info = get_info_locked(ik); 736 info->add_enum_klass_static_field(root_index); 737 } 738 739 void SystemDictionaryShared::add_to_dump_time_lambda_proxy_class_dictionary(LambdaProxyClassKey& key, 740 InstanceKlass* proxy_klass) { 741 assert_lock_strong(DumpTimeTable_lock); 742 743 bool created; 744 DumpTimeLambdaProxyClassInfo* info = _dumptime_lambda_proxy_class_dictionary->put_if_absent(key, &created); 745 info->add_proxy_klass(proxy_klass); 746 if (created) { 747 ++_dumptime_lambda_proxy_class_dictionary->_count; 748 } 749 } 750 751 void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik, 752 InstanceKlass* lambda_ik, 753 Symbol* invoked_name, 754 Symbol* invoked_type, 755 Symbol* method_type, 756 Method* member_method, 757 Symbol* instantiated_method_type, 758 TRAPS) { 759 760 assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader"); 761 assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data"); 762 assert(java_lang_Class::class_data(lambda_ik->java_mirror()) == nullptr, "must not have class data"); 763 764 MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag); 765 766 lambda_ik->assign_class_loader_type(); 767 lambda_ik->set_shared_classpath_index(caller_ik->shared_classpath_index()); 768 InstanceKlass* nest_host = caller_ik->nest_host(CHECK); 769 assert(nest_host != nullptr, "unexpected nullptr nest_host"); 770 771 DumpTimeClassInfo* info = _dumptime_table->get(lambda_ik); 772 if (info != nullptr && !lambda_ik->is_non_strong_hidden() && is_builtin(lambda_ik) && is_builtin(caller_ik) 773 // Don't include the lambda proxy if its nest host is not in the "linked" state. 774 && nest_host->is_linked()) { 775 // Set _is_archived_lambda_proxy in DumpTimeClassInfo so that the lambda_ik 776 // won't be excluded during dumping of shared archive. See ExcludeDumpTimeSharedClasses. 777 info->_is_archived_lambda_proxy = true; 778 info->set_nest_host(nest_host); 779 780 LambdaProxyClassKey key(caller_ik, 781 invoked_name, 782 invoked_type, 783 method_type, 784 member_method, 785 instantiated_method_type); 786 add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik); 787 } 788 } 789 790 InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik, 791 Symbol* invoked_name, 792 Symbol* invoked_type, 793 Symbol* method_type, 794 Method* member_method, 795 Symbol* instantiated_method_type) { 796 MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag); 797 LambdaProxyClassKey key(caller_ik, invoked_name, invoked_type, 798 method_type, member_method, instantiated_method_type); 799 800 // Try to retrieve the lambda proxy class from static archive. 801 const RunTimeLambdaProxyClassInfo* info = _static_archive.lookup_lambda_proxy_class(&key); 802 InstanceKlass* proxy_klass = retrieve_lambda_proxy_class(info); 803 if (proxy_klass == nullptr) { 804 if (info != nullptr && log_is_enabled(Debug, cds)) { 805 ResourceMark rm; 806 log_debug(cds)("Used all static archived lambda proxy classes for: %s %s%s", 807 caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string()); 808 } 809 } else { 810 return proxy_klass; 811 } 812 813 // Retrieving from static archive is unsuccessful, try dynamic archive. 814 info = _dynamic_archive.lookup_lambda_proxy_class(&key); 815 proxy_klass = retrieve_lambda_proxy_class(info); 816 if (proxy_klass == nullptr) { 817 if (info != nullptr && log_is_enabled(Debug, cds)) { 818 ResourceMark rm; 819 log_debug(cds)("Used all dynamic archived lambda proxy classes for: %s %s%s", 820 caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string()); 821 } 822 } 823 return proxy_klass; 824 } 825 826 InstanceKlass* SystemDictionaryShared::retrieve_lambda_proxy_class(const RunTimeLambdaProxyClassInfo* info) { 827 InstanceKlass* proxy_klass = nullptr; 828 if (info != nullptr) { 829 InstanceKlass* curr_klass = info->proxy_klass_head(); 830 InstanceKlass* prev_klass = curr_klass; 831 if (curr_klass->lambda_proxy_is_available()) { 832 while (curr_klass->next_link() != nullptr) { 833 prev_klass = curr_klass; 834 curr_klass = InstanceKlass::cast(curr_klass->next_link()); 835 } 836 assert(curr_klass->is_hidden(), "must be"); 837 assert(curr_klass->lambda_proxy_is_available(), "must be"); 838 839 prev_klass->set_next_link(nullptr); 840 proxy_klass = curr_klass; 841 proxy_klass->clear_lambda_proxy_is_available(); 842 if (log_is_enabled(Debug, cds)) { 843 ResourceMark rm; 844 log_debug(cds)("Loaded lambda proxy: %s ", proxy_klass->external_name()); 845 } 846 } 847 } 848 return proxy_klass; 849 } 850 851 InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) { 852 assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only"); 853 RunTimeClassInfo* record = RunTimeClassInfo::get_for(lambda_ik); 854 return record->nest_host(); 855 } 856 857 InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik, 858 InstanceKlass* caller_ik, TRAPS) { 859 Handle class_loader(THREAD, caller_ik->class_loader()); 860 Handle protection_domain; 861 PackageEntry* pkg_entry = caller_ik->package(); 862 if (caller_ik->class_loader() != nullptr) { 863 protection_domain = CDSProtectionDomain::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL); 864 } 865 866 InstanceKlass* shared_nest_host = get_shared_nest_host(lambda_ik); 867 assert(shared_nest_host != nullptr, "unexpected nullptr _nest_host"); 868 869 InstanceKlass* loaded_lambda = 870 SystemDictionary::load_shared_lambda_proxy_class(lambda_ik, class_loader, protection_domain, pkg_entry, CHECK_NULL); 871 872 if (loaded_lambda == nullptr) { 873 return nullptr; 874 } 875 876 // Ensures the nest host is the same as the lambda proxy's 877 // nest host recorded at dump time. 878 InstanceKlass* nest_host = caller_ik->nest_host(THREAD); 879 assert(nest_host == shared_nest_host, "mismatched nest host"); 880 881 EventClassLoad class_load_start_event; 882 883 // Add to class hierarchy, and do possible deoptimizations. 884 loaded_lambda->add_to_hierarchy(THREAD); 885 // But, do not add to dictionary. 886 887 loaded_lambda->link_class(CHECK_NULL); 888 // notify jvmti 889 if (JvmtiExport::should_post_class_load()) { 890 JvmtiExport::post_class_load(THREAD, loaded_lambda); 891 } 892 if (class_load_start_event.should_commit()) { 893 SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader())); 894 } 895 896 loaded_lambda->initialize(CHECK_NULL); 897 898 return loaded_lambda; 899 } 900 901 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass, 902 TRAPS) { 903 assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only"); 904 RunTimeClassInfo* record = RunTimeClassInfo::get_for(klass); 905 906 int length = record->_num_verifier_constraints; 907 if (length > 0) { 908 for (int i = 0; i < length; i++) { 909 RunTimeClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i); 910 Symbol* name = vc->name(); 911 Symbol* from_name = vc->from_name(); 912 char c = record->verifier_constraint_flag(i); 913 914 if (log_is_enabled(Trace, cds, verification)) { 915 ResourceMark rm(THREAD); 916 log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]", 917 klass->external_name(), from_name->as_klass_external_name(), 918 name->as_klass_external_name(), c); 919 } 920 921 bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false; 922 bool from_is_array = (c & SystemDictionaryShared::FROM_IS_ARRAY) ? true : false; 923 bool from_is_object = (c & SystemDictionaryShared::FROM_IS_OBJECT) ? true : false; 924 925 bool ok = VerificationType::resolve_and_check_assignability(klass, name, 926 from_name, from_field_is_protected, from_is_array, from_is_object, CHECK); 927 if (!ok) { 928 ResourceMark rm(THREAD); 929 stringStream ss; 930 931 ss.print_cr("Bad type on operand stack"); 932 ss.print_cr("Exception Details:"); 933 ss.print_cr(" Location:\n %s", klass->name()->as_C_string()); 934 ss.print_cr(" Reason:\n Type '%s' is not assignable to '%s'", 935 from_name->as_quoted_ascii(), name->as_quoted_ascii()); 936 THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string()); 937 } 938 } 939 } 940 } 941 942 static oop get_class_loader_by(char type) { 943 if (type == (char)ClassLoader::BOOT_LOADER) { 944 return (oop)nullptr; 945 } else if (type == (char)ClassLoader::PLATFORM_LOADER) { 946 return SystemDictionary::java_platform_loader(); 947 } else { 948 assert (type == (char)ClassLoader::APP_LOADER, "Sanity"); 949 return SystemDictionary::java_system_loader(); 950 } 951 } 952 953 // Record class loader constraints that are checked inside 954 // InstanceKlass::link_class(), so that these can be checked quickly 955 // at runtime without laying out the vtable/itables. 956 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass, 957 Handle loader1, Handle loader2) { 958 // A linking constraint check is executed when: 959 // - klass extends or implements type S 960 // - klass overrides method S.M(...) with X.M 961 // - If klass defines the method M, X is 962 // the same as klass. 963 // - If klass does not define the method M, 964 // X must be a supertype of klass and X.M is 965 // a default method defined by X. 966 // - loader1 = X->class_loader() 967 // - loader2 = S->class_loader() 968 // - loader1 != loader2 969 // - M's parameter(s) include an object type T 970 // We require that 971 // - whenever loader1 and loader2 try to 972 // resolve the type T, they must always resolve to 973 // the same InstanceKlass. 974 // NOTE: type T may or may not be currently resolved in 975 // either of these two loaders. The check itself does not 976 // try to resolve T. 977 oop klass_loader = klass->class_loader(); 978 979 if (!is_system_class_loader(klass_loader) && 980 !is_platform_class_loader(klass_loader)) { 981 // If klass is loaded by system/platform loaders, we can 982 // guarantee that klass and S must be loaded by the same 983 // respective loader between dump time and run time, and 984 // the exact same check on (name, loader1, loader2) will 985 // be executed. Hence, we can cache this check and execute 986 // it at runtime without walking the vtable/itables. 987 // 988 // This cannot be guaranteed for classes loaded by other 989 // loaders, so we bail. 990 return; 991 } 992 993 assert(is_builtin(klass), "must be"); 994 assert(klass_loader != nullptr, "should not be called for boot loader"); 995 assert(loader1 != loader2, "must be"); 996 997 if (CDSConfig::is_dumping_dynamic_archive() && Thread::current()->is_VM_thread()) { 998 // We are re-laying out the vtable/itables of the *copy* of 999 // a class during the final stage of dynamic dumping. The 1000 // linking constraints for this class has already been recorded. 1001 return; 1002 } 1003 assert(!Thread::current()->is_VM_thread(), "must be"); 1004 1005 assert(CDSConfig::is_dumping_archive(), "sanity"); 1006 DumpTimeClassInfo* info = get_info(klass); 1007 info->record_linking_constraint(name, loader1, loader2); 1008 } 1009 1010 // returns true IFF there's no need to re-initialize the i/v-tables for klass for 1011 // the purpose of checking class loader constraints. 1012 bool SystemDictionaryShared::check_linking_constraints(Thread* current, InstanceKlass* klass) { 1013 assert(!CDSConfig::is_dumping_static_archive() && CDSConfig::is_using_archive(), "called at run time with CDS enabled only"); 1014 LogTarget(Info, class, loader, constraints) log; 1015 if (klass->is_shared_boot_class()) { 1016 // No class loader constraint check performed for boot classes. 1017 return true; 1018 } 1019 if (klass->is_shared_platform_class() || klass->is_shared_app_class()) { 1020 RunTimeClassInfo* info = RunTimeClassInfo::get_for(klass); 1021 assert(info != nullptr, "Sanity"); 1022 if (info->_num_loader_constraints > 0) { 1023 HandleMark hm(current); 1024 for (int i = 0; i < info->_num_loader_constraints; i++) { 1025 RunTimeClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i); 1026 Symbol* name = lc->constraint_name(); 1027 Handle loader1(current, get_class_loader_by(lc->_loader_type1)); 1028 Handle loader2(current, get_class_loader_by(lc->_loader_type2)); 1029 if (log.is_enabled()) { 1030 ResourceMark rm(current); 1031 log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s", 1032 klass->external_name(), name->as_C_string(), 1033 ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(), 1034 ClassLoaderData::class_loader_data(loader2())->loader_name_and_id()); 1035 } 1036 if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2)) { 1037 // Loader constraint violation has been found. The caller 1038 // will re-layout the vtable/itables to produce the correct 1039 // exception. 1040 if (log.is_enabled()) { 1041 log.print(" failed]"); 1042 } 1043 return false; 1044 } 1045 if (log.is_enabled()) { 1046 log.print(" succeeded]"); 1047 } 1048 } 1049 return true; // for all recorded constraints added successfully. 1050 } 1051 } 1052 if (log.is_enabled()) { 1053 ResourceMark rm(current); 1054 log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name()); 1055 } 1056 return false; 1057 } 1058 1059 bool SystemDictionaryShared::is_supported_invokedynamic(BootstrapInfo* bsi) { 1060 LogTarget(Debug, cds, lambda) log; 1061 if (bsi->arg_values() == nullptr || !bsi->arg_values()->is_objArray()) { 1062 if (log.is_enabled()) { 1063 LogStream log_stream(log); 1064 log.print("bsi check failed"); 1065 log.print(" bsi->arg_values().not_null() %d", bsi->arg_values().not_null()); 1066 if (bsi->arg_values().not_null()) { 1067 log.print(" bsi->arg_values()->is_objArray() %d", bsi->arg_values()->is_objArray()); 1068 bsi->print_msg_on(&log_stream); 1069 } 1070 } 1071 return false; 1072 } 1073 1074 Handle bsm = bsi->bsm(); 1075 if (bsm.is_null() || !java_lang_invoke_DirectMethodHandle::is_instance(bsm())) { 1076 if (log.is_enabled()) { 1077 log.print("bsm check failed"); 1078 log.print(" bsm.is_null() %d", bsm.is_null()); 1079 log.print(" java_lang_invoke_DirectMethodHandle::is_instance(bsm()) %d", 1080 java_lang_invoke_DirectMethodHandle::is_instance(bsm())); 1081 } 1082 return false; 1083 } 1084 1085 oop mn = java_lang_invoke_DirectMethodHandle::member(bsm()); 1086 Method* method = java_lang_invoke_MemberName::vmtarget(mn); 1087 if (method->klass_name()->equals("java/lang/invoke/LambdaMetafactory") && 1088 method->name()->equals("metafactory") && 1089 method->signature()->equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;" 1090 "Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;" 1091 "Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;")) { 1092 return true; 1093 } else { 1094 if (log.is_enabled()) { 1095 ResourceMark rm; 1096 log.print("method check failed"); 1097 log.print(" klass_name() %s", method->klass_name()->as_C_string()); 1098 log.print(" name() %s", method->name()->as_C_string()); 1099 log.print(" signature() %s", method->signature()->as_C_string()); 1100 } 1101 } 1102 1103 return false; 1104 } 1105 1106 class EstimateSizeForArchive : StackObj { 1107 size_t _shared_class_info_size; 1108 int _num_builtin_klasses; 1109 int _num_unregistered_klasses; 1110 1111 public: 1112 EstimateSizeForArchive() { 1113 _shared_class_info_size = 0; 1114 _num_builtin_klasses = 0; 1115 _num_unregistered_klasses = 0; 1116 } 1117 1118 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) { 1119 if (!info.is_excluded()) { 1120 size_t byte_size = info.runtime_info_bytesize(); 1121 _shared_class_info_size += align_up(byte_size, SharedSpaceObjectAlignment); 1122 } 1123 } 1124 1125 size_t total() { 1126 return _shared_class_info_size; 1127 } 1128 }; 1129 1130 size_t SystemDictionaryShared::estimate_size_for_archive() { 1131 EstimateSizeForArchive est; 1132 _dumptime_table->iterate_all_live_classes(&est); 1133 size_t total_size = est.total() + 1134 CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) + 1135 CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false)); 1136 1137 size_t bytesize = align_up(sizeof(RunTimeLambdaProxyClassInfo), SharedSpaceObjectAlignment); 1138 total_size += 1139 (bytesize * _dumptime_lambda_proxy_class_dictionary->_count) + 1140 CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count); 1141 1142 return total_size; 1143 } 1144 1145 unsigned int SystemDictionaryShared::hash_for_shared_dictionary(address ptr) { 1146 if (ArchiveBuilder::is_active()) { 1147 uintx offset = ArchiveBuilder::current()->any_to_offset(ptr); 1148 unsigned int hash = primitive_hash<uintx>(offset); 1149 DEBUG_ONLY({ 1150 if (MetaspaceObj::is_shared((const MetaspaceObj*)ptr)) { 1151 assert(hash == SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr), "must be"); 1152 } 1153 }); 1154 return hash; 1155 } else { 1156 return SystemDictionaryShared::hash_for_shared_dictionary_quick(ptr); 1157 } 1158 } 1159 1160 class CopyLambdaProxyClassInfoToArchive : StackObj { 1161 CompactHashtableWriter* _writer; 1162 ArchiveBuilder* _builder; 1163 public: 1164 CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer) 1165 : _writer(writer), _builder(ArchiveBuilder::current()) {} 1166 bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) { 1167 // In static dump, info._proxy_klasses->at(0) is already relocated to point to the archived class 1168 // (not the original class). 1169 // 1170 // The following check has been moved to SystemDictionaryShared::check_excluded_classes(), which 1171 // happens before the classes are copied. 1172 // 1173 // if (SystemDictionaryShared::is_excluded_class(info._proxy_klasses->at(0))) { 1174 // return true; 1175 //} 1176 ResourceMark rm; 1177 log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klasses->at(0)->external_name()); 1178 size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo); 1179 RunTimeLambdaProxyClassInfo* runtime_info = 1180 (RunTimeLambdaProxyClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size); 1181 runtime_info->init(key, info); 1182 unsigned int hash = runtime_info->hash(); 1183 u4 delta = _builder->any_to_offset_u4((void*)runtime_info); 1184 _writer->add(hash, delta); 1185 return true; 1186 } 1187 }; 1188 1189 class AdjustLambdaProxyClassInfo : StackObj { 1190 public: 1191 AdjustLambdaProxyClassInfo() {} 1192 bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) { 1193 int len = info._proxy_klasses->length(); 1194 InstanceKlass* last_buff_k = nullptr; 1195 1196 for (int i = len - 1; i >= 0; i--) { 1197 InstanceKlass* orig_k = info._proxy_klasses->at(i); 1198 InstanceKlass* buff_k = ArchiveBuilder::current()->get_buffered_addr(orig_k); 1199 assert(ArchiveBuilder::current()->is_in_buffer_space(buff_k), "must be"); 1200 buff_k->set_lambda_proxy_is_available(); 1201 buff_k->set_next_link(last_buff_k); 1202 if (last_buff_k != nullptr) { 1203 ArchivePtrMarker::mark_pointer(buff_k->next_link_addr()); 1204 } 1205 last_buff_k = buff_k; 1206 } 1207 1208 return true; 1209 } 1210 }; 1211 1212 class CopySharedClassInfoToArchive : StackObj { 1213 CompactHashtableWriter* _writer; 1214 bool _is_builtin; 1215 ArchiveBuilder *_builder; 1216 public: 1217 CopySharedClassInfoToArchive(CompactHashtableWriter* writer, 1218 bool is_builtin) 1219 : _writer(writer), _is_builtin(is_builtin), _builder(ArchiveBuilder::current()) {} 1220 1221 void do_entry(InstanceKlass* k, DumpTimeClassInfo& info) { 1222 if (!info.is_excluded() && info.is_builtin() == _is_builtin) { 1223 size_t byte_size = info.runtime_info_bytesize(); 1224 RunTimeClassInfo* record; 1225 record = (RunTimeClassInfo*)ArchiveBuilder::ro_region_alloc(byte_size); 1226 record->init(info); 1227 1228 unsigned int hash; 1229 Symbol* name = info._klass->name(); 1230 name = ArchiveBuilder::current()->get_buffered_addr(name); 1231 hash = SystemDictionaryShared::hash_for_shared_dictionary((address)name); 1232 u4 delta = _builder->buffer_to_offset_u4((address)record); 1233 if (_is_builtin && info._klass->is_hidden()) { 1234 // skip 1235 } else { 1236 _writer->add(hash, delta); 1237 } 1238 if (log_is_enabled(Trace, cds, hashtables)) { 1239 ResourceMark rm; 1240 log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name()); 1241 } 1242 1243 // Save this for quick runtime lookup of InstanceKlass* -> RunTimeClassInfo* 1244 InstanceKlass* buffered_klass = ArchiveBuilder::current()->get_buffered_addr(info._klass); 1245 RunTimeClassInfo::set_for(buffered_klass, record); 1246 } 1247 } 1248 }; 1249 1250 void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) { 1251 CompactHashtableStats stats; 1252 dictionary->reset(); 1253 CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats); 1254 CopyLambdaProxyClassInfoToArchive copy(&writer); 1255 _dumptime_lambda_proxy_class_dictionary->iterate(©); 1256 writer.dump(dictionary, "lambda proxy class dictionary"); 1257 } 1258 1259 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary, 1260 bool is_builtin) { 1261 CompactHashtableStats stats; 1262 dictionary->reset(); 1263 CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats); 1264 CopySharedClassInfoToArchive copy(&writer, is_builtin); 1265 assert_lock_strong(DumpTimeTable_lock); 1266 _dumptime_table->iterate_all_live_classes(©); 1267 writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary"); 1268 } 1269 1270 void SystemDictionaryShared::write_to_archive(bool is_static_archive) { 1271 ArchiveInfo* archive = get_archive(is_static_archive); 1272 1273 write_dictionary(&archive->_builtin_dictionary, true); 1274 write_dictionary(&archive->_unregistered_dictionary, false); 1275 1276 write_lambda_proxy_class_dictionary(&archive->_lambda_proxy_class_dictionary); 1277 } 1278 1279 void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() { 1280 AdjustLambdaProxyClassInfo adjuster; 1281 _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster); 1282 } 1283 1284 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc, 1285 bool is_static_archive) { 1286 ArchiveInfo* archive = get_archive(is_static_archive); 1287 1288 archive->_builtin_dictionary.serialize_header(soc); 1289 archive->_unregistered_dictionary.serialize_header(soc); 1290 archive->_lambda_proxy_class_dictionary.serialize_header(soc); 1291 } 1292 1293 void SystemDictionaryShared::serialize_vm_classes(SerializeClosure* soc) { 1294 for (auto id : EnumRange<vmClassID>{}) { 1295 soc->do_ptr(vmClasses::klass_addr_at(id)); 1296 } 1297 } 1298 1299 const RunTimeClassInfo* 1300 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) { 1301 if (!CDSConfig::is_using_archive() || !name->is_shared()) { 1302 // The names of all shared classes must also be a shared Symbol. 1303 return nullptr; 1304 } 1305 1306 unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary_quick(name); 1307 const RunTimeClassInfo* record = nullptr; 1308 if (DynamicArchive::is_mapped()) { 1309 // Use the regenerated holder classes in the dynamic archive as they 1310 // have more methods than those in the base archive. 1311 if (name == vmSymbols::java_lang_invoke_Invokers_Holder() || 1312 name == vmSymbols::java_lang_invoke_DirectMethodHandle_Holder() || 1313 name == vmSymbols::java_lang_invoke_LambdaForm_Holder() || 1314 name == vmSymbols::java_lang_invoke_DelegatingMethodHandle_Holder()) { 1315 record = dynamic_dict->lookup(name, hash, 0); 1316 if (record != nullptr) { 1317 return record; 1318 } 1319 } 1320 } 1321 1322 if (!MetaspaceShared::is_shared_dynamic(name)) { 1323 // The names of all shared classes in the static dict must also be in the 1324 // static archive 1325 record = static_dict->lookup(name, hash, 0); 1326 } 1327 1328 if (record == nullptr && DynamicArchive::is_mapped()) { 1329 record = dynamic_dict->lookup(name, hash, 0); 1330 } 1331 1332 return record; 1333 } 1334 1335 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) { 1336 const RunTimeClassInfo* record = find_record(&_static_archive._builtin_dictionary, 1337 &_dynamic_archive._builtin_dictionary, 1338 name); 1339 if (record != nullptr) { 1340 assert(!record->_klass->is_hidden(), "hidden class cannot be looked up by name"); 1341 #ifdef _LP64 1342 if (UseCompressedClassPointers) { 1343 DEBUG_ONLY(CompressedKlassPointers::check_valid_klass(record->_klass);) 1344 } 1345 #endif 1346 // We did not save the classfile data of the generated LambdaForm invoker classes, 1347 // so we cannot support CLFH for such classes. 1348 if (record->_klass->is_generated_shared_class() && JvmtiExport::should_post_class_file_load_hook()) { 1349 return nullptr; 1350 } 1351 return record->_klass; 1352 } else { 1353 return nullptr; 1354 } 1355 } 1356 1357 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) { 1358 assert(CDSConfig::is_dumping_static_archive(), "class ID is used only for static dump (from classlist)"); 1359 DumpTimeClassInfo* info = get_info(k); 1360 info->_id = id; 1361 } 1362 1363 static const char* class_loader_name_for_shared(Klass* k) { 1364 assert(k != nullptr, "Sanity"); 1365 assert(k->is_shared(), "Must be"); 1366 assert(k->is_instance_klass(), "Must be"); 1367 InstanceKlass* ik = InstanceKlass::cast(k); 1368 if (ik->is_shared_boot_class()) { 1369 return "boot_loader"; 1370 } else if (ik->is_shared_platform_class()) { 1371 return "platform_loader"; 1372 } else if (ik->is_shared_app_class()) { 1373 return "app_loader"; 1374 } else if (ik->is_shared_unregistered_class()) { 1375 return "unregistered_loader"; 1376 } else { 1377 return "unknown loader"; 1378 } 1379 } 1380 1381 class SharedDictionaryPrinter : StackObj { 1382 outputStream* _st; 1383 int _index; 1384 public: 1385 SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {} 1386 1387 void do_value(const RunTimeClassInfo* record) { 1388 ResourceMark rm; 1389 _st->print_cr("%4d: %s %s", _index++, record->_klass->external_name(), 1390 class_loader_name_for_shared(record->_klass)); 1391 if (record->_klass->array_klasses() != nullptr) { 1392 record->_klass->array_klasses()->cds_print_value_on(_st); 1393 _st->cr(); 1394 } 1395 } 1396 int index() const { return _index; } 1397 }; 1398 1399 class SharedLambdaDictionaryPrinter : StackObj { 1400 outputStream* _st; 1401 int _index; 1402 public: 1403 SharedLambdaDictionaryPrinter(outputStream* st, int idx) : _st(st), _index(idx) {} 1404 1405 void do_value(const RunTimeLambdaProxyClassInfo* record) { 1406 if (record->proxy_klass_head()->lambda_proxy_is_available()) { 1407 ResourceMark rm; 1408 Klass* k = record->proxy_klass_head(); 1409 while (k != nullptr) { 1410 _st->print_cr("%4d: %s %s", _index++, k->external_name(), 1411 class_loader_name_for_shared(k)); 1412 k = k->next_link(); 1413 } 1414 } 1415 } 1416 }; 1417 1418 void SystemDictionaryShared::ArchiveInfo::print_on(const char* prefix, 1419 outputStream* st) { 1420 st->print_cr("%sShared Dictionary", prefix); 1421 SharedDictionaryPrinter p(st); 1422 st->print_cr("%sShared Builtin Dictionary", prefix); 1423 _builtin_dictionary.iterate(&p); 1424 st->print_cr("%sShared Unregistered Dictionary", prefix); 1425 _unregistered_dictionary.iterate(&p); 1426 if (!_lambda_proxy_class_dictionary.empty()) { 1427 st->print_cr("%sShared Lambda Dictionary", prefix); 1428 SharedLambdaDictionaryPrinter ldp(st, p.index()); 1429 _lambda_proxy_class_dictionary.iterate(&ldp); 1430 } 1431 } 1432 1433 void SystemDictionaryShared::ArchiveInfo::print_table_statistics(const char* prefix, 1434 outputStream* st) { 1435 st->print_cr("%sArchve Statistics", prefix); 1436 _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary"); 1437 _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary"); 1438 _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary"); 1439 } 1440 1441 void SystemDictionaryShared::print_shared_archive(outputStream* st, bool is_static) { 1442 if (CDSConfig::is_using_archive()) { 1443 if (is_static) { 1444 _static_archive.print_on("", st); 1445 } else { 1446 if (DynamicArchive::is_mapped()) { 1447 _dynamic_archive.print_on("Dynamic ", st); 1448 } 1449 } 1450 } 1451 } 1452 1453 void SystemDictionaryShared::print_on(outputStream* st) { 1454 print_shared_archive(st, true); 1455 print_shared_archive(st, false); 1456 } 1457 1458 void SystemDictionaryShared::print_table_statistics(outputStream* st) { 1459 if (CDSConfig::is_using_archive()) { 1460 _static_archive.print_table_statistics("Static ", st); 1461 if (DynamicArchive::is_mapped()) { 1462 _dynamic_archive.print_table_statistics("Dynamic ", st); 1463 } 1464 } 1465 } 1466 1467 bool SystemDictionaryShared::is_dumptime_table_empty() { 1468 assert_lock_strong(DumpTimeTable_lock); 1469 _dumptime_table->update_counts(); 1470 if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){ 1471 return true; 1472 } 1473 return false; 1474 } 1475 1476 class CleanupDumpTimeLambdaProxyClassTable: StackObj { 1477 public: 1478 bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) { 1479 assert_lock_strong(DumpTimeTable_lock); 1480 InstanceKlass* caller_ik = key.caller_ik(); 1481 InstanceKlass* nest_host = caller_ik->nest_host_not_null(); 1482 1483 // If the caller class and/or nest_host are excluded, the associated lambda proxy 1484 // must also be excluded. 1485 bool always_exclude = SystemDictionaryShared::check_for_exclusion(caller_ik, nullptr) || 1486 SystemDictionaryShared::check_for_exclusion(nest_host, nullptr); 1487 1488 for (int i = info._proxy_klasses->length() - 1; i >= 0; i--) { 1489 InstanceKlass* ik = info._proxy_klasses->at(i); 1490 if (always_exclude || SystemDictionaryShared::check_for_exclusion(ik, nullptr)) { 1491 SystemDictionaryShared::reset_registered_lambda_proxy_class(ik); 1492 info._proxy_klasses->remove_at(i); 1493 } 1494 } 1495 return info._proxy_klasses->length() == 0 ? true /* delete the node*/ : false; 1496 } 1497 }; 1498 1499 void SystemDictionaryShared::cleanup_lambda_proxy_class_dictionary() { 1500 assert_lock_strong(DumpTimeTable_lock); 1501 CleanupDumpTimeLambdaProxyClassTable cleanup_proxy_classes; 1502 _dumptime_lambda_proxy_class_dictionary->unlink(&cleanup_proxy_classes); 1503 }