1 /*
   2  * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classListParser.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/classLoaderData.inline.hpp"
  30 #include "classfile/classLoaderExt.hpp"
  31 #include "classfile/compactHashtable.inline.hpp"
  32 #include "classfile/dictionary.hpp"
  33 #include "classfile/javaClasses.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/systemDictionary.hpp"
  36 #include "classfile/systemDictionaryShared.hpp"
  37 #include "classfile/verificationType.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "logging/log.hpp"
  40 #include "memory/allocation.hpp"
  41 #include "memory/filemap.hpp"
  42 #include "memory/metadataFactory.hpp"
  43 #include "memory/metaspaceClosure.hpp"
  44 #include "memory/oopFactory.hpp"
  45 #include "memory/resourceArea.hpp"
  46 #include "oops/instanceKlass.hpp"
  47 #include "oops/klass.inline.hpp"
  48 #include "oops/objArrayOop.inline.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "oops/typeArrayOop.inline.hpp"
  51 #include "runtime/handles.inline.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/javaCalls.hpp"
  54 #include "runtime/mutexLocker.hpp"
  55 #include "utilities/hashtable.inline.hpp"
  56 #include "utilities/stringUtils.hpp"
  57 
  58 
  59 objArrayOop SystemDictionaryShared::_shared_protection_domains  =  NULL;
  60 objArrayOop SystemDictionaryShared::_shared_jar_urls            =  NULL;
  61 objArrayOop SystemDictionaryShared::_shared_jar_manifests       =  NULL;
  62 
  63 static Mutex* SharedDictionary_lock = NULL;
  64 
  65 void SystemDictionaryShared::initialize(TRAPS) {
  66   if (_java_system_loader != NULL) {
  67     SharedDictionary_lock = new Mutex(Mutex::leaf, "SharedDictionary_lock", true);
  68 
  69     // These classes need to be initialized before calling get_shared_jar_manifest(), etc.
  70     SystemDictionary::ByteArrayInputStream_klass()->initialize(CHECK);
  71     SystemDictionary::File_klass()->initialize(CHECK);
  72     SystemDictionary::Jar_Manifest_klass()->initialize(CHECK);
  73     SystemDictionary::CodeSource_klass()->initialize(CHECK);
  74   }
  75 }
  76 
  77 oop SystemDictionaryShared::shared_protection_domain(int index) {
  78   return _shared_protection_domains->obj_at(index);
  79 }
  80 
  81 oop SystemDictionaryShared::shared_jar_url(int index) {
  82   return _shared_jar_urls->obj_at(index);
  83 }
  84 
  85 oop SystemDictionaryShared::shared_jar_manifest(int index) {
  86   return _shared_jar_manifests->obj_at(index);
  87 }
  88 
  89 
  90 Handle SystemDictionaryShared::get_shared_jar_manifest(int shared_path_index, TRAPS) {
  91   Handle empty;
  92   Handle manifest ;
  93   if (shared_jar_manifest(shared_path_index) == NULL) {
  94     SharedClassPathEntry* ent = FileMapInfo::shared_path(shared_path_index);
  95     long size = ent->manifest_size();
  96     if (size <= 0) {
  97       return empty; // No manifest - return NULL handle
  98     }
  99 
 100     // ByteArrayInputStream bais = new ByteArrayInputStream(buf);
 101     InstanceKlass* bais_klass = SystemDictionary::ByteArrayInputStream_klass();
 102     Handle bais = bais_klass->allocate_instance_handle(CHECK_(empty));
 103     {
 104       const char* src = ent->manifest();
 105       assert(src != NULL, "No Manifest data");
 106       typeArrayOop buf = oopFactory::new_byteArray(size, CHECK_(empty));
 107       typeArrayHandle bufhandle(THREAD, buf);
 108       char* dst = (char*)(buf->byte_at_addr(0));
 109       memcpy(dst, src, (size_t)size);
 110 
 111       JavaValue result(T_VOID);
 112       JavaCalls::call_special(&result, bais, bais_klass,
 113                               vmSymbols::object_initializer_name(),
 114                               vmSymbols::byte_array_void_signature(),
 115                               bufhandle, CHECK_(empty));
 116     }
 117 
 118     // manifest = new Manifest(bais)
 119     InstanceKlass* manifest_klass = SystemDictionary::Jar_Manifest_klass();
 120     manifest = manifest_klass->allocate_instance_handle(CHECK_(empty));
 121     {
 122       JavaValue result(T_VOID);
 123       JavaCalls::call_special(&result, manifest, manifest_klass,
 124                               vmSymbols::object_initializer_name(),
 125                               vmSymbols::input_stream_void_signature(),
 126                               bais, CHECK_(empty));
 127     }
 128     atomic_set_shared_jar_manifest(shared_path_index, manifest());
 129   }
 130 
 131   manifest = Handle(THREAD, shared_jar_manifest(shared_path_index));
 132   assert(manifest.not_null(), "sanity");
 133   return manifest;
 134 }
 135 
 136 Handle SystemDictionaryShared::get_shared_jar_url(int shared_path_index, TRAPS) {
 137   Handle url_h;
 138   if (shared_jar_url(shared_path_index) == NULL) {
 139     JavaValue result(T_OBJECT);
 140     const char* path = FileMapInfo::shared_path_name(shared_path_index);
 141     Handle path_string = java_lang_String::create_from_str(path, CHECK_(url_h));
 142     Klass* classLoaders_klass =
 143         SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 144         JavaCalls::call_static(&result, classLoaders_klass,
 145                                vmSymbols::toFileURL_name(),
 146                                vmSymbols::toFileURL_signature(),
 147                                path_string, CHECK_(url_h));
 148 
 149     atomic_set_shared_jar_url(shared_path_index, (oop)result.get_jobject());
 150   }
 151 
 152   url_h = Handle(THREAD, shared_jar_url(shared_path_index));
 153   assert(url_h.not_null(), "sanity");
 154   return url_h;
 155 }
 156 
 157 Handle SystemDictionaryShared::get_package_name(Symbol* class_name, TRAPS) {
 158   ResourceMark rm(THREAD);
 159   Handle pkgname_string;
 160   char* pkgname = (char*) ClassLoader::package_from_name((const char*) class_name->as_C_string());
 161   if (pkgname != NULL) { // Package prefix found
 162     StringUtils::replace_no_expand(pkgname, "/", ".");
 163     pkgname_string = java_lang_String::create_from_str(pkgname,
 164                                                        CHECK_(pkgname_string));
 165   }
 166   return pkgname_string;
 167 }
 168 
 169 // Define Package for shared app classes from JAR file and also checks for
 170 // package sealing (all done in Java code)
 171 // See http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html
 172 void SystemDictionaryShared::define_shared_package(Symbol*  class_name,
 173                                                    Handle class_loader,
 174                                                    Handle manifest,
 175                                                    Handle url,
 176                                                    TRAPS) {
 177   assert(class_loader == _java_system_loader, "unexpected class loader");
 178   // get_package_name() returns a NULL handle if the class is in unnamed package
 179   Handle pkgname_string = get_package_name(class_name, CHECK);
 180   if (pkgname_string.not_null()) {
 181     Klass* app_classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
 182     JavaValue result(T_OBJECT);
 183     JavaCallArguments args(3);
 184     args.set_receiver(class_loader);
 185     args.push_oop(pkgname_string);
 186     args.push_oop(manifest);
 187     args.push_oop(url);
 188     JavaCalls::call_virtual(&result, app_classLoader_klass,
 189                             vmSymbols::defineOrCheckPackage_name(),
 190                             vmSymbols::defineOrCheckPackage_signature(),
 191                             &args,
 192                             CHECK);
 193   }
 194 }
 195 
 196 // Define Package for shared app/platform classes from named module
 197 void SystemDictionaryShared::define_shared_package(Symbol* class_name,
 198                                                    Handle class_loader,
 199                                                    ModuleEntry* mod_entry,
 200                                                    TRAPS) {
 201   assert(mod_entry != NULL, "module_entry should not be NULL");
 202   Handle module_handle(THREAD, mod_entry->module());
 203 
 204   Handle pkg_name = get_package_name(class_name, CHECK);
 205   assert(pkg_name.not_null(), "Package should not be null for class in named module");
 206 
 207   Klass* classLoader_klass;
 208   if (SystemDictionary::is_system_class_loader(class_loader())) {
 209     classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
 210   } else {
 211     assert(SystemDictionary::is_platform_class_loader(class_loader()), "unexpected classloader");
 212     classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass();
 213   }
 214 
 215   JavaValue result(T_OBJECT);
 216   JavaCallArguments args(2);
 217   args.set_receiver(class_loader);
 218   args.push_oop(pkg_name);
 219   args.push_oop(module_handle);
 220   JavaCalls::call_virtual(&result, classLoader_klass,
 221                           vmSymbols::definePackage_name(),
 222                           vmSymbols::definePackage_signature(),
 223                           &args,
 224                           CHECK);
 225 }
 226 
 227 // Get the ProtectionDomain associated with the CodeSource from the classloader.
 228 Handle SystemDictionaryShared::get_protection_domain_from_classloader(Handle class_loader,
 229                                                                       Handle url, TRAPS) {
 230   // CodeSource cs = new CodeSource(url, null);
 231   InstanceKlass* cs_klass = SystemDictionary::CodeSource_klass();
 232   Handle cs = cs_klass->allocate_instance_handle(CHECK_NH);
 233   JavaValue void_result(T_VOID);
 234   JavaCalls::call_special(&void_result, cs, cs_klass,
 235                           vmSymbols::object_initializer_name(),
 236                           vmSymbols::url_code_signer_array_void_signature(),
 237                           url, Handle(), CHECK_NH);
 238 
 239   // protection_domain = SecureClassLoader.getProtectionDomain(cs);
 240   Klass* secureClassLoader_klass = SystemDictionary::SecureClassLoader_klass();
 241   JavaValue obj_result(T_OBJECT);
 242   JavaCalls::call_virtual(&obj_result, class_loader, secureClassLoader_klass,
 243                           vmSymbols::getProtectionDomain_name(),
 244                           vmSymbols::getProtectionDomain_signature(),
 245                           cs, CHECK_NH);
 246   return Handle(THREAD, (oop)obj_result.get_jobject());
 247 }
 248 
 249 // Returns the ProtectionDomain associated with the JAR file identified by the url.
 250 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 251                                                             int shared_path_index,
 252                                                             Handle url,
 253                                                             TRAPS) {
 254   Handle protection_domain;
 255   if (shared_protection_domain(shared_path_index) == NULL) {
 256     Handle pd = get_protection_domain_from_classloader(class_loader, url, THREAD);
 257     atomic_set_shared_protection_domain(shared_path_index, pd());
 258   }
 259 
 260   // Acquire from the cache because if another thread beats the current one to
 261   // set the shared protection_domain and the atomic_set fails, the current thread
 262   // needs to get the updated protection_domain from the cache.
 263   protection_domain = Handle(THREAD, shared_protection_domain(shared_path_index));
 264   assert(protection_domain.not_null(), "sanity");
 265   return protection_domain;
 266 }
 267 
 268 // Returns the ProtectionDomain associated with the moduleEntry.
 269 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 270                                                             ModuleEntry* mod, TRAPS) {
 271   ClassLoaderData *loader_data = mod->loader_data();
 272   Handle protection_domain;
 273   if (mod->shared_protection_domain() == NULL) {
 274     Symbol* location = mod->location();
 275     if (location != NULL) {
 276       Handle url_string = java_lang_String::create_from_symbol(
 277                                  location, CHECK_(protection_domain));
 278       JavaValue result(T_OBJECT);
 279       Klass* classLoaders_klass =
 280         SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 281         JavaCalls::call_static(&result, classLoaders_klass, vmSymbols::toFileURL_name(),
 282                                vmSymbols::toFileURL_signature(),
 283                                url_string, CHECK_(protection_domain));
 284       Handle url = Handle(THREAD, (oop)result.get_jobject());
 285 
 286       Handle pd = get_protection_domain_from_classloader(class_loader, url, THREAD);
 287       mod->set_shared_protection_domain(loader_data, pd);
 288     }
 289   }
 290 
 291   protection_domain = Handle(THREAD, mod->shared_protection_domain());
 292   assert(protection_domain.not_null(), "sanity");
 293   return protection_domain;
 294 }
 295 
 296 // Initializes the java.lang.Package and java.security.ProtectionDomain objects associated with
 297 // the given InstanceKlass.
 298 // Returns the ProtectionDomain for the InstanceKlass.
 299 Handle SystemDictionaryShared::init_security_info(Handle class_loader, InstanceKlass* ik, TRAPS) {
 300   Handle pd;
 301 
 302   if (ik != NULL) {
 303     int index = ik->shared_classpath_index();
 304     assert(index >= 0, "Sanity");
 305     SharedClassPathEntry* ent = FileMapInfo::shared_path(index);
 306     Symbol* class_name = ik->name();
 307 
 308     if (ent->is_modules_image()) {
 309       // For shared app/platform classes originated from the run-time image:
 310       //   The ProtectionDomains are cached in the corresponding ModuleEntries
 311       //   for fast access by the VM.
 312       ResourceMark rm;
 313       ClassLoaderData *loader_data =
 314                 ClassLoaderData::class_loader_data(class_loader());
 315       PackageEntryTable* pkgEntryTable = loader_data->packages();
 316       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_(pd));
 317       if (pkg_name != NULL) {
 318         PackageEntry* pkg_entry = pkgEntryTable->lookup_only(pkg_name);
 319         if (pkg_entry != NULL) {
 320           ModuleEntry* mod_entry = pkg_entry->module();
 321           pd = get_shared_protection_domain(class_loader, mod_entry, THREAD);
 322           define_shared_package(class_name, class_loader, mod_entry, CHECK_(pd));
 323         }
 324       }
 325     } else {
 326       // For shared app/platform classes originated from JAR files on the class path:
 327       //   Each of the 3 SystemDictionaryShared::_shared_xxx arrays has the same length
 328       //   as the shared classpath table in the shared archive (see
 329       //   FileMap::_shared_path_table in filemap.hpp for details).
 330       //
 331       //   If a shared InstanceKlass k is loaded from the class path, let
 332       //
 333       //     index = k->shared_classpath_index():
 334       //
 335       //   FileMap::_shared_path_table[index] identifies the JAR file that contains k.
 336       //
 337       //   k's protection domain is:
 338       //
 339       //     ProtectionDomain pd = _shared_protection_domains[index];
 340       //
 341       //   and k's Package is initialized using
 342       //
 343       //     manifest = _shared_jar_manifests[index];
 344       //     url = _shared_jar_urls[index];
 345       //     define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 346       //
 347       //   Note that if an element of these 3 _shared_xxx arrays is NULL, it will be initialized by
 348       //   the corresponding SystemDictionaryShared::get_shared_xxx() function.
 349       Handle manifest = get_shared_jar_manifest(index, CHECK_(pd));
 350       Handle url = get_shared_jar_url(index, CHECK_(pd));
 351       define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 352       pd = get_shared_protection_domain(class_loader, index, url, CHECK_(pd));
 353     }
 354   }
 355   return pd;
 356 }
 357 
 358 bool SystemDictionaryShared::is_sharing_possible(ClassLoaderData* loader_data) {
 359   oop class_loader = loader_data->class_loader();
 360   return (class_loader == NULL ||
 361           SystemDictionary::is_system_class_loader(class_loader) ||
 362           SystemDictionary::is_platform_class_loader(class_loader));
 363 }
 364 
 365 // Currently AppCDS only archives classes from the run-time image, the
 366 // -Xbootclasspath/a path, the class path, and the module path.
 367 //
 368 // Check if a shared class can be loaded by the specific classloader. Following
 369 // are the "visible" archived classes for different classloaders.
 370 //
 371 // NULL classloader:
 372 //   - see SystemDictionary::is_shared_class_visible()
 373 // Platform classloader:
 374 //   - Module class from runtime image. ModuleEntry must be defined in the
 375 //     classloader.
 376 // App classloader:
 377 //   - Module Class from runtime image and module path. ModuleEntry must be defined in the
 378 //     classloader.
 379 //   - Class from -cp. The class must have no PackageEntry defined in any of the
 380 //     boot/platform/app classloader, or must be in the unnamed module defined in the
 381 //     AppClassLoader.
 382 bool SystemDictionaryShared::is_shared_class_visible_for_classloader(
 383                                                      InstanceKlass* ik,
 384                                                      Handle class_loader,
 385                                                      const char* pkg_string,
 386                                                      Symbol* pkg_name,
 387                                                      PackageEntry* pkg_entry,
 388                                                      ModuleEntry* mod_entry,
 389                                                      TRAPS) {
 390   assert(class_loader.not_null(), "Class loader should not be NULL");
 391   assert(Universe::is_module_initialized(), "Module system is not initialized");
 392   ResourceMark rm(THREAD);
 393 
 394   int path_index = ik->shared_classpath_index();
 395   SharedClassPathEntry* ent =
 396             (SharedClassPathEntry*)FileMapInfo::shared_path(path_index);
 397 
 398   if (SystemDictionary::is_platform_class_loader(class_loader())) {
 399     assert(ent != NULL, "shared class for PlatformClassLoader should have valid SharedClassPathEntry");
 400     // The PlatformClassLoader can only load archived class originated from the
 401     // run-time image. The class' PackageEntry/ModuleEntry must be
 402     // defined by the PlatformClassLoader.
 403     if (mod_entry != NULL) {
 404       // PackageEntry/ModuleEntry is found in the classloader. Check if the
 405       // ModuleEntry's location agrees with the archived class' origination.
 406       if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 407         return true; // Module class from the runtime image
 408       }
 409     }
 410   } else if (SystemDictionary::is_system_class_loader(class_loader())) {
 411     assert(ent != NULL, "shared class for system loader should have valid SharedClassPathEntry");
 412     if (pkg_string == NULL) {
 413       // The archived class is in the unnamed package. Currently, the boot image
 414       // does not contain any class in the unnamed package.
 415       assert(!ent->is_modules_image(), "Class in the unnamed package must be from the classpath");
 416       if (path_index >= ClassLoaderExt::app_class_paths_start_index()) {
 417         assert(path_index < ClassLoaderExt::app_module_paths_start_index(), "invalid path_index");
 418         return true;
 419       }
 420     } else {
 421       // Check if this is from a PackageEntry/ModuleEntry defined in the AppClassloader.
 422       if (pkg_entry == NULL) {
 423         // It's not guaranteed that the class is from the classpath if the
 424         // PackageEntry cannot be found from the AppClassloader. Need to check
 425         // the boot and platform classloader as well.
 426         if (get_package_entry(pkg_name, ClassLoaderData::class_loader_data_or_null(SystemDictionary::java_platform_loader())) == NULL &&
 427             get_package_entry(pkg_name, ClassLoaderData::the_null_class_loader_data()) == NULL) {
 428           // The PackageEntry is not defined in any of the boot/platform/app classloaders.
 429           // The archived class must from -cp path and not from the runtime image.
 430           if (!ent->is_modules_image() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 431                                           path_index < ClassLoaderExt::app_module_paths_start_index()) {
 432             return true;
 433           }
 434         }
 435       } else if (mod_entry != NULL) {
 436         // The package/module is defined in the AppClassLoader. We support
 437         // archiving application module class from the runtime image or from
 438         // a named module from a module path.
 439         // Packages from the -cp path are in the unnamed_module.
 440         if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 441           // shared module class from runtime image
 442           return true;
 443         } else if (pkg_entry->in_unnamed_module() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 444             path_index < ClassLoaderExt::app_module_paths_start_index()) {
 445           // shared class from -cp
 446           DEBUG_ONLY( \
 447             ClassLoaderData* loader_data = class_loader_data(class_loader); \
 448             assert(mod_entry == loader_data->unnamed_module(), "the unnamed module is not defined in the classloader");)
 449           return true;
 450         } else {
 451           if(!pkg_entry->in_unnamed_module() &&
 452               (path_index >= ClassLoaderExt::app_module_paths_start_index())&&
 453               (path_index < FileMapInfo::get_number_of_shared_paths()) &&
 454               (strcmp(ent->name(), ClassLoader::skip_uri_protocol(mod_entry->location()->as_C_string())) == 0)) {
 455             // shared module class from module path
 456             return true;
 457           } else {
 458             assert(path_index < FileMapInfo::get_number_of_shared_paths(), "invalid path_index");
 459           }
 460         }
 461       }
 462     }
 463   } else {
 464     // TEMP: if a shared class can be found by a custom loader, consider it visible now.
 465     // FIXME: is this actually correct?
 466     return true;
 467   }
 468   return false;
 469 }
 470 
 471 // The following stack shows how this code is reached:
 472 //
 473 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 474 //   [1] JVM_FindLoadedClass
 475 //   [2] java.lang.ClassLoader.findLoadedClass0()
 476 //   [3] java.lang.ClassLoader.findLoadedClass()
 477 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 478 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 479 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 480 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 481 //
 482 // AppCDS supports fast class loading for these 2 built-in class loaders:
 483 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 484 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 485 // with the following assumptions (based on the JDK core library source code):
 486 //
 487 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 488 //     load the named class.
 489 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 490 // [c] At this point, if the named class was loaded by the
 491 //     AppClassLoader during archive dump time, we know that it must be
 492 //     loaded by the AppClassLoader during run time, and will not be loaded
 493 //     by a delegated class loader. This is true because we have checked the
 494 //     CLASSPATH and module path to ensure compatibility between dump time and
 495 //     run time.
 496 //     (The above paragraph is also true for the PlatformClassLoader).
 497 //
 498 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 499 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 500 // the archive (subject to checks inside is_shared_class_visible_for_classloader()).
 501 // This allows us to improve start-up because we avoid decoding the classfile,
 502 // and avoid delegating to the parent loader (since we know the parent will not find
 503 // this class).
 504 //
 505 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 506 // needs to be redesigned.
 507 //
 508 // An alternative is to modify the Java code of BuiltinClassLoader.loadClassOrNull().
 509 //
 510 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 511                  Symbol* name, Handle class_loader, TRAPS) {
 512   InstanceKlass* k = NULL;
 513   if (UseSharedSpaces) {
 514     if (!FileMapInfo::current_info()->header()->has_platform_or_app_classes()) {
 515       return NULL;
 516     }
 517 
 518     if (shared_dictionary() != NULL &&
 519         (SystemDictionary::is_system_class_loader(class_loader()) ||
 520          SystemDictionary::is_platform_class_loader(class_loader()))) {
 521       // Fix for 4474172; see evaluation for more details
 522       class_loader = Handle(
 523         THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 524       ClassLoaderData *loader_data = register_loader(class_loader);
 525       Dictionary* dictionary = loader_data->dictionary();
 526 
 527       unsigned int d_hash = dictionary->compute_hash(name);
 528 
 529       bool DoObjectLock = true;
 530       if (is_parallelCapable(class_loader)) {
 531         DoObjectLock = false;
 532       }
 533 
 534       // Make sure we are synchronized on the class loader before we proceed
 535       //
 536       // Note: currently, find_or_load_shared_class is called only from
 537       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 538       // which are parallel-capable loaders, so this lock is NOT taken.
 539       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 540       check_loader_lock_contention(lockObject, THREAD);
 541       ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 542 
 543       {
 544         MutexLocker mu(SystemDictionary_lock, THREAD);
 545         Klass* check = find_class(d_hash, name, dictionary);
 546         if (check != NULL) {
 547           return InstanceKlass::cast(check);
 548         }
 549       }
 550 
 551       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 552       if (k != NULL) {
 553         define_instance_class(k, CHECK_NULL);
 554       }
 555     }
 556   }
 557   return k;
 558 }
 559 
 560 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 561                  Symbol* class_name, Handle class_loader, TRAPS) {
 562   assert(UseSharedSpaces, "must be");
 563   assert(shared_dictionary() != NULL, "already checked");
 564   Klass* k = shared_dictionary()->find_class_for_builtin_loader(class_name);
 565 
 566   if (k != NULL) {
 567     InstanceKlass* ik = InstanceKlass::cast(k);
 568     if ((ik->is_shared_app_class() &&
 569          SystemDictionary::is_system_class_loader(class_loader()))  ||
 570         (ik->is_shared_platform_class() &&
 571          SystemDictionary::is_platform_class_loader(class_loader()))) {
 572       Handle protection_domain =
 573         SystemDictionaryShared::init_security_info(class_loader, ik, CHECK_NULL);
 574       return load_shared_class(ik, class_loader, protection_domain, THREAD);
 575     }
 576   }
 577 
 578   return NULL;
 579 }
 580 
 581 void SystemDictionaryShared::oops_do(OopClosure* f) {
 582   f->do_oop((oop*)&_shared_protection_domains);
 583   f->do_oop((oop*)&_shared_jar_urls);
 584   f->do_oop((oop*)&_shared_jar_manifests);
 585 }
 586 
 587 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) {
 588   if (_shared_protection_domains == NULL) {
 589     _shared_protection_domains = oopFactory::new_objArray(
 590         SystemDictionary::ProtectionDomain_klass(), size, CHECK);
 591   }
 592 }
 593 
 594 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) {
 595   if (_shared_jar_urls == NULL) {
 596     _shared_jar_urls = oopFactory::new_objArray(
 597         SystemDictionary::URL_klass(), size, CHECK);
 598   }
 599 }
 600 
 601 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) {
 602   if (_shared_jar_manifests == NULL) {
 603     _shared_jar_manifests = oopFactory::new_objArray(
 604         SystemDictionary::Jar_Manifest_klass(), size, CHECK);
 605   }
 606 }
 607 
 608 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) {
 609   allocate_shared_protection_domain_array(size, CHECK);
 610   allocate_shared_jar_url_array(size, CHECK);
 611   allocate_shared_jar_manifest_array(size, CHECK);
 612 }
 613 
 614 // This function is called for loading only UNREGISTERED classes
 615 InstanceKlass* SystemDictionaryShared::lookup_from_stream(const Symbol* class_name,
 616                                                           Handle class_loader,
 617                                                           Handle protection_domain,
 618                                                           const ClassFileStream* cfs,
 619                                                           TRAPS) {
 620   if (shared_dictionary() == NULL) {
 621     return NULL;
 622   }
 623   if (class_name == NULL) {  // don't do this for anonymous classes
 624     return NULL;
 625   }
 626   if (class_loader.is_null() ||
 627       SystemDictionary::is_system_class_loader(class_loader()) ||
 628       SystemDictionary::is_platform_class_loader(class_loader())) {
 629     // Do nothing for the BUILTIN loaders.
 630     return NULL;
 631   }
 632 
 633   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 634   Klass* k;
 635 
 636   { // UNREGISTERED loader
 637     if (!shared_dictionary()->class_exists_for_unregistered_loader(class_name)) {
 638       // No classes of this name for unregistered loaders.
 639       return NULL;
 640     }
 641 
 642     int clsfile_size  = cfs->length();
 643     int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 644 
 645     k = shared_dictionary()->find_class_for_unregistered_loader(class_name,
 646                                                                 clsfile_size, clsfile_crc32);
 647   }
 648 
 649   if (k == NULL) { // not archived
 650     return NULL;
 651   }
 652 
 653   return acquire_class_for_current_thread(InstanceKlass::cast(k), class_loader,
 654                                           protection_domain, THREAD);
 655 }
 656 
 657 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 658                    InstanceKlass *ik,
 659                    Handle class_loader,
 660                    Handle protection_domain,
 661                    TRAPS) {
 662   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 663 
 664   {
 665     MutexLocker mu(SharedDictionary_lock, THREAD);
 666     if (ik->class_loader_data() != NULL) {
 667       //    ik is already loaded (by this loader or by a different loader)
 668       // or ik is being loaded by a different thread (by this loader or by a different loader)
 669       return NULL;
 670     }
 671 
 672     // No other thread has acquired this yet, so give it to *this thread*
 673     ik->set_class_loader_data(loader_data);
 674   }
 675 
 676   // No longer holding SharedDictionary_lock
 677   // No need to lock, as <ik> can be held only by a single thread.
 678   loader_data->add_class(ik);
 679 
 680   // Load and check super/interfaces, restore unsharable info
 681   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain, THREAD);
 682   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
 683     // TODO: clean up <ik> so it can be used again
 684     return NULL;
 685   }
 686 
 687   return shared_klass;
 688 }
 689 
 690 bool SystemDictionaryShared::add_non_builtin_klass(Symbol* name,
 691                                                    ClassLoaderData* loader_data,
 692                                                    InstanceKlass* k,
 693                                                    TRAPS) {
 694   assert(DumpSharedSpaces, "only when dumping");
 695   assert(boot_loader_dictionary() != NULL, "must be");
 696 
 697   if (boot_loader_dictionary()->add_non_builtin_klass(name, loader_data, k)) {
 698     MutexLocker mu_r(Compile_lock, THREAD); // not really necessary, but add_to_hierarchy asserts this.
 699     add_to_hierarchy(k, CHECK_0);
 700     return true;
 701   }
 702   return false;
 703 }
 704 
 705 // This function is called to resolve the super/interfaces of shared classes for
 706 // non-built-in loaders. E.g., ChildClass in the below example
 707 // where "super:" (and optionally "interface:") have been specified.
 708 //
 709 // java/lang/Object id: 0
 710 // Interface   id: 2 super: 0 source: cust.jar
 711 // ChildClass  id: 4 super: 0 interfaces: 2 source: cust.jar
 712 Klass* SystemDictionaryShared::dump_time_resolve_super_or_fail(
 713     Symbol* child_name, Symbol* class_name, Handle class_loader,
 714     Handle protection_domain, bool is_superclass, TRAPS) {
 715 
 716   assert(DumpSharedSpaces, "only when dumping");
 717 
 718   ClassListParser* parser = ClassListParser::instance();
 719   if (parser == NULL) {
 720     // We're still loading the well-known classes, before the ClassListParser is created.
 721     return NULL;
 722   }
 723   if (child_name->equals(parser->current_class_name())) {
 724     // When this function is called, all the numbered super and interface types
 725     // must have already been loaded. Hence this function is never recursively called.
 726     if (is_superclass) {
 727       return parser->lookup_super_for_current_class(class_name);
 728     } else {
 729       return parser->lookup_interface_for_current_class(class_name);
 730     }
 731   } else {
 732     // The VM is not trying to resolve a super type of parser->current_class_name().
 733     // Instead, it's resolving an error class (because parser->current_class_name() has
 734     // failed parsing or verification). Don't do anything here.
 735     return NULL;
 736   }
 737 }
 738 
 739 struct SharedMiscInfo {
 740   Klass* _klass;
 741   int _clsfile_size;
 742   int _clsfile_crc32;
 743 };
 744 
 745 static GrowableArray<SharedMiscInfo>* misc_info_array = NULL;
 746 
 747 void SystemDictionaryShared::set_shared_class_misc_info(Klass* k, ClassFileStream* cfs) {
 748   assert(DumpSharedSpaces, "only when dumping");
 749   int clsfile_size  = cfs->length();
 750   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 751 
 752   if (misc_info_array == NULL) {
 753     misc_info_array = new (ResourceObj::C_HEAP, mtClass) GrowableArray<SharedMiscInfo>(20, /*c heap*/ true);
 754   }
 755 
 756   SharedMiscInfo misc_info;
 757   DEBUG_ONLY({
 758       for (int i=0; i<misc_info_array->length(); i++) {
 759         misc_info = misc_info_array->at(i);
 760         assert(misc_info._klass != k, "cannot call set_shared_class_misc_info twice for the same class");
 761       }
 762     });
 763 
 764   misc_info._klass = k;
 765   misc_info._clsfile_size = clsfile_size;
 766   misc_info._clsfile_crc32 = clsfile_crc32;
 767 
 768   misc_info_array->append(misc_info);
 769 }
 770 
 771 void SystemDictionaryShared::init_shared_dictionary_entry(Klass* k, DictionaryEntry* ent) {
 772   SharedDictionaryEntry* entry = (SharedDictionaryEntry*)ent;
 773   entry->_id = -1;
 774   entry->_clsfile_size = -1;
 775   entry->_clsfile_crc32 = -1;
 776   entry->_verifier_constraints = NULL;
 777   entry->_verifier_constraint_flags = NULL;
 778 
 779   if (misc_info_array != NULL) {
 780     for (int i=0; i<misc_info_array->length(); i++) {
 781       SharedMiscInfo misc_info = misc_info_array->at(i);
 782       if (misc_info._klass == k) {
 783         entry->_clsfile_size = misc_info._clsfile_size;
 784         entry->_clsfile_crc32 = misc_info._clsfile_crc32;
 785         misc_info_array->remove_at(i);
 786         return;
 787       }
 788     }
 789   }
 790 }
 791 
 792 bool SystemDictionaryShared::add_verification_constraint(Klass* k, Symbol* name,
 793          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 794   assert(DumpSharedSpaces, "called at dump time only");
 795 
 796   // Skip anonymous classes, which are not archived as they are not in
 797   // dictionary (see assert_no_anonymoys_classes_in_dictionaries() in
 798   // VM_PopulateDumpSharedSpace::doit()).
 799   if (k->class_loader_data()->is_anonymous()) {
 800     return true; // anonymous classes are not archived, skip
 801   }
 802 
 803   SharedDictionaryEntry* entry = ((SharedDictionary*)(k->class_loader_data()->dictionary()))->find_entry_for(k);
 804   ResourceMark rm;
 805   // Lambda classes are not archived and will be regenerated at runtime.
 806   if (entry == NULL && strstr(k->name()->as_C_string(), "Lambda$") != NULL) {
 807     return true;
 808   }
 809   assert(entry != NULL, "class should be in dictionary before being verified");
 810   entry->add_verification_constraint(name, from_name, from_field_is_protected,
 811                                      from_is_array, from_is_object);
 812   if (entry->is_builtin()) {
 813     // For builtin class loaders, we can try to complete the verification check at dump time,
 814     // because we can resolve all the constraint classes.
 815     return false;
 816   } else {
 817     // For non-builtin class loaders, we cannot complete the verification check at dump time,
 818     // because at dump time we don't know how to resolve classes for such loaders.
 819     return true;
 820   }
 821 }
 822 
 823 void SystemDictionaryShared::finalize_verification_constraints() {
 824   boot_loader_dictionary()->finalize_verification_constraints();
 825 }
 826 
 827 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
 828                                                              TRAPS) {
 829   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
 830   SharedDictionaryEntry* entry = shared_dictionary()->find_entry_for(klass);
 831   assert(entry != NULL, "call this only for shared classes");
 832   entry->check_verification_constraints(klass, THREAD);
 833 }
 834 
 835 SharedDictionaryEntry* SharedDictionary::find_entry_for(Klass* klass) {
 836   Symbol* class_name = klass->name();
 837   unsigned int hash = compute_hash(class_name);
 838   int index = hash_to_index(hash);
 839 
 840   for (SharedDictionaryEntry* entry = bucket(index);
 841                               entry != NULL;
 842                               entry = entry->next()) {
 843     if (entry->hash() == hash && entry->literal() == klass) {
 844       return entry;
 845     }
 846   }
 847 
 848   return NULL;
 849 }
 850 
 851 void SharedDictionary::finalize_verification_constraints() {
 852   int bytes = 0, count = 0;
 853   for (int index = 0; index < table_size(); index++) {
 854     for (SharedDictionaryEntry *probe = bucket(index);
 855                                 probe != NULL;
 856                                probe = probe->next()) {
 857       int n = probe->finalize_verification_constraints();
 858       if (n > 0) {
 859         bytes += n;
 860         count ++;
 861       }
 862     }
 863   }
 864   if (log_is_enabled(Info, cds, verification)) {
 865     double avg = 0;
 866     if (count > 0) {
 867       avg = double(bytes) / double(count);
 868     }
 869     log_info(cds, verification)("Recorded verification constraints for %d classes = %d bytes (avg = %.2f bytes) ", count, bytes, avg);
 870   }
 871 }
 872 
 873 void SharedDictionaryEntry::add_verification_constraint(Symbol* name,
 874          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
 875   if (_verifier_constraints == NULL) {
 876     _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<Symbol*>(8, true, mtClass);
 877   }
 878   if (_verifier_constraint_flags == NULL) {
 879     _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, true, mtClass);
 880   }
 881   GrowableArray<Symbol*>* vc_array = (GrowableArray<Symbol*>*)_verifier_constraints;
 882   for (int i=0; i<vc_array->length(); i+= 2) {
 883     if (name      == vc_array->at(i) &&
 884         from_name == vc_array->at(i+1)) {
 885       return;
 886     }
 887   }
 888   vc_array->append(name);
 889   vc_array->append(from_name);
 890 
 891   GrowableArray<char>* vcflags_array = (GrowableArray<char>*)_verifier_constraint_flags;
 892   char c = 0;
 893   c |= from_field_is_protected ? FROM_FIELD_IS_PROTECTED : 0;
 894   c |= from_is_array           ? FROM_IS_ARRAY           : 0;
 895   c |= from_is_object          ? FROM_IS_OBJECT          : 0;
 896   vcflags_array->append(c);
 897 
 898   if (log_is_enabled(Trace, cds, verification)) {
 899     ResourceMark rm;
 900     log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s",
 901                                  instance_klass()->external_name(), from_name->as_klass_external_name(),
 902                                  name->as_klass_external_name());
 903   }
 904 }
 905 
 906 int SharedDictionaryEntry::finalize_verification_constraints() {
 907   assert(DumpSharedSpaces, "called at dump time only");
 908   Thread* THREAD = Thread::current();
 909   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
 910   GrowableArray<Symbol*>* vc_array = (GrowableArray<Symbol*>*)_verifier_constraints;
 911   GrowableArray<char>* vcflags_array = (GrowableArray<char>*)_verifier_constraint_flags;
 912 
 913   if (vc_array != NULL) {
 914     if (log_is_enabled(Trace, cds, verification)) {
 915       ResourceMark rm;
 916       log_trace(cds, verification)("finalize_verification_constraint: %s",
 917                                    literal()->external_name());
 918     }
 919 
 920     // Copy the constraints from C_HEAP-alloced GrowableArrays to Metaspace-alloced
 921     // Arrays
 922     int size = 0;
 923     {
 924       // FIXME: change this to be done after relocation, so we can use symbol offset??
 925       int length = vc_array->length();
 926       Array<Symbol*>* out = MetadataFactory::new_array<Symbol*>(loader_data, length, 0, THREAD);
 927       assert(out != NULL, "Dump time allocation failure would have aborted VM");
 928       for (int i=0; i<length; i++) {
 929         out->at_put(i, vc_array->at(i));
 930       }
 931       _verifier_constraints = out;
 932       size += out->size() * BytesPerWord;
 933       delete vc_array;
 934     }
 935     {
 936       int length = vcflags_array->length();
 937       Array<char>* out = MetadataFactory::new_array<char>(loader_data, length, 0, THREAD);
 938       assert(out != NULL, "Dump time allocation failure would have aborted VM");
 939       for (int i=0; i<length; i++) {
 940         out->at_put(i, vcflags_array->at(i));
 941       }
 942       _verifier_constraint_flags = out;
 943       size += out->size() * BytesPerWord;
 944       delete vcflags_array;
 945     }
 946 
 947     return size;
 948   }
 949   return 0;
 950 }
 951 
 952 void SharedDictionaryEntry::check_verification_constraints(InstanceKlass* klass, TRAPS) {
 953   Array<Symbol*>* vc_array = (Array<Symbol*>*)_verifier_constraints;
 954   Array<char>* vcflags_array = (Array<char>*)_verifier_constraint_flags;
 955 
 956   if (vc_array != NULL) {
 957     int length = vc_array->length();
 958     for (int i=0; i<length; i+=2) {
 959       Symbol* name      = vc_array->at(i);
 960       Symbol* from_name = vc_array->at(i+1);
 961       char c = vcflags_array->at(i/2);
 962 
 963       bool from_field_is_protected = (c & FROM_FIELD_IS_PROTECTED) ? true : false;
 964       bool from_is_array           = (c & FROM_IS_ARRAY)           ? true : false;
 965       bool from_is_object          = (c & FROM_IS_OBJECT)          ? true : false;
 966 
 967       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
 968          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
 969       if (!ok) {
 970         ResourceMark rm(THREAD);
 971         stringStream ss;
 972 
 973         ss.print_cr("Bad type on operand stack");
 974         ss.print_cr("Exception Details:");
 975         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
 976         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
 977                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
 978         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
 979       }
 980     }
 981   }
 982 }
 983 
 984 void SharedDictionaryEntry::metaspace_pointers_do(MetaspaceClosure* it) {
 985   it->push((Array<Symbol*>**)&_verifier_constraints);
 986   it->push((Array<char>**)&_verifier_constraint_flags);
 987 }
 988 
 989 bool SharedDictionary::add_non_builtin_klass(const Symbol* class_name,
 990                                              ClassLoaderData* loader_data,
 991                                              InstanceKlass* klass) {
 992 
 993   assert(DumpSharedSpaces, "supported only when dumping");
 994   assert(klass != NULL, "adding NULL klass");
 995   assert(klass->name() == class_name, "sanity check on name");
 996   assert(klass->shared_classpath_index() < 0,
 997          "the shared classpath index should not be set for shared class loaded by the custom loaders");
 998 
 999   // Add an entry for a non-builtin class.
1000   // For a shared class for custom class loaders, SystemDictionary::resolve_or_null will
1001   // not find this class, because is_builtin() is false.
1002   unsigned int hash = compute_hash(class_name);
1003   int index = hash_to_index(hash);
1004 
1005   for (SharedDictionaryEntry* entry = bucket(index);
1006                               entry != NULL;
1007                               entry = entry->next()) {
1008     if (entry->hash() == hash) {
1009       Klass* klass = (Klass*)entry->literal();
1010       if (klass->name() == class_name && klass->class_loader_data() == loader_data) {
1011         // There is already a class defined with the same name
1012         return false;
1013       }
1014     }
1015   }
1016 
1017   assert(Dictionary::entry_size() >= sizeof(SharedDictionaryEntry), "must be big enough");
1018   SharedDictionaryEntry* entry = (SharedDictionaryEntry*)new_entry(hash, klass);
1019   add_entry(index, entry);
1020 
1021   assert(entry->is_unregistered(), "sanity");
1022   assert(!entry->is_builtin(), "sanity");
1023   return true;
1024 }
1025 
1026 
1027 //-----------------
1028 // SharedDictionary
1029 //-----------------
1030 
1031 
1032 Klass* SharedDictionary::find_class_for_builtin_loader(const Symbol* name) const {
1033   SharedDictionaryEntry* entry = get_entry_for_builtin_loader(name);
1034   return entry != NULL ? entry->instance_klass() : (Klass*)NULL;
1035 }
1036 
1037 Klass* SharedDictionary::find_class_for_unregistered_loader(const Symbol* name,
1038                                                             int clsfile_size,
1039                                                             int clsfile_crc32) const {
1040 
1041   const SharedDictionaryEntry* entry = get_entry_for_unregistered_loader(name,
1042                                                                          clsfile_size,
1043                                                                          clsfile_crc32);
1044   return entry != NULL ? entry->instance_klass() : (Klass*)NULL;
1045 }
1046 
1047 void SharedDictionary::update_entry(Klass* klass, int id) {
1048   assert(DumpSharedSpaces, "supported only when dumping");
1049   Symbol* class_name = klass->name();
1050   unsigned int hash = compute_hash(class_name);
1051   int index = hash_to_index(hash);
1052 
1053   for (SharedDictionaryEntry* entry = bucket(index);
1054                               entry != NULL;
1055                               entry = entry->next()) {
1056     if (entry->hash() == hash && entry->literal() == klass) {
1057       entry->_id = id;
1058       return;
1059     }
1060   }
1061 
1062   ShouldNotReachHere();
1063 }
1064 
1065 SharedDictionaryEntry* SharedDictionary::get_entry_for_builtin_loader(const Symbol* class_name) const {
1066   assert(!DumpSharedSpaces, "supported only when at runtime");
1067   unsigned int hash = compute_hash(class_name);
1068   const int index = hash_to_index(hash);
1069 
1070   for (SharedDictionaryEntry* entry = bucket(index);
1071                               entry != NULL;
1072                               entry = entry->next()) {
1073     if (entry->hash() == hash && entry->equals(class_name)) {
1074       if (entry->is_builtin()) {
1075         return entry;
1076       }
1077     }
1078   }
1079   return NULL;
1080 }
1081 
1082 SharedDictionaryEntry* SharedDictionary::get_entry_for_unregistered_loader(const Symbol* class_name,
1083                                                                            int clsfile_size,
1084                                                                            int clsfile_crc32) const {
1085   assert(!DumpSharedSpaces, "supported only when at runtime");
1086   unsigned int hash = compute_hash(class_name);
1087   int index = hash_to_index(hash);
1088 
1089   for (SharedDictionaryEntry* entry = bucket(index);
1090                               entry != NULL;
1091                               entry = entry->next()) {
1092     if (entry->hash() == hash && entry->equals(class_name)) {
1093       if (entry->is_unregistered()) {
1094         if (clsfile_size == -1) {
1095           // We're called from class_exists_for_unregistered_loader. At run time, we want to
1096           // compute the CRC of a ClassFileStream only if there is an UNREGISTERED class
1097           // with the matching name.
1098           return entry;
1099         } else {
1100           // We're called from find_class_for_unregistered_loader
1101           if (entry->_clsfile_size && clsfile_crc32 == entry->_clsfile_crc32) {
1102             return entry;
1103           }
1104         }
1105 
1106         // There can be only 1 class with this name for unregistered loaders.
1107         return NULL;
1108       }
1109     }
1110   }
1111   return NULL;
1112 }