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