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