1 /*
   2  * Copyright (c) 2014, 2020, 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/archiveUtils.hpp"
  42 #include "memory/filemap.hpp"
  43 #include "memory/heapShared.hpp"
  44 #include "memory/metadataFactory.hpp"
  45 #include "memory/metaspaceClosure.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"
  49 #include "memory/dynamicArchive.hpp"
  50 #include "oops/instanceKlass.hpp"
  51 #include "oops/klass.inline.hpp"
  52 #include "oops/objArrayOop.inline.hpp"
  53 #include "oops/oop.inline.hpp"
  54 #include "oops/typeArrayOop.inline.hpp"
  55 #include "runtime/handles.inline.hpp"
  56 #include "runtime/java.hpp"
  57 #include "runtime/javaCalls.hpp"
  58 #include "runtime/mutexLocker.hpp"
  59 #include "utilities/hashtable.inline.hpp"
  60 #include "utilities/resourceHash.hpp"
  61 #include "utilities/stringUtils.hpp"
  62 
  63 
  64 OopHandle SystemDictionaryShared::_shared_protection_domains  =  NULL;
  65 OopHandle SystemDictionaryShared::_shared_jar_urls            =  NULL;
  66 OopHandle SystemDictionaryShared::_shared_jar_manifests       =  NULL;
  67 DEBUG_ONLY(bool SystemDictionaryShared::_no_class_loading_should_happen = false;)
  68 
  69 class DumpTimeSharedClassInfo: public CHeapObj<mtClass> {
  70   bool                         _excluded;
  71 public:
  72   struct DTLoaderConstraint {
  73     Symbol* _name;
  74     char _loader_type1;
  75     char _loader_type2;
  76     DTLoaderConstraint(Symbol* name, char l1, char l2) : _name(name), _loader_type1(l1), _loader_type2(l2) {
  77       _name->increment_refcount();
  78     }
  79     DTLoaderConstraint() : _name(NULL), _loader_type1('0'), _loader_type2('0') {}
  80     bool equals(const DTLoaderConstraint& t) {
  81       return t._name == _name &&
  82              ((t._loader_type1 == _loader_type1 && t._loader_type2 == _loader_type2) ||
  83               (t._loader_type2 == _loader_type1 && t._loader_type1 == _loader_type2));
  84     }
  85   };
  86 
  87   struct DTVerifierConstraint {
  88     Symbol* _name;
  89     Symbol* _from_name;
  90     DTVerifierConstraint() : _name(NULL), _from_name(NULL) {}
  91     DTVerifierConstraint(Symbol* n, Symbol* fn) : _name(n), _from_name(fn) {
  92       _name->increment_refcount();
  93       _from_name->increment_refcount();
  94     }
  95   };
  96 
  97   InstanceKlass*               _klass;
  98   bool                         _failed_verification;
  99   int                          _id;
 100   int                          _clsfile_size;
 101   int                          _clsfile_crc32;
 102   GrowableArray<DTVerifierConstraint>* _verifier_constraints;
 103   GrowableArray<char>*                 _verifier_constraint_flags;
 104   GrowableArray<DTLoaderConstraint>* _loader_constraints;
 105 
 106   DumpTimeSharedClassInfo() {
 107     _klass = NULL;
 108     _failed_verification = false;
 109     _id = -1;
 110     _clsfile_size = -1;
 111     _clsfile_crc32 = -1;
 112     _excluded = false;
 113     _verifier_constraints = NULL;
 114     _verifier_constraint_flags = NULL;
 115     _loader_constraints = NULL;
 116   }
 117 
 118   void add_verification_constraint(InstanceKlass* k, Symbol* name,
 119          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object);
 120   void record_linking_constraint(Symbol* name, Handle loader1, Handle loader2);
 121 
 122   bool is_builtin() {
 123     return SystemDictionaryShared::is_builtin(_klass);
 124   }
 125 
 126   int num_verifier_constraints() {
 127     if (_verifier_constraint_flags != NULL) {
 128       return _verifier_constraint_flags->length();
 129     } else {
 130       return 0;
 131     }
 132   }
 133 
 134   int num_loader_constraints() {
 135     if (_loader_constraints != NULL) {
 136       return _loader_constraints->length();
 137     } else {
 138       return 0;
 139     }
 140   }
 141 
 142   void metaspace_pointers_do(MetaspaceClosure* it) {
 143     it->push(&_klass);
 144     if (_verifier_constraints != NULL) {
 145       for (int i = 0; i < _verifier_constraints->length(); i++) {
 146         DTVerifierConstraint* cons = _verifier_constraints->adr_at(i);
 147         it->push(&cons->_name);
 148         it->push(&cons->_from_name);
 149       }
 150     }
 151     if (_loader_constraints != NULL) {
 152       for (int i = 0; i < _loader_constraints->length(); i++) {
 153         DTLoaderConstraint* lc = _loader_constraints->adr_at(i);
 154         it->push(&lc->_name);
 155       }
 156     }
 157   }
 158 
 159   void set_excluded() {
 160     _excluded = true;
 161   }
 162 
 163   bool is_excluded() {
 164     // _klass may become NULL due to DynamicArchiveBuilder::set_to_null
 165     return _excluded || _failed_verification || _klass == NULL;
 166   }
 167 
 168   void set_failed_verification() {
 169     _failed_verification = true;
 170   }
 171 
 172   bool failed_verification() {
 173     return _failed_verification;
 174   }
 175 };
 176 
 177 inline unsigned DumpTimeSharedClassTable_hash(InstanceKlass* const& k) {
 178   if (DumpSharedSpaces) {
 179     // Deterministic archive contents
 180     uintx delta = k->name() - MetaspaceShared::symbol_rs_base();
 181     return primitive_hash<uintx>(delta);
 182   } else {
 183     // Deterministic archive is not possible because classes can be loaded
 184     // in multiple threads.
 185     return primitive_hash<InstanceKlass*>(k);
 186   }
 187 }
 188 
 189 class DumpTimeSharedClassTable: public ResourceHashtable<
 190   InstanceKlass*,
 191   DumpTimeSharedClassInfo,
 192   &DumpTimeSharedClassTable_hash,
 193   primitive_equals<InstanceKlass*>,
 194   15889, // prime number
 195   ResourceObj::C_HEAP>
 196 {
 197   int _builtin_count;
 198   int _unregistered_count;
 199 public:
 200   DumpTimeSharedClassInfo* find_or_allocate_info_for(InstanceKlass* k) {
 201     bool created = false;
 202     DumpTimeSharedClassInfo* p = put_if_absent(k, &created);
 203     if (created) {
 204       assert(!SystemDictionaryShared::no_class_loading_should_happen(),
 205              "no new classes can be loaded while dumping archive");
 206       p->_klass = k;
 207     } else {
 208       assert(p->_klass == k, "Sanity");
 209     }
 210     return p;
 211   }
 212 
 213   class CountClassByCategory : StackObj {
 214     DumpTimeSharedClassTable* _table;
 215   public:
 216     CountClassByCategory(DumpTimeSharedClassTable* table) : _table(table) {}
 217     bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
 218       if (!info.is_excluded()) {
 219         if (info.is_builtin()) {
 220           ++ _table->_builtin_count;
 221         } else {
 222           ++ _table->_unregistered_count;
 223         }
 224       }
 225       return true; // keep on iterating
 226     }
 227   };
 228 
 229   void update_counts() {
 230     _builtin_count = 0;
 231     _unregistered_count = 0;
 232     CountClassByCategory counter(this);
 233     iterate(&counter);
 234   }
 235 
 236   int count_of(bool is_builtin) const {
 237     if (is_builtin) {
 238       return _builtin_count;
 239     } else {
 240       return _unregistered_count;
 241     }
 242   }
 243 };
 244 
 245 class RunTimeSharedClassInfo {
 246 public:
 247   struct CrcInfo {
 248     int _clsfile_size;
 249     int _clsfile_crc32;
 250   };
 251 
 252   // This is different than  DumpTimeSharedClassInfo::DTVerifierConstraint. We use
 253   // u4 instead of Symbol* to save space on 64-bit CPU.
 254   struct RTVerifierConstraint {
 255     u4 _name;
 256     u4 _from_name;
 257     Symbol* name() { return (Symbol*)(SharedBaseAddress + _name);}
 258     Symbol* from_name() { return (Symbol*)(SharedBaseAddress + _from_name); }
 259   };
 260 
 261   struct RTLoaderConstraint {
 262     u4   _name;
 263     char _loader_type1;
 264     char _loader_type2;
 265     Symbol* constraint_name() {
 266       return (Symbol*)(SharedBaseAddress + _name);
 267     }
 268   };
 269 
 270   InstanceKlass* _klass;
 271   int _num_verifier_constraints;
 272   int _num_loader_constraints;
 273 
 274   // optional CrcInfo              _crc;  (only for UNREGISTERED classes)
 275   // optional RTLoaderConstraint   _loader_constraint_types[_num_loader_constraints]
 276   // optional RTVerifierConstraint _verifier_constraints[_num_verifier_constraints]
 277   // optional char                 _verifier_constraint_flags[_num_verifier_constraints]
 278 
 279 private:
 280   static size_t header_size_size() {
 281     return sizeof(RunTimeSharedClassInfo);
 282   }
 283   static size_t crc_size(InstanceKlass* klass) {
 284     if (!SystemDictionaryShared::is_builtin(klass)) {
 285       return sizeof(CrcInfo);
 286     } else {
 287       return 0;
 288     }
 289   }
 290   static size_t verifier_constraints_size(int num_verifier_constraints) {
 291     return sizeof(RTVerifierConstraint) * num_verifier_constraints;
 292   }
 293   static size_t verifier_constraint_flags_size(int num_verifier_constraints) {
 294     return sizeof(char) * num_verifier_constraints;
 295   }
 296   static size_t loader_constraints_size(int num_loader_constraints) {
 297     return sizeof(RTLoaderConstraint) * num_loader_constraints;
 298   }
 299 
 300 public:
 301   static size_t byte_size(InstanceKlass* klass, int num_verifier_constraints, int num_loader_constraints) {
 302     return header_size_size() +
 303            crc_size(klass) +
 304            loader_constraints_size(num_loader_constraints) +
 305            verifier_constraints_size(num_verifier_constraints) +
 306            verifier_constraint_flags_size(num_verifier_constraints);
 307   }
 308 
 309 private:
 310   size_t crc_offset() const {
 311     return header_size_size();
 312   }
 313 
 314   size_t loader_constraints_offset() const  {
 315     return crc_offset() + crc_size(_klass);
 316   }
 317   size_t verifier_constraints_offset() const {
 318     return loader_constraints_offset() + loader_constraints_size(_num_loader_constraints);
 319   }
 320   size_t verifier_constraint_flags_offset() const {
 321     return verifier_constraints_offset() + verifier_constraints_size(_num_verifier_constraints);
 322   }
 323 
 324   void check_verifier_constraint_offset(int i) const {
 325     assert(0 <= i && i < _num_verifier_constraints, "sanity");
 326   }
 327 
 328   void check_loader_constraint_offset(int i) const {
 329     assert(0 <= i && i < _num_loader_constraints, "sanity");
 330   }
 331 
 332 public:
 333   CrcInfo* crc() const {
 334     assert(crc_size(_klass) > 0, "must be");
 335     return (CrcInfo*)(address(this) + crc_offset());
 336   }
 337   RTVerifierConstraint* verifier_constraints() {
 338     assert(_num_verifier_constraints > 0, "sanity");
 339     return (RTVerifierConstraint*)(address(this) + verifier_constraints_offset());
 340   }
 341   RTVerifierConstraint* verifier_constraint_at(int i) {
 342     check_verifier_constraint_offset(i);
 343     return verifier_constraints() + i;
 344   }
 345 
 346   char* verifier_constraint_flags() {
 347     assert(_num_verifier_constraints > 0, "sanity");
 348     return (char*)(address(this) + verifier_constraint_flags_offset());
 349   }
 350 
 351   RTLoaderConstraint* loader_constraints() {
 352     assert(_num_loader_constraints > 0, "sanity");
 353     return (RTLoaderConstraint*)(address(this) + loader_constraints_offset());
 354   }
 355 
 356   RTLoaderConstraint* loader_constraint_at(int i) {
 357     check_loader_constraint_offset(i);
 358     return loader_constraints() + i;
 359   }
 360 
 361   static u4 object_delta_u4(Symbol* sym) {
 362     if (DynamicDumpSharedSpaces) {
 363       sym = DynamicArchive::original_to_target(sym);
 364     }
 365     return MetaspaceShared::object_delta_u4(sym);
 366   }
 367 
 368   void init(DumpTimeSharedClassInfo& info) {
 369     _klass = info._klass;
 370     if (!SystemDictionaryShared::is_builtin(_klass)) {
 371       CrcInfo* c = crc();
 372       c->_clsfile_size = info._clsfile_size;
 373       c->_clsfile_crc32 = info._clsfile_crc32;
 374     }
 375     _num_verifier_constraints = info.num_verifier_constraints();
 376     _num_loader_constraints   = info.num_loader_constraints();
 377     int i;
 378     if (_num_verifier_constraints > 0) {
 379       RTVerifierConstraint* vf_constraints = verifier_constraints();
 380       char* flags = verifier_constraint_flags();
 381       for (i = 0; i < _num_verifier_constraints; i++) {
 382         vf_constraints[i]._name      = object_delta_u4(info._verifier_constraints->at(i)._name);
 383         vf_constraints[i]._from_name = object_delta_u4(info._verifier_constraints->at(i)._from_name);
 384       }
 385       for (i = 0; i < _num_verifier_constraints; i++) {
 386         flags[i] = info._verifier_constraint_flags->at(i);
 387       }
 388     }
 389 
 390     if (_num_loader_constraints > 0) {
 391       RTLoaderConstraint* ld_constraints = loader_constraints();
 392       for (i = 0; i < _num_loader_constraints; i++) {
 393         ld_constraints[i]._name = object_delta_u4(info._loader_constraints->at(i)._name);
 394         ld_constraints[i]._loader_type1 = info._loader_constraints->at(i)._loader_type1;
 395         ld_constraints[i]._loader_type2 = info._loader_constraints->at(i)._loader_type2;
 396       }
 397     }
 398     if (DynamicDumpSharedSpaces) {
 399       _klass = DynamicArchive::original_to_target(info._klass);
 400     }
 401     ArchivePtrMarker::mark_pointer(&_klass);
 402   }
 403 
 404   bool matches(int clsfile_size, int clsfile_crc32) const {
 405     return crc()->_clsfile_size  == clsfile_size &&
 406            crc()->_clsfile_crc32 == clsfile_crc32;
 407   }
 408 
 409   char verifier_constraint_flag(int i) {
 410     check_verifier_constraint_offset(i);
 411     return verifier_constraint_flags()[i];
 412   }
 413 
 414 private:
 415   // ArchiveCompactor::allocate() has reserved a pointer immediately before
 416   // archived InstanceKlasses. We can use this slot to do a quick
 417   // lookup of InstanceKlass* -> RunTimeSharedClassInfo* without
 418   // building a new hashtable.
 419   //
 420   //  info_pointer_addr(klass) --> 0x0100   RunTimeSharedClassInfo*
 421   //  InstanceKlass* klass     --> 0x0108   <C++ vtbl>
 422   //                               0x0110   fields from Klass ...
 423   static RunTimeSharedClassInfo** info_pointer_addr(InstanceKlass* klass) {
 424     return &((RunTimeSharedClassInfo**)klass)[-1];
 425   }
 426 
 427 public:
 428   static RunTimeSharedClassInfo* get_for(InstanceKlass* klass) {
 429     return *info_pointer_addr(klass);
 430   }
 431   static void set_for(InstanceKlass* klass, RunTimeSharedClassInfo* record) {
 432     if (DynamicDumpSharedSpaces) {
 433       klass = DynamicArchive::original_to_buffer(klass);
 434       *info_pointer_addr(klass) = DynamicArchive::buffer_to_target(record);
 435     } else {
 436       *info_pointer_addr(klass) = record;
 437     }
 438 
 439     ArchivePtrMarker::mark_pointer(info_pointer_addr(klass));
 440   }
 441 
 442   // Used by RunTimeSharedDictionary to implement OffsetCompactHashtable::EQUALS
 443   static inline bool EQUALS(
 444        const RunTimeSharedClassInfo* value, Symbol* key, int len_unused) {
 445     return (value->_klass->name() == key);
 446   }
 447 };
 448 
 449 class RunTimeSharedDictionary : public OffsetCompactHashtable<
 450   Symbol*,
 451   const RunTimeSharedClassInfo*,
 452   RunTimeSharedClassInfo::EQUALS> {};
 453 
 454 static DumpTimeSharedClassTable* _dumptime_table = NULL;
 455 // SystemDictionaries in the base layer static archive
 456 static RunTimeSharedDictionary _builtin_dictionary;
 457 static RunTimeSharedDictionary _unregistered_dictionary;
 458 // SystemDictionaries in the top layer dynamic archive
 459 static RunTimeSharedDictionary _dynamic_builtin_dictionary;
 460 static RunTimeSharedDictionary _dynamic_unregistered_dictionary;
 461 
 462 oop SystemDictionaryShared::shared_protection_domain(int index) {
 463   return ((objArrayOop)_shared_protection_domains.resolve())->obj_at(index);
 464 }
 465 
 466 oop SystemDictionaryShared::shared_jar_url(int index) {
 467   return ((objArrayOop)_shared_jar_urls.resolve())->obj_at(index);
 468 }
 469 
 470 oop SystemDictionaryShared::shared_jar_manifest(int index) {
 471   return ((objArrayOop)_shared_jar_manifests.resolve())->obj_at(index);
 472 }
 473 
 474 Handle SystemDictionaryShared::get_shared_jar_manifest(int shared_path_index, TRAPS) {
 475   Handle manifest ;
 476   if (shared_jar_manifest(shared_path_index) == NULL) {
 477     SharedClassPathEntry* ent = FileMapInfo::shared_path(shared_path_index);
 478     long size = ent->manifest_size();
 479     if (size <= 0) {
 480       return Handle();
 481     }
 482 
 483     // ByteArrayInputStream bais = new ByteArrayInputStream(buf);
 484     const char* src = ent->manifest();
 485     assert(src != NULL, "No Manifest data");
 486     typeArrayOop buf = oopFactory::new_byteArray(size, CHECK_NH);
 487     typeArrayHandle bufhandle(THREAD, buf);
 488     ArrayAccess<>::arraycopy_from_native(reinterpret_cast<const jbyte*>(src),
 489                                          buf, typeArrayOopDesc::element_offset<jbyte>(0), size);
 490 
 491     Handle bais = JavaCalls::construct_new_instance(SystemDictionary::ByteArrayInputStream_klass(),
 492                       vmSymbols::byte_array_void_signature(),
 493                       bufhandle, CHECK_NH);
 494 
 495     // manifest = new Manifest(bais)
 496     manifest = JavaCalls::construct_new_instance(SystemDictionary::Jar_Manifest_klass(),
 497                       vmSymbols::input_stream_void_signature(),
 498                       bais, CHECK_NH);
 499     atomic_set_shared_jar_manifest(shared_path_index, manifest());
 500   }
 501 
 502   manifest = Handle(THREAD, shared_jar_manifest(shared_path_index));
 503   assert(manifest.not_null(), "sanity");
 504   return manifest;
 505 }
 506 
 507 Handle SystemDictionaryShared::get_shared_jar_url(int shared_path_index, TRAPS) {
 508   Handle url_h;
 509   if (shared_jar_url(shared_path_index) == NULL) {
 510     JavaValue result(T_OBJECT);
 511     const char* path = FileMapInfo::shared_path_name(shared_path_index);
 512     Handle path_string = java_lang_String::create_from_str(path, CHECK_(url_h));
 513     Klass* classLoaders_klass =
 514         SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 515     JavaCalls::call_static(&result, classLoaders_klass,
 516                            vmSymbols::toFileURL_name(),
 517                            vmSymbols::toFileURL_signature(),
 518                            path_string, CHECK_(url_h));
 519 
 520     atomic_set_shared_jar_url(shared_path_index, (oop)result.get_jobject());
 521   }
 522 
 523   url_h = Handle(THREAD, shared_jar_url(shared_path_index));
 524   assert(url_h.not_null(), "sanity");
 525   return url_h;
 526 }
 527 
 528 Handle SystemDictionaryShared::get_package_name(Symbol* class_name, TRAPS) {
 529   ResourceMark rm(THREAD);
 530   Handle pkgname_string;
 531   Symbol* pkg = ClassLoader::package_from_class_name(class_name);
 532   if (pkg != NULL) { // Package prefix found
 533     const char* pkgname = pkg->as_klass_external_name();
 534     pkgname_string = java_lang_String::create_from_str(pkgname,
 535                                                        CHECK_(pkgname_string));
 536   }
 537   return pkgname_string;
 538 }
 539 
 540 // Define Package for shared app classes from JAR file and also checks for
 541 // package sealing (all done in Java code)
 542 // See http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html
 543 void SystemDictionaryShared::define_shared_package(Symbol*  class_name,
 544                                                    Handle class_loader,
 545                                                    Handle manifest,
 546                                                    Handle url,
 547                                                    TRAPS) {
 548   assert(SystemDictionary::is_system_class_loader(class_loader()), "unexpected class loader");
 549   // get_package_name() returns a NULL handle if the class is in unnamed package
 550   Handle pkgname_string = get_package_name(class_name, CHECK);
 551   if (pkgname_string.not_null()) {
 552     Klass* app_classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
 553     JavaValue result(T_OBJECT);
 554     JavaCallArguments args(3);
 555     args.set_receiver(class_loader);
 556     args.push_oop(pkgname_string);
 557     args.push_oop(manifest);
 558     args.push_oop(url);
 559     JavaCalls::call_virtual(&result, app_classLoader_klass,
 560                             vmSymbols::defineOrCheckPackage_name(),
 561                             vmSymbols::defineOrCheckPackage_signature(),
 562                             &args,
 563                             CHECK);
 564   }
 565 }
 566 
 567 // Get the ProtectionDomain associated with the CodeSource from the classloader.
 568 Handle SystemDictionaryShared::get_protection_domain_from_classloader(Handle class_loader,
 569                                                                       Handle url, TRAPS) {
 570   // CodeSource cs = new CodeSource(url, null);
 571   Handle cs = JavaCalls::construct_new_instance(SystemDictionary::CodeSource_klass(),
 572                   vmSymbols::url_code_signer_array_void_signature(),
 573                   url, Handle(), CHECK_NH);
 574 
 575   // protection_domain = SecureClassLoader.getProtectionDomain(cs);
 576   Klass* secureClassLoader_klass = SystemDictionary::SecureClassLoader_klass();
 577   JavaValue obj_result(T_OBJECT);
 578   JavaCalls::call_virtual(&obj_result, class_loader, secureClassLoader_klass,
 579                           vmSymbols::getProtectionDomain_name(),
 580                           vmSymbols::getProtectionDomain_signature(),
 581                           cs, CHECK_NH);
 582   return Handle(THREAD, (oop)obj_result.get_jobject());
 583 }
 584 
 585 // Returns the ProtectionDomain associated with the JAR file identified by the url.
 586 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 587                                                             int shared_path_index,
 588                                                             Handle url,
 589                                                             TRAPS) {
 590   Handle protection_domain;
 591   if (shared_protection_domain(shared_path_index) == NULL) {
 592     Handle pd = get_protection_domain_from_classloader(class_loader, url, THREAD);
 593     atomic_set_shared_protection_domain(shared_path_index, pd());
 594   }
 595 
 596   // Acquire from the cache because if another thread beats the current one to
 597   // set the shared protection_domain and the atomic_set fails, the current thread
 598   // needs to get the updated protection_domain from the cache.
 599   protection_domain = Handle(THREAD, shared_protection_domain(shared_path_index));
 600   assert(protection_domain.not_null(), "sanity");
 601   return protection_domain;
 602 }
 603 
 604 // Returns the ProtectionDomain associated with the moduleEntry.
 605 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 606                                                             ModuleEntry* mod, TRAPS) {
 607   ClassLoaderData *loader_data = mod->loader_data();
 608   if (mod->shared_protection_domain() == NULL) {
 609     Symbol* location = mod->location();
 610     if (location != NULL) {
 611       Handle location_string = java_lang_String::create_from_symbol(
 612                                      location, CHECK_NH);
 613       Handle url;
 614       JavaValue result(T_OBJECT);
 615       if (location->starts_with("jrt:/")) {
 616         url = JavaCalls::construct_new_instance(SystemDictionary::URL_klass(),
 617                                                 vmSymbols::string_void_signature(),
 618                                                 location_string, CHECK_NH);
 619       } else {
 620         Klass* classLoaders_klass =
 621           SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 622         JavaCalls::call_static(&result, classLoaders_klass, vmSymbols::toFileURL_name(),
 623                                vmSymbols::toFileURL_signature(),
 624                                location_string, CHECK_NH);
 625         url = Handle(THREAD, (oop)result.get_jobject());
 626       }
 627 
 628       Handle pd = get_protection_domain_from_classloader(class_loader, url,
 629                                                          CHECK_NH);
 630       mod->set_shared_protection_domain(loader_data, pd);
 631     }
 632   }
 633 
 634   Handle protection_domain(THREAD, mod->shared_protection_domain());
 635   assert(protection_domain.not_null(), "sanity");
 636   return protection_domain;
 637 }
 638 
 639 // Initializes the java.lang.Package and java.security.ProtectionDomain objects associated with
 640 // the given InstanceKlass.
 641 // Returns the ProtectionDomain for the InstanceKlass.
 642 Handle SystemDictionaryShared::init_security_info(Handle class_loader, InstanceKlass* ik, PackageEntry* pkg_entry, TRAPS) {
 643   Handle pd;
 644 
 645   if (ik != NULL) {
 646     int index = ik->shared_classpath_index();
 647     assert(index >= 0, "Sanity");
 648     SharedClassPathEntry* ent = FileMapInfo::shared_path(index);
 649     Symbol* class_name = ik->name();
 650 
 651     if (ent->is_modules_image()) {
 652       // For shared app/platform classes originated from the run-time image:
 653       //   The ProtectionDomains are cached in the corresponding ModuleEntries
 654       //   for fast access by the VM.
 655       // all packages from module image are already created during VM bootstrap in
 656       // Modules::define_module().
 657       assert(pkg_entry != NULL, "archived class in module image cannot be from unnamed package");
 658       ModuleEntry* mod_entry = pkg_entry->module();
 659       pd = get_shared_protection_domain(class_loader, mod_entry, THREAD);
 660     } else {
 661       // For shared app/platform classes originated from JAR files on the class path:
 662       //   Each of the 3 SystemDictionaryShared::_shared_xxx arrays has the same length
 663       //   as the shared classpath table in the shared archive (see
 664       //   FileMap::_shared_path_table in filemap.hpp for details).
 665       //
 666       //   If a shared InstanceKlass k is loaded from the class path, let
 667       //
 668       //     index = k->shared_classpath_index():
 669       //
 670       //   FileMap::_shared_path_table[index] identifies the JAR file that contains k.
 671       //
 672       //   k's protection domain is:
 673       //
 674       //     ProtectionDomain pd = _shared_protection_domains[index];
 675       //
 676       //   and k's Package is initialized using
 677       //
 678       //     manifest = _shared_jar_manifests[index];
 679       //     url = _shared_jar_urls[index];
 680       //     define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 681       //
 682       //   Note that if an element of these 3 _shared_xxx arrays is NULL, it will be initialized by
 683       //   the corresponding SystemDictionaryShared::get_shared_xxx() function.
 684       Handle manifest = get_shared_jar_manifest(index, CHECK_(pd));
 685       Handle url = get_shared_jar_url(index, CHECK_(pd));
 686       define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 687       pd = get_shared_protection_domain(class_loader, index, url, CHECK_(pd));
 688     }
 689   }
 690   return pd;
 691 }
 692 
 693 bool SystemDictionaryShared::is_sharing_possible(ClassLoaderData* loader_data) {
 694   oop class_loader = loader_data->class_loader();
 695   return (class_loader == NULL ||
 696           SystemDictionary::is_system_class_loader(class_loader) ||
 697           SystemDictionary::is_platform_class_loader(class_loader));
 698 }
 699 
 700 // Currently AppCDS only archives classes from the run-time image, the
 701 // -Xbootclasspath/a path, the class path, and the module path.
 702 //
 703 // Check if a shared class can be loaded by the specific classloader. Following
 704 // are the "visible" archived classes for different classloaders.
 705 //
 706 // NULL classloader:
 707 //   - see SystemDictionary::is_shared_class_visible()
 708 // Platform classloader:
 709 //   - Module class from runtime image. ModuleEntry must be defined in the
 710 //     classloader.
 711 // App classloader:
 712 //   - Module Class from runtime image and module path. ModuleEntry must be defined in the
 713 //     classloader.
 714 //   - Class from -cp. The class must have no PackageEntry defined in any of the
 715 //     boot/platform/app classloader, or must be in the unnamed module defined in the
 716 //     AppClassLoader.
 717 bool SystemDictionaryShared::is_shared_class_visible_for_classloader(
 718                                                      InstanceKlass* ik,
 719                                                      Handle class_loader,
 720                                                      Symbol* pkg_name,
 721                                                      PackageEntry* pkg_entry,
 722                                                      ModuleEntry* mod_entry,
 723                                                      TRAPS) {
 724   assert(class_loader.not_null(), "Class loader should not be NULL");
 725   assert(Universe::is_module_initialized(), "Module system is not initialized");
 726   ResourceMark rm(THREAD);
 727 
 728   int path_index = ik->shared_classpath_index();
 729   SharedClassPathEntry* ent =
 730             (SharedClassPathEntry*)FileMapInfo::shared_path(path_index);
 731 
 732   if (SystemDictionary::is_platform_class_loader(class_loader())) {
 733     assert(ent != NULL, "shared class for PlatformClassLoader should have valid SharedClassPathEntry");
 734     // The PlatformClassLoader can only load archived class originated from the
 735     // run-time image. The class' PackageEntry/ModuleEntry must be
 736     // defined by the PlatformClassLoader.
 737     if (mod_entry != NULL) {
 738       // PackageEntry/ModuleEntry is found in the classloader. Check if the
 739       // ModuleEntry's location agrees with the archived class' origination.
 740       if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 741         return true; // Module class from the runtime image
 742       }
 743     }
 744   } else if (SystemDictionary::is_system_class_loader(class_loader())) {
 745     assert(ent != NULL, "shared class for system loader should have valid SharedClassPathEntry");
 746     if (pkg_name == NULL) {
 747       // The archived class is in the unnamed package. Currently, the boot image
 748       // does not contain any class in the unnamed package.
 749       assert(!ent->is_modules_image(), "Class in the unnamed package must be from the classpath");
 750       if (path_index >= ClassLoaderExt::app_class_paths_start_index()) {
 751         assert(path_index < ClassLoaderExt::app_module_paths_start_index(), "invalid path_index");
 752         return true;
 753       }
 754     } else {
 755       // Check if this is from a PackageEntry/ModuleEntry defined in the AppClassloader.
 756       if (pkg_entry == NULL) {
 757         // It's not guaranteed that the class is from the classpath if the
 758         // PackageEntry cannot be found from the AppClassloader. Need to check
 759         // the boot and platform classloader as well.
 760         ClassLoaderData* platform_loader_data =
 761           ClassLoaderData::class_loader_data_or_null(SystemDictionary::java_platform_loader()); // can be NULL during bootstrap
 762         if ((platform_loader_data == NULL ||
 763              ClassLoader::get_package_entry(pkg_name, platform_loader_data) == NULL) &&
 764              ClassLoader::get_package_entry(pkg_name, ClassLoaderData::the_null_class_loader_data()) == NULL) {
 765           // The PackageEntry is not defined in any of the boot/platform/app classloaders.
 766           // The archived class must from -cp path and not from the runtime image.
 767           if (!ent->is_modules_image() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 768                                           path_index < ClassLoaderExt::app_module_paths_start_index()) {
 769             return true;
 770           }
 771         }
 772       } else if (mod_entry != NULL) {
 773         // The package/module is defined in the AppClassLoader. We support
 774         // archiving application module class from the runtime image or from
 775         // a named module from a module path.
 776         // Packages from the -cp path are in the unnamed_module.
 777         if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 778           // shared module class from runtime image
 779           return true;
 780         } else if (pkg_entry->in_unnamed_module() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 781             path_index < ClassLoaderExt::app_module_paths_start_index()) {
 782           // shared class from -cp
 783           DEBUG_ONLY( \
 784             ClassLoaderData* loader_data = class_loader_data(class_loader); \
 785             assert(mod_entry == loader_data->unnamed_module(), "the unnamed module is not defined in the classloader");)
 786           return true;
 787         } else {
 788           if(!pkg_entry->in_unnamed_module() &&
 789               (path_index >= ClassLoaderExt::app_module_paths_start_index())&&
 790               (path_index < FileMapInfo::get_number_of_shared_paths()) &&
 791               (strcmp(ent->name(), ClassLoader::skip_uri_protocol(mod_entry->location()->as_C_string())) == 0)) {
 792             // shared module class from module path
 793             return true;
 794           } else {
 795             assert(path_index < FileMapInfo::get_number_of_shared_paths(), "invalid path_index");
 796           }
 797         }
 798       }
 799     }
 800   } else {
 801     // TEMP: if a shared class can be found by a custom loader, consider it visible now.
 802     // FIXME: is this actually correct?
 803     return true;
 804   }
 805   return false;
 806 }
 807 
 808 bool SystemDictionaryShared::has_platform_or_app_classes() {
 809   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 810     return true;
 811   }
 812   if (DynamicArchive::is_mapped() &&
 813       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 814     return true;
 815   }
 816   return false;
 817 }
 818 
 819 // The following stack shows how this code is reached:
 820 //
 821 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 822 //   [1] JVM_FindLoadedClass
 823 //   [2] java.lang.ClassLoader.findLoadedClass0()
 824 //   [3] java.lang.ClassLoader.findLoadedClass()
 825 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 826 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 827 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 828 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 829 //
 830 // AppCDS supports fast class loading for these 2 built-in class loaders:
 831 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 832 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 833 // with the following assumptions (based on the JDK core library source code):
 834 //
 835 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 836 //     load the named class.
 837 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 838 // [c] At this point, if we can find the named class inside the
 839 //     shared_dictionary, we can perform further checks (see
 840 //     is_shared_class_visible_for_classloader() to ensure that this class
 841 //     was loaded by the same class loader during dump time.
 842 //
 843 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 844 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 845 // the archive for the 2 built-in class loaders. This way,
 846 // we can improve start-up because we avoid decoding the classfile,
 847 // and avoid delegating to the parent loader.
 848 //
 849 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 850 // needs to be redesigned.
 851 
 852 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 853                  Symbol* name, Handle class_loader, TRAPS) {
 854   InstanceKlass* k = NULL;
 855   if (UseSharedSpaces) {
 856     if (!has_platform_or_app_classes()) {
 857       return NULL;
 858     }
 859 
 860     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 861         SystemDictionary::is_platform_class_loader(class_loader())) {
 862       // Fix for 4474172; see evaluation for more details
 863       class_loader = Handle(
 864         THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 865       ClassLoaderData *loader_data = register_loader(class_loader);
 866       Dictionary* dictionary = loader_data->dictionary();
 867 
 868       unsigned int d_hash = dictionary->compute_hash(name);
 869 
 870       bool DoObjectLock = true;
 871       if (is_parallelCapable(class_loader)) {
 872         DoObjectLock = false;
 873       }
 874 
 875       // Make sure we are synchronized on the class loader before we proceed
 876       //
 877       // Note: currently, find_or_load_shared_class is called only from
 878       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 879       // which are parallel-capable loaders, so this lock is NOT taken.
 880       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 881       check_loader_lock_contention(lockObject, THREAD);
 882       ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 883 
 884       {
 885         MutexLocker mu(THREAD, SystemDictionary_lock);
 886         InstanceKlass* check = find_class(d_hash, name, dictionary);
 887         if (check != NULL) {
 888           return check;
 889         }
 890       }
 891 
 892       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 893       if (k != NULL) {
 894         define_instance_class(k, CHECK_NULL);
 895       }
 896     }
 897   }
 898   return k;
 899 }
 900 
 901 PackageEntry* SystemDictionaryShared::get_package_entry_from_class_name(Handle class_loader, Symbol* class_name) {
 902   PackageEntry* pkg_entry = NULL;
 903   TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
 904   if (pkg_name != NULL) {
 905     pkg_entry = class_loader_data(class_loader)->packages()->lookup_only(pkg_name);
 906   }
 907   return pkg_entry;
 908 }
 909 
 910 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 911                  Symbol* class_name, Handle class_loader, TRAPS) {
 912   assert(UseSharedSpaces, "must be");
 913   InstanceKlass* ik = find_builtin_class(class_name);
 914 
 915   if (ik != NULL) {
 916     if ((ik->is_shared_app_class() &&
 917          SystemDictionary::is_system_class_loader(class_loader()))  ||
 918         (ik->is_shared_platform_class() &&
 919          SystemDictionary::is_platform_class_loader(class_loader()))) {
 920       PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, class_name);
 921       Handle protection_domain =
 922         SystemDictionaryShared::init_security_info(class_loader, ik, pkg_entry, CHECK_NULL);
 923       return load_shared_class(ik, class_loader, protection_domain, NULL, pkg_entry, THREAD);
 924     }
 925   }
 926   return NULL;
 927 }
 928 
 929 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) {
 930   if (_shared_protection_domains.resolve() == NULL) {
 931     oop spd = oopFactory::new_objArray(
 932         SystemDictionary::ProtectionDomain_klass(), size, CHECK);
 933     _shared_protection_domains = OopHandle::create(spd);
 934   }
 935 }
 936 
 937 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) {
 938   if (_shared_jar_urls.resolve() == NULL) {
 939     oop sju = oopFactory::new_objArray(
 940         SystemDictionary::URL_klass(), size, CHECK);
 941     _shared_jar_urls = OopHandle::create(sju);
 942   }
 943 }
 944 
 945 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) {
 946   if (_shared_jar_manifests.resolve() == NULL) {
 947     oop sjm = oopFactory::new_objArray(
 948         SystemDictionary::Jar_Manifest_klass(), size, CHECK);
 949     _shared_jar_manifests = OopHandle::create(sjm);
 950   }
 951 }
 952 
 953 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) {
 954   allocate_shared_protection_domain_array(size, CHECK);
 955   allocate_shared_jar_url_array(size, CHECK);
 956   allocate_shared_jar_manifest_array(size, CHECK);
 957 }
 958 
 959 // This function is called for loading only UNREGISTERED classes
 960 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 961                                                           Handle class_loader,
 962                                                           Handle protection_domain,
 963                                                           const ClassFileStream* cfs,
 964                                                           TRAPS) {
 965   if (!UseSharedSpaces) {
 966     return NULL;
 967   }
 968   if (class_name == NULL) {  // don't do this for hidden and unsafe anonymous classes
 969     return NULL;
 970   }
 971   if (class_loader.is_null() ||
 972       SystemDictionary::is_system_class_loader(class_loader()) ||
 973       SystemDictionary::is_platform_class_loader(class_loader())) {
 974     // Do nothing for the BUILTIN loaders.
 975     return NULL;
 976   }
 977 
 978   const RunTimeSharedClassInfo* record = find_record(&_unregistered_dictionary, &_dynamic_unregistered_dictionary, class_name);
 979   if (record == NULL) {
 980     return NULL;
 981   }
 982 
 983   int clsfile_size  = cfs->length();
 984   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 985 
 986   if (!record->matches(clsfile_size, clsfile_crc32)) {
 987     return NULL;
 988   }
 989 
 990   return acquire_class_for_current_thread(record->_klass, class_loader,
 991                                           protection_domain, cfs,
 992                                           THREAD);
 993 }
 994 
 995 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 996                    InstanceKlass *ik,
 997                    Handle class_loader,
 998                    Handle protection_domain,
 999                    const ClassFileStream *cfs,
1000                    TRAPS) {
1001   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1002 
1003   {
1004     MutexLocker mu(THREAD, SharedDictionary_lock);
1005     if (ik->class_loader_data() != NULL) {
1006       //    ik is already loaded (by this loader or by a different loader)
1007       // or ik is being loaded by a different thread (by this loader or by a different loader)
1008       return NULL;
1009     }
1010 
1011     // No other thread has acquired this yet, so give it to *this thread*
1012     ik->set_class_loader_data(loader_data);
1013   }
1014 
1015   // No longer holding SharedDictionary_lock
1016   // No need to lock, as <ik> can be held only by a single thread.
1017   loader_data->add_class(ik);
1018 
1019   // Get the package entry.
1020   PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, ik->name());
1021 
1022   // Load and check super/interfaces, restore unsharable info
1023   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
1024                                                   cfs, pkg_entry, THREAD);
1025   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
1026     // TODO: clean up <ik> so it can be used again
1027     return NULL;
1028   }
1029 
1030   return shared_klass;
1031 }
1032 
1033 static ResourceHashtable<
1034   Symbol*, bool,
1035   primitive_hash<Symbol*>,
1036   primitive_equals<Symbol*>,
1037   6661,                             // prime number
1038   ResourceObj::C_HEAP> _loaded_unregistered_classes;
1039 
1040 bool SystemDictionaryShared::add_unregistered_class(InstanceKlass* k, TRAPS) {
1041   // We don't allow duplicated unregistered classes of the same name.
1042   assert(DumpSharedSpaces, "only when dumping");
1043   Symbol* name = k->name();
1044   bool created = false;
1045   _loaded_unregistered_classes.put_if_absent(name, true, &created);
1046   if (created) {
1047     MutexLocker mu_r(THREAD, Compile_lock); // add_to_hierarchy asserts this.
1048     SystemDictionary::add_to_hierarchy(k, CHECK_false);
1049   }
1050   return created;
1051 }
1052 
1053 // This function is called to resolve the super/interfaces of shared classes for
1054 // non-built-in loaders. E.g., ChildClass in the below example
1055 // where "super:" (and optionally "interface:") have been specified.
1056 //
1057 // java/lang/Object id: 0
1058 // Interface   id: 2 super: 0 source: cust.jar
1059 // ChildClass  id: 4 super: 0 interfaces: 2 source: cust.jar
1060 InstanceKlass* SystemDictionaryShared::dump_time_resolve_super_or_fail(
1061     Symbol* child_name, Symbol* class_name, Handle class_loader,
1062     Handle protection_domain, bool is_superclass, TRAPS) {
1063 
1064   assert(DumpSharedSpaces, "only when dumping");
1065 
1066   ClassListParser* parser = ClassListParser::instance();
1067   if (parser == NULL) {
1068     // We're still loading the well-known classes, before the ClassListParser is created.
1069     return NULL;
1070   }
1071   if (child_name->equals(parser->current_class_name())) {
1072     // When this function is called, all the numbered super and interface types
1073     // must have already been loaded. Hence this function is never recursively called.
1074     if (is_superclass) {
1075       return parser->lookup_super_for_current_class(class_name);
1076     } else {
1077       return parser->lookup_interface_for_current_class(class_name);
1078     }
1079   } else {
1080     // The VM is not trying to resolve a super type of parser->current_class_name().
1081     // Instead, it's resolving an error class (because parser->current_class_name() has
1082     // failed parsing or verification). Don't do anything here.
1083     return NULL;
1084   }
1085 }
1086 
1087 DumpTimeSharedClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) {
1088   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1089   if (_dumptime_table == NULL) {
1090     _dumptime_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeSharedClassTable();
1091   }
1092   return _dumptime_table->find_or_allocate_info_for(k);
1093 }
1094 
1095 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
1096   Arguments::assert_is_dumping_archive();
1097   assert(!is_builtin(k), "must be unregistered class");
1098   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1099   info->_clsfile_size  = cfs->length();
1100   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
1101 }
1102 
1103 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
1104   (void)find_or_allocate_info_for(k);
1105 }
1106 
1107 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
1108   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1109   DumpTimeSharedClassInfo* p = _dumptime_table->get(k);
1110   if (p == NULL) {
1111     return;
1112   }
1113   if (p->_verifier_constraints != NULL) {
1114     for (int i = 0; i < p->_verifier_constraints->length(); i++) {
1115       DumpTimeSharedClassInfo::DTVerifierConstraint constraint = p->_verifier_constraints->at(i);
1116       if (constraint._name != NULL ) {
1117         constraint._name->decrement_refcount();
1118       }
1119       if (constraint._from_name != NULL ) {
1120         constraint._from_name->decrement_refcount();
1121       }
1122     }
1123     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTVerifierConstraint, p->_verifier_constraints);
1124     p->_verifier_constraints = NULL;
1125     FREE_C_HEAP_ARRAY(char, p->_verifier_constraint_flags);
1126     p->_verifier_constraint_flags = NULL;
1127   }
1128   if (p->_loader_constraints != NULL) {
1129     for (int i = 0; i < p->_loader_constraints->length(); i++) {
1130       DumpTimeSharedClassInfo::DTLoaderConstraint ld =  p->_loader_constraints->at(i);
1131       if (ld._name != NULL) {
1132         ld._name->decrement_refcount();
1133       }
1134     }
1135     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTLoaderConstraint, p->_loader_constraints);
1136     p->_loader_constraints = NULL;
1137   }
1138   _dumptime_table->remove(k);
1139 }
1140 
1141 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
1142   while (k) {
1143     if (k->name()->equals("jdk/internal/event/Event")) {
1144       return true;
1145     }
1146     k = k->java_super();
1147   }
1148   return false;
1149 }
1150 
1151 void SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
1152   ResourceMark rm;
1153   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
1154 }
1155 
1156 bool SystemDictionaryShared::should_be_excluded(InstanceKlass* k) {
1157   if (k->is_hidden() || k->is_unsafe_anonymous()) {
1158     warn_excluded(k, "Hidden or Unsafe anonymous class");
1159     return true; // hidden and unsafe anonymous classes are not archived, skip
1160   }
1161   if (k->is_in_error_state()) {
1162     warn_excluded(k, "In error state");
1163     return true;
1164   }
1165   if (k->has_been_redefined()) {
1166     warn_excluded(k, "Has been redefined");
1167     return true;
1168   }
1169   if (k->shared_classpath_index() < 0 && is_builtin(k)) {
1170     // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
1171     // agent during dump time).
1172     warn_excluded(k, "Unsupported location");
1173     return true;
1174   }
1175   if (k->signers() != NULL) {
1176     // We cannot include signed classes in the archive because the certificates
1177     // used during dump time may be different than those used during
1178     // runtime (due to expiration, etc).
1179     warn_excluded(k, "Signed JAR");
1180     return true;
1181   }
1182   if (is_jfr_event_class(k)) {
1183     // We cannot include JFR event classes because they need runtime-specific
1184     // instrumentation in order to work with -XX:FlightRecorderOptions=retransform=false.
1185     // There are only a small number of these classes, so it's not worthwhile to
1186     // support them and make CDS more complicated.
1187     warn_excluded(k, "JFR event class");
1188     return true;
1189   }
1190   if (k->init_state() < InstanceKlass::linked) {
1191     // In CDS dumping, we will attempt to link all classes. Those that fail to link will
1192     // be recorded in DumpTimeSharedClassInfo.
1193     Arguments::assert_is_dumping_archive();
1194 
1195     // TODO -- rethink how this can be handled.
1196     // We should try to link ik, however, we can't do it here because
1197     // 1. We are at VM exit
1198     // 2. linking a class may cause other classes to be loaded, which means
1199     //    a custom ClassLoader.loadClass() may be called, at a point where the
1200     //    class loader doesn't expect it.
1201     if (has_class_failed_verification(k)) {
1202       warn_excluded(k, "Failed verification");
1203     } else {
1204       warn_excluded(k, "Not linked");
1205     }
1206     return true;
1207   }
1208   if (k->major_version() < 50 /*JAVA_6_VERSION*/) {
1209     ResourceMark rm;
1210     log_warning(cds)("Pre JDK 6 class not supported by CDS: %u.%u %s",
1211                      k->major_version(),  k->minor_version(), k->name()->as_C_string());
1212     return true;
1213   }
1214 
1215   InstanceKlass* super = k->java_super();
1216   if (super != NULL && should_be_excluded(super)) {
1217     ResourceMark rm;
1218     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
1219     return true;
1220   }
1221 
1222   Array<InstanceKlass*>* interfaces = k->local_interfaces();
1223   int len = interfaces->length();
1224   for (int i = 0; i < len; i++) {
1225     InstanceKlass* intf = interfaces->at(i);
1226     if (should_be_excluded(intf)) {
1227       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
1228       return true;
1229     }
1230   }
1231 
1232   return false;
1233 }
1234 
1235 // k is a class before relocating by ArchiveCompactor
1236 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
1237   ResourceMark rm;
1238   const char* name = k->name()->as_C_string();
1239   DumpTimeSharedClassInfo* info = _dumptime_table->get(k);
1240   assert(_no_class_loading_should_happen, "class loading must be disabled");
1241   guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name);
1242   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
1243   if (is_builtin(k)) {
1244     guarantee(!k->is_shared_unregistered_class(),
1245               "Class loader type must be set for BUILTIN class %s", name);
1246   } else {
1247     guarantee(k->is_shared_unregistered_class(),
1248               "Class loader type must not be set for UNREGISTERED class %s", name);
1249   }
1250 }
1251 
1252 class ExcludeDumpTimeSharedClasses : StackObj {
1253 public:
1254   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1255     if (SystemDictionaryShared::should_be_excluded(k)) {
1256       info.set_excluded();
1257     }
1258     return true; // keep on iterating
1259   }
1260 };
1261 
1262 void SystemDictionaryShared::check_excluded_classes() {
1263   ExcludeDumpTimeSharedClasses excl;
1264   _dumptime_table->iterate(&excl);
1265   _dumptime_table->update_counts();
1266 }
1267 
1268 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
1269   assert(_no_class_loading_should_happen, "sanity");
1270   Arguments::assert_is_dumping_archive();
1271   return find_or_allocate_info_for(k)->is_excluded();
1272 }
1273 
1274 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
1275   Arguments::assert_is_dumping_archive();
1276   find_or_allocate_info_for(ik)->set_failed_verification();
1277 }
1278 
1279 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
1280   Arguments::assert_is_dumping_archive();
1281   if (_dumptime_table == NULL) {
1282     assert(DynamicDumpSharedSpaces, "sanity");
1283     assert(ik->is_shared(), "must be a shared class in the static archive");
1284     return false;
1285   }
1286   DumpTimeSharedClassInfo* p = _dumptime_table->get(ik);
1287   return (p == NULL) ? false : p->failed_verification();
1288 }
1289 
1290 class IterateDumpTimeSharedClassTable : StackObj {
1291   MetaspaceClosure *_it;
1292 public:
1293   IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {}
1294 
1295   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1296     if (!info.is_excluded()) {
1297       info.metaspace_pointers_do(_it);
1298     }
1299     return true; // keep on iterating
1300   }
1301 };
1302 
1303 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
1304   IterateDumpTimeSharedClassTable iter(it);
1305   _dumptime_table->iterate(&iter);
1306 }
1307 
1308 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1309          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1310   Arguments::assert_is_dumping_archive();
1311   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1312   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
1313                                     from_is_array, from_is_object);
1314 
1315   if (DynamicDumpSharedSpaces) {
1316     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
1317     // the initial run prior to creating the archive before vm exit. We will also perform verification
1318     // check when running with the archive.
1319     return false;
1320   } else {
1321     if (is_builtin(k)) {
1322       // For builtin class loaders, we can try to complete the verification check at dump time,
1323       // because we can resolve all the constraint classes. We will also perform verification check
1324       // when running with the archive.
1325       return false;
1326     } else {
1327       // For non-builtin class loaders, we cannot complete the verification check at dump time,
1328       // because at dump time we don't know how to resolve classes for such loaders.
1329       return true;
1330     }
1331   }
1332 }
1333 
1334 void DumpTimeSharedClassInfo::add_verification_constraint(InstanceKlass* k, Symbol* name,
1335          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1336   if (_verifier_constraints == NULL) {
1337     _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<DTVerifierConstraint>(4, true, mtClass);
1338   }
1339   if (_verifier_constraint_flags == NULL) {
1340     _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, true, mtClass);
1341   }
1342   GrowableArray<DTVerifierConstraint>* vc_array = _verifier_constraints;
1343   for (int i = 0; i < vc_array->length(); i++) {
1344     DTVerifierConstraint* p = vc_array->adr_at(i);
1345     if (name == p->_name && from_name == p->_from_name) {
1346       return;
1347     }
1348   }
1349   DTVerifierConstraint cons(name, from_name);
1350   vc_array->append(cons);
1351 
1352   GrowableArray<char>* vcflags_array = _verifier_constraint_flags;
1353   char c = 0;
1354   c |= from_field_is_protected ? SystemDictionaryShared::FROM_FIELD_IS_PROTECTED : 0;
1355   c |= from_is_array           ? SystemDictionaryShared::FROM_IS_ARRAY           : 0;
1356   c |= from_is_object          ? SystemDictionaryShared::FROM_IS_OBJECT          : 0;
1357   vcflags_array->append(c);
1358 
1359   if (log_is_enabled(Trace, cds, verification)) {
1360     ResourceMark rm;
1361     log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1362                                  k->external_name(), from_name->as_klass_external_name(),
1363                                  name->as_klass_external_name(), c);
1364   }
1365 }
1366 
1367 static char get_loader_type_by(oop  loader) {
1368   assert(SystemDictionary::is_builtin_class_loader(loader), "Must be built-in loader");
1369   if (SystemDictionary::is_boot_class_loader(loader)) {
1370     return (char)ClassLoader::BOOT_LOADER;
1371   } else if (SystemDictionary::is_platform_class_loader(loader)) {
1372     return (char)ClassLoader::PLATFORM_LOADER;
1373   } else {
1374     assert(SystemDictionary::is_system_class_loader(loader), "Class loader mismatch");
1375     return (char)ClassLoader::APP_LOADER;
1376   }
1377 }
1378 
1379 static oop get_class_loader_by(char type) {
1380   if (type == (char)ClassLoader::BOOT_LOADER) {
1381     return (oop)NULL;
1382   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1383     return SystemDictionary::java_platform_loader();
1384   } else {
1385     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1386     return SystemDictionary::java_system_loader();
1387   }
1388 }
1389 
1390 void DumpTimeSharedClassInfo::record_linking_constraint(Symbol* name, Handle loader1, Handle loader2) {
1391   assert(loader1 != loader2, "sanity");
1392   LogTarget(Info, class, loader, constraints) log;
1393   if (_loader_constraints == NULL) {
1394     _loader_constraints = new (ResourceObj::C_HEAP, mtClass) GrowableArray<DTLoaderConstraint>(4, true, mtClass);
1395   }
1396   char lt1 = get_loader_type_by(loader1());
1397   char lt2 = get_loader_type_by(loader2());
1398   DTLoaderConstraint lc(name, lt1, lt2);
1399   for (int i = 0; i < _loader_constraints->length(); i++) {
1400     DTLoaderConstraint dt = _loader_constraints->at(i);
1401     if (lc.equals(dt)) {
1402       if (log.is_enabled()) {
1403         ResourceMark rm;
1404         // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1405         log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s already added]",
1406                   _klass->external_name(), name->as_C_string(),
1407                   ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1408                   ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1409       }
1410       return;
1411     }
1412   }
1413   _loader_constraints->append(lc);
1414   if (log.is_enabled()) {
1415     ResourceMark rm;
1416     // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1417     log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s total %d]",
1418               _klass->external_name(), name->as_C_string(),
1419               ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1420               ClassLoaderData::class_loader_data(loader2())->loader_name_and_id(),
1421               _loader_constraints->length());
1422   }
1423 }
1424 
1425 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1426                                                             TRAPS) {
1427   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1428   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(klass);
1429 
1430   int length = record->_num_verifier_constraints;
1431   if (length > 0) {
1432     for (int i = 0; i < length; i++) {
1433       RunTimeSharedClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1434       Symbol* name      = vc->name();
1435       Symbol* from_name = vc->from_name();
1436       char c            = record->verifier_constraint_flag(i);
1437 
1438       if (log_is_enabled(Trace, cds, verification)) {
1439         ResourceMark rm(THREAD);
1440         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1441                                      klass->external_name(), from_name->as_klass_external_name(),
1442                                      name->as_klass_external_name(), c);
1443       }
1444 
1445       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
1446       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
1447       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
1448 
1449       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
1450          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
1451       if (!ok) {
1452         ResourceMark rm(THREAD);
1453         stringStream ss;
1454 
1455         ss.print_cr("Bad type on operand stack");
1456         ss.print_cr("Exception Details:");
1457         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1458         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1459                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1460         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1461       }
1462     }
1463   }
1464 }
1465 
1466 // Record class loader constraints that are checked inside
1467 // InstanceKlass::link_class(), so that these can be checked quickly
1468 // at runtime without laying out the vtable/itables.
1469 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1470                                                     Handle loader1, Handle loader2, TRAPS) {
1471   // A linking constraint check is executed when:
1472   //   - klass extends or implements type S
1473   //   - klass overrides method S.M(...) with X.M
1474   //     - If klass defines the method M, X is
1475   //       the same as klass.
1476   //     - If klass does not define the method M,
1477   //       X must be a supertype of klass and X.M is
1478   //       a default method defined by X.
1479   //   - loader1 = X->class_loader()
1480   //   - loader2 = S->class_loader()
1481   //   - loader1 != loader2
1482   //   - M's paramater(s) include an object type T
1483   // We require that
1484   //   - whenever loader1 and loader2 try to
1485   //     resolve the type T, they must always resolve to
1486   //     the same InstanceKlass.
1487   // NOTE: type T may or may not be currently resolved in
1488   // either of these two loaders. The check itself does not
1489   // try to resolve T.
1490   oop klass_loader = klass->class_loader();
1491   assert(klass_loader != NULL, "should not be called for boot loader");
1492   assert(loader1 != loader2, "must be");
1493 
1494   if (!is_system_class_loader(klass_loader) &&
1495       !is_platform_class_loader(klass_loader)) {
1496     // If klass is loaded by system/platform loaders, we can
1497     // guarantee that klass and S must be loaded by the same
1498     // respective loader between dump time and run time, and
1499     // the exact same check on (name, loader1, loader2) will
1500     // be executed. Hence, we can cache this check and execute
1501     // it at runtime without walking the vtable/itables.
1502     //
1503     // This cannot be guaranteed for classes loaded by other
1504     // loaders, so we bail.
1505     return;
1506   }
1507 
1508   if (THREAD->is_VM_thread()) {
1509     assert(DynamicDumpSharedSpaces, "must be");
1510     // We are re-laying out the vtable/itables of the *copy* of
1511     // a class during the final stage of dynamic dumping. The
1512     // linking constraints for this class has already been recorded.
1513     return;
1514   }
1515   Arguments::assert_is_dumping_archive();
1516   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(klass);
1517   info->record_linking_constraint(name, loader1, loader2);
1518 }
1519 
1520 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1521 // the purpose of checking class loader constraints.
1522 bool SystemDictionaryShared::check_linking_constraints(InstanceKlass* klass, TRAPS) {
1523   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1524   LogTarget(Info, class, loader, constraints) log;
1525   if (klass->is_shared_boot_class()) {
1526     // No class loader constraint check performed for boot classes.
1527     return true;
1528   }
1529   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1530     RunTimeSharedClassInfo* info = RunTimeSharedClassInfo::get_for(klass);
1531     assert(info != NULL, "Sanity");
1532     if (info->_num_loader_constraints > 0) {
1533       HandleMark hm;
1534       for (int i = 0; i < info->_num_loader_constraints; i++) {
1535         RunTimeSharedClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1536         Symbol* name = lc->constraint_name();
1537         Handle loader1(THREAD, get_class_loader_by(lc->_loader_type1));
1538         Handle loader2(THREAD, get_class_loader_by(lc->_loader_type2));
1539         if (log.is_enabled()) {
1540           ResourceMark rm(THREAD);
1541           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1542                     klass->external_name(), name->as_C_string(),
1543                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1544                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1545         }
1546         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2, THREAD)) {
1547           // Loader constraint violation has been found. The caller
1548           // will re-layout the vtable/itables to produce the correct
1549           // exception.
1550           if (log.is_enabled()) {
1551             log.print(" failed]");
1552           }
1553           return false;
1554         }
1555         if (log.is_enabled()) {
1556             log.print(" succeeded]");
1557         }
1558       }
1559       return true; // for all recorded constraints added successully.
1560     }
1561   }
1562   if (log.is_enabled()) {
1563     ResourceMark rm(THREAD);
1564     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1565   }
1566   return false;
1567 }
1568 
1569 class EstimateSizeForArchive : StackObj {
1570   size_t _shared_class_info_size;
1571   int _num_builtin_klasses;
1572   int _num_unregistered_klasses;
1573 
1574 public:
1575   EstimateSizeForArchive() {
1576     _shared_class_info_size = 0;
1577     _num_builtin_klasses = 0;
1578     _num_unregistered_klasses = 0;
1579   }
1580 
1581   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1582     if (!info.is_excluded()) {
1583       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
1584       _shared_class_info_size += align_up(byte_size, BytesPerWord);
1585     }
1586     return true; // keep on iterating
1587   }
1588 
1589   size_t total() {
1590     return _shared_class_info_size;
1591   }
1592 };
1593 
1594 size_t SystemDictionaryShared::estimate_size_for_archive() {
1595   EstimateSizeForArchive est;
1596   _dumptime_table->iterate(&est);
1597   return est.total() +
1598     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1599     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1600 }
1601 
1602 class CopySharedClassInfoToArchive : StackObj {
1603   CompactHashtableWriter* _writer;
1604   bool _is_builtin;
1605 public:
1606   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1607                                bool is_builtin,
1608                                bool is_static_archive)
1609     : _writer(writer), _is_builtin(is_builtin) {}
1610 
1611   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1612     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1613       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
1614       RunTimeSharedClassInfo* record;
1615       record = (RunTimeSharedClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
1616       record->init(info);
1617 
1618       unsigned int hash;
1619       Symbol* name = info._klass->name();
1620       if (DynamicDumpSharedSpaces) {
1621         name = DynamicArchive::original_to_target(name);
1622       }
1623       hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
1624       u4 delta;
1625       if (DynamicDumpSharedSpaces) {
1626         delta = MetaspaceShared::object_delta_u4(DynamicArchive::buffer_to_target(record));
1627       } else {
1628         delta = MetaspaceShared::object_delta_u4(record);
1629       }
1630       _writer->add(hash, delta);
1631       if (log_is_enabled(Trace, cds, hashtables)) {
1632         ResourceMark rm;
1633         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1634       }
1635 
1636       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeSharedClassInfo*
1637       RunTimeSharedClassInfo::set_for(info._klass, record);
1638     }
1639     return true; // keep on iterating
1640   }
1641 };
1642 
1643 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1644                                               bool is_builtin,
1645                                               bool is_static_archive) {
1646   CompactHashtableStats stats;
1647   dictionary->reset();
1648   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1649   CopySharedClassInfoToArchive copy(&writer, is_builtin, is_static_archive);
1650   _dumptime_table->iterate(&copy);
1651   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1652 }
1653 
1654 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1655   if (is_static_archive) {
1656     write_dictionary(&_builtin_dictionary, true);
1657     write_dictionary(&_unregistered_dictionary, false);
1658   } else {
1659     write_dictionary(&_dynamic_builtin_dictionary, true);
1660     write_dictionary(&_dynamic_unregistered_dictionary, false);
1661   }
1662 }
1663 
1664 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1665                                                           bool is_static_archive) {
1666   if (is_static_archive) {
1667     _builtin_dictionary.serialize_header(soc);
1668     _unregistered_dictionary.serialize_header(soc);
1669   } else {
1670     _dynamic_builtin_dictionary.serialize_header(soc);
1671     _dynamic_unregistered_dictionary.serialize_header(soc);
1672   }
1673 }
1674 
1675 void SystemDictionaryShared::serialize_well_known_klasses(SerializeClosure* soc) {
1676   for (int i = FIRST_WKID; i < WKID_LIMIT; i++) {
1677     soc->do_ptr((void**)&_well_known_klasses[i]);
1678   }
1679 }
1680 
1681 const RunTimeSharedClassInfo*
1682 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1683   if (!UseSharedSpaces || !name->is_shared()) {
1684     // The names of all shared classes must also be a shared Symbol.
1685     return NULL;
1686   }
1687 
1688   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
1689   const RunTimeSharedClassInfo* record = NULL;
1690   if (!MetaspaceShared::is_shared_dynamic(name)) {
1691     // The names of all shared classes in the static dict must also be in the
1692     // static archive
1693     record = static_dict->lookup(name, hash, 0);
1694   }
1695 
1696   if (record == NULL && DynamicArchive::is_mapped()) {
1697     record = dynamic_dict->lookup(name, hash, 0);
1698   }
1699 
1700   return record;
1701 }
1702 
1703 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1704   const RunTimeSharedClassInfo* record = find_record(&_builtin_dictionary, &_dynamic_builtin_dictionary, name);
1705   if (record != NULL) {
1706     return record->_klass;
1707   } else {
1708     return NULL;
1709   }
1710 }
1711 
1712 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1713   assert(DumpSharedSpaces, "supported only when dumping");
1714   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1715   info->_id = id;
1716 }
1717 
1718 class SharedDictionaryPrinter : StackObj {
1719   outputStream* _st;
1720   int _index;
1721 public:
1722   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1723 
1724   void do_value(const RunTimeSharedClassInfo* record) {
1725     ResourceMark rm;
1726     _st->print_cr("%4d:  %s", (_index++), record->_klass->external_name());
1727   }
1728 };
1729 
1730 void SystemDictionaryShared::print_on(outputStream* st) {
1731   if (UseSharedSpaces) {
1732     st->print_cr("Shared Dictionary");
1733     SharedDictionaryPrinter p(st);
1734     _builtin_dictionary.iterate(&p);
1735     _unregistered_dictionary.iterate(&p);
1736     if (DynamicArchive::is_mapped()) {
1737       _dynamic_builtin_dictionary.iterate(&p);
1738       _unregistered_dictionary.iterate(&p);
1739     }
1740   }
1741 }
1742 
1743 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1744   if (UseSharedSpaces) {
1745     _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1746     _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1747     if (DynamicArchive::is_mapped()) {
1748       _dynamic_builtin_dictionary.print_table_statistics(st, "Dynamic Builtin Shared Dictionary");
1749       _dynamic_unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1750     }
1751   }
1752 }
1753 
1754 bool SystemDictionaryShared::empty_dumptime_table() {
1755   if (_dumptime_table == NULL) {
1756     return true;
1757   }
1758   _dumptime_table->update_counts();
1759   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1760     return true;
1761   }
1762   return false;
1763 }
1764 
1765 #if INCLUDE_CDS_JAVA_HEAP
1766 
1767 class ArchivedMirrorPatcher {
1768   static void update(Klass* k) {
1769     if (k->has_raw_archived_mirror()) {
1770       oop m = HeapShared::materialize_archived_object(k->archived_java_mirror_raw_narrow());
1771       if (m != NULL) {
1772         java_lang_Class::update_archived_mirror_native_pointers(m);
1773       }
1774     }
1775   }
1776 
1777 public:
1778   static void update_array_klasses(Klass* ak) {
1779     while (ak != NULL) {
1780       update(ak);
1781       ak = ArrayKlass::cast(ak)->higher_dimension();
1782     }
1783   }
1784 
1785   void do_value(const RunTimeSharedClassInfo* info) {
1786     InstanceKlass* ik = info->_klass;
1787     update(ik);
1788     update_array_klasses(ik->array_klasses());
1789   }
1790 };
1791 
1792 void SystemDictionaryShared::update_archived_mirror_native_pointers_for(RunTimeSharedDictionary* dict) {
1793   ArchivedMirrorPatcher patcher;
1794   dict->iterate(&patcher);
1795 }
1796 
1797 void SystemDictionaryShared::update_archived_mirror_native_pointers() {
1798   if (!HeapShared::open_archive_heap_region_mapped()) {
1799     return;
1800   }
1801   if (MetaspaceShared::relocation_delta() == 0) {
1802     return;
1803   }
1804   update_archived_mirror_native_pointers_for(&_builtin_dictionary);
1805   update_archived_mirror_native_pointers_for(&_unregistered_dictionary);
1806 
1807   for (int t = T_BOOLEAN; t <= T_LONG; t++) {
1808     Klass* k = Universe::typeArrayKlassObj((BasicType)t);
1809     ArchivedMirrorPatcher::update_array_klasses(k);
1810   }
1811 }
1812 #endif