1 /* 2 * Copyright (c) 1997, 2017, 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 "aot/aotLoader.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/classLoaderExt.hpp" 32 #include "classfile/dictionary.hpp" 33 #include "classfile/javaClasses.inline.hpp" 34 #include "classfile/klassFactory.hpp" 35 #include "classfile/loaderConstraints.hpp" 36 #include "classfile/packageEntry.hpp" 37 #include "classfile/placeholders.hpp" 38 #include "classfile/protectionDomainCache.hpp" 39 #include "classfile/resolutionErrors.hpp" 40 #include "classfile/stringTable.hpp" 41 #include "classfile/systemDictionary.hpp" 42 #include "classfile/vmSymbols.hpp" 43 #include "code/codeCache.hpp" 44 #include "compiler/compileBroker.hpp" 45 #include "gc/shared/gcLocker.hpp" 46 #include "gc/shared/gcTraceTime.inline.hpp" 47 #include "interpreter/bytecodeStream.hpp" 48 #include "interpreter/interpreter.hpp" 49 #include "logging/log.hpp" 50 #include "logging/logStream.hpp" 51 #include "memory/filemap.hpp" 52 #include "memory/metaspaceClosure.hpp" 53 #include "memory/oopFactory.hpp" 54 #include "memory/resourceArea.hpp" 55 #include "oops/instanceKlass.hpp" 56 #include "oops/instanceRefKlass.hpp" 57 #include "oops/klass.inline.hpp" 58 #include "oops/methodData.hpp" 59 #include "oops/objArrayKlass.hpp" 60 #include "oops/objArrayOop.inline.hpp" 61 #include "oops/oop.inline.hpp" 62 #include "oops/symbol.hpp" 63 #include "oops/typeArrayKlass.hpp" 64 #include "prims/jvm.h" 65 #include "prims/jvmtiEnvBase.hpp" 66 #include "prims/resolvedMethodTable.hpp" 67 #include "prims/methodHandles.hpp" 68 #include "runtime/arguments.hpp" 69 #include "runtime/arguments_ext.hpp" 70 #include "runtime/biasedLocking.hpp" 71 #include "runtime/fieldType.hpp" 72 #include "runtime/handles.inline.hpp" 73 #include "runtime/java.hpp" 74 #include "runtime/javaCalls.hpp" 75 #include "runtime/mutexLocker.hpp" 76 #include "runtime/orderAccess.inline.hpp" 77 #include "runtime/signature.hpp" 78 #include "services/classLoadingService.hpp" 79 #include "services/diagnosticCommand.hpp" 80 #include "services/threadService.hpp" 81 #include "trace/tracing.hpp" 82 #include "utilities/macros.hpp" 83 #if INCLUDE_CDS 84 #include "classfile/sharedClassUtil.hpp" 85 #include "classfile/systemDictionaryShared.hpp" 86 #endif 87 #if INCLUDE_JVMCI 88 #include "jvmci/jvmciRuntime.hpp" 89 #endif 90 91 PlaceholderTable* SystemDictionary::_placeholders = NULL; 92 Dictionary* SystemDictionary::_shared_dictionary = NULL; 93 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL; 94 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL; 95 SymbolPropertyTable* SystemDictionary::_invoke_method_table = NULL; 96 ProtectionDomainCacheTable* SystemDictionary::_pd_cache_table = NULL; 97 98 int SystemDictionary::_number_of_modifications = 0; 99 oop SystemDictionary::_system_loader_lock_obj = NULL; 100 101 InstanceKlass* SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT] 102 = { NULL /*, NULL...*/ }; 103 104 InstanceKlass* SystemDictionary::_box_klasses[T_VOID+1] = { NULL /*, NULL...*/ }; 105 106 oop SystemDictionary::_java_system_loader = NULL; 107 oop SystemDictionary::_java_platform_loader = NULL; 108 109 bool SystemDictionary::_has_loadClassInternal = false; 110 bool SystemDictionary::_has_checkPackageAccess = false; 111 112 // lazily initialized klass variables 113 InstanceKlass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL; 114 115 // Default ProtectionDomainCacheSize value 116 117 const int defaultProtectionDomainCacheSize = 1009; 118 119 120 // ---------------------------------------------------------------------------- 121 // Java-level SystemLoader and PlatformLoader 122 123 oop SystemDictionary::java_system_loader() { 124 return _java_system_loader; 125 } 126 127 oop SystemDictionary::java_platform_loader() { 128 return _java_platform_loader; 129 } 130 131 void SystemDictionary::compute_java_loaders(TRAPS) { 132 JavaValue result(T_OBJECT); 133 InstanceKlass* class_loader_klass = SystemDictionary::ClassLoader_klass(); 134 JavaCalls::call_static(&result, 135 class_loader_klass, 136 vmSymbols::getSystemClassLoader_name(), 137 vmSymbols::void_classloader_signature(), 138 CHECK); 139 140 _java_system_loader = (oop)result.get_jobject(); 141 142 JavaCalls::call_static(&result, 143 class_loader_klass, 144 vmSymbols::getPlatformClassLoader_name(), 145 vmSymbols::void_classloader_signature(), 146 CHECK); 147 148 _java_platform_loader = (oop)result.get_jobject(); 149 150 CDS_ONLY(SystemDictionaryShared::initialize(CHECK);) 151 } 152 153 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) { 154 if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data(); 155 return ClassLoaderDataGraph::find_or_create(class_loader, THREAD); 156 } 157 158 // ---------------------------------------------------------------------------- 159 // Parallel class loading check 160 161 bool SystemDictionary::is_parallelCapable(Handle class_loader) { 162 if (UnsyncloadClass || class_loader.is_null()) return true; 163 if (AlwaysLockClassLoader) return false; 164 return java_lang_ClassLoader::parallelCapable(class_loader()); 165 } 166 // ---------------------------------------------------------------------------- 167 // ParallelDefineClass flag does not apply to bootclass loader 168 bool SystemDictionary::is_parallelDefine(Handle class_loader) { 169 if (class_loader.is_null()) return false; 170 if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) { 171 return true; 172 } 173 return false; 174 } 175 176 // Returns true if the passed class loader is the builtin application class loader 177 // or a custom system class loader. A customer system class loader can be 178 // specified via -Djava.system.class.loader. 179 bool SystemDictionary::is_system_class_loader(oop class_loader) { 180 if (class_loader == NULL) { 181 return false; 182 } 183 return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() || 184 class_loader == _java_system_loader); 185 } 186 187 // Returns true if the passed class loader is the platform class loader. 188 bool SystemDictionary::is_platform_class_loader(oop class_loader) { 189 if (class_loader == NULL) { 190 return false; 191 } 192 return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass()); 193 } 194 195 // ---------------------------------------------------------------------------- 196 // Resolving of classes 197 198 // Forwards to resolve_or_null 199 200 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) { 201 Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD); 202 if (HAS_PENDING_EXCEPTION || klass == NULL) { 203 // can return a null klass 204 klass = handle_resolution_exception(class_name, throw_error, klass, THREAD); 205 } 206 return klass; 207 } 208 209 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name, 210 bool throw_error, 211 Klass* klass, TRAPS) { 212 if (HAS_PENDING_EXCEPTION) { 213 // If we have a pending exception we forward it to the caller, unless throw_error is true, 214 // in which case we have to check whether the pending exception is a ClassNotFoundException, 215 // and if so convert it to a NoClassDefFoundError 216 // And chain the original ClassNotFoundException 217 if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) { 218 ResourceMark rm(THREAD); 219 assert(klass == NULL, "Should not have result with exception pending"); 220 Handle e(THREAD, PENDING_EXCEPTION); 221 CLEAR_PENDING_EXCEPTION; 222 THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e); 223 } else { 224 return NULL; 225 } 226 } 227 // Class not found, throw appropriate error or exception depending on value of throw_error 228 if (klass == NULL) { 229 ResourceMark rm(THREAD); 230 if (throw_error) { 231 THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string()); 232 } else { 233 THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string()); 234 } 235 } 236 return klass; 237 } 238 239 240 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, 241 bool throw_error, TRAPS) 242 { 243 return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD); 244 } 245 246 247 // Forwards to resolve_instance_class_or_null 248 249 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) { 250 assert(THREAD->can_call_java(), 251 "can not load classes with compiler thread: class=%s, classloader=%s", 252 class_name->as_C_string(), 253 class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string()); 254 if (FieldType::is_array(class_name)) { 255 return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD); 256 } else if (FieldType::is_obj(class_name)) { 257 ResourceMark rm(THREAD); 258 // Ignore wrapping L and ;. 259 TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1, 260 class_name->utf8_length() - 2, CHECK_NULL); 261 return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD); 262 } else { 263 return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD); 264 } 265 } 266 267 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) { 268 return resolve_or_null(class_name, Handle(), Handle(), THREAD); 269 } 270 271 // Forwards to resolve_instance_class_or_null 272 273 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name, 274 Handle class_loader, 275 Handle protection_domain, 276 TRAPS) { 277 assert(FieldType::is_array(class_name), "must be array"); 278 Klass* k = NULL; 279 FieldArrayInfo fd; 280 // dimension and object_key in FieldArrayInfo are assigned as a side-effect 281 // of this call 282 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_NULL); 283 if (t == T_OBJECT) { 284 // naked oop "k" is OK here -- we assign back into it 285 k = SystemDictionary::resolve_instance_class_or_null(fd.object_key(), 286 class_loader, 287 protection_domain, 288 CHECK_NULL); 289 if (k != NULL) { 290 k = k->array_klass(fd.dimension(), CHECK_NULL); 291 } 292 } else { 293 k = Universe::typeArrayKlassObj(t); 294 k = TypeArrayKlass::cast(k)->array_klass(fd.dimension(), CHECK_NULL); 295 } 296 return k; 297 } 298 299 300 // Must be called for any super-class or super-interface resolution 301 // during class definition to allow class circularity checking 302 // super-interface callers: 303 // parse_interfaces - for defineClass & jvmtiRedefineClasses 304 // super-class callers: 305 // ClassFileParser - for defineClass & jvmtiRedefineClasses 306 // load_shared_class - while loading a class from shared archive 307 // resolve_instance_class_or_null: 308 // via: handle_parallel_super_load 309 // when resolving a class that has an existing placeholder with 310 // a saved superclass [i.e. a defineClass is currently in progress] 311 // if another thread is trying to resolve the class, it must do 312 // super-class checks on its own thread to catch class circularity 313 // This last call is critical in class circularity checking for cases 314 // where classloading is delegated to different threads and the 315 // classloader lock is released. 316 // Take the case: Base->Super->Base 317 // 1. If thread T1 tries to do a defineClass of class Base 318 // resolve_super_or_fail creates placeholder: T1, Base (super Super) 319 // 2. resolve_instance_class_or_null does not find SD or placeholder for Super 320 // so it tries to load Super 321 // 3. If we load the class internally, or user classloader uses same thread 322 // loadClassFromxxx or defineClass via parseClassFile Super ... 323 // 3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base) 324 // 3.3 resolve_instance_class_or_null Base, finds placeholder for Base 325 // 3.4 calls resolve_super_or_fail Base 326 // 3.5 finds T1,Base -> throws class circularity 327 //OR 4. If T2 tries to resolve Super via defineClass Super ... 328 // 4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base) 329 // 4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super) 330 // 4.3 calls resolve_super_or_fail Super in parallel on own thread T2 331 // 4.4 finds T2, Super -> throws class circularity 332 // Must be called, even if superclass is null, since this is 333 // where the placeholder entry is created which claims this 334 // thread is loading this class/classloader. 335 // Be careful when modifying this code: once you have run 336 // placeholders()->find_and_add(PlaceholderTable::LOAD_SUPER), 337 // you need to find_and_remove it before returning. 338 // So be careful to not exit with a CHECK_ macro betweeen these calls. 339 Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name, 340 Symbol* class_name, 341 Handle class_loader, 342 Handle protection_domain, 343 bool is_superclass, 344 TRAPS) { 345 #if INCLUDE_CDS 346 if (DumpSharedSpaces) { 347 // Special processing for CDS dump time. 348 Klass* k = SystemDictionaryShared::dump_time_resolve_super_or_fail(child_name, 349 class_name, class_loader, protection_domain, is_superclass, CHECK_NULL); 350 if (k) { 351 return k; 352 } 353 } 354 #endif // INCLUDE_CDS 355 356 // Double-check, if child class is already loaded, just return super-class,interface 357 // Don't add a placedholder if already loaded, i.e. already in appropriate class loader 358 // dictionary. 359 // Make sure there's a placeholder for the *child* before resolving. 360 // Used as a claim that this thread is currently loading superclass/classloader 361 // Used here for ClassCircularity checks and also for heap verification 362 // (every InstanceKlass needs to be in its class loader dictionary or have a placeholder). 363 // Must check ClassCircularity before checking if super class is already loaded. 364 // 365 // We might not already have a placeholder if this child_name was 366 // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass); 367 // the name of the class might not be known until the stream is actually 368 // parsed. 369 // Bugs 4643874, 4715493 370 371 ClassLoaderData* loader_data = class_loader_data(class_loader); 372 Dictionary* dictionary = loader_data->dictionary(); 373 unsigned int d_hash = dictionary->compute_hash(child_name); 374 int d_index = dictionary->hash_to_index(d_hash); 375 unsigned int p_hash = placeholders()->compute_hash(child_name); 376 int p_index = placeholders()->hash_to_index(p_hash); 377 // can't throw error holding a lock 378 bool child_already_loaded = false; 379 bool throw_circularity_error = false; 380 { 381 MutexLocker mu(SystemDictionary_lock, THREAD); 382 Klass* childk = find_class(d_index, d_hash, child_name, dictionary); 383 Klass* quicksuperk; 384 // to support // loading: if child done loading, just return superclass 385 // if class_name, & class_loader don't match: 386 // if initial define, SD update will give LinkageError 387 // if redefine: compare_class_versions will give HIERARCHY_CHANGED 388 // so we don't throw an exception here. 389 // see: nsk redefclass014 & java.lang.instrument Instrument032 390 if ((childk != NULL ) && (is_superclass) && 391 ((quicksuperk = childk->super()) != NULL) && 392 393 ((quicksuperk->name() == class_name) && 394 (quicksuperk->class_loader() == class_loader()))) { 395 return quicksuperk; 396 } else { 397 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data); 398 if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) { 399 throw_circularity_error = true; 400 } 401 } 402 if (!throw_circularity_error) { 403 // Be careful not to exit resolve_super 404 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD); 405 } 406 } 407 if (throw_circularity_error) { 408 ResourceMark rm(THREAD); 409 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string()); 410 } 411 412 // java.lang.Object should have been found above 413 assert(class_name != NULL, "null super class for resolving"); 414 // Resolve the super class or interface, check results on return 415 Klass* superk = SystemDictionary::resolve_or_null(class_name, 416 class_loader, 417 protection_domain, 418 THREAD); 419 420 // Clean up of placeholders moved so that each classloadAction registrar self-cleans up 421 // It is no longer necessary to keep the placeholder table alive until update_dictionary 422 // or error. GC used to walk the placeholder table as strong roots. 423 // The instanceKlass is kept alive because the class loader is on the stack, 424 // which keeps the loader_data alive, as well as all instanceKlasses in 425 // the loader_data. parseClassFile adds the instanceKlass to loader_data. 426 { 427 MutexLocker mu(SystemDictionary_lock, THREAD); 428 placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD); 429 SystemDictionary_lock->notify_all(); 430 } 431 if (HAS_PENDING_EXCEPTION || superk == NULL) { 432 // can null superk 433 superk = handle_resolution_exception(class_name, true, superk, THREAD); 434 } 435 436 return superk; 437 } 438 439 void SystemDictionary::validate_protection_domain(InstanceKlass* klass, 440 Handle class_loader, 441 Handle protection_domain, 442 TRAPS) { 443 if(!has_checkPackageAccess()) return; 444 445 // Now we have to call back to java to check if the initating class has access 446 JavaValue result(T_VOID); 447 LogTarget(Debug, protectiondomain) lt; 448 if (lt.is_enabled()) { 449 ResourceMark rm; 450 // Print out trace information 451 LogStream ls(lt); 452 ls.print_cr("Checking package access"); 453 ls.print("class loader: "); class_loader()->print_value_on(&ls); 454 ls.print(" protection domain: "); protection_domain()->print_value_on(&ls); 455 ls.print(" loading: "); klass->print_value_on(&ls); 456 ls.cr(); 457 } 458 459 // This handle and the class_loader handle passed in keeps this class from 460 // being unloaded through several GC points. 461 // The class_loader handle passed in is the initiating loader. 462 Handle mirror(THREAD, klass->java_mirror()); 463 464 InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass(); 465 JavaCalls::call_special(&result, 466 class_loader, 467 system_loader, 468 vmSymbols::checkPackageAccess_name(), 469 vmSymbols::class_protectiondomain_signature(), 470 mirror, 471 protection_domain, 472 THREAD); 473 474 if (HAS_PENDING_EXCEPTION) { 475 log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!"); 476 } else { 477 log_debug(protectiondomain)("granted"); 478 } 479 480 if (HAS_PENDING_EXCEPTION) return; 481 482 // If no exception has been thrown, we have validated the protection domain 483 // Insert the protection domain of the initiating class into the set. 484 { 485 ClassLoaderData* loader_data = class_loader_data(class_loader); 486 Dictionary* dictionary = loader_data->dictionary(); 487 488 Symbol* kn = klass->name(); 489 unsigned int d_hash = dictionary->compute_hash(kn); 490 int d_index = dictionary->hash_to_index(d_hash); 491 492 MutexLocker mu(SystemDictionary_lock, THREAD); 493 dictionary->add_protection_domain(d_index, d_hash, klass, 494 protection_domain, THREAD); 495 } 496 } 497 498 // We only get here if this thread finds that another thread 499 // has already claimed the placeholder token for the current operation, 500 // but that other thread either never owned or gave up the 501 // object lock 502 // Waits on SystemDictionary_lock to indicate placeholder table updated 503 // On return, caller must recheck placeholder table state 504 // 505 // We only get here if 506 // 1) custom classLoader, i.e. not bootstrap classloader 507 // 2) UnsyncloadClass not set 508 // 3) custom classLoader has broken the class loader objectLock 509 // so another thread got here in parallel 510 // 511 // lockObject must be held. 512 // Complicated dance due to lock ordering: 513 // Must first release the classloader object lock to 514 // allow initial definer to complete the class definition 515 // and to avoid deadlock 516 // Reclaim classloader lock object with same original recursion count 517 // Must release SystemDictionary_lock after notify, since 518 // class loader lock must be claimed before SystemDictionary_lock 519 // to prevent deadlocks 520 // 521 // The notify allows applications that did an untimed wait() on 522 // the classloader object lock to not hang. 523 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) { 524 assert_lock_strong(SystemDictionary_lock); 525 526 bool calledholdinglock 527 = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject); 528 assert(calledholdinglock,"must hold lock for notify"); 529 assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait"); 530 ObjectSynchronizer::notifyall(lockObject, THREAD); 531 intptr_t recursions = ObjectSynchronizer::complete_exit(lockObject, THREAD); 532 SystemDictionary_lock->wait(); 533 SystemDictionary_lock->unlock(); 534 ObjectSynchronizer::reenter(lockObject, recursions, THREAD); 535 SystemDictionary_lock->lock(); 536 } 537 538 // If the class in is in the placeholder table, class loading is in progress 539 // For cases where the application changes threads to load classes, it 540 // is critical to ClassCircularity detection that we try loading 541 // the superclass on the same thread internally, so we do parallel 542 // super class loading here. 543 // This also is critical in cases where the original thread gets stalled 544 // even in non-circularity situations. 545 // Note: must call resolve_super_or_fail even if null super - 546 // to force placeholder entry creation for this class for circularity detection 547 // Caller must check for pending exception 548 // Returns non-null Klass* if other thread has completed load 549 // and we are done, 550 // If return null Klass* and no pending exception, the caller must load the class 551 InstanceKlass* SystemDictionary::handle_parallel_super_load( 552 Symbol* name, Symbol* superclassname, Handle class_loader, 553 Handle protection_domain, Handle lockObject, TRAPS) { 554 555 ClassLoaderData* loader_data = class_loader_data(class_loader); 556 Dictionary* dictionary = loader_data->dictionary(); 557 unsigned int d_hash = dictionary->compute_hash(name); 558 int d_index = dictionary->hash_to_index(d_hash); 559 unsigned int p_hash = placeholders()->compute_hash(name); 560 int p_index = placeholders()->hash_to_index(p_hash); 561 562 // superk is not used, resolve_super called for circularity check only 563 // This code is reached in two situations. One if this thread 564 // is loading the same class twice (e.g. ClassCircularity, or 565 // java.lang.instrument). 566 // The second is if another thread started the resolve_super first 567 // and has not yet finished. 568 // In both cases the original caller will clean up the placeholder 569 // entry on error. 570 Klass* superk = SystemDictionary::resolve_super_or_fail(name, 571 superclassname, 572 class_loader, 573 protection_domain, 574 true, 575 CHECK_NULL); 576 577 // parallelCapable class loaders do NOT wait for parallel superclass loads to complete 578 // Serial class loaders and bootstrap classloader do wait for superclass loads 579 if (!class_loader.is_null() && is_parallelCapable(class_loader)) { 580 MutexLocker mu(SystemDictionary_lock, THREAD); 581 // Check if classloading completed while we were loading superclass or waiting 582 return find_class(d_index, d_hash, name, dictionary); 583 } 584 585 // must loop to both handle other placeholder updates 586 // and spurious notifications 587 bool super_load_in_progress = true; 588 PlaceholderEntry* placeholder; 589 while (super_load_in_progress) { 590 MutexLocker mu(SystemDictionary_lock, THREAD); 591 // Check if classloading completed while we were loading superclass or waiting 592 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary); 593 if (check != NULL) { 594 // Klass is already loaded, so just return it 595 return check; 596 } else { 597 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data); 598 if (placeholder && placeholder->super_load_in_progress() ){ 599 // Before UnsyncloadClass: 600 // We only get here if the application has released the 601 // classloader lock when another thread was in the middle of loading a 602 // superclass/superinterface for this class, and now 603 // this thread is also trying to load this class. 604 // To minimize surprises, the first thread that started to 605 // load a class should be the one to complete the loading 606 // with the classfile it initially expected. 607 // This logic has the current thread wait once it has done 608 // all the superclass/superinterface loading it can, until 609 // the original thread completes the class loading or fails 610 // If it completes we will use the resulting InstanceKlass 611 // which we will find below in the systemDictionary. 612 // We also get here for parallel bootstrap classloader 613 if (class_loader.is_null()) { 614 SystemDictionary_lock->wait(); 615 } else { 616 double_lock_wait(lockObject, THREAD); 617 } 618 } else { 619 // If not in SD and not in PH, other thread's load must have failed 620 super_load_in_progress = false; 621 } 622 } 623 } 624 return NULL; 625 } 626 627 static void post_class_load_event(EventClassLoad* event, 628 const InstanceKlass* k, 629 const ClassLoaderData* init_cld) { 630 #if INCLUDE_TRACE 631 assert(event != NULL, "invariant"); 632 assert(k != NULL, "invariant"); 633 if (event->should_commit()) { 634 event->set_loadedClass(k); 635 event->set_definingClassLoader(k->class_loader_data()); 636 event->set_initiatingClassLoader(init_cld); 637 event->commit(); 638 } 639 #endif // INCLUDE_TRACE 640 } 641 642 static void class_define_event(InstanceKlass* k, 643 const ClassLoaderData* def_cld) { 644 #if INCLUDE_TRACE 645 EventClassDefine event; 646 if (event.should_commit()) { 647 event.set_definedClass(k); 648 event.set_definingClassLoader(def_cld); 649 event.commit(); 650 } 651 #endif // INCLUDE_TRACE 652 } 653 654 // Be careful when modifying this code: once you have run 655 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE), 656 // you need to find_and_remove it before returning. 657 // So be careful to not exit with a CHECK_ macro betweeen these calls. 658 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name, 659 Handle class_loader, 660 Handle protection_domain, 661 TRAPS) { 662 assert(name != NULL && !FieldType::is_array(name) && 663 !FieldType::is_obj(name), "invalid class name"); 664 665 EventClassLoad class_load_start_event; 666 667 HandleMark hm(THREAD); 668 669 // Fix for 4474172; see evaluation for more details 670 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 671 ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL); 672 Dictionary* dictionary = loader_data->dictionary(); 673 674 // Do lookup to see if class already exist and the protection domain 675 // has the right access 676 // This call uses find which checks protection domain already matches 677 // All subsequent calls use find_class, and set has_loaded_class so that 678 // before we return a result we call out to java to check for valid protection domain 679 // to allow returning the Klass* and add it to the pd_set if it is valid 680 unsigned int d_hash = dictionary->compute_hash(name); 681 int d_index = dictionary->hash_to_index(d_hash); 682 Klass* probe = dictionary->find(d_index, d_hash, name, protection_domain); 683 if (probe != NULL) return probe; 684 685 686 // Non-bootstrap class loaders will call out to class loader and 687 // define via jvm/jni_DefineClass which will acquire the 688 // class loader object lock to protect against multiple threads 689 // defining the class in parallel by accident. 690 // This lock must be acquired here so the waiter will find 691 // any successful result in the SystemDictionary and not attempt 692 // the define 693 // ParallelCapable Classloaders and the bootstrap classloader, 694 // or all classloaders with UnsyncloadClass do not acquire lock here 695 bool DoObjectLock = true; 696 if (is_parallelCapable(class_loader)) { 697 DoObjectLock = false; 698 } 699 700 unsigned int p_hash = placeholders()->compute_hash(name); 701 int p_index = placeholders()->hash_to_index(p_hash); 702 703 // Class is not in SystemDictionary so we have to do loading. 704 // Make sure we are synchronized on the class loader before we proceed 705 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 706 check_loader_lock_contention(lockObject, THREAD); 707 ObjectLocker ol(lockObject, THREAD, DoObjectLock); 708 709 // Check again (after locking) if class already exist in SystemDictionary 710 bool class_has_been_loaded = false; 711 bool super_load_in_progress = false; 712 bool havesupername = false; 713 InstanceKlass* k = NULL; 714 PlaceholderEntry* placeholder; 715 Symbol* superclassname = NULL; 716 717 { 718 MutexLocker mu(SystemDictionary_lock, THREAD); 719 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary); 720 if (check != NULL) { 721 // Klass is already loaded, so just return it 722 class_has_been_loaded = true; 723 k = check; 724 } else { 725 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data); 726 if (placeholder && placeholder->super_load_in_progress()) { 727 super_load_in_progress = true; 728 if (placeholder->havesupername() == true) { 729 superclassname = placeholder->supername(); 730 havesupername = true; 731 } 732 } 733 } 734 } 735 736 // If the class is in the placeholder table, class loading is in progress 737 if (super_load_in_progress && havesupername==true) { 738 k = handle_parallel_super_load(name, 739 superclassname, 740 class_loader, 741 protection_domain, 742 lockObject, THREAD); 743 if (HAS_PENDING_EXCEPTION) { 744 return NULL; 745 } 746 if (k != NULL) { 747 class_has_been_loaded = true; 748 } 749 } 750 751 bool throw_circularity_error = false; 752 if (!class_has_been_loaded) { 753 bool load_instance_added = false; 754 755 // add placeholder entry to record loading instance class 756 // Five cases: 757 // All cases need to prevent modifying bootclasssearchpath 758 // in parallel with a classload of same classname 759 // Redefineclasses uses existence of the placeholder for the duration 760 // of the class load to prevent concurrent redefinition of not completely 761 // defined classes. 762 // case 1. traditional classloaders that rely on the classloader object lock 763 // - no other need for LOAD_INSTANCE 764 // case 2. traditional classloaders that break the classloader object lock 765 // as a deadlock workaround. Detection of this case requires that 766 // this check is done while holding the classloader object lock, 767 // and that lock is still held when calling classloader's loadClass. 768 // For these classloaders, we ensure that the first requestor 769 // completes the load and other requestors wait for completion. 770 // case 3. UnsyncloadClass - don't use objectLocker 771 // With this flag, we allow parallel classloading of a 772 // class/classloader pair 773 // case4. Bootstrap classloader - don't own objectLocker 774 // This classloader supports parallelism at the classloader level, 775 // but only allows a single load of a class/classloader pair. 776 // No performance benefit and no deadlock issues. 777 // case 5. parallelCapable user level classloaders - without objectLocker 778 // Allow parallel classloading of a class/classloader pair 779 780 { 781 MutexLocker mu(SystemDictionary_lock, THREAD); 782 if (class_loader.is_null() || !is_parallelCapable(class_loader)) { 783 PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data); 784 if (oldprobe) { 785 // only need check_seen_thread once, not on each loop 786 // 6341374 java/lang/Instrument with -Xcomp 787 if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) { 788 throw_circularity_error = true; 789 } else { 790 // case 1: traditional: should never see load_in_progress. 791 while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) { 792 793 // case 4: bootstrap classloader: prevent futile classloading, 794 // wait on first requestor 795 if (class_loader.is_null()) { 796 SystemDictionary_lock->wait(); 797 } else { 798 // case 2: traditional with broken classloader lock. wait on first 799 // requestor. 800 double_lock_wait(lockObject, THREAD); 801 } 802 // Check if classloading completed while we were waiting 803 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary); 804 if (check != NULL) { 805 // Klass is already loaded, so just return it 806 k = check; 807 class_has_been_loaded = true; 808 } 809 // check if other thread failed to load and cleaned up 810 oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data); 811 } 812 } 813 } 814 } 815 // All cases: add LOAD_INSTANCE holding SystemDictionary_lock 816 // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try 817 // LOAD_INSTANCE in parallel 818 819 if (!throw_circularity_error && !class_has_been_loaded) { 820 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD); 821 load_instance_added = true; 822 // For class loaders that do not acquire the classloader object lock, 823 // if they did not catch another thread holding LOAD_INSTANCE, 824 // need a check analogous to the acquire ObjectLocker/find_class 825 // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL 826 // one final check if the load has already completed 827 // class loaders holding the ObjectLock shouldn't find the class here 828 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary); 829 if (check != NULL) { 830 // Klass is already loaded, so return it after checking/adding protection domain 831 k = check; 832 class_has_been_loaded = true; 833 } 834 } 835 } 836 837 // must throw error outside of owning lock 838 if (throw_circularity_error) { 839 assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup"); 840 ResourceMark rm(THREAD); 841 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string()); 842 } 843 844 if (!class_has_been_loaded) { 845 846 // Do actual loading 847 k = load_instance_class(name, class_loader, THREAD); 848 849 // For UnsyncloadClass only 850 // If they got a linkageError, check if a parallel class load succeeded. 851 // If it did, then for bytecode resolution the specification requires 852 // that we return the same result we did for the other thread, i.e. the 853 // successfully loaded InstanceKlass 854 // Should not get here for classloaders that support parallelism 855 // with the new cleaner mechanism, even with AllowParallelDefineClass 856 // Bootstrap goes through here to allow for an extra guarantee check 857 if (UnsyncloadClass || (class_loader.is_null())) { 858 if (k == NULL && HAS_PENDING_EXCEPTION 859 && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) { 860 MutexLocker mu(SystemDictionary_lock, THREAD); 861 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary); 862 if (check != NULL) { 863 // Klass is already loaded, so just use it 864 k = check; 865 CLEAR_PENDING_EXCEPTION; 866 guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?"); 867 } 868 } 869 } 870 871 // If everything was OK (no exceptions, no null return value), and 872 // class_loader is NOT the defining loader, do a little more bookkeeping. 873 if (!HAS_PENDING_EXCEPTION && k != NULL && 874 k->class_loader() != class_loader()) { 875 876 check_constraints(d_index, d_hash, k, class_loader, false, THREAD); 877 878 // Need to check for a PENDING_EXCEPTION again; check_constraints 879 // can throw and doesn't use the CHECK macro. 880 if (!HAS_PENDING_EXCEPTION) { 881 { // Grabbing the Compile_lock prevents systemDictionary updates 882 // during compilations. 883 MutexLocker mu(Compile_lock, THREAD); 884 update_dictionary(d_index, d_hash, p_index, p_hash, 885 k, class_loader, THREAD); 886 } 887 888 if (JvmtiExport::should_post_class_load()) { 889 Thread *thread = THREAD; 890 assert(thread->is_Java_thread(), "thread->is_Java_thread()"); 891 JvmtiExport::post_class_load((JavaThread *) thread, k); 892 } 893 } 894 } 895 } // load_instance_class 896 897 if (load_instance_added == true) { 898 // clean up placeholder entries for LOAD_INSTANCE success or error 899 // This brackets the SystemDictionary updates for both defining 900 // and initiating loaders 901 MutexLocker mu(SystemDictionary_lock, THREAD); 902 placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD); 903 SystemDictionary_lock->notify_all(); 904 } 905 } 906 907 if (HAS_PENDING_EXCEPTION || k == NULL) { 908 return NULL; 909 } 910 911 post_class_load_event(&class_load_start_event, k, loader_data); 912 913 #ifdef ASSERT 914 { 915 ClassLoaderData* loader_data = k->class_loader_data(); 916 MutexLocker mu(SystemDictionary_lock, THREAD); 917 Klass* kk = find_class(name, loader_data); 918 assert(kk == k, "should be present in dictionary"); 919 } 920 #endif 921 922 // return if the protection domain in NULL 923 if (protection_domain() == NULL) return k; 924 925 // Check the protection domain has the right access 926 if (dictionary->is_valid_protection_domain(d_index, d_hash, name, 927 protection_domain)) { 928 return k; 929 } 930 931 // Verify protection domain. If it fails an exception is thrown 932 validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL); 933 934 return k; 935 } 936 937 938 // This routine does not lock the system dictionary. 939 // 940 // Since readers don't hold a lock, we must make sure that system 941 // dictionary entries are only removed at a safepoint (when only one 942 // thread is running), and are added to in a safe way (all links must 943 // be updated in an MT-safe manner). 944 // 945 // Callers should be aware that an entry could be added just after 946 // _dictionary->bucket(index) is read here, so the caller will not see 947 // the new entry. 948 949 Klass* SystemDictionary::find(Symbol* class_name, 950 Handle class_loader, 951 Handle protection_domain, 952 TRAPS) { 953 954 // The result of this call should be consistent with the result 955 // of the call to resolve_instance_class_or_null(). 956 // See evaluation 6790209 and 4474172 for more details. 957 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader())); 958 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader()); 959 960 if (loader_data == NULL) { 961 // If the ClassLoaderData has not been setup, 962 // then the class loader has no entries in the dictionary. 963 return NULL; 964 } 965 966 Dictionary* dictionary = loader_data->dictionary(); 967 unsigned int d_hash = dictionary->compute_hash(class_name); 968 int d_index = dictionary->hash_to_index(d_hash); 969 return dictionary->find(d_index, d_hash, class_name, 970 protection_domain); 971 } 972 973 974 // Look for a loaded instance or array klass by name. Do not do any loading. 975 // return NULL in case of error. 976 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name, 977 Handle class_loader, 978 Handle protection_domain, 979 TRAPS) { 980 Klass* k = NULL; 981 assert(class_name != NULL, "class name must be non NULL"); 982 983 if (FieldType::is_array(class_name)) { 984 // The name refers to an array. Parse the name. 985 // dimension and object_key in FieldArrayInfo are assigned as a 986 // side-effect of this call 987 FieldArrayInfo fd; 988 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL)); 989 if (t != T_OBJECT) { 990 k = Universe::typeArrayKlassObj(t); 991 } else { 992 k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD); 993 } 994 if (k != NULL) { 995 k = k->array_klass_or_null(fd.dimension()); 996 } 997 } else { 998 k = find(class_name, class_loader, protection_domain, THREAD); 999 } 1000 return k; 1001 } 1002 1003 // Note: this method is much like resolve_from_stream, but 1004 // does not publish the classes via the SystemDictionary. 1005 // Handles unsafe_DefineAnonymousClass and redefineclasses 1006 // RedefinedClasses do not add to the class hierarchy 1007 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name, 1008 Handle class_loader, 1009 Handle protection_domain, 1010 ClassFileStream* st, 1011 const InstanceKlass* host_klass, 1012 GrowableArray<Handle>* cp_patches, 1013 TRAPS) { 1014 1015 EventClassLoad class_load_start_event; 1016 1017 ClassLoaderData* loader_data; 1018 if (host_klass != NULL) { 1019 // Create a new CLD for anonymous class, that uses the same class loader 1020 // as the host_klass 1021 guarantee(host_klass->class_loader() == class_loader(), "should be the same"); 1022 loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL); 1023 } else { 1024 loader_data = ClassLoaderData::class_loader_data(class_loader()); 1025 } 1026 1027 assert(st != NULL, "invariant"); 1028 assert(st->need_verify(), "invariant"); 1029 1030 // Parse stream and create a klass. 1031 // Note that we do this even though this klass might 1032 // already be present in the SystemDictionary, otherwise we would not 1033 // throw potential ClassFormatErrors. 1034 1035 InstanceKlass* k = KlassFactory::create_from_stream(st, 1036 class_name, 1037 loader_data, 1038 protection_domain, 1039 host_klass, 1040 cp_patches, 1041 CHECK_NULL); 1042 1043 if (host_klass != NULL && k != NULL) { 1044 // If it's anonymous, initialize it now, since nobody else will. 1045 1046 { 1047 MutexLocker mu_r(Compile_lock, THREAD); 1048 1049 // Add to class hierarchy, initialize vtables, and do possible 1050 // deoptimizations. 1051 add_to_hierarchy(k, CHECK_NULL); // No exception, but can block 1052 1053 // But, do not add to dictionary. 1054 1055 // compiled code dependencies need to be validated anyway 1056 notice_modification(); 1057 } 1058 1059 // Rewrite and patch constant pool here. 1060 k->link_class(CHECK_NULL); 1061 if (cp_patches != NULL) { 1062 k->constants()->patch_resolved_references(cp_patches); 1063 } 1064 k->eager_initialize(CHECK_NULL); 1065 1066 // notify jvmti 1067 if (JvmtiExport::should_post_class_load()) { 1068 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()"); 1069 JvmtiExport::post_class_load((JavaThread *) THREAD, k); 1070 } 1071 1072 post_class_load_event(&class_load_start_event, k, loader_data); 1073 } 1074 assert(host_klass != NULL || NULL == cp_patches, 1075 "cp_patches only found with host_klass"); 1076 1077 return k; 1078 } 1079 1080 // Add a klass to the system from a stream (called by jni_DefineClass and 1081 // JVM_DefineClass). 1082 // Note: class_name can be NULL. In that case we do not know the name of 1083 // the class until we have parsed the stream. 1084 1085 InstanceKlass* SystemDictionary::resolve_from_stream(Symbol* class_name, 1086 Handle class_loader, 1087 Handle protection_domain, 1088 ClassFileStream* st, 1089 TRAPS) { 1090 #if INCLUDE_CDS 1091 ResourceMark rm(THREAD); 1092 if (DumpSharedSpaces && !class_loader.is_null() && 1093 !ArgumentsExt::using_AppCDS() && strcmp(class_name->as_C_string(), "Unnamed") != 0) { 1094 // If AppCDS is not enabled, don't define the class at dump time (except for the "Unnamed" 1095 // class, which is used by MethodHandles). 1096 THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string()); 1097 } 1098 #endif 1099 1100 HandleMark hm(THREAD); 1101 1102 // Classloaders that support parallelism, e.g. bootstrap classloader, 1103 // or all classloaders with UnsyncloadClass do not acquire lock here 1104 bool DoObjectLock = true; 1105 if (is_parallelCapable(class_loader)) { 1106 DoObjectLock = false; 1107 } 1108 1109 ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL); 1110 1111 // Make sure we are synchronized on the class loader before we proceed 1112 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 1113 check_loader_lock_contention(lockObject, THREAD); 1114 ObjectLocker ol(lockObject, THREAD, DoObjectLock); 1115 1116 assert(st != NULL, "invariant"); 1117 1118 // Parse the stream and create a klass. 1119 // Note that we do this even though this klass might 1120 // already be present in the SystemDictionary, otherwise we would not 1121 // throw potential ClassFormatErrors. 1122 InstanceKlass* k = NULL; 1123 1124 #if INCLUDE_CDS 1125 if (!DumpSharedSpaces) { 1126 k = SystemDictionaryShared::lookup_from_stream(class_name, 1127 class_loader, 1128 protection_domain, 1129 st, 1130 CHECK_NULL); 1131 } 1132 #endif 1133 1134 if (k == NULL) { 1135 if (st->buffer() == NULL) { 1136 return NULL; 1137 } 1138 k = KlassFactory::create_from_stream(st, 1139 class_name, 1140 loader_data, 1141 protection_domain, 1142 NULL, // host_klass 1143 NULL, // cp_patches 1144 CHECK_NULL); 1145 } 1146 1147 assert(k != NULL, "no klass created"); 1148 Symbol* h_name = k->name(); 1149 assert(class_name == NULL || class_name == h_name, "name mismatch"); 1150 1151 // Add class just loaded 1152 // If a class loader supports parallel classloading handle parallel define requests 1153 // find_or_define_instance_class may return a different InstanceKlass 1154 if (is_parallelCapable(class_loader)) { 1155 InstanceKlass* defined_k = find_or_define_instance_class(h_name, class_loader, k, THREAD); 1156 if (!HAS_PENDING_EXCEPTION && defined_k != k) { 1157 // If a parallel capable class loader already defined this class, register 'k' for cleanup. 1158 assert(defined_k != NULL, "Should have a klass if there's no exception"); 1159 loader_data->add_to_deallocate_list(k); 1160 k = defined_k; 1161 } 1162 } else { 1163 define_instance_class(k, THREAD); 1164 } 1165 1166 // If defining the class throws an exception register 'k' for cleanup. 1167 if (HAS_PENDING_EXCEPTION) { 1168 assert(k != NULL, "Must have an instance klass here!"); 1169 loader_data->add_to_deallocate_list(k); 1170 return NULL; 1171 } 1172 1173 // Make sure we have an entry in the SystemDictionary on success 1174 debug_only( { 1175 MutexLocker mu(SystemDictionary_lock, THREAD); 1176 1177 Klass* check = find_class(h_name, k->class_loader_data()); 1178 assert(check == k, "should be present in the dictionary"); 1179 } ); 1180 1181 return k; 1182 } 1183 1184 #if INCLUDE_CDS 1185 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length, 1186 int number_of_entries) { 1187 assert(length == _shared_dictionary_size * sizeof(HashtableBucket<mtClass>), 1188 "bad shared dictionary size."); 1189 _shared_dictionary = new Dictionary(ClassLoaderData::the_null_class_loader_data(), 1190 _shared_dictionary_size, t, number_of_entries); 1191 } 1192 1193 1194 // If there is a shared dictionary, then find the entry for the 1195 // given shared system class, if any. 1196 1197 InstanceKlass* SystemDictionary::find_shared_class(Symbol* class_name) { 1198 if (shared_dictionary() != NULL) { 1199 unsigned int d_hash = shared_dictionary()->compute_hash(class_name); 1200 int d_index = shared_dictionary()->hash_to_index(d_hash); 1201 1202 return shared_dictionary()->find_shared_class(d_index, d_hash, class_name); 1203 } else { 1204 return NULL; 1205 } 1206 } 1207 1208 1209 // Load a class from the shared spaces (found through the shared system 1210 // dictionary). Force the superclass and all interfaces to be loaded. 1211 // Update the class definition to include sibling classes and no 1212 // subclasses (yet). [Classes in the shared space are not part of the 1213 // object hierarchy until loaded.] 1214 1215 InstanceKlass* SystemDictionary::load_shared_class( 1216 Symbol* class_name, Handle class_loader, TRAPS) { 1217 InstanceKlass* ik = find_shared_class(class_name); 1218 // Make sure we only return the boot class for the NULL classloader. 1219 if (ik != NULL && 1220 ik->is_shared_boot_class() && class_loader.is_null()) { 1221 Handle protection_domain; 1222 return load_shared_class(ik, class_loader, protection_domain, THREAD); 1223 } 1224 return NULL; 1225 } 1226 1227 // Check if a shared class can be loaded by the specific classloader: 1228 // 1229 // NULL classloader: 1230 // - Module class from "modules" jimage. ModuleEntry must be defined in the classloader. 1231 // - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must 1232 // be defined in an unnamed module. 1233 bool SystemDictionary::is_shared_class_visible(Symbol* class_name, 1234 InstanceKlass* ik, 1235 Handle class_loader, TRAPS) { 1236 assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(), 1237 "Cannot use sharing if java.base is patched"); 1238 ResourceMark rm; 1239 int path_index = ik->shared_classpath_index(); 1240 ClassLoaderData* loader_data = class_loader_data(class_loader); 1241 if (path_index < 0) { 1242 // path_index < 0 indicates that the class is intended for a custom loader 1243 // and should not be loaded by boot/platform/app loaders 1244 if (loader_data->is_builtin_class_loader_data()) { 1245 return false; 1246 } else { 1247 return true; 1248 } 1249 } 1250 SharedClassPathEntry* ent = 1251 (SharedClassPathEntry*)FileMapInfo::shared_classpath(path_index); 1252 if (!Universe::is_module_initialized()) { 1253 assert(ent != NULL && ent->is_modules_image(), 1254 "Loading non-bootstrap classes before the module system is initialized"); 1255 assert(class_loader.is_null(), "sanity"); 1256 return true; 1257 } 1258 // Get the pkg_entry from the classloader 1259 TempNewSymbol pkg_name = NULL; 1260 PackageEntry* pkg_entry = NULL; 1261 ModuleEntry* mod_entry = NULL; 1262 const char* pkg_string = NULL; 1263 pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false); 1264 if (pkg_name != NULL) { 1265 pkg_string = pkg_name->as_C_string(); 1266 if (loader_data != NULL) { 1267 pkg_entry = loader_data->packages()->lookup_only(pkg_name); 1268 } 1269 if (pkg_entry != NULL) { 1270 mod_entry = pkg_entry->module(); 1271 } 1272 } 1273 1274 // If the archived class is from a module that has been patched at runtime, 1275 // the class cannot be loaded from the archive. 1276 if (mod_entry != NULL && mod_entry->is_patched()) { 1277 return false; 1278 } 1279 1280 if (class_loader.is_null()) { 1281 assert(ent != NULL, "Shared class for NULL classloader must have valid SharedClassPathEntry"); 1282 // The NULL classloader can load archived class originated from the 1283 // "modules" jimage and the -Xbootclasspath/a. For class from the 1284 // "modules" jimage, the PackageEntry/ModuleEntry must be defined 1285 // by the NULL classloader. 1286 if (mod_entry != NULL) { 1287 // PackageEntry/ModuleEntry is found in the classloader. Check if the 1288 // ModuleEntry's location agrees with the archived class' origination. 1289 if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) { 1290 return true; // Module class from the "module" jimage 1291 } 1292 } 1293 1294 // If the archived class is not from the "module" jimage, the class can be 1295 // loaded by the NULL classloader if 1296 // 1297 // 1. the class is from the unamed package 1298 // 2. or, the class is not from a module defined in the NULL classloader 1299 // 3. or, the class is from an unamed module 1300 if (!ent->is_modules_image() && ik->is_shared_boot_class()) { 1301 // the class is from the -Xbootclasspath/a 1302 if (pkg_string == NULL || 1303 pkg_entry == NULL || 1304 pkg_entry->in_unnamed_module()) { 1305 assert(mod_entry == NULL || 1306 mod_entry == loader_data->unnamed_module(), 1307 "the unnamed module is not defined in the classloader"); 1308 return true; 1309 } 1310 } 1311 return false; 1312 } else { 1313 bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader( 1314 ik, class_loader, pkg_string, pkg_name, 1315 pkg_entry, mod_entry, CHECK_(false)); 1316 return res; 1317 } 1318 } 1319 1320 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik, 1321 Handle class_loader, 1322 Handle protection_domain, TRAPS) { 1323 1324 if (ik != NULL) { 1325 Symbol* class_name = ik->name(); 1326 1327 bool visible = is_shared_class_visible( 1328 class_name, ik, class_loader, CHECK_NULL); 1329 if (!visible) { 1330 return NULL; 1331 } 1332 1333 // Resolve the superclass and interfaces. They must be the same 1334 // as in dump time, because the layout of <ik> depends on 1335 // the specific layout of ik->super() and ik->local_interfaces(). 1336 // 1337 // If unexpected superclass or interfaces are found, we cannot 1338 // load <ik> from the shared archive. 1339 1340 if (ik->super() != NULL) { 1341 Symbol* cn = ik->super()->name(); 1342 Klass *s = resolve_super_or_fail(class_name, cn, 1343 class_loader, protection_domain, true, CHECK_NULL); 1344 if (s != ik->super()) { 1345 // The dynamically resolved super class is not the same as the one we used during dump time, 1346 // so we cannot use ik. 1347 return NULL; 1348 } else { 1349 assert(s->is_shared(), "must be"); 1350 } 1351 } 1352 1353 Array<Klass*>* interfaces = ik->local_interfaces(); 1354 int num_interfaces = interfaces->length(); 1355 for (int index = 0; index < num_interfaces; index++) { 1356 Klass* k = interfaces->at(index); 1357 Symbol* name = k->name(); 1358 Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_NULL); 1359 if (k != i) { 1360 // The dynamically resolved interface class is not the same as the one we used during dump time, 1361 // so we cannot use ik. 1362 return NULL; 1363 } else { 1364 assert(i->is_shared(), "must be"); 1365 } 1366 } 1367 1368 InstanceKlass* new_ik = KlassFactory::check_shared_class_file_load_hook( 1369 ik, class_name, class_loader, protection_domain, CHECK_NULL); 1370 if (new_ik != NULL) { 1371 // The class is changed by CFLH. Return the new class. The shared class is 1372 // not used. 1373 return new_ik; 1374 } 1375 1376 // Adjust methods to recover missing data. They need addresses for 1377 // interpreter entry points and their default native method address 1378 // must be reset. 1379 1380 // Updating methods must be done under a lock so multiple 1381 // threads don't update these in parallel 1382 // 1383 // Shared classes are all currently loaded by either the bootstrap or 1384 // internal parallel class loaders, so this will never cause a deadlock 1385 // on a custom class loader lock. 1386 1387 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 1388 { 1389 HandleMark hm(THREAD); 1390 Handle lockObject = compute_loader_lock_object(class_loader, THREAD); 1391 check_loader_lock_contention(lockObject, THREAD); 1392 ObjectLocker ol(lockObject, THREAD, true); 1393 // prohibited package check assumes all classes loaded from archive call 1394 // restore_unshareable_info which calls ik->set_package() 1395 ik->restore_unshareable_info(loader_data, protection_domain, CHECK_NULL); 1396 } 1397 1398 ik->print_class_load_logging(loader_data, NULL, NULL); 1399 1400 // For boot loader, ensure that GetSystemPackage knows that a class in this 1401 // package was loaded. 1402 if (class_loader.is_null()) { 1403 int path_index = ik->shared_classpath_index(); 1404 ResourceMark rm; 1405 ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD); 1406 } 1407 1408 if (DumpLoadedClassList != NULL && classlist_file->is_open()) { 1409 // Only dump the classes that can be stored into CDS archive 1410 if (SystemDictionaryShared::is_sharing_possible(loader_data)) { 1411 ResourceMark rm(THREAD); 1412 classlist_file->print_cr("%s", ik->name()->as_C_string()); 1413 classlist_file->flush(); 1414 } 1415 } 1416 1417 // notify a class loaded from shared object 1418 ClassLoadingService::notify_class_loaded(ik, true /* shared class */); 1419 } 1420 1421 ik->set_has_passed_fingerprint_check(false); 1422 if (UseAOT && ik->supers_have_passed_fingerprint_checks()) { 1423 uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik); 1424 uint64_t cds_fp = ik->get_stored_fingerprint(); 1425 if (aot_fp != 0 && aot_fp == cds_fp) { 1426 // This class matches with a class saved in an AOT library 1427 ik->set_has_passed_fingerprint_check(true); 1428 } else { 1429 ResourceMark rm; 1430 log_info(class, fingerprint)("%s : expected = " PTR64_FORMAT " actual = " PTR64_FORMAT, ik->external_name(), aot_fp, cds_fp); 1431 } 1432 } 1433 return ik; 1434 } 1435 1436 void SystemDictionary::clear_invoke_method_table() { 1437 SymbolPropertyEntry* spe = NULL; 1438 for (int index = 0; index < _invoke_method_table->table_size(); index++) { 1439 SymbolPropertyEntry* p = _invoke_method_table->bucket(index); 1440 while (p != NULL) { 1441 spe = p; 1442 p = p->next(); 1443 _invoke_method_table->free_entry(spe); 1444 } 1445 } 1446 } 1447 #endif // INCLUDE_CDS 1448 1449 InstanceKlass* SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) { 1450 1451 if (class_loader.is_null()) { 1452 ResourceMark rm; 1453 PackageEntry* pkg_entry = NULL; 1454 bool search_only_bootloader_append = false; 1455 ClassLoaderData *loader_data = class_loader_data(class_loader); 1456 1457 // Find the package in the boot loader's package entry table. 1458 TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL); 1459 if (pkg_name != NULL) { 1460 pkg_entry = loader_data->packages()->lookup_only(pkg_name); 1461 } 1462 1463 // Prior to attempting to load the class, enforce the boot loader's 1464 // visibility boundaries. 1465 if (!Universe::is_module_initialized()) { 1466 // During bootstrapping, prior to module initialization, any 1467 // class attempting to be loaded must be checked against the 1468 // java.base packages in the boot loader's PackageEntryTable. 1469 // No class outside of java.base is allowed to be loaded during 1470 // this bootstrapping window. 1471 if (!DumpSharedSpaces) { 1472 if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) { 1473 // Class is either in the unnamed package or in 1474 // a named package within the unnamed module. Either 1475 // case is outside of java.base, do not attempt to 1476 // load the class post java.base definition. If 1477 // java.base has not been defined, let the class load 1478 // and its package will be checked later by 1479 // ModuleEntryTable::verify_javabase_packages. 1480 if (ModuleEntryTable::javabase_defined()) { 1481 return NULL; 1482 } 1483 } else { 1484 // Check that the class' package is defined within java.base. 1485 ModuleEntry* mod_entry = pkg_entry->module(); 1486 Symbol* mod_entry_name = mod_entry->name(); 1487 if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) { 1488 return NULL; 1489 } 1490 } 1491 } 1492 } else { 1493 // After the module system has been initialized, check if the class' 1494 // package is in a module defined to the boot loader. 1495 if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) { 1496 // Class is either in the unnamed package, in a named package 1497 // within a module not defined to the boot loader or in a 1498 // a named package within the unnamed module. In all cases, 1499 // limit visibility to search for the class only in the boot 1500 // loader's append path. 1501 search_only_bootloader_append = true; 1502 } 1503 } 1504 1505 // Prior to bootstrapping's module initialization, never load a class outside 1506 // of the boot loader's module path 1507 assert(Universe::is_module_initialized() || DumpSharedSpaces || 1508 !search_only_bootloader_append, 1509 "Attempt to load a class outside of boot loader's module path"); 1510 1511 // Search the shared system dictionary for classes preloaded into the 1512 // shared spaces. 1513 InstanceKlass* k = NULL; 1514 { 1515 #if INCLUDE_CDS 1516 PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time()); 1517 k = load_shared_class(class_name, class_loader, THREAD); 1518 #endif 1519 } 1520 1521 if (k == NULL) { 1522 // Use VM class loader 1523 PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time()); 1524 k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL); 1525 } 1526 1527 // find_or_define_instance_class may return a different InstanceKlass 1528 if (k != NULL) { 1529 InstanceKlass* defined_k = 1530 find_or_define_instance_class(class_name, class_loader, k, THREAD); 1531 if (!HAS_PENDING_EXCEPTION && defined_k != k) { 1532 // If a parallel capable class loader already defined this class, register 'k' for cleanup. 1533 assert(defined_k != NULL, "Should have a klass if there's no exception"); 1534 loader_data->add_to_deallocate_list(k); 1535 k = defined_k; 1536 } else if (HAS_PENDING_EXCEPTION) { 1537 loader_data->add_to_deallocate_list(k); 1538 return NULL; 1539 } 1540 } 1541 return k; 1542 } else { 1543 // Use user specified class loader to load class. Call loadClass operation on class_loader. 1544 ResourceMark rm(THREAD); 1545 1546 assert(THREAD->is_Java_thread(), "must be a JavaThread"); 1547 JavaThread* jt = (JavaThread*) THREAD; 1548 1549 PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(), 1550 ClassLoader::perf_app_classload_selftime(), 1551 ClassLoader::perf_app_classload_count(), 1552 jt->get_thread_stat()->perf_recursion_counts_addr(), 1553 jt->get_thread_stat()->perf_timers_addr(), 1554 PerfClassTraceTime::CLASS_LOAD); 1555 1556 Handle s = java_lang_String::create_from_symbol(class_name, CHECK_NULL); 1557 // Translate to external class name format, i.e., convert '/' chars to '.' 1558 Handle string = java_lang_String::externalize_classname(s, CHECK_NULL); 1559 1560 JavaValue result(T_OBJECT); 1561 1562 InstanceKlass* spec_klass = SystemDictionary::ClassLoader_klass(); 1563 1564 // Call public unsynchronized loadClass(String) directly for all class loaders 1565 // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will 1566 // acquire a class-name based lock rather than the class loader object lock. 1567 // JDK < 7 already acquire the class loader lock in loadClass(String, boolean), 1568 // so the call to loadClassInternal() was not required. 1569 // 1570 // UnsyncloadClass flag means both call loadClass(String) and do 1571 // not acquire the class loader lock even for class loaders that are 1572 // not parallelCapable. This was a risky transitional 1573 // flag for diagnostic purposes only. It is risky to call 1574 // custom class loaders without synchronization. 1575 // WARNING If a custom class loader does NOT synchronizer findClass, or callers of 1576 // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field. 1577 // Do NOT assume this will be supported in future releases. 1578 // 1579 // Added MustCallLoadClassInternal in case we discover in the field 1580 // a customer that counts on this call 1581 if (MustCallLoadClassInternal && has_loadClassInternal()) { 1582 JavaCalls::call_special(&result, 1583 class_loader, 1584 spec_klass, 1585 vmSymbols::loadClassInternal_name(), 1586 vmSymbols::string_class_signature(), 1587 string, 1588 CHECK_NULL); 1589 } else { 1590 JavaCalls::call_virtual(&result, 1591 class_loader, 1592 spec_klass, 1593 vmSymbols::loadClass_name(), 1594 vmSymbols::string_class_signature(), 1595 string, 1596 CHECK_NULL); 1597 } 1598 1599 assert(result.get_type() == T_OBJECT, "just checking"); 1600 oop obj = (oop) result.get_jobject(); 1601 1602 // Primitive classes return null since forName() can not be 1603 // used to obtain any of the Class objects representing primitives or void 1604 if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) { 1605 InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj)); 1606 // For user defined Java class loaders, check that the name returned is 1607 // the same as that requested. This check is done for the bootstrap 1608 // loader when parsing the class file. 1609 if (class_name == k->name()) { 1610 return k; 1611 } 1612 } 1613 // Class is not found or has the wrong name, return NULL 1614 return NULL; 1615 } 1616 } 1617 1618 void SystemDictionary::define_instance_class(InstanceKlass* k, TRAPS) { 1619 1620 HandleMark hm(THREAD); 1621 ClassLoaderData* loader_data = k->class_loader_data(); 1622 Handle class_loader_h(THREAD, loader_data->class_loader()); 1623 1624 // for bootstrap and other parallel classloaders don't acquire lock, 1625 // use placeholder token 1626 // If a parallelCapable class loader calls define_instance_class instead of 1627 // find_or_define_instance_class to get here, we have a timing 1628 // hole with systemDictionary updates and check_constraints 1629 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) { 1630 assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, 1631 compute_loader_lock_object(class_loader_h, THREAD)), 1632 "define called without lock"); 1633 } 1634 1635 // Check class-loading constraints. Throw exception if violation is detected. 1636 // Grabs and releases SystemDictionary_lock 1637 // The check_constraints/find_class call and update_dictionary sequence 1638 // must be "atomic" for a specific class/classloader pair so we never 1639 // define two different instanceKlasses for that class/classloader pair. 1640 // Existing classloaders will call define_instance_class with the 1641 // classloader lock held 1642 // Parallel classloaders will call find_or_define_instance_class 1643 // which will require a token to perform the define class 1644 Symbol* name_h = k->name(); 1645 Dictionary* dictionary = loader_data->dictionary(); 1646 unsigned int d_hash = dictionary->compute_hash(name_h); 1647 int d_index = dictionary->hash_to_index(d_hash); 1648 check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK); 1649 1650 // Register class just loaded with class loader (placed in Vector) 1651 // Note we do this before updating the dictionary, as this can 1652 // fail with an OutOfMemoryError (if it does, we will *not* put this 1653 // class in the dictionary and will not update the class hierarchy). 1654 // JVMTI FollowReferences needs to find the classes this way. 1655 if (k->class_loader() != NULL) { 1656 methodHandle m(THREAD, Universe::loader_addClass_method()); 1657 JavaValue result(T_VOID); 1658 JavaCallArguments args(class_loader_h); 1659 args.push_oop(Handle(THREAD, k->java_mirror())); 1660 JavaCalls::call(&result, m, &args, CHECK); 1661 } 1662 1663 // Add the new class. We need recompile lock during update of CHA. 1664 { 1665 unsigned int p_hash = placeholders()->compute_hash(name_h); 1666 int p_index = placeholders()->hash_to_index(p_hash); 1667 1668 MutexLocker mu_r(Compile_lock, THREAD); 1669 1670 // Add to class hierarchy, initialize vtables, and do possible 1671 // deoptimizations. 1672 add_to_hierarchy(k, CHECK); // No exception, but can block 1673 1674 // Add to systemDictionary - so other classes can see it. 1675 // Grabs and releases SystemDictionary_lock 1676 update_dictionary(d_index, d_hash, p_index, p_hash, 1677 k, class_loader_h, THREAD); 1678 } 1679 k->eager_initialize(THREAD); 1680 1681 // notify jvmti 1682 if (JvmtiExport::should_post_class_load()) { 1683 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()"); 1684 JvmtiExport::post_class_load((JavaThread *) THREAD, k); 1685 1686 } 1687 class_define_event(k, loader_data); 1688 } 1689 1690 // Support parallel classloading 1691 // All parallel class loaders, including bootstrap classloader 1692 // lock a placeholder entry for this class/class_loader pair 1693 // to allow parallel defines of different classes for this class loader 1694 // With AllowParallelDefine flag==true, in case they do not synchronize around 1695 // FindLoadedClass/DefineClass, calls, we check for parallel 1696 // loading for them, wait if a defineClass is in progress 1697 // and return the initial requestor's results 1698 // This flag does not apply to the bootstrap classloader. 1699 // With AllowParallelDefine flag==false, call through to define_instance_class 1700 // which will throw LinkageError: duplicate class definition. 1701 // False is the requested default. 1702 // For better performance, the class loaders should synchronize 1703 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they 1704 // potentially waste time reading and parsing the bytestream. 1705 // Note: VM callers should ensure consistency of k/class_name,class_loader 1706 // Be careful when modifying this code: once you have run 1707 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS), 1708 // you need to find_and_remove it before returning. 1709 // So be careful to not exit with a CHECK_ macro betweeen these calls. 1710 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, 1711 InstanceKlass* k, TRAPS) { 1712 1713 Symbol* name_h = k->name(); // passed in class_name may be null 1714 ClassLoaderData* loader_data = class_loader_data(class_loader); 1715 Dictionary* dictionary = loader_data->dictionary(); 1716 1717 unsigned int d_hash = dictionary->compute_hash(name_h); 1718 int d_index = dictionary->hash_to_index(d_hash); 1719 1720 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS 1721 unsigned int p_hash = placeholders()->compute_hash(name_h); 1722 int p_index = placeholders()->hash_to_index(p_hash); 1723 PlaceholderEntry* probe; 1724 1725 { 1726 MutexLocker mu(SystemDictionary_lock, THREAD); 1727 // First check if class already defined 1728 if (UnsyncloadClass || (is_parallelDefine(class_loader))) { 1729 InstanceKlass* check = find_class(d_index, d_hash, name_h, dictionary); 1730 if (check != NULL) { 1731 return check; 1732 } 1733 } 1734 1735 // Acquire define token for this class/classloader 1736 probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD); 1737 // Wait if another thread defining in parallel 1738 // All threads wait - even those that will throw duplicate class: otherwise 1739 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails 1740 // if other thread has not finished updating dictionary 1741 while (probe->definer() != NULL) { 1742 SystemDictionary_lock->wait(); 1743 } 1744 // Only special cases allow parallel defines and can use other thread's results 1745 // Other cases fall through, and may run into duplicate defines 1746 // caught by finding an entry in the SystemDictionary 1747 if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) { 1748 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1749 SystemDictionary_lock->notify_all(); 1750 #ifdef ASSERT 1751 InstanceKlass* check = find_class(d_index, d_hash, name_h, dictionary); 1752 assert(check != NULL, "definer missed recording success"); 1753 #endif 1754 return probe->instance_klass(); 1755 } else { 1756 // This thread will define the class (even if earlier thread tried and had an error) 1757 probe->set_definer(THREAD); 1758 } 1759 } 1760 1761 define_instance_class(k, THREAD); 1762 1763 Handle linkage_exception = Handle(); // null handle 1764 1765 // definer must notify any waiting threads 1766 { 1767 MutexLocker mu(SystemDictionary_lock, THREAD); 1768 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data); 1769 assert(probe != NULL, "DEFINE_CLASS placeholder lost?"); 1770 if (probe != NULL) { 1771 if (HAS_PENDING_EXCEPTION) { 1772 linkage_exception = Handle(THREAD,PENDING_EXCEPTION); 1773 CLEAR_PENDING_EXCEPTION; 1774 } else { 1775 probe->set_instance_klass(k); 1776 } 1777 probe->set_definer(NULL); 1778 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD); 1779 SystemDictionary_lock->notify_all(); 1780 } 1781 } 1782 1783 // Can't throw exception while holding lock due to rank ordering 1784 if (linkage_exception() != NULL) { 1785 THROW_OOP_(linkage_exception(), NULL); // throws exception and returns 1786 } 1787 1788 return k; 1789 } 1790 1791 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) { 1792 // If class_loader is NULL we synchronize on _system_loader_lock_obj 1793 if (class_loader.is_null()) { 1794 return Handle(THREAD, _system_loader_lock_obj); 1795 } else { 1796 return class_loader; 1797 } 1798 } 1799 1800 // This method is added to check how often we have to wait to grab loader 1801 // lock. The results are being recorded in the performance counters defined in 1802 // ClassLoader::_sync_systemLoaderLockContentionRate and 1803 // ClassLoader::_sync_nonSystemLoaderLockConteionRate. 1804 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) { 1805 if (!UsePerfData) { 1806 return; 1807 } 1808 1809 assert(!loader_lock.is_null(), "NULL lock object"); 1810 1811 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock) 1812 == ObjectSynchronizer::owner_other) { 1813 // contention will likely happen, so increment the corresponding 1814 // contention counter. 1815 if (loader_lock() == _system_loader_lock_obj) { 1816 ClassLoader::sync_systemLoaderLockContentionRate()->inc(); 1817 } else { 1818 ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc(); 1819 } 1820 } 1821 } 1822 1823 // ---------------------------------------------------------------------------- 1824 // Lookup 1825 1826 InstanceKlass* SystemDictionary::find_class(int index, unsigned int hash, 1827 Symbol* class_name, 1828 Dictionary* dictionary) { 1829 assert_locked_or_safepoint(SystemDictionary_lock); 1830 return dictionary->find_class(index, hash, class_name); 1831 } 1832 1833 1834 // Basic find on classes in the midst of being loaded 1835 Symbol* SystemDictionary::find_placeholder(Symbol* class_name, 1836 ClassLoaderData* loader_data) { 1837 assert_locked_or_safepoint(SystemDictionary_lock); 1838 unsigned int p_hash = placeholders()->compute_hash(class_name); 1839 int p_index = placeholders()->hash_to_index(p_hash); 1840 return placeholders()->find_entry(p_index, p_hash, class_name, loader_data); 1841 } 1842 1843 1844 // Used for assertions and verification only 1845 // Precalculating the hash and index is an optimization because there are many lookups 1846 // before adding the class. 1847 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) { 1848 assert_locked_or_safepoint(SystemDictionary_lock); 1849 #ifndef ASSERT 1850 guarantee(VerifyBeforeGC || 1851 VerifyDuringGC || 1852 VerifyBeforeExit || 1853 VerifyDuringStartup || 1854 VerifyAfterGC, "too expensive"); 1855 #endif 1856 1857 Dictionary* dictionary = loader_data->dictionary(); 1858 unsigned int d_hash = dictionary->compute_hash(class_name); 1859 int d_index = dictionary->hash_to_index(d_hash); 1860 return find_class(d_index, d_hash, class_name, dictionary); 1861 } 1862 1863 1864 // ---------------------------------------------------------------------------- 1865 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock 1866 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in 1867 // before a new class is used. 1868 1869 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) { 1870 assert(k != NULL, "just checking"); 1871 assert_locked_or_safepoint(Compile_lock); 1872 1873 // Link into hierachy. Make sure the vtables are initialized before linking into 1874 k->append_to_sibling_list(); // add to superklass/sibling list 1875 k->process_interfaces(THREAD); // handle all "implements" declarations 1876 k->set_init_state(InstanceKlass::loaded); 1877 // Now flush all code that depended on old class hierarchy. 1878 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97) 1879 // Also, first reinitialize vtable because it may have gotten out of synch 1880 // while the new class wasn't connected to the class hierarchy. 1881 CodeCache::flush_dependents_on(k); 1882 } 1883 1884 // ---------------------------------------------------------------------------- 1885 // GC support 1886 1887 void SystemDictionary::always_strong_oops_do(OopClosure* blk) { 1888 roots_oops_do(blk, NULL); 1889 } 1890 1891 1892 #ifdef ASSERT 1893 class VerifySDReachableAndLiveClosure : public OopClosure { 1894 private: 1895 BoolObjectClosure* _is_alive; 1896 1897 template <class T> void do_oop_work(T* p) { 1898 oop obj = oopDesc::load_decode_heap_oop(p); 1899 guarantee(_is_alive->do_object_b(obj), "Oop in protection domain cache table must be live"); 1900 } 1901 1902 public: 1903 VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { } 1904 1905 virtual void do_oop(oop* p) { do_oop_work(p); } 1906 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 1907 }; 1908 #endif 1909 1910 // Assumes classes in the SystemDictionary are only unloaded at a safepoint 1911 // Note: anonymous classes are not in the SD. 1912 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive, 1913 GCTimer* gc_timer, 1914 bool do_cleaning) { 1915 1916 1917 bool unloading_occurred; 1918 { 1919 GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer); 1920 1921 // First, mark for unload all ClassLoaderData referencing a dead class loader. 1922 unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive, 1923 do_cleaning); 1924 } 1925 1926 if (unloading_occurred) { 1927 GCTraceTime(Debug, gc, phases) t("Dictionary", gc_timer); 1928 constraints()->purge_loader_constraints(); 1929 resolution_errors()->purge_resolution_errors(); 1930 } 1931 1932 { 1933 GCTraceTime(Debug, gc, phases) t("ProtectionDomainCacheTable", gc_timer); 1934 // Oops referenced by the protection domain cache table may get unreachable independently 1935 // of the class loader (eg. cached protection domain oops). So we need to 1936 // explicitly unlink them here. 1937 _pd_cache_table->unlink(is_alive); 1938 1939 #ifdef ASSERT 1940 VerifySDReachableAndLiveClosure cl(is_alive); 1941 _pd_cache_table->oops_do(&cl); 1942 #endif 1943 } 1944 1945 if (do_cleaning) { 1946 GCTraceTime(Debug, gc, phases) t("ResolvedMethodTable", gc_timer); 1947 ResolvedMethodTable::unlink(is_alive); 1948 } 1949 1950 return unloading_occurred; 1951 } 1952 1953 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) { 1954 strong->do_oop(&_java_system_loader); 1955 strong->do_oop(&_java_platform_loader); 1956 strong->do_oop(&_system_loader_lock_obj); 1957 CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);) 1958 1959 // Do strong roots marking if the closures are the same. 1960 if (strong == weak || !ClassUnloading) { 1961 // Only the protection domain oops contain references into the heap. Iterate 1962 // over all of them. 1963 _pd_cache_table->oops_do(strong); 1964 } else { 1965 if (weak != NULL) { 1966 _pd_cache_table->oops_do(weak); 1967 } 1968 } 1969 1970 // Visit extra methods 1971 invoke_method_table()->oops_do(strong); 1972 1973 if (weak != NULL) { 1974 ResolvedMethodTable::oops_do(weak); 1975 } 1976 } 1977 1978 void SystemDictionary::oops_do(OopClosure* f) { 1979 f->do_oop(&_java_system_loader); 1980 f->do_oop(&_java_platform_loader); 1981 f->do_oop(&_system_loader_lock_obj); 1982 CDS_ONLY(SystemDictionaryShared::oops_do(f);) 1983 1984 // Only the protection domain oops contain references into the heap. Iterate 1985 // over all of them. 1986 _pd_cache_table->oops_do(f); 1987 1988 // Visit extra methods 1989 invoke_method_table()->oops_do(f); 1990 1991 ResolvedMethodTable::oops_do(f); 1992 } 1993 1994 // CDS: scan and relocate all classes in the system dictionary. 1995 void SystemDictionary::classes_do(MetaspaceClosure* it) { 1996 ClassLoaderData::the_null_class_loader_data()->dictionary()->classes_do(it); 1997 } 1998 1999 // CDS: scan and relocate all classes referenced by _well_known_klasses[]. 2000 void SystemDictionary::well_known_klasses_do(MetaspaceClosure* it) { 2001 for (int id = FIRST_WKID; id < WKID_LIMIT; id++) { 2002 it->push(well_known_klass_addr((WKID)id)); 2003 } 2004 } 2005 2006 void SystemDictionary::methods_do(void f(Method*)) { 2007 // Walk methods in loaded classes 2008 ClassLoaderDataGraph::methods_do(f); 2009 // Walk method handle intrinsics 2010 invoke_method_table()->methods_do(f); 2011 } 2012 2013 class RemoveClassesClosure : public CLDClosure { 2014 public: 2015 void do_cld(ClassLoaderData* cld) { 2016 if (cld->is_system_class_loader_data() || cld->is_platform_class_loader_data()) { 2017 cld->dictionary()->remove_classes_in_error_state(); 2018 } 2019 } 2020 }; 2021 2022 void SystemDictionary::remove_classes_in_error_state() { 2023 ClassLoaderData::the_null_class_loader_data()->dictionary()->remove_classes_in_error_state(); 2024 RemoveClassesClosure rcc; 2025 ClassLoaderDataGraph::cld_do(&rcc); 2026 } 2027 2028 // ---------------------------------------------------------------------------- 2029 // Lazily load klasses 2030 2031 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) { 2032 // if multiple threads calling this function, only one thread will load 2033 // the class. The other threads will find the loaded version once the 2034 // class is loaded. 2035 Klass* aos = _abstract_ownable_synchronizer_klass; 2036 if (aos == NULL) { 2037 Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK); 2038 // Force a fence to prevent any read before the write completes 2039 OrderAccess::fence(); 2040 _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k); 2041 } 2042 } 2043 2044 // ---------------------------------------------------------------------------- 2045 // Initialization 2046 2047 void SystemDictionary::initialize(TRAPS) { 2048 // Allocate arrays 2049 _placeholders = new PlaceholderTable(_placeholder_table_size); 2050 _number_of_modifications = 0; 2051 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size); 2052 _resolution_errors = new ResolutionErrorTable(_resolution_error_size); 2053 _invoke_method_table = new SymbolPropertyTable(_invoke_method_size); 2054 _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize); 2055 2056 // Allocate private object used as system class loader lock 2057 _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK); 2058 // Initialize basic classes 2059 initialize_preloaded_classes(CHECK); 2060 } 2061 2062 // Compact table of directions on the initialization of klasses: 2063 static const short wk_init_info[] = { 2064 #define WK_KLASS_INIT_INFO(name, symbol, option) \ 2065 ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \ 2066 << SystemDictionary::CEIL_LG_OPTION_LIMIT) \ 2067 | (int)SystemDictionary::option ), 2068 WK_KLASSES_DO(WK_KLASS_INIT_INFO) 2069 #undef WK_KLASS_INIT_INFO 2070 0 2071 }; 2072 2073 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) { 2074 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob"); 2075 int info = wk_init_info[id - FIRST_WKID]; 2076 int sid = (info >> CEIL_LG_OPTION_LIMIT); 2077 Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid); 2078 InstanceKlass** klassp = &_well_known_klasses[id]; 2079 2080 bool must_load; 2081 #if INCLUDE_JVMCI 2082 if (EnableJVMCI) { 2083 // If JVMCI is enabled we require its classes to be found. 2084 must_load = (init_opt < SystemDictionary::Opt) || (init_opt == SystemDictionary::Jvmci); 2085 } else 2086 #endif 2087 { 2088 must_load = (init_opt < SystemDictionary::Opt); 2089 } 2090 2091 if ((*klassp) == NULL) { 2092 Klass* k; 2093 if (must_load) { 2094 k = resolve_or_fail(symbol, true, CHECK_0); // load required class 2095 } else { 2096 k = resolve_or_null(symbol, CHECK_0); // load optional klass 2097 } 2098 (*klassp) = (k == NULL) ? NULL : InstanceKlass::cast(k); 2099 } 2100 return ((*klassp) != NULL); 2101 } 2102 2103 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) { 2104 assert((int)start_id <= (int)limit_id, "IDs are out of order!"); 2105 for (int id = (int)start_id; id < (int)limit_id; id++) { 2106 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob"); 2107 int info = wk_init_info[id - FIRST_WKID]; 2108 int sid = (info >> CEIL_LG_OPTION_LIMIT); 2109 int opt = (info & right_n_bits(CEIL_LG_OPTION_LIMIT)); 2110 2111 initialize_wk_klass((WKID)id, opt, CHECK); 2112 } 2113 2114 // move the starting value forward to the limit: 2115 start_id = limit_id; 2116 } 2117 2118 void SystemDictionary::initialize_preloaded_classes(TRAPS) { 2119 assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once"); 2120 2121 // Create the ModuleEntry for java.base. This call needs to be done here, 2122 // after vmSymbols::initialize() is called but before any classes are pre-loaded. 2123 ClassLoader::classLoader_init2(CHECK); 2124 2125 // Preload commonly used klasses 2126 WKID scan = FIRST_WKID; 2127 // first do Object, then String, Class 2128 #if INCLUDE_CDS 2129 if (UseSharedSpaces) { 2130 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK); 2131 // Initialize the constant pool for the Object_class 2132 Object_klass()->constants()->restore_unshareable_info(CHECK); 2133 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK); 2134 } else 2135 #endif 2136 { 2137 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK); 2138 } 2139 2140 // Calculate offsets for String and Class classes since they are loaded and 2141 // can be used after this point. 2142 java_lang_String::compute_offsets(); 2143 java_lang_Class::compute_offsets(); 2144 2145 // Fixup mirrors for classes loaded before java.lang.Class. 2146 // These calls iterate over the objects currently in the perm gen 2147 // so calling them at this point is matters (not before when there 2148 // are fewer objects and not later after there are more objects 2149 // in the perm gen. 2150 Universe::initialize_basic_type_mirrors(CHECK); 2151 Universe::fixup_mirrors(CHECK); 2152 2153 // do a bunch more: 2154 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK); 2155 2156 // Preload ref klasses and set reference types 2157 InstanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER); 2158 InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass)); 2159 2160 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK); 2161 InstanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT); 2162 InstanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK); 2163 InstanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL); 2164 InstanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM); 2165 2166 // JSR 292 classes 2167 WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass); 2168 WKID jsr292_group_end = WK_KLASS_ENUM_NAME(VolatileCallSite_klass); 2169 initialize_wk_klasses_until(jsr292_group_start, scan, CHECK); 2170 initialize_wk_klasses_through(jsr292_group_end, scan, CHECK); 2171 initialize_wk_klasses_until(NOT_JVMCI(WKID_LIMIT) JVMCI_ONLY(FIRST_JVMCI_WKID), scan, CHECK); 2172 2173 _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass); 2174 _box_klasses[T_CHAR] = WK_KLASS(Character_klass); 2175 _box_klasses[T_FLOAT] = WK_KLASS(Float_klass); 2176 _box_klasses[T_DOUBLE] = WK_KLASS(Double_klass); 2177 _box_klasses[T_BYTE] = WK_KLASS(Byte_klass); 2178 _box_klasses[T_SHORT] = WK_KLASS(Short_klass); 2179 _box_klasses[T_INT] = WK_KLASS(Integer_klass); 2180 _box_klasses[T_LONG] = WK_KLASS(Long_klass); 2181 //_box_klasses[T_OBJECT] = WK_KLASS(object_klass); 2182 //_box_klasses[T_ARRAY] = WK_KLASS(object_klass); 2183 2184 { // Compute whether we should use loadClass or loadClassInternal when loading classes. 2185 Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature()); 2186 _has_loadClassInternal = (method != NULL); 2187 } 2188 { // Compute whether we should use checkPackageAccess or NOT 2189 Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature()); 2190 _has_checkPackageAccess = (method != NULL); 2191 } 2192 } 2193 2194 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer). 2195 // If so, returns the basic type it holds. If not, returns T_OBJECT. 2196 BasicType SystemDictionary::box_klass_type(Klass* k) { 2197 assert(k != NULL, ""); 2198 for (int i = T_BOOLEAN; i < T_VOID+1; i++) { 2199 if (_box_klasses[i] == k) 2200 return (BasicType)i; 2201 } 2202 return T_OBJECT; 2203 } 2204 2205 // Constraints on class loaders. The details of the algorithm can be 2206 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java 2207 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is 2208 // that the dictionary needs to maintain a set of contraints that 2209 // must be satisfied by all classes in the dictionary. 2210 // if defining is true, then LinkageError if already in dictionary 2211 // if initiating loader, then ok if InstanceKlass matches existing entry 2212 2213 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash, 2214 InstanceKlass* k, 2215 Handle class_loader, bool defining, 2216 TRAPS) { 2217 const char *linkage_error1 = NULL; 2218 const char *linkage_error2 = NULL; 2219 { 2220 Symbol* name = k->name(); 2221 ClassLoaderData *loader_data = class_loader_data(class_loader); 2222 2223 MutexLocker mu(SystemDictionary_lock, THREAD); 2224 2225 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data->dictionary()); 2226 if (check != NULL) { 2227 // if different InstanceKlass - duplicate class definition, 2228 // else - ok, class loaded by a different thread in parallel, 2229 // we should only have found it if it was done loading and ok to use 2230 // dictionary only holds instance classes, placeholders 2231 // also holds array classes 2232 2233 assert(check->is_instance_klass(), "noninstance in systemdictionary"); 2234 if ((defining == true) || (k != check)) { 2235 linkage_error1 = "loader (instance of "; 2236 linkage_error2 = "): attempted duplicate class definition for name: \""; 2237 } else { 2238 return; 2239 } 2240 } 2241 2242 #ifdef ASSERT 2243 Symbol* ph_check = find_placeholder(name, loader_data); 2244 assert(ph_check == NULL || ph_check == name, "invalid symbol"); 2245 #endif 2246 2247 if (linkage_error1 == NULL) { 2248 if (constraints()->check_or_update(k, class_loader, name) == false) { 2249 linkage_error1 = "loader constraint violation: loader (instance of "; 2250 linkage_error2 = ") previously initiated loading for a different type with name \""; 2251 } 2252 } 2253 } 2254 2255 // Throw error now if needed (cannot throw while holding 2256 // SystemDictionary_lock because of rank ordering) 2257 2258 if (linkage_error1) { 2259 ResourceMark rm(THREAD); 2260 const char* class_loader_name = loader_name(class_loader()); 2261 char* type_name = k->name()->as_C_string(); 2262 size_t buflen = strlen(linkage_error1) + strlen(class_loader_name) + 2263 strlen(linkage_error2) + strlen(type_name) + 2; // +2 for '"' and null byte. 2264 char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen); 2265 jio_snprintf(buf, buflen, "%s%s%s%s\"", linkage_error1, class_loader_name, linkage_error2, type_name); 2266 THROW_MSG(vmSymbols::java_lang_LinkageError(), buf); 2267 } 2268 } 2269 2270 2271 // Update class loader data dictionary - done after check_constraint and add_to_hierachy 2272 // have been called. 2273 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash, 2274 int p_index, unsigned int p_hash, 2275 InstanceKlass* k, 2276 Handle class_loader, 2277 TRAPS) { 2278 // Compile_lock prevents systemDictionary updates during compilations 2279 assert_locked_or_safepoint(Compile_lock); 2280 Symbol* name = k->name(); 2281 ClassLoaderData *loader_data = class_loader_data(class_loader); 2282 2283 { 2284 MutexLocker mu1(SystemDictionary_lock, THREAD); 2285 2286 // See whether biased locking is enabled and if so set it for this 2287 // klass. 2288 // Note that this must be done past the last potential blocking 2289 // point / safepoint. We enable biased locking lazily using a 2290 // VM_Operation to iterate the SystemDictionary and installing the 2291 // biasable mark word into each InstanceKlass's prototype header. 2292 // To avoid race conditions where we accidentally miss enabling the 2293 // optimization for one class in the process of being added to the 2294 // dictionary, we must not safepoint after the test of 2295 // BiasedLocking::enabled(). 2296 if (UseBiasedLocking && BiasedLocking::enabled()) { 2297 // Set biased locking bit for all loaded classes; it will be 2298 // cleared if revocation occurs too often for this type 2299 // NOTE that we must only do this when the class is initally 2300 // defined, not each time it is referenced from a new class loader 2301 if (k->class_loader() == class_loader()) { 2302 k->set_prototype_header(markOopDesc::biased_locking_prototype()); 2303 } 2304 } 2305 2306 // Make a new dictionary entry. 2307 Dictionary* dictionary = loader_data->dictionary(); 2308 InstanceKlass* sd_check = find_class(d_index, d_hash, name, dictionary); 2309 if (sd_check == NULL) { 2310 dictionary->add_klass(d_index, d_hash, name, k); 2311 notice_modification(); 2312 } 2313 #ifdef ASSERT 2314 sd_check = find_class(d_index, d_hash, name, dictionary); 2315 assert (sd_check != NULL, "should have entry in dictionary"); 2316 // Note: there may be a placeholder entry: for circularity testing 2317 // or for parallel defines 2318 #endif 2319 SystemDictionary_lock->notify_all(); 2320 } 2321 } 2322 2323 2324 // Try to find a class name using the loader constraints. The 2325 // loader constraints might know about a class that isn't fully loaded 2326 // yet and these will be ignored. 2327 Klass* SystemDictionary::find_constrained_instance_or_array_klass( 2328 Symbol* class_name, Handle class_loader, TRAPS) { 2329 2330 // First see if it has been loaded directly. 2331 // Force the protection domain to be null. (This removes protection checks.) 2332 Handle no_protection_domain; 2333 Klass* klass = find_instance_or_array_klass(class_name, class_loader, 2334 no_protection_domain, CHECK_NULL); 2335 if (klass != NULL) 2336 return klass; 2337 2338 // Now look to see if it has been loaded elsewhere, and is subject to 2339 // a loader constraint that would require this loader to return the 2340 // klass that is already loaded. 2341 if (FieldType::is_array(class_name)) { 2342 // For array classes, their Klass*s are not kept in the 2343 // constraint table. The element Klass*s are. 2344 FieldArrayInfo fd; 2345 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL)); 2346 if (t != T_OBJECT) { 2347 klass = Universe::typeArrayKlassObj(t); 2348 } else { 2349 MutexLocker mu(SystemDictionary_lock, THREAD); 2350 klass = constraints()->find_constrained_klass(fd.object_key(), class_loader); 2351 } 2352 // If element class already loaded, allocate array klass 2353 if (klass != NULL) { 2354 klass = klass->array_klass_or_null(fd.dimension()); 2355 } 2356 } else { 2357 MutexLocker mu(SystemDictionary_lock, THREAD); 2358 // Non-array classes are easy: simply check the constraint table. 2359 klass = constraints()->find_constrained_klass(class_name, class_loader); 2360 } 2361 2362 return klass; 2363 } 2364 2365 2366 bool SystemDictionary::add_loader_constraint(Symbol* class_name, 2367 Handle class_loader1, 2368 Handle class_loader2, 2369 Thread* THREAD) { 2370 ClassLoaderData* loader_data1 = class_loader_data(class_loader1); 2371 ClassLoaderData* loader_data2 = class_loader_data(class_loader2); 2372 2373 Symbol* constraint_name = NULL; 2374 if (!FieldType::is_array(class_name)) { 2375 constraint_name = class_name; 2376 } else { 2377 // For array classes, their Klass*s are not kept in the 2378 // constraint table. The element classes are. 2379 FieldArrayInfo fd; 2380 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false)); 2381 // primitive types always pass 2382 if (t != T_OBJECT) { 2383 return true; 2384 } else { 2385 constraint_name = fd.object_key(); 2386 } 2387 } 2388 2389 Dictionary* dictionary1 = loader_data1->dictionary(); 2390 unsigned int d_hash1 = dictionary1->compute_hash(constraint_name); 2391 int d_index1 = dictionary1->hash_to_index(d_hash1); 2392 2393 Dictionary* dictionary2 = loader_data2->dictionary(); 2394 unsigned int d_hash2 = dictionary2->compute_hash(constraint_name); 2395 int d_index2 = dictionary2->hash_to_index(d_hash2); 2396 2397 { 2398 MutexLocker mu_s(SystemDictionary_lock, THREAD); 2399 InstanceKlass* klass1 = find_class(d_index1, d_hash1, constraint_name, dictionary1); 2400 InstanceKlass* klass2 = find_class(d_index2, d_hash2, constraint_name, dictionary2); 2401 return constraints()->add_entry(constraint_name, klass1, class_loader1, 2402 klass2, class_loader2); 2403 } 2404 } 2405 2406 // Add entry to resolution error table to record the error when the first 2407 // attempt to resolve a reference to a class has failed. 2408 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which, 2409 Symbol* error, Symbol* message) { 2410 unsigned int hash = resolution_errors()->compute_hash(pool, which); 2411 int index = resolution_errors()->hash_to_index(hash); 2412 { 2413 MutexLocker ml(SystemDictionary_lock, Thread::current()); 2414 resolution_errors()->add_entry(index, hash, pool, which, error, message); 2415 } 2416 } 2417 2418 // Delete a resolution error for RedefineClasses for a constant pool is going away 2419 void SystemDictionary::delete_resolution_error(ConstantPool* pool) { 2420 resolution_errors()->delete_entry(pool); 2421 } 2422 2423 // Lookup resolution error table. Returns error if found, otherwise NULL. 2424 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which, 2425 Symbol** message) { 2426 unsigned int hash = resolution_errors()->compute_hash(pool, which); 2427 int index = resolution_errors()->hash_to_index(hash); 2428 { 2429 MutexLocker ml(SystemDictionary_lock, Thread::current()); 2430 ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which); 2431 if (entry != NULL) { 2432 *message = entry->message(); 2433 return entry->error(); 2434 } else { 2435 return NULL; 2436 } 2437 } 2438 } 2439 2440 2441 // Signature constraints ensure that callers and callees agree about 2442 // the meaning of type names in their signatures. This routine is the 2443 // intake for constraints. It collects them from several places: 2444 // 2445 // * LinkResolver::resolve_method (if check_access is true) requires 2446 // that the resolving class (the caller) and the defining class of 2447 // the resolved method (the callee) agree on each type in the 2448 // method's signature. 2449 // 2450 // * LinkResolver::resolve_interface_method performs exactly the same 2451 // checks. 2452 // 2453 // * LinkResolver::resolve_field requires that the constant pool 2454 // attempting to link to a field agree with the field's defining 2455 // class about the type of the field signature. 2456 // 2457 // * klassVtable::initialize_vtable requires that, when a class 2458 // overrides a vtable entry allocated by a superclass, that the 2459 // overriding method (i.e., the callee) agree with the superclass 2460 // on each type in the method's signature. 2461 // 2462 // * klassItable::initialize_itable requires that, when a class fills 2463 // in its itables, for each non-abstract method installed in an 2464 // itable, the method (i.e., the callee) agree with the interface 2465 // on each type in the method's signature. 2466 // 2467 // All those methods have a boolean (check_access, checkconstraints) 2468 // which turns off the checks. This is used from specialized contexts 2469 // such as bootstrapping, dumping, and debugging. 2470 // 2471 // No direct constraint is placed between the class and its 2472 // supertypes. Constraints are only placed along linked relations 2473 // between callers and callees. When a method overrides or implements 2474 // an abstract method in a supertype (superclass or interface), the 2475 // constraints are placed as if the supertype were the caller to the 2476 // overriding method. (This works well, since callers to the 2477 // supertype have already established agreement between themselves and 2478 // the supertype.) As a result of all this, a class can disagree with 2479 // its supertype about the meaning of a type name, as long as that 2480 // class neither calls a relevant method of the supertype, nor is 2481 // called (perhaps via an override) from the supertype. 2482 // 2483 // 2484 // SystemDictionary::check_signature_loaders(sig, l1, l2) 2485 // 2486 // Make sure all class components (including arrays) in the given 2487 // signature will be resolved to the same class in both loaders. 2488 // Returns the name of the type that failed a loader constraint check, or 2489 // NULL if no constraint failed. No exception except OOME is thrown. 2490 // Arrays are not added to the loader constraint table, their elements are. 2491 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature, 2492 Handle loader1, Handle loader2, 2493 bool is_method, TRAPS) { 2494 // Nothing to do if loaders are the same. 2495 if (loader1() == loader2()) { 2496 return NULL; 2497 } 2498 2499 SignatureStream sig_strm(signature, is_method); 2500 while (!sig_strm.is_done()) { 2501 if (sig_strm.is_object()) { 2502 Symbol* sig = sig_strm.as_symbol(CHECK_NULL); 2503 if (!add_loader_constraint(sig, loader1, loader2, THREAD)) { 2504 return sig; 2505 } 2506 } 2507 sig_strm.next(); 2508 } 2509 return NULL; 2510 } 2511 2512 2513 methodHandle SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid, 2514 Symbol* signature, 2515 TRAPS) { 2516 methodHandle empty; 2517 assert(MethodHandles::is_signature_polymorphic(iid) && 2518 MethodHandles::is_signature_polymorphic_intrinsic(iid) && 2519 iid != vmIntrinsics::_invokeGeneric, 2520 "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid)); 2521 2522 unsigned int hash = invoke_method_table()->compute_hash(signature, iid); 2523 int index = invoke_method_table()->hash_to_index(hash); 2524 SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid); 2525 methodHandle m; 2526 if (spe == NULL || spe->method() == NULL) { 2527 spe = NULL; 2528 // Must create lots of stuff here, but outside of the SystemDictionary lock. 2529 m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty)); 2530 if (!Arguments::is_interpreter_only()) { 2531 // Generate a compiled form of the MH intrinsic. 2532 AdapterHandlerLibrary::create_native_wrapper(m); 2533 // Check if have the compiled code. 2534 if (!m->has_compiled_code()) { 2535 THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(), 2536 "Out of space in CodeCache for method handle intrinsic", empty); 2537 } 2538 } 2539 // Now grab the lock. We might have to throw away the new method, 2540 // if a racing thread has managed to install one at the same time. 2541 { 2542 MutexLocker ml(SystemDictionary_lock, THREAD); 2543 spe = invoke_method_table()->find_entry(index, hash, signature, iid); 2544 if (spe == NULL) 2545 spe = invoke_method_table()->add_entry(index, hash, signature, iid); 2546 if (spe->method() == NULL) 2547 spe->set_method(m()); 2548 } 2549 } 2550 2551 assert(spe != NULL && spe->method() != NULL, ""); 2552 assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() && 2553 spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()), 2554 "MH intrinsic invariant"); 2555 return spe->method(); 2556 } 2557 2558 // Helper for unpacking the return value from linkMethod and linkCallSite. 2559 static methodHandle unpack_method_and_appendix(Handle mname, 2560 Klass* accessing_klass, 2561 objArrayHandle appendix_box, 2562 Handle* appendix_result, 2563 TRAPS) { 2564 methodHandle empty; 2565 if (mname.not_null()) { 2566 Method* m = java_lang_invoke_MemberName::vmtarget(mname()); 2567 if (m != NULL) { 2568 oop appendix = appendix_box->obj_at(0); 2569 if (TraceMethodHandles) { 2570 #ifndef PRODUCT 2571 ttyLocker ttyl; 2572 tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m)); 2573 m->print(); 2574 if (appendix != NULL) { tty->print("appendix = "); appendix->print(); } 2575 tty->cr(); 2576 #endif //PRODUCT 2577 } 2578 (*appendix_result) = Handle(THREAD, appendix); 2579 // the target is stored in the cpCache and if a reference to this 2580 // MethodName is dropped we need a way to make sure the 2581 // class_loader containing this method is kept alive. 2582 // FIXME: the appendix might also preserve this dependency. 2583 ClassLoaderData* this_key = accessing_klass->class_loader_data(); 2584 this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM 2585 return methodHandle(THREAD, m); 2586 } 2587 } 2588 THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty); 2589 return empty; 2590 } 2591 2592 methodHandle SystemDictionary::find_method_handle_invoker(Klass* klass, 2593 Symbol* name, 2594 Symbol* signature, 2595 Klass* accessing_klass, 2596 Handle *appendix_result, 2597 Handle *method_type_result, 2598 TRAPS) { 2599 methodHandle empty; 2600 assert(THREAD->can_call_java() ,""); 2601 Handle method_type = 2602 SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty)); 2603 2604 int ref_kind = JVM_REF_invokeVirtual; 2605 oop name_oop = StringTable::intern(name, CHECK_(empty)); 2606 Handle name_str (THREAD, name_oop); 2607 objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty)); 2608 assert(appendix_box->obj_at(0) == NULL, ""); 2609 2610 // This should not happen. JDK code should take care of that. 2611 if (accessing_klass == NULL || method_type.is_null()) { 2612 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty); 2613 } 2614 2615 // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName 2616 JavaCallArguments args; 2617 args.push_oop(Handle(THREAD, accessing_klass->java_mirror())); 2618 args.push_int(ref_kind); 2619 args.push_oop(Handle(THREAD, klass->java_mirror())); 2620 args.push_oop(name_str); 2621 args.push_oop(method_type); 2622 args.push_oop(appendix_box); 2623 JavaValue result(T_OBJECT); 2624 JavaCalls::call_static(&result, 2625 SystemDictionary::MethodHandleNatives_klass(), 2626 vmSymbols::linkMethod_name(), 2627 vmSymbols::linkMethod_signature(), 2628 &args, CHECK_(empty)); 2629 Handle mname(THREAD, (oop) result.get_jobject()); 2630 (*method_type_result) = method_type; 2631 return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD); 2632 } 2633 2634 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks. 2635 // We must ensure that all class loaders everywhere will reach this class, for any client. 2636 // This is a safe bet for public classes in java.lang, such as Object and String. 2637 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types. 2638 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util. 2639 static bool is_always_visible_class(oop mirror) { 2640 Klass* klass = java_lang_Class::as_Klass(mirror); 2641 if (klass->is_objArray_klass()) { 2642 klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type 2643 } 2644 if (klass->is_typeArray_klass()) { 2645 return true; // primitive array 2646 } 2647 assert(klass->is_instance_klass(), "%s", klass->external_name()); 2648 return klass->is_public() && 2649 (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) || // java.lang 2650 InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass())); // java.lang.invoke 2651 } 2652 2653 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given 2654 // signature, as interpreted relative to the given class loader. 2655 // Because of class loader constraints, all method handle usage must be 2656 // consistent with this loader. 2657 Handle SystemDictionary::find_method_handle_type(Symbol* signature, 2658 Klass* accessing_klass, 2659 TRAPS) { 2660 Handle empty; 2661 vmIntrinsics::ID null_iid = vmIntrinsics::_none; // distinct from all method handle invoker intrinsics 2662 unsigned int hash = invoke_method_table()->compute_hash(signature, null_iid); 2663 int index = invoke_method_table()->hash_to_index(hash); 2664 SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid); 2665 if (spe != NULL && spe->method_type() != NULL) { 2666 assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), ""); 2667 return Handle(THREAD, spe->method_type()); 2668 } else if (!THREAD->can_call_java()) { 2669 warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME 2670 return Handle(); // do not attempt from within compiler, unless it was cached 2671 } 2672 2673 Handle class_loader, protection_domain; 2674 if (accessing_klass != NULL) { 2675 class_loader = Handle(THREAD, accessing_klass->class_loader()); 2676 protection_domain = Handle(THREAD, accessing_klass->protection_domain()); 2677 } 2678 bool can_be_cached = true; 2679 int npts = ArgumentCount(signature).size(); 2680 objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty)); 2681 int arg = 0; 2682 Handle rt; // the return type from the signature 2683 ResourceMark rm(THREAD); 2684 for (SignatureStream ss(signature); !ss.is_done(); ss.next()) { 2685 oop mirror = NULL; 2686 if (can_be_cached) { 2687 // Use neutral class loader to lookup candidate classes to be placed in the cache. 2688 mirror = ss.as_java_mirror(Handle(), Handle(), 2689 SignatureStream::ReturnNull, CHECK_(empty)); 2690 if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) { 2691 // Fall back to accessing_klass context. 2692 can_be_cached = false; 2693 } 2694 } 2695 if (!can_be_cached) { 2696 // Resolve, throwing a real error if it doesn't work. 2697 mirror = ss.as_java_mirror(class_loader, protection_domain, 2698 SignatureStream::NCDFError, CHECK_(empty)); 2699 } 2700 assert(!oopDesc::is_null(mirror), "%s", ss.as_symbol(THREAD)->as_C_string()); 2701 if (ss.at_return_type()) 2702 rt = Handle(THREAD, mirror); 2703 else 2704 pts->obj_at_put(arg++, mirror); 2705 2706 // Check accessibility. 2707 if (ss.is_object() && accessing_klass != NULL) { 2708 Klass* sel_klass = java_lang_Class::as_Klass(mirror); 2709 mirror = NULL; // safety 2710 // Emulate ConstantPool::verify_constant_pool_resolve. 2711 if (sel_klass->is_objArray_klass()) 2712 sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass(); 2713 if (sel_klass->is_instance_klass()) { 2714 LinkResolver::check_klass_accessability(accessing_klass, sel_klass, CHECK_(empty)); 2715 } 2716 } 2717 } 2718 assert(arg == npts, ""); 2719 2720 // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType 2721 JavaCallArguments args(Handle(THREAD, rt())); 2722 args.push_oop(pts); 2723 JavaValue result(T_OBJECT); 2724 JavaCalls::call_static(&result, 2725 SystemDictionary::MethodHandleNatives_klass(), 2726 vmSymbols::findMethodHandleType_name(), 2727 vmSymbols::findMethodHandleType_signature(), 2728 &args, CHECK_(empty)); 2729 Handle method_type(THREAD, (oop) result.get_jobject()); 2730 2731 if (can_be_cached) { 2732 // We can cache this MethodType inside the JVM. 2733 MutexLocker ml(SystemDictionary_lock, THREAD); 2734 spe = invoke_method_table()->find_entry(index, hash, signature, null_iid); 2735 if (spe == NULL) 2736 spe = invoke_method_table()->add_entry(index, hash, signature, null_iid); 2737 if (spe->method_type() == NULL) { 2738 spe->set_method_type(method_type()); 2739 } 2740 } 2741 2742 // report back to the caller with the MethodType 2743 return method_type; 2744 } 2745 2746 // Ask Java code to find or construct a method handle constant. 2747 Handle SystemDictionary::link_method_handle_constant(Klass* caller, 2748 int ref_kind, //e.g., JVM_REF_invokeVirtual 2749 Klass* callee, 2750 Symbol* name_sym, 2751 Symbol* signature, 2752 TRAPS) { 2753 Handle empty; 2754 Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty)); 2755 Handle type; 2756 if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') { 2757 type = find_method_handle_type(signature, caller, CHECK_(empty)); 2758 } else if (caller == NULL) { 2759 // This should not happen. JDK code should take care of that. 2760 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty); 2761 } else { 2762 ResourceMark rm(THREAD); 2763 SignatureStream ss(signature, false); 2764 if (!ss.is_done()) { 2765 oop mirror = ss.as_java_mirror(Handle(THREAD, caller->class_loader()), 2766 Handle(THREAD, caller->protection_domain()), 2767 SignatureStream::NCDFError, CHECK_(empty)); 2768 type = Handle(THREAD, mirror); 2769 ss.next(); 2770 if (!ss.is_done()) type = Handle(); // error! 2771 } 2772 } 2773 if (type.is_null()) { 2774 THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty); 2775 } 2776 2777 // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle 2778 JavaCallArguments args; 2779 args.push_oop(Handle(THREAD, caller->java_mirror())); // the referring class 2780 args.push_int(ref_kind); 2781 args.push_oop(Handle(THREAD, callee->java_mirror())); // the target class 2782 args.push_oop(name); 2783 args.push_oop(type); 2784 JavaValue result(T_OBJECT); 2785 JavaCalls::call_static(&result, 2786 SystemDictionary::MethodHandleNatives_klass(), 2787 vmSymbols::linkMethodHandleConstant_name(), 2788 vmSymbols::linkMethodHandleConstant_signature(), 2789 &args, CHECK_(empty)); 2790 return Handle(THREAD, (oop) result.get_jobject()); 2791 } 2792 2793 // Ask Java code to find or construct a java.lang.invoke.CallSite for the given 2794 // name and signature, as interpreted relative to the given class loader. 2795 methodHandle SystemDictionary::find_dynamic_call_site_invoker(Klass* caller, 2796 Handle bootstrap_specifier, 2797 Symbol* name, 2798 Symbol* type, 2799 Handle *appendix_result, 2800 Handle *method_type_result, 2801 TRAPS) { 2802 methodHandle empty; 2803 Handle bsm, info; 2804 if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) { 2805 bsm = bootstrap_specifier; 2806 } else { 2807 assert(bootstrap_specifier->is_objArray(), ""); 2808 objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier()); 2809 int len = args->length(); 2810 assert(len >= 1, ""); 2811 bsm = Handle(THREAD, args->obj_at(0)); 2812 if (len > 1) { 2813 objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty)); 2814 for (int i = 1; i < len; i++) 2815 args1->obj_at_put(i-1, args->obj_at(i)); 2816 info = Handle(THREAD, args1); 2817 } 2818 } 2819 guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()), 2820 "caller must supply a valid BSM"); 2821 2822 Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty)); 2823 Handle method_type = find_method_handle_type(type, caller, CHECK_(empty)); 2824 2825 // This should not happen. JDK code should take care of that. 2826 if (caller == NULL || method_type.is_null()) { 2827 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty); 2828 } 2829 2830 objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty)); 2831 assert(appendix_box->obj_at(0) == NULL, ""); 2832 2833 // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix) 2834 JavaCallArguments args; 2835 args.push_oop(Handle(THREAD, caller->java_mirror())); 2836 args.push_oop(bsm); 2837 args.push_oop(method_name); 2838 args.push_oop(method_type); 2839 args.push_oop(info); 2840 args.push_oop(appendix_box); 2841 JavaValue result(T_OBJECT); 2842 JavaCalls::call_static(&result, 2843 SystemDictionary::MethodHandleNatives_klass(), 2844 vmSymbols::linkCallSite_name(), 2845 vmSymbols::linkCallSite_signature(), 2846 &args, CHECK_(empty)); 2847 Handle mname(THREAD, (oop) result.get_jobject()); 2848 (*method_type_result) = method_type; 2849 return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD); 2850 } 2851 2852 // Protection domain cache table handling 2853 2854 ProtectionDomainCacheEntry* SystemDictionary::cache_get(Handle protection_domain) { 2855 return _pd_cache_table->get(protection_domain); 2856 } 2857 2858 void SystemDictionary::reorder_dictionary_for_sharing() { 2859 ClassLoaderData::the_null_class_loader_data()->dictionary()->reorder_dictionary_for_sharing(); 2860 } 2861 2862 size_t SystemDictionary::count_bytes_for_buckets() { 2863 return ClassLoaderData::the_null_class_loader_data()->dictionary()->count_bytes_for_buckets(); 2864 } 2865 2866 size_t SystemDictionary::count_bytes_for_table() { 2867 return ClassLoaderData::the_null_class_loader_data()->dictionary()->count_bytes_for_table(); 2868 } 2869 2870 void SystemDictionary::copy_buckets(char* top, char* end) { 2871 ClassLoaderData::the_null_class_loader_data()->dictionary()->copy_buckets(top, end); 2872 } 2873 2874 void SystemDictionary::copy_table(char* top, char* end) { 2875 ClassLoaderData::the_null_class_loader_data()->dictionary()->copy_table(top, end); 2876 } 2877 2878 // ---------------------------------------------------------------------------- 2879 void SystemDictionary::print_shared(outputStream *st) { 2880 shared_dictionary()->print_on(st); 2881 } 2882 2883 void SystemDictionary::print_on(outputStream *st) { 2884 if (shared_dictionary() != NULL) { 2885 st->print_cr("Shared Dictionary"); 2886 shared_dictionary()->print_on(st); 2887 st->cr(); 2888 } 2889 2890 GCMutexLocker mu(SystemDictionary_lock); 2891 2892 ClassLoaderDataGraph::print_dictionary(st); 2893 2894 // Placeholders 2895 placeholders()->print_on(st); 2896 st->cr(); 2897 2898 // loader constraints - print under SD_lock 2899 constraints()->print_on(st); 2900 st->cr(); 2901 2902 _pd_cache_table->print_on(st); 2903 st->cr(); 2904 } 2905 2906 void SystemDictionary::verify() { 2907 guarantee(constraints() != NULL, 2908 "Verify of loader constraints failed"); 2909 guarantee(placeholders()->number_of_entries() >= 0, 2910 "Verify of placeholders failed"); 2911 2912 GCMutexLocker mu(SystemDictionary_lock); 2913 2914 // Verify dictionary 2915 ClassLoaderDataGraph::verify_dictionary(); 2916 2917 placeholders()->verify(); 2918 2919 // Verify constraint table 2920 guarantee(constraints() != NULL, "Verify of loader constraints failed"); 2921 constraints()->verify(placeholders()); 2922 2923 _pd_cache_table->verify(); 2924 } 2925 2926 void SystemDictionary::dump(outputStream *st, bool verbose) { 2927 assert_locked_or_safepoint(SystemDictionary_lock); 2928 if (verbose) { 2929 print_on(st); 2930 } else { 2931 if (shared_dictionary() != NULL) { 2932 shared_dictionary()->print_table_statistics(st, "Shared Dictionary"); 2933 } 2934 ClassLoaderDataGraph::print_dictionary_statistics(st); 2935 placeholders()->print_table_statistics(st, "Placeholder Table"); 2936 constraints()->print_table_statistics(st, "LoaderConstraints Table"); 2937 _pd_cache_table->print_table_statistics(st, "ProtectionDomainCache Table"); 2938 } 2939 } 2940 2941 // Utility for dumping dictionaries. 2942 SystemDictionaryDCmd::SystemDictionaryDCmd(outputStream* output, bool heap) : 2943 DCmdWithParser(output, heap), 2944 _verbose("-verbose", "Dump the content of each dictionary entry for all class loaders", 2945 "BOOLEAN", false, "false") { 2946 _dcmdparser.add_dcmd_option(&_verbose); 2947 } 2948 2949 void SystemDictionaryDCmd::execute(DCmdSource source, TRAPS) { 2950 VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSysDict, 2951 _verbose.value()); 2952 VMThread::execute(&dumper); 2953 } 2954 2955 int SystemDictionaryDCmd::num_arguments() { 2956 ResourceMark rm; 2957 SystemDictionaryDCmd* dcmd = new SystemDictionaryDCmd(NULL, false); 2958 if (dcmd != NULL) { 2959 DCmdMark mark(dcmd); 2960 return dcmd->_dcmdparser.num_arguments(); 2961 } else { 2962 return 0; 2963 } 2964 } 2965 2966 class CombineDictionariesClosure : public CLDClosure { 2967 private: 2968 Dictionary* _master_dictionary; 2969 public: 2970 CombineDictionariesClosure(Dictionary* master_dictionary) : 2971 _master_dictionary(master_dictionary) {} 2972 void do_cld(ClassLoaderData* cld) { 2973 ResourceMark rm; 2974 if (cld->is_system_class_loader_data() || cld->is_platform_class_loader_data()) { 2975 for (int i = 0; i < cld->dictionary()->table_size(); ++i) { 2976 Dictionary* curr_dictionary = cld->dictionary(); 2977 DictionaryEntry* p = curr_dictionary->bucket(i); 2978 while (p != NULL) { 2979 Symbol* name = p->instance_klass()->name(); 2980 unsigned int d_hash = _master_dictionary->compute_hash(name); 2981 int d_index = _master_dictionary->hash_to_index(d_hash); 2982 DictionaryEntry* next = p->next(); 2983 if (p->literal()->class_loader_data() != cld) { 2984 // This is an initiating class loader entry; don't use it 2985 log_trace(cds)("Skipping initiating cl entry: %s", name->as_C_string()); 2986 curr_dictionary->free_entry(p); 2987 } else { 2988 log_trace(cds)("Moved to boot dictionary: %s", name->as_C_string()); 2989 curr_dictionary->unlink_entry(p); 2990 p->set_pd_set(NULL); // pd_set is runtime only information and will be reconstructed. 2991 _master_dictionary->add_entry(d_index, p); 2992 } 2993 p = next; 2994 } 2995 *curr_dictionary->bucket_addr(i) = NULL; 2996 } 2997 } 2998 } 2999 }; 3000 3001 // Combining platform and system loader dictionaries into boot loader dictionaries. 3002 // During run time, we only have one shared dictionary. 3003 void SystemDictionary::combine_shared_dictionaries() { 3004 assert(DumpSharedSpaces, "dump time only"); 3005 Dictionary* master_dictionary = ClassLoaderData::the_null_class_loader_data()->dictionary(); 3006 CombineDictionariesClosure cdc(master_dictionary); 3007 ClassLoaderDataGraph::cld_do(&cdc); 3008 3009 // These tables are no longer valid or necessary. Keeping them around will 3010 // cause SystemDictionary::verify() to fail. Let's empty them. 3011 _placeholders = new PlaceholderTable(_placeholder_table_size); 3012 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size); 3013 3014 NOT_PRODUCT(SystemDictionary::verify()); 3015 } 3016 3017 // caller needs ResourceMark 3018 const char* SystemDictionary::loader_name(const oop loader) { 3019 return ((loader) == NULL ? "<bootloader>" : 3020 InstanceKlass::cast((loader)->klass())->name()->as_C_string()); 3021 } 3022 3023 // caller needs ResourceMark 3024 const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) { 3025 return (loader_data->class_loader() == NULL ? "<bootloader>" : 3026 SystemDictionary::loader_name(loader_data->class_loader())); 3027 }