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