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