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