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