1 /*
   2  * Copyright (c) 2014, 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 "classfile/classFileStream.hpp"
  27 #include "classfile/classListParser.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/classLoaderData.inline.hpp"
  30 #include "classfile/classLoaderDataGraph.hpp"
  31 #include "classfile/classLoaderExt.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/resourceHash.hpp"
  57 #include "utilities/stringUtils.hpp"
  58 
  59 
  60 objArrayOop SystemDictionaryShared::_shared_protection_domains  =  NULL;
  61 objArrayOop SystemDictionaryShared::_shared_jar_urls            =  NULL;
  62 objArrayOop SystemDictionaryShared::_shared_jar_manifests       =  NULL;
  63 DEBUG_ONLY(bool SystemDictionaryShared::_checked_excluded_classes = false;)
  64 
  65 class DumpTimeSharedClassInfo: public CHeapObj<mtClass> {
  66 public:
  67   struct DTConstraint {
  68     Symbol* _name;
  69     Symbol* _from_name;
  70     DTConstraint() : _name(NULL), _from_name(NULL) {}
  71     DTConstraint(Symbol* n, Symbol* fn) : _name(n), _from_name(fn) {}
  72   };
  73 
  74   InstanceKlass*               _klass;
  75   int                          _id;
  76   int                          _clsfile_size;
  77   int                          _clsfile_crc32;
  78   bool                         _excluded;
  79   GrowableArray<DTConstraint>* _verifier_constraints;
  80   GrowableArray<char>*         _verifier_constraint_flags;
  81 
  82   DumpTimeSharedClassInfo() {
  83     _klass = NULL;
  84     _id = -1;
  85     _clsfile_size = -1;
  86     _clsfile_crc32 = -1;
  87     _excluded = false;
  88     _verifier_constraints = NULL;
  89     _verifier_constraint_flags = NULL;
  90   }
  91 
  92   void add_verification_constraint(InstanceKlass* k, Symbol* name,
  93          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object);
  94 
  95   bool is_builtin() {
  96     return SystemDictionaryShared::is_builtin(_klass);
  97   }
  98 
  99   int num_constraints() {
 100     if (_verifier_constraint_flags != NULL) {
 101       return _verifier_constraint_flags->length();
 102     } else {
 103       return 0;
 104     }
 105   }
 106 
 107   void metaspace_pointers_do(MetaspaceClosure* it) {
 108     it->push(&_klass);
 109     if (_verifier_constraints != NULL) {
 110       for (int i = 0; i < _verifier_constraints->length(); i++) {
 111         DTConstraint* cons = _verifier_constraints->adr_at(i);
 112         it->push(&cons->_name);
 113         it->push(&cons->_from_name);
 114       }
 115     }
 116   }
 117 };
 118 
 119 class DumpTimeSharedClassTable: public ResourceHashtable<
 120   InstanceKlass*,
 121   DumpTimeSharedClassInfo,
 122   primitive_hash<InstanceKlass*>,
 123   primitive_equals<InstanceKlass*>,
 124   15889, // prime number
 125   ResourceObj::C_HEAP>
 126 {
 127   int _builtin_count;
 128   int _unregistered_count;
 129 public:
 130   DumpTimeSharedClassInfo* find_or_allocate_info_for(InstanceKlass* k) {
 131     DumpTimeSharedClassInfo* p = get(k);
 132     if (p == NULL) {
 133       assert(!SystemDictionaryShared::checked_excluded_classes(),
 134              "no new classes can be added after check_excluded_classes");
 135       put(k, DumpTimeSharedClassInfo());
 136       p = get(k);
 137       assert(p != NULL, "sanity");
 138       p->_klass = k;
 139     }
 140     return p;
 141   }
 142 
 143   class CountClassByCategory : StackObj {
 144     DumpTimeSharedClassTable* _table;
 145   public:
 146     CountClassByCategory(DumpTimeSharedClassTable* table) : _table(table) {}
 147     bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
 148       if (SystemDictionaryShared::is_builtin(k)) {
 149         ++ _table->_builtin_count;
 150       } else {
 151         ++ _table->_unregistered_count;
 152       }
 153       return true; // keep on iterating
 154     }
 155   };
 156 
 157   void update_counts() {
 158     CountClassByCategory counter(this);
 159     iterate(&counter);
 160   }
 161 
 162   int count_of(bool is_builtin) const {
 163     if (is_builtin) {
 164       return _builtin_count;
 165     } else {
 166       return _unregistered_count;
 167     }
 168   }
 169 };
 170 
 171 class RunTimeSharedClassInfo {
 172 public:
 173   struct CrcInfo {
 174     int _clsfile_size;
 175     int _clsfile_crc32;
 176   };
 177 
 178   // This is different than  DumpTimeSharedClassInfo::DTConstraint. We use
 179   // u4 instead of Symbol* to save space on 64-bit CPU.
 180   struct RTConstraint {
 181     u4 _name;
 182     u4 _from_name;
 183   };
 184 
 185   InstanceKlass* _klass;
 186   int _num_constraints;
 187 
 188   // optional CrcInfo      _crc;  (only for UNREGISTERED classes)
 189   // optional RTConstraint _verifier_constraints[_num_constraints]
 190   // optional char         _verifier_constraint_flags[_num_constraints]
 191 
 192 private:
 193   static size_t header_size_size() {
 194     return sizeof(RunTimeSharedClassInfo);
 195   }
 196   static size_t crc_size(InstanceKlass* klass) {
 197     if (!SystemDictionaryShared::is_builtin(klass)) {
 198       return sizeof(CrcInfo);
 199     } else {
 200       return 0;
 201     }
 202   }
 203   static size_t verifier_constraints_size(int num_constraints) {
 204     return sizeof(RTConstraint) * num_constraints;
 205   }
 206   static size_t verifier_constraint_flags_size(int num_constraints) {
 207     return sizeof(char) * num_constraints;
 208   }
 209 
 210 public:
 211   static size_t byte_size(InstanceKlass* klass, int num_constraints) {
 212     return header_size_size() +
 213            crc_size(klass) +
 214            verifier_constraints_size(num_constraints) +
 215            verifier_constraint_flags_size(num_constraints);
 216   }
 217 
 218 private:
 219   size_t crc_offset() const {
 220     return header_size_size();
 221   }
 222   size_t verifier_constraints_offset() const {
 223     return crc_offset() + crc_size(_klass);
 224   }
 225   size_t verifier_constraint_flags_offset() const {
 226     return verifier_constraints_offset() + verifier_constraints_size(_num_constraints);
 227   }
 228 
 229   void check_constraint_offset(int i) const {
 230     assert(0 <= i && i < _num_constraints, "sanity");
 231   }
 232 
 233 public:
 234   CrcInfo* crc() const {
 235     assert(crc_size(_klass) > 0, "must be");
 236     return (CrcInfo*)(address(this) + crc_offset());
 237   }
 238   RTConstraint* verifier_constraints() {
 239     assert(_num_constraints > 0, "sanity");
 240     return (RTConstraint*)(address(this) + verifier_constraints_offset());
 241   }
 242   RTConstraint* verifier_constraint_at(int i) {
 243     check_constraint_offset(i);
 244     return verifier_constraints() + i;
 245   }
 246 
 247   char* verifier_constraint_flags() {
 248     assert(_num_constraints > 0, "sanity");
 249     return (char*)(address(this) + verifier_constraint_flags_offset());
 250   }
 251 
 252   void init(DumpTimeSharedClassInfo& info) {
 253     _klass = info._klass;
 254     _num_constraints = info.num_constraints();
 255     if (!SystemDictionaryShared::is_builtin(_klass)) {
 256       CrcInfo* c = crc();
 257       c->_clsfile_size = info._clsfile_size;
 258       c->_clsfile_crc32 = info._clsfile_crc32;
 259     }
 260     if (_num_constraints > 0) {
 261       RTConstraint* constraints = verifier_constraints();
 262       char* flags = verifier_constraint_flags();
 263       int i;
 264       for (i = 0; i < _num_constraints; i++) {
 265         constraints[i]._name      = MetaspaceShared::object_delta_u4(info._verifier_constraints->at(i)._name);
 266         constraints[i]._from_name = MetaspaceShared::object_delta_u4(info._verifier_constraints->at(i)._from_name);
 267       }
 268       for (i = 0; i < _num_constraints; i++) {
 269         flags[i] = info._verifier_constraint_flags->at(i);
 270       }
 271     }
 272   }
 273 
 274   bool matches(int clsfile_size, int clsfile_crc32) const {
 275     return crc()->_clsfile_size  == clsfile_size &&
 276            crc()->_clsfile_crc32 == clsfile_crc32;
 277   }
 278 
 279   Symbol* get_constraint_name(int i) {
 280     return (Symbol*)(SharedBaseAddress + verifier_constraint_at(i)->_name);
 281   }
 282   Symbol* get_constraint_from_name(int i) {
 283     return (Symbol*)(SharedBaseAddress + verifier_constraint_at(i)->_from_name);
 284   }
 285 
 286   char get_constraint_flag(int i) {
 287     check_constraint_offset(i);
 288     return verifier_constraint_flags()[i];
 289   }
 290 
 291 private:
 292   // ArchiveCompactor::allocate() has reserved a pointer immediately before
 293   // archived InstanceKlasses. We can use this slot to do a quick
 294   // lookup of InstanceKlass* -> RunTimeSharedClassInfo* without
 295   // building a new hashtable.
 296   //
 297   //  info_pointer_addr(klass) --> 0x0100   RunTimeSharedClassInfo*
 298   //  InstanceKlass* klass     --> 0x0108   <C++ vtbl>
 299   //                               0x0110   fields from Klass ...
 300   static RunTimeSharedClassInfo** info_pointer_addr(InstanceKlass* klass) {
 301     return &((RunTimeSharedClassInfo**)klass)[-1];
 302   }
 303 
 304 public:
 305   static RunTimeSharedClassInfo* get_for(InstanceKlass* klass) {
 306     return *info_pointer_addr(klass);
 307   }
 308   static void set_for(InstanceKlass* klass, RunTimeSharedClassInfo* record) {
 309     *info_pointer_addr(klass) = record;
 310   }
 311 
 312   // Used by RunTimeSharedDictionary to implement OffsetCompactHashtable::EQUALS
 313   static inline bool EQUALS(
 314        const RunTimeSharedClassInfo* value, Symbol* key, int len_unused) {
 315     return (value->_klass->name() == key);
 316   }
 317 };
 318 
 319 class RunTimeSharedDictionary : public OffsetCompactHashtable<
 320   Symbol*,
 321   const RunTimeSharedClassInfo*,
 322   RunTimeSharedClassInfo::EQUALS> {};
 323 
 324 static DumpTimeSharedClassTable* _dumptime_table = NULL;
 325 static RunTimeSharedDictionary _builtin_dictionary;
 326 static RunTimeSharedDictionary _unregistered_dictionary;
 327 
 328 oop SystemDictionaryShared::shared_protection_domain(int index) {
 329   return _shared_protection_domains->obj_at(index);
 330 }
 331 
 332 oop SystemDictionaryShared::shared_jar_url(int index) {
 333   return _shared_jar_urls->obj_at(index);
 334 }
 335 
 336 oop SystemDictionaryShared::shared_jar_manifest(int index) {
 337   return _shared_jar_manifests->obj_at(index);
 338 }
 339 
 340 
 341 Handle SystemDictionaryShared::get_shared_jar_manifest(int shared_path_index, TRAPS) {
 342   Handle manifest ;
 343   if (shared_jar_manifest(shared_path_index) == NULL) {
 344     SharedClassPathEntry* ent = FileMapInfo::shared_path(shared_path_index);
 345     long size = ent->manifest_size();
 346     if (size <= 0) {
 347       return Handle();
 348     }
 349 
 350     // ByteArrayInputStream bais = new ByteArrayInputStream(buf);
 351     const char* src = ent->manifest();
 352     assert(src != NULL, "No Manifest data");
 353     typeArrayOop buf = oopFactory::new_byteArray(size, CHECK_NH);
 354     typeArrayHandle bufhandle(THREAD, buf);
 355     ArrayAccess<>::arraycopy_from_native(reinterpret_cast<const jbyte*>(src),
 356                                          buf, typeArrayOopDesc::element_offset<jbyte>(0), size);
 357 
 358     Handle bais = JavaCalls::construct_new_instance(SystemDictionary::ByteArrayInputStream_klass(),
 359                       vmSymbols::byte_array_void_signature(),
 360                       bufhandle, CHECK_NH);
 361 
 362     // manifest = new Manifest(bais)
 363     manifest = JavaCalls::construct_new_instance(SystemDictionary::Jar_Manifest_klass(),
 364                       vmSymbols::input_stream_void_signature(),
 365                       bais, CHECK_NH);
 366     atomic_set_shared_jar_manifest(shared_path_index, manifest());
 367   }
 368 
 369   manifest = Handle(THREAD, shared_jar_manifest(shared_path_index));
 370   assert(manifest.not_null(), "sanity");
 371   return manifest;
 372 }
 373 
 374 Handle SystemDictionaryShared::get_shared_jar_url(int shared_path_index, TRAPS) {
 375   Handle url_h;
 376   if (shared_jar_url(shared_path_index) == NULL) {
 377     JavaValue result(T_OBJECT);
 378     const char* path = FileMapInfo::shared_path_name(shared_path_index);
 379     Handle path_string = java_lang_String::create_from_str(path, CHECK_(url_h));
 380     Klass* classLoaders_klass =
 381         SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 382     JavaCalls::call_static(&result, classLoaders_klass,
 383                            vmSymbols::toFileURL_name(),
 384                            vmSymbols::toFileURL_signature(),
 385                            path_string, CHECK_(url_h));
 386 
 387     atomic_set_shared_jar_url(shared_path_index, (oop)result.get_jobject());
 388   }
 389 
 390   url_h = Handle(THREAD, shared_jar_url(shared_path_index));
 391   assert(url_h.not_null(), "sanity");
 392   return url_h;
 393 }
 394 
 395 Handle SystemDictionaryShared::get_package_name(Symbol* class_name, TRAPS) {
 396   ResourceMark rm(THREAD);
 397   Handle pkgname_string;
 398   char* pkgname = (char*) ClassLoader::package_from_name((const char*) class_name->as_C_string());
 399   if (pkgname != NULL) { // Package prefix found
 400     StringUtils::replace_no_expand(pkgname, "/", ".");
 401     pkgname_string = java_lang_String::create_from_str(pkgname,
 402                                                        CHECK_(pkgname_string));
 403   }
 404   return pkgname_string;
 405 }
 406 
 407 // Define Package for shared app classes from JAR file and also checks for
 408 // package sealing (all done in Java code)
 409 // See http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html
 410 void SystemDictionaryShared::define_shared_package(Symbol*  class_name,
 411                                                    Handle class_loader,
 412                                                    Handle manifest,
 413                                                    Handle url,
 414                                                    TRAPS) {
 415   assert(SystemDictionary::is_system_class_loader(class_loader()), "unexpected class loader");
 416   // get_package_name() returns a NULL handle if the class is in unnamed package
 417   Handle pkgname_string = get_package_name(class_name, CHECK);
 418   if (pkgname_string.not_null()) {
 419     Klass* app_classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
 420     JavaValue result(T_OBJECT);
 421     JavaCallArguments args(3);
 422     args.set_receiver(class_loader);
 423     args.push_oop(pkgname_string);
 424     args.push_oop(manifest);
 425     args.push_oop(url);
 426     JavaCalls::call_virtual(&result, app_classLoader_klass,
 427                             vmSymbols::defineOrCheckPackage_name(),
 428                             vmSymbols::defineOrCheckPackage_signature(),
 429                             &args,
 430                             CHECK);
 431   }
 432 }
 433 
 434 // Define Package for shared app/platform classes from named module
 435 void SystemDictionaryShared::define_shared_package(Symbol* class_name,
 436                                                    Handle class_loader,
 437                                                    ModuleEntry* mod_entry,
 438                                                    TRAPS) {
 439   assert(mod_entry != NULL, "module_entry should not be NULL");
 440   Handle module_handle(THREAD, mod_entry->module());
 441 
 442   Handle pkg_name = get_package_name(class_name, CHECK);
 443   assert(pkg_name.not_null(), "Package should not be null for class in named module");
 444 
 445   Klass* classLoader_klass;
 446   if (SystemDictionary::is_system_class_loader(class_loader())) {
 447     classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
 448   } else {
 449     assert(SystemDictionary::is_platform_class_loader(class_loader()), "unexpected classloader");
 450     classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass();
 451   }
 452 
 453   JavaValue result(T_OBJECT);
 454   JavaCallArguments args(2);
 455   args.set_receiver(class_loader);
 456   args.push_oop(pkg_name);
 457   args.push_oop(module_handle);
 458   JavaCalls::call_virtual(&result, classLoader_klass,
 459                           vmSymbols::definePackage_name(),
 460                           vmSymbols::definePackage_signature(),
 461                           &args,
 462                           CHECK);
 463 }
 464 
 465 // Get the ProtectionDomain associated with the CodeSource from the classloader.
 466 Handle SystemDictionaryShared::get_protection_domain_from_classloader(Handle class_loader,
 467                                                                       Handle url, TRAPS) {
 468   // CodeSource cs = new CodeSource(url, null);
 469   Handle cs = JavaCalls::construct_new_instance(SystemDictionary::CodeSource_klass(),
 470                   vmSymbols::url_code_signer_array_void_signature(),
 471                   url, Handle(), CHECK_NH);
 472 
 473   // protection_domain = SecureClassLoader.getProtectionDomain(cs);
 474   Klass* secureClassLoader_klass = SystemDictionary::SecureClassLoader_klass();
 475   JavaValue obj_result(T_OBJECT);
 476   JavaCalls::call_virtual(&obj_result, class_loader, secureClassLoader_klass,
 477                           vmSymbols::getProtectionDomain_name(),
 478                           vmSymbols::getProtectionDomain_signature(),
 479                           cs, CHECK_NH);
 480   return Handle(THREAD, (oop)obj_result.get_jobject());
 481 }
 482 
 483 // Returns the ProtectionDomain associated with the JAR file identified by the url.
 484 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 485                                                             int shared_path_index,
 486                                                             Handle url,
 487                                                             TRAPS) {
 488   Handle protection_domain;
 489   if (shared_protection_domain(shared_path_index) == NULL) {
 490     Handle pd = get_protection_domain_from_classloader(class_loader, url, THREAD);
 491     atomic_set_shared_protection_domain(shared_path_index, pd());
 492   }
 493 
 494   // Acquire from the cache because if another thread beats the current one to
 495   // set the shared protection_domain and the atomic_set fails, the current thread
 496   // needs to get the updated protection_domain from the cache.
 497   protection_domain = Handle(THREAD, shared_protection_domain(shared_path_index));
 498   assert(protection_domain.not_null(), "sanity");
 499   return protection_domain;
 500 }
 501 
 502 // Returns the ProtectionDomain associated with the moduleEntry.
 503 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 504                                                             ModuleEntry* mod, TRAPS) {
 505   ClassLoaderData *loader_data = mod->loader_data();
 506   if (mod->shared_protection_domain() == NULL) {
 507     Symbol* location = mod->location();
 508     if (location != NULL) {
 509       Handle location_string = java_lang_String::create_from_symbol(
 510                                      location, CHECK_NH);
 511       Handle url;
 512       JavaValue result(T_OBJECT);
 513       if (location->starts_with("jrt:/")) {
 514         url = JavaCalls::construct_new_instance(SystemDictionary::URL_klass(),
 515                                                 vmSymbols::string_void_signature(),
 516                                                 location_string, CHECK_NH);
 517       } else {
 518         Klass* classLoaders_klass =
 519           SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 520         JavaCalls::call_static(&result, classLoaders_klass, vmSymbols::toFileURL_name(),
 521                                vmSymbols::toFileURL_signature(),
 522                                location_string, CHECK_NH);
 523         url = Handle(THREAD, (oop)result.get_jobject());
 524       }
 525 
 526       Handle pd = get_protection_domain_from_classloader(class_loader, url,
 527                                                          CHECK_NH);
 528       mod->set_shared_protection_domain(loader_data, pd);
 529     }
 530   }
 531 
 532   Handle protection_domain(THREAD, mod->shared_protection_domain());
 533   assert(protection_domain.not_null(), "sanity");
 534   return protection_domain;
 535 }
 536 
 537 // Initializes the java.lang.Package and java.security.ProtectionDomain objects associated with
 538 // the given InstanceKlass.
 539 // Returns the ProtectionDomain for the InstanceKlass.
 540 Handle SystemDictionaryShared::init_security_info(Handle class_loader, InstanceKlass* ik, TRAPS) {
 541   Handle pd;
 542 
 543   if (ik != NULL) {
 544     int index = ik->shared_classpath_index();
 545     assert(index >= 0, "Sanity");
 546     SharedClassPathEntry* ent = FileMapInfo::shared_path(index);
 547     Symbol* class_name = ik->name();
 548 
 549     if (ent->is_modules_image()) {
 550       // For shared app/platform classes originated from the run-time image:
 551       //   The ProtectionDomains are cached in the corresponding ModuleEntries
 552       //   for fast access by the VM.
 553       ResourceMark rm;
 554       ClassLoaderData *loader_data =
 555                 ClassLoaderData::class_loader_data(class_loader());
 556       PackageEntryTable* pkgEntryTable = loader_data->packages();
 557       TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_(pd));
 558       if (pkg_name != NULL) {
 559         PackageEntry* pkg_entry = pkgEntryTable->lookup_only(pkg_name);
 560         if (pkg_entry != NULL) {
 561           ModuleEntry* mod_entry = pkg_entry->module();
 562           pd = get_shared_protection_domain(class_loader, mod_entry, THREAD);
 563           define_shared_package(class_name, class_loader, mod_entry, CHECK_(pd));
 564         }
 565       }
 566     } else {
 567       // For shared app/platform classes originated from JAR files on the class path:
 568       //   Each of the 3 SystemDictionaryShared::_shared_xxx arrays has the same length
 569       //   as the shared classpath table in the shared archive (see
 570       //   FileMap::_shared_path_table in filemap.hpp for details).
 571       //
 572       //   If a shared InstanceKlass k is loaded from the class path, let
 573       //
 574       //     index = k->shared_classpath_index():
 575       //
 576       //   FileMap::_shared_path_table[index] identifies the JAR file that contains k.
 577       //
 578       //   k's protection domain is:
 579       //
 580       //     ProtectionDomain pd = _shared_protection_domains[index];
 581       //
 582       //   and k's Package is initialized using
 583       //
 584       //     manifest = _shared_jar_manifests[index];
 585       //     url = _shared_jar_urls[index];
 586       //     define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 587       //
 588       //   Note that if an element of these 3 _shared_xxx arrays is NULL, it will be initialized by
 589       //   the corresponding SystemDictionaryShared::get_shared_xxx() function.
 590       Handle manifest = get_shared_jar_manifest(index, CHECK_(pd));
 591       Handle url = get_shared_jar_url(index, CHECK_(pd));
 592       define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 593       pd = get_shared_protection_domain(class_loader, index, url, CHECK_(pd));
 594     }
 595   }
 596   return pd;
 597 }
 598 
 599 bool SystemDictionaryShared::is_sharing_possible(ClassLoaderData* loader_data) {
 600   oop class_loader = loader_data->class_loader();
 601   return (class_loader == NULL ||
 602           SystemDictionary::is_system_class_loader(class_loader) ||
 603           SystemDictionary::is_platform_class_loader(class_loader));
 604 }
 605 
 606 // Currently AppCDS only archives classes from the run-time image, the
 607 // -Xbootclasspath/a path, the class path, and the module path.
 608 //
 609 // Check if a shared class can be loaded by the specific classloader. Following
 610 // are the "visible" archived classes for different classloaders.
 611 //
 612 // NULL classloader:
 613 //   - see SystemDictionary::is_shared_class_visible()
 614 // Platform classloader:
 615 //   - Module class from runtime image. ModuleEntry must be defined in the
 616 //     classloader.
 617 // App classloader:
 618 //   - Module Class from runtime image and module path. ModuleEntry must be defined in the
 619 //     classloader.
 620 //   - Class from -cp. The class must have no PackageEntry defined in any of the
 621 //     boot/platform/app classloader, or must be in the unnamed module defined in the
 622 //     AppClassLoader.
 623 bool SystemDictionaryShared::is_shared_class_visible_for_classloader(
 624                                                      InstanceKlass* ik,
 625                                                      Handle class_loader,
 626                                                      const char* pkg_string,
 627                                                      Symbol* pkg_name,
 628                                                      PackageEntry* pkg_entry,
 629                                                      ModuleEntry* mod_entry,
 630                                                      TRAPS) {
 631   assert(class_loader.not_null(), "Class loader should not be NULL");
 632   assert(Universe::is_module_initialized(), "Module system is not initialized");
 633   ResourceMark rm(THREAD);
 634 
 635   int path_index = ik->shared_classpath_index();
 636   SharedClassPathEntry* ent =
 637             (SharedClassPathEntry*)FileMapInfo::shared_path(path_index);
 638 
 639   if (SystemDictionary::is_platform_class_loader(class_loader())) {
 640     assert(ent != NULL, "shared class for PlatformClassLoader should have valid SharedClassPathEntry");
 641     // The PlatformClassLoader can only load archived class originated from the
 642     // run-time image. The class' PackageEntry/ModuleEntry must be
 643     // defined by the PlatformClassLoader.
 644     if (mod_entry != NULL) {
 645       // PackageEntry/ModuleEntry is found in the classloader. Check if the
 646       // ModuleEntry's location agrees with the archived class' origination.
 647       if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 648         return true; // Module class from the runtime image
 649       }
 650     }
 651   } else if (SystemDictionary::is_system_class_loader(class_loader())) {
 652     assert(ent != NULL, "shared class for system loader should have valid SharedClassPathEntry");
 653     if (pkg_string == NULL) {
 654       // The archived class is in the unnamed package. Currently, the boot image
 655       // does not contain any class in the unnamed package.
 656       assert(!ent->is_modules_image(), "Class in the unnamed package must be from the classpath");
 657       if (path_index >= ClassLoaderExt::app_class_paths_start_index()) {
 658         assert(path_index < ClassLoaderExt::app_module_paths_start_index(), "invalid path_index");
 659         return true;
 660       }
 661     } else {
 662       // Check if this is from a PackageEntry/ModuleEntry defined in the AppClassloader.
 663       if (pkg_entry == NULL) {
 664         // It's not guaranteed that the class is from the classpath if the
 665         // PackageEntry cannot be found from the AppClassloader. Need to check
 666         // the boot and platform classloader as well.
 667         if (get_package_entry(pkg_name, ClassLoaderData::class_loader_data_or_null(SystemDictionary::java_platform_loader())) == NULL &&
 668             get_package_entry(pkg_name, ClassLoaderData::the_null_class_loader_data()) == NULL) {
 669           // The PackageEntry is not defined in any of the boot/platform/app classloaders.
 670           // The archived class must from -cp path and not from the runtime image.
 671           if (!ent->is_modules_image() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 672                                           path_index < ClassLoaderExt::app_module_paths_start_index()) {
 673             return true;
 674           }
 675         }
 676       } else if (mod_entry != NULL) {
 677         // The package/module is defined in the AppClassLoader. We support
 678         // archiving application module class from the runtime image or from
 679         // a named module from a module path.
 680         // Packages from the -cp path are in the unnamed_module.
 681         if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 682           // shared module class from runtime image
 683           return true;
 684         } else if (pkg_entry->in_unnamed_module() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 685             path_index < ClassLoaderExt::app_module_paths_start_index()) {
 686           // shared class from -cp
 687           DEBUG_ONLY( \
 688             ClassLoaderData* loader_data = class_loader_data(class_loader); \
 689             assert(mod_entry == loader_data->unnamed_module(), "the unnamed module is not defined in the classloader");)
 690           return true;
 691         } else {
 692           if(!pkg_entry->in_unnamed_module() &&
 693               (path_index >= ClassLoaderExt::app_module_paths_start_index())&&
 694               (path_index < FileMapInfo::get_number_of_shared_paths()) &&
 695               (strcmp(ent->name(), ClassLoader::skip_uri_protocol(mod_entry->location()->as_C_string())) == 0)) {
 696             // shared module class from module path
 697             return true;
 698           } else {
 699             assert(path_index < FileMapInfo::get_number_of_shared_paths(), "invalid path_index");
 700           }
 701         }
 702       }
 703     }
 704   } else {
 705     // TEMP: if a shared class can be found by a custom loader, consider it visible now.
 706     // FIXME: is this actually correct?
 707     return true;
 708   }
 709   return false;
 710 }
 711 
 712 // The following stack shows how this code is reached:
 713 //
 714 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 715 //   [1] JVM_FindLoadedClass
 716 //   [2] java.lang.ClassLoader.findLoadedClass0()
 717 //   [3] java.lang.ClassLoader.findLoadedClass()
 718 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 719 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 720 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 721 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 722 //
 723 // AppCDS supports fast class loading for these 2 built-in class loaders:
 724 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 725 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 726 // with the following assumptions (based on the JDK core library source code):
 727 //
 728 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 729 //     load the named class.
 730 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 731 // [c] At this point, if we can find the named class inside the
 732 //     shared_dictionary, we can perform further checks (see
 733 //     is_shared_class_visible_for_classloader() to ensure that this class
 734 //     was loaded by the same class loader during dump time.
 735 //
 736 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 737 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 738 // the archive for the 2 built-in class loaders. This way,
 739 // we can improve start-up because we avoid decoding the classfile,
 740 // and avoid delegating to the parent loader.
 741 //
 742 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 743 // needs to be redesigned.
 744 
 745 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 746                  Symbol* name, Handle class_loader, TRAPS) {
 747   InstanceKlass* k = NULL;
 748   if (UseSharedSpaces) {
 749     if (!FileMapInfo::current_info()->header()->has_platform_or_app_classes()) {
 750       return NULL;
 751     }
 752 
 753     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 754         SystemDictionary::is_platform_class_loader(class_loader())) {
 755       // Fix for 4474172; see evaluation for more details
 756       class_loader = Handle(
 757         THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 758       ClassLoaderData *loader_data = register_loader(class_loader);
 759       Dictionary* dictionary = loader_data->dictionary();
 760 
 761       unsigned int d_hash = dictionary->compute_hash(name);
 762 
 763       bool DoObjectLock = true;
 764       if (is_parallelCapable(class_loader)) {
 765         DoObjectLock = false;
 766       }
 767 
 768       // Make sure we are synchronized on the class loader before we proceed
 769       //
 770       // Note: currently, find_or_load_shared_class is called only from
 771       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 772       // which are parallel-capable loaders, so this lock is NOT taken.
 773       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 774       check_loader_lock_contention(lockObject, THREAD);
 775       ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 776 
 777       {
 778         MutexLocker mu(SystemDictionary_lock, THREAD);
 779         InstanceKlass* check = find_class(d_hash, name, dictionary);
 780         if (check != NULL) {
 781           return check;
 782         }
 783       }
 784 
 785       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 786       if (k != NULL) {
 787         define_instance_class(k, CHECK_NULL);
 788       }
 789     }
 790   }
 791   return k;
 792 }
 793 
 794 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 795                  Symbol* class_name, Handle class_loader, TRAPS) {
 796   assert(UseSharedSpaces, "must be");
 797   InstanceKlass* ik = find_builtin_class(class_name);
 798 
 799   if (ik != NULL) {
 800     if ((ik->is_shared_app_class() &&
 801          SystemDictionary::is_system_class_loader(class_loader()))  ||
 802         (ik->is_shared_platform_class() &&
 803          SystemDictionary::is_platform_class_loader(class_loader()))) {
 804       Handle protection_domain =
 805         SystemDictionaryShared::init_security_info(class_loader, ik, CHECK_NULL);
 806       return load_shared_class(ik, class_loader, protection_domain, NULL, THREAD);
 807     }
 808   }
 809   return NULL;
 810 }
 811 
 812 void SystemDictionaryShared::oops_do(OopClosure* f) {
 813   f->do_oop((oop*)&_shared_protection_domains);
 814   f->do_oop((oop*)&_shared_jar_urls);
 815   f->do_oop((oop*)&_shared_jar_manifests);
 816 }
 817 
 818 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) {
 819   if (_shared_protection_domains == NULL) {
 820     _shared_protection_domains = oopFactory::new_objArray(
 821         SystemDictionary::ProtectionDomain_klass(), size, CHECK);
 822   }
 823 }
 824 
 825 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) {
 826   if (_shared_jar_urls == NULL) {
 827     _shared_jar_urls = oopFactory::new_objArray(
 828         SystemDictionary::URL_klass(), size, CHECK);
 829   }
 830 }
 831 
 832 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) {
 833   if (_shared_jar_manifests == NULL) {
 834     _shared_jar_manifests = oopFactory::new_objArray(
 835         SystemDictionary::Jar_Manifest_klass(), size, CHECK);
 836   }
 837 }
 838 
 839 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) {
 840   allocate_shared_protection_domain_array(size, CHECK);
 841   allocate_shared_jar_url_array(size, CHECK);
 842   allocate_shared_jar_manifest_array(size, CHECK);
 843 }
 844 
 845 // This function is called for loading only UNREGISTERED classes
 846 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 847                                                           Handle class_loader,
 848                                                           Handle protection_domain,
 849                                                           const ClassFileStream* cfs,
 850                                                           TRAPS) {
 851   if (!UseSharedSpaces) {
 852     return NULL;
 853   }
 854   if (class_name == NULL) {  // don't do this for anonymous classes
 855     return NULL;
 856   }
 857   if (class_loader.is_null() ||
 858       SystemDictionary::is_system_class_loader(class_loader()) ||
 859       SystemDictionary::is_platform_class_loader(class_loader())) {
 860     // Do nothing for the BUILTIN loaders.
 861     return NULL;
 862   }
 863 
 864   const RunTimeSharedClassInfo* record = find_record(&_unregistered_dictionary, class_name);
 865   if (record == NULL) {
 866     return NULL;
 867   }
 868 
 869   int clsfile_size  = cfs->length();
 870   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 871   if (!record->matches(clsfile_size, clsfile_crc32)) {
 872     return NULL;
 873   }
 874 
 875   return acquire_class_for_current_thread(record->_klass, class_loader,
 876                                           protection_domain, cfs,
 877                                           THREAD);
 878 }
 879 
 880 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 881                    InstanceKlass *ik,
 882                    Handle class_loader,
 883                    Handle protection_domain,
 884                    const ClassFileStream *cfs,
 885                    TRAPS) {
 886   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 887 
 888   {
 889     MutexLocker mu(SharedDictionary_lock, THREAD);
 890     if (ik->class_loader_data() != NULL) {
 891       //    ik is already loaded (by this loader or by a different loader)
 892       // or ik is being loaded by a different thread (by this loader or by a different loader)
 893       return NULL;
 894     }
 895 
 896     // No other thread has acquired this yet, so give it to *this thread*
 897     ik->set_class_loader_data(loader_data);
 898   }
 899 
 900   // No longer holding SharedDictionary_lock
 901   // No need to lock, as <ik> can be held only by a single thread.
 902   loader_data->add_class(ik);
 903 
 904   // Load and check super/interfaces, restore unsharable info
 905   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
 906                                                   cfs, THREAD);
 907   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
 908     // TODO: clean up <ik> so it can be used again
 909     return NULL;
 910   }
 911 
 912   return shared_klass;
 913 }
 914 
 915 static ResourceHashtable<
 916   Symbol*, bool,
 917   primitive_hash<Symbol*>,
 918   primitive_equals<Symbol*>,
 919   6661,                             // prime number
 920   ResourceObj::C_HEAP> _loaded_unregistered_classes;
 921 
 922 bool SystemDictionaryShared::add_unregistered_class(InstanceKlass* k, TRAPS) {
 923   assert(DumpSharedSpaces, "only when dumping");
 924 
 925   Symbol* name = k->name();
 926   if (_loaded_unregistered_classes.get(name) != NULL) {
 927     // We don't allow duplicated unregistered classes of the same name.
 928     return false;
 929   } else {
 930     bool isnew = _loaded_unregistered_classes.put(name, true);
 931     assert(isnew, "sanity");
 932     MutexLocker mu_r(Compile_lock, THREAD); // add_to_hierarchy asserts this.
 933     SystemDictionary::add_to_hierarchy(k, CHECK_0);
 934     return true;
 935   }
 936 }
 937 
 938 // This function is called to resolve the super/interfaces of shared classes for
 939 // non-built-in loaders. E.g., ChildClass in the below example
 940 // where "super:" (and optionally "interface:") have been specified.
 941 //
 942 // java/lang/Object id: 0
 943 // Interface   id: 2 super: 0 source: cust.jar
 944 // ChildClass  id: 4 super: 0 interfaces: 2 source: cust.jar
 945 InstanceKlass* SystemDictionaryShared::dump_time_resolve_super_or_fail(
 946     Symbol* child_name, Symbol* class_name, Handle class_loader,
 947     Handle protection_domain, bool is_superclass, TRAPS) {
 948 
 949   assert(DumpSharedSpaces, "only when dumping");
 950 
 951   ClassListParser* parser = ClassListParser::instance();
 952   if (parser == NULL) {
 953     // We're still loading the well-known classes, before the ClassListParser is created.
 954     return NULL;
 955   }
 956   if (child_name->equals(parser->current_class_name())) {
 957     // When this function is called, all the numbered super and interface types
 958     // must have already been loaded. Hence this function is never recursively called.
 959     if (is_superclass) {
 960       return parser->lookup_super_for_current_class(class_name);
 961     } else {
 962       return parser->lookup_interface_for_current_class(class_name);
 963     }
 964   } else {
 965     // The VM is not trying to resolve a super type of parser->current_class_name().
 966     // Instead, it's resolving an error class (because parser->current_class_name() has
 967     // failed parsing or verification). Don't do anything here.
 968     return NULL;
 969   }
 970 }
 971 
 972 DumpTimeSharedClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) {
 973   if (_dumptime_table == NULL) {
 974     _dumptime_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeSharedClassTable();
 975   }
 976   return _dumptime_table->find_or_allocate_info_for(k);
 977 }
 978 
 979 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
 980   assert(DumpSharedSpaces, "only when dumping");
 981   assert(!is_builtin(k), "must be unregistered class");
 982   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
 983   info->_clsfile_size  = cfs->length();
 984   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 985 }
 986 
 987 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
 988   (void)find_or_allocate_info_for(k);
 989 }
 990 
 991 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
 992   _dumptime_table->remove(k);
 993 }
 994 
 995 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
 996   while (k) {
 997     if (k->name()->equals("jdk/internal/event/Event")) {
 998       return true;
 999     }
1000     k = k->java_super();
1001   }
1002   return false;
1003 }
1004 
1005 void SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
1006   ResourceMark rm;
1007   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
1008 }
1009 
1010 bool SystemDictionaryShared::should_be_excluded(InstanceKlass* k) {
1011   if (k->class_loader_data()->is_unsafe_anonymous()) {
1012     return true; // unsafe anonymous classes are not archived, skip
1013   }
1014   if (k->is_in_error_state()) {
1015     return true;
1016   }
1017   if (k->shared_classpath_index() < 0 && is_builtin(k)) {
1018     // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
1019     // agent during dump time).
1020     warn_excluded(k, "Unsupported location");
1021     return true;
1022   }
1023   if (k->signers() != NULL) {
1024     // We cannot include signed classes in the archive because the certificates
1025     // used during dump time may be different than those used during
1026     // runtime (due to expiration, etc).
1027     warn_excluded(k, "Signed JAR");
1028     return true;
1029   }
1030   if (is_jfr_event_class(k)) {
1031     // We cannot include JFR event classes because they need runtime-specific
1032     // instrumentation in order to work with -XX:FlightRecorderOptions=retransform=false.
1033     // There are only a small number of these classes, so it's not worthwhile to
1034     // support them and make CDS more complicated.
1035     warn_excluded(k, "JFR event class");
1036     return true;
1037   }
1038   return false;
1039 }
1040 
1041 // k is a class before relocating by ArchiveCompactor
1042 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
1043   ResourceMark rm;
1044   const char* name = k->name()->as_C_string();
1045   DumpTimeSharedClassInfo* info = _dumptime_table->get(k);
1046   guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name);
1047   guarantee(!info->_excluded, "Should not attempt to archive excluded class %s", name);
1048   if (is_builtin(k)) {
1049     guarantee(k->loader_type() != 0,
1050               "Class loader type must be set for BUILTIN class %s", name);
1051   } else {
1052     guarantee(k->loader_type() == 0,
1053               "Class loader type must not be set for UNREGISTERED class %s", name);
1054   }
1055 }
1056 
1057 class ExcludeDumpTimeSharedClasses : StackObj {
1058 public:
1059   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1060     if (SystemDictionaryShared::should_be_excluded(k)) {
1061       info._excluded = true;
1062     }
1063     return true; // keep on iterating
1064   }
1065 };
1066 
1067 void SystemDictionaryShared::check_excluded_classes() {
1068   ExcludeDumpTimeSharedClasses excl;
1069   _dumptime_table->iterate(&excl);
1070   DEBUG_ONLY(_checked_excluded_classes = true;)
1071 }
1072 
1073 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
1074   assert(_checked_excluded_classes, "sanity");
1075   assert(DumpSharedSpaces, "only when dumping");
1076   return find_or_allocate_info_for(k)->_excluded;
1077 }
1078 
1079 class IterateDumpTimeSharedClassTable : StackObj {
1080   MetaspaceClosure *_it;
1081 public:
1082   IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {}
1083 
1084   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1085     if (!info._excluded) {
1086       info.metaspace_pointers_do(_it);
1087     }
1088     return true; // keep on iterating
1089   }
1090 };
1091 
1092 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
1093   IterateDumpTimeSharedClassTable iter(it);
1094   _dumptime_table->iterate(&iter);
1095 }
1096 
1097 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1098          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1099   assert(DumpSharedSpaces, "called at dump time only");
1100   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1101   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
1102                                     from_is_array, from_is_object);
1103   if (is_builtin(k)) {
1104     // For builtin class loaders, we can try to complete the verification check at dump time,
1105     // because we can resolve all the constraint classes.
1106     return false;
1107   } else {
1108     // For non-builtin class loaders, we cannot complete the verification check at dump time,
1109     // because at dump time we don't know how to resolve classes for such loaders.
1110     return true;
1111   }
1112 }
1113 
1114 void DumpTimeSharedClassInfo::add_verification_constraint(InstanceKlass* k, Symbol* name,
1115          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1116   if (_verifier_constraints == NULL) {
1117     _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<DTConstraint>(4, true, mtClass);
1118   }
1119   if (_verifier_constraint_flags == NULL) {
1120     _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, true, mtClass);
1121   }
1122   GrowableArray<DTConstraint>* vc_array = _verifier_constraints;
1123   for (int i = 0; i < vc_array->length(); i++) {
1124     DTConstraint* p = vc_array->adr_at(i);
1125     if (name == p->_name && from_name == p->_from_name) {
1126       return;
1127     }
1128   }
1129   DTConstraint cons(name, from_name);
1130   vc_array->append(cons);
1131 
1132   GrowableArray<char>* vcflags_array = _verifier_constraint_flags;
1133   char c = 0;
1134   c |= from_field_is_protected ? SystemDictionaryShared::FROM_FIELD_IS_PROTECTED : 0;
1135   c |= from_is_array           ? SystemDictionaryShared::FROM_IS_ARRAY           : 0;
1136   c |= from_is_object          ? SystemDictionaryShared::FROM_IS_OBJECT          : 0;
1137   vcflags_array->append(c);
1138 
1139   if (log_is_enabled(Trace, cds, verification)) {
1140     ResourceMark rm;
1141     log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s",
1142                                  k->external_name(), from_name->as_klass_external_name(),
1143                                  name->as_klass_external_name());
1144   }
1145 }
1146 
1147 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1148                                                             TRAPS) {
1149   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1150   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(klass);
1151 
1152   int length = record->_num_constraints;
1153   if (length > 0) {
1154     for (int i = 0; i < length; i++) {
1155       Symbol* name      = record->get_constraint_name(i);
1156       Symbol* from_name = record->get_constraint_from_name(i);
1157       char c            = record->get_constraint_flag(i);
1158 
1159       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
1160       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
1161       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
1162 
1163       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
1164          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
1165       if (!ok) {
1166         ResourceMark rm(THREAD);
1167         stringStream ss;
1168 
1169         ss.print_cr("Bad type on operand stack");
1170         ss.print_cr("Exception Details:");
1171         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1172         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1173                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1174         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1175       }
1176     }
1177   }
1178 }
1179 
1180 class CopySharedClassInfoToArchive : StackObj {
1181   CompactHashtableWriter* _writer;
1182   bool _is_builtin;
1183 public:
1184   CopySharedClassInfoToArchive(CompactHashtableWriter* writer, bool is_builtin)
1185     : _writer(writer), _is_builtin(is_builtin) {}
1186 
1187   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1188     if (!info._excluded && info.is_builtin() == _is_builtin) {
1189       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_constraints());
1190       RunTimeSharedClassInfo* record =
1191         (RunTimeSharedClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
1192       record->init(info);
1193 
1194       unsigned int hash = primitive_hash<Symbol*>(info._klass->name());
1195       _writer->add(hash, MetaspaceShared::object_delta_u4(record));
1196 
1197       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeSharedClassInfo*
1198       RunTimeSharedClassInfo::set_for(info._klass, record);
1199     }
1200     return true; // keep on iterating
1201   }
1202 };
1203 
1204 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary, bool is_builtin) {
1205   CompactHashtableStats stats;
1206   dictionary->reset();
1207   int num_buckets = CompactHashtableWriter::default_num_buckets(_dumptime_table->count_of(is_builtin));
1208   CompactHashtableWriter writer(num_buckets, &stats);
1209   CopySharedClassInfoToArchive copy(&writer, is_builtin);
1210   _dumptime_table->iterate(&copy);
1211   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1212 }
1213 
1214 void SystemDictionaryShared::write_to_archive() {
1215   _dumptime_table->update_counts();
1216   write_dictionary(&_builtin_dictionary, true);
1217   write_dictionary(&_unregistered_dictionary, false);
1218 }
1219 
1220 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc) {
1221   _builtin_dictionary.serialize_header(soc);
1222   _unregistered_dictionary.serialize_header(soc);
1223 }
1224 
1225 const RunTimeSharedClassInfo*
1226 SystemDictionaryShared::find_record(RunTimeSharedDictionary* dict, Symbol* name) {
1227   if (UseSharedSpaces) {
1228     unsigned int hash = primitive_hash<Symbol*>(name);
1229     return dict->lookup(name, hash, 0);
1230   } else {
1231     return NULL;
1232   }
1233 }
1234 
1235 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1236   const RunTimeSharedClassInfo* record = find_record(&_builtin_dictionary, name);
1237   if (record) {
1238     return record->_klass;
1239   } else {
1240     return NULL;
1241   }
1242 }
1243 
1244 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1245   assert(DumpSharedSpaces, "supported only when dumping");
1246   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1247   info->_id = id;
1248 }
1249 
1250 class SharedDictionaryPrinter : StackObj {
1251   outputStream* _st;
1252   int _index;
1253 public:
1254   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1255 
1256   void do_value(const RunTimeSharedClassInfo* record) {
1257     ResourceMark rm;
1258     _st->print_cr("%4d:  %s", (_index++), record->_klass->external_name());
1259   }
1260 };
1261 
1262 void SystemDictionaryShared::print_on(outputStream* st) {
1263   if (UseSharedSpaces) {
1264     st->print_cr("Shared Dictionary");
1265     SharedDictionaryPrinter p(st);
1266     _builtin_dictionary.iterate(&p);
1267     _unregistered_dictionary.iterate(&p);
1268   }
1269 }
1270 
1271 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1272   if (UseSharedSpaces) {
1273     _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1274     _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1275   }
1276 }