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