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