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