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