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