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