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