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