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