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