1 /* 2 * Copyright (c) 1997, 2017, 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(oop class_loader) { 164 if (class_loader == 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(oop class_loader) { 173 if (class_loader == 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 HandleMark hm(THREAD); 666 667 // Fix for 4474172; see evaluation for more details 668 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 669 ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL); 670 671 // Do lookup to see if class already exist and the protection domain 672 // has the right access 673 // This call uses find which checks protection domain already matches 674 // All subsequent calls use find_class, and set has_loaded_class so that 675 // before we return a result we call out to java to check for valid protection domain 676 // to allow returning the Klass* and add it to the pd_set if it is valid 677 unsigned int d_hash = dictionary()->compute_hash(name, loader_data); 678 int d_index = dictionary()->hash_to_index(d_hash); 679 Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data, 680 protection_domain, THREAD); 681 if (probe != NULL) return probe; 682 683 684 // Non-bootstrap class loaders will call out to class loader and 685 // define via jvm/jni_DefineClass which will acquire the 686 // class loader object lock to protect against multiple threads 687 // defining the class in parallel by accident. 688 // This lock must be acquired here so the waiter will find 689 // any successful result in the SystemDictionary and not attempt 690 // the define 691 // ParallelCapable Classloaders and the bootstrap classloader, 692 // or all classloaders with UnsyncloadClass do not acquire lock here 693 bool DoObjectLock = true; 694 if (is_parallelCapable(class_loader)) { 695 DoObjectLock = false; 696 } 697 698 unsigned int p_hash = placeholders()->compute_hash(name, loader_data); 699 int p_index = placeholders()->hash_to_index(p_hash); 700 701 // Class is not in SystemDictionary so we have to do loading. 702 // Make sure we are synchronized on the class loader before we proceed 703 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 704 check_loader_lock_contention(lockObject, THREAD); 705 ObjectLocker ol(lockObject, THREAD, DoObjectLock); 706 707 // Check again (after locking) if class already exist in SystemDictionary 708 bool class_has_been_loaded = false; 709 bool super_load_in_progress = false; 710 bool havesupername = false; 711 instanceKlassHandle k; 712 PlaceholderEntry* placeholder; 713 Symbol* superclassname = NULL; 714 715 { 716 MutexLocker mu(SystemDictionary_lock, THREAD); 717 Klass* check = find_class(d_index, d_hash, name, loader_data); 718 if (check != NULL) { 719 // Klass is already loaded, so just return it 720 class_has_been_loaded = true; 721 k = instanceKlassHandle(THREAD, check); 722 } else { 723 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data); 724 if (placeholder && placeholder->super_load_in_progress()) { 725 super_load_in_progress = true; 726 if (placeholder->havesupername() == true) { 727 superclassname = placeholder->supername(); 728 havesupername = true; 729 } 730 } 731 } 732 } 733 734 // If the class is in the placeholder table, class loading is in progress 735 if (super_load_in_progress && havesupername==true) { 736 k = SystemDictionary::handle_parallel_super_load(name, superclassname, 737 class_loader, protection_domain, lockObject, THREAD); 738 if (HAS_PENDING_EXCEPTION) { 739 return NULL; 740 } 741 if (!k.is_null()) { 742 class_has_been_loaded = true; 743 } 744 } 745 746 bool throw_circularity_error = false; 747 if (!class_has_been_loaded) { 748 bool load_instance_added = false; 749 750 // add placeholder entry to record loading instance class 751 // Five cases: 752 // All cases need to prevent modifying bootclasssearchpath 753 // in parallel with a classload of same classname 754 // Redefineclasses uses existence of the placeholder for the duration 755 // of the class load to prevent concurrent redefinition of not completely 756 // defined classes. 757 // case 1. traditional classloaders that rely on the classloader object lock 758 // - no other need for LOAD_INSTANCE 759 // case 2. traditional classloaders that break the classloader object lock 760 // as a deadlock workaround. Detection of this case requires that 761 // this check is done while holding the classloader object lock, 762 // and that lock is still held when calling classloader's loadClass. 763 // For these classloaders, we ensure that the first requestor 764 // completes the load and other requestors wait for completion. 765 // case 3. UnsyncloadClass - don't use objectLocker 766 // With this flag, we allow parallel classloading of a 767 // class/classloader pair 768 // case4. Bootstrap classloader - don't own objectLocker 769 // This classloader supports parallelism at the classloader level, 770 // but only allows a single load of a class/classloader pair. 771 // No performance benefit and no deadlock issues. 772 // case 5. parallelCapable user level classloaders - without objectLocker 773 // Allow parallel classloading of a class/classloader pair 774 775 { 776 MutexLocker mu(SystemDictionary_lock, THREAD); 777 if (class_loader.is_null() || !is_parallelCapable(class_loader)) { 778 PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data); 779 if (oldprobe) { 780 // only need check_seen_thread once, not on each loop 781 // 6341374 java/lang/Instrument with -Xcomp 782 if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) { 783 throw_circularity_error = true; 784 } else { 785 // case 1: traditional: should never see load_in_progress. 786 while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) { 787 788 // case 4: bootstrap classloader: prevent futile classloading, 789 // wait on first requestor 790 if (class_loader.is_null()) { 791 SystemDictionary_lock->wait(); 792 } else { 793 // case 2: traditional with broken classloader lock. wait on first 794 // requestor. 795 double_lock_wait(lockObject, THREAD); 796 } 797 // Check if classloading completed while we were waiting 798 Klass* check = find_class(d_index, d_hash, name, loader_data); 799 if (check != NULL) { 800 // Klass is already loaded, so just return it 801 k = instanceKlassHandle(THREAD, check); 802 class_has_been_loaded = true; 803 } 804 // check if other thread failed to load and cleaned up 805 oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data); 806 } 807 } 808 } 809 } 810 // All cases: add LOAD_INSTANCE holding SystemDictionary_lock 811 // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try 812 // LOAD_INSTANCE in parallel 813 814 if (!throw_circularity_error && !class_has_been_loaded) { 815 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD); 816 load_instance_added = true; 817 // For class loaders that do not acquire the classloader object lock, 818 // if they did not catch another thread holding LOAD_INSTANCE, 819 // need a check analogous to the acquire ObjectLocker/find_class 820 // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL 821 // one final check if the load has already completed 822 // class loaders holding the ObjectLock shouldn't find the class here 823 Klass* check = find_class(d_index, d_hash, name, loader_data); 824 if (check != NULL) { 825 // Klass is already loaded, so return it after checking/adding protection domain 826 k = instanceKlassHandle(THREAD, check); 827 class_has_been_loaded = true; 828 } 829 } 830 } 831 832 // must throw error outside of owning lock 833 if (throw_circularity_error) { 834 assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup"); 835 ResourceMark rm(THREAD); 836 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string()); 837 } 838 839 if (!class_has_been_loaded) { 840 841 // Do actual loading 842 k = load_instance_class(name, class_loader, THREAD); 843 844 // For UnsyncloadClass only 845 // If they got a linkageError, check if a parallel class load succeeded. 846 // If it did, then for bytecode resolution the specification requires 847 // that we return the same result we did for the other thread, i.e. the 848 // successfully loaded InstanceKlass 849 // Should not get here for classloaders that support parallelism 850 // with the new cleaner mechanism, even with AllowParallelDefineClass 851 // Bootstrap goes through here to allow for an extra guarantee check 852 if (UnsyncloadClass || (class_loader.is_null())) { 853 if (k.is_null() && HAS_PENDING_EXCEPTION 854 && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) { 855 MutexLocker mu(SystemDictionary_lock, THREAD); 856 Klass* check = find_class(d_index, d_hash, name, loader_data); 857 if (check != NULL) { 858 // Klass is already loaded, so just use it 859 k = instanceKlassHandle(THREAD, check); 860 CLEAR_PENDING_EXCEPTION; 861 guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?"); 862 } 863 } 864 } 865 866 // If everything was OK (no exceptions, no null return value), and 867 // class_loader is NOT the defining loader, do a little more bookkeeping. 868 if (!HAS_PENDING_EXCEPTION && !k.is_null() && 869 k->class_loader() != class_loader()) { 870 871 check_constraints(d_index, d_hash, k, class_loader, false, THREAD); 872 873 // Need to check for a PENDING_EXCEPTION again; check_constraints 874 // can throw and doesn't use the CHECK macro. 875 if (!HAS_PENDING_EXCEPTION) { 876 { // Grabbing the Compile_lock prevents systemDictionary updates 877 // during compilations. 878 MutexLocker mu(Compile_lock, THREAD); 879 update_dictionary(d_index, d_hash, p_index, p_hash, 880 k, class_loader, THREAD); 881 } 882 883 if (JvmtiExport::should_post_class_load()) { 884 Thread *thread = THREAD; 885 assert(thread->is_Java_thread(), "thread->is_Java_thread()"); 886 JvmtiExport::post_class_load((JavaThread *) thread, k()); 887 } 888 } 889 } 890 } // load_instance_class loop 891 892 if (load_instance_added == true) { 893 // clean up placeholder entries for LOAD_INSTANCE success or error 894 // This brackets the SystemDictionary updates for both defining 895 // and initiating loaders 896 MutexLocker mu(SystemDictionary_lock, THREAD); 897 placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD); 898 SystemDictionary_lock->notify_all(); 899 } 900 } 901 902 if (HAS_PENDING_EXCEPTION || k.is_null()) { 903 return NULL; 904 } 905 906 post_class_load_event(class_load_start_time, k, loader_data); 907 908 #ifdef ASSERT 909 { 910 ClassLoaderData* loader_data = k->class_loader_data(); 911 MutexLocker mu(SystemDictionary_lock, THREAD); 912 Klass* kk = find_class(name, loader_data); 913 assert(kk == k(), "should be present in dictionary"); 914 } 915 #endif 916 917 // return if the protection domain in NULL 918 if (protection_domain() == NULL) return k(); 919 920 // Check the protection domain has the right access 921 { 922 MutexLocker mu(SystemDictionary_lock, THREAD); 923 // Note that we have an entry, and entries can be deleted only during GC, 924 // so we cannot allow GC to occur while we're holding this entry. 925 // We're using a NoSafepointVerifier to catch any place where we 926 // might potentially do a GC at all. 927 // Dictionary::do_unloading() asserts that classes in SD are only 928 // unloaded at a safepoint. Anonymous classes are not in SD. 929 NoSafepointVerifier nosafepoint; 930 if (dictionary()->is_valid_protection_domain(d_index, d_hash, name, 931 loader_data, 932 protection_domain)) { 933 return k(); 934 } 935 } 936 937 // Verify protection domain. If it fails an exception is thrown 938 validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL); 939 940 return k(); 941 } 942 943 944 // This routine does not lock the system dictionary. 945 // 946 // Since readers don't hold a lock, we must make sure that system 947 // dictionary entries are only removed at a safepoint (when only one 948 // thread is running), and are added to in a safe way (all links must 949 // be updated in an MT-safe manner). 950 // 951 // Callers should be aware that an entry could be added just after 952 // _dictionary->bucket(index) is read here, so the caller will not see 953 // the new entry. 954 955 Klass* SystemDictionary::find(Symbol* class_name, 956 Handle class_loader, 957 Handle protection_domain, 958 TRAPS) { 959 960 // The result of this call should be consistent with the result 961 // of the call to resolve_instance_class_or_null(). 962 // See evaluation 6790209 and 4474172 for more details. 963 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 964 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader()); 965 966 if (loader_data == NULL) { 967 // If the ClassLoaderData has not been setup, 968 // then the class loader has no entries in the dictionary. 969 return NULL; 970 } 971 972 unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data); 973 int d_index = dictionary()->hash_to_index(d_hash); 974 975 { 976 // Note that we have an entry, and entries can be deleted only during GC, 977 // so we cannot allow GC to occur while we're holding this entry. 978 // We're using a NoSafepointVerifier to catch any place where we 979 // might potentially do a GC at all. 980 // Dictionary::do_unloading() asserts that classes in SD are only 981 // unloaded at a safepoint. Anonymous classes are not in SD. 982 NoSafepointVerifier nosafepoint; 983 return dictionary()->find(d_index, d_hash, class_name, loader_data, 984 protection_domain, THREAD); 985 } 986 } 987 988 989 // Look for a loaded instance or array klass by name. Do not do any loading. 990 // return NULL in case of error. 991 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name, 992 Handle class_loader, 993 Handle protection_domain, 994 TRAPS) { 995 Klass* k = NULL; 996 assert(class_name != NULL, "class name must be non NULL"); 997 998 if (FieldType::is_array(class_name)) { 999 // The name refers to an array. Parse the name. 1000 // dimension and object_key in FieldArrayInfo are assigned as a 1001 // side-effect of this call 1002 FieldArrayInfo fd; 1003 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL)); 1004 if (t != T_OBJECT) { 1005 k = Universe::typeArrayKlassObj(t); 1006 } else { 1007 k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD); 1008 } 1009 if (k != NULL) { 1010 k = k->array_klass_or_null(fd.dimension()); 1011 } 1012 } else { 1013 k = find(class_name, class_loader, protection_domain, THREAD); 1014 } 1015 return k; 1016 } 1017 1018 // Note: this method is much like resolve_from_stream, but 1019 // does not publish the classes via the SystemDictionary. 1020 // Handles unsafe_DefineAnonymousClass and redefineclasses 1021 // RedefinedClasses do not add to the class hierarchy 1022 Klass* SystemDictionary::parse_stream(Symbol* class_name, 1023 Handle class_loader, 1024 Handle protection_domain, 1025 ClassFileStream* st, 1026 const InstanceKlass* host_klass, 1027 GrowableArray<Handle>* cp_patches, 1028 TRAPS) { 1029 1030 Ticks class_load_start_time = Ticks::now(); 1031 1032 ClassLoaderData* loader_data; 1033 if (host_klass != NULL) { 1034 // Create a new CLD for anonymous class, that uses the same class loader 1035 // as the host_klass 1036 guarantee(host_klass->class_loader() == class_loader(), "should be the same"); 1037 guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping"); 1038 loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL); 1039 loader_data->record_dependency(host_klass, CHECK_NULL); 1040 } else { 1041 loader_data = ClassLoaderData::class_loader_data(class_loader()); 1042 } 1043 1044 assert(st != NULL, "invariant"); 1045 assert(st->need_verify(), "invariant"); 1046 1047 // Parse stream and create a klass. 1048 // Note that we do this even though this klass might 1049 // already be present in the SystemDictionary, otherwise we would not 1050 // throw potential ClassFormatErrors. 1051 1052 instanceKlassHandle k = KlassFactory::create_from_stream(st, 1053 class_name, 1054 loader_data, 1055 protection_domain, 1056 host_klass, 1057 cp_patches, 1058 CHECK_NULL); 1059 1060 if (host_klass != NULL && k.not_null()) { 1061 // If it's anonymous, initialize it now, since nobody else will. 1062 1063 { 1064 MutexLocker mu_r(Compile_lock, THREAD); 1065 1066 // Add to class hierarchy, initialize vtables, and do possible 1067 // deoptimizations. 1068 add_to_hierarchy(k, CHECK_NULL); // No exception, but can block 1069 1070 // But, do not add to system dictionary. 1071 1072 // compiled code dependencies need to be validated anyway 1073 notice_modification(); 1074 } 1075 1076 // Rewrite and patch constant pool here. 1077 k->link_class(CHECK_NULL); 1078 if (cp_patches != NULL) { 1079 k->constants()->patch_resolved_references(cp_patches); 1080 } 1081 k->eager_initialize(CHECK_NULL); 1082 1083 // notify jvmti 1084 if (JvmtiExport::should_post_class_load()) { 1085 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()"); 1086 JvmtiExport::post_class_load((JavaThread *) THREAD, k()); 1087 } 1088 1089 post_class_load_event(class_load_start_time, k, loader_data); 1090 } 1091 assert(host_klass != NULL || NULL == cp_patches, 1092 "cp_patches only found with host_klass"); 1093 1094 return k(); 1095 } 1096 1097 // Add a klass to the system from a stream (called by jni_DefineClass and 1098 // JVM_DefineClass). 1099 // Note: class_name can be NULL. In that case we do not know the name of 1100 // the class until we have parsed the stream. 1101 1102 Klass* SystemDictionary::resolve_from_stream(Symbol* class_name, 1103 Handle class_loader, 1104 Handle protection_domain, 1105 ClassFileStream* st, 1106 TRAPS) { 1107 1108 HandleMark hm(THREAD); 1109 1110 // Classloaders that support parallelism, e.g. bootstrap classloader, 1111 // or all classloaders with UnsyncloadClass do not acquire lock here 1112 bool DoObjectLock = true; 1113 if (is_parallelCapable(class_loader)) { 1114 DoObjectLock = false; 1115 } 1116 1117 ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL); 1118 1119 // Make sure we are synchronized on the class loader before we proceed 1120 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 1121 check_loader_lock_contention(lockObject, THREAD); 1122 ObjectLocker ol(lockObject, THREAD, DoObjectLock); 1123 1124 assert(st != NULL, "invariant"); 1125 1126 // Parse the stream and create a klass. 1127 // Note that we do this even though this klass might 1128 // already be present in the SystemDictionary, otherwise we would not 1129 // throw potential ClassFormatErrors. 1130 // 1131 1132 instanceKlassHandle k; 1133 1134 #if INCLUDE_CDS 1135 k = SystemDictionaryShared::lookup_from_stream(class_name, 1136 class_loader, 1137 protection_domain, 1138 st, 1139 CHECK_NULL); 1140 #endif 1141 1142 if (k.is_null()) { 1143 if (st->buffer() == NULL) { 1144 return NULL; 1145 } 1146 k = KlassFactory::create_from_stream(st, 1147 class_name, 1148 loader_data, 1149 protection_domain, 1150 NULL, // host_klass 1151 NULL, // cp_patches 1152 CHECK_NULL); 1153 } 1154 1155 assert(k.not_null(), "no klass created"); 1156 Symbol* h_name = k->name(); 1157 assert(class_name == NULL || class_name == h_name, "name mismatch"); 1158 1159 bool define_succeeded = false; 1160 // Add class just loaded 1161 // If a class loader supports parallel classloading handle parallel define requests 1162 // find_or_define_instance_class may return a different InstanceKlass 1163 if (is_parallelCapable(class_loader)) { 1164 instanceKlassHandle defined_k = find_or_define_instance_class(h_name, class_loader, k, CHECK_NULL); 1165 if (k() == defined_k()) { 1166 // we have won over other concurrent threads (if any) that are 1167 // competing to define the same class. 1168 define_succeeded = true; 1169 } 1170 k = defined_k; 1171 } else { 1172 define_instance_class(k, CHECK_NULL); 1173 define_succeeded = true; 1174 } 1175 1176 // Make sure we have an entry in the SystemDictionary on success 1177 debug_only( { 1178 MutexLocker mu(SystemDictionary_lock, THREAD); 1179 1180 Klass* check = find_class(h_name, k->class_loader_data()); 1181 assert(check == k(), "should be present in the dictionary"); 1182 } ); 1183 1184 return k(); 1185 } 1186 1187 #if INCLUDE_CDS 1188 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length, 1189 int number_of_entries) { 1190 assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>), 1191 "bad shared dictionary size."); 1192 _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries); 1193 } 1194 1195 1196 // If there is a shared dictionary, then find the entry for the 1197 // given shared system class, if any. 1198 1199 Klass* SystemDictionary::find_shared_class(Symbol* class_name) { 1200 if (shared_dictionary() != NULL) { 1201 unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL); 1202 int d_index = shared_dictionary()->hash_to_index(d_hash); 1203 1204 return shared_dictionary()->find_shared_class(d_index, d_hash, class_name); 1205 } else { 1206 return NULL; 1207 } 1208 } 1209 1210 1211 // Load a class from the shared spaces (found through the shared system 1212 // dictionary). Force the superclass and all interfaces to be loaded. 1213 // Update the class definition to include sibling classes and no 1214 // subclasses (yet). [Classes in the shared space are not part of the 1215 // object hierarchy until loaded.] 1216 1217 instanceKlassHandle SystemDictionary::load_shared_class( 1218 Symbol* class_name, Handle class_loader, TRAPS) { 1219 instanceKlassHandle ik (THREAD, find_shared_class(class_name)); 1220 // Make sure we only return the boot class for the NULL classloader. 1221 if (ik.not_null() && 1222 ik->is_shared_boot_class() && class_loader.is_null()) { 1223 Handle protection_domain; 1224 return load_shared_class(ik, class_loader, protection_domain, THREAD); 1225 } 1226 return instanceKlassHandle(); 1227 } 1228 1229 // Check if a shared class can be loaded by the specific classloader: 1230 // 1231 // NULL classloader: 1232 // - Module class from "modules" jimage. ModuleEntry must be defined in the classloader. 1233 // - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must 1234 // be defined in an unnamed module. 1235 bool SystemDictionary::is_shared_class_visible(Symbol* class_name, 1236 instanceKlassHandle ik, 1237 Handle class_loader, TRAPS) { 1238 assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(), 1239 "Cannot use sharing if java.base is patched"); 1240 ResourceMark rm; 1241 int path_index = ik->shared_classpath_index(); 1242 SharedClassPathEntry* ent = 1243 (SharedClassPathEntry*)FileMapInfo::shared_classpath(path_index); 1244 if (!Universe::is_module_initialized()) { 1245 assert(ent != NULL && ent->is_jrt(), 1246 "Loading non-bootstrap classes before the module system is initialized"); 1247 assert(class_loader.is_null(), "sanity"); 1248 return true; 1249 } 1250 // Get the pkg_entry from the classloader 1251 TempNewSymbol pkg_name = NULL; 1252 PackageEntry* pkg_entry = NULL; 1253 ModuleEntry* mod_entry = NULL; 1254 const char* pkg_string = NULL; 1255 ClassLoaderData* loader_data = class_loader_data(class_loader); 1256 pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false); 1257 if (pkg_name != NULL) { 1258 pkg_string = pkg_name->as_C_string(); 1259 if (loader_data != NULL) { 1260 pkg_entry = loader_data->packages()->lookup_only(pkg_name); 1261 } 1262 if (pkg_entry != NULL) { 1263 mod_entry = pkg_entry->module(); 1264 } 1265 } 1266 1267 // If the archived class is from a module that has been patched at runtime, 1268 // the class cannot be loaded from the archive. 1269 if (mod_entry != NULL && mod_entry->is_patched()) { 1270 return false; 1271 } 1272 1273 if (class_loader.is_null()) { 1274 assert(ent != NULL, "Shared class for NULL classloader must have valid SharedClassPathEntry"); 1275 // The NULL classloader can load archived class originated from the 1276 // "modules" jimage and the -Xbootclasspath/a. For class from the 1277 // "modules" jimage, the PackageEntry/ModuleEntry must be defined 1278 // by the NULL classloader. 1279 if (mod_entry != NULL) { 1280 // PackageEntry/ModuleEntry is found in the classloader. Check if the 1281 // ModuleEntry's location agrees with the archived class' origination. 1282 if (ent->is_jrt() && mod_entry->location()->starts_with("jrt:")) { 1283 return true; // Module class from the "module" jimage 1284 } 1285 } 1286 1287 // If the archived class is not from the "module" jimage, the class can be 1288 // loaded by the NULL classloader if 1289 // 1290 // 1. the class is from the unamed package 1291 // 2. or, the class is not from a module defined in the NULL classloader 1292 // 3. or, the class is from an unamed module 1293 if (!ent->is_jrt() && ik->is_shared_boot_class()) { 1294 // the class is from the -Xbootclasspath/a 1295 if (pkg_string == NULL || 1296 pkg_entry == NULL || 1297 pkg_entry->in_unnamed_module()) { 1298 assert(mod_entry == NULL || 1299 mod_entry == loader_data->modules()->unnamed_module(), 1300 "the unnamed module is not defined in the classloader"); 1301 return true; 1302 } 1303 } 1304 return false; 1305 } else { 1306 bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader( 1307 ik, class_loader, pkg_string, pkg_name, 1308 pkg_entry, mod_entry, CHECK_(false)); 1309 return res; 1310 } 1311 } 1312 1313 instanceKlassHandle SystemDictionary::load_shared_class(instanceKlassHandle ik, 1314 Handle class_loader, 1315 Handle protection_domain, TRAPS) { 1316 instanceKlassHandle nh = instanceKlassHandle(); // null Handle 1317 1318 if (ik.not_null()) { 1319 Symbol* class_name = ik->name(); 1320 1321 bool visible = is_shared_class_visible( 1322 class_name, ik, class_loader, CHECK_(nh)); 1323 if (!visible) { 1324 return nh; 1325 } 1326 1327 // Resolve the superclass and interfaces. They must be the same 1328 // as in dump time, because the layout of <ik> depends on 1329 // the specific layout of ik->super() and ik->local_interfaces(). 1330 // 1331 // If unexpected superclass or interfaces are found, we cannot 1332 // load <ik> from the shared archive. 1333 1334 if (ik->super() != NULL) { 1335 Symbol* cn = ik->super()->name(); 1336 Klass *s = resolve_super_or_fail(class_name, cn, 1337 class_loader, protection_domain, true, CHECK_(nh)); 1338 if (s != ik->super()) { 1339 // The dynamically resolved super class is not the same as the one we used during dump time, 1340 // so we cannot use ik. 1341 return nh; 1342 } else { 1343 assert(s->is_shared(), "must be"); 1344 } 1345 } 1346 1347 Array<Klass*>* interfaces = ik->local_interfaces(); 1348 int num_interfaces = interfaces->length(); 1349 for (int index = 0; index < num_interfaces; index++) { 1350 Klass* k = interfaces->at(index); 1351 1352 // Note: can not use InstanceKlass::cast here because 1353 // interfaces' InstanceKlass's C++ vtbls haven't been 1354 // reinitialized yet (they will be once the interface classes 1355 // are loaded) 1356 Symbol* name = k->name(); 1357 Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_(nh)); 1358 if (k != i) { 1359 // The dynamically resolved interface class is not the same as the one we used during dump time, 1360 // so we cannot use ik. 1361 return nh; 1362 } else { 1363 assert(i->is_shared(), "must be"); 1364 } 1365 } 1366 1367 instanceKlassHandle new_ik = KlassFactory::check_shared_class_file_load_hook( 1368 ik, class_name, class_loader, protection_domain, CHECK_(nh)); 1369 if (new_ik.not_null()) { 1370 // The class is changed by CFLH. Return the new class. The shared class is 1371 // not used. 1372 return new_ik; 1373 } 1374 1375 // Adjust methods to recover missing data. They need addresses for 1376 // interpreter entry points and their default native method address 1377 // must be reset. 1378 1379 // Updating methods must be done under a lock so multiple 1380 // threads don't update these in parallel 1381 // 1382 // Shared classes are all currently loaded by either the bootstrap or 1383 // internal parallel class loaders, so this will never cause a deadlock 1384 // on a custom class loader lock. 1385 1386 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 1387 { 1388 HandleMark hm(THREAD); 1389 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 1390 check_loader_lock_contention(lockObject, THREAD); 1391 ObjectLocker ol(lockObject, THREAD, true); 1392 // prohibited package check assumes all classes loaded from archive call 1393 // restore_unshareable_info which calls ik->set_package() 1394 ik->restore_unshareable_info(loader_data, protection_domain, CHECK_(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, CHECK_(nh)); 1527 k = defined_k; 1528 } 1529 return k; 1530 } else { 1531 // Use user specified class loader to load class. Call loadClass operation on class_loader. 1532 ResourceMark rm(THREAD); 1533 1534 assert(THREAD->is_Java_thread(), "must be a JavaThread"); 1535 JavaThread* jt = (JavaThread*) THREAD; 1536 1537 PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(), 1538 ClassLoader::perf_app_classload_selftime(), 1539 ClassLoader::perf_app_classload_count(), 1540 jt->get_thread_stat()->perf_recursion_counts_addr(), 1541 jt->get_thread_stat()->perf_timers_addr(), 1542 PerfClassTraceTime::CLASS_LOAD); 1543 1544 Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh)); 1545 // Translate to external class name format, i.e., convert '/' chars to '.' 1546 Handle string = java_lang_String::externalize_classname(s, CHECK_(nh)); 1547 1548 JavaValue result(T_OBJECT); 1549 1550 KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass()); 1551 1552 // Call public unsynchronized loadClass(String) directly for all class loaders 1553 // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will 1554 // acquire a class-name based lock rather than the class loader object lock. 1555 // JDK < 7 already acquire the class loader lock in loadClass(String, boolean), 1556 // so the call to loadClassInternal() was not required. 1557 // 1558 // UnsyncloadClass flag means both call loadClass(String) and do 1559 // not acquire the class loader lock even for class loaders that are 1560 // not parallelCapable. This was a risky transitional 1561 // flag for diagnostic purposes only. It is risky to call 1562 // custom class loaders without synchronization. 1563 // WARNING If a custom class loader does NOT synchronizer findClass, or callers of 1564 // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field. 1565 // Do NOT assume this will be supported in future releases. 1566 // 1567 // Added MustCallLoadClassInternal in case we discover in the field 1568 // a customer that counts on this call 1569 if (MustCallLoadClassInternal && has_loadClassInternal()) { 1570 JavaCalls::call_special(&result, 1571 class_loader, 1572 spec_klass, 1573 vmSymbols::loadClassInternal_name(), 1574 vmSymbols::string_class_signature(), 1575 string, 1576 CHECK_(nh)); 1577 } else { 1578 JavaCalls::call_virtual(&result, 1579 class_loader, 1580 spec_klass, 1581 vmSymbols::loadClass_name(), 1582 vmSymbols::string_class_signature(), 1583 string, 1584 CHECK_(nh)); 1585 } 1586 1587 assert(result.get_type() == T_OBJECT, "just checking"); 1588 oop obj = (oop) result.get_jobject(); 1589 1590 // Primitive classes return null since forName() can not be 1591 // used to obtain any of the Class objects representing primitives or void 1592 if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) { 1593 instanceKlassHandle k = 1594 instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj)); 1595 // For user defined Java class loaders, check that the name returned is 1596 // the same as that requested. This check is done for the bootstrap 1597 // loader when parsing the class file. 1598 if (class_name == k->name()) { 1599 return k; 1600 } 1601 } 1602 // Class is not found or has the wrong name, return NULL 1603 return nh; 1604 } 1605 } 1606 1607 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) { 1608 1609 HandleMark hm(THREAD); 1610 ClassLoaderData* loader_data = k->class_loader_data(); 1611 Handle class_loader_h(THREAD, loader_data->class_loader()); 1612 1613 // for bootstrap and other parallel classloaders don't acquire lock, 1614 // use placeholder token 1615 // If a parallelCapable class loader calls define_instance_class instead of 1616 // find_or_define_instance_class to get here, we have a timing 1617 // hole with systemDictionary updates and check_constraints 1618 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) { 1619 assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, 1620 compute_loader_lock_object(class_loader_h, THREAD)), 1621 "define called without lock"); 1622 } 1623 1624 // Check class-loading constraints. Throw exception if violation is detected. 1625 // Grabs and releases SystemDictionary_lock 1626 // The check_constraints/find_class call and update_dictionary sequence 1627 // must be "atomic" for a specific class/classloader pair so we never 1628 // define two different instanceKlasses for that class/classloader pair. 1629 // Existing classloaders will call define_instance_class with the 1630 // classloader lock held 1631 // Parallel classloaders will call find_or_define_instance_class 1632 // which will require a token to perform the define class 1633 Symbol* name_h = k->name(); 1634 unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data); 1635 int d_index = dictionary()->hash_to_index(d_hash); 1636 check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK); 1637 1638 // Register class just loaded with class loader (placed in Vector) 1639 // Note we do this before updating the dictionary, as this can 1640 // fail with an OutOfMemoryError (if it does, we will *not* put this 1641 // class in the dictionary and will not update the class hierarchy). 1642 // JVMTI FollowReferences needs to find the classes this way. 1643 if (k->class_loader() != NULL) { 1644 methodHandle m(THREAD, Universe::loader_addClass_method()); 1645 JavaValue result(T_VOID); 1646 JavaCallArguments args(class_loader_h); 1647 args.push_oop(Handle(THREAD, k->java_mirror())); 1648 JavaCalls::call(&result, m, &args, CHECK); 1649 } 1650 1651 // Add the new class. We need recompile lock during update of CHA. 1652 { 1653 unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data); 1654 int p_index = placeholders()->hash_to_index(p_hash); 1655 1656 MutexLocker mu_r(Compile_lock, THREAD); 1657 1658 // Add to class hierarchy, initialize vtables, and do possible 1659 // deoptimizations. 1660 add_to_hierarchy(k, CHECK); // No exception, but can block 1661 1662 // Add to systemDictionary - so other classes can see it. 1663 // Grabs and releases SystemDictionary_lock 1664 update_dictionary(d_index, d_hash, p_index, p_hash, 1665 k, class_loader_h, THREAD); 1666 } 1667 k->eager_initialize(THREAD); 1668 1669 // notify jvmti 1670 if (JvmtiExport::should_post_class_load()) { 1671 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()"); 1672 JvmtiExport::post_class_load((JavaThread *) THREAD, k()); 1673 1674 } 1675 class_define_event(k, loader_data); 1676 } 1677 1678 // Support parallel classloading 1679 // All parallel class loaders, including bootstrap classloader 1680 // lock a placeholder entry for this class/class_loader pair 1681 // to allow parallel defines of different classes for this class loader 1682 // With AllowParallelDefine flag==true, in case they do not synchronize around 1683 // FindLoadedClass/DefineClass, calls, we check for parallel 1684 // loading for them, wait if a defineClass is in progress 1685 // and return the initial requestor's results 1686 // This flag does not apply to the bootstrap classloader. 1687 // With AllowParallelDefine flag==false, call through to define_instance_class 1688 // which will throw LinkageError: duplicate class definition. 1689 // False is the requested default. 1690 // For better performance, the class loaders should synchronize 1691 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they 1692 // potentially waste time reading and parsing the bytestream. 1693 // Note: VM callers should ensure consistency of k/class_name,class_loader 1694 // Be careful when modifying this code: once you have run 1695 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS), 1696 // you need to find_and_remove it before returning. 1697 // So be careful to not exit with a CHECK_ macro betweeen these calls. 1698 instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) { 1699 1700 instanceKlassHandle nh = instanceKlassHandle(); // null Handle 1701 Symbol* name_h = k->name(); // passed in class_name may be null 1702 ClassLoaderData* loader_data = class_loader_data(class_loader); 1703 1704 unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data); 1705 int d_index = dictionary()->hash_to_index(d_hash); 1706 1707 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS 1708 unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data); 1709 int p_index = placeholders()->hash_to_index(p_hash); 1710 PlaceholderEntry* probe; 1711 1712 { 1713 MutexLocker mu(SystemDictionary_lock, THREAD); 1714 // First check if class already defined 1715 if (UnsyncloadClass || (is_parallelDefine(class_loader))) { 1716 Klass* check = find_class(d_index, d_hash, name_h, loader_data); 1717 if (check != NULL) { 1718 return(instanceKlassHandle(THREAD, check)); 1719 } 1720 } 1721 1722 // Acquire define token for this class/classloader 1723 probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD); 1724 // Wait if another thread defining in parallel 1725 // All threads wait - even those that will throw duplicate class: otherwise 1726 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails 1727 // if other thread has not finished updating dictionary 1728 while (probe->definer() != NULL) { 1729 SystemDictionary_lock->wait(); 1730 } 1731 // Only special cases allow parallel defines and can use other thread's results 1732 // Other cases fall through, and may run into duplicate defines 1733 // caught by finding an entry in the SystemDictionary 1734 if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) { 1735 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1736 SystemDictionary_lock->notify_all(); 1737 #ifdef ASSERT 1738 Klass* check = find_class(d_index, d_hash, name_h, loader_data); 1739 assert(check != NULL, "definer missed recording success"); 1740 #endif 1741 return(instanceKlassHandle(THREAD, probe->instance_klass())); 1742 } else { 1743 // This thread will define the class (even if earlier thread tried and had an error) 1744 probe->set_definer(THREAD); 1745 } 1746 } 1747 1748 define_instance_class(k, THREAD); 1749 1750 Handle linkage_exception = Handle(); // null handle 1751 1752 // definer must notify any waiting threads 1753 { 1754 MutexLocker mu(SystemDictionary_lock, THREAD); 1755 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data); 1756 assert(probe != NULL, "DEFINE_CLASS placeholder lost?"); 1757 if (probe != NULL) { 1758 if (HAS_PENDING_EXCEPTION) { 1759 linkage_exception = Handle(THREAD,PENDING_EXCEPTION); 1760 CLEAR_PENDING_EXCEPTION; 1761 } else { 1762 probe->set_instance_klass(k()); 1763 } 1764 probe->set_definer(NULL); 1765 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1766 SystemDictionary_lock->notify_all(); 1767 } 1768 } 1769 1770 // Can't throw exception while holding lock due to rank ordering 1771 if (linkage_exception() != NULL) { 1772 THROW_OOP_(linkage_exception(), nh); // throws exception and returns 1773 } 1774 1775 return k; 1776 } 1777 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) { 1778 // If class_loader is NULL we synchronize on _system_loader_lock_obj 1779 if (class_loader.is_null()) { 1780 return Handle(THREAD, _system_loader_lock_obj); 1781 } else { 1782 return class_loader; 1783 } 1784 } 1785 1786 // This method is added to check how often we have to wait to grab loader 1787 // lock. The results are being recorded in the performance counters defined in 1788 // ClassLoader::_sync_systemLoaderLockContentionRate and 1789 // ClassLoader::_sync_nonSystemLoaderLockConteionRate. 1790 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) { 1791 if (!UsePerfData) { 1792 return; 1793 } 1794 1795 assert(!loader_lock.is_null(), "NULL lock object"); 1796 1797 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock) 1798 == ObjectSynchronizer::owner_other) { 1799 // contention will likely happen, so increment the corresponding 1800 // contention counter. 1801 if (loader_lock() == _system_loader_lock_obj) { 1802 ClassLoader::sync_systemLoaderLockContentionRate()->inc(); 1803 } else { 1804 ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc(); 1805 } 1806 } 1807 } 1808 1809 // ---------------------------------------------------------------------------- 1810 // Lookup 1811 1812 Klass* SystemDictionary::find_class(int index, unsigned int hash, 1813 Symbol* class_name, 1814 ClassLoaderData* loader_data) { 1815 assert_locked_or_safepoint(SystemDictionary_lock); 1816 assert (index == dictionary()->index_for(class_name, loader_data), 1817 "incorrect index?"); 1818 1819 Klass* k = dictionary()->find_class(index, hash, class_name, loader_data); 1820 return k; 1821 } 1822 1823 1824 // Basic find on classes in the midst of being loaded 1825 Symbol* SystemDictionary::find_placeholder(Symbol* class_name, 1826 ClassLoaderData* loader_data) { 1827 assert_locked_or_safepoint(SystemDictionary_lock); 1828 unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data); 1829 int p_index = placeholders()->hash_to_index(p_hash); 1830 return placeholders()->find_entry(p_index, p_hash, class_name, loader_data); 1831 } 1832 1833 1834 // Used for assertions and verification only 1835 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) { 1836 #ifndef ASSERT 1837 guarantee(VerifyBeforeGC || 1838 VerifyDuringGC || 1839 VerifyBeforeExit || 1840 VerifyDuringStartup || 1841 VerifyAfterGC, "too expensive"); 1842 #endif 1843 assert_locked_or_safepoint(SystemDictionary_lock); 1844 1845 // First look in the loaded class array 1846 unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data); 1847 int d_index = dictionary()->hash_to_index(d_hash); 1848 return find_class(d_index, d_hash, class_name, loader_data); 1849 } 1850 1851 1852 // Get the next class in the dictionary. 1853 Klass* SystemDictionary::try_get_next_class() { 1854 return dictionary()->try_get_next_class(); 1855 } 1856 1857 1858 // ---------------------------------------------------------------------------- 1859 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock 1860 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in 1861 // before a new class is used. 1862 1863 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) { 1864 assert(k.not_null(), "just checking"); 1865 assert_locked_or_safepoint(Compile_lock); 1866 1867 // Link into hierachy. Make sure the vtables are initialized before linking into 1868 k->append_to_sibling_list(); // add to superklass/sibling list 1869 k->process_interfaces(THREAD); // handle all "implements" declarations 1870 k->set_init_state(InstanceKlass::loaded); 1871 // Now flush all code that depended on old class hierarchy. 1872 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97) 1873 // Also, first reinitialize vtable because it may have gotten out of synch 1874 // while the new class wasn't connected to the class hierarchy. 1875 CodeCache::flush_dependents_on(k); 1876 } 1877 1878 // ---------------------------------------------------------------------------- 1879 // GC support 1880 1881 // Following roots during mark-sweep is separated in two phases. 1882 // 1883 // The first phase follows preloaded classes and all other system 1884 // classes, since these will never get unloaded anyway. 1885 // 1886 // The second phase removes (unloads) unreachable classes from the 1887 // system dictionary and follows the remaining classes' contents. 1888 1889 void SystemDictionary::always_strong_oops_do(OopClosure* blk) { 1890 roots_oops_do(blk, NULL); 1891 } 1892 1893 void SystemDictionary::always_strong_classes_do(KlassClosure* closure) { 1894 // Follow all system classes and temporary placeholders in dictionary 1895 dictionary()->always_strong_classes_do(closure); 1896 1897 // Placeholders. These represent classes we're actively loading. 1898 placeholders()->classes_do(closure); 1899 } 1900 1901 // Calculate a "good" systemdictionary size based 1902 // on predicted or current loaded classes count 1903 int SystemDictionary::calculate_systemdictionary_size(int classcount) { 1904 int newsize = _old_default_sdsize; 1905 if ((classcount > 0) && !DumpSharedSpaces) { 1906 int desiredsize = classcount/_average_depth_goal; 1907 for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1; 1908 newsize = _primelist[++_sdgeneration]) { 1909 if (desiredsize <= newsize) { 1910 break; 1911 } 1912 } 1913 } 1914 return newsize; 1915 } 1916 1917 #ifdef ASSERT 1918 class VerifySDReachableAndLiveClosure : public OopClosure { 1919 private: 1920 BoolObjectClosure* _is_alive; 1921 1922 template <class T> void do_oop_work(T* p) { 1923 oop obj = oopDesc::load_decode_heap_oop(p); 1924 guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live"); 1925 } 1926 1927 public: 1928 VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { } 1929 1930 virtual void do_oop(oop* p) { do_oop_work(p); } 1931 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 1932 }; 1933 #endif 1934 1935 // Assumes classes in the SystemDictionary are only unloaded at a safepoint 1936 // Note: anonymous classes are not in the SD. 1937 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive, 1938 bool clean_previous_versions) { 1939 // First, mark for unload all ClassLoaderData referencing a dead class loader. 1940 bool unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive, 1941 clean_previous_versions); 1942 if (unloading_occurred) { 1943 dictionary()->do_unloading(); 1944 constraints()->purge_loader_constraints(); 1945 resolution_errors()->purge_resolution_errors(); 1946 } 1947 // Oops referenced by the system dictionary may get unreachable independently 1948 // of the class loader (eg. cached protection domain oops). So we need to 1949 // explicitly unlink them here instead of in Dictionary::do_unloading. 1950 dictionary()->unlink(is_alive); 1951 #ifdef ASSERT 1952 VerifySDReachableAndLiveClosure cl(is_alive); 1953 dictionary()->oops_do(&cl); 1954 #endif 1955 return unloading_occurred; 1956 } 1957 1958 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) { 1959 strong->do_oop(&_java_system_loader); 1960 strong->do_oop(&_system_loader_lock_obj); 1961 CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);) 1962 1963 // Adjust dictionary 1964 dictionary()->roots_oops_do(strong, weak); 1965 1966 // Visit extra methods 1967 invoke_method_table()->oops_do(strong); 1968 } 1969 1970 void SystemDictionary::oops_do(OopClosure* f) { 1971 f->do_oop(&_java_system_loader); 1972 f->do_oop(&_system_loader_lock_obj); 1973 CDS_ONLY(SystemDictionaryShared::oops_do(f);) 1974 1975 // Adjust dictionary 1976 dictionary()->oops_do(f); 1977 1978 // Visit extra methods 1979 invoke_method_table()->oops_do(f); 1980 } 1981 1982 // Extended Class redefinition support. 1983 // If one of these classes is replaced, we need to replace it in these places. 1984 // KlassClosure::do_klass should take the address of a class but we can 1985 // change that later. 1986 void SystemDictionary::preloaded_classes_do(KlassClosure* f) { 1987 for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) { 1988 f->do_klass(_well_known_klasses[k]); 1989 } 1990 1991 { 1992 for (int i = 0; i < T_VOID+1; i++) { 1993 if (_box_klasses[i] != NULL) { 1994 assert(i >= T_BOOLEAN, "checking"); 1995 f->do_klass(_box_klasses[i]); 1996 } 1997 } 1998 } 1999 2000 FilteredFieldsMap::classes_do(f); 2001 } 2002 2003 void SystemDictionary::lazily_loaded_classes_do(KlassClosure* f) { 2004 f->do_klass(_abstract_ownable_synchronizer_klass); 2005 } 2006 2007 // Just the classes from defining class loaders 2008 // Don't iterate over placeholders 2009 void SystemDictionary::classes_do(void f(Klass*)) { 2010 dictionary()->classes_do(f); 2011 } 2012 2013 // Added for initialize_itable_for_klass 2014 // Just the classes from defining class loaders 2015 // Don't iterate over placeholders 2016 void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) { 2017 dictionary()->classes_do(f, CHECK); 2018 } 2019 2020 // All classes, and their class loaders 2021 // Don't iterate over placeholders 2022 void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) { 2023 dictionary()->classes_do(f); 2024 } 2025 2026 void SystemDictionary::placeholders_do(void f(Symbol*)) { 2027 placeholders()->entries_do(f); 2028 } 2029 2030 void SystemDictionary::methods_do(void f(Method*)) { 2031 dictionary()->methods_do(f); 2032 invoke_method_table()->methods_do(f); 2033 } 2034 2035 void SystemDictionary::remove_classes_in_error_state() { 2036 dictionary()->remove_classes_in_error_state(); 2037 } 2038 2039 // ---------------------------------------------------------------------------- 2040 // Lazily load klasses 2041 2042 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) { 2043 // if multiple threads calling this function, only one thread will load 2044 // the class. The other threads will find the loaded version once the 2045 // class is loaded. 2046 Klass* aos = _abstract_ownable_synchronizer_klass; 2047 if (aos == NULL) { 2048 Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK); 2049 // Force a fence to prevent any read before the write completes 2050 OrderAccess::fence(); 2051 _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k); 2052 } 2053 } 2054 2055 // ---------------------------------------------------------------------------- 2056 // Initialization 2057 2058 void SystemDictionary::initialize(TRAPS) { 2059 // Allocate arrays 2060 assert(dictionary() == NULL, 2061 "SystemDictionary should only be initialized once"); 2062 _sdgeneration = 0; 2063 _dictionary = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount)); 2064 _placeholders = new PlaceholderTable(_nof_buckets); 2065 _number_of_modifications = 0; 2066 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size); 2067 _resolution_errors = new ResolutionErrorTable(_resolution_error_size); 2068 _invoke_method_table = new SymbolPropertyTable(_invoke_method_size); 2069 2070 // Allocate private object used as system class loader lock 2071 _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK); 2072 // Initialize basic classes 2073 initialize_preloaded_classes(CHECK); 2074 } 2075 2076 // Compact table of directions on the initialization of klasses: 2077 static const short wk_init_info[] = { 2078 #define WK_KLASS_INIT_INFO(name, symbol, option) \ 2079 ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \ 2080 << SystemDictionary::CEIL_LG_OPTION_LIMIT) \ 2081 | (int)SystemDictionary::option ), 2082 WK_KLASSES_DO(WK_KLASS_INIT_INFO) 2083 #undef WK_KLASS_INIT_INFO 2084 0 2085 }; 2086 2087 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) { 2088 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob"); 2089 int info = wk_init_info[id - FIRST_WKID]; 2090 int sid = (info >> CEIL_LG_OPTION_LIMIT); 2091 Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid); 2092 InstanceKlass** klassp = &_well_known_klasses[id]; 2093 2094 bool must_load; 2095 #if INCLUDE_JVMCI 2096 if (EnableJVMCI) { 2097 // If JVMCI is enabled we require its classes to be found. 2098 must_load = (init_opt < SystemDictionary::Opt) || (init_opt == SystemDictionary::Jvmci); 2099 } else 2100 #endif 2101 { 2102 must_load = (init_opt < SystemDictionary::Opt); 2103 } 2104 2105 if ((*klassp) == NULL) { 2106 Klass* k; 2107 if (must_load) { 2108 k = resolve_or_fail(symbol, true, CHECK_0); // load required class 2109 } else { 2110 k = resolve_or_null(symbol, CHECK_0); // load optional klass 2111 } 2112 (*klassp) = (k == NULL) ? NULL : InstanceKlass::cast(k); 2113 } 2114 return ((*klassp) != NULL); 2115 } 2116 2117 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) { 2118 assert((int)start_id <= (int)limit_id, "IDs are out of order!"); 2119 for (int id = (int)start_id; id < (int)limit_id; id++) { 2120 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob"); 2121 int info = wk_init_info[id - FIRST_WKID]; 2122 int sid = (info >> CEIL_LG_OPTION_LIMIT); 2123 int opt = (info & right_n_bits(CEIL_LG_OPTION_LIMIT)); 2124 2125 initialize_wk_klass((WKID)id, opt, CHECK); 2126 } 2127 2128 // move the starting value forward to the limit: 2129 start_id = limit_id; 2130 } 2131 2132 void SystemDictionary::initialize_preloaded_classes(TRAPS) { 2133 assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once"); 2134 2135 // Create the ModuleEntry for java.base. This call needs to be done here, 2136 // after vmSymbols::initialize() is called but before any classes are pre-loaded. 2137 ClassLoader::classLoader_init2(CHECK); 2138 2139 // Preload commonly used klasses 2140 WKID scan = FIRST_WKID; 2141 // first do Object, then String, Class 2142 if (UseSharedSpaces) { 2143 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK); 2144 // Initialize the constant pool for the Object_class 2145 InstanceKlass* ik = InstanceKlass::cast(Object_klass()); 2146 ik->constants()->restore_unshareable_info(CHECK); 2147 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK); 2148 } else { 2149 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK); 2150 } 2151 2152 // Calculate offsets for String and Class classes since they are loaded and 2153 // can be used after this point. 2154 java_lang_String::compute_offsets(); 2155 java_lang_Class::compute_offsets(); 2156 2157 // Fixup mirrors for classes loaded before java.lang.Class. 2158 // These calls iterate over the objects currently in the perm gen 2159 // so calling them at this point is matters (not before when there 2160 // are fewer objects and not later after there are more objects 2161 // in the perm gen. 2162 Universe::initialize_basic_type_mirrors(CHECK); 2163 Universe::fixup_mirrors(CHECK); 2164 2165 // do a bunch more: 2166 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK); 2167 2168 // Preload ref klasses and set reference types 2169 InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER); 2170 InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass)); 2171 2172 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK); 2173 InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT); 2174 InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK); 2175 InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL); 2176 InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM); 2177 2178 // JSR 292 classes 2179 WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass); 2180 WKID jsr292_group_end = WK_KLASS_ENUM_NAME(VolatileCallSite_klass); 2181 initialize_wk_klasses_until(jsr292_group_start, scan, CHECK); 2182 initialize_wk_klasses_through(jsr292_group_end, scan, CHECK); 2183 initialize_wk_klasses_until(NOT_JVMCI(WKID_LIMIT) JVMCI_ONLY(FIRST_JVMCI_WKID), scan, CHECK); 2184 2185 _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass); 2186 _box_klasses[T_CHAR] = WK_KLASS(Character_klass); 2187 _box_klasses[T_FLOAT] = WK_KLASS(Float_klass); 2188 _box_klasses[T_DOUBLE] = WK_KLASS(Double_klass); 2189 _box_klasses[T_BYTE] = WK_KLASS(Byte_klass); 2190 _box_klasses[T_SHORT] = WK_KLASS(Short_klass); 2191 _box_klasses[T_INT] = WK_KLASS(Integer_klass); 2192 _box_klasses[T_LONG] = WK_KLASS(Long_klass); 2193 //_box_klasses[T_OBJECT] = WK_KLASS(object_klass); 2194 //_box_klasses[T_ARRAY] = WK_KLASS(object_klass); 2195 2196 { // Compute whether we should use loadClass or loadClassInternal when loading classes. 2197 Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature()); 2198 _has_loadClassInternal = (method != NULL); 2199 } 2200 { // Compute whether we should use checkPackageAccess or NOT 2201 Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature()); 2202 _has_checkPackageAccess = (method != NULL); 2203 } 2204 } 2205 2206 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer). 2207 // If so, returns the basic type it holds. If not, returns T_OBJECT. 2208 BasicType SystemDictionary::box_klass_type(Klass* k) { 2209 assert(k != NULL, ""); 2210 for (int i = T_BOOLEAN; i < T_VOID+1; i++) { 2211 if (_box_klasses[i] == k) 2212 return (BasicType)i; 2213 } 2214 return T_OBJECT; 2215 } 2216 2217 // Constraints on class loaders. The details of the algorithm can be 2218 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java 2219 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is 2220 // that the system dictionary needs to maintain a set of contraints that 2221 // must be satisfied by all classes in the dictionary. 2222 // if defining is true, then LinkageError if already in systemDictionary 2223 // if initiating loader, then ok if InstanceKlass matches existing entry 2224 2225 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash, 2226 instanceKlassHandle k, 2227 Handle class_loader, bool defining, 2228 TRAPS) { 2229 const char *linkage_error1 = NULL; 2230 const char *linkage_error2 = NULL; 2231 { 2232 Symbol* name = k->name(); 2233 ClassLoaderData *loader_data = class_loader_data(class_loader); 2234 2235 MutexLocker mu(SystemDictionary_lock, THREAD); 2236 2237 Klass* check = find_class(d_index, d_hash, name, loader_data); 2238 if (check != (Klass*)NULL) { 2239 // if different InstanceKlass - duplicate class definition, 2240 // else - ok, class loaded by a different thread in parallel, 2241 // we should only have found it if it was done loading and ok to use 2242 // system dictionary only holds instance classes, placeholders 2243 // also holds array classes 2244 2245 assert(check->is_instance_klass(), "noninstance in systemdictionary"); 2246 if ((defining == true) || (k() != check)) { 2247 linkage_error1 = "loader (instance of "; 2248 linkage_error2 = "): attempted duplicate class definition for name: \""; 2249 } else { 2250 return; 2251 } 2252 } 2253 2254 #ifdef ASSERT 2255 Symbol* ph_check = find_placeholder(name, loader_data); 2256 assert(ph_check == NULL || ph_check == name, "invalid symbol"); 2257 #endif 2258 2259 if (linkage_error1 == NULL) { 2260 if (constraints()->check_or_update(k, class_loader, name) == false) { 2261 linkage_error1 = "loader constraint violation: loader (instance of "; 2262 linkage_error2 = ") previously initiated loading for a different type with name \""; 2263 } 2264 } 2265 } 2266 2267 // Throw error now if needed (cannot throw while holding 2268 // SystemDictionary_lock because of rank ordering) 2269 2270 if (linkage_error1) { 2271 ResourceMark rm(THREAD); 2272 const char* class_loader_name = loader_name(class_loader()); 2273 char* type_name = k->name()->as_C_string(); 2274 size_t buflen = strlen(linkage_error1) + strlen(class_loader_name) + 2275 strlen(linkage_error2) + strlen(type_name) + 2; // +2 for '"' and null byte. 2276 char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen); 2277 jio_snprintf(buf, buflen, "%s%s%s%s\"", linkage_error1, class_loader_name, linkage_error2, type_name); 2278 THROW_MSG(vmSymbols::java_lang_LinkageError(), buf); 2279 } 2280 } 2281 2282 2283 // Update system dictionary - done after check_constraint and add_to_hierachy 2284 // have been called. 2285 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash, 2286 int p_index, unsigned int p_hash, 2287 instanceKlassHandle k, 2288 Handle class_loader, 2289 TRAPS) { 2290 // Compile_lock prevents systemDictionary updates during compilations 2291 assert_locked_or_safepoint(Compile_lock); 2292 Symbol* name = k->name(); 2293 ClassLoaderData *loader_data = class_loader_data(class_loader); 2294 2295 { 2296 MutexLocker mu1(SystemDictionary_lock, THREAD); 2297 2298 // See whether biased locking is enabled and if so set it for this 2299 // klass. 2300 // Note that this must be done past the last potential blocking 2301 // point / safepoint. We enable biased locking lazily using a 2302 // VM_Operation to iterate the SystemDictionary and installing the 2303 // biasable mark word into each InstanceKlass's prototype header. 2304 // To avoid race conditions where we accidentally miss enabling the 2305 // optimization for one class in the process of being added to the 2306 // dictionary, we must not safepoint after the test of 2307 // BiasedLocking::enabled(). 2308 if (UseBiasedLocking && BiasedLocking::enabled()) { 2309 // Set biased locking bit for all loaded classes; it will be 2310 // cleared if revocation occurs too often for this type 2311 // NOTE that we must only do this when the class is initally 2312 // defined, not each time it is referenced from a new class loader 2313 if (k->class_loader() == class_loader()) { 2314 k->set_prototype_header(markOopDesc::biased_locking_prototype()); 2315 } 2316 } 2317 2318 // Make a new system dictionary entry. 2319 Klass* sd_check = find_class(d_index, d_hash, name, loader_data); 2320 if (sd_check == NULL) { 2321 dictionary()->add_klass(name, loader_data, k); 2322 notice_modification(); 2323 } 2324 #ifdef ASSERT 2325 sd_check = find_class(d_index, d_hash, name, loader_data); 2326 assert (sd_check != NULL, "should have entry in system dictionary"); 2327 // Note: there may be a placeholder entry: for circularity testing 2328 // or for parallel defines 2329 #endif 2330 SystemDictionary_lock->notify_all(); 2331 } 2332 } 2333 2334 2335 // Try to find a class name using the loader constraints. The 2336 // loader constraints might know about a class that isn't fully loaded 2337 // yet and these will be ignored. 2338 Klass* SystemDictionary::find_constrained_instance_or_array_klass( 2339 Symbol* class_name, Handle class_loader, TRAPS) { 2340 2341 // First see if it has been loaded directly. 2342 // Force the protection domain to be null. (This removes protection checks.) 2343 Handle no_protection_domain; 2344 Klass* klass = find_instance_or_array_klass(class_name, class_loader, 2345 no_protection_domain, CHECK_NULL); 2346 if (klass != NULL) 2347 return klass; 2348 2349 // Now look to see if it has been loaded elsewhere, and is subject to 2350 // a loader constraint that would require this loader to return the 2351 // klass that is already loaded. 2352 if (FieldType::is_array(class_name)) { 2353 // For array classes, their Klass*s are not kept in the 2354 // constraint table. The element Klass*s are. 2355 FieldArrayInfo fd; 2356 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL)); 2357 if (t != T_OBJECT) { 2358 klass = Universe::typeArrayKlassObj(t); 2359 } else { 2360 MutexLocker mu(SystemDictionary_lock, THREAD); 2361 klass = constraints()->find_constrained_klass(fd.object_key(), class_loader); 2362 } 2363 // If element class already loaded, allocate array klass 2364 if (klass != NULL) { 2365 klass = klass->array_klass_or_null(fd.dimension()); 2366 } 2367 } else { 2368 MutexLocker mu(SystemDictionary_lock, THREAD); 2369 // Non-array classes are easy: simply check the constraint table. 2370 klass = constraints()->find_constrained_klass(class_name, class_loader); 2371 } 2372 2373 return klass; 2374 } 2375 2376 2377 bool SystemDictionary::add_loader_constraint(Symbol* class_name, 2378 Handle class_loader1, 2379 Handle class_loader2, 2380 Thread* THREAD) { 2381 ClassLoaderData* loader_data1 = class_loader_data(class_loader1); 2382 ClassLoaderData* loader_data2 = class_loader_data(class_loader2); 2383 2384 Symbol* constraint_name = NULL; 2385 if (!FieldType::is_array(class_name)) { 2386 constraint_name = class_name; 2387 } else { 2388 // For array classes, their Klass*s are not kept in the 2389 // constraint table. The element classes are. 2390 FieldArrayInfo fd; 2391 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false)); 2392 // primitive types always pass 2393 if (t != T_OBJECT) { 2394 return true; 2395 } else { 2396 constraint_name = fd.object_key(); 2397 } 2398 } 2399 unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1); 2400 int d_index1 = dictionary()->hash_to_index(d_hash1); 2401 2402 unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2); 2403 int d_index2 = dictionary()->hash_to_index(d_hash2); 2404 { 2405 MutexLocker mu_s(SystemDictionary_lock, THREAD); 2406 2407 // Better never do a GC while we're holding these oops 2408 NoSafepointVerifier nosafepoint; 2409 2410 Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1); 2411 Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2); 2412 return constraints()->add_entry(constraint_name, klass1, class_loader1, 2413 klass2, class_loader2); 2414 } 2415 } 2416 2417 // Add entry to resolution error table to record the error when the first 2418 // attempt to resolve a reference to a class has failed. 2419 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which, 2420 Symbol* error, Symbol* message) { 2421 unsigned int hash = resolution_errors()->compute_hash(pool, which); 2422 int index = resolution_errors()->hash_to_index(hash); 2423 { 2424 MutexLocker ml(SystemDictionary_lock, Thread::current()); 2425 resolution_errors()->add_entry(index, hash, pool, which, error, message); 2426 } 2427 } 2428 2429 // Delete a resolution error for RedefineClasses for a constant pool is going away 2430 void SystemDictionary::delete_resolution_error(ConstantPool* pool) { 2431 resolution_errors()->delete_entry(pool); 2432 } 2433 2434 // Lookup resolution error table. Returns error if found, otherwise NULL. 2435 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which, 2436 Symbol** message) { 2437 unsigned int hash = resolution_errors()->compute_hash(pool, which); 2438 int index = resolution_errors()->hash_to_index(hash); 2439 { 2440 MutexLocker ml(SystemDictionary_lock, Thread::current()); 2441 ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which); 2442 if (entry != NULL) { 2443 *message = entry->message(); 2444 return entry->error(); 2445 } else { 2446 return NULL; 2447 } 2448 } 2449 } 2450 2451 2452 // Signature constraints ensure that callers and callees agree about 2453 // the meaning of type names in their signatures. This routine is the 2454 // intake for constraints. It collects them from several places: 2455 // 2456 // * LinkResolver::resolve_method (if check_access is true) requires 2457 // that the resolving class (the caller) and the defining class of 2458 // the resolved method (the callee) agree on each type in the 2459 // method's signature. 2460 // 2461 // * LinkResolver::resolve_interface_method performs exactly the same 2462 // checks. 2463 // 2464 // * LinkResolver::resolve_field requires that the constant pool 2465 // attempting to link to a field agree with the field's defining 2466 // class about the type of the field signature. 2467 // 2468 // * klassVtable::initialize_vtable requires that, when a class 2469 // overrides a vtable entry allocated by a superclass, that the 2470 // overriding method (i.e., the callee) agree with the superclass 2471 // on each type in the method's signature. 2472 // 2473 // * klassItable::initialize_itable requires that, when a class fills 2474 // in its itables, for each non-abstract method installed in an 2475 // itable, the method (i.e., the callee) agree with the interface 2476 // on each type in the method's signature. 2477 // 2478 // All those methods have a boolean (check_access, checkconstraints) 2479 // which turns off the checks. This is used from specialized contexts 2480 // such as bootstrapping, dumping, and debugging. 2481 // 2482 // No direct constraint is placed between the class and its 2483 // supertypes. Constraints are only placed along linked relations 2484 // between callers and callees. When a method overrides or implements 2485 // an abstract method in a supertype (superclass or interface), the 2486 // constraints are placed as if the supertype were the caller to the 2487 // overriding method. (This works well, since callers to the 2488 // supertype have already established agreement between themselves and 2489 // the supertype.) As a result of all this, a class can disagree with 2490 // its supertype about the meaning of a type name, as long as that 2491 // class neither calls a relevant method of the supertype, nor is 2492 // called (perhaps via an override) from the supertype. 2493 // 2494 // 2495 // SystemDictionary::check_signature_loaders(sig, l1, l2) 2496 // 2497 // Make sure all class components (including arrays) in the given 2498 // signature will be resolved to the same class in both loaders. 2499 // Returns the name of the type that failed a loader constraint check, or 2500 // NULL if no constraint failed. No exception except OOME is thrown. 2501 // Arrays are not added to the loader constraint table, their elements are. 2502 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature, 2503 Handle loader1, Handle loader2, 2504 bool is_method, TRAPS) { 2505 // Nothing to do if loaders are the same. 2506 if (loader1() == loader2()) { 2507 return NULL; 2508 } 2509 2510 SignatureStream sig_strm(signature, is_method); 2511 while (!sig_strm.is_done()) { 2512 if (sig_strm.is_object()) { 2513 Symbol* sig = sig_strm.as_symbol(CHECK_NULL); 2514 if (!add_loader_constraint(sig, loader1, loader2, THREAD)) { 2515 return sig; 2516 } 2517 } 2518 sig_strm.next(); 2519 } 2520 return NULL; 2521 } 2522 2523 2524 methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid, 2525 Symbol* signature, 2526 TRAPS) { 2527 methodHandle empty; 2528 assert(MethodHandles::is_signature_polymorphic(iid) && 2529 MethodHandles::is_signature_polymorphic_intrinsic(iid) && 2530 iid != vmIntrinsics::_invokeGeneric, 2531 "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid)); 2532 2533 unsigned int hash = invoke_method_table()->compute_hash(signature, iid); 2534 int index = invoke_method_table()->hash_to_index(hash); 2535 SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid); 2536 methodHandle m; 2537 if (spe == NULL || spe->method() == NULL) { 2538 spe = NULL; 2539 // Must create lots of stuff here, but outside of the SystemDictionary lock. 2540 m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty)); 2541 if (!Arguments::is_interpreter_only()) { 2542 // Generate a compiled form of the MH intrinsic. 2543 AdapterHandlerLibrary::create_native_wrapper(m); 2544 // Check if have the compiled code. 2545 if (!m->has_compiled_code()) { 2546 THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(), 2547 "Out of space in CodeCache for method handle intrinsic", empty); 2548 } 2549 } 2550 // Now grab the lock. We might have to throw away the new method, 2551 // if a racing thread has managed to install one at the same time. 2552 { 2553 MutexLocker ml(SystemDictionary_lock, THREAD); 2554 spe = invoke_method_table()->find_entry(index, hash, signature, iid); 2555 if (spe == NULL) 2556 spe = invoke_method_table()->add_entry(index, hash, signature, iid); 2557 if (spe->method() == NULL) 2558 spe->set_method(m()); 2559 } 2560 } 2561 2562 assert(spe != NULL && spe->method() != NULL, ""); 2563 assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() && 2564 spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()), 2565 "MH intrinsic invariant"); 2566 return spe->method(); 2567 } 2568 2569 // Helper for unpacking the return value from linkMethod and linkCallSite. 2570 static methodHandle unpack_method_and_appendix(Handle mname, 2571 KlassHandle accessing_klass, 2572 objArrayHandle appendix_box, 2573 Handle* appendix_result, 2574 TRAPS) { 2575 methodHandle empty; 2576 if (mname.not_null()) { 2577 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname()); 2578 if (vmtarget != NULL && vmtarget->is_method()) { 2579 Method* m = (Method*)vmtarget; 2580 oop appendix = appendix_box->obj_at(0); 2581 if (TraceMethodHandles) { 2582 #ifndef PRODUCT 2583 ttyLocker ttyl; 2584 tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m)); 2585 m->print(); 2586 if (appendix != NULL) { tty->print("appendix = "); appendix->print(); } 2587 tty->cr(); 2588 #endif //PRODUCT 2589 } 2590 (*appendix_result) = Handle(THREAD, appendix); 2591 // the target is stored in the cpCache and if a reference to this 2592 // MethodName is dropped we need a way to make sure the 2593 // class_loader containing this method is kept alive. 2594 // FIXME: the appendix might also preserve this dependency. 2595 ClassLoaderData* this_key = InstanceKlass::cast(accessing_klass())->class_loader_data(); 2596 this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM 2597 return methodHandle(THREAD, m); 2598 } 2599 } 2600 THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty); 2601 return empty; 2602 } 2603 2604 methodHandle SystemDictionary::find_method_handle_invoker(KlassHandle klass, 2605 Symbol* name, 2606 Symbol* signature, 2607 KlassHandle accessing_klass, 2608 Handle *appendix_result, 2609 Handle *method_type_result, 2610 TRAPS) { 2611 methodHandle empty; 2612 assert(THREAD->can_call_java() ,""); 2613 Handle method_type = 2614 SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty)); 2615 2616 int ref_kind = JVM_REF_invokeVirtual; 2617 oop name_oop = StringTable::intern(name, CHECK_(empty)); 2618 Handle name_str (THREAD, name_oop); 2619 objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty)); 2620 assert(appendix_box->obj_at(0) == NULL, ""); 2621 2622 // This should not happen. JDK code should take care of that. 2623 if (accessing_klass.is_null() || method_type.is_null()) { 2624 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty); 2625 } 2626 2627 // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName 2628 JavaCallArguments args; 2629 args.push_oop(Handle(THREAD, accessing_klass()->java_mirror())); 2630 args.push_int(ref_kind); 2631 args.push_oop(Handle(THREAD, klass()->java_mirror())); 2632 args.push_oop(name_str); 2633 args.push_oop(method_type); 2634 args.push_oop(appendix_box); 2635 JavaValue result(T_OBJECT); 2636 JavaCalls::call_static(&result, 2637 SystemDictionary::MethodHandleNatives_klass(), 2638 vmSymbols::linkMethod_name(), 2639 vmSymbols::linkMethod_signature(), 2640 &args, CHECK_(empty)); 2641 Handle mname(THREAD, (oop) result.get_jobject()); 2642 (*method_type_result) = method_type; 2643 return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD); 2644 } 2645 2646 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks. 2647 // We must ensure that all class loaders everywhere will reach this class, for any client. 2648 // This is a safe bet for public classes in java.lang, such as Object and String. 2649 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types. 2650 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util. 2651 static bool is_always_visible_class(oop mirror) { 2652 Klass* klass = java_lang_Class::as_Klass(mirror); 2653 if (klass->is_objArray_klass()) { 2654 klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type 2655 } 2656 if (klass->is_typeArray_klass()) { 2657 return true; // primitive array 2658 } 2659 assert(klass->is_instance_klass(), "%s", klass->external_name()); 2660 return klass->is_public() && 2661 (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) || // java.lang 2662 InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass())); // java.lang.invoke 2663 } 2664 2665 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given 2666 // signature, as interpreted relative to the given class loader. 2667 // Because of class loader constraints, all method handle usage must be 2668 // consistent with this loader. 2669 Handle SystemDictionary::find_method_handle_type(Symbol* signature, 2670 KlassHandle accessing_klass, 2671 TRAPS) { 2672 Handle empty; 2673 vmIntrinsics::ID null_iid = vmIntrinsics::_none; // distinct from all method handle invoker intrinsics 2674 unsigned int hash = invoke_method_table()->compute_hash(signature, null_iid); 2675 int index = invoke_method_table()->hash_to_index(hash); 2676 SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid); 2677 if (spe != NULL && spe->method_type() != NULL) { 2678 assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), ""); 2679 return Handle(THREAD, spe->method_type()); 2680 } else if (!THREAD->can_call_java()) { 2681 warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME 2682 return Handle(); // do not attempt from within compiler, unless it was cached 2683 } 2684 2685 Handle class_loader, protection_domain; 2686 if (accessing_klass.not_null()) { 2687 class_loader = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader()); 2688 protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain()); 2689 } 2690 bool can_be_cached = true; 2691 int npts = ArgumentCount(signature).size(); 2692 objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty)); 2693 int arg = 0; 2694 Handle rt; // the return type from the signature 2695 ResourceMark rm(THREAD); 2696 for (SignatureStream ss(signature); !ss.is_done(); ss.next()) { 2697 oop mirror = NULL; 2698 if (can_be_cached) { 2699 // Use neutral class loader to lookup candidate classes to be placed in the cache. 2700 mirror = ss.as_java_mirror(Handle(), Handle(), 2701 SignatureStream::ReturnNull, CHECK_(empty)); 2702 if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) { 2703 // Fall back to accessing_klass context. 2704 can_be_cached = false; 2705 } 2706 } 2707 if (!can_be_cached) { 2708 // Resolve, throwing a real error if it doesn't work. 2709 mirror = ss.as_java_mirror(class_loader, protection_domain, 2710 SignatureStream::NCDFError, CHECK_(empty)); 2711 } 2712 assert(!oopDesc::is_null(mirror), "%s", ss.as_symbol(THREAD)->as_C_string()); 2713 if (ss.at_return_type()) 2714 rt = Handle(THREAD, mirror); 2715 else 2716 pts->obj_at_put(arg++, mirror); 2717 2718 // Check accessibility. 2719 if (ss.is_object() && accessing_klass.not_null()) { 2720 Klass* sel_klass = java_lang_Class::as_Klass(mirror); 2721 mirror = NULL; // safety 2722 // Emulate ConstantPool::verify_constant_pool_resolve. 2723 if (sel_klass->is_objArray_klass()) 2724 sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass(); 2725 if (sel_klass->is_instance_klass()) { 2726 KlassHandle sel_kh(THREAD, sel_klass); 2727 LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty)); 2728 } 2729 } 2730 } 2731 assert(arg == npts, ""); 2732 2733 // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType 2734 JavaCallArguments args(Handle(THREAD, rt())); 2735 args.push_oop(pts); 2736 JavaValue result(T_OBJECT); 2737 JavaCalls::call_static(&result, 2738 SystemDictionary::MethodHandleNatives_klass(), 2739 vmSymbols::findMethodHandleType_name(), 2740 vmSymbols::findMethodHandleType_signature(), 2741 &args, CHECK_(empty)); 2742 Handle method_type(THREAD, (oop) result.get_jobject()); 2743 2744 if (can_be_cached) { 2745 // We can cache this MethodType inside the JVM. 2746 MutexLocker ml(SystemDictionary_lock, THREAD); 2747 spe = invoke_method_table()->find_entry(index, hash, signature, null_iid); 2748 if (spe == NULL) 2749 spe = invoke_method_table()->add_entry(index, hash, signature, null_iid); 2750 if (spe->method_type() == NULL) { 2751 spe->set_method_type(method_type()); 2752 } 2753 } 2754 2755 // report back to the caller with the MethodType 2756 return method_type; 2757 } 2758 2759 // Ask Java code to find or construct a method handle constant. 2760 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller, 2761 int ref_kind, //e.g., JVM_REF_invokeVirtual 2762 KlassHandle callee, 2763 Symbol* name_sym, 2764 Symbol* signature, 2765 TRAPS) { 2766 Handle empty; 2767 Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty)); 2768 Handle type; 2769 if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') { 2770 type = find_method_handle_type(signature, caller, CHECK_(empty)); 2771 } else if (caller.is_null()) { 2772 // This should not happen. JDK code should take care of that. 2773 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty); 2774 } else { 2775 ResourceMark rm(THREAD); 2776 SignatureStream ss(signature, false); 2777 if (!ss.is_done()) { 2778 oop mirror = ss.as_java_mirror(Handle(THREAD, caller->class_loader()), 2779 Handle(THREAD, caller->protection_domain()), 2780 SignatureStream::NCDFError, CHECK_(empty)); 2781 type = Handle(THREAD, mirror); 2782 ss.next(); 2783 if (!ss.is_done()) type = Handle(); // error! 2784 } 2785 } 2786 if (type.is_null()) { 2787 THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty); 2788 } 2789 2790 // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle 2791 JavaCallArguments args; 2792 args.push_oop(Handle(THREAD, caller->java_mirror())); // the referring class 2793 args.push_int(ref_kind); 2794 args.push_oop(Handle(THREAD, callee->java_mirror())); // the target class 2795 args.push_oop(name); 2796 args.push_oop(type); 2797 JavaValue result(T_OBJECT); 2798 JavaCalls::call_static(&result, 2799 SystemDictionary::MethodHandleNatives_klass(), 2800 vmSymbols::linkMethodHandleConstant_name(), 2801 vmSymbols::linkMethodHandleConstant_signature(), 2802 &args, CHECK_(empty)); 2803 return Handle(THREAD, (oop) result.get_jobject()); 2804 } 2805 2806 // Ask Java code to find or construct a java.lang.invoke.CallSite for the given 2807 // name and signature, as interpreted relative to the given class loader. 2808 methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller, 2809 Handle bootstrap_specifier, 2810 Symbol* name, 2811 Symbol* type, 2812 Handle *appendix_result, 2813 Handle *method_type_result, 2814 TRAPS) { 2815 methodHandle empty; 2816 Handle bsm, info; 2817 if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) { 2818 bsm = bootstrap_specifier; 2819 } else { 2820 assert(bootstrap_specifier->is_objArray(), ""); 2821 objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier()); 2822 int len = args->length(); 2823 assert(len >= 1, ""); 2824 bsm = Handle(THREAD, args->obj_at(0)); 2825 if (len > 1) { 2826 objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty)); 2827 for (int i = 1; i < len; i++) 2828 args1->obj_at_put(i-1, args->obj_at(i)); 2829 info = Handle(THREAD, args1); 2830 } 2831 } 2832 guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()), 2833 "caller must supply a valid BSM"); 2834 2835 Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty)); 2836 Handle method_type = find_method_handle_type(type, caller, CHECK_(empty)); 2837 2838 // This should not happen. JDK code should take care of that. 2839 if (caller.is_null() || method_type.is_null()) { 2840 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty); 2841 } 2842 2843 objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty)); 2844 assert(appendix_box->obj_at(0) == NULL, ""); 2845 2846 // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix) 2847 JavaCallArguments args; 2848 args.push_oop(Handle(THREAD, caller->java_mirror())); 2849 args.push_oop(bsm); 2850 args.push_oop(method_name); 2851 args.push_oop(method_type); 2852 args.push_oop(info); 2853 args.push_oop(appendix_box); 2854 JavaValue result(T_OBJECT); 2855 JavaCalls::call_static(&result, 2856 SystemDictionary::MethodHandleNatives_klass(), 2857 vmSymbols::linkCallSite_name(), 2858 vmSymbols::linkCallSite_signature(), 2859 &args, CHECK_(empty)); 2860 Handle mname(THREAD, (oop) result.get_jobject()); 2861 (*method_type_result) = method_type; 2862 return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD); 2863 } 2864 2865 // Since the identity hash code for symbols changes when the symbols are 2866 // moved from the regular perm gen (hash in the mark word) to the shared 2867 // spaces (hash is the address), the classes loaded into the dictionary 2868 // may be in the wrong buckets. 2869 2870 void SystemDictionary::reorder_dictionary() { 2871 dictionary()->reorder_dictionary(); 2872 } 2873 2874 2875 void SystemDictionary::copy_buckets(char** top, char* end) { 2876 dictionary()->copy_buckets(top, end); 2877 } 2878 2879 2880 void SystemDictionary::copy_table(char** top, char* end) { 2881 dictionary()->copy_table(top, end); 2882 } 2883 2884 2885 void SystemDictionary::reverse() { 2886 dictionary()->reverse(); 2887 } 2888 2889 int SystemDictionary::number_of_classes() { 2890 return dictionary()->number_of_entries(); 2891 } 2892 2893 2894 // ---------------------------------------------------------------------------- 2895 void SystemDictionary::print_shared(bool details) { 2896 shared_dictionary()->print(details); 2897 } 2898 2899 void SystemDictionary::print(bool details) { 2900 dictionary()->print(details); 2901 2902 // Placeholders 2903 GCMutexLocker mu(SystemDictionary_lock); 2904 placeholders()->print(); 2905 2906 // loader constraints - print under SD_lock 2907 constraints()->print(); 2908 } 2909 2910 2911 void SystemDictionary::verify() { 2912 guarantee(dictionary() != NULL, "Verify of system dictionary failed"); 2913 guarantee(constraints() != NULL, 2914 "Verify of loader constraints failed"); 2915 guarantee(dictionary()->number_of_entries() >= 0 && 2916 placeholders()->number_of_entries() >= 0, 2917 "Verify of system dictionary failed"); 2918 2919 // Verify dictionary 2920 dictionary()->verify(); 2921 2922 GCMutexLocker mu(SystemDictionary_lock); 2923 placeholders()->verify(); 2924 2925 // Verify constraint table 2926 guarantee(constraints() != NULL, "Verify of loader constraints failed"); 2927 constraints()->verify(dictionary(), placeholders()); 2928 } 2929 2930 // caller needs ResourceMark 2931 const char* SystemDictionary::loader_name(const oop loader) { 2932 return ((loader) == NULL ? "<bootloader>" : 2933 InstanceKlass::cast((loader)->klass())->name()->as_C_string()); 2934 } 2935 2936 // caller needs ResourceMark 2937 const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) { 2938 return (loader_data->class_loader() == NULL ? "<bootloader>" : 2939 SystemDictionary::loader_name(loader_data->class_loader())); 2940 } --- EOF ---