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