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