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