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