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