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