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