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 objArrayOop SystemDictionaryShared::_shared_protection_domains  =  NULL;
  65 objArrayOop SystemDictionaryShared::_shared_jar_urls            =  NULL;
  66 objArrayOop 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 _shared_protection_domains->obj_at(index);
 464 }
 465 
 466 oop SystemDictionaryShared::shared_jar_url(int index) {
 467   return _shared_jar_urls->obj_at(index);
 468 }
 469 
 470 oop SystemDictionaryShared::shared_jar_manifest(int index) {
 471   return _shared_jar_manifests->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::oops_do(OopClosure* f) {
 930   f->do_oop((oop*)&_shared_protection_domains);
 931   f->do_oop((oop*)&_shared_jar_urls);
 932   f->do_oop((oop*)&_shared_jar_manifests);
 933 }
 934 
 935 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) {
 936   if (_shared_protection_domains == NULL) {
 937     _shared_protection_domains = oopFactory::new_objArray(
 938         SystemDictionary::ProtectionDomain_klass(), size, CHECK);
 939   }
 940 }
 941 
 942 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) {
 943   if (_shared_jar_urls == NULL) {
 944     _shared_jar_urls = oopFactory::new_objArray(
 945         SystemDictionary::URL_klass(), size, CHECK);
 946   }
 947 }
 948 
 949 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) {
 950   if (_shared_jar_manifests == NULL) {
 951     _shared_jar_manifests = oopFactory::new_objArray(
 952         SystemDictionary::Jar_Manifest_klass(), size, CHECK);
 953   }
 954 }
 955 
 956 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) {
 957   allocate_shared_protection_domain_array(size, CHECK);
 958   allocate_shared_jar_url_array(size, CHECK);
 959   allocate_shared_jar_manifest_array(size, CHECK);
 960 }
 961 
 962 // This function is called for loading only UNREGISTERED classes
 963 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 964                                                           Handle class_loader,
 965                                                           Handle protection_domain,
 966                                                           const ClassFileStream* cfs,
 967                                                           TRAPS) {
 968   if (!UseSharedSpaces) {
 969     return NULL;
 970   }
 971   if (class_name == NULL) {  // don't do this for hidden and unsafe anonymous classes
 972     return NULL;
 973   }
 974   if (class_loader.is_null() ||
 975       SystemDictionary::is_system_class_loader(class_loader()) ||
 976       SystemDictionary::is_platform_class_loader(class_loader())) {
 977     // Do nothing for the BUILTIN loaders.
 978     return NULL;
 979   }
 980 
 981   const RunTimeSharedClassInfo* record = find_record(&_unregistered_dictionary, &_dynamic_unregistered_dictionary, class_name);
 982   if (record == NULL) {
 983     return NULL;
 984   }
 985 
 986   int clsfile_size  = cfs->length();
 987   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 988 
 989   if (!record->matches(clsfile_size, clsfile_crc32)) {
 990     return NULL;
 991   }
 992 
 993   return acquire_class_for_current_thread(record->_klass, class_loader,
 994                                           protection_domain, cfs,
 995                                           THREAD);
 996 }
 997 
 998 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 999                    InstanceKlass *ik,
