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