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