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