1 /* 2 * Copyright (c) 1997, 2024, 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 "cds/cdsConfig.hpp" 27 #include "cds/heapShared.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/classLoaderExt.hpp" 34 #include "classfile/classLoadInfo.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/vmClasses.hpp" 47 #include "classfile/vmSymbols.hpp" 48 #include "gc/shared/gcTraceTime.inline.hpp" 49 #include "interpreter/bootstrapInfo.hpp" 50 #include "jfr/jfrEvents.hpp" 51 #include "jvm.h" 52 #include "logging/log.hpp" 53 #include "logging/logStream.hpp" 54 #include "memory/metaspaceClosure.hpp" 55 #include "memory/oopFactory.hpp" 56 #include "memory/resourceArea.hpp" 57 #include "memory/universe.hpp" 58 #include "oops/access.inline.hpp" 59 #include "oops/fieldStreams.inline.hpp" 60 #include "oops/instanceKlass.hpp" 61 #include "oops/klass.inline.hpp" 62 #include "oops/method.inline.hpp" 63 #include "oops/objArrayKlass.hpp" 64 #include "oops/objArrayOop.inline.hpp" 65 #include "oops/oop.inline.hpp" 66 #include "oops/oop.hpp" 67 #include "oops/oopHandle.hpp" 68 #include "oops/oopHandle.inline.hpp" 69 #include "oops/symbol.hpp" 70 #include "oops/typeArrayKlass.hpp" 71 #include "oops/inlineKlass.inline.hpp" 72 #include "prims/jvmtiExport.hpp" 73 #include "prims/methodHandles.hpp" 74 #include "runtime/arguments.hpp" 75 #include "runtime/atomic.hpp" 76 #include "runtime/handles.inline.hpp" 77 #include "runtime/java.hpp" 78 #include "runtime/javaCalls.hpp" 79 #include "runtime/mutexLocker.hpp" 80 #include "runtime/os.hpp" 81 #include "runtime/sharedRuntime.hpp" 82 #include "runtime/signature.hpp" 83 #include "runtime/synchronizer.hpp" 84 #include "services/classLoadingService.hpp" 85 #include "services/diagnosticCommand.hpp" 86 #include "services/finalizerService.hpp" 87 #include "services/threadService.hpp" 88 #include "utilities/macros.hpp" 89 #include "utilities/utf8.hpp" 90 #if INCLUDE_CDS 91 #include "classfile/systemDictionaryShared.hpp" 92 #endif 93 #if INCLUDE_JFR 94 #include "jfr/jfr.hpp" 95 #endif 96 97 class InvokeMethodKey : public StackObj { 98 private: 99 Symbol* _symbol; 100 intptr_t _iid; 101 102 public: 103 InvokeMethodKey(Symbol* symbol, intptr_t iid) : 104 _symbol(symbol), 105 _iid(iid) {} 106 107 static bool key_comparison(InvokeMethodKey const &k1, InvokeMethodKey const &k2){ 108 return k1._symbol == k2._symbol && k1._iid == k2._iid; 109 } 110 111 static unsigned int compute_hash(const InvokeMethodKey &k) { 112 Symbol* sym = k._symbol; 113 intptr_t iid = k._iid; 114 unsigned int hash = (unsigned int) sym -> identity_hash(); 115 return (unsigned int) (hash ^ iid); 116 } 117 118 }; 119 120 using InvokeMethodIntrinsicTable = ResourceHashtable<InvokeMethodKey, Method*, 139, AnyObj::C_HEAP, mtClass, 121 InvokeMethodKey::compute_hash, InvokeMethodKey::key_comparison>; 122 static InvokeMethodIntrinsicTable* _invoke_method_intrinsic_table; 123 using InvokeMethodTypeTable = ResourceHashtable<SymbolHandle, OopHandle, 139, AnyObj::C_HEAP, mtClass, SymbolHandle::compute_hash>; 124 static InvokeMethodTypeTable* _invoke_method_type_table; 125 126 OopHandle SystemDictionary::_java_system_loader; 127 OopHandle SystemDictionary::_java_platform_loader; 128 129 // ---------------------------------------------------------------------------- 130 // Java-level SystemLoader and PlatformLoader 131 oop SystemDictionary::java_system_loader() { 132 return _java_system_loader.resolve(); 133 } 134 135 oop SystemDictionary::java_platform_loader() { 136 return _java_platform_loader.resolve(); 137 } 138 139 void SystemDictionary::compute_java_loaders(TRAPS) { 140 if (_java_system_loader.is_empty()) { 141 oop system_loader = get_system_class_loader_impl(CHECK); 142 _java_system_loader = OopHandle(Universe::vm_global(), system_loader); 143 } else { 144 // It must have been restored from the archived module graph 145 assert(UseSharedSpaces, "must be"); 146 assert(CDSConfig::is_loading_full_module_graph(), "must be"); 147 DEBUG_ONLY( 148 oop system_loader = get_system_class_loader_impl(CHECK); 149 assert(_java_system_loader.resolve() == system_loader, "must be"); 150 ) 151 } 152 153 if (_java_platform_loader.is_empty()) { 154 oop platform_loader = get_platform_class_loader_impl(CHECK); 155 _java_platform_loader = OopHandle(Universe::vm_global(), platform_loader); 156 } else { 157 // It must have been restored from the archived module graph 158 assert(UseSharedSpaces, "must be"); 159 assert(CDSConfig::is_loading_full_module_graph(), "must be"); 160 DEBUG_ONLY( 161 oop platform_loader = get_platform_class_loader_impl(CHECK); 162 assert(_java_platform_loader.resolve() == platform_loader, "must be"); 163 ) 164 } 165 } 166 167 oop SystemDictionary::get_system_class_loader_impl(TRAPS) { 168 JavaValue result(T_OBJECT); 169 InstanceKlass* class_loader_klass = vmClasses::ClassLoader_klass(); 170 JavaCalls::call_static(&result, 171 class_loader_klass, 172 vmSymbols::getSystemClassLoader_name(), 173 vmSymbols::void_classloader_signature(), 174 CHECK_NULL); 175 return result.get_oop(); 176 } 177 178 oop SystemDictionary::get_platform_class_loader_impl(TRAPS) { 179 JavaValue result(T_OBJECT); 180 InstanceKlass* class_loader_klass = vmClasses::ClassLoader_klass(); 181 JavaCalls::call_static(&result, 182 class_loader_klass, 183 vmSymbols::getPlatformClassLoader_name(), 184 vmSymbols::void_classloader_signature(), 185 CHECK_NULL); 186 return result.get_oop(); 187 } 188 189 // Helper function 190 inline ClassLoaderData* class_loader_data(Handle class_loader) { 191 return ClassLoaderData::class_loader_data(class_loader()); 192 } 193 194 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, bool create_mirror_cld) { 195 if (create_mirror_cld) { 196 // Add a new class loader data to the graph. 197 return ClassLoaderDataGraph::add(class_loader, true); 198 } else { 199 return (class_loader() == nullptr) ? ClassLoaderData::the_null_class_loader_data() : 200 ClassLoaderDataGraph::find_or_create(class_loader); 201 } 202 } 203 204 void SystemDictionary::set_system_loader(ClassLoaderData *cld) { 205 assert(_java_system_loader.is_empty(), "already set!"); 206 _java_system_loader = cld->class_loader_handle(); 207 208 } 209 210 void SystemDictionary::set_platform_loader(ClassLoaderData *cld) { 211 assert(_java_platform_loader.is_empty(), "already set!"); 212 _java_platform_loader = cld->class_loader_handle(); 213 } 214 215 // ---------------------------------------------------------------------------- 216 // Parallel class loading check 217 218 bool is_parallelCapable(Handle class_loader) { 219 if (class_loader.is_null()) return true; 220 return java_lang_ClassLoader::parallelCapable(class_loader()); 221 } 222 // ---------------------------------------------------------------------------- 223 // ParallelDefineClass flag does not apply to bootclass loader 224 bool is_parallelDefine(Handle class_loader) { 225 if (class_loader.is_null()) return false; 226 if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) { 227 return true; 228 } 229 return false; 230 } 231 232 // Returns true if the passed class loader is the builtin application class loader 233 // or a custom system class loader. A customer system class loader can be 234 // specified via -Djava.system.class.loader. 235 bool SystemDictionary::is_system_class_loader(oop class_loader) { 236 if (class_loader == nullptr) { 237 return false; 238 } 239 return (class_loader->klass() == vmClasses::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() || 240 class_loader == _java_system_loader.peek()); 241 } 242 243 // Returns true if the passed class loader is the platform class loader. 244 bool SystemDictionary::is_platform_class_loader(oop class_loader) { 245 if (class_loader == nullptr) { 246 return false; 247 } 248 return (class_loader->klass() == vmClasses::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass()); 249 } 250 251 Handle SystemDictionary::get_loader_lock_or_null(Handle class_loader) { 252 // If class_loader is null or parallelCapable, the JVM doesn't acquire a lock while loading. 253 if (is_parallelCapable(class_loader)) { 254 return Handle(); 255 } else { 256 return class_loader; 257 } 258 } 259 260 // ---------------------------------------------------------------------------- 261 // Resolving of classes 262 263 Symbol* SystemDictionary::class_name_symbol(const char* name, Symbol* exception, TRAPS) { 264 if (name == nullptr) { 265 THROW_MSG_0(exception, "No class name given"); 266 } 267 if ((int)strlen(name) > Symbol::max_length()) { 268 // It's impossible to create this class; the name cannot fit 269 // into the constant pool. 270 Exceptions::fthrow(THREAD_AND_LOCATION, exception, 271 "Class name exceeds maximum length of %d: %s", 272 Symbol::max_length(), 273 name); 274 return nullptr; 275 } 276 // Callers should ensure that the name is never an illegal UTF8 string. 277 assert(UTF8::is_legal_utf8((const unsigned char*)name, (int)strlen(name), false), 278 "Class name is not a valid utf8 string."); 279 280 // Make a new symbol for the class name. 281 return SymbolTable::new_symbol(name); 282 } 283 284 #ifdef ASSERT 285 // Used to verify that class loading succeeded in adding k to the dictionary. 286 void verify_dictionary_entry(Symbol* class_name, InstanceKlass* k) { 287 MutexLocker mu(SystemDictionary_lock); 288 ClassLoaderData* loader_data = k->class_loader_data(); 289 Dictionary* dictionary = loader_data->dictionary(); 290 assert(class_name == k->name(), "Must be the same"); 291 InstanceKlass* kk = dictionary->find_class(JavaThread::current(), class_name); 292 assert(kk == k, "should be present in dictionary"); 293 } 294 #endif 295 296 static void handle_resolution_exception(Symbol* class_name, bool throw_error, TRAPS) { 297 if (HAS_PENDING_EXCEPTION) { 298 // If we have a pending exception we forward it to the caller, unless throw_error is true, 299 // in which case we have to check whether the pending exception is a ClassNotFoundException, 300 // and convert it to a NoClassDefFoundError and chain the original ClassNotFoundException. 301 if (throw_error && PENDING_EXCEPTION->is_a(vmClasses::ClassNotFoundException_klass())) { 302 ResourceMark rm(THREAD); 303 Handle e(THREAD, PENDING_EXCEPTION); 304 CLEAR_PENDING_EXCEPTION; 305 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e); 306 } else { 307 return; // the caller will throw the incoming exception 308 } 309 } 310 // If the class is not found, ie, caller has checked that klass is null, throw the appropriate 311 // error or exception depending on the value of throw_error. 312 ResourceMark rm(THREAD); 313 if (throw_error) { 314 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string()); 315 } else { 316 THROW_MSG(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string()); 317 } 318 } 319 320 // Forwards to resolve_or_null 321 322 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, 323 bool throw_error, TRAPS) { 324 Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD); 325 // Check for pending exception or null klass, and throw exception 326 if (HAS_PENDING_EXCEPTION || klass == nullptr) { 327 handle_resolution_exception(class_name, throw_error, CHECK_NULL); 328 } 329 return klass; 330 } 331 332 // Forwards to resolve_array_class_or_null or resolve_instance_class_or_null 333 334 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) { 335 if (Signature::is_array(class_name)) { 336 return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD); 337 } else { 338 assert(class_name != nullptr && !Signature::is_array(class_name), "must be"); 339 if (Signature::has_envelope(class_name)) { 340 ResourceMark rm(THREAD); 341 // Ignore wrapping L and ; (and Q and ; for value types). 342 TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1, 343 class_name->utf8_length() - 2); 344 return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD); 345 } else { 346 return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD); 347 } 348 } 349 } 350 351 // Forwards to resolve_instance_class_or_null 352 353 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name, 354 Handle class_loader, 355 Handle protection_domain, 356 TRAPS) { 357 assert(Signature::is_array(class_name), "must be array"); 358 ResourceMark rm(THREAD); 359 SignatureStream ss(class_name, false); 360 int ndims = ss.skip_array_prefix(); // skip all '['s 361 Klass* k = nullptr; 362 BasicType t = ss.type(); 363 if (ss.has_envelope()) { 364 Symbol* obj_class = ss.as_symbol(); 365 k = SystemDictionary::resolve_instance_class_or_null(obj_class, 366 class_loader, 367 protection_domain, 368 CHECK_NULL); 369 if (k != nullptr) { 370 k = k->array_klass(ndims, CHECK_NULL); 371 } 372 } else { 373 k = Universe::typeArrayKlassObj(t); 374 k = TypeArrayKlass::cast(k)->array_klass(ndims, CHECK_NULL); 375 } 376 return k; 377 } 378 379 static inline void log_circularity_error(Symbol* name, PlaceholderEntry* probe) { 380 LogTarget(Debug, class, load, placeholders) lt; 381 if (lt.is_enabled()) { 382 ResourceMark rm; 383 LogStream ls(lt); 384 ls.print("ClassCircularityError detected for placeholder entry %s", name->as_C_string()); 385 probe->print_on(&ls); 386 ls.cr(); 387 } 388 } 389 390 // Must be called for any superclass or superinterface resolution 391 // during class definition to allow class circularity checking 392 // superinterface callers: 393 // parse_interfaces - from defineClass 394 // superclass callers: 395 // ClassFileParser - from defineClass 396 // load_shared_class - while loading a class from shared archive 397 // resolve_instance_class_or_null: 398 // via: handle_parallel_super_load 399 // when resolving a class that has an existing placeholder with 400 // a saved superclass [i.e. a defineClass is currently in progress] 401 // If another thread is trying to resolve the class, it must do 402 // superclass checks on its own thread to catch class circularity and 403 // to avoid deadlock. 404 // 405 // resolve_with_circularity_detection_or_fail adds a DETECT_CIRCULARITY placeholder to the placeholder table before calling 406 // resolve_instance_class_or_null. ClassCircularityError is detected when a DETECT_CIRCULARITY or LOAD_INSTANCE 407 // placeholder for the same thread, class, classloader is found. 408 // This can be seen with logging option: -Xlog:class+load+placeholders=debug. 409 // 410 InstanceKlass* SystemDictionary::resolve_with_circularity_detection_or_fail(Symbol* class_name, 411 Symbol* next_name, 412 Handle class_loader, 413 Handle protection_domain, 414 bool is_superclass, 415 TRAPS) { 416 417 assert(next_name != nullptr, "null superclass for resolving"); 418 assert(!Signature::is_array(next_name), "invalid superclass name"); 419 #if INCLUDE_CDS 420 if (CDSConfig::is_dumping_static_archive()) { 421 // Special processing for handling UNREGISTERED shared classes. 422 InstanceKlass* k = SystemDictionaryShared::lookup_super_for_unregistered_class(class_name, 423 next_name, is_superclass); 424 if (k) { 425 return k; 426 } 427 } 428 #endif // INCLUDE_CDS 429 430 // If klass is already loaded, just return the superclass or superinterface. 431 // Make sure there's a placeholder for the class_name before resolving. 432 // This is used as a claim that this thread is currently loading superclass/classloader 433 // and for ClassCircularity checks. 434 435 ClassLoaderData* loader_data = class_loader_data(class_loader); 436 Dictionary* dictionary = loader_data->dictionary(); 437 438 // can't throw error holding a lock 439 bool throw_circularity_error = false; 440 { 441 MutexLocker mu(THREAD, SystemDictionary_lock); 442 InstanceKlass* klassk = dictionary->find_class(THREAD, class_name); 443 InstanceKlass* quicksuperk; 444 // To support parallel loading: if class is done loading, just return the superclass 445 // if the next_name matches class->super()->name() and if the class loaders match. 446 // Otherwise, a LinkageError will be thrown later. 447 if (klassk != nullptr && is_superclass && 448 ((quicksuperk = klassk->java_super()) != nullptr) && 449 ((quicksuperk->name() == next_name) && 450 (quicksuperk->class_loader() == class_loader()))) { 451 return quicksuperk; 452 } else { 453 // Must check ClassCircularity before checking if superclass is already loaded. 454 PlaceholderEntry* probe = PlaceholderTable::get_entry(class_name, loader_data); 455 if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::DETECT_CIRCULARITY)) { 456 log_circularity_error(class_name, probe); 457 throw_circularity_error = true; 458 } 459 } 460 461 if (!throw_circularity_error) { 462 // Be careful not to exit resolve_super without removing this placeholder. 463 PlaceholderEntry* newprobe = PlaceholderTable::find_and_add(class_name, 464 loader_data, 465 PlaceholderTable::DETECT_CIRCULARITY, 466 next_name, THREAD); 467 } 468 } 469 470 if (throw_circularity_error) { 471 ResourceMark rm(THREAD); 472 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), class_name->as_C_string()); 473 } 474 475 // Resolve the superclass or superinterface, check results on return 476 InstanceKlass* superk = 477 SystemDictionary::resolve_instance_class_or_null(next_name, 478 class_loader, 479 protection_domain, 480 THREAD); 481 482 // Clean up placeholder entry. 483 { 484 MutexLocker mu(THREAD, SystemDictionary_lock); 485 PlaceholderTable::find_and_remove(class_name, loader_data, PlaceholderTable::DETECT_CIRCULARITY, THREAD); 486 SystemDictionary_lock->notify_all(); 487 } 488 489 // Check for pending exception or null superk, and throw exception 490 if (HAS_PENDING_EXCEPTION || superk == nullptr) { 491 handle_resolution_exception(next_name, true, CHECK_NULL); 492 } 493 494 return superk; 495 } 496 497 // If the class in is in the placeholder table, class loading is in progress. 498 // For cases where the application changes threads to load classes, it 499 // is critical to ClassCircularity detection that we try loading 500 // the superclass on the new thread internally, so we do parallel 501 // superclass loading here. This avoids deadlock for ClassCircularity 502 // detection for parallelCapable class loaders that lock on a per-class lock. 503 static void handle_parallel_super_load(Symbol* name, 504 Symbol* superclassname, 505 Handle class_loader, 506 Handle protection_domain, TRAPS) { 507 508 // superk is not used; resolve_super_or_fail is called for circularity check only. 509 Klass* superk = SystemDictionary::resolve_with_circularity_detection_or_fail(name, 510 superclassname, 511 class_loader, 512 protection_domain, 513 false, 514 CHECK); 515 } 516 517 // Bootstrap and non-parallel capable class loaders use the LOAD_INSTANCE placeholder to 518 // wait for parallel class loading and/or to check for circularity error for Xcomp when loading. 519 static bool needs_load_placeholder(Handle class_loader) { 520 return class_loader.is_null() || !is_parallelCapable(class_loader); 521 } 522 523 // Check for other threads loading this class either to throw CCE or wait in the case of the boot loader. 524 static InstanceKlass* handle_parallel_loading(JavaThread* current, 525 Symbol* name, 526 ClassLoaderData* loader_data, 527 bool must_wait_for_class_loading, 528 bool* throw_circularity_error) { 529 PlaceholderEntry* oldprobe = PlaceholderTable::get_entry(name, loader_data); 530 if (oldprobe != nullptr) { 531 // -Xcomp calls load_signature_classes which might result in loading 532 // a class that's already in the process of loading, so we detect CCE here also. 533 // Only need check_seen_thread once, not on each loop 534 if (oldprobe->check_seen_thread(current, PlaceholderTable::LOAD_INSTANCE)) { 535 log_circularity_error(name, oldprobe); 536 *throw_circularity_error = true; 537 return nullptr; 538 } else if (must_wait_for_class_loading) { 539 // Wait until the first thread has finished loading this class. Also wait until all the 540 // threads trying to load its superclass have removed their placeholders. 541 while (oldprobe != nullptr && 542 (oldprobe->instance_load_in_progress() || oldprobe->circularity_detection_in_progress())) { 543 544 // LOAD_INSTANCE placeholders are used to implement parallel capable class loading 545 // for the bootclass loader. 546 SystemDictionary_lock->wait(); 547 548 // Check if classloading completed while we were waiting 549 InstanceKlass* check = loader_data->dictionary()->find_class(current, name); 550 if (check != nullptr) { 551 // Klass is already loaded, so just return it 552 return check; 553 } 554 // check if other thread failed to load and cleaned up 555 oldprobe = PlaceholderTable::get_entry(name, loader_data); 556 } 557 } 558 } 559 return nullptr; 560 } 561 562 void SystemDictionary::post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld) { 563 assert(event != nullptr, "invariant"); 564 assert(k != nullptr, "invariant"); 565 event->set_loadedClass(k); 566 event->set_definingClassLoader(k->class_loader_data()); 567 event->set_initiatingClassLoader(init_cld); 568 event->commit(); 569 } 570 571 // SystemDictionary::resolve_instance_class_or_null is the main function for class name resolution. 572 // After checking if the InstanceKlass already exists, it checks for ClassCircularityError and 573 // whether the thread must wait for loading in parallel. It eventually calls load_instance_class, 574 // which will load the class via the bootstrap loader or call ClassLoader.loadClass(). 575 // This can return null, an exception or an InstanceKlass. 576 InstanceKlass* SystemDictionary::resolve_instance_class_or_null(Symbol* name, 577 Handle class_loader, 578 Handle protection_domain, 579 TRAPS) { 580 // name must be in the form of "java/lang/Object" -- cannot be "Ljava/lang/Object;" 581 assert(name != nullptr && !Signature::is_array(name) && 582 !Signature::has_envelope(name), "invalid class name: %s", name == nullptr ? "nullptr" : name->as_C_string()); 583 584 EventClassLoad class_load_start_event; 585 586 HandleMark hm(THREAD); 587 588 // Fix for 4474172; see evaluation for more details 589 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 590 ClassLoaderData* loader_data = register_loader(class_loader); 591 Dictionary* dictionary = loader_data->dictionary(); 592 593 // Do lookup to see if class already exists and the protection domain 594 // has the right access. 595 // This call uses find which checks protection domain already matches 596 // All subsequent calls use find_class, and set loaded_class so that 597 // before we return a result, we call out to java to check for valid protection domain. 598 InstanceKlass* probe = dictionary->find(THREAD, name, protection_domain); 599 if (probe != nullptr) return probe; 600 601 // Non-bootstrap class loaders will call out to class loader and 602 // define via jvm/jni_DefineClass which will acquire the 603 // class loader object lock to protect against multiple threads 604 // defining the class in parallel by accident. 605 // This lock must be acquired here so the waiter will find 606 // any successful result in the SystemDictionary and not attempt 607 // the define. 608 // ParallelCapable class loaders and the bootstrap classloader 609 // do not acquire lock here. 610 Handle lockObject = get_loader_lock_or_null(class_loader); 611 ObjectLocker ol(lockObject, THREAD); 612 613 bool circularity_detection_in_progress = false; 614 InstanceKlass* loaded_class = nullptr; 615 SymbolHandle superclassname; // Keep alive while loading in parallel thread. 616 617 guarantee(THREAD->can_call_java(), 618 "can not load classes with compiler thread: class=%s, classloader=%s", 619 name->as_C_string(), 620 class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string()); 621 622 // Check again (after locking) if the class already exists in SystemDictionary 623 { 624 MutexLocker mu(THREAD, SystemDictionary_lock); 625 InstanceKlass* check = dictionary->find_class(THREAD, name); 626 if (check != nullptr) { 627 // InstanceKlass is already loaded, but we still need to check protection domain below. 628 loaded_class = check; 629 } else { 630 PlaceholderEntry* placeholder = PlaceholderTable::get_entry(name, loader_data); 631 if (placeholder != nullptr && placeholder->circularity_detection_in_progress()) { 632 circularity_detection_in_progress = true; 633 superclassname = placeholder->next_klass_name(); 634 assert(superclassname != nullptr, "superclass has to have a name"); 635 } 636 } 637 } 638 639 // If the class is in the placeholder table with super_class set, 640 // handle superclass loading in progress. 641 if (circularity_detection_in_progress) { 642 handle_parallel_super_load(name, superclassname, 643 class_loader, 644 protection_domain, 645 CHECK_NULL); 646 } 647 648 bool throw_circularity_error = false; 649 if (loaded_class == nullptr) { 650 bool load_placeholder_added = false; 651 652 // Add placeholder entry to record loading instance class 653 // case 1. Bootstrap classloader 654 // This classloader supports parallelism at the classloader level 655 // but only allows a single thread to load a class/classloader pair. 656 // The LOAD_INSTANCE placeholder is the mechanism for mutual exclusion. 657 // case 2. parallelCapable user level classloaders 658 // These class loaders lock a per-class object lock when ClassLoader.loadClass() 659 // is called. A LOAD_INSTANCE placeholder isn't used for mutual exclusion. 660 // case 3. traditional classloaders that rely on the classloader object lock 661 // There should be no need for need for LOAD_INSTANCE for mutual exclusion, 662 // except the LOAD_INSTANCE placeholder is used to detect CCE for -Xcomp. 663 // TODO: should also be used to detect CCE for parallel capable class loaders but it's not. 664 { 665 MutexLocker mu(THREAD, SystemDictionary_lock); 666 if (needs_load_placeholder(class_loader)) { 667 loaded_class = handle_parallel_loading(THREAD, 668 name, 669 loader_data, 670 class_loader.is_null(), 671 &throw_circularity_error); 672 } 673 674 // Recheck if the class has been loaded for all class loader cases and 675 // add a LOAD_INSTANCE placeholder while holding the SystemDictionary_lock. 676 if (!throw_circularity_error && loaded_class == nullptr) { 677 InstanceKlass* check = dictionary->find_class(THREAD, name); 678 if (check != nullptr) { 679 loaded_class = check; 680 } else if (needs_load_placeholder(class_loader)) { 681 // Add the LOAD_INSTANCE token. Threads will wait on loading to complete for this thread. 682 PlaceholderEntry* newprobe = PlaceholderTable::find_and_add(name, loader_data, 683 PlaceholderTable::LOAD_INSTANCE, 684 nullptr, 685 THREAD); 686 load_placeholder_added = true; 687 } 688 } 689 } 690 691 // Must throw error outside of owning lock 692 if (throw_circularity_error) { 693 assert(!HAS_PENDING_EXCEPTION && !load_placeholder_added, "circularity error cleanup"); 694 ResourceMark rm(THREAD); 695 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string()); 696 } 697 698 // Be careful when modifying this code: once you have run 699 // PlaceholderTable::find_and_add(PlaceholderTable::LOAD_INSTANCE), 700 // you need to find_and_remove it before returning. 701 // So be careful to not exit with a CHECK_ macro between these calls. 702 703 if (loaded_class == nullptr) { 704 // Do actual loading 705 loaded_class = load_instance_class(name, class_loader, THREAD); 706 } 707 708 if (load_placeholder_added) { 709 // clean up placeholder entries for LOAD_INSTANCE success or error 710 // This brackets the SystemDictionary updates for both defining 711 // and initiating loaders 712 MutexLocker mu(THREAD, SystemDictionary_lock); 713 PlaceholderTable::find_and_remove(name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD); 714 SystemDictionary_lock->notify_all(); 715 } 716 } 717 718 if (HAS_PENDING_EXCEPTION || loaded_class == nullptr) { 719 return nullptr; 720 } 721 722 if (class_load_start_event.should_commit()) { 723 post_class_load_event(&class_load_start_event, loaded_class, loader_data); 724 } 725 726 // Make sure we have the right class in the dictionary 727 DEBUG_ONLY(verify_dictionary_entry(name, loaded_class)); 728 729 // Check if the protection domain is present it has the right access 730 if (protection_domain() != nullptr) { 731 // Verify protection domain. If it fails an exception is thrown 732 dictionary->validate_protection_domain(loaded_class, class_loader, protection_domain, CHECK_NULL); 733 } 734 735 return loaded_class; 736 } 737 738 739 // This routine does not lock the system dictionary. 740 // 741 // Since readers don't hold a lock, we must make sure that system 742 // dictionary entries are added to in a safe way (all links must 743 // be updated in an MT-safe manner). All entries are removed during class 744 // unloading, when this class loader is no longer referenced. 745 // 746 // Callers should be aware that an entry could be added just after 747 // Dictionary is read here, so the caller will not see 748 // the new entry. 749 750 InstanceKlass* SystemDictionary::find_instance_klass(Thread* current, 751 Symbol* class_name, 752 Handle class_loader, 753 Handle protection_domain) { 754 755 // The result of this call should be consistent with the result 756 // of the call to resolve_instance_class_or_null(). 757 // See evaluation 6790209 and 4474172 for more details. 758 oop class_loader_oop = java_lang_ClassLoader::non_reflection_class_loader(class_loader()); 759 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader_oop); 760 761 if (loader_data == nullptr) { 762 // If the ClassLoaderData has not been setup, 763 // then the class loader has no entries in the dictionary. 764 return nullptr; 765 } 766 767 Dictionary* dictionary = loader_data->dictionary(); 768 return dictionary->find(current, class_name, protection_domain); 769 } 770 771 // Look for a loaded instance or array klass by name. Do not do any loading. 772 // return null in case of error. 773 Klass* SystemDictionary::find_instance_or_array_klass(Thread* current, 774 Symbol* class_name, 775 Handle class_loader, 776 Handle protection_domain) { 777 Klass* k = nullptr; 778 assert(class_name != nullptr, "class name must be non nullptr"); 779 780 if (Signature::is_array(class_name)) { 781 // The name refers to an array. Parse the name. 782 // dimension and object_key in FieldArrayInfo are assigned as a 783 // side-effect of this call 784 SignatureStream ss(class_name, false); 785 int ndims = ss.skip_array_prefix(); // skip all '['s 786 BasicType t = ss.type(); 787 if (t != T_OBJECT) { 788 k = Universe::typeArrayKlassObj(t); 789 } else { 790 k = SystemDictionary::find_instance_klass(current, ss.as_symbol(), class_loader, protection_domain); 791 } 792 if (k != nullptr) { 793 k = k->array_klass_or_null(ndims); 794 } 795 } else { 796 k = find_instance_klass(current, class_name, class_loader, protection_domain); 797 } 798 return k; 799 } 800 801 // Note: this method is much like resolve_class_from_stream, but 802 // does not publish the classes in the SystemDictionary. 803 // Handles Lookup.defineClass hidden. 804 InstanceKlass* SystemDictionary::resolve_hidden_class_from_stream( 805 ClassFileStream* st, 806 Symbol* class_name, 807 Handle class_loader, 808 const ClassLoadInfo& cl_info, 809 TRAPS) { 810 811 EventClassLoad class_load_start_event; 812 ClassLoaderData* loader_data; 813 814 // - for hidden classes that are not strong: create a new CLD that has a class holder and 815 // whose loader is the Lookup class's loader. 816 // - for hidden class: add the class to the Lookup class's loader's CLD. 817 assert (cl_info.is_hidden(), "only used for hidden classes"); 818 bool create_mirror_cld = !cl_info.is_strong_hidden(); 819 loader_data = register_loader(class_loader, create_mirror_cld); 820 821 assert(st != nullptr, "invariant"); 822 assert(st->need_verify(), "invariant"); 823 824 // Parse stream and create a klass. 825 InstanceKlass* k = KlassFactory::create_from_stream(st, 826 class_name, 827 loader_data, 828 cl_info, 829 CHECK_NULL); 830 assert(k != nullptr, "no klass created"); 831 832 // Hidden classes that are not strong must update ClassLoaderData holder 833 // so that they can be unloaded when the mirror is no longer referenced. 834 if (!cl_info.is_strong_hidden()) { 835 k->class_loader_data()->initialize_holder(Handle(THREAD, k->java_mirror())); 836 } 837 838 // Add to class hierarchy, and do possible deoptimizations. 839 k->add_to_hierarchy(THREAD); 840 // But, do not add to dictionary. 841 842 k->link_class(CHECK_NULL); 843 844 // notify jvmti 845 if (JvmtiExport::should_post_class_load()) { 846 JvmtiExport::post_class_load(THREAD, k); 847 } 848 if (class_load_start_event.should_commit()) { 849 post_class_load_event(&class_load_start_event, k, loader_data); 850 } 851 852 return k; 853 } 854 855 // Add a klass to the system from a stream (called by jni_DefineClass and 856 // JVM_DefineClass). 857 // Note: class_name can be null. In that case we do not know the name of 858 // the class until we have parsed the stream. 859 // This function either returns an InstanceKlass or throws an exception. It does 860 // not return null without a pending exception. 861 InstanceKlass* SystemDictionary::resolve_class_from_stream( 862 ClassFileStream* st, 863 Symbol* class_name, 864 Handle class_loader, 865 const ClassLoadInfo& cl_info, 866 TRAPS) { 867 868 HandleMark hm(THREAD); 869 870 ClassLoaderData* loader_data = register_loader(class_loader); 871 872 // Classloaders that support parallelism, e.g. bootstrap classloader, 873 // do not acquire lock here 874 Handle lockObject = get_loader_lock_or_null(class_loader); 875 ObjectLocker ol(lockObject, THREAD); 876 877 // Parse the stream and create a klass. 878 // Note that we do this even though this klass might 879 // already be present in the SystemDictionary, otherwise we would not 880 // throw potential ClassFormatErrors. 881 InstanceKlass* k = nullptr; 882 883 #if INCLUDE_CDS 884 if (!CDSConfig::is_dumping_static_archive()) { 885 k = SystemDictionaryShared::lookup_from_stream(class_name, 886 class_loader, 887 cl_info.protection_domain(), 888 st, 889 CHECK_NULL); 890 } 891 #endif 892 893 if (k == nullptr) { 894 k = KlassFactory::create_from_stream(st, class_name, loader_data, cl_info, CHECK_NULL); 895 } 896 897 assert(k != nullptr, "no klass created"); 898 Symbol* h_name = k->name(); 899 assert(class_name == nullptr || class_name == h_name, "name mismatch"); 900 901 // Add class just loaded 902 // If a class loader supports parallel classloading, handle parallel define requests. 903 // find_or_define_instance_class may return a different InstanceKlass, 904 // in which case the old k would be deallocated 905 if (is_parallelCapable(class_loader)) { 906 k = find_or_define_instance_class(h_name, class_loader, k, CHECK_NULL); 907 } else { 908 define_instance_class(k, class_loader, THREAD); 909 910 // If defining the class throws an exception register 'k' for cleanup. 911 if (HAS_PENDING_EXCEPTION) { 912 assert(k != nullptr, "Must have an instance klass here!"); 913 loader_data->add_to_deallocate_list(k); 914 return nullptr; 915 } 916 } 917 918 // Make sure we have an entry in the SystemDictionary on success 919 DEBUG_ONLY(verify_dictionary_entry(h_name, k)); 920 921 return k; 922 } 923 924 InstanceKlass* SystemDictionary::resolve_from_stream(ClassFileStream* st, 925 Symbol* class_name, 926 Handle class_loader, 927 const ClassLoadInfo& cl_info, 928 TRAPS) { 929 if (cl_info.is_hidden()) { 930 return resolve_hidden_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL); 931 } else { 932 return resolve_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL); 933 } 934 } 935 936 937 #if INCLUDE_CDS 938 // Check if a shared class can be loaded by the specific classloader. 939 bool SystemDictionary::is_shared_class_visible(Symbol* class_name, 940 InstanceKlass* ik, 941 PackageEntry* pkg_entry, 942 Handle class_loader) { 943 assert(!Arguments::module_patching_disables_cds(), "Cannot use CDS"); 944 945 // (1) Check if we are loading into the same loader as in dump time. 946 947 if (ik->is_shared_boot_class()) { 948 if (class_loader() != nullptr) { 949 return false; 950 } 951 } else if (ik->is_shared_platform_class()) { 952 if (class_loader() != java_platform_loader()) { 953 return false; 954 } 955 } else if (ik->is_shared_app_class()) { 956 if (class_loader() != java_system_loader()) { 957 return false; 958 } 959 } else { 960 // ik was loaded by a custom loader during dump time 961 if (class_loader_data(class_loader)->is_builtin_class_loader_data()) { 962 return false; 963 } else { 964 return true; 965 } 966 } 967 968 // (2) Check if we are loading into the same module from the same location as in dump time. 969 970 if (MetaspaceShared::use_optimized_module_handling()) { 971 // Class visibility has not changed between dump time and run time, so a class 972 // that was visible (and thus archived) during dump time is always visible during runtime. 973 assert(SystemDictionary::is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader), 974 "visibility cannot change between dump time and runtime"); 975 return true; 976 } 977 return is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader); 978 } 979 980 bool SystemDictionary::is_shared_class_visible_impl(Symbol* class_name, 981 InstanceKlass* ik, 982 PackageEntry* pkg_entry, 983 Handle class_loader) { 984 int scp_index = ik->shared_classpath_index(); 985 assert(!ik->is_shared_unregistered_class(), "this function should be called for built-in classes only"); 986 assert(scp_index >= 0, "must be"); 987 SharedClassPathEntry* scp_entry = FileMapInfo::shared_path(scp_index); 988 if (!Universe::is_module_initialized()) { 989 assert(scp_entry != nullptr, "must be"); 990 // At this point, no modules have been defined yet. KlassSubGraphInfo::check_allowed_klass() 991 // has restricted the classes can be loaded at this step to be only: 992 // [1] scp_entry->is_modules_image(): classes in java.base, or, 993 // [2] HeapShared::is_a_test_class_in_unnamed_module(ik): classes in bootstrap/unnamed module 994 assert(scp_entry->is_modules_image() || HeapShared::is_a_test_class_in_unnamed_module(ik), 995 "only these classes can be loaded before the module system is initialized"); 996 assert(class_loader.is_null(), "sanity"); 997 return true; 998 } 999 1000 if (pkg_entry == nullptr) { 1001 // We might have looked up pkg_entry before the module system was initialized. 1002 // Need to reload it now. 1003 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name); 1004 if (pkg_name != nullptr) { 1005 pkg_entry = class_loader_data(class_loader)->packages()->lookup_only(pkg_name); 1006 } 1007 } 1008 1009 ModuleEntry* mod_entry = (pkg_entry == nullptr) ? nullptr : pkg_entry->module(); 1010 bool should_be_in_named_module = (mod_entry != nullptr && mod_entry->is_named()); 1011 bool was_archived_from_named_module = scp_entry->in_named_module(); 1012 bool visible; 1013 1014 if (was_archived_from_named_module) { 1015 if (should_be_in_named_module) { 1016 // Is the module loaded from the same location as during dump time? 1017 visible = mod_entry->shared_path_index() == scp_index; 1018 if (visible) { 1019 assert(!Arguments::module_patching_disables_cds(), "Cannot use CDS"); 1020 } 1021 } else { 1022 // During dump time, this class was in a named module, but at run time, this class should be 1023 // in an unnamed module. 1024 visible = false; 1025 } 1026 } else { 1027 if (should_be_in_named_module) { 1028 // During dump time, this class was in an unnamed, but at run time, this class should be 1029 // in a named module. 1030 visible = false; 1031 } else { 1032 visible = true; 1033 } 1034 } 1035 1036 return visible; 1037 } 1038 1039 bool SystemDictionary::check_shared_class_super_type(InstanceKlass* klass, InstanceKlass* super_type, 1040 Handle class_loader, Handle protection_domain, 1041 bool is_superclass, TRAPS) { 1042 assert(super_type->is_shared(), "must be"); 1043 1044 // Quick check if the super type has been already loaded. 1045 // + Don't do it for unregistered classes -- they can be unloaded so 1046 // super_type->class_loader_data() could be stale. 1047 // + Don't check if loader data is null, ie. the super_type isn't fully loaded. 1048 if (!super_type->is_shared_unregistered_class() && super_type->class_loader_data() != nullptr) { 1049 // Check if the superclass is loaded by the current class_loader 1050 Symbol* name = super_type->name(); 1051 InstanceKlass* check = find_instance_klass(THREAD, name, class_loader, protection_domain); 1052 if (check == super_type) { 1053 return true; 1054 } 1055 } 1056 1057 Klass *found = resolve_with_circularity_detection_or_fail(klass->name(), super_type->name(), 1058 class_loader, protection_domain, is_superclass, CHECK_0); 1059 if (found == super_type) { 1060 return true; 1061 } else { 1062 // The dynamically resolved super type is not the same as the one we used during dump time, 1063 // so we cannot use the class. 1064 return false; 1065 } 1066 } 1067 1068 bool SystemDictionary::check_shared_class_super_types(InstanceKlass* ik, Handle class_loader, 1069 Handle protection_domain, TRAPS) { 1070 // Check the superclass and interfaces. They must be the same 1071 // as in dump time, because the layout of <ik> depends on 1072 // the specific layout of ik->super() and ik->local_interfaces(). 1073 // 1074 // If unexpected superclass or interfaces are found, we cannot 1075 // load <ik> from the shared archive. 1076 1077 if (ik->super() != nullptr && 1078 !check_shared_class_super_type(ik, InstanceKlass::cast(ik->super()), 1079 class_loader, protection_domain, true, THREAD)) { 1080 return false; 1081 } 1082 1083 Array<InstanceKlass*>* interfaces = ik->local_interfaces(); 1084 int num_interfaces = interfaces->length(); 1085 for (int index = 0; index < num_interfaces; index++) { 1086 if (!check_shared_class_super_type(ik, interfaces->at(index), class_loader, protection_domain, false, THREAD)) { 1087 return false; 1088 } 1089 } 1090 1091 return true; 1092 } 1093 1094 InstanceKlass* SystemDictionary::load_shared_lambda_proxy_class(InstanceKlass* ik, 1095 Handle class_loader, 1096 Handle protection_domain, 1097 PackageEntry* pkg_entry, 1098 TRAPS) { 1099 InstanceKlass* shared_nest_host = SystemDictionaryShared::get_shared_nest_host(ik); 1100 assert(shared_nest_host->is_shared(), "nest host must be in CDS archive"); 1101 Symbol* cn = shared_nest_host->name(); 1102 Klass *s = resolve_or_fail(cn, class_loader, protection_domain, true, CHECK_NULL); 1103 if (s != shared_nest_host) { 1104 // The dynamically resolved nest_host is not the same as the one we used during dump time, 1105 // so we cannot use ik. 1106 return nullptr; 1107 } else { 1108 assert(s->is_shared(), "must be"); 1109 } 1110 1111 InstanceKlass* loaded_ik = load_shared_class(ik, class_loader, protection_domain, nullptr, pkg_entry, CHECK_NULL); 1112 1113 if (loaded_ik != nullptr) { 1114 assert(shared_nest_host->is_same_class_package(ik), 1115 "lambda proxy class and its nest host must be in the same package"); 1116 } 1117 1118 // The lambda proxy class and its nest host have the same class loader and class loader data, 1119 // as verified in SystemDictionaryShared::add_lambda_proxy_class() 1120 assert(shared_nest_host->class_loader() == class_loader(), "mismatched class loader"); 1121 assert(shared_nest_host->class_loader_data() == class_loader_data(class_loader), "mismatched class loader data"); 1122 ik->set_nest_host(shared_nest_host); 1123 1124 return loaded_ik; 1125 } 1126 1127 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik, 1128 Handle class_loader, 1129 Handle protection_domain, 1130 const ClassFileStream *cfs, 1131 PackageEntry* pkg_entry, 1132 TRAPS) { 1133 assert(ik != nullptr, "sanity"); 1134 assert(!ik->is_unshareable_info_restored(), "shared class can be restored only once"); 1135 assert(Atomic::add(&ik->_shared_class_load_count, 1) == 1, "shared class loaded more than once"); 1136 Symbol* class_name = ik->name(); 1137 1138 if (!is_shared_class_visible(class_name, ik, pkg_entry, class_loader)) { 1139 return nullptr; 1140 } 1141 1142 if (!check_shared_class_super_types(ik, class_loader, protection_domain, THREAD)) { 1143 return nullptr; 1144 } 1145 1146 if (ik->has_inline_type_fields()) { 1147 for (AllFieldStream fs(ik); !fs.done(); fs.next()) { 1148 if (fs.access_flags().is_static()) continue; 1149 Symbol* sig = fs.signature(); 1150 if (fs.is_null_free_inline_type()) { 1151 // Pre-load inline class 1152 TempNewSymbol name = Signature::strip_envelope(sig); 1153 Klass* real_k = SystemDictionary::resolve_with_circularity_detection_or_fail(ik->name(), name, 1154 class_loader, protection_domain, false, CHECK_NULL); 1155 Klass* k = ik->get_inline_type_field_klass_or_null(fs.index()); 1156 if (real_k != k) { 1157 // oops, the app has substituted a different version of k! 1158 return nullptr; 1159 } 1160 } else if (Signature::has_envelope(sig)) { 1161 TempNewSymbol name = Signature::strip_envelope(sig); 1162 if (name != ik->name() && ik->is_class_in_preload_attribute(name)) { 1163 Klass* real_k = SystemDictionary::resolve_with_circularity_detection_or_fail(ik->name(), name, 1164 class_loader, protection_domain, false, THREAD); 1165 if (HAS_PENDING_EXCEPTION) { 1166 CLEAR_PENDING_EXCEPTION; 1167 } 1168 Klass* k = ik->get_inline_type_field_klass_or_null(fs.index()); 1169 if (real_k != k) { 1170 // oops, the app has substituted a different version of k! 1171 return nullptr; 1172 } 1173 } 1174 } 1175 } 1176 } 1177 1178 InstanceKlass* new_ik = nullptr; 1179 // CFLH check is skipped for VM hidden classes (see KlassFactory::create_from_stream). 1180 // It will be skipped for shared VM hidden lambda proxy classes. 1181 if (!SystemDictionaryShared::is_hidden_lambda_proxy(ik)) { 1182 new_ik = KlassFactory::check_shared_class_file_load_hook( 1183 ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL); 1184 } 1185 if (new_ik != nullptr) { 1186 // The class is changed by CFLH. Return the new class. The shared class is 1187 // not used. 1188 return new_ik; 1189 } 1190 1191 // Adjust methods to recover missing data. They need addresses for 1192 // interpreter entry points and their default native method address 1193 // must be reset. 1194 1195 // Shared classes are all currently loaded by either the bootstrap or 1196 // internal parallel class loaders, so this will never cause a deadlock 1197 // on a custom class loader lock. 1198 // Since this class is already locked with parallel capable class 1199 // loaders, including the bootstrap loader via the placeholder table, 1200 // this lock is currently a nop. 1201 1202 ClassLoaderData* loader_data = class_loader_data(class_loader); 1203 { 1204 HandleMark hm(THREAD); 1205 Handle lockObject = get_loader_lock_or_null(class_loader); 1206 ObjectLocker ol(lockObject, THREAD); 1207 // prohibited package check assumes all classes loaded from archive call 1208 // restore_unshareable_info which calls ik->set_package() 1209 ik->restore_unshareable_info(loader_data, protection_domain, pkg_entry, CHECK_NULL); 1210 } 1211 1212 load_shared_class_misc(ik, loader_data); 1213 1214 return ik; 1215 } 1216 1217 void SystemDictionary::load_shared_class_misc(InstanceKlass* ik, ClassLoaderData* loader_data) { 1218 ik->print_class_load_logging(loader_data, nullptr, nullptr); 1219 1220 // For boot loader, ensure that GetSystemPackage knows that a class in this 1221 // package was loaded. 1222 if (loader_data->is_the_null_class_loader_data()) { 1223 s2 path_index = ik->shared_classpath_index(); 1224 ik->set_classpath_index(path_index); 1225 } 1226 1227 // notify a class loaded from shared object 1228 ClassLoadingService::notify_class_loaded(ik, true /* shared class */); 1229 } 1230 1231 #endif // INCLUDE_CDS 1232 1233 InstanceKlass* SystemDictionary::load_instance_class_impl(Symbol* class_name, Handle class_loader, TRAPS) { 1234 1235 if (class_loader.is_null()) { 1236 ResourceMark rm(THREAD); 1237 PackageEntry* pkg_entry = nullptr; 1238 bool search_only_bootloader_append = false; 1239 1240 // Find the package in the boot loader's package entry table. 1241 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name); 1242 if (pkg_name != nullptr) { 1243 pkg_entry = class_loader_data(class_loader)->packages()->lookup_only(pkg_name); 1244 } 1245 1246 // Prior to attempting to load the class, enforce the boot loader's 1247 // visibility boundaries. 1248 if (!Universe::is_module_initialized()) { 1249 // During bootstrapping, prior to module initialization, any 1250 // class attempting to be loaded must be checked against the 1251 // java.base packages in the boot loader's PackageEntryTable. 1252 // No class outside of java.base is allowed to be loaded during 1253 // this bootstrapping window. 1254 if (pkg_entry == nullptr || pkg_entry->in_unnamed_module()) { 1255 // Class is either in the unnamed package or in 1256 // a named package within the unnamed module. Either 1257 // case is outside of java.base, do not attempt to 1258 // load the class post java.base definition. If 1259 // java.base has not been defined, let the class load 1260 // and its package will be checked later by 1261 // ModuleEntryTable::verify_javabase_packages. 1262 if (ModuleEntryTable::javabase_defined()) { 1263 return nullptr; 1264 } 1265 } else { 1266 // Check that the class' package is defined within java.base. 1267 ModuleEntry* mod_entry = pkg_entry->module(); 1268 Symbol* mod_entry_name = mod_entry->name(); 1269 if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) { 1270 return nullptr; 1271 } 1272 } 1273 } else { 1274 // After the module system has been initialized, check if the class' 1275 // package is in a module defined to the boot loader. 1276 if (pkg_name == nullptr || pkg_entry == nullptr || pkg_entry->in_unnamed_module()) { 1277 // Class is either in the unnamed package, in a named package 1278 // within a module not defined to the boot loader or in a 1279 // a named package within the unnamed module. In all cases, 1280 // limit visibility to search for the class only in the boot 1281 // loader's append path. 1282 if (!ClassLoader::has_bootclasspath_append()) { 1283 // If there is no bootclasspath append entry, no need to continue 1284 // searching. 1285 return nullptr; 1286 } 1287 search_only_bootloader_append = true; 1288 } 1289 } 1290 1291 // Prior to bootstrapping's module initialization, never load a class outside 1292 // of the boot loader's module path 1293 assert(Universe::is_module_initialized() || 1294 !search_only_bootloader_append, 1295 "Attempt to load a class outside of boot loader's module path"); 1296 1297 // Search for classes in the CDS archive. 1298 InstanceKlass* k = nullptr; 1299 1300 #if INCLUDE_CDS 1301 if (UseSharedSpaces) 1302 { 1303 PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time()); 1304 InstanceKlass* ik = SystemDictionaryShared::find_builtin_class(class_name); 1305 if (ik != nullptr && ik->is_shared_boot_class() && !ik->shared_loading_failed()) { 1306 SharedClassLoadingMark slm(THREAD, ik); 1307 k = load_shared_class(ik, class_loader, Handle(), nullptr, pkg_entry, CHECK_NULL); 1308 } 1309 } 1310 #endif 1311 1312 if (k == nullptr) { 1313 // Use VM class loader 1314 PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time()); 1315 k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL); 1316 } 1317 1318 // find_or_define_instance_class may return a different InstanceKlass 1319 if (k != nullptr) { 1320 CDS_ONLY(SharedClassLoadingMark slm(THREAD, k);) 1321 k = find_or_define_instance_class(class_name, class_loader, k, CHECK_NULL); 1322 } 1323 return k; 1324 } else { 1325 // Use user specified class loader to load class. Call loadClass operation on class_loader. 1326 ResourceMark rm(THREAD); 1327 1328 JavaThread* jt = THREAD; 1329 1330 PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(), 1331 ClassLoader::perf_app_classload_selftime(), 1332 ClassLoader::perf_app_classload_count(), 1333 jt->get_thread_stat()->perf_recursion_counts_addr(), 1334 jt->get_thread_stat()->perf_timers_addr(), 1335 PerfClassTraceTime::CLASS_LOAD); 1336 1337 // Translate to external class name format, i.e., convert '/' chars to '.' 1338 Handle string = java_lang_String::externalize_classname(class_name, CHECK_NULL); 1339 1340 JavaValue result(T_OBJECT); 1341 1342 InstanceKlass* spec_klass = vmClasses::ClassLoader_klass(); 1343 1344 // Call public unsynchronized loadClass(String) directly for all class loaders. 1345 // For parallelCapable class loaders, JDK >=7, loadClass(String, boolean) will 1346 // acquire a class-name based lock rather than the class loader object lock. 1347 // JDK < 7 already acquire the class loader lock in loadClass(String, boolean). 1348 JavaCalls::call_virtual(&result, 1349 class_loader, 1350 spec_klass, 1351 vmSymbols::loadClass_name(), 1352 vmSymbols::string_class_signature(), 1353 string, 1354 CHECK_NULL); 1355 1356 assert(result.get_type() == T_OBJECT, "just checking"); 1357 oop obj = result.get_oop(); 1358 1359 // Primitive classes return null since forName() can not be 1360 // used to obtain any of the Class objects representing primitives or void 1361 if ((obj != nullptr) && !(java_lang_Class::is_primitive(obj))) { 1362 InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj)); 1363 // For user defined Java class loaders, check that the name returned is 1364 // the same as that requested. This check is done for the bootstrap 1365 // loader when parsing the class file. 1366 if (class_name == k->name()) { 1367 return k; 1368 } 1369 } 1370 // Class is not found or has the wrong name, return null 1371 return nullptr; 1372 } 1373 } 1374 1375 InstanceKlass* SystemDictionary::load_instance_class(Symbol* name, 1376 Handle class_loader, 1377 TRAPS) { 1378 1379 InstanceKlass* loaded_class = load_instance_class_impl(name, class_loader, CHECK_NULL); 1380 1381 // If everything was OK (no exceptions, no null return value), and 1382 // class_loader is NOT the defining loader, do a little more bookkeeping. 1383 if (loaded_class != nullptr && 1384 loaded_class->class_loader() != class_loader()) { 1385 1386 ClassLoaderData* loader_data = class_loader_data(class_loader); 1387 check_constraints(loaded_class, loader_data, false, CHECK_NULL); 1388 1389 // Record dependency for non-parent delegation. 1390 // This recording keeps the defining class loader of the klass (loaded_class) found 1391 // from being unloaded while the initiating class loader is loaded 1392 // even if the reference to the defining class loader is dropped 1393 // before references to the initiating class loader. 1394 loader_data->record_dependency(loaded_class); 1395 1396 update_dictionary(THREAD, loaded_class, loader_data); 1397 1398 if (JvmtiExport::should_post_class_load()) { 1399 JvmtiExport::post_class_load(THREAD, loaded_class); 1400 } 1401 } 1402 return loaded_class; 1403 } 1404 1405 static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) { 1406 EventClassDefine event; 1407 if (event.should_commit()) { 1408 event.set_definedClass(k); 1409 event.set_definingClassLoader(def_cld); 1410 event.commit(); 1411 } 1412 } 1413 1414 void SystemDictionary::define_instance_class(InstanceKlass* k, Handle class_loader, TRAPS) { 1415 1416 ClassLoaderData* loader_data = k->class_loader_data(); 1417 assert(loader_data->class_loader() == class_loader(), "they must be the same"); 1418 1419 // Bootstrap and other parallel classloaders don't acquire a lock, 1420 // they use placeholder token. 1421 // If a parallelCapable class loader calls define_instance_class instead of 1422 // find_or_define_instance_class to get here, we have a timing 1423 // hole with systemDictionary updates and check_constraints 1424 if (!is_parallelCapable(class_loader)) { 1425 assert(ObjectSynchronizer::current_thread_holds_lock(THREAD, 1426 get_loader_lock_or_null(class_loader)), 1427 "define called without lock"); 1428 } 1429 1430 // Check class-loading constraints. Throw exception if violation is detected. 1431 // Grabs and releases SystemDictionary_lock 1432 // The check_constraints/find_class call and update_dictionary sequence 1433 // must be "atomic" for a specific class/classloader pair so we never 1434 // define two different instanceKlasses for that class/classloader pair. 1435 // Existing classloaders will call define_instance_class with the 1436 // classloader lock held 1437 // Parallel classloaders will call find_or_define_instance_class 1438 // which will require a token to perform the define class 1439 check_constraints(k, loader_data, true, CHECK); 1440 1441 // Register class just loaded with class loader (placed in ArrayList) 1442 // Note we do this before updating the dictionary, as this can 1443 // fail with an OutOfMemoryError (if it does, we will *not* put this 1444 // class in the dictionary and will not update the class hierarchy). 1445 // JVMTI FollowReferences needs to find the classes this way. 1446 if (k->class_loader() != nullptr) { 1447 methodHandle m(THREAD, Universe::loader_addClass_method()); 1448 JavaValue result(T_VOID); 1449 JavaCallArguments args(class_loader); 1450 args.push_oop(Handle(THREAD, k->java_mirror())); 1451 JavaCalls::call(&result, m, &args, CHECK); 1452 } 1453 1454 // Add to class hierarchy, and do possible deoptimizations. 1455 k->add_to_hierarchy(THREAD); 1456 1457 // Add to systemDictionary - so other classes can see it. 1458 // Grabs and releases SystemDictionary_lock 1459 update_dictionary(THREAD, k, loader_data); 1460 1461 // notify jvmti 1462 if (JvmtiExport::should_post_class_load()) { 1463 JvmtiExport::post_class_load(THREAD, k); 1464 } 1465 post_class_define_event(k, loader_data); 1466 } 1467 1468 // Support parallel classloading 1469 // All parallel class loaders, including bootstrap classloader 1470 // lock a placeholder entry for this class/class_loader pair 1471 // to allow parallel defines of different classes for this class loader 1472 // With AllowParallelDefine flag==true, in case they do not synchronize around 1473 // FindLoadedClass/DefineClass, calls, we check for parallel 1474 // loading for them, wait if a defineClass is in progress 1475 // and return the initial requestor's results 1476 // This flag does not apply to the bootstrap classloader. 1477 // With AllowParallelDefine flag==false, call through to define_instance_class 1478 // which will throw LinkageError: duplicate class definition. 1479 // False is the requested default. 1480 // For better performance, the class loaders should synchronize 1481 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they 1482 // potentially waste time reading and parsing the bytestream. 1483 // Note: VM callers should ensure consistency of k/class_name,class_loader 1484 // Be careful when modifying this code: once you have run 1485 // PlaceholderTable::find_and_add(PlaceholderTable::DEFINE_CLASS), 1486 // you need to find_and_remove it before returning. 1487 // So be careful to not exit with a CHECK_ macro between these calls. 1488 InstanceKlass* SystemDictionary::find_or_define_helper(Symbol* class_name, Handle class_loader, 1489 InstanceKlass* k, TRAPS) { 1490 1491 Symbol* name_h = k->name(); 1492 ClassLoaderData* loader_data = class_loader_data(class_loader); 1493 Dictionary* dictionary = loader_data->dictionary(); 1494 1495 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS 1496 { 1497 MutexLocker mu(THREAD, SystemDictionary_lock); 1498 // First check if class already defined 1499 if (is_parallelDefine(class_loader)) { 1500 InstanceKlass* check = dictionary->find_class(THREAD, name_h); 1501 if (check != nullptr) { 1502 return check; 1503 } 1504 } 1505 1506 // Acquire define token for this class/classloader 1507 PlaceholderEntry* probe = PlaceholderTable::find_and_add(name_h, loader_data, 1508 PlaceholderTable::DEFINE_CLASS, nullptr, THREAD); 1509 // Wait if another thread defining in parallel 1510 // All threads wait - even those that will throw duplicate class: otherwise 1511 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails 1512 // if other thread has not finished updating dictionary 1513 while (probe->definer() != nullptr) { 1514 SystemDictionary_lock->wait(); 1515 } 1516 // Only special cases allow parallel defines and can use other thread's results 1517 // Other cases fall through, and may run into duplicate defines 1518 // caught by finding an entry in the SystemDictionary 1519 if (is_parallelDefine(class_loader) && (probe->instance_klass() != nullptr)) { 1520 InstanceKlass* ik = probe->instance_klass(); 1521 PlaceholderTable::find_and_remove(name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1522 SystemDictionary_lock->notify_all(); 1523 #ifdef ASSERT 1524 InstanceKlass* check = dictionary->find_class(THREAD, name_h); 1525 assert(check != nullptr, "definer missed recording success"); 1526 #endif 1527 return ik; 1528 } else { 1529 // This thread will define the class (even if earlier thread tried and had an error) 1530 probe->set_definer(THREAD); 1531 } 1532 } 1533 1534 define_instance_class(k, class_loader, THREAD); 1535 1536 // definer must notify any waiting threads 1537 { 1538 MutexLocker mu(THREAD, SystemDictionary_lock); 1539 PlaceholderEntry* probe = PlaceholderTable::get_entry(name_h, loader_data); 1540 assert(probe != nullptr, "DEFINE_CLASS placeholder lost?"); 1541 if (!HAS_PENDING_EXCEPTION) { 1542 probe->set_instance_klass(k); 1543 } 1544 probe->set_definer(nullptr); 1545 PlaceholderTable::find_and_remove(name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1546 SystemDictionary_lock->notify_all(); 1547 } 1548 1549 return HAS_PENDING_EXCEPTION ? nullptr : k; 1550 } 1551 1552 // If a class loader supports parallel classloading handle parallel define requests. 1553 // find_or_define_instance_class may return a different InstanceKlass 1554 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, 1555 InstanceKlass* k, TRAPS) { 1556 InstanceKlass* defined_k = find_or_define_helper(class_name, class_loader, k, THREAD); 1557 // Clean up original InstanceKlass if duplicate or error 1558 if (!HAS_PENDING_EXCEPTION && defined_k != k) { 1559 // If a parallel capable class loader already defined this class, register 'k' for cleanup. 1560 assert(defined_k != nullptr, "Should have a klass if there's no exception"); 1561 k->class_loader_data()->add_to_deallocate_list(k); 1562 } else if (HAS_PENDING_EXCEPTION) { 1563 // Remove this InstanceKlass from the LoaderConstraintTable if added. 1564 LoaderConstraintTable::remove_failed_loaded_klass(k, class_loader_data(class_loader)); 1565 assert(defined_k == nullptr, "Should not have a klass if there's an exception"); 1566 k->class_loader_data()->add_to_deallocate_list(k); 1567 } 1568 return defined_k; 1569 } 1570 1571 1572 // ---------------------------------------------------------------------------- 1573 // GC support 1574 1575 // Assumes classes in the SystemDictionary are only unloaded at a safepoint 1576 bool SystemDictionary::do_unloading(GCTimer* gc_timer) { 1577 1578 bool unloading_occurred; 1579 bool is_concurrent = !SafepointSynchronize::is_at_safepoint(); 1580 { 1581 GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer); 1582 assert_locked_or_safepoint(ClassLoaderDataGraph_lock); // caller locks. 1583 // First, mark for unload all ClassLoaderData referencing a dead class loader. 1584 unloading_occurred = ClassLoaderDataGraph::do_unloading(); 1585 if (unloading_occurred) { 1586 ConditionalMutexLocker ml2(Module_lock, is_concurrent); 1587 JFR_ONLY(Jfr::on_unloading_classes();) 1588 MANAGEMENT_ONLY(FinalizerService::purge_unloaded();) 1589 ConditionalMutexLocker ml1(SystemDictionary_lock, is_concurrent); 1590 ClassLoaderDataGraph::clean_module_and_package_info(); 1591 LoaderConstraintTable::purge_loader_constraints(); 1592 ResolutionErrorTable::purge_resolution_errors(); 1593 } 1594 } 1595 1596 GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer); 1597 1598 if (unloading_occurred) { 1599 SymbolTable::trigger_cleanup(); 1600 1601 if (java_lang_System::allow_security_manager()) { 1602 // Oops referenced by the protection domain cache table may get unreachable independently 1603 // of the class loader (eg. cached protection domain oops). So we need to 1604 // explicitly unlink them here. 1605 // All protection domain oops are linked to the caller class, so if nothing 1606 // unloads, this is not needed. 1607 ProtectionDomainCacheTable::trigger_cleanup(); 1608 } else { 1609 assert(ProtectionDomainCacheTable::number_of_entries() == 0, "should be empty"); 1610 } 1611 1612 ConditionalMutexLocker ml(ClassInitError_lock, is_concurrent); 1613 InstanceKlass::clean_initialization_error_table(); 1614 } 1615 1616 return unloading_occurred; 1617 } 1618 1619 void SystemDictionary::methods_do(void f(Method*)) { 1620 // Walk methods in loaded classes 1621 1622 { 1623 MutexLocker ml(ClassLoaderDataGraph_lock); 1624 ClassLoaderDataGraph::methods_do(f); 1625 } 1626 1627 auto doit = [&] (InvokeMethodKey key, Method* method) { 1628 if (method != nullptr) { 1629 f(method); 1630 } 1631 }; 1632 1633 { 1634 MutexLocker ml(InvokeMethodIntrinsicTable_lock); 1635 _invoke_method_intrinsic_table->iterate_all(doit); 1636 } 1637 1638 } 1639 1640 // ---------------------------------------------------------------------------- 1641 // Initialization 1642 1643 void SystemDictionary::initialize(TRAPS) { 1644 _invoke_method_intrinsic_table = new (mtClass) InvokeMethodIntrinsicTable(); 1645 _invoke_method_type_table = new (mtClass) InvokeMethodTypeTable(); 1646 ResolutionErrorTable::initialize(); 1647 LoaderConstraintTable::initialize(); 1648 PlaceholderTable::initialize(); 1649 ProtectionDomainCacheTable::initialize(); 1650 #if INCLUDE_CDS 1651 SystemDictionaryShared::initialize(); 1652 #endif 1653 // Resolve basic classes 1654 vmClasses::resolve_all(CHECK); 1655 // Resolve classes used by archived heap objects 1656 if (UseSharedSpaces) { 1657 HeapShared::resolve_classes(THREAD); 1658 } 1659 } 1660 1661 // Constraints on class loaders. The details of the algorithm can be 1662 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java 1663 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is 1664 // that the dictionary needs to maintain a set of constraints that 1665 // must be satisfied by all classes in the dictionary. 1666 // if defining is true, then LinkageError if already in dictionary 1667 // if initiating loader, then ok if InstanceKlass matches existing entry 1668 1669 void SystemDictionary::check_constraints(InstanceKlass* k, 1670 ClassLoaderData* loader_data, 1671 bool defining, 1672 TRAPS) { 1673 ResourceMark rm(THREAD); 1674 stringStream ss; 1675 bool throwException = false; 1676 1677 { 1678 Symbol* name = k->name(); 1679 1680 MutexLocker mu(THREAD, SystemDictionary_lock); 1681 1682 InstanceKlass* check = loader_data->dictionary()->find_class(THREAD, name); 1683 if (check != nullptr) { 1684 // If different InstanceKlass - duplicate class definition, 1685 // else - ok, class loaded by a different thread in parallel. 1686 // We should only have found it if it was done loading and ok to use. 1687 1688 if ((defining == true) || (k != check)) { 1689 throwException = true; 1690 ss.print("loader %s", loader_data->loader_name_and_id()); 1691 ss.print(" attempted duplicate %s definition for %s. (%s)", 1692 k->external_kind(), k->external_name(), k->class_in_module_of_loader(false, true)); 1693 } else { 1694 return; 1695 } 1696 } 1697 1698 if (throwException == false) { 1699 if (LoaderConstraintTable::check_or_update(k, loader_data, name) == false) { 1700 throwException = true; 1701 ss.print("loader constraint violation: loader %s", loader_data->loader_name_and_id()); 1702 ss.print(" wants to load %s %s.", 1703 k->external_kind(), k->external_name()); 1704 Klass *existing_klass = LoaderConstraintTable::find_constrained_klass(name, loader_data); 1705 if (existing_klass != nullptr && existing_klass->class_loader_data() != loader_data) { 1706 ss.print(" A different %s with the same name was previously loaded by %s. (%s)", 1707 existing_klass->external_kind(), 1708 existing_klass->class_loader_data()->loader_name_and_id(), 1709 existing_klass->class_in_module_of_loader(false, true)); 1710 } else { 1711 ss.print(" (%s)", k->class_in_module_of_loader(false, true)); 1712 } 1713 } 1714 } 1715 } 1716 1717 // Throw error now if needed (cannot throw while holding 1718 // SystemDictionary_lock because of rank ordering) 1719 if (throwException == true) { 1720 THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string()); 1721 } 1722 } 1723 1724 // Update class loader data dictionary - done after check_constraint and add_to_hierarchy 1725 // have been called. 1726 void SystemDictionary::update_dictionary(JavaThread* current, 1727 InstanceKlass* k, 1728 ClassLoaderData* loader_data) { 1729 MonitorLocker mu1(SystemDictionary_lock); 1730 1731 // Make a new dictionary entry. 1732 Symbol* name = k->name(); 1733 Dictionary* dictionary = loader_data->dictionary(); 1734 InstanceKlass* sd_check = dictionary->find_class(current, name); 1735 if (sd_check == nullptr) { 1736 dictionary->add_klass(current, name, k); 1737 } 1738 mu1.notify_all(); 1739 } 1740 1741 1742 // Try to find a class name using the loader constraints. The 1743 // loader constraints might know about a class that isn't fully loaded 1744 // yet and these will be ignored. 1745 Klass* SystemDictionary::find_constrained_instance_or_array_klass( 1746 Thread* current, Symbol* class_name, Handle class_loader) { 1747 1748 // First see if it has been loaded directly. 1749 // Force the protection domain to be null. (This removes protection checks.) 1750 Handle no_protection_domain; 1751 Klass* klass = find_instance_or_array_klass(current, class_name, class_loader, 1752 no_protection_domain); 1753 if (klass != nullptr) 1754 return klass; 1755 1756 // Now look to see if it has been loaded elsewhere, and is subject to 1757 // a loader constraint that would require this loader to return the 1758 // klass that is already loaded. 1759 if (Signature::is_array(class_name)) { 1760 // For array classes, their Klass*s are not kept in the 1761 // constraint table. The element Klass*s are. 1762 SignatureStream ss(class_name, false); 1763 int ndims = ss.skip_array_prefix(); // skip all '['s 1764 BasicType t = ss.type(); 1765 if (t != T_OBJECT) { 1766 klass = Universe::typeArrayKlassObj(t); 1767 } else { 1768 MutexLocker mu(current, SystemDictionary_lock); 1769 klass = LoaderConstraintTable::find_constrained_klass(ss.as_symbol(), class_loader_data(class_loader)); 1770 } 1771 // If element class already loaded, allocate array klass 1772 if (klass != nullptr) { 1773 klass = klass->array_klass_or_null(ndims); 1774 } 1775 } else { 1776 MutexLocker mu(current, SystemDictionary_lock); 1777 // Non-array classes are easy: simply check the constraint table. 1778 klass = LoaderConstraintTable::find_constrained_klass(class_name, class_loader_data(class_loader)); 1779 } 1780 1781 return klass; 1782 } 1783 1784 bool SystemDictionary::add_loader_constraint(Symbol* class_name, 1785 Klass* klass_being_linked, 1786 Handle class_loader1, 1787 Handle class_loader2) { 1788 ClassLoaderData* loader_data1 = class_loader_data(class_loader1); 1789 ClassLoaderData* loader_data2 = class_loader_data(class_loader2); 1790 1791 Symbol* constraint_name = nullptr; 1792 1793 if (!Signature::is_array(class_name)) { 1794 constraint_name = class_name; 1795 } else { 1796 // For array classes, their Klass*s are not kept in the 1797 // constraint table. The element classes are. 1798 SignatureStream ss(class_name, false); 1799 ss.skip_array_prefix(); // skip all '['s 1800 if (!ss.has_envelope()) { 1801 return true; // primitive types always pass 1802 } 1803 constraint_name = ss.as_symbol(); 1804 // Increment refcount to keep constraint_name alive after 1805 // SignatureStream is destructed. It will be decremented below 1806 // before returning. 1807 constraint_name->increment_refcount(); 1808 } 1809 1810 Dictionary* dictionary1 = loader_data1->dictionary(); 1811 Dictionary* dictionary2 = loader_data2->dictionary(); 1812 1813 JavaThread* current = JavaThread::current(); 1814 { 1815 MutexLocker mu_s(SystemDictionary_lock); 1816 InstanceKlass* klass1 = dictionary1->find_class(current, constraint_name); 1817 InstanceKlass* klass2 = dictionary2->find_class(current, constraint_name); 1818 bool result = LoaderConstraintTable::add_entry(constraint_name, klass1, loader_data1, 1819 klass2, loader_data2); 1820 #if INCLUDE_CDS 1821 if (CDSConfig::is_dumping_archive() && klass_being_linked != nullptr && 1822 !klass_being_linked->is_shared()) { 1823 SystemDictionaryShared::record_linking_constraint(constraint_name, 1824 InstanceKlass::cast(klass_being_linked), 1825 class_loader1, class_loader2); 1826 } 1827 #endif // INCLUDE_CDS 1828 if (Signature::is_array(class_name)) { 1829 constraint_name->decrement_refcount(); 1830 } 1831 return result; 1832 } 1833 } 1834 1835 // Add entry to resolution error table to record the error when the first 1836 // attempt to resolve a reference to a class has failed. 1837 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which, 1838 Symbol* error, Symbol* message, 1839 Symbol* cause, Symbol* cause_msg) { 1840 { 1841 MutexLocker ml(Thread::current(), SystemDictionary_lock); 1842 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which); 1843 if (entry == nullptr) { 1844 ResolutionErrorTable::add_entry(pool, which, error, message, cause, cause_msg); 1845 } 1846 } 1847 } 1848 1849 // Delete a resolution error for RedefineClasses for a constant pool is going away 1850 void SystemDictionary::delete_resolution_error(ConstantPool* pool) { 1851 ResolutionErrorTable::delete_entry(pool); 1852 } 1853 1854 // Lookup resolution error table. Returns error if found, otherwise null. 1855 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which, 1856 Symbol** message, Symbol** cause, Symbol** cause_msg) { 1857 1858 { 1859 MutexLocker ml(Thread::current(), SystemDictionary_lock); 1860 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which); 1861 if (entry != nullptr) { 1862 *message = entry->message(); 1863 *cause = entry->cause(); 1864 *cause_msg = entry->cause_msg(); 1865 return entry->error(); 1866 } else { 1867 return nullptr; 1868 } 1869 } 1870 } 1871 1872 // Add an entry to resolution error table to record an error in resolving or 1873 // validating a nest host. This is used to construct informative error 1874 // messages when IllegalAccessError's occur. If an entry already exists it will 1875 // be updated with the nest host error message. 1876 1877 void SystemDictionary::add_nest_host_error(const constantPoolHandle& pool, 1878 int which, 1879 const char* message) { 1880 { 1881 MutexLocker ml(Thread::current(), SystemDictionary_lock); 1882 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which); 1883 if (entry != nullptr && entry->nest_host_error() == nullptr) { 1884 // An existing entry means we had a true resolution failure (LinkageError) with our nest host, but we 1885 // still want to add the error message for the higher-level access checks to report. We should 1886 // only reach here under the same error condition, so we can ignore the potential race with setting 1887 // the message. If we see it is already set then we can ignore it. 1888 entry->set_nest_host_error(message); 1889 } else { 1890 ResolutionErrorTable::add_entry(pool, which, message); 1891 } 1892 } 1893 } 1894 1895 // Lookup any nest host error 1896 const char* SystemDictionary::find_nest_host_error(const constantPoolHandle& pool, int which) { 1897 { 1898 MutexLocker ml(Thread::current(), SystemDictionary_lock); 1899 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which); 1900 if (entry != nullptr) { 1901 return entry->nest_host_error(); 1902 } else { 1903 return nullptr; 1904 } 1905 } 1906 } 1907 1908 // Signature constraints ensure that callers and callees agree about 1909 // the meaning of type names in their signatures. This routine is the 1910 // intake for constraints. It collects them from several places: 1911 // 1912 // * LinkResolver::resolve_method (if check_access is true) requires 1913 // that the resolving class (the caller) and the defining class of 1914 // the resolved method (the callee) agree on each type in the 1915 // method's signature. 1916 // 1917 // * LinkResolver::resolve_interface_method performs exactly the same 1918 // checks. 1919 // 1920 // * LinkResolver::resolve_field requires that the constant pool 1921 // attempting to link to a field agree with the field's defining 1922 // class about the type of the field signature. 1923 // 1924 // * klassVtable::initialize_vtable requires that, when a class 1925 // overrides a vtable entry allocated by a superclass, that the 1926 // overriding method (i.e., the callee) agree with the superclass 1927 // on each type in the method's signature. 1928 // 1929 // * klassItable::initialize_itable requires that, when a class fills 1930 // in its itables, for each non-abstract method installed in an 1931 // itable, the method (i.e., the callee) agree with the interface 1932 // on each type in the method's signature. 1933 // 1934 // All those methods have a boolean (check_access, checkconstraints) 1935 // which turns off the checks. This is used from specialized contexts 1936 // such as bootstrapping, dumping, and debugging. 1937 // 1938 // No direct constraint is placed between the class and its 1939 // supertypes. Constraints are only placed along linked relations 1940 // between callers and callees. When a method overrides or implements 1941 // an abstract method in a supertype (superclass or interface), the 1942 // constraints are placed as if the supertype were the caller to the 1943 // overriding method. (This works well, since callers to the 1944 // supertype have already established agreement between themselves and 1945 // the supertype.) As a result of all this, a class can disagree with 1946 // its supertype about the meaning of a type name, as long as that 1947 // class neither calls a relevant method of the supertype, nor is 1948 // called (perhaps via an override) from the supertype. 1949 // 1950 // 1951 // SystemDictionary::check_signature_loaders(sig, klass_being_linked, l1, l2) 1952 // 1953 // Make sure all class components (including arrays) in the given 1954 // signature will be resolved to the same class in both loaders. 1955 // Returns the name of the type that failed a loader constraint check, or 1956 // null if no constraint failed. No exception except OOME is thrown. 1957 // Arrays are not added to the loader constraint table, their elements are. 1958 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature, 1959 Klass* klass_being_linked, 1960 Handle loader1, Handle loader2, 1961 bool is_method) { 1962 // Nothing to do if loaders are the same. 1963 if (loader1() == loader2()) { 1964 return nullptr; 1965 } 1966 1967 for (SignatureStream ss(signature, is_method); !ss.is_done(); ss.next()) { 1968 if (ss.is_reference()) { 1969 Symbol* sig = ss.as_symbol(); 1970 // Note: In the future, if template-like types can take 1971 // arguments, we will want to recognize them and dig out class 1972 // names hiding inside the argument lists. 1973 if (!add_loader_constraint(sig, klass_being_linked, loader1, loader2)) { 1974 return sig; 1975 } 1976 } 1977 } 1978 return nullptr; 1979 } 1980 1981 Method* SystemDictionary::find_method_handle_intrinsic(vmIntrinsicID iid, 1982 Symbol* signature, 1983 TRAPS) { 1984 1985 const int iid_as_int = vmIntrinsics::as_int(iid); 1986 assert(MethodHandles::is_signature_polymorphic(iid) && 1987 MethodHandles::is_signature_polymorphic_intrinsic(iid) && 1988 iid != vmIntrinsics::_invokeGeneric, 1989 "must be a known MH intrinsic iid=%d: %s", iid_as_int, vmIntrinsics::name_at(iid)); 1990 1991 InvokeMethodKey key(signature, iid_as_int); 1992 Method** met = nullptr; 1993 1994 // We only want one entry in the table for this (signature/id, method) pair but the code 1995 // to create the intrinsic method needs to be outside the lock. 1996 // The first thread claims the entry by adding the key and the other threads wait, until the 1997 // Method has been added as the value. 1998 { 1999 MonitorLocker ml(THREAD, InvokeMethodIntrinsicTable_lock); 2000 while (true) { 2001 bool created; 2002 met = _invoke_method_intrinsic_table->put_if_absent(key, &created); 2003 assert(met != nullptr, "either created or found"); 2004 if (*met != nullptr) { 2005 return *met; 2006 } else if (created) { 2007 // The current thread won the race and will try to create the full entry. 2008 break; 2009 } else { 2010 // Another thread beat us to it, so wait for them to complete 2011 // and return *met; or if they hit an error we get another try. 2012 ml.wait(); 2013 // Note it is not safe to read *met here as that entry could have 2014 // been deleted, so we must loop and try put_if_absent again. 2015 } 2016 } 2017 } 2018 2019 methodHandle m = Method::make_method_handle_intrinsic(iid, signature, THREAD); 2020 bool throw_error = HAS_PENDING_EXCEPTION; 2021 if (!throw_error && (!Arguments::is_interpreter_only() || iid == vmIntrinsics::_linkToNative)) { 2022 // Generate a compiled form of the MH intrinsic 2023 // linkToNative doesn't have interpreter-specific implementation, so always has to go through compiled version. 2024 AdapterHandlerLibrary::create_native_wrapper(m); 2025 // Check if have the compiled code. 2026 throw_error = (!m->has_compiled_code()); 2027 } 2028 2029 { 2030 MonitorLocker ml(THREAD, InvokeMethodIntrinsicTable_lock); 2031 if (throw_error) { 2032 // Remove the entry and let another thread try, or get the same exception. 2033 bool removed = _invoke_method_intrinsic_table->remove(key); 2034 assert(removed, "must be the owner"); 2035 ml.notify_all(); 2036 } else { 2037 signature->make_permanent(); // The signature is never unloaded. 2038 assert(Arguments::is_interpreter_only() || (m->has_compiled_code() && 2039 m->code()->entry_point() == m->from_compiled_entry()), 2040 "MH intrinsic invariant"); 2041 *met = m(); // insert the element 2042 ml.notify_all(); 2043 return m(); 2044 } 2045 } 2046 2047 // Throw VirtualMachineError or the pending exception in the JavaThread 2048 if (throw_error && !HAS_PENDING_EXCEPTION) { 2049 THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), 2050 "Out of space in CodeCache for method handle intrinsic"); 2051 } 2052 return nullptr; 2053 } 2054 2055 // Helper for unpacking the return value from linkMethod and linkCallSite. 2056 static Method* unpack_method_and_appendix(Handle mname, 2057 Klass* accessing_klass, 2058 objArrayHandle appendix_box, 2059 Handle* appendix_result, 2060 TRAPS) { 2061 if (mname.not_null()) { 2062 Method* m = java_lang_invoke_MemberName::vmtarget(mname()); 2063 if (m != nullptr) { 2064 oop appendix = appendix_box->obj_at(0); 2065 LogTarget(Info, methodhandles) lt; 2066 if (lt.develop_is_enabled()) { 2067 ResourceMark rm(THREAD); 2068 LogStream ls(lt); 2069 ls.print("Linked method=" INTPTR_FORMAT ": ", p2i(m)); 2070 m->print_on(&ls); 2071 if (appendix != nullptr) { ls.print("appendix = "); appendix->print_on(&ls); } 2072 ls.cr(); 2073 } 2074 2075 (*appendix_result) = Handle(THREAD, appendix); 2076 // the target is stored in the cpCache and if a reference to this 2077 // MemberName is dropped we need a way to make sure the 2078 // class_loader containing this method is kept alive. 2079 methodHandle mh(THREAD, m); // record_dependency can safepoint. 2080 ClassLoaderData* this_key = accessing_klass->class_loader_data(); 2081 this_key->record_dependency(m->method_holder()); 2082 return mh(); 2083 } 2084 } 2085 THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives"); 2086 } 2087 2088 Method* SystemDictionary::find_method_handle_invoker(Klass* klass, 2089 Symbol* name, 2090 Symbol* signature, 2091 Klass* accessing_klass, 2092 Handle* appendix_result, 2093 TRAPS) { 2094 guarantee(THREAD->can_call_java(), ""); 2095 Handle method_type = 2096 SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL); 2097 2098 int ref_kind = JVM_REF_invokeVirtual; 2099 oop name_oop = StringTable::intern(name, CHECK_NULL); 2100 Handle name_str (THREAD, name_oop); 2101 objArrayHandle appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK_NULL); 2102 assert(appendix_box->obj_at(0) == nullptr, ""); 2103 2104 // This should not happen. JDK code should take care of that. 2105 if (accessing_klass == nullptr || method_type.is_null()) { 2106 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle"); 2107 } 2108 2109 // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName 2110 JavaCallArguments args; 2111 args.push_oop(Handle(THREAD, accessing_klass->java_mirror())); 2112 args.push_int(ref_kind); 2113 args.push_oop(Handle(THREAD, klass->java_mirror())); 2114 args.push_oop(name_str); 2115 args.push_oop(method_type); 2116 args.push_oop(appendix_box); 2117 JavaValue result(T_OBJECT); 2118 JavaCalls::call_static(&result, 2119 vmClasses::MethodHandleNatives_klass(), 2120 vmSymbols::linkMethod_name(), 2121 vmSymbols::linkMethod_signature(), 2122 &args, CHECK_NULL); 2123 Handle mname(THREAD, result.get_oop()); 2124 return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD); 2125 } 2126 2127 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks. 2128 // We must ensure that all class loaders everywhere will reach this class, for any client. 2129 // This is a safe bet for public classes in java.lang, such as Object and String. 2130 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types. 2131 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util. 2132 static bool is_always_visible_class(oop mirror) { 2133 Klass* klass = java_lang_Class::as_Klass(mirror); 2134 if (klass->is_objArray_klass()) { 2135 klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type 2136 } 2137 if (klass->is_typeArray_klass()) { 2138 return true; // primitive array 2139 } 2140 assert(klass->is_instance_klass(), "%s", klass->external_name()); 2141 return klass->is_public() && 2142 (InstanceKlass::cast(klass)->is_same_class_package(vmClasses::Object_klass()) || // java.lang 2143 InstanceKlass::cast(klass)->is_same_class_package(vmClasses::MethodHandle_klass())); // java.lang.invoke 2144 } 2145 2146 // Find or construct the Java mirror (java.lang.Class instance) for 2147 // the given field type signature, as interpreted relative to the 2148 // given class loader. Handles primitives, void, references, arrays, 2149 // and all other reflectable types, except method types. 2150 // N.B. Code in reflection should use this entry point. 2151 Handle SystemDictionary::find_java_mirror_for_type(Symbol* signature, 2152 Klass* accessing_klass, 2153 Handle class_loader, 2154 Handle protection_domain, 2155 SignatureStream::FailureMode failure_mode, 2156 TRAPS) { 2157 assert(accessing_klass == nullptr || (class_loader.is_null() && protection_domain.is_null()), 2158 "one or the other, or perhaps neither"); 2159 2160 // What we have here must be a valid field descriptor, 2161 // and all valid field descriptors are supported. 2162 // Produce the same java.lang.Class that reflection reports. 2163 if (accessing_klass != nullptr) { 2164 class_loader = Handle(THREAD, accessing_klass->class_loader()); 2165 protection_domain = Handle(THREAD, accessing_klass->protection_domain()); 2166 } 2167 ResolvingSignatureStream ss(signature, class_loader, protection_domain, false); 2168 oop mirror_oop = ss.as_java_mirror(failure_mode, CHECK_NH); 2169 if (mirror_oop == nullptr) { 2170 return Handle(); // report failure this way 2171 } 2172 Handle mirror(THREAD, mirror_oop); 2173 2174 if (accessing_klass != nullptr) { 2175 // Check accessibility, emulating ConstantPool::verify_constant_pool_resolve. 2176 Klass* sel_klass = java_lang_Class::as_Klass(mirror()); 2177 if (sel_klass != nullptr) { 2178 LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_NH); 2179 } 2180 } 2181 return mirror; 2182 } 2183 2184 2185 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given 2186 // signature, as interpreted relative to the given class loader. 2187 // Because of class loader constraints, all method handle usage must be 2188 // consistent with this loader. 2189 Handle SystemDictionary::find_method_handle_type(Symbol* signature, 2190 Klass* accessing_klass, 2191 TRAPS) { 2192 Handle empty; 2193 OopHandle* o; 2194 { 2195 MutexLocker ml(THREAD, InvokeMethodTypeTable_lock); 2196 o = _invoke_method_type_table->get(signature); 2197 } 2198 2199 if (o != nullptr) { 2200 oop mt = o->resolve(); 2201 assert(java_lang_invoke_MethodType::is_instance(mt), ""); 2202 return Handle(THREAD, mt); 2203 } else if (!THREAD->can_call_java()) { 2204 warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME 2205 return Handle(); // do not attempt from within compiler, unless it was cached 2206 } 2207 2208 Handle class_loader, protection_domain; 2209 if (accessing_klass != nullptr) { 2210 class_loader = Handle(THREAD, accessing_klass->class_loader()); 2211 protection_domain = Handle(THREAD, accessing_klass->protection_domain()); 2212 } 2213 bool can_be_cached = true; 2214 int npts = ArgumentCount(signature).size(); 2215 objArrayHandle pts = oopFactory::new_objArray_handle(vmClasses::Class_klass(), npts, CHECK_(empty)); 2216 int arg = 0; 2217 Handle rt; // the return type from the signature 2218 ResourceMark rm(THREAD); 2219 for (SignatureStream ss(signature); !ss.is_done(); ss.next()) { 2220 oop mirror = nullptr; 2221 if (can_be_cached) { 2222 // Use neutral class loader to lookup candidate classes to be placed in the cache. 2223 mirror = ss.as_java_mirror(Handle(), Handle(), 2224 SignatureStream::ReturnNull, CHECK_(empty)); 2225 if (mirror == nullptr || (ss.is_reference() && !is_always_visible_class(mirror))) { 2226 // Fall back to accessing_klass context. 2227 can_be_cached = false; 2228 } 2229 } 2230 if (!can_be_cached) { 2231 // Resolve, throwing a real error if it doesn't work. 2232 mirror = ss.as_java_mirror(class_loader, protection_domain, 2233 SignatureStream::NCDFError, CHECK_(empty)); 2234 } 2235 assert(mirror != nullptr, "%s", ss.as_symbol()->as_C_string()); 2236 if (ss.at_return_type()) 2237 rt = Handle(THREAD, mirror); 2238 else 2239 pts->obj_at_put(arg++, mirror); 2240 2241 // Check accessibility. 2242 if (!java_lang_Class::is_primitive(mirror) && accessing_klass != nullptr) { 2243 Klass* sel_klass = java_lang_Class::as_Klass(mirror); 2244 mirror = nullptr; // safety 2245 // Emulate ConstantPool::verify_constant_pool_resolve. 2246 LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_(empty)); 2247 } 2248 } 2249 assert(arg == npts, ""); 2250 2251 // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType 2252 JavaCallArguments args(Handle(THREAD, rt())); 2253 args.push_oop(pts); 2254 JavaValue result(T_OBJECT); 2255 JavaCalls::call_static(&result, 2256 vmClasses::MethodHandleNatives_klass(), 2257 vmSymbols::findMethodHandleType_name(), 2258 vmSymbols::findMethodHandleType_signature(), 2259 &args, CHECK_(empty)); 2260 Handle method_type(THREAD, result.get_oop()); 2261 2262 if (can_be_cached) { 2263 // We can cache this MethodType inside the JVM. 2264 MutexLocker ml(THREAD, InvokeMethodTypeTable_lock); 2265 bool created = false; 2266 assert(method_type != nullptr, "unexpected null"); 2267 OopHandle* h = _invoke_method_type_table->get(signature); 2268 if (h == nullptr) { 2269 signature->make_permanent(); // The signature is never unloaded. 2270 OopHandle elem = OopHandle(Universe::vm_global(), method_type()); 2271 bool created = _invoke_method_type_table->put(signature, elem); 2272 assert(created, "better be created"); 2273 } 2274 } 2275 // report back to the caller with the MethodType 2276 return method_type; 2277 } 2278 2279 Handle SystemDictionary::find_field_handle_type(Symbol* signature, 2280 Klass* accessing_klass, 2281 TRAPS) { 2282 Handle empty; 2283 ResourceMark rm(THREAD); 2284 SignatureStream ss(signature, /*is_method=*/ false); 2285 if (!ss.is_done()) { 2286 Handle class_loader, protection_domain; 2287 if (accessing_klass != nullptr) { 2288 class_loader = Handle(THREAD, accessing_klass->class_loader()); 2289 protection_domain = Handle(THREAD, accessing_klass->protection_domain()); 2290 } 2291 oop mirror = ss.as_java_mirror(class_loader, protection_domain, SignatureStream::NCDFError, CHECK_(empty)); 2292 ss.next(); 2293 if (ss.is_done()) { 2294 return Handle(THREAD, mirror); 2295 } 2296 } 2297 return empty; 2298 } 2299 2300 // Ask Java code to find or construct a method handle constant. 2301 Handle SystemDictionary::link_method_handle_constant(Klass* caller, 2302 int ref_kind, //e.g., JVM_REF_invokeVirtual 2303 Klass* callee, 2304 Symbol* name, 2305 Symbol* signature, 2306 TRAPS) { 2307 Handle empty; 2308 if (caller == nullptr) { 2309 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty); 2310 } 2311 Handle name_str = java_lang_String::create_from_symbol(name, CHECK_(empty)); 2312 Handle signature_str = java_lang_String::create_from_symbol(signature, CHECK_(empty)); 2313 2314 // Put symbolic info from the MH constant into freshly created MemberName and resolve it. 2315 Handle mname = vmClasses::MemberName_klass()->allocate_instance_handle(CHECK_(empty)); 2316 java_lang_invoke_MemberName::set_clazz(mname(), callee->java_mirror()); 2317 java_lang_invoke_MemberName::set_name (mname(), name_str()); 2318 java_lang_invoke_MemberName::set_type (mname(), signature_str()); 2319 java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind)); 2320 2321 if (ref_kind == JVM_REF_invokeVirtual && 2322 MethodHandles::is_signature_polymorphic_public_name(callee, name)) { 2323 // Skip resolution for public signature polymorphic methods such as 2324 // j.l.i.MethodHandle.invoke()/invokeExact() and those on VarHandle 2325 // They require appendix argument which MemberName resolution doesn't handle. 2326 // There's special logic on JDK side to handle them 2327 // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()). 2328 } else { 2329 MethodHandles::resolve_MemberName(mname, caller, 0, false /*speculative_resolve*/, CHECK_(empty)); 2330 } 2331 2332 // After method/field resolution succeeded, it's safe to resolve MH signature as well. 2333 Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty)); 2334 2335 // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle 2336 JavaCallArguments args; 2337 args.push_oop(Handle(THREAD, caller->java_mirror())); // the referring class 2338 args.push_int(ref_kind); 2339 args.push_oop(Handle(THREAD, callee->java_mirror())); // the target class 2340 args.push_oop(name_str); 2341 args.push_oop(type); 2342 JavaValue result(T_OBJECT); 2343 JavaCalls::call_static(&result, 2344 vmClasses::MethodHandleNatives_klass(), 2345 vmSymbols::linkMethodHandleConstant_name(), 2346 vmSymbols::linkMethodHandleConstant_signature(), 2347 &args, CHECK_(empty)); 2348 return Handle(THREAD, result.get_oop()); 2349 } 2350 2351 // Ask Java to run a bootstrap method, in order to create a dynamic call site 2352 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry 2353 // with linkage results being stored back into the bootstrap specifier. 2354 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) { 2355 // Resolve the bootstrap specifier, its name, type, and static arguments 2356 bootstrap_specifier.resolve_bsm(CHECK); 2357 2358 // This should not happen. JDK code should take care of that. 2359 if (bootstrap_specifier.caller() == nullptr || bootstrap_specifier.type_arg().is_null()) { 2360 THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument"); 2361 } 2362 2363 bool is_indy = bootstrap_specifier.is_method_call(); 2364 objArrayHandle appendix_box; 2365 if (is_indy) { 2366 // Some method calls may require an appendix argument. Arrange to receive it. 2367 appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK); 2368 assert(appendix_box->obj_at(0) == nullptr, ""); 2369 } 2370 2371 // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, bsm, type, info) 2372 // indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix) 2373 JavaCallArguments args; 2374 args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror())); 2375 args.push_oop(bootstrap_specifier.bsm()); 2376 args.push_oop(bootstrap_specifier.name_arg()); 2377 args.push_oop(bootstrap_specifier.type_arg()); 2378 args.push_oop(bootstrap_specifier.arg_values()); 2379 if (is_indy) { 2380 args.push_oop(appendix_box); 2381 } 2382 JavaValue result(T_OBJECT); 2383 JavaCalls::call_static(&result, 2384 vmClasses::MethodHandleNatives_klass(), 2385 is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(), 2386 is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(), 2387 &args, CHECK); 2388 2389 Handle value(THREAD, result.get_oop()); 2390 if (is_indy) { 2391 Handle appendix; 2392 Method* method = unpack_method_and_appendix(value, 2393 bootstrap_specifier.caller(), 2394 appendix_box, 2395 &appendix, CHECK); 2396 methodHandle mh(THREAD, method); 2397 bootstrap_specifier.set_resolved_method(mh, appendix); 2398 } else { 2399 bootstrap_specifier.set_resolved_value(value); 2400 } 2401 2402 // sanity check 2403 assert(bootstrap_specifier.is_resolved() || 2404 (bootstrap_specifier.is_method_call() && 2405 bootstrap_specifier.resolved_method().not_null()), "bootstrap method call failed"); 2406 } 2407 2408 2409 bool SystemDictionary::is_nonpublic_Object_method(Method* m) { 2410 assert(m != nullptr, "Unexpected nullptr Method*"); 2411 return !m->is_public() && m->method_holder() == vmClasses::Object_klass(); 2412 } 2413 2414 // ---------------------------------------------------------------------------- 2415 2416 void SystemDictionary::print_on(outputStream *st) { 2417 CDS_ONLY(SystemDictionaryShared::print_on(st)); 2418 GCMutexLocker mu(SystemDictionary_lock); 2419 2420 ClassLoaderDataGraph::print_dictionary(st); 2421 2422 // Placeholders 2423 PlaceholderTable::print_on(st); 2424 st->cr(); 2425 2426 // loader constraints - print under SD_lock 2427 LoaderConstraintTable::print_on(st); 2428 st->cr(); 2429 2430 ProtectionDomainCacheTable::print_on(st); 2431 st->cr(); 2432 } 2433 2434 void SystemDictionary::print() { print_on(tty); } 2435 2436 void SystemDictionary::verify() { 2437 2438 GCMutexLocker mu(SystemDictionary_lock); 2439 2440 // Verify dictionary 2441 ClassLoaderDataGraph::verify_dictionary(); 2442 2443 // Verify constraint table 2444 LoaderConstraintTable::verify(); 2445 2446 // Verify protection domain table 2447 ProtectionDomainCacheTable::verify(); 2448 } 2449 2450 void SystemDictionary::dump(outputStream *st, bool verbose) { 2451 assert_locked_or_safepoint(SystemDictionary_lock); 2452 if (verbose) { 2453 print_on(st); 2454 } else { 2455 CDS_ONLY(SystemDictionaryShared::print_table_statistics(st)); 2456 ClassLoaderDataGraph::print_table_statistics(st); 2457 LoaderConstraintTable::print_table_statistics(st); 2458 ProtectionDomainCacheTable::print_table_statistics(st); 2459 } 2460 } 2461 2462 // Utility for dumping dictionaries. 2463 SystemDictionaryDCmd::SystemDictionaryDCmd(outputStream* output, bool heap) : 2464 DCmdWithParser(output, heap), 2465 _verbose("-verbose", "Dump the content of each dictionary entry for all class loaders", 2466 "BOOLEAN", false, "false") { 2467 _dcmdparser.add_dcmd_option(&_verbose); 2468 } 2469 2470 void SystemDictionaryDCmd::execute(DCmdSource source, TRAPS) { 2471 VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSysDict, 2472 _verbose.value()); 2473 VMThread::execute(&dumper); 2474 }