1000                    Handle class_loader,
1001                    Handle protection_domain,
1002                    const ClassFileStream *cfs,
1003                    TRAPS) {
1004   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1005 
1006   {
1007     MutexLocker mu(THREAD, SharedDictionary_lock);
1008     if (ik->class_loader_data() != NULL) {
1009       //    ik is already loaded (by this loader or by a different loader)
1010       // or ik is being loaded by a different thread (by this loader or by a different loader)
1011       return NULL;
1012     }
1013 
1014     // No other thread has acquired this yet, so give it to *this thread*
1015     ik->set_class_loader_data(loader_data);
1016   }
1017 
1018   // No longer holding SharedDictionary_lock
1019   // No need to lock, as <ik> can be held only by a single thread.
1020   loader_data->add_class(ik);
1021 
1022   // Get the package entry.
1023   PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, ik->name());
1024 
1025   // Load and check super/interfaces, restore unsharable info
1026   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
1027                                                   cfs, pkg_entry, THREAD);
1028   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
1029     // TODO: clean up <ik> so it can be used again
1030     return NULL;
1031   }
1032 
1033   return shared_klass;
1034 }
1035 
1036 static ResourceHashtable<
1037   Symbol*, bool,
1038   primitive_hash<Symbol*>,
1039   primitive_equals<Symbol*>,
1040   6661,                             // prime number
1041   ResourceObj::C_HEAP> _loaded_unregistered_classes;
1042 
1043 bool SystemDictionaryShared::add_unregistered_class(InstanceKlass* k, TRAPS) {
1044   // We don't allow duplicated unregistered classes of the same name.
1045   assert(DumpSharedSpaces, "only when dumping");
1046   Symbol* name = k->name();
1047   bool created = false;
1048   _loaded_unregistered_classes.put_if_absent(name, true, &created);
1049   if (created) {
1050     MutexLocker mu_r(THREAD, Compile_lock); // add_to_hierarchy asserts this.
1051     SystemDictionary::add_to_hierarchy(k, CHECK_false);
1052   }
1053   return created;
1054 }
1055 
1056 // This function is called to resolve the super/interfaces of shared classes for
1057 // non-built-in loaders. E.g., ChildClass in the below example
1058 // where "super:" (and optionally "interface:") have been specified.
1059 //
1060 // java/lang/Object id: 0
1061 // Interface   id: 2 super: 0 source: cust.jar
1062 // ChildClass  id: 4 super: 0 interfaces: 2 source: cust.jar
1063 InstanceKlass* SystemDictionaryShared::dump_time_resolve_super_or_fail(
1064     Symbol* child_name, Symbol* class_name, Handle class_loader,
1065     Handle protection_domain, bool is_superclass, TRAPS) {
1066 
1067   assert(DumpSharedSpaces, "only when dumping");
1068 
1069   ClassListParser* parser = ClassListParser::instance();
1070   if (parser == NULL) {
1071     // We're still loading the well-known classes, before the ClassListParser is created.
1072     return NULL;
1073   }
1074   if (child_name->equals(parser->current_class_name())) {
1075     // When this function is called, all the numbered super and interface types
1076     // must have already been loaded. Hence this function is never recursively called.
1077     if (is_superclass) {
1078       return parser->lookup_super_for_current_class(class_name);
1079     } else {
1080       return parser->lookup_interface_for_current_class(class_name);
1081     }
1082   } else {
1083     // The VM is not trying to resolve a super type of parser->current_class_name().
1084     // Instead, it's resolving an error class (because parser->current_class_name() has
1085     // failed parsing or verification). Don't do anything here.
1086     return NULL;
1087   }
1088 }
1089 
1090 DumpTimeSharedClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) {
1091   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1092   if (_dumptime_table == NULL) {
1093     _dumptime_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeSharedClassTable();
1094   }
1095   return _dumptime_table->find_or_allocate_info_for(k);
1096 }
1097 
1098 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
1099   Arguments::assert_is_dumping_archive();
1100   assert(!is_builtin(k), "must be unregistered class");
1101   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1102   info->_clsfile_size  = cfs->length();
1103   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
1104 }
1105 
1106 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
1107   (void)find_or_allocate_info_for(k);
1108 }
1109 
1110 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
1111   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1112   DumpTimeSharedClassInfo* p = _dumptime_table->get(k);
1113   if (p == NULL) {
1114     return;
1115   }
1116   if (p->_verifier_constraints != NULL) {
1117     for (int i = 0; i < p->_verifier_constraints->length(); i++) {
1118       DumpTimeSharedClassInfo::DTVerifierConstraint constraint = p->_verifier_constraints->at(i);
1119       if (constraint._name != NULL ) {
1120         constraint._name->decrement_refcount();
1121       }
1122       if (constraint._from_name != NULL ) {
1123         constraint._from_name->decrement_refcount();
1124       }
1125     }
1126     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTVerifierConstraint, p->_verifier_constraints);
1127     p->_verifier_constraints = NULL;
1128     FREE_C_HEAP_ARRAY(char, p->_verifier_constraint_flags);
1129     p->_verifier_constraint_flags = NULL;
1130   }
1131   if (p->_loader_constraints != NULL) {
1132     for (int i = 0; i < p->_loader_constraints->length(); i++) {
1133       DumpTimeSharedClassInfo::DTLoaderConstraint ld =  p->_loader_constraints->at(i);
1134       if (ld._name != NULL) {
1135         ld._name->decrement_refcount();
1136       }
1137     }
1138     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTLoaderConstraint, p->_loader_constraints);
1139     p->_loader_constraints = NULL;
1140   }
1141   _dumptime_table->remove(k);
1142 }
1143 
1144 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
1145   while (k) {
1146     if (k->name()->equals("jdk/internal/event/Event")) {
1147       return true;
1148     }
1149     k = k->java_super();
1150   }
1151   return false;
1152 }
1153 
1154 void SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
1155   ResourceMark rm;
1156   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
1157 }
1158 
1159 bool SystemDictionaryShared::should_be_excluded(InstanceKlass* k) {
1160   if (k->is_hidden() || k->is_unsafe_anonymous()) {
1161     warn_excluded(k, "Hidden or Unsafe anonymous class");
1162     return true; // hidden and unsafe anonymous classes are not archived, skip
1163   }
1164   if (k->is_in_error_state()) {
1165     warn_excluded(k, "In error state");
1166     return true;
1167   }
1168   if (k->has_been_redefined()) {
1169     warn_excluded(k, "Has been redefined");
1170     return true;
1171   }
1172   if (k->shared_classpath_index() < 0 && is_builtin(k)) {
1173     // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
1174     // agent during dump time).
1175     warn_excluded(k, "Unsupported location");
1176     return true;
1177   }
1178   if (k->signers() != NULL) {
1179     // We cannot include signed classes in the archive because the certificates
1180     // used during dump time may be different than those used during
1181     // runtime (due to expiration, etc).
1182     warn_excluded(k, "Signed JAR");
1183     return true;
1184   }
1185   if (is_jfr_event_class(k)) {
1186     // We cannot include JFR event classes because they need runtime-specific
1187     // instrumentation in order to work with -XX:FlightRecorderOptions=retransform=false.
1188     // There are only a small number of these classes, so it's not worthwhile to
1189     // support them and make CDS more complicated.
1190     warn_excluded(k, "JFR event class");
1191     return true;
1192   }
1193   if (k->init_state() < InstanceKlass::linked) {
1194     // In CDS dumping, we will attempt to link all classes. Those that fail to link will
1195     // be recorded in DumpTimeSharedClassInfo.
1196     Arguments::assert_is_dumping_archive();
1197 
1198     // TODO -- rethink how this can be handled.
1199     // We should try to link ik, however, we can't do it here because
1200     // 1. We are at VM exit
1201     // 2. linking a class may cause other classes to be loaded, which means
1202     //    a custom ClassLoader.loadClass() may be called, at a point where the
1203     //    class loader doesn't expect it.
1204     if (has_class_failed_verification(k)) {
1205       warn_excluded(k, "Failed verification");
1206     } else {
1207       warn_excluded(k, "Not linked");
1208     }
1209     return true;
1210   }
1211   if (k->major_version() < 50 /*JAVA_6_VERSION*/) {
1212     ResourceMark rm;
1213     log_warning(cds)("Pre JDK 6 class not supported by CDS: %u.%u %s",
1214                      k->major_version(),  k->minor_version(), k->name()->as_C_string());
1215     return true;
1216   }
1217 
1218   InstanceKlass* super = k->java_super();
1219   if (super != NULL && should_be_excluded(super)) {
1220     ResourceMark rm;
1221     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
1222     return true;
1223   }
1224 
1225   Array<InstanceKlass*>* interfaces = k->local_interfaces();
1226   int len = interfaces->length();
1227   for (int i = 0; i < len; i++) {
1228     InstanceKlass* intf = interfaces->at(i);
1229     if (should_be_excluded(intf)) {
1230       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
1231       return true;
1232     }
1233   }
1234 
1235   return false;
1236 }
1237 
1238 // k is a class before relocating by ArchiveCompactor
1239 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
1240   ResourceMark rm;
1241   const char* name = k->name()->as_C_string();
1242   DumpTimeSharedClassInfo* info = _dumptime_table->get(k);
1243   assert(_no_class_loading_should_happen, "class loading must be disabled");
1244   guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name);
1245   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
1246   if (is_builtin(k)) {
1247     guarantee(!k->is_shared_unregistered_class(),
1248               "Class loader type must be set for BUILTIN class %s", name);
1249   } else {
1250     guarantee(k->is_shared_unregistered_class(),
1251               "Class loader type must not be set for UNREGISTERED class %s", name);
1252   }
1253 }
1254 
1255 class ExcludeDumpTimeSharedClasses : StackObj {
1256 public:
1257   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1258     if (SystemDictionaryShared::should_be_excluded(k)) {
1259       info.set_excluded();
1260     }
1261     return true; // keep on iterating
1262   }
1263 };
1264 
1265 void SystemDictionaryShared::check_excluded_classes() {
1266   ExcludeDumpTimeSharedClasses excl;
1267   _dumptime_table->iterate(&excl);
1268   _dumptime_table->update_counts();
1269 }
1270 
1271 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
1272   assert(_no_class_loading_should_happen, "sanity");
1273   Arguments::assert_is_dumping_archive();
1274   return find_or_allocate_info_for(k)->is_excluded();
1275 }
1276 
1277 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
1278   Arguments::assert_is_dumping_archive();
1279   find_or_allocate_info_for(ik)->set_failed_verification();
1280 }
1281 
1282 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
1283   Arguments::assert_is_dumping_archive();
1284   if (_dumptime_table == NULL) {
1285     assert(DynamicDumpSharedSpaces, "sanity");
1286     assert(ik->is_shared(), "must be a shared class in the static archive");
1287     return false;
1288   }
1289   DumpTimeSharedClassInfo* p = _dumptime_table->get(ik);
1290   return (p == NULL) ? false : p->failed_verification();
1291 }
1292 
1293 class IterateDumpTimeSharedClassTable : StackObj {
1294   MetaspaceClosure *_it;
1295 public:
1296   IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {}
1297 
1298   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1299     if (!info.is_excluded()) {
1300       info.metaspace_pointers_do(_it);
1301     }
1302     return true; // keep on iterating
1303   }
1304 };
1305 
1306 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
1307   IterateDumpTimeSharedClassTable iter(it);
1308   _dumptime_table->iterate(&iter);
1309 }
1310 
1311 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1312          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1313   Arguments::assert_is_dumping_archive();
1314   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1315   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
1316                                     from_is_array, from_is_object);
1317 
1318   if (DynamicDumpSharedSpaces) {
1319     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
1320     // the initial run prior to creating the archive before vm exit. We will also perform verification
1321     // check when running with the archive.
1322     return false;
1323   } else {
1324     if (is_builtin(k)) {
1325       // For builtin class loaders, we can try to complete the verification check at dump time,
1326       // because we can resolve all the constraint classes. We will also perform verification check
1327       // when running with the archive.
1328       return false;
1329     } else {
1330       // For non-builtin class loaders, we cannot complete the verification check at dump time,
1331       // because at dump time we don't know how to resolve classes for such loaders.
1332       return true;
1333     }
1334   }
1335 }
1336 
1337 void DumpTimeSharedClassInfo::add_verification_constraint(InstanceKlass* k, Symbol* name,
1338          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1339   if (_verifier_constraints == NULL) {
1340     _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<DTVerifierConstraint>(4, true, mtClass);
1341   }
1342   if (_verifier_constraint_flags == NULL) {
1343     _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, true, mtClass);
1344   }
1345   GrowableArray<DTVerifierConstraint>* vc_array = _verifier_constraints;
1346   for (int i = 0; i < vc_array->length(); i++) {
1347     DTVerifierConstraint* p = vc_array->adr_at(i);
1348     if (name == p->_name && from_name == p->_from_name) {
1349       return;
1350     }
1351   }
1352   DTVerifierConstraint cons(name, from_name);
1353   vc_array->append(cons);
1354 
1355   GrowableArray<char>* vcflags_array = _verifier_constraint_flags;
1356   char c = 0;
1357   c |= from_field_is_protected ? SystemDictionaryShared::FROM_FIELD_IS_PROTECTED : 0;
1358   c |= from_is_array           ? SystemDictionaryShared::FROM_IS_ARRAY           : 0;
1359   c |= from_is_object          ? SystemDictionaryShared::FROM_IS_OBJECT          : 0;
1360   vcflags_array->append(c);
1361 
1362   if (log_is_enabled(Trace, cds, verification)) {
1363     ResourceMark rm;
1364     log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1365                                  k->external_name(), from_name->as_klass_external_name(),
1366                                  name->as_klass_external_name(), c);
1367   }
1368 }
1369 
1370 static char get_loader_type_by(oop  loader) {
1371   assert(SystemDictionary::is_builtin_class_loader(loader), "Must be built-in loader");
1372   if (SystemDictionary::is_boot_class_loader(loader)) {
1373     return (char)ClassLoader::BOOT_LOADER;
1374   } else if (SystemDictionary::is_platform_class_loader(loader)) {
1375     return (char)ClassLoader::PLATFORM_LOADER;
1376   } else {
1377     assert(SystemDictionary::is_system_class_loader(loader), "Class loader mismatch");
1378     return (char)ClassLoader::APP_LOADER;
1379   }
1380 }
1381 
1382 static oop get_class_loader_by(char type) {
1383   if (type == (char)ClassLoader::BOOT_LOADER) {
1384     return (oop)NULL;
1385   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1386     return SystemDictionary::java_platform_loader();
1387   } else {
1388     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1389     return SystemDictionary::java_system_loader();
1390   }
1391 }
1392 
1393 void DumpTimeSharedClassInfo::record_linking_constraint(Symbol* name, Handle loader1, Handle loader2) {
1394   assert(loader1 != loader2, "sanity");
1395   LogTarget(Info, class, loader, constraints) log;
1396   if (_loader_constraints == NULL) {
1397     _loader_constraints = new (ResourceObj::C_HEAP, mtClass) GrowableArray<DTLoaderConstraint>(4, true, mtClass);
1398   }
1399   char lt1 = get_loader_type_by(loader1());
1400   char lt2 = get_loader_type_by(loader2());
1401   DTLoaderConstraint lc(name, lt1, lt2);
1402   for (int i = 0; i < _loader_constraints->length(); i++) {
1403     DTLoaderConstraint dt = _loader_constraints->at(i);
1404     if (lc.equals(dt)) {
1405       if (log.is_enabled()) {
1406         ResourceMark rm;
1407         // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1408         log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s already added]",
1409                   _klass->external_name(), name->as_C_string(),
1410                   ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1411                   ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1412       }
1413       return;
1414     }
1415   }
1416   _loader_constraints->append(lc);
1417   if (log.is_enabled()) {
1418     ResourceMark rm;
1419     // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1420     log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s total %d]",
1421               _klass->external_name(), name->as_C_string(),
1422               ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1423               ClassLoaderData::class_loader_data(loader2())->loader_name_and_id(),
1424               _loader_constraints->length());
1425   }
1426 }
1427 
1428 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1429                                                             TRAPS) {
1430   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1431   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(klass);
1432 
1433   int length = record->_num_verifier_constraints;
1434   if (length > 0) {
1435     for (int i = 0; i < length; i++) {
1436       RunTimeSharedClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1437       Symbol* name      = vc->name();
1438       Symbol* from_name = vc->from_name();
1439       char c            = record->verifier_constraint_flag(i);
1440 
1441       if (log_is_enabled(Trace, cds, verification)) {
1442         ResourceMark rm(THREAD);
1443         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1444                                      klass->external_name(), from_name->as_klass_external_name(),
1445                                      name->as_klass_external_name(), c);
1446       }
1447 
1448       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
1449       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
1450       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
1451 
1452       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
1453          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
1454       if (!ok) {
1455         ResourceMark rm(THREAD);
1456         stringStream ss;
1457 
1458         ss.print_cr("Bad type on operand stack");
1459         ss.print_cr("Exception Details:");
1460         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1461         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1462                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1463         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1464       }
1465     }
1466   }
1467 }
1468 
1469 // Record class loader constraints that are checked inside
1470 // InstanceKlass::link_class(), so that these can be checked quickly
1471 // at runtime without laying out the vtable/itables.
1472 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1473                                                     Handle loader1, Handle loader2, TRAPS) {
1474   // A linking constraint check is executed when:
1475   //   - klass extends or implements type S
1476   //   - klass overrides method S.M(...) with X.M
1477   //     - If klass defines the method M, X is
1478   //       the same as klass.
1479   //     - If klass does not define the method M,
1480   //       X must be a supertype of klass and X.M is
1481   //       a default method defined by X.
1482   //   - loader1 = X->class_loader()
1483   //   - loader2 = S->class_loader()
1484   //   - loader1 != loader2
1485   //   - M's paramater(s) include an object type T
1486   // We require that
1487   //   - whenever loader1 and loader2 try to
1488   //     resolve the type T, they must always resolve to
1489   //     the same InstanceKlass.
1490   // NOTE: type T may or may not be currently resolved in
1491   // either of these two loaders. The check itself does not
1492   // try to resolve T.
1493   oop klass_loader = klass->class_loader();
1494   assert(klass_loader != NULL, "should not be called for boot loader");
1495   assert(loader1 != loader2, "must be");
1496 
1497   if (!is_system_class_loader(klass_loader) &&
1498       !is_platform_class_loader(klass_loader)) {
1499     // If klass is loaded by system/platform loaders, we can
1500     // guarantee that klass and S must be loaded by the same
1501     // respective loader between dump time and run time, and
1502     // the exact same check on (name, loader1, loader2) will
1503     // be executed. Hence, we can cache this check and execute
1504     // it at runtime without walking the vtable/itables.
1505     //
1506     // This cannot be guaranteed for classes loaded by other
1507     // loaders, so we bail.
1508     return;
1509   }
1510 
1511   if (THREAD->is_VM_thread()) {
1512     assert(DynamicDumpSharedSpaces, "must be");
1513     // We are re-laying out the vtable/itables of the *copy* of
1514     // a class during the final stage of dynamic dumping. The
1515     // linking constraints for this class has already been recorded.
1516     return;
1517   }
1518   Arguments::assert_is_dumping_archive();
1519   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(klass);
1520   info->record_linking_constraint(name, loader1, loader2);
1521 }
1522 
1523 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1524 // the purpose of checking class loader constraints.
1525 bool SystemDictionaryShared::check_linking_constraints(InstanceKlass* klass, TRAPS) {
1526   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1527   LogTarget(Info, class, loader, constraints) log;
1528   if (klass->is_shared_boot_class()) {
1529     // No class loader constraint check performed for boot classes.
1530     return true;
1531   }
1532   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1533     RunTimeSharedClassInfo* info = RunTimeSharedClassInfo::get_for(klass);
1534     assert(info != NULL, "Sanity");
1535     if (info->_num_loader_constraints > 0) {
1536       HandleMark hm;
1537       for (int i = 0; i < info->_num_loader_constraints; i++) {
1538         RunTimeSharedClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1539         Symbol* name = lc->constraint_name();
1540         Handle loader1(THREAD, get_class_loader_by(lc->_loader_type1));
1541         Handle loader2(THREAD, get_class_loader_by(lc->_loader_type2));
1542         if (log.is_enabled()) {
1543           ResourceMark rm(THREAD);
1544           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1545                     klass->external_name(), name->as_C_string(),
1546                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1547                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1548         }
1549         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2, THREAD)) {
1550           // Loader constraint violation has been found. The caller
1551           // will re-layout the vtable/itables to produce the correct
1552           // exception.
1553           if (log.is_enabled()) {
1554             log.print(" failed]");
1555           }
1556           return false;
1557         }
1558         if (log.is_enabled()) {
1559             log.print(" succeeded]");
1560         }
1561       }
1562       return true; // for all recorded constraints added successully.
1563     }
1564   }
1565   if (log.is_enabled()) {
1566     ResourceMark rm(THREAD);
1567     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1568   }
1569   return false;
1570 }
1571 
1572 class EstimateSizeForArchive : StackObj {
1573   size_t _shared_class_info_size;
1574   int _num_builtin_klasses;
1575   int _num_unregistered_klasses;
1576 
1577 public:
1578   EstimateSizeForArchive() {
1579     _shared_class_info_size = 0;
1580     _num_builtin_klasses = 0;
1581     _num_unregistered_klasses = 0;
1582   }
1583 
1584   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1585     if (!info.is_excluded()) {
1586       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
1587       _shared_class_info_size += align_up(byte_size, BytesPerWord);
1588     }
1589     return true; // keep on iterating
1590   }
1591 
1592   size_t total() {
1593     return _shared_class_info_size;
1594   }
1595 };
1596 
1597 size_t SystemDictionaryShared::estimate_size_for_archive() {
1598   EstimateSizeForArchive est;
1599   _dumptime_table->iterate(&est);
1600   return est.total() +
1601     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1602     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1603 }
1604 
1605 class CopySharedClassInfoToArchive : StackObj {
1606   CompactHashtableWriter* _writer;
1607   bool _is_builtin;
1608 public:
1609   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1610                                bool is_builtin,
1611                                bool is_static_archive)
1612     : _writer(writer), _is_builtin(is_builtin) {}
1613 
1614   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1615     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1616       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
1617       RunTimeSharedClassInfo* record;
1618       record = (RunTimeSharedClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
1619       record->init(info);
1620 
1621       unsigned int hash;
1622       Symbol* name = info._klass->name();
1623       if (DynamicDumpSharedSpaces) {
1624         name = DynamicArchive::original_to_target(name);
1625       }
1626       hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
1627       u4 delta;
1628       if (DynamicDumpSharedSpaces) {
1629         delta = MetaspaceShared::object_delta_u4(DynamicArchive::buffer_to_target(record));
1630       } else {
1631         delta = MetaspaceShared::object_delta_u4(record);
1632       }
1633       _writer->add(hash, delta);
1634       if (log_is_enabled(Trace, cds, hashtables)) {
1635         ResourceMark rm;
1636         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1637       }
1638 
1639       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeSharedClassInfo*
1640       RunTimeSharedClassInfo::set_for(info._klass, record);
1641     }
1642     return true; // keep on iterating
1643   }
1644 };
1645 
1646 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1647                                               bool is_builtin,
1648                                               bool is_static_archive) {
1649   CompactHashtableStats stats;
1650   dictionary->reset();
1651   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1652   CopySharedClassInfoToArchive copy(&writer, is_builtin, is_static_archive);
1653   _dumptime_table->iterate(&copy);
1654   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1655 }
1656 
1657 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1658   if (is_static_archive) {
1659     write_dictionary(&_builtin_dictionary, true);
1660     write_dictionary(&_unregistered_dictionary, false);
1661   } else {
1662     write_dictionary(&_dynamic_builtin_dictionary, true);
1663     write_dictionary(&_dynamic_unregistered_dictionary, false);
1664   }
1665 }
1666 
1667 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1668                                                           bool is_static_archive) {
1669   if (is_static_archive) {
1670     _builtin_dictionary.serialize_header(soc);
1671     _unregistered_dictionary.serialize_header(soc);
1672   } else {
1673     _dynamic_builtin_dictionary.serialize_header(soc);
1674     _dynamic_unregistered_dictionary.serialize_header(soc);
1675   }
1676 }
1677 
1678 void SystemDictionaryShared::serialize_well_known_klasses(SerializeClosure* soc) {
1679   for (int i = FIRST_WKID; i < WKID_LIMIT; i++) {
1680     soc->do_ptr((void**)&_well_known_klasses[i]);
1681   }
1682 }
1683 
1684 const RunTimeSharedClassInfo*
1685 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1686   if (!UseSharedSpaces || !name->is_shared()) {
1687     // The names of all shared classes must also be a shared Symbol.
1688     return NULL;
1689   }
1690 
1691   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
1692   const RunTimeSharedClassInfo* record = NULL;
1693   if (!MetaspaceShared::is_shared_dynamic(name)) {
1694     // The names of all shared classes in the static dict must also be in the
1695     // static archive
1696     record = static_dict->lookup(name, hash, 0);
1697   }
1698 
1699   if (record == NULL && DynamicArchive::is_mapped()) {
1700     record = dynamic_dict->lookup(name, hash, 0);
1701   }
1702 
1703   return record;
1704 }
1705 
1706 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1707   const RunTimeSharedClassInfo* record = find_record(&_builtin_dictionary, &_dynamic_builtin_dictionary, name);
1708   if (record != NULL) {
1709     return record->_klass;
1710   } else {
1711     return NULL;
1712   }
1713 }
1714 
1715 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1716   assert(DumpSharedSpaces, "supported only when dumping");
1717   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1718   info->_id = id;
1719 }
1720 
1721 class SharedDictionaryPrinter : StackObj {
1722   outputStream* _st;
1723   int _index;
1724 public:
1725   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1726 
1727   void do_value(const RunTimeSharedClassInfo* record) {
1728     ResourceMark rm;
1729     _st->print_cr("%4d:  %s", (_index++), record->_klass->external_name());
1730   }
1731 };
1732 
1733 void SystemDictionaryShared::print_on(outputStream* st) {
1734   if (UseSharedSpaces) {
1735     st->print_cr("Shared Dictionary");
1736     SharedDictionaryPrinter p(st);
1737     _builtin_dictionary.iterate(&p);
1738     _unregistered_dictionary.iterate(&p);
1739     if (DynamicArchive::is_mapped()) {
1740       _dynamic_builtin_dictionary.iterate(&p);
1741       _unregistered_dictionary.iterate(&p);
1742     }
1743   }
1744 }
1745 
1746 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1747   if (UseSharedSpaces) {
1748     _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1749     _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1750     if (DynamicArchive::is_mapped()) {
1751       _dynamic_builtin_dictionary.print_table_statistics(st, "Dynamic Builtin Shared Dictionary");
1752       _dynamic_unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1753     }
1754   }
1755 }
1756 
1757 bool SystemDictionaryShared::empty_dumptime_table() {
1758   if (_dumptime_table == NULL) {
1759     return true;
1760   }
1761   _dumptime_table->update_counts();
1762   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1763     return true;
1764   }
1765   return false;
1766 }
1767 
1768 #if INCLUDE_CDS_JAVA_HEAP
1769 
1770 class ArchivedMirrorPatcher {
1771   static void update(Klass* k) {
1772     if (k->has_raw_archived_mirror()) {
1773       oop m = HeapShared::materialize_archived_object(k->archived_java_mirror_raw_narrow());
1774       if (m != NULL) {
1775         java_lang_Class::update_archived_mirror_native_pointers(m);
1776       }
1777     }
1778   }
1779 
1780 public:
1781   static void update_array_klasses(Klass* ak) {
1782     while (ak != NULL) {
1783       update(ak);
1784       ak = ArrayKlass::cast(ak)->higher_dimension();
1785     }
1786   }
1787 
1788   void do_value(const RunTimeSharedClassInfo* info) {
1789     InstanceKlass* ik = info->_klass;
1790     update(ik);
1791     update_array_klasses(ik->array_klasses());
1792   }
1793 };
1794 
1795 void SystemDictionaryShared::update_archived_mirror_native_pointers_for(RunTimeSharedDictionary* dict) {
1796   ArchivedMirrorPatcher patcher;
1797   dict->iterate(&patcher);
1798 }
1799 
1800 void SystemDictionaryShared::update_archived_mirror_native_pointers() {
1801   if (!HeapShared::open_archive_heap_region_mapped()) {
1802     return;
1803   }
1804   if (MetaspaceShared::relocation_delta() == 0) {
1805     return;
1806   }
1807   update_archived_mirror_native_pointers_for(&_builtin_dictionary);
1808   update_archived_mirror_native_pointers_for(&_unregistered_dictionary);
1809 
1810   for (int t = T_BOOLEAN; t <= T_LONG; t++) {
1811     Klass* k = Universe::typeArrayKlassObj((BasicType)t);
1812     ArchivedMirrorPatcher::update_array_klasses(k);
1813   }
1814 }
1815 #endif