rev 12858 : 8184323: compile-time guard some UseSharedSpaces-only coding with the INCLUDE_CDS macro

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