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