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