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