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