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