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