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