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