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