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