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