1 /* 2 * Copyright (c) 1997, 2020, 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 "jvm.h" 27 #include "aot/aotLoader.hpp" 28 #include "classfile/classFileParser.hpp" 29 #include "classfile/classFileStream.hpp" 30 #include "classfile/classLoader.hpp" 31 #include "classfile/classLoaderData.inline.hpp" 32 #include "classfile/classLoaderDataGraph.inline.hpp" 33 #include "classfile/classLoaderExt.hpp" 34 #include "classfile/dictionary.hpp" 35 #include "classfile/javaClasses.inline.hpp" 36 #include "classfile/klassFactory.hpp" 37 #include "classfile/loaderConstraints.hpp" 38 #include "classfile/packageEntry.hpp" 39 #include "classfile/placeholders.hpp" 40 #include "classfile/protectionDomainCache.hpp" 41 #include "classfile/resolutionErrors.hpp" 42 #include "classfile/stringTable.hpp" 43 #include "classfile/symbolTable.hpp" 44 #include "classfile/systemDictionary.hpp" 45 #include "classfile/vmSymbols.hpp" 46 #include "code/codeCache.hpp" 47 #include "compiler/compileBroker.hpp" 48 #include "gc/shared/gcTraceTime.inline.hpp" 49 #include "gc/shared/oopStorage.inline.hpp" 50 #include "gc/shared/oopStorageSet.hpp" 51 #include "interpreter/bytecodeStream.hpp" 52 #include "interpreter/interpreter.hpp" 53 #include "jfr/jfrEvents.hpp" 54 #include "logging/log.hpp" 55 #include "logging/logStream.hpp" 56 #include "memory/filemap.hpp" 57 #include "memory/heapShared.hpp" 58 #include "memory/metaspaceClosure.hpp" 59 #include "memory/oopFactory.hpp" 60 #include "memory/resourceArea.hpp" 61 #include "memory/universe.hpp" 62 #include "oops/access.inline.hpp" 63 #include "oops/instanceKlass.hpp" 64 #include "oops/instanceRefKlass.hpp" 65 #include "oops/klass.inline.hpp" 66 #include "oops/method.inline.hpp" 67 #include "oops/methodData.hpp" 68 #include "oops/objArrayKlass.hpp" 69 #include "oops/objArrayOop.inline.hpp" 70 #include "oops/oop.inline.hpp" 71 #include "oops/symbol.hpp" 72 #include "oops/typeArrayKlass.hpp" 73 #include "prims/jvmtiExport.hpp" 74 #include "prims/methodHandles.hpp" 75 #include "runtime/arguments.hpp" 76 #include "runtime/biasedLocking.hpp" 77 #include "runtime/handles.inline.hpp" 78 #include "runtime/java.hpp" 79 #include "runtime/javaCalls.hpp" 80 #include "runtime/mutexLocker.hpp" 81 #include "runtime/sharedRuntime.hpp" 82 #include "runtime/signature.hpp" 83 #include "services/classLoadingService.hpp" 84 #include "services/diagnosticCommand.hpp" 85 #include "services/threadService.hpp" 86 #include "utilities/macros.hpp" 87 #if INCLUDE_CDS 88 #include "classfile/systemDictionaryShared.hpp" 89 #endif 90 #if INCLUDE_JFR 91 #include "jfr/jfr.hpp" 92 #endif 93 94 PlaceholderTable* SystemDictionary::_placeholders = NULL; 95 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL; 96 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL; 97 SymbolPropertyTable* SystemDictionary::_invoke_method_table = NULL; 98 ProtectionDomainCacheTable* SystemDictionary::_pd_cache_table = NULL; 99 100 oop SystemDictionary::_system_loader_lock_obj = NULL; 101 102 InstanceKlass* SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT] 103 = { NULL /*, NULL...*/ }; 104 105 InstanceKlass* SystemDictionary::_box_klasses[T_VOID+1] = { NULL /*, NULL...*/ }; 106 107 oop SystemDictionary::_java_system_loader = NULL; 108 oop SystemDictionary::_java_platform_loader = NULL; 109 110 // Default ProtectionDomainCacheSize value 111 112 const int defaultProtectionDomainCacheSize = 1009; 113 114 // ---------------------------------------------------------------------------- 115 // Java-level SystemLoader and PlatformLoader 116 117 oop SystemDictionary::java_system_loader() { 118 return _java_system_loader; 119 } 120 121 oop SystemDictionary::java_platform_loader() { 122 return _java_platform_loader; 123 } 124 125 void SystemDictionary::compute_java_loaders(TRAPS) { 126 JavaValue result(T_OBJECT); 127 InstanceKlass* class_loader_klass = SystemDictionary::ClassLoader_klass(); 128 JavaCalls::call_static(&result, 129 class_loader_klass, 130 vmSymbols::getSystemClassLoader_name(), 131 vmSymbols::void_classloader_signature(), 132 CHECK); 133 134 _java_system_loader = (oop)result.get_jobject(); 135 136 JavaCalls::call_static(&result, 137 class_loader_klass, 138 vmSymbols::getPlatformClassLoader_name(), 139 vmSymbols::void_classloader_signature(), 140 CHECK); 141 142 _java_platform_loader = (oop)result.get_jobject(); 143 } 144 145 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader) { 146 if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data(); 147 return ClassLoaderDataGraph::find_or_create(class_loader); 148 } 149 150 // ---------------------------------------------------------------------------- 151 // Parallel class loading check 152 153 bool SystemDictionary::is_parallelCapable(Handle class_loader) { 154 if (class_loader.is_null()) return true; 155 if (AlwaysLockClassLoader) return false; 156 return java_lang_ClassLoader::parallelCapable(class_loader()); 157 } 158 // ---------------------------------------------------------------------------- 159 // ParallelDefineClass flag does not apply to bootclass loader 160 bool SystemDictionary::is_parallelDefine(Handle class_loader) { 161 if (class_loader.is_null()) return false; 162 if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) { 163 return true; 164 } 165 return false; 166 } 167 168 // Returns true if the passed class loader is the builtin application class loader 169 // or a custom system class loader. A customer system class loader can be 170 // specified via -Djava.system.class.loader. 171 bool SystemDictionary::is_system_class_loader(oop class_loader) { 172 if (class_loader == NULL) { 173 return false; 174 } 175 return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() || 176 class_loader == _java_system_loader); 177 } 178 179 // Returns true if the passed class loader is the platform class loader. 180 bool SystemDictionary::is_platform_class_loader(oop class_loader) { 181 if (class_loader == NULL) { 182 return false; 183 } 184 return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass()); 185 } 186 187 // ---------------------------------------------------------------------------- 188 // Resolving of classes 189 190 // Forwards to resolve_or_null 191 192 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) { 193 Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD); 194 if (HAS_PENDING_EXCEPTION || klass == NULL) { 195 // can return a null klass 196 klass = handle_resolution_exception(class_name, throw_error, klass, THREAD); 197 } 198 return klass; 199 } 200 201 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name, 202 bool throw_error, 203 Klass* klass, TRAPS) { 204 if (HAS_PENDING_EXCEPTION) { 205 // If we have a pending exception we forward it to the caller, unless throw_error is true, 206 // in which case we have to check whether the pending exception is a ClassNotFoundException, 207 // and if so convert it to a NoClassDefFoundError 208 // And chain the original ClassNotFoundException 209 if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) { 210 ResourceMark rm(THREAD); 211 assert(klass == NULL, "Should not have result with exception pending"); 212 Handle e(THREAD, PENDING_EXCEPTION); 213 CLEAR_PENDING_EXCEPTION; 214 THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e); 215 } else { 216 return NULL; 217 } 218 } 219 // Class not found, throw appropriate error or exception depending on value of throw_error 220 if (klass == NULL) { 221 ResourceMark rm(THREAD); 222 if (throw_error) { 223 THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string()); 224 } else { 225 THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string()); 226 } 227 } 228 return klass; 229 } 230 231 232 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, 233 bool throw_error, TRAPS) 234 { 235 return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD); 236 } 237 238 239 // Forwards to resolve_array_class_or_null or resolve_instance_class_or_null 240 241 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) { 242 if (Signature::is_array(class_name)) { 243 return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD); 244 } else { 245 return resolve_instance_class_or_null_helper(class_name, class_loader, protection_domain, THREAD); 246 } 247 } 248 249 // name may be in the form of "java/lang/Object" or "Ljava/lang/Object;" 250 InstanceKlass* SystemDictionary::resolve_instance_class_or_null_helper(Symbol* class_name, 251 Handle class_loader, 252 Handle protection_domain, 253 TRAPS) { 254 assert(class_name != NULL && !Signature::is_array(class_name), "must be"); 255 if (Signature::has_envelope(class_name)) { 256 ResourceMark rm(THREAD); 257 // Ignore wrapping L and ;. 258 TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1, 259 class_name->utf8_length() - 2); 260 return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD); 261 } else { 262 return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD); 263 } 264 } 265 266 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) { 267 return resolve_or_null(class_name, Handle(), Handle(), THREAD); 268 } 269 270 // Forwards to resolve_instance_class_or_null 271 272 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name, 273 Handle class_loader, 274 Handle protection_domain, 275 TRAPS) { 276 assert(Signature::is_array(class_name), "must be array"); 277 ResourceMark rm(THREAD); 278 SignatureStream ss(class_name, false); 279 int ndims = ss.skip_array_prefix(); // skip all '['s 280 Klass* k = NULL; 281 BasicType t = ss.type(); 282 if (ss.has_envelope()) { 283 Symbol* obj_class = ss.as_symbol(); 284 k = SystemDictionary::resolve_instance_class_or_null(obj_class, 285 class_loader, 286 protection_domain, 287 CHECK_NULL); 288 if (k != NULL) { 289 k = k->array_klass(ndims, CHECK_NULL); 290 } 291 } else { 292 k = Universe::typeArrayKlassObj(t); 293 k = TypeArrayKlass::cast(k)->array_klass(ndims, CHECK_NULL); 294 } 295 return k; 296 } 297 298 299 // Must be called for any super-class or super-interface resolution 300 // during class definition to allow class circularity checking 301 // super-interface callers: 302 // parse_interfaces - for defineClass & jvmtiRedefineClasses 303 // super-class callers: 304 // ClassFileParser - for defineClass & jvmtiRedefineClasses 305 // load_shared_class - while loading a class from shared archive 306 // resolve_instance_class_or_null: 307 // via: handle_parallel_super_load 308 // when resolving a class that has an existing placeholder with 309 // a saved superclass [i.e. a defineClass is currently in progress] 310 // if another thread is trying to resolve the class, it must do 311 // super-class checks on its own thread to catch class circularity 312 // This last call is critical in class circularity checking for cases 313 // where classloading is delegated to different threads and the 314 // classloader lock is released. 315 // Take the case: Base->Super->Base 316 // 1. If thread T1 tries to do a defineClass of class Base 317 // resolve_super_or_fail creates placeholder: T1, Base (super Super) 318 // 2. resolve_instance_class_or_null does not find SD or placeholder for Super 319 // so it tries to load Super 320 // 3. If we load the class internally, or user classloader uses same thread 321 // loadClassFromxxx or defineClass via parseClassFile Super ... 322 // 3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base) 323 // 3.3 resolve_instance_class_or_null Base, finds placeholder for Base 324 // 3.4 calls resolve_super_or_fail Base 325 // 3.5 finds T1,Base -> throws class circularity 326 //OR 4. If T2 tries to resolve Super via defineClass Super ... 327 // 4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base) 328 // 4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super) 329 // 4.3 calls resolve_super_or_fail Super in parallel on own thread T2 330 // 4.4 finds T2, Super -> throws class circularity 331 // Must be called, even if superclass is null, since this is 332 // where the placeholder entry is created which claims this 333 // thread is loading this class/classloader. 334 // Be careful when modifying this code: once you have run 335 // placeholders()->find_and_add(PlaceholderTable::LOAD_SUPER), 336 // you need to find_and_remove it before returning. 337 // So be careful to not exit with a CHECK_ macro betweeen these calls. 338 InstanceKlass* SystemDictionary::resolve_super_or_fail(Symbol* child_name, 339 Symbol* super_name, 340 Handle class_loader, 341 Handle protection_domain, 342 bool is_superclass, 343 TRAPS) { 344 assert(!Signature::is_array(super_name), "invalid super class name"); 345 #if INCLUDE_CDS 346 if (DumpSharedSpaces) { 347 // Special processing for handling UNREGISTERED shared classes. 348 InstanceKlass* k = SystemDictionaryShared::dump_time_resolve_super_or_fail(child_name, 349 super_name, class_loader, protection_domain, is_superclass, CHECK_NULL); 350 if (k) { 351 return k; 352 } 353 } 354 #endif // INCLUDE_CDS 355 356 // Double-check, if child class is already loaded, just return super-class,interface 357 // Don't add a placedholder if already loaded, i.e. already in appropriate class loader 358 // dictionary. 359 // Make sure there's a placeholder for the *child* before resolving. 360 // Used as a claim that this thread is currently loading superclass/classloader 361 // Used here for ClassCircularity checks and also for heap verification 362 // (every InstanceKlass needs to be in its class loader dictionary or have a placeholder). 363 // Must check ClassCircularity before checking if super class is already loaded. 364 // 365 // We might not already have a placeholder if this child_name was 366 // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass); 367 // the name of the class might not be known until the stream is actually 368 // parsed. 369 // Bugs 4643874, 4715493 370 371 ClassLoaderData* loader_data = class_loader_data(class_loader); 372 Dictionary* dictionary = loader_data->dictionary(); 373 unsigned int d_hash = dictionary->compute_hash(child_name); 374 unsigned int p_hash = placeholders()->compute_hash(child_name); 375 int p_index = placeholders()->hash_to_index(p_hash); 376 // can't throw error holding a lock 377 bool child_already_loaded = false; 378 bool throw_circularity_error = false; 379 { 380 MutexLocker mu(THREAD, SystemDictionary_lock); 381 InstanceKlass* childk = find_class(d_hash, child_name, dictionary); 382 InstanceKlass* quicksuperk; 383 // to support // loading: if child done loading, just return superclass 384 // if super_name, & class_loader don't match: 385 // if initial define, SD update will give LinkageError 386 // if redefine: compare_class_versions will give HIERARCHY_CHANGED 387 // so we don't throw an exception here. 388 // see: nsk redefclass014 & java.lang.instrument Instrument032 389 if ((childk != NULL ) && (is_superclass) && 390 ((quicksuperk = childk->java_super()) != NULL) && 391 ((quicksuperk->name() == super_name) && 392 (quicksuperk->class_loader() == class_loader()))) { 393 return quicksuperk; 394 } else { 395 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data); 396 if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) { 397 throw_circularity_error = true; 398 } 399 } 400 if (!throw_circularity_error) { 401 // Be careful not to exit resolve_super 402 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, super_name, THREAD); 403 } 404 } 405 if (throw_circularity_error) { 406 ResourceMark rm(THREAD); 407 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string()); 408 } 409 410 // java.lang.Object should have been found above 411 assert(super_name != NULL, "null super class for resolving"); 412 // Resolve the super class or interface, check results on return 413 InstanceKlass* superk = 414 SystemDictionary::resolve_instance_class_or_null_helper(super_name, 415 class_loader, 416 protection_domain, 417 THREAD); 418 419 // Clean up of placeholders moved so that each classloadAction registrar self-cleans up 420 // It is no longer necessary to keep the placeholder table alive until update_dictionary 421 // or error. GC used to walk the placeholder table as strong roots. 422 // The instanceKlass is kept alive because the class loader is on the stack, 423 // which keeps the loader_data alive, as well as all instanceKlasses in 424 // the loader_data. parseClassFile adds the instanceKlass to loader_data. 425 { 426 MutexLocker mu(THREAD, SystemDictionary_lock); 427 placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD); 428 SystemDictionary_lock->notify_all(); 429 } 430 if (HAS_PENDING_EXCEPTION || superk == NULL) { 431 // can null superk 432 Klass* k = handle_resolution_exception(super_name, true, superk, THREAD); 433 assert(k == NULL || k == superk, "must be"); 434 if (k == NULL) { 435 superk = NULL; 436 } 437 } 438 439 return superk; 440 } 441 442 void SystemDictionary::validate_protection_domain(InstanceKlass* klass, 443 Handle class_loader, 444 Handle protection_domain, 445 TRAPS) { 446 // Now we have to call back to java to check if the initating class has access 447 JavaValue result(T_VOID); 448 LogTarget(Debug, protectiondomain) lt; 449 if (lt.is_enabled()) { 450 ResourceMark rm(THREAD); 451 // Print out trace information 452 LogStream ls(lt); 453 ls.print_cr("Checking package access"); 454 if (class_loader() != NULL) { 455 ls.print("class loader: "); 456 class_loader()->print_value_on(&ls); 457 } else { 458 ls.print_cr("class loader: NULL"); 459 } 460 if (protection_domain() != NULL) { 461 ls.print(" protection domain: "); 462 protection_domain()->print_value_on(&ls); 463 } else { 464 ls.print_cr(" protection domain: NULL"); 465 } 466 ls.print(" loading: "); klass->print_value_on(&ls); 467 ls.cr(); 468 } 469 470 // This handle and the class_loader handle passed in keeps this class from 471 // being unloaded through several GC points. 472 // The class_loader handle passed in is the initiating loader. 473 Handle mirror(THREAD, klass->java_mirror()); 474 475 InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass(); 476 JavaCalls::call_special(&result, 477 class_loader, 478 system_loader, 479 vmSymbols::checkPackageAccess_name(), 480 vmSymbols::class_protectiondomain_signature(), 481 mirror, 482 protection_domain, 483 THREAD); 484 485 if (HAS_PENDING_EXCEPTION) { 486 log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!"); 487 } else { 488 log_debug(protectiondomain)("granted"); 489 } 490 491 if (HAS_PENDING_EXCEPTION) return; 492 493 // If no exception has been thrown, we have validated the protection domain 494 // Insert the protection domain of the initiating class into the set. 495 { 496 ClassLoaderData* loader_data = class_loader_data(class_loader); 497 Dictionary* dictionary = loader_data->dictionary(); 498 499 Symbol* kn = klass->name(); 500 unsigned int d_hash = dictionary->compute_hash(kn); 501 502 MutexLocker mu(THREAD, SystemDictionary_lock); 503 int d_index = dictionary->hash_to_index(d_hash); 504 dictionary->add_protection_domain(d_index, d_hash, klass, 505 protection_domain, THREAD); 506 } 507 } 508 509 // We only get here if this thread finds that another thread 510 // has already claimed the placeholder token for the current operation, 511 // but that other thread either never owned or gave up the 512 // object lock 513 // Waits on SystemDictionary_lock to indicate placeholder table updated 514 // On return, caller must recheck placeholder table state 515 // 516 // We only get here if 517 // 1) custom classLoader, i.e. not bootstrap classloader 518 // 2) custom classLoader has broken the class loader objectLock 519 // so another thread got here in parallel 520 // 521 // lockObject must be held. 522 // Complicated dance due to lock ordering: 523 // Must first release the classloader object lock to 524 // allow initial definer to complete the class definition 525 // and to avoid deadlock 526 // Reclaim classloader lock object with same original recursion count 527 // Must release SystemDictionary_lock after notify, since 528 // class loader lock must be claimed before SystemDictionary_lock 529 // to prevent deadlocks 530 // 531 // The notify allows applications that did an untimed wait() on 532 // the classloader object lock to not hang. 533 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) { 534 assert_lock_strong(SystemDictionary_lock); 535 536 bool calledholdinglock 537 = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject); 538 assert(calledholdinglock,"must hold lock for notify"); 539 assert((lockObject() != _system_loader_lock_obj && !is_parallelCapable(lockObject)), "unexpected double_lock_wait"); 540 ObjectSynchronizer::notifyall(lockObject, THREAD); 541 542 TSAN_ONLY(int tsan_rec = 0;) 543 TSAN_RUNTIME_ONLY( 544 tsan_rec = SharedRuntime::tsan_oop_rec_unlock(THREAD, lockObject()); 545 assert(tsan_rec > 0, "tsan: unlocking unlocked mutex"); 546 ); 547 intx recursions = ObjectSynchronizer::complete_exit(lockObject, THREAD); 548 SystemDictionary_lock->wait(); 549 SystemDictionary_lock->unlock(); 550 ObjectSynchronizer::reenter(lockObject, recursions, THREAD); 551 TSAN_RUNTIME_ONLY(SharedRuntime::tsan_oop_rec_lock(THREAD, lockObject(), tsan_rec)); 552 SystemDictionary_lock->lock(); 553 } 554 555 // If the class in is in the placeholder table, class loading is in progress 556 // For cases where the application changes threads to load classes, it 557 // is critical to ClassCircularity detection that we try loading 558 // the superclass on the same thread internally, so we do parallel 559 // super class loading here. 560 // This also is critical in cases where the original thread gets stalled 561 // even in non-circularity situations. 562 // Note: must call resolve_super_or_fail even if null super - 563 // to force placeholder entry creation for this class for circularity detection 564 // Caller must check for pending exception 565 // Returns non-null Klass* if other thread has completed load 566 // and we are done, 567 // If return null Klass* and no pending exception, the caller must load the class 568 InstanceKlass* SystemDictionary::handle_parallel_super_load( 569 Symbol* name, Symbol* superclassname, Handle class_loader, 570 Handle protection_domain, Handle lockObject, TRAPS) { 571 572 ClassLoaderData* loader_data = class_loader_data(class_loader); 573 Dictionary* dictionary = loader_data->dictionary(); 574 unsigned int d_hash = dictionary->compute_hash(name); 575 unsigned int p_hash = placeholders()->compute_hash(name); 576 int p_index = placeholders()->hash_to_index(p_hash); 577 578 // superk is not used, resolve_super called for circularity check only 579 // This code is reached in two situations. One if this thread 580 // is loading the same class twice (e.g. ClassCircularity, or 581 // java.lang.instrument). 582 // The second is if another thread started the resolve_super first 583 // and has not yet finished. 584 // In both cases the original caller will clean up the placeholder 585 // entry on error. 586 Klass* superk = SystemDictionary::resolve_super_or_fail(name, 587 superclassname, 588 class_loader, 589 protection_domain, 590 true, 591 CHECK_NULL); 592 593 // parallelCapable class loaders do NOT wait for parallel superclass loads to complete 594 // Serial class loaders and bootstrap classloader do wait for superclass loads 595 if (!class_loader.is_null() && is_parallelCapable(class_loader)) { 596 MutexLocker mu(THREAD, SystemDictionary_lock); 597 // Check if classloading completed while we were loading superclass or waiting 598 return find_class(d_hash, name, dictionary); 599 } 600 601 // must loop to both handle other placeholder updates 602 // and spurious notifications 603 bool super_load_in_progress = true; 604 PlaceholderEntry* placeholder; 605 while (super_load_in_progress) { 606 MutexLocker mu(THREAD, SystemDictionary_lock); 607 // Check if classloading completed while we were loading superclass or waiting 608 InstanceKlass* check = find_class(d_hash, name, dictionary); 609 if (check != NULL) { 610 // Klass is already loaded, so just return it 611 return check; 612 } else { 613 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data); 614 if (placeholder && placeholder->super_load_in_progress() ){ 615 // We only get here if the application has released the 616 // classloader lock when another thread was in the middle of loading a 617 // superclass/superinterface for this class, and now 618 // this thread is also trying to load this class. 619 // To minimize surprises, the first thread that started to 620 // load a class should be the one to complete the loading 621 // with the classfile it initially expected. 622 // This logic has the current thread wait once it has done 623 // all the superclass/superinterface loading it can, until 624 // the original thread completes the class loading or fails 625 // If it completes we will use the resulting InstanceKlass 626 // which we will find below in the systemDictionary. 627 // We also get here for parallel bootstrap classloader 628 if (class_loader.is_null()) { 629 SystemDictionary_lock->wait(); 630 } else { 631 double_lock_wait(lockObject, THREAD); 632 } 633 } else { 634 // If not in SD and not in PH, other thread's load must have failed 635 super_load_in_progress = false; 636 } 637 } 638 } 639 return NULL; 640 } 641 642 static void post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld) { 643 assert(event != NULL, "invariant"); 644 assert(k != NULL, "invariant"); 645 assert(event->should_commit(), "invariant"); 646 event->set_loadedClass(k); 647 event->set_definingClassLoader(k->class_loader_data()); 648 event->set_initiatingClassLoader(init_cld); 649 event->commit(); 650 } 651 652 653 // Be careful when modifying this code: once you have run 654 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE), 655 // you need to find_and_remove it before returning. 656 // So be careful to not exit with a CHECK_ macro betweeen these calls. 657 // 658 // name must be in the form of "java/lang/Object" -- cannot be "Ljava/lang/Object;" 659 InstanceKlass* SystemDictionary::resolve_instance_class_or_null(Symbol* name, 660 Handle class_loader, 661 Handle protection_domain, 662 TRAPS) { 663 assert(name != NULL && !Signature::is_array(name) && 664 !Signature::has_envelope(name), "invalid class name"); 665 666 EventClassLoad class_load_start_event; 667 668 HandleMark hm(THREAD); 669 670 // Fix for 4474172; see evaluation for more details 671 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 672 ClassLoaderData* loader_data = register_loader(class_loader); 673 Dictionary* dictionary = loader_data->dictionary(); 674 unsigned int d_hash = dictionary->compute_hash(name); 675 676 // Do lookup to see if class already exist and the protection domain 677 // has the right access 678 // This call uses find which checks protection domain already matches 679 // All subsequent calls use find_class, and set has_loaded_class so that 680 // before we return a result we call out to java to check for valid protection domain 681 // to allow returning the Klass* and add it to the pd_set if it is valid 682 { 683 InstanceKlass* probe = dictionary->find(d_hash, name, protection_domain); 684 if (probe != NULL) return probe; 685 } 686 687 // Non-bootstrap class loaders will call out to class loader and 688 // define via jvm/jni_DefineClass which will acquire the 689 // class loader object lock to protect against multiple threads 690 // defining the class in parallel by accident. 691 // This lock must be acquired here so the waiter will find 692 // any successful result in the SystemDictionary and not attempt 693 // the define. 694 // ParallelCapable Classloaders and the bootstrap classloader 695 // do not acquire lock here. 696 bool DoObjectLock = true; 697 if (is_parallelCapable(class_loader)) { 698 DoObjectLock = false; 699 } 700 701 unsigned int p_hash = placeholders()->compute_hash(name); 702 int p_index = placeholders()->hash_to_index(p_hash); 703 704 // Class is not in SystemDictionary so we have to do loading. 705 // Make sure we are synchronized on the class loader before we proceed 706 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 707 check_loader_lock_contention(lockObject, THREAD); 708 ObjectLocker ol(lockObject, THREAD, DoObjectLock); 709 710 // Check again (after locking) if class already exist in SystemDictionary 711 bool class_has_been_loaded = false; 712 bool super_load_in_progress = false; 713 bool havesupername = false; 714 InstanceKlass* k = NULL; 715 PlaceholderEntry* placeholder; 716 Symbol* superclassname = NULL; 717 718 assert(THREAD->can_call_java(), 719 "can not load classes with compiler thread: class=%s, classloader=%s", 720 name->as_C_string(), 721 class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string()); 722 { 723 MutexLocker mu(THREAD, SystemDictionary_lock); 724 InstanceKlass* check = find_class(d_hash, name, dictionary); 725 if (check != NULL) { 726 // InstanceKlass is already loaded, so just return it 727 class_has_been_loaded = true; 728 k = check; 729 } else { 730 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data); 731 if (placeholder && placeholder->super_load_in_progress()) { 732 super_load_in_progress = true; 733 if (placeholder->havesupername() == true) { 734 superclassname = placeholder->supername(); 735 havesupername = true; 736 } 737 } 738 } 739 } 740 741 // If the class is in the placeholder table, class loading is in progress 742 if (super_load_in_progress && havesupername==true) { 743 k = handle_parallel_super_load(name, 744 superclassname, 745 class_loader, 746 protection_domain, 747 lockObject, THREAD); 748 if (HAS_PENDING_EXCEPTION) { 749 return NULL; 750 } 751 if (k != NULL) { 752 class_has_been_loaded = true; 753 } 754 } 755 756 bool throw_circularity_error = false; 757 if (!class_has_been_loaded) { 758 bool load_instance_added = false; 759 760 // add placeholder entry to record loading instance class 761 // Five cases: 762 // All cases need to prevent modifying bootclasssearchpath 763 // in parallel with a classload of same classname 764 // Redefineclasses uses existence of the placeholder for the duration 765 // of the class load to prevent concurrent redefinition of not completely 766 // defined classes. 767 // case 1. traditional classloaders that rely on the classloader object lock 768 // - no other need for LOAD_INSTANCE 769 // case 2. traditional classloaders that break the classloader object lock 770 // as a deadlock workaround. Detection of this case requires that 771 // this check is done while holding the classloader object lock, 772 // and that lock is still held when calling classloader's loadClass. 773 // For these classloaders, we ensure that the first requestor 774 // completes the load and other requestors wait for completion. 775 // case 3. Bootstrap classloader - don't own objectLocker 776 // This classloader supports parallelism at the classloader level, 777 // but only allows a single load of a class/classloader pair. 778 // No performance benefit and no deadlock issues. 779 // case 4. parallelCapable user level classloaders - without objectLocker 780 // Allow parallel classloading of a class/classloader pair 781 782 { 783 MutexLocker mu(THREAD, SystemDictionary_lock); 784 if (class_loader.is_null() || !is_parallelCapable(class_loader)) { 785 PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data); 786 if (oldprobe) { 787 // only need check_seen_thread once, not on each loop 788 // 6341374 java/lang/Instrument with -Xcomp 789 if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) { 790 throw_circularity_error = true; 791 } else { 792 // case 1: traditional: should never see load_in_progress. 793 while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) { 794 795 // case 3: bootstrap classloader: prevent futile classloading, 796 // wait on first requestor 797 if (class_loader.is_null()) { 798 SystemDictionary_lock->wait(); 799 } else { 800 // case 2: traditional with broken classloader lock. wait on first 801 // requestor. 802 double_lock_wait(lockObject, THREAD); 803 } 804 // Check if classloading completed while we were waiting 805 InstanceKlass* check = find_class(d_hash, name, dictionary); 806 if (check != NULL) { 807 // Klass is already loaded, so just return it 808 k = check; 809 class_has_been_loaded = true; 810 } 811 // check if other thread failed to load and cleaned up 812 oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data); 813 } 814 } 815 } 816 } 817 // All cases: add LOAD_INSTANCE holding SystemDictionary_lock 818 // case 4: parallelCapable: allow competing threads to try 819 // LOAD_INSTANCE in parallel 820 821 if (!throw_circularity_error && !class_has_been_loaded) { 822 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD); 823 load_instance_added = true; 824 // For class loaders that do not acquire the classloader object lock, 825 // if they did not catch another thread holding LOAD_INSTANCE, 826 // need a check analogous to the acquire ObjectLocker/find_class 827 // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL 828 // one final check if the load has already completed 829 // class loaders holding the ObjectLock shouldn't find the class here 830 InstanceKlass* check = find_class(d_hash, name, dictionary); 831 if (check != NULL) { 832 // Klass is already loaded, so return it after checking/adding protection domain 833 k = check; 834 class_has_been_loaded = true; 835 } 836 } 837 } 838 839 // must throw error outside of owning lock 840 if (throw_circularity_error) { 841 assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup"); 842 ResourceMark rm(THREAD); 843 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string()); 844 } 845 846 if (!class_has_been_loaded) { 847 848 // Do actual loading 849 k = load_instance_class(name, class_loader, THREAD); 850 851 // If everything was OK (no exceptions, no null return value), and 852 // class_loader is NOT the defining loader, do a little more bookkeeping. 853 if (!HAS_PENDING_EXCEPTION && k != NULL && 854 k->class_loader() != class_loader()) { 855 856 check_constraints(d_hash, k, class_loader, false, THREAD); 857 858 // Need to check for a PENDING_EXCEPTION again; check_constraints 859 // can throw but we may have to remove entry from the placeholder table below. 860 if (!HAS_PENDING_EXCEPTION) { 861 // Record dependency for non-parent delegation. 862 // This recording keeps the defining class loader of the klass (k) found 863 // from being unloaded while the initiating class loader is loaded 864 // even if the reference to the defining class loader is dropped 865 // before references to the initiating class loader. 866 loader_data->record_dependency(k); 867 868 { // Grabbing the Compile_lock prevents systemDictionary updates 869 // during compilations. 870 MutexLocker mu(THREAD, Compile_lock); 871 update_dictionary(d_hash, p_index, p_hash, 872 k, class_loader, THREAD); 873 } 874 875 if (JvmtiExport::should_post_class_load()) { 876 Thread *thread = THREAD; 877 assert(thread->is_Java_thread(), "thread->is_Java_thread()"); 878 JvmtiExport::post_class_load((JavaThread *) thread, k); 879 } 880 } 881 } 882 } // load_instance_class 883 884 if (load_instance_added == true) { 885 // clean up placeholder entries for LOAD_INSTANCE success or error 886 // This brackets the SystemDictionary updates for both defining 887 // and initiating loaders 888 MutexLocker mu(THREAD, SystemDictionary_lock); 889 placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD); 890 SystemDictionary_lock->notify_all(); 891 } 892 } 893 894 if (HAS_PENDING_EXCEPTION || k == NULL) { 895 return NULL; 896 } 897 if (class_load_start_event.should_commit()) { 898 post_class_load_event(&class_load_start_event, k, loader_data); 899 } 900 #ifdef ASSERT 901 { 902 ClassLoaderData* loader_data = k->class_loader_data(); 903 MutexLocker mu(THREAD, SystemDictionary_lock); 904 InstanceKlass* kk = find_class(name, loader_data); 905 assert(kk == k, "should be present in dictionary"); 906 } 907 #endif 908 909 // return if the protection domain in NULL 910 if (protection_domain() == NULL) return k; 911 912 // Check the protection domain has the right access 913 if (dictionary->is_valid_protection_domain(d_hash, name, 914 protection_domain)) { 915 return k; 916 } 917 918 // Verify protection domain. If it fails an exception is thrown 919 validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL); 920 921 return k; 922 } 923 924 925 // This routine does not lock the system dictionary. 926 // 927 // Since readers don't hold a lock, we must make sure that system 928 // dictionary entries are only removed at a safepoint (when only one 929 // thread is running), and are added to in a safe way (all links must 930 // be updated in an MT-safe manner). 931 // 932 // Callers should be aware that an entry could be added just after 933 // _dictionary->bucket(index) is read here, so the caller will not see 934 // the new entry. 935 936 Klass* SystemDictionary::find(Symbol* class_name, 937 Handle class_loader, 938 Handle protection_domain, 939 TRAPS) { 940 941 // The result of this call should be consistent with the result 942 // of the call to resolve_instance_class_or_null(). 943 // See evaluation 6790209 and 4474172 for more details. 944 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 945 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader()); 946 947 if (loader_data == NULL) { 948 // If the ClassLoaderData has not been setup, 949 // then the class loader has no entries in the dictionary. 950 return NULL; 951 } 952 953 Dictionary* dictionary = loader_data->dictionary(); 954 unsigned int d_hash = dictionary->compute_hash(class_name); 955 return dictionary->find(d_hash, class_name, 956 protection_domain); 957 } 958 959 960 // Look for a loaded instance or array klass by name. Do not do any loading. 961 // return NULL in case of error. 962 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name, 963 Handle class_loader, 964 Handle protection_domain, 965 TRAPS) { 966 Klass* k = NULL; 967 assert(class_name != NULL, "class name must be non NULL"); 968 969 if (Signature::is_array(class_name)) { 970 // The name refers to an array. Parse the name. 971 // dimension and object_key in FieldArrayInfo are assigned as a 972 // side-effect of this call 973 SignatureStream ss(class_name, false); 974 int ndims = ss.skip_array_prefix(); // skip all '['s 975 BasicType t = ss.type(); 976 if (t != T_OBJECT) { 977 k = Universe::typeArrayKlassObj(t); 978 } else { 979 Symbol* obj_class = ss.as_symbol(); 980 k = SystemDictionary::find(obj_class, class_loader, protection_domain, THREAD); 981 } 982 if (k != NULL) { 983 k = k->array_klass_or_null(ndims); 984 } 985 } else { 986 k = find(class_name, class_loader, protection_domain, THREAD); 987 } 988 return k; 989 } 990 991 // Note: this method is much like resolve_from_stream, but 992 // does not publish the classes via the SystemDictionary. 993 // Handles unsafe_DefineAnonymousClass and redefineclasses 994 // RedefinedClasses do not add to the class hierarchy 995 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name, 996 Handle class_loader, 997 Handle protection_domain, 998 ClassFileStream* st, 999 const InstanceKlass* unsafe_anonymous_host, 1000 GrowableArray<Handle>* cp_patches, 1001 TRAPS) { 1002 1003 EventClassLoad class_load_start_event; 1004 1005 ClassLoaderData* loader_data; 1006 if (unsafe_anonymous_host != NULL) { 1007 // Create a new CLD for an unsafe anonymous class, that uses the same class loader 1008 // as the unsafe_anonymous_host 1009 guarantee(unsafe_anonymous_host->class_loader() == class_loader(), "should be the same"); 1010 loader_data = ClassLoaderData::unsafe_anonymous_class_loader_data(class_loader); 1011 } else { 1012 loader_data = ClassLoaderData::class_loader_data(class_loader()); 1013 } 1014 1015 assert(st != NULL, "invariant"); 1016 assert(st->need_verify(), "invariant"); 1017 1018 // Parse stream and create a klass. 1019 // Note that we do this even though this klass might 1020 // already be present in the SystemDictionary, otherwise we would not 1021 // throw potential ClassFormatErrors. 1022 1023 InstanceKlass* k = KlassFactory::create_from_stream(st, 1024 class_name, 1025 loader_data, 1026 protection_domain, 1027 unsafe_anonymous_host, 1028 cp_patches, 1029 CHECK_NULL); 1030 1031 if (unsafe_anonymous_host != NULL && k != NULL) { 1032 // Unsafe anonymous classes must update ClassLoaderData holder (was unsafe_anonymous_host loader) 1033 // so that they can be unloaded when the mirror is no longer referenced. 1034 k->class_loader_data()->initialize_holder(Handle(THREAD, k->java_mirror())); 1035 1036 { 1037 MutexLocker mu_r(THREAD, Compile_lock); 1038 1039 // Add to class hierarchy, initialize vtables, and do possible 1040 // deoptimizations. 1041 add_to_hierarchy(k, CHECK_NULL); // No exception, but can block 1042 // But, do not add to dictionary. 1043 } 1044 1045 // Rewrite and patch constant pool here. 1046 k->link_class(CHECK_NULL); 1047 if (cp_patches != NULL) { 1048 k->constants()->patch_resolved_references(cp_patches); 1049 } 1050 1051 // If it's anonymous, initialize it now, since nobody else will. 1052 k->eager_initialize(CHECK_NULL); 1053 1054 // notify jvmti 1055 if (JvmtiExport::should_post_class_load()) { 1056 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()"); 1057 JvmtiExport::post_class_load((JavaThread *) THREAD, k); 1058 } 1059 if (class_load_start_event.should_commit()) { 1060 post_class_load_event(&class_load_start_event, k, loader_data); 1061 } 1062 } 1063 assert(unsafe_anonymous_host != NULL || NULL == cp_patches, 1064 "cp_patches only found with unsafe_anonymous_host"); 1065 1066 return k; 1067 } 1068 1069 // Add a klass to the system from a stream (called by jni_DefineClass and 1070 // JVM_DefineClass). 1071 // Note: class_name can be NULL. In that case we do not know the name of 1072 // the class until we have parsed the stream. 1073 1074 InstanceKlass* SystemDictionary::resolve_from_stream(Symbol* class_name, 1075 Handle class_loader, 1076 Handle protection_domain, 1077 ClassFileStream* st, 1078 TRAPS) { 1079 1080 HandleMark hm(THREAD); 1081 1082 // Classloaders that support parallelism, e.g. bootstrap classloader, 1083 // do not acquire lock here 1084 bool DoObjectLock = true; 1085 if (is_parallelCapable(class_loader)) { 1086 DoObjectLock = false; 1087 } 1088 1089 ClassLoaderData* loader_data = register_loader(class_loader); 1090 1091 // Make sure we are synchronized on the class loader before we proceed 1092 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 1093 check_loader_lock_contention(lockObject, THREAD); 1094 ObjectLocker ol(lockObject, THREAD, DoObjectLock); 1095 1096 assert(st != NULL, "invariant"); 1097 1098 // Parse the stream and create a klass. 1099 // Note that we do this even though this klass might 1100 // already be present in the SystemDictionary, otherwise we would not 1101 // throw potential ClassFormatErrors. 1102 InstanceKlass* k = NULL; 1103 1104 #if INCLUDE_CDS 1105 if (!DumpSharedSpaces) { 1106 k = SystemDictionaryShared::lookup_from_stream(class_name, 1107 class_loader, 1108 protection_domain, 1109 st, 1110 CHECK_NULL); 1111 } 1112 #endif 1113 1114 if (k == NULL) { 1115 if (st->buffer() == NULL) { 1116 return NULL; 1117 } 1118 k = KlassFactory::create_from_stream(st, 1119 class_name, 1120 loader_data, 1121 protection_domain, 1122 NULL, // unsafe_anonymous_host 1123 NULL, // cp_patches 1124 CHECK_NULL); 1125 } 1126 1127 assert(k != NULL, "no klass created"); 1128 Symbol* h_name = k->name(); 1129 assert(class_name == NULL || class_name == h_name, "name mismatch"); 1130 1131 // Add class just loaded 1132 // If a class loader supports parallel classloading handle parallel define requests 1133 // find_or_define_instance_class may return a different InstanceKlass 1134 if (is_parallelCapable(class_loader)) { 1135 InstanceKlass* defined_k = find_or_define_instance_class(h_name, class_loader, k, THREAD); 1136 if (!HAS_PENDING_EXCEPTION && defined_k != k) { 1137 // If a parallel capable class loader already defined this class, register 'k' for cleanup. 1138 assert(defined_k != NULL, "Should have a klass if there's no exception"); 1139 loader_data->add_to_deallocate_list(k); 1140 k = defined_k; 1141 } 1142 } else { 1143 define_instance_class(k, THREAD); 1144 } 1145 1146 // If defining the class throws an exception register 'k' for cleanup. 1147 if (HAS_PENDING_EXCEPTION) { 1148 assert(k != NULL, "Must have an instance klass here!"); 1149 loader_data->add_to_deallocate_list(k); 1150 return NULL; 1151 } 1152 1153 // Make sure we have an entry in the SystemDictionary on success 1154 debug_only( { 1155 MutexLocker mu(THREAD, SystemDictionary_lock); 1156 1157 Klass* check = find_class(h_name, k->class_loader_data()); 1158 assert(check == k, "should be present in the dictionary"); 1159 } ); 1160 1161 return k; 1162 } 1163 1164 #if INCLUDE_CDS 1165 // Load a class for boot loader from the shared spaces. This also 1166 // forces the super class and all interfaces to be loaded. 1167 InstanceKlass* SystemDictionary::load_shared_boot_class(Symbol* class_name, 1168 TRAPS) { 1169 InstanceKlass* ik = SystemDictionaryShared::find_builtin_class(class_name); 1170 if (ik != NULL && ik->is_shared_boot_class()) { 1171 return load_shared_class(ik, Handle(), Handle(), NULL, THREAD); 1172 } 1173 return NULL; 1174 } 1175 1176 // Check if a shared class can be loaded by the specific classloader: 1177 // 1178 // NULL classloader: 1179 // - Module class from "modules" jimage. ModuleEntry must be defined in the classloader. 1180 // - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must 1181 // be defined in an unnamed module. 1182 bool SystemDictionary::is_shared_class_visible(Symbol* class_name, 1183 InstanceKlass* ik, 1184 Handle class_loader, TRAPS) { 1185 assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(), 1186 "Cannot use sharing if java.base is patched"); 1187 ResourceMark rm(THREAD); 1188 int path_index = ik->shared_classpath_index(); 1189 ClassLoaderData* loader_data = class_loader_data(class_loader); 1190 if (path_index < 0) { 1191 // path_index < 0 indicates that the class is intended for a custom loader 1192 // and should not be loaded by boot/platform/app loaders 1193 if (loader_data->is_builtin_class_loader_data()) { 1194 return false; 1195 } else { 1196 return true; 1197 } 1198 } 1199 SharedClassPathEntry* ent = 1200 (SharedClassPathEntry*)FileMapInfo::shared_path(path_index); 1201 if (!Universe::is_module_initialized()) { 1202 assert(ent != NULL && ent->is_modules_image(), 1203 "Loading non-bootstrap classes before the module system is initialized"); 1204 assert(class_loader.is_null(), "sanity"); 1205 return true; 1206 } 1207 // Get the pkg_entry from the classloader 1208 TempNewSymbol pkg_name = NULL; 1209 PackageEntry* pkg_entry = NULL; 1210 ModuleEntry* mod_entry = NULL; 1211 pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false); 1212 if (pkg_name != NULL) { 1213 if (loader_data != NULL) { 1214 pkg_entry = loader_data->packages()->lookup_only(pkg_name); 1215 } 1216 if (pkg_entry != NULL) { 1217 mod_entry = pkg_entry->module(); 1218 } 1219 } 1220 1221 // If the archived class is from a module that has been patched at runtime, 1222 // the class cannot be loaded from the archive. 1223 if (mod_entry != NULL && mod_entry->is_patched()) { 1224 return false; 1225 } 1226 1227 if (class_loader.is_null()) { 1228 assert(ent != NULL, "Shared class for NULL classloader must have valid SharedClassPathEntry"); 1229 // The NULL classloader can load archived class originated from the 1230 // "modules" jimage and the -Xbootclasspath/a. For class from the 1231 // "modules" jimage, the PackageEntry/ModuleEntry must be defined 1232 // by the NULL classloader. 1233 if (mod_entry != NULL) { 1234 // PackageEntry/ModuleEntry is found in the classloader. Check if the 1235 // ModuleEntry's location agrees with the archived class' origination. 1236 if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) { 1237 return true; // Module class from the "module" jimage 1238 } 1239 } 1240 1241 // If the archived class is not from the "module" jimage, the class can be 1242 // loaded by the NULL classloader if 1243 // 1244 // 1. the class is from the unamed package 1245 // 2. or, the class is not from a module defined in the NULL classloader 1246 // 3. or, the class is from an unamed module 1247 if (!ent->is_modules_image() && ik->is_shared_boot_class()) { 1248 // the class is from the -Xbootclasspath/a 1249 if (pkg_name == NULL || 1250 pkg_entry == NULL || 1251 pkg_entry->in_unnamed_module()) { 1252 assert(mod_entry == NULL || 1253 mod_entry == loader_data->unnamed_module(), 1254 "the unnamed module is not defined in the classloader"); 1255 return true; 1256 } 1257 } 1258 return false; 1259 } else { 1260 bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader( 1261 ik, class_loader, pkg_name, pkg_entry, mod_entry, CHECK_(false)); 1262 return res; 1263 } 1264 } 1265 1266 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik, 1267 Handle class_loader, 1268 Handle protection_domain, 1269 const ClassFileStream *cfs, 1270 TRAPS) { 1271 assert(ik != NULL, "sanity"); 1272 assert(!ik->is_unshareable_info_restored(), "shared class can be loaded only once"); 1273 Symbol* class_name = ik->name(); 1274 1275 bool visible = is_shared_class_visible( 1276 class_name, ik, class_loader, CHECK_NULL); 1277 if (!visible) { 1278 return NULL; 1279 } 1280 1281 // Resolve the superclass and interfaces. They must be the same 1282 // as in dump time, because the layout of <ik> depends on 1283 // the specific layout of ik->super() and ik->local_interfaces(). 1284 // 1285 // If unexpected superclass or interfaces are found, we cannot 1286 // load <ik> from the shared archive. 1287 1288 if (ik->super() != NULL) { 1289 Symbol* cn = ik->super()->name(); 1290 Klass *s = resolve_super_or_fail(class_name, cn, 1291 class_loader, protection_domain, true, CHECK_NULL); 1292 if (s != ik->super()) { 1293 // The dynamically resolved super class is not the same as the one we used during dump time, 1294 // so we cannot use ik. 1295 return NULL; 1296 } else { 1297 assert(s->is_shared(), "must be"); 1298 } 1299 } 1300 1301 Array<InstanceKlass*>* interfaces = ik->local_interfaces(); 1302 int num_interfaces = interfaces->length(); 1303 for (int index = 0; index < num_interfaces; index++) { 1304 InstanceKlass* k = interfaces->at(index); 1305 Symbol* name = k->name(); 1306 Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_NULL); 1307 if (k != i) { 1308 // The dynamically resolved interface class is not the same as the one we used during dump time, 1309 // so we cannot use ik. 1310 return NULL; 1311 } else { 1312 assert(i->is_shared(), "must be"); 1313 } 1314 } 1315 1316 InstanceKlass* new_ik = KlassFactory::check_shared_class_file_load_hook( 1317 ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL); 1318 if (new_ik != NULL) { 1319 // The class is changed by CFLH. Return the new class. The shared class is 1320 // not used. 1321 return new_ik; 1322 } 1323 1324 // Adjust methods to recover missing data. They need addresses for 1325 // interpreter entry points and their default native method address 1326 // must be reset. 1327 1328 // Updating methods must be done under a lock so multiple 1329 // threads don't update these in parallel 1330 // 1331 // Shared classes are all currently loaded by either the bootstrap or 1332 // internal parallel class loaders, so this will never cause a deadlock 1333 // on a custom class loader lock. 1334 1335 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 1336 { 1337 HandleMark hm(THREAD); 1338 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 1339 check_loader_lock_contention(lockObject, THREAD); 1340 ObjectLocker ol(lockObject, THREAD, true); 1341 // prohibited package check assumes all classes loaded from archive call 1342 // restore_unshareable_info which calls ik->set_package() 1343 ik->restore_unshareable_info(loader_data, protection_domain, CHECK_NULL); 1344 } 1345 1346 ik->print_class_load_logging(loader_data, NULL, NULL); 1347 1348 // For boot loader, ensure that GetSystemPackage knows that a class in this 1349 // package was loaded. 1350 if (class_loader.is_null()) { 1351 int path_index = ik->shared_classpath_index(); 1352 ResourceMark rm(THREAD); 1353 ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD); 1354 } 1355 1356 if (DumpLoadedClassList != NULL && classlist_file->is_open()) { 1357 // Only dump the classes that can be stored into CDS archive 1358 if (SystemDictionaryShared::is_sharing_possible(loader_data)) { 1359 ResourceMark rm(THREAD); 1360 classlist_file->print_cr("%s", ik->name()->as_C_string()); 1361 classlist_file->flush(); 1362 } 1363 } 1364 1365 // notify a class loaded from shared object 1366 ClassLoadingService::notify_class_loaded(ik, true /* shared class */); 1367 1368 ik->set_has_passed_fingerprint_check(false); 1369 if (UseAOT && ik->supers_have_passed_fingerprint_checks()) { 1370 uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik); 1371 uint64_t cds_fp = ik->get_stored_fingerprint(); 1372 if (aot_fp != 0 && aot_fp == cds_fp) { 1373 // This class matches with a class saved in an AOT library 1374 ik->set_has_passed_fingerprint_check(true); 1375 } else { 1376 if (log_is_enabled(Info, class, fingerprint)) { 1377 ResourceMark rm(THREAD); 1378 log_info(class, fingerprint)("%s : expected = " PTR64_FORMAT " actual = " PTR64_FORMAT, ik->external_name(), aot_fp, cds_fp); 1379 } 1380 } 1381 } 1382 1383 return ik; 1384 } 1385 #endif // INCLUDE_CDS 1386 1387 InstanceKlass* SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) { 1388 1389 if (class_loader.is_null()) { 1390 ResourceMark rm(THREAD); 1391 PackageEntry* pkg_entry = NULL; 1392 bool search_only_bootloader_append = false; 1393 ClassLoaderData *loader_data = class_loader_data(class_loader); 1394 1395 // Find the package in the boot loader's package entry table. 1396 TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL); 1397 if (pkg_name != NULL) { 1398 pkg_entry = loader_data->packages()->lookup_only(pkg_name); 1399 } 1400 1401 // Prior to attempting to load the class, enforce the boot loader's 1402 // visibility boundaries. 1403 if (!Universe::is_module_initialized()) { 1404 // During bootstrapping, prior to module initialization, any 1405 // class attempting to be loaded must be checked against the 1406 // java.base packages in the boot loader's PackageEntryTable. 1407 // No class outside of java.base is allowed to be loaded during 1408 // this bootstrapping window. 1409 if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) { 1410 // Class is either in the unnamed package or in 1411 // a named package within the unnamed module. Either 1412 // case is outside of java.base, do not attempt to 1413 // load the class post java.base definition. If 1414 // java.base has not been defined, let the class load 1415 // and its package will be checked later by 1416 // ModuleEntryTable::verify_javabase_packages. 1417 if (ModuleEntryTable::javabase_defined()) { 1418 return NULL; 1419 } 1420 } else { 1421 // Check that the class' package is defined within java.base. 1422 ModuleEntry* mod_entry = pkg_entry->module(); 1423 Symbol* mod_entry_name = mod_entry->name(); 1424 if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) { 1425 return NULL; 1426 } 1427 } 1428 } else { 1429 // After the module system has been initialized, check if the class' 1430 // package is in a module defined to the boot loader. 1431 if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) { 1432 // Class is either in the unnamed package, in a named package 1433 // within a module not defined to the boot loader or in a 1434 // a named package within the unnamed module. In all cases, 1435 // limit visibility to search for the class only in the boot 1436 // loader's append path. 1437 if (!ClassLoader::has_bootclasspath_append()) { 1438 // If there is no bootclasspath append entry, no need to continue 1439 // searching. 1440 return NULL; 1441 } 1442 search_only_bootloader_append = true; 1443 } 1444 } 1445 1446 // Prior to bootstrapping's module initialization, never load a class outside 1447 // of the boot loader's module path 1448 assert(Universe::is_module_initialized() || 1449 !search_only_bootloader_append, 1450 "Attempt to load a class outside of boot loader's module path"); 1451 1452 // Search for classes in the CDS archive. 1453 InstanceKlass* k = NULL; 1454 { 1455 #if INCLUDE_CDS 1456 PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time()); 1457 k = load_shared_boot_class(class_name, THREAD); 1458 #endif 1459 } 1460 1461 if (k == NULL) { 1462 // Use VM class loader 1463 PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time()); 1464 k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL); 1465 } 1466 1467 // find_or_define_instance_class may return a different InstanceKlass 1468 if (k != NULL) { 1469 InstanceKlass* defined_k = 1470 find_or_define_instance_class(class_name, class_loader, k, THREAD); 1471 if (!HAS_PENDING_EXCEPTION && defined_k != k) { 1472 // If a parallel capable class loader already defined this class, register 'k' for cleanup. 1473 assert(defined_k != NULL, "Should have a klass if there's no exception"); 1474 loader_data->add_to_deallocate_list(k); 1475 k = defined_k; 1476 } else if (HAS_PENDING_EXCEPTION) { 1477 loader_data->add_to_deallocate_list(k); 1478 return NULL; 1479 } 1480 } 1481 return k; 1482 } else { 1483 // Use user specified class loader to load class. Call loadClass operation on class_loader. 1484 ResourceMark rm(THREAD); 1485 1486 assert(THREAD->is_Java_thread(), "must be a JavaThread"); 1487 JavaThread* jt = (JavaThread*) THREAD; 1488 1489 PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(), 1490 ClassLoader::perf_app_classload_selftime(), 1491 ClassLoader::perf_app_classload_count(), 1492 jt->get_thread_stat()->perf_recursion_counts_addr(), 1493 jt->get_thread_stat()->perf_timers_addr(), 1494 PerfClassTraceTime::CLASS_LOAD); 1495 1496 Handle s = java_lang_String::create_from_symbol(class_name, CHECK_NULL); 1497 // Translate to external class name format, i.e., convert '/' chars to '.' 1498 Handle string = java_lang_String::externalize_classname(s, CHECK_NULL); 1499 1500 JavaValue result(T_OBJECT); 1501 1502 InstanceKlass* spec_klass = SystemDictionary::ClassLoader_klass(); 1503 1504 // Call public unsynchronized loadClass(String) directly for all class loaders. 1505 // For parallelCapable class loaders, JDK >=7, loadClass(String, boolean) will 1506 // acquire a class-name based lock rather than the class loader object lock. 1507 // JDK < 7 already acquire the class loader lock in loadClass(String, boolean). 1508 JavaCalls::call_virtual(&result, 1509 class_loader, 1510 spec_klass, 1511 vmSymbols::loadClass_name(), 1512 vmSymbols::string_class_signature(), 1513 string, 1514 CHECK_NULL); 1515 1516 assert(result.get_type() == T_OBJECT, "just checking"); 1517 oop obj = (oop) result.get_jobject(); 1518 1519 // Primitive classes return null since forName() can not be 1520 // used to obtain any of the Class objects representing primitives or void 1521 if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) { 1522 InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj)); 1523 // For user defined Java class loaders, check that the name returned is 1524 // the same as that requested. This check is done for the bootstrap 1525 // loader when parsing the class file. 1526 if (class_name == k->name()) { 1527 return k; 1528 } 1529 } 1530 // Class is not found or has the wrong name, return NULL 1531 return NULL; 1532 } 1533 } 1534 1535 static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) { 1536 EventClassDefine event; 1537 if (event.should_commit()) { 1538 event.set_definedClass(k); 1539 event.set_definingClassLoader(def_cld); 1540 event.commit(); 1541 } 1542 } 1543 1544 void SystemDictionary::define_instance_class(InstanceKlass* k, TRAPS) { 1545 1546 HandleMark hm(THREAD); 1547 ClassLoaderData* loader_data = k->class_loader_data(); 1548 Handle class_loader_h(THREAD, loader_data->class_loader()); 1549 1550 // for bootstrap and other parallel classloaders don't acquire lock, 1551 // use placeholder token 1552 // If a parallelCapable class loader calls define_instance_class instead of 1553 // find_or_define_instance_class to get here, we have a timing 1554 // hole with systemDictionary updates and check_constraints 1555 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) { 1556 assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, 1557 compute_loader_lock_object(class_loader_h, THREAD)), 1558 "define called without lock"); 1559 } 1560 1561 // Check class-loading constraints. Throw exception if violation is detected. 1562 // Grabs and releases SystemDictionary_lock 1563 // The check_constraints/find_class call and update_dictionary sequence 1564 // must be "atomic" for a specific class/classloader pair so we never 1565 // define two different instanceKlasses for that class/classloader pair. 1566 // Existing classloaders will call define_instance_class with the 1567 // classloader lock held 1568 // Parallel classloaders will call find_or_define_instance_class 1569 // which will require a token to perform the define class 1570 Symbol* name_h = k->name(); 1571 Dictionary* dictionary = loader_data->dictionary(); 1572 unsigned int d_hash = dictionary->compute_hash(name_h); 1573 check_constraints(d_hash, k, class_loader_h, true, CHECK); 1574 1575 // Register class just loaded with class loader (placed in ArrayList) 1576 // Note we do this before updating the dictionary, as this can 1577 // fail with an OutOfMemoryError (if it does, we will *not* put this 1578 // class in the dictionary and will not update the class hierarchy). 1579 // JVMTI FollowReferences needs to find the classes this way. 1580 if (k->class_loader() != NULL) { 1581 methodHandle m(THREAD, Universe::loader_addClass_method()); 1582 JavaValue result(T_VOID); 1583 JavaCallArguments args(class_loader_h); 1584 args.push_oop(Handle(THREAD, k->java_mirror())); 1585 JavaCalls::call(&result, m, &args, CHECK); 1586 } 1587 1588 // Add the new class. We need recompile lock during update of CHA. 1589 { 1590 unsigned int p_hash = placeholders()->compute_hash(name_h); 1591 int p_index = placeholders()->hash_to_index(p_hash); 1592 1593 MutexLocker mu_r(THREAD, Compile_lock); 1594 1595 // Add to class hierarchy, initialize vtables, and do possible 1596 // deoptimizations. 1597 add_to_hierarchy(k, CHECK); // No exception, but can block 1598 1599 // Add to systemDictionary - so other classes can see it. 1600 // Grabs and releases SystemDictionary_lock 1601 update_dictionary(d_hash, p_index, p_hash, 1602 k, class_loader_h, THREAD); 1603 } 1604 k->eager_initialize(THREAD); 1605 1606 // notify jvmti 1607 if (JvmtiExport::should_post_class_load()) { 1608 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()"); 1609 JvmtiExport::post_class_load((JavaThread *) THREAD, k); 1610 1611 } 1612 post_class_define_event(k, loader_data); 1613 } 1614 1615 // Support parallel classloading 1616 // All parallel class loaders, including bootstrap classloader 1617 // lock a placeholder entry for this class/class_loader pair 1618 // to allow parallel defines of different classes for this class loader 1619 // With AllowParallelDefine flag==true, in case they do not synchronize around 1620 // FindLoadedClass/DefineClass, calls, we check for parallel 1621 // loading for them, wait if a defineClass is in progress 1622 // and return the initial requestor's results 1623 // This flag does not apply to the bootstrap classloader. 1624 // With AllowParallelDefine flag==false, call through to define_instance_class 1625 // which will throw LinkageError: duplicate class definition. 1626 // False is the requested default. 1627 // For better performance, the class loaders should synchronize 1628 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they 1629 // potentially waste time reading and parsing the bytestream. 1630 // Note: VM callers should ensure consistency of k/class_name,class_loader 1631 // Be careful when modifying this code: once you have run 1632 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS), 1633 // you need to find_and_remove it before returning. 1634 // So be careful to not exit with a CHECK_ macro betweeen these calls. 1635 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, 1636 InstanceKlass* k, TRAPS) { 1637 1638 Symbol* name_h = k->name(); // passed in class_name may be null 1639 ClassLoaderData* loader_data = class_loader_data(class_loader); 1640 Dictionary* dictionary = loader_data->dictionary(); 1641 1642 unsigned int d_hash = dictionary->compute_hash(name_h); 1643 1644 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS 1645 unsigned int p_hash = placeholders()->compute_hash(name_h); 1646 int p_index = placeholders()->hash_to_index(p_hash); 1647 PlaceholderEntry* probe; 1648 1649 { 1650 MutexLocker mu(THREAD, SystemDictionary_lock); 1651 // First check if class already defined 1652 if (is_parallelDefine(class_loader)) { 1653 InstanceKlass* check = find_class(d_hash, name_h, dictionary); 1654 if (check != NULL) { 1655 return check; 1656 } 1657 } 1658 1659 // Acquire define token for this class/classloader 1660 probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD); 1661 // Wait if another thread defining in parallel 1662 // All threads wait - even those that will throw duplicate class: otherwise 1663 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails 1664 // if other thread has not finished updating dictionary 1665 while (probe->definer() != NULL) { 1666 SystemDictionary_lock->wait(); 1667 } 1668 // Only special cases allow parallel defines and can use other thread's results 1669 // Other cases fall through, and may run into duplicate defines 1670 // caught by finding an entry in the SystemDictionary 1671 if (is_parallelDefine(class_loader) && (probe->instance_klass() != NULL)) { 1672 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1673 SystemDictionary_lock->notify_all(); 1674 #ifdef ASSERT 1675 InstanceKlass* check = find_class(d_hash, name_h, dictionary); 1676 assert(check != NULL, "definer missed recording success"); 1677 #endif 1678 return probe->instance_klass(); 1679 } else { 1680 // This thread will define the class (even if earlier thread tried and had an error) 1681 probe->set_definer(THREAD); 1682 } 1683 } 1684 1685 define_instance_class(k, THREAD); 1686 1687 Handle linkage_exception = Handle(); // null handle 1688 1689 // definer must notify any waiting threads 1690 { 1691 MutexLocker mu(THREAD, SystemDictionary_lock); 1692 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data); 1693 assert(probe != NULL, "DEFINE_CLASS placeholder lost?"); 1694 if (probe != NULL) { 1695 if (HAS_PENDING_EXCEPTION) { 1696 linkage_exception = Handle(THREAD,PENDING_EXCEPTION); 1697 CLEAR_PENDING_EXCEPTION; 1698 } else { 1699 probe->set_instance_klass(k); 1700 } 1701 probe->set_definer(NULL); 1702 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1703 SystemDictionary_lock->notify_all(); 1704 } 1705 } 1706 1707 // Can't throw exception while holding lock due to rank ordering 1708 if (linkage_exception() != NULL) { 1709 THROW_OOP_(linkage_exception(), NULL); // throws exception and returns 1710 } 1711 1712 return k; 1713 } 1714 1715 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) { 1716 // If class_loader is NULL we synchronize on _system_loader_lock_obj 1717 if (class_loader.is_null()) { 1718 return Handle(THREAD, _system_loader_lock_obj); 1719 } else { 1720 return class_loader; 1721 } 1722 } 1723 1724 // This method is added to check how often we have to wait to grab loader 1725 // lock. The results are being recorded in the performance counters defined in 1726 // ClassLoader::_sync_systemLoaderLockContentionRate and 1727 // ClassLoader::_sync_nonSystemLoaderLockConteionRate. 1728 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) { 1729 if (!UsePerfData) { 1730 return; 1731 } 1732 1733 assert(!loader_lock.is_null(), "NULL lock object"); 1734 1735 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock) 1736 == ObjectSynchronizer::owner_other) { 1737 // contention will likely happen, so increment the corresponding 1738 // contention counter. 1739 if (loader_lock() == _system_loader_lock_obj) { 1740 ClassLoader::sync_systemLoaderLockContentionRate()->inc(); 1741 } else { 1742 ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc(); 1743 } 1744 } 1745 } 1746 1747 // ---------------------------------------------------------------------------- 1748 // Lookup 1749 1750 InstanceKlass* SystemDictionary::find_class(unsigned int hash, 1751 Symbol* class_name, 1752 Dictionary* dictionary) { 1753 assert_locked_or_safepoint(SystemDictionary_lock); 1754 int index = dictionary->hash_to_index(hash); 1755 return dictionary->find_class(index, hash, class_name); 1756 } 1757 1758 1759 // Basic find on classes in the midst of being loaded 1760 Symbol* SystemDictionary::find_placeholder(Symbol* class_name, 1761 ClassLoaderData* loader_data) { 1762 assert_locked_or_safepoint(SystemDictionary_lock); 1763 unsigned int p_hash = placeholders()->compute_hash(class_name); 1764 int p_index = placeholders()->hash_to_index(p_hash); 1765 return placeholders()->find_entry(p_index, p_hash, class_name, loader_data); 1766 } 1767 1768 1769 // Used for assertions and verification only 1770 // Precalculating the hash and index is an optimization because there are many lookups 1771 // before adding the class. 1772 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) { 1773 assert_locked_or_safepoint(SystemDictionary_lock); 1774 #ifndef ASSERT 1775 guarantee(VerifyBeforeGC || 1776 VerifyDuringGC || 1777 VerifyBeforeExit || 1778 VerifyDuringStartup || 1779 VerifyAfterGC, "too expensive"); 1780 #endif 1781 1782 Dictionary* dictionary = loader_data->dictionary(); 1783 unsigned int d_hash = dictionary->compute_hash(class_name); 1784 return find_class(d_hash, class_name, dictionary); 1785 } 1786 1787 1788 // ---------------------------------------------------------------------------- 1789 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock 1790 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in 1791 // before a new class is used. 1792 1793 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) { 1794 assert(k != NULL, "just checking"); 1795 assert_locked_or_safepoint(Compile_lock); 1796 1797 k->set_init_state(InstanceKlass::loaded); 1798 // make sure init_state store is already done. 1799 // The compiler reads the hierarchy outside of the Compile_lock. 1800 // Access ordering is used to add to hierarchy. 1801 1802 // Link into hierachy. 1803 k->append_to_sibling_list(); // add to superklass/sibling list 1804 k->process_interfaces(THREAD); // handle all "implements" declarations 1805 1806 // Now flush all code that depended on old class hierarchy. 1807 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97) 1808 CodeCache::flush_dependents_on(k); 1809 } 1810 1811 // ---------------------------------------------------------------------------- 1812 // GC support 1813 1814 // Assumes classes in the SystemDictionary are only unloaded at a safepoint 1815 // Note: anonymous classes are not in the SD. 1816 bool SystemDictionary::do_unloading(GCTimer* gc_timer) { 1817 1818 bool unloading_occurred; 1819 bool is_concurrent = !SafepointSynchronize::is_at_safepoint(); 1820 { 1821 GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer); 1822 assert_locked_or_safepoint(ClassLoaderDataGraph_lock); // caller locks. 1823 // First, mark for unload all ClassLoaderData referencing a dead class loader. 1824 unloading_occurred = ClassLoaderDataGraph::do_unloading(); 1825 if (unloading_occurred) { 1826 MutexLocker ml2(is_concurrent ? Module_lock : NULL); 1827 JFR_ONLY(Jfr::on_unloading_classes();) 1828 1829 MutexLocker ml1(is_concurrent ? SystemDictionary_lock : NULL); 1830 ClassLoaderDataGraph::clean_module_and_package_info(); 1831 constraints()->purge_loader_constraints(); 1832 resolution_errors()->purge_resolution_errors(); 1833 } 1834 } 1835 1836 GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer); 1837 1838 if (unloading_occurred) { 1839 SymbolTable::trigger_cleanup(); 1840 1841 // Oops referenced by the protection domain cache table may get unreachable independently 1842 // of the class loader (eg. cached protection domain oops). So we need to 1843 // explicitly unlink them here. 1844 // All protection domain oops are linked to the caller class, so if nothing 1845 // unloads, this is not needed. 1846 _pd_cache_table->trigger_cleanup(); 1847 } 1848 1849 return unloading_occurred; 1850 } 1851 1852 void SystemDictionary::oops_do(OopClosure* f, bool include_handles) { 1853 f->do_oop(&_java_system_loader); 1854 f->do_oop(&_java_platform_loader); 1855 f->do_oop(&_system_loader_lock_obj); 1856 CDS_ONLY(SystemDictionaryShared::oops_do(f);) 1857 1858 // Visit extra methods 1859 invoke_method_table()->oops_do(f); 1860 1861 if (include_handles) { 1862 OopStorageSet::vm_global()->oops_do(f); 1863 } 1864 } 1865 1866 // CDS: scan and relocate all classes referenced by _well_known_klasses[]. 1867 void SystemDictionary::well_known_klasses_do(MetaspaceClosure* it) { 1868 for (int id = FIRST_WKID; id < WKID_LIMIT; id++) { 1869 it->push(well_known_klass_addr((WKID)id)); 1870 } 1871 } 1872 1873 void SystemDictionary::methods_do(void f(Method*)) { 1874 // Walk methods in loaded classes 1875 MutexLocker ml(ClassLoaderDataGraph_lock); 1876 ClassLoaderDataGraph::methods_do(f); 1877 // Walk method handle intrinsics 1878 invoke_method_table()->methods_do(f); 1879 } 1880 1881 // ---------------------------------------------------------------------------- 1882 // Initialization 1883 1884 void SystemDictionary::initialize(TRAPS) { 1885 // Allocate arrays 1886 _placeholders = new PlaceholderTable(_placeholder_table_size); 1887 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size); 1888 _resolution_errors = new ResolutionErrorTable(_resolution_error_size); 1889 _invoke_method_table = new SymbolPropertyTable(_invoke_method_size); 1890 _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize); 1891 1892 // Allocate private object used as system class loader lock 1893 _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK); 1894 // Initialize basic classes 1895 resolve_well_known_classes(CHECK); 1896 } 1897 1898 // Compact table of directions on the initialization of klasses: 1899 static const short wk_init_info[] = { 1900 #define WK_KLASS_INIT_INFO(name, symbol) \ 1901 ((short)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol)), 1902 1903 WK_KLASSES_DO(WK_KLASS_INIT_INFO) 1904 #undef WK_KLASS_INIT_INFO 1905 0 1906 }; 1907 1908 #ifdef ASSERT 1909 bool SystemDictionary::is_well_known_klass(Symbol* class_name) { 1910 int sid; 1911 for (int i = 0; (sid = wk_init_info[i]) != 0; i++) { 1912 Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid); 1913 if (class_name == symbol) { 1914 return true; 1915 } 1916 } 1917 return false; 1918 } 1919 #endif 1920 1921 bool SystemDictionary::resolve_wk_klass(WKID id, TRAPS) { 1922 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob"); 1923 int sid = wk_init_info[id - FIRST_WKID]; 1924 Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid); 1925 InstanceKlass** klassp = &_well_known_klasses[id]; 1926 1927 if ((*klassp) == NULL) { 1928 Klass* k = resolve_or_fail(symbol, true, CHECK_0); 1929 (*klassp) = InstanceKlass::cast(k); 1930 } 1931 return ((*klassp) != NULL); 1932 } 1933 1934 void SystemDictionary::resolve_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) { 1935 assert((int)start_id <= (int)limit_id, "IDs are out of order!"); 1936 for (int id = (int)start_id; id < (int)limit_id; id++) { 1937 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob"); 1938 resolve_wk_klass((WKID)id, CHECK); 1939 } 1940 1941 // move the starting value forward to the limit: 1942 start_id = limit_id; 1943 } 1944 1945 void SystemDictionary::resolve_well_known_classes(TRAPS) { 1946 assert(WK_KLASS(Object_klass) == NULL, "well-known classes should only be initialized once"); 1947 1948 // Create the ModuleEntry for java.base. This call needs to be done here, 1949 // after vmSymbols::initialize() is called but before any classes are pre-loaded. 1950 ClassLoader::classLoader_init2(CHECK); 1951 1952 // Preload commonly used klasses 1953 WKID scan = FIRST_WKID; 1954 // first do Object, then String, Class 1955 #if INCLUDE_CDS 1956 if (UseSharedSpaces) { 1957 resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK); 1958 1959 // It's unsafe to access the archived heap regions before they 1960 // are fixed up, so we must do the fixup as early as possible 1961 // before the archived java objects are accessed by functions 1962 // such as java_lang_Class::restore_archived_mirror and 1963 // ConstantPool::restore_unshareable_info (restores the archived 1964 // resolved_references array object). 1965 // 1966 // HeapShared::fixup_mapped_heap_regions() fills the empty 1967 // spaces in the archived heap regions and may use 1968 // SystemDictionary::Object_klass(), so we can do this only after 1969 // Object_klass is resolved. See the above resolve_wk_klasses_through() 1970 // call. No mirror objects are accessed/restored in the above call. 1971 // Mirrors are restored after java.lang.Class is loaded. 1972 HeapShared::fixup_mapped_heap_regions(); 1973 1974 // Initialize the constant pool for the Object_class 1975 assert(Object_klass()->is_shared(), "must be"); 1976 Object_klass()->constants()->restore_unshareable_info(CHECK); 1977 resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK); 1978 } else 1979 #endif 1980 { 1981 resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK); 1982 } 1983 1984 assert(WK_KLASS(Object_klass) != NULL, "well-known classes should now be initialized"); 1985 1986 java_lang_Object::register_natives(CHECK); 1987 1988 // Calculate offsets for String and Class classes since they are loaded and 1989 // can be used after this point. 1990 java_lang_String::compute_offsets(); 1991 java_lang_Class::compute_offsets(); 1992 1993 // Fixup mirrors for classes loaded before java.lang.Class. 1994 // These calls iterate over the objects currently in the perm gen 1995 // so calling them at this point is matters (not before when there 1996 // are fewer objects and not later after there are more objects 1997 // in the perm gen. 1998 Universe::initialize_basic_type_mirrors(CHECK); 1999 Universe::fixup_mirrors(CHECK); 2000 2001 // do a bunch more: 2002 resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK); 2003 2004 // Preload ref klasses and set reference types 2005 WK_KLASS(Reference_klass)->set_reference_type(REF_OTHER); 2006 InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass)); 2007 2008 resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK); 2009 WK_KLASS(SoftReference_klass)->set_reference_type(REF_SOFT); 2010 WK_KLASS(WeakReference_klass)->set_reference_type(REF_WEAK); 2011 WK_KLASS(FinalReference_klass)->set_reference_type(REF_FINAL); 2012 WK_KLASS(PhantomReference_klass)->set_reference_type(REF_PHANTOM); 2013 2014 // JSR 292 classes 2015 WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass); 2016 WKID jsr292_group_end = WK_KLASS_ENUM_NAME(VolatileCallSite_klass); 2017 resolve_wk_klasses_until(jsr292_group_start, scan, CHECK); 2018 resolve_wk_klasses_through(jsr292_group_end, scan, CHECK); 2019 WKID last = WKID_LIMIT; 2020 resolve_wk_klasses_until(last, scan, CHECK); 2021 2022 _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass); 2023 _box_klasses[T_CHAR] = WK_KLASS(Character_klass); 2024 _box_klasses[T_FLOAT] = WK_KLASS(Float_klass); 2025 _box_klasses[T_DOUBLE] = WK_KLASS(Double_klass); 2026 _box_klasses[T_BYTE] = WK_KLASS(Byte_klass); 2027 _box_klasses[T_SHORT] = WK_KLASS(Short_klass); 2028 _box_klasses[T_INT] = WK_KLASS(Integer_klass); 2029 _box_klasses[T_LONG] = WK_KLASS(Long_klass); 2030 //_box_klasses[T_OBJECT] = WK_KLASS(object_klass); 2031 //_box_klasses[T_ARRAY] = WK_KLASS(object_klass); 2032 2033 #ifdef ASSERT 2034 if (UseSharedSpaces) { 2035 assert(JvmtiExport::is_early_phase(), 2036 "All well known classes must be resolved in JVMTI early phase"); 2037 for (int i = FIRST_WKID; i < last; i++) { 2038 InstanceKlass* k = _well_known_klasses[i]; 2039 assert(k->is_shared(), "must not be replaced by JVMTI class file load hook"); 2040 } 2041 } 2042 #endif 2043 } 2044 2045 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer). 2046 // If so, returns the basic type it holds. If not, returns T_OBJECT. 2047 BasicType SystemDictionary::box_klass_type(Klass* k) { 2048 assert(k != NULL, ""); 2049 for (int i = T_BOOLEAN; i < T_VOID+1; i++) { 2050 if (_box_klasses[i] == k) 2051 return (BasicType)i; 2052 } 2053 return T_OBJECT; 2054 } 2055 2056 // Constraints on class loaders. The details of the algorithm can be 2057 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java 2058 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is 2059 // that the dictionary needs to maintain a set of contraints that 2060 // must be satisfied by all classes in the dictionary. 2061 // if defining is true, then LinkageError if already in dictionary 2062 // if initiating loader, then ok if InstanceKlass matches existing entry 2063 2064 void SystemDictionary::check_constraints(unsigned int d_hash, 2065 InstanceKlass* k, 2066 Handle class_loader, 2067 bool defining, 2068 TRAPS) { 2069 ResourceMark rm(THREAD); 2070 stringStream ss; 2071 bool throwException = false; 2072 2073 { 2074 Symbol *name = k->name(); 2075 ClassLoaderData *loader_data = class_loader_data(class_loader); 2076 2077 MutexLocker mu(THREAD, SystemDictionary_lock); 2078 2079 InstanceKlass* check = find_class(d_hash, name, loader_data->dictionary()); 2080 if (check != NULL) { 2081 // If different InstanceKlass - duplicate class definition, 2082 // else - ok, class loaded by a different thread in parallel. 2083 // We should only have found it if it was done loading and ok to use. 2084 // The dictionary only holds instance classes, placeholders 2085 // also hold array classes. 2086 2087 assert(check->is_instance_klass(), "noninstance in systemdictionary"); 2088 if ((defining == true) || (k != check)) { 2089 throwException = true; 2090 ss.print("loader %s", loader_data->loader_name_and_id()); 2091 ss.print(" attempted duplicate %s definition for %s. (%s)", 2092 k->external_kind(), k->external_name(), k->class_in_module_of_loader(false, true)); 2093 } else { 2094 return; 2095 } 2096 } 2097 2098 #ifdef ASSERT 2099 Symbol* ph_check = find_placeholder(name, loader_data); 2100 assert(ph_check == NULL || ph_check == name, "invalid symbol"); 2101 #endif 2102 2103 if (throwException == false) { 2104 if (constraints()->check_or_update(k, class_loader, name) == false) { 2105 throwException = true; 2106 ss.print("loader constraint violation: loader %s", loader_data->loader_name_and_id()); 2107 ss.print(" wants to load %s %s.", 2108 k->external_kind(), k->external_name()); 2109 Klass *existing_klass = constraints()->find_constrained_klass(name, class_loader); 2110 if (existing_klass != NULL && existing_klass->class_loader() != class_loader()) { 2111 ss.print(" A different %s with the same name was previously loaded by %s. (%s)", 2112 existing_klass->external_kind(), 2113 existing_klass->class_loader_data()->loader_name_and_id(), 2114 existing_klass->class_in_module_of_loader(false, true)); 2115 } else { 2116 ss.print(" (%s)", k->class_in_module_of_loader(false, true)); 2117 } 2118 } 2119 } 2120 } 2121 2122 // Throw error now if needed (cannot throw while holding 2123 // SystemDictionary_lock because of rank ordering) 2124 if (throwException == true) { 2125 THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string()); 2126 } 2127 } 2128 2129 // Update class loader data dictionary - done after check_constraint and add_to_hierachy 2130 // have been called. 2131 void SystemDictionary::update_dictionary(unsigned int d_hash, 2132 int p_index, unsigned int p_hash, 2133 InstanceKlass* k, 2134 Handle class_loader, 2135 TRAPS) { 2136 // Compile_lock prevents systemDictionary updates during compilations 2137 assert_locked_or_safepoint(Compile_lock); 2138 Symbol* name = k->name(); 2139 ClassLoaderData *loader_data = class_loader_data(class_loader); 2140 2141 { 2142 MutexLocker mu1(THREAD, SystemDictionary_lock); 2143 2144 // Make a new dictionary entry. 2145 Dictionary* dictionary = loader_data->dictionary(); 2146 InstanceKlass* sd_check = find_class(d_hash, name, dictionary); 2147 if (sd_check == NULL) { 2148 dictionary->add_klass(d_hash, name, k); 2149 } 2150 #ifdef ASSERT 2151 sd_check = find_class(d_hash, name, dictionary); 2152 assert (sd_check != NULL, "should have entry in dictionary"); 2153 // Note: there may be a placeholder entry: for circularity testing 2154 // or for parallel defines 2155 #endif 2156 SystemDictionary_lock->notify_all(); 2157 } 2158 } 2159 2160 2161 // Try to find a class name using the loader constraints. The 2162 // loader constraints might know about a class that isn't fully loaded 2163 // yet and these will be ignored. 2164 Klass* SystemDictionary::find_constrained_instance_or_array_klass( 2165 Symbol* class_name, Handle class_loader, TRAPS) { 2166 2167 // First see if it has been loaded directly. 2168 // Force the protection domain to be null. (This removes protection checks.) 2169 Handle no_protection_domain; 2170 Klass* klass = find_instance_or_array_klass(class_name, class_loader, 2171 no_protection_domain, CHECK_NULL); 2172 if (klass != NULL) 2173 return klass; 2174 2175 // Now look to see if it has been loaded elsewhere, and is subject to 2176 // a loader constraint that would require this loader to return the 2177 // klass that is already loaded. 2178 if (Signature::is_array(class_name)) { 2179 // For array classes, their Klass*s are not kept in the 2180 // constraint table. The element Klass*s are. 2181 SignatureStream ss(class_name, false); 2182 int ndims = ss.skip_array_prefix(); // skip all '['s 2183 BasicType t = ss.type(); 2184 if (t != T_OBJECT) { 2185 klass = Universe::typeArrayKlassObj(t); 2186 } else { 2187 MutexLocker mu(THREAD, SystemDictionary_lock); 2188 klass = constraints()->find_constrained_klass(ss.as_symbol(), class_loader); 2189 } 2190 // If element class already loaded, allocate array klass 2191 if (klass != NULL) { 2192 klass = klass->array_klass_or_null(ndims); 2193 } 2194 } else { 2195 MutexLocker mu(THREAD, SystemDictionary_lock); 2196 // Non-array classes are easy: simply check the constraint table. 2197 klass = constraints()->find_constrained_klass(class_name, class_loader); 2198 } 2199 2200 return klass; 2201 } 2202 2203 2204 bool SystemDictionary::add_loader_constraint(Symbol* class_name, 2205 Handle class_loader1, 2206 Handle class_loader2, 2207 Thread* THREAD) { 2208 ClassLoaderData* loader_data1 = class_loader_data(class_loader1); 2209 ClassLoaderData* loader_data2 = class_loader_data(class_loader2); 2210 2211 Symbol* constraint_name = NULL; 2212 2213 if (!Signature::is_array(class_name)) { 2214 constraint_name = class_name; 2215 } else { 2216 // For array classes, their Klass*s are not kept in the 2217 // constraint table. The element classes are. 2218 SignatureStream ss(class_name, false); 2219 ss.skip_array_prefix(); // skip all '['s 2220 if (!ss.has_envelope()) { 2221 return true; // primitive types always pass 2222 } 2223 constraint_name = ss.as_symbol(); 2224 // Increment refcount to keep constraint_name alive after 2225 // SignatureStream is destructed. It will be decremented below 2226 // before returning. 2227 constraint_name->increment_refcount(); 2228 } 2229 2230 Dictionary* dictionary1 = loader_data1->dictionary(); 2231 unsigned int d_hash1 = dictionary1->compute_hash(constraint_name); 2232 2233 Dictionary* dictionary2 = loader_data2->dictionary(); 2234 unsigned int d_hash2 = dictionary2->compute_hash(constraint_name); 2235 2236 { 2237 MutexLocker mu_s(THREAD, SystemDictionary_lock); 2238 InstanceKlass* klass1 = find_class(d_hash1, constraint_name, dictionary1); 2239 InstanceKlass* klass2 = find_class(d_hash2, constraint_name, dictionary2); 2240 bool result = constraints()->add_entry(constraint_name, klass1, class_loader1, 2241 klass2, class_loader2); 2242 if (Signature::is_array(class_name)) { 2243 constraint_name->decrement_refcount(); 2244 } 2245 return result; 2246 } 2247 } 2248 2249 // Add entry to resolution error table to record the error when the first 2250 // attempt to resolve a reference to a class has failed. 2251 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which, 2252 Symbol* error, Symbol* message) { 2253 unsigned int hash = resolution_errors()->compute_hash(pool, which); 2254 int index = resolution_errors()->hash_to_index(hash); 2255 { 2256 MutexLocker ml(Thread::current(), SystemDictionary_lock); 2257 resolution_errors()->add_entry(index, hash, pool, which, error, message); 2258 } 2259 } 2260 2261 // Delete a resolution error for RedefineClasses for a constant pool is going away 2262 void SystemDictionary::delete_resolution_error(ConstantPool* pool) { 2263 resolution_errors()->delete_entry(pool); 2264 } 2265 2266 // Lookup resolution error table. Returns error if found, otherwise NULL. 2267 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which, 2268 Symbol** message) { 2269 unsigned int hash = resolution_errors()->compute_hash(pool, which); 2270 int index = resolution_errors()->hash_to_index(hash); 2271 { 2272 MutexLocker ml(Thread::current(), SystemDictionary_lock); 2273 ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which); 2274 if (entry != NULL) { 2275 *message = entry->message(); 2276 return entry->error(); 2277 } else { 2278 return NULL; 2279 } 2280 } 2281 } 2282 2283 2284 // Signature constraints ensure that callers and callees agree about 2285 // the meaning of type names in their signatures. This routine is the 2286 // intake for constraints. It collects them from several places: 2287 // 2288 // * LinkResolver::resolve_method (if check_access is true) requires 2289 // that the resolving class (the caller) and the defining class of 2290 // the resolved method (the callee) agree on each type in the 2291 // method's signature. 2292 // 2293 // * LinkResolver::resolve_interface_method performs exactly the same 2294 // checks. 2295 // 2296 // * LinkResolver::resolve_field requires that the constant pool 2297 // attempting to link to a field agree with the field's defining 2298 // class about the type of the field signature. 2299 // 2300 // * klassVtable::initialize_vtable requires that, when a class 2301 // overrides a vtable entry allocated by a superclass, that the 2302 // overriding method (i.e., the callee) agree with the superclass 2303 // on each type in the method's signature. 2304 // 2305 // * klassItable::initialize_itable requires that, when a class fills 2306 // in its itables, for each non-abstract method installed in an 2307 // itable, the method (i.e., the callee) agree with the interface 2308 // on each type in the method's signature. 2309 // 2310 // All those methods have a boolean (check_access, checkconstraints) 2311 // which turns off the checks. This is used from specialized contexts 2312 // such as bootstrapping, dumping, and debugging. 2313 // 2314 // No direct constraint is placed between the class and its 2315 // supertypes. Constraints are only placed along linked relations 2316 // between callers and callees. When a method overrides or implements 2317 // an abstract method in a supertype (superclass or interface), the 2318 // constraints are placed as if the supertype were the caller to the 2319 // overriding method. (This works well, since callers to the 2320 // supertype have already established agreement between themselves and 2321 // the supertype.) As a result of all this, a class can disagree with 2322 // its supertype about the meaning of a type name, as long as that 2323 // class neither calls a relevant method of the supertype, nor is 2324 // called (perhaps via an override) from the supertype. 2325 // 2326 // 2327 // SystemDictionary::check_signature_loaders(sig, l1, l2) 2328 // 2329 // Make sure all class components (including arrays) in the given 2330 // signature will be resolved to the same class in both loaders. 2331 // Returns the name of the type that failed a loader constraint check, or 2332 // NULL if no constraint failed. No exception except OOME is thrown. 2333 // Arrays are not added to the loader constraint table, their elements are. 2334 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature, 2335 Handle loader1, Handle loader2, 2336 bool is_method, TRAPS) { 2337 // Nothing to do if loaders are the same. 2338 if (loader1() == loader2()) { 2339 return NULL; 2340 } 2341 2342 for (SignatureStream ss(signature, is_method); !ss.is_done(); ss.next()) { 2343 if (ss.is_reference()) { 2344 Symbol* sig = ss.as_symbol(); 2345 // Note: In the future, if template-like types can take 2346 // arguments, we will want to recognize them and dig out class 2347 // names hiding inside the argument lists. 2348 if (!add_loader_constraint(sig, loader1, loader2, THREAD)) { 2349 return sig; 2350 } 2351 } 2352 } 2353 return NULL; 2354 } 2355 2356 2357 Method* SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid, 2358 Symbol* signature, 2359 TRAPS) { 2360 methodHandle empty; 2361 assert(MethodHandles::is_signature_polymorphic(iid) && 2362 MethodHandles::is_signature_polymorphic_intrinsic(iid) && 2363 iid != vmIntrinsics::_invokeGeneric, 2364 "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid)); 2365 2366 unsigned int hash = invoke_method_table()->compute_hash(signature, iid); 2367 int index = invoke_method_table()->hash_to_index(hash); 2368 SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid); 2369 methodHandle m; 2370 if (spe == NULL || spe->method() == NULL) { 2371 spe = NULL; 2372 // Must create lots of stuff here, but outside of the SystemDictionary lock. 2373 m = Method::make_method_handle_intrinsic(iid, signature, CHECK_NULL); 2374 if (!Arguments::is_interpreter_only()) { 2375 // Generate a compiled form of the MH intrinsic. 2376 AdapterHandlerLibrary::create_native_wrapper(m); 2377 // Check if have the compiled code. 2378 if (!m->has_compiled_code()) { 2379 THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), 2380 "Out of space in CodeCache for method handle intrinsic"); 2381 } 2382 } 2383 // Now grab the lock. We might have to throw away the new method, 2384 // if a racing thread has managed to install one at the same time. 2385 { 2386 MutexLocker ml(THREAD, SystemDictionary_lock); 2387 spe = invoke_method_table()->find_entry(index, hash, signature, iid); 2388 if (spe == NULL) 2389 spe = invoke_method_table()->add_entry(index, hash, signature, iid); 2390 if (spe->method() == NULL) 2391 spe->set_method(m()); 2392 } 2393 } 2394 2395 assert(spe != NULL && spe->method() != NULL, ""); 2396 assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() && 2397 spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()), 2398 "MH intrinsic invariant"); 2399 return spe->method(); 2400 } 2401 2402 // Helper for unpacking the return value from linkMethod and linkCallSite. 2403 static Method* unpack_method_and_appendix(Handle mname, 2404 Klass* accessing_klass, 2405 objArrayHandle appendix_box, 2406 Handle* appendix_result, 2407 TRAPS) { 2408 if (mname.not_null()) { 2409 Method* m = java_lang_invoke_MemberName::vmtarget(mname()); 2410 if (m != NULL) { 2411 oop appendix = appendix_box->obj_at(0); 2412 if (TraceMethodHandles) { 2413 #ifndef PRODUCT 2414 ttyLocker ttyl; 2415 tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m)); 2416 m->print(); 2417 if (appendix != NULL) { tty->print("appendix = "); appendix->print(); } 2418 tty->cr(); 2419 #endif //PRODUCT 2420 } 2421 (*appendix_result) = Handle(THREAD, appendix); 2422 // the target is stored in the cpCache and if a reference to this 2423 // MemberName is dropped we need a way to make sure the 2424 // class_loader containing this method is kept alive. 2425 methodHandle mh(THREAD, m); // record_dependency can safepoint. 2426 ClassLoaderData* this_key = accessing_klass->class_loader_data(); 2427 this_key->record_dependency(m->method_holder()); 2428 return mh(); 2429 } 2430 } 2431 THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives"); 2432 } 2433 2434 Method* SystemDictionary::find_method_handle_invoker(Klass* klass, 2435 Symbol* name, 2436 Symbol* signature, 2437 Klass* accessing_klass, 2438 Handle *appendix_result, 2439 TRAPS) { 2440 assert(THREAD->can_call_java() ,""); 2441 Handle method_type = 2442 SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL); 2443 2444 int ref_kind = JVM_REF_invokeVirtual; 2445 oop name_oop = StringTable::intern(name, CHECK_NULL); 2446 Handle name_str (THREAD, name_oop); 2447 objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_NULL); 2448 assert(appendix_box->obj_at(0) == NULL, ""); 2449 2450 // This should not happen. JDK code should take care of that. 2451 if (accessing_klass == NULL || method_type.is_null()) { 2452 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle"); 2453 } 2454 2455 // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName 2456 JavaCallArguments args; 2457 args.push_oop(Handle(THREAD, accessing_klass->java_mirror())); 2458 args.push_int(ref_kind); 2459 args.push_oop(Handle(THREAD, klass->java_mirror())); 2460 args.push_oop(name_str); 2461 args.push_oop(method_type); 2462 args.push_oop(appendix_box); 2463 JavaValue result(T_OBJECT); 2464 JavaCalls::call_static(&result, 2465 SystemDictionary::MethodHandleNatives_klass(), 2466 vmSymbols::linkMethod_name(), 2467 vmSymbols::linkMethod_signature(), 2468 &args, CHECK_NULL); 2469 Handle mname(THREAD, (oop) result.get_jobject()); 2470 return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD); 2471 } 2472 2473 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks. 2474 // We must ensure that all class loaders everywhere will reach this class, for any client. 2475 // This is a safe bet for public classes in java.lang, such as Object and String. 2476 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types. 2477 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util. 2478 static bool is_always_visible_class(oop mirror) { 2479 Klass* klass = java_lang_Class::as_Klass(mirror); 2480 if (klass->is_objArray_klass()) { 2481 klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type 2482 } 2483 if (klass->is_typeArray_klass()) { 2484 return true; // primitive array 2485 } 2486 assert(klass->is_instance_klass(), "%s", klass->external_name()); 2487 return klass->is_public() && 2488 (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) || // java.lang 2489 InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass())); // java.lang.invoke 2490 } 2491 2492 // Find or construct the Java mirror (java.lang.Class instance) for a 2493 // for the given field type signature, as interpreted relative to the 2494 // given class loader. Handles primitives, void, references, arrays, 2495 // and all other reflectable types, except method types. 2496 // N.B. Code in reflection should use this entry point. 2497 Handle SystemDictionary::find_java_mirror_for_type(Symbol* signature, 2498 Klass* accessing_klass, 2499 Handle class_loader, 2500 Handle protection_domain, 2501 SignatureStream::FailureMode failure_mode, 2502 TRAPS) { 2503 Handle empty; 2504 2505 assert(accessing_klass == NULL || (class_loader.is_null() && protection_domain.is_null()), 2506 "one or the other, or perhaps neither"); 2507 2508 SignatureStream ss(signature, false); 2509 2510 // What we have here must be a valid field descriptor, 2511 // and all valid field descriptors are supported. 2512 // Produce the same java.lang.Class that reflection reports. 2513 if (ss.is_primitive() || (ss.type() == T_VOID)) { 2514 2515 // It's a primitive. (Void has a primitive mirror too.) 2516 return Handle(THREAD, java_lang_Class::primitive_mirror(ss.type())); 2517 2518 } else if (ss.is_reference()) { 2519 2520 // It's a reference type. 2521 if (accessing_klass != NULL) { 2522 class_loader = Handle(THREAD, accessing_klass->class_loader()); 2523 protection_domain = Handle(THREAD, accessing_klass->protection_domain()); 2524 } 2525 Klass* constant_type_klass; 2526 if (failure_mode == SignatureStream::ReturnNull) { 2527 constant_type_klass = resolve_or_null(signature, class_loader, protection_domain, 2528 CHECK_(empty)); 2529 } else { 2530 bool throw_error = (failure_mode == SignatureStream::NCDFError); 2531 constant_type_klass = resolve_or_fail(signature, class_loader, protection_domain, 2532 throw_error, CHECK_(empty)); 2533 } 2534 if (constant_type_klass == NULL) { 2535 return Handle(); // report failure this way 2536 } 2537 Handle mirror(THREAD, constant_type_klass->java_mirror()); 2538 2539 // Check accessibility, emulating ConstantPool::verify_constant_pool_resolve. 2540 if (accessing_klass != NULL) { 2541 Klass* sel_klass = constant_type_klass; 2542 bool fold_type_to_class = true; 2543 LinkResolver::check_klass_accessability(accessing_klass, sel_klass, 2544 fold_type_to_class, CHECK_(empty)); 2545 } 2546 2547 return mirror; 2548 2549 } 2550 2551 // Fall through to an error. 2552 assert(false, "unsupported mirror syntax"); 2553 THROW_MSG_(vmSymbols::java_lang_InternalError(), "unsupported mirror syntax", empty); 2554 } 2555 2556 2557 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given 2558 // signature, as interpreted relative to the given class loader. 2559 // Because of class loader constraints, all method handle usage must be 2560 // consistent with this loader. 2561 Handle SystemDictionary::find_method_handle_type(Symbol* signature, 2562 Klass* accessing_klass, 2563 TRAPS) { 2564 Handle empty; 2565 vmIntrinsics::ID null_iid = vmIntrinsics::_none; // distinct from all method handle invoker intrinsics 2566 unsigned int hash = invoke_method_table()->compute_hash(signature, null_iid); 2567 int index = invoke_method_table()->hash_to_index(hash); 2568 SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid); 2569 if (spe != NULL && spe->method_type() != NULL) { 2570 assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), ""); 2571 return Handle(THREAD, spe->method_type()); 2572 } else if (!THREAD->can_call_java()) { 2573 warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME 2574 return Handle(); // do not attempt from within compiler, unless it was cached 2575 } 2576 2577 Handle class_loader, protection_domain; 2578 if (accessing_klass != NULL) { 2579 class_loader = Handle(THREAD, accessing_klass->class_loader()); 2580 protection_domain = Handle(THREAD, accessing_klass->protection_domain()); 2581 } 2582 bool can_be_cached = true; 2583 int npts = ArgumentCount(signature).size(); 2584 objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty)); 2585 int arg = 0; 2586 Handle rt; // the return type from the signature 2587 ResourceMark rm(THREAD); 2588 for (SignatureStream ss(signature); !ss.is_done(); ss.next()) { 2589 oop mirror = NULL; 2590 if (can_be_cached) { 2591 // Use neutral class loader to lookup candidate classes to be placed in the cache. 2592 mirror = ss.as_java_mirror(Handle(), Handle(), 2593 SignatureStream::ReturnNull, CHECK_(empty)); 2594 if (mirror == NULL || (ss.is_reference() && !is_always_visible_class(mirror))) { 2595 // Fall back to accessing_klass context. 2596 can_be_cached = false; 2597 } 2598 } 2599 if (!can_be_cached) { 2600 // Resolve, throwing a real error if it doesn't work. 2601 mirror = ss.as_java_mirror(class_loader, protection_domain, 2602 SignatureStream::NCDFError, CHECK_(empty)); 2603 } 2604 assert(mirror != NULL, "%s", ss.as_symbol()->as_C_string()); 2605 if (ss.at_return_type()) 2606 rt = Handle(THREAD, mirror); 2607 else 2608 pts->obj_at_put(arg++, mirror); 2609 2610 // Check accessibility. 2611 if (!java_lang_Class::is_primitive(mirror) && accessing_klass != NULL) { 2612 Klass* sel_klass = java_lang_Class::as_Klass(mirror); 2613 mirror = NULL; // safety 2614 // Emulate ConstantPool::verify_constant_pool_resolve. 2615 bool fold_type_to_class = true; 2616 LinkResolver::check_klass_accessability(accessing_klass, sel_klass, 2617 fold_type_to_class, CHECK_(empty)); 2618 } 2619 } 2620 assert(arg == npts, ""); 2621 2622 // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType 2623 JavaCallArguments args(Handle(THREAD, rt())); 2624 args.push_oop(pts); 2625 JavaValue result(T_OBJECT); 2626 JavaCalls::call_static(&result, 2627 SystemDictionary::MethodHandleNatives_klass(), 2628 vmSymbols::findMethodHandleType_name(), 2629 vmSymbols::findMethodHandleType_signature(), 2630 &args, CHECK_(empty)); 2631 Handle method_type(THREAD, (oop) result.get_jobject()); 2632 2633 if (can_be_cached) { 2634 // We can cache this MethodType inside the JVM. 2635 MutexLocker ml(THREAD, SystemDictionary_lock); 2636 spe = invoke_method_table()->find_entry(index, hash, signature, null_iid); 2637 if (spe == NULL) 2638 spe = invoke_method_table()->add_entry(index, hash, signature, null_iid); 2639 if (spe->method_type() == NULL) { 2640 spe->set_method_type(method_type()); 2641 } 2642 } 2643 2644 // report back to the caller with the MethodType 2645 return method_type; 2646 } 2647 2648 Handle SystemDictionary::find_field_handle_type(Symbol* signature, 2649 Klass* accessing_klass, 2650 TRAPS) { 2651 Handle empty; 2652 ResourceMark rm(THREAD); 2653 SignatureStream ss(signature, /*is_method=*/ false); 2654 if (!ss.is_done()) { 2655 Handle class_loader, protection_domain; 2656 if (accessing_klass != NULL) { 2657 class_loader = Handle(THREAD, accessing_klass->class_loader()); 2658 protection_domain = Handle(THREAD, accessing_klass->protection_domain()); 2659 } 2660 oop mirror = ss.as_java_mirror(class_loader, protection_domain, SignatureStream::NCDFError, CHECK_(empty)); 2661 ss.next(); 2662 if (ss.is_done()) { 2663 return Handle(THREAD, mirror); 2664 } 2665 } 2666 return empty; 2667 } 2668 2669 // Ask Java code to find or construct a method handle constant. 2670 Handle SystemDictionary::link_method_handle_constant(Klass* caller, 2671 int ref_kind, //e.g., JVM_REF_invokeVirtual 2672 Klass* callee, 2673 Symbol* name, 2674 Symbol* signature, 2675 TRAPS) { 2676 Handle empty; 2677 if (caller == NULL) { 2678 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty); 2679 } 2680 Handle name_str = java_lang_String::create_from_symbol(name, CHECK_(empty)); 2681 Handle signature_str = java_lang_String::create_from_symbol(signature, CHECK_(empty)); 2682 2683 // Put symbolic info from the MH constant into freshly created MemberName and resolve it. 2684 Handle mname = MemberName_klass()->allocate_instance_handle(CHECK_(empty)); 2685 java_lang_invoke_MemberName::set_clazz(mname(), callee->java_mirror()); 2686 java_lang_invoke_MemberName::set_name (mname(), name_str()); 2687 java_lang_invoke_MemberName::set_type (mname(), signature_str()); 2688 java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind)); 2689 2690 if (ref_kind == JVM_REF_invokeVirtual && 2691 MethodHandles::is_signature_polymorphic_public_name(callee, name)) { 2692 // Skip resolution for public signature polymorphic methods such as 2693 // j.l.i.MethodHandle.invoke()/invokeExact() and those on VarHandle 2694 // They require appendix argument which MemberName resolution doesn't handle. 2695 // There's special logic on JDK side to handle them 2696 // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()). 2697 } else { 2698 MethodHandles::resolve_MemberName(mname, caller, /*speculative_resolve*/false, CHECK_(empty)); 2699 } 2700 2701 // After method/field resolution succeeded, it's safe to resolve MH signature as well. 2702 Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty)); 2703 2704 // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle 2705 JavaCallArguments args; 2706 args.push_oop(Handle(THREAD, caller->java_mirror())); // the referring class 2707 args.push_int(ref_kind); 2708 args.push_oop(Handle(THREAD, callee->java_mirror())); // the target class 2709 args.push_oop(name_str); 2710 args.push_oop(type); 2711 JavaValue result(T_OBJECT); 2712 JavaCalls::call_static(&result, 2713 SystemDictionary::MethodHandleNatives_klass(), 2714 vmSymbols::linkMethodHandleConstant_name(), 2715 vmSymbols::linkMethodHandleConstant_signature(), 2716 &args, CHECK_(empty)); 2717 return Handle(THREAD, (oop) result.get_jobject()); 2718 } 2719 2720 // Ask Java to run a bootstrap method, in order to create a dynamic call site 2721 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry 2722 // with linkage results being stored back into the bootstrap specifier. 2723 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) { 2724 // Resolve the bootstrap specifier, its name, type, and static arguments 2725 bootstrap_specifier.resolve_bsm(CHECK); 2726 2727 // This should not happen. JDK code should take care of that. 2728 if (bootstrap_specifier.caller() == NULL || bootstrap_specifier.type_arg().is_null()) { 2729 THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument"); 2730 } 2731 2732 bool is_indy = bootstrap_specifier.is_method_call(); 2733 objArrayHandle appendix_box; 2734 if (is_indy) { 2735 // Some method calls may require an appendix argument. Arrange to receive it. 2736 appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK); 2737 assert(appendix_box->obj_at(0) == NULL, ""); 2738 } 2739 2740 // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, condy_index, bsm, type, info) 2741 // indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, indy_index, bsm, name, mtype, info, &appendix) 2742 JavaCallArguments args; 2743 args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror())); 2744 args.push_int(bootstrap_specifier.bss_index()); 2745 args.push_oop(bootstrap_specifier.bsm()); 2746 args.push_oop(bootstrap_specifier.name_arg()); 2747 args.push_oop(bootstrap_specifier.type_arg()); 2748 args.push_oop(bootstrap_specifier.arg_values()); 2749 if (is_indy) { 2750 args.push_oop(appendix_box); 2751 } 2752 JavaValue result(T_OBJECT); 2753 JavaCalls::call_static(&result, 2754 SystemDictionary::MethodHandleNatives_klass(), 2755 is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(), 2756 is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(), 2757 &args, CHECK); 2758 2759 Handle value(THREAD, (oop) result.get_jobject()); 2760 if (is_indy) { 2761 Handle appendix; 2762 Method* method = unpack_method_and_appendix(value, 2763 bootstrap_specifier.caller(), 2764 appendix_box, 2765 &appendix, CHECK); 2766 methodHandle mh(THREAD, method); 2767 bootstrap_specifier.set_resolved_method(mh, appendix); 2768 } else { 2769 bootstrap_specifier.set_resolved_value(value); 2770 } 2771 2772 // sanity check 2773 assert(bootstrap_specifier.is_resolved() || 2774 (bootstrap_specifier.is_method_call() && 2775 bootstrap_specifier.resolved_method().not_null()), "bootstrap method call failed"); 2776 } 2777 2778 // Protection domain cache table handling 2779 2780 ProtectionDomainCacheEntry* SystemDictionary::cache_get(Handle protection_domain) { 2781 return _pd_cache_table->get(protection_domain); 2782 } 2783 2784 // ---------------------------------------------------------------------------- 2785 2786 void SystemDictionary::print_on(outputStream *st) { 2787 CDS_ONLY(SystemDictionaryShared::print_on(st)); 2788 GCMutexLocker mu(SystemDictionary_lock); 2789 2790 ClassLoaderDataGraph::print_dictionary(st); 2791 2792 // Placeholders 2793 placeholders()->print_on(st); 2794 st->cr(); 2795 2796 // loader constraints - print under SD_lock 2797 constraints()->print_on(st); 2798 st->cr(); 2799 2800 _pd_cache_table->print_on(st); 2801 st->cr(); 2802 } 2803 2804 void SystemDictionary::print() { print_on(tty); } 2805 2806 void SystemDictionary::verify() { 2807 guarantee(constraints() != NULL, 2808 "Verify of loader constraints failed"); 2809 guarantee(placeholders()->number_of_entries() >= 0, 2810 "Verify of placeholders failed"); 2811 2812 GCMutexLocker mu(SystemDictionary_lock); 2813 2814 // Verify dictionary 2815 ClassLoaderDataGraph::verify_dictionary(); 2816 2817 placeholders()->verify(); 2818 2819 // Verify constraint table 2820 guarantee(constraints() != NULL, "Verify of loader constraints failed"); 2821 constraints()->verify(placeholders()); 2822 2823 _pd_cache_table->verify(); 2824 } 2825 2826 void SystemDictionary::dump(outputStream *st, bool verbose) { 2827 assert_locked_or_safepoint(SystemDictionary_lock); 2828 if (verbose) { 2829 print_on(st); 2830 } else { 2831 CDS_ONLY(SystemDictionaryShared::print_table_statistics(st)); 2832 ClassLoaderDataGraph::print_table_statistics(st); 2833 placeholders()->print_table_statistics(st, "Placeholder Table"); 2834 constraints()->print_table_statistics(st, "LoaderConstraints Table"); 2835 pd_cache_table()->print_table_statistics(st, "ProtectionDomainCache Table"); 2836 } 2837 } 2838 2839 TableStatistics SystemDictionary::placeholders_statistics() { 2840 MutexLocker ml(SystemDictionary_lock); 2841 return placeholders()->statistics_calculate(); 2842 } 2843 2844 TableStatistics SystemDictionary::loader_constraints_statistics() { 2845 MutexLocker ml(SystemDictionary_lock); 2846 return constraints()->statistics_calculate(); 2847 } 2848 2849 TableStatistics SystemDictionary::protection_domain_cache_statistics() { 2850 MutexLocker ml(SystemDictionary_lock); 2851 return pd_cache_table()->statistics_calculate(); 2852 } 2853 2854 // Utility for dumping dictionaries. 2855 SystemDictionaryDCmd::SystemDictionaryDCmd(outputStream* output, bool heap) : 2856 DCmdWithParser(output, heap), 2857 _verbose("-verbose", "Dump the content of each dictionary entry for all class loaders", 2858 "BOOLEAN", false, "false") { 2859 _dcmdparser.add_dcmd_option(&_verbose); 2860 } 2861 2862 void SystemDictionaryDCmd::execute(DCmdSource source, TRAPS) { 2863 VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSysDict, 2864 _verbose.value()); 2865 VMThread::execute(&dumper); 2866 } 2867 2868 int SystemDictionaryDCmd::num_arguments() { 2869 ResourceMark rm; 2870 SystemDictionaryDCmd* dcmd = new SystemDictionaryDCmd(NULL, false); 2871 if (dcmd != NULL) { 2872 DCmdMark mark(dcmd); 2873 return dcmd->_dcmdparser.num_arguments(); 2874 } else { 2875 return 0; 2876 } 2877 }