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