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