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