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 objArrayOop SystemDictionaryShared::_shared_protection_domains  =  NULL;
  66 objArrayOop SystemDictionaryShared::_shared_jar_urls            =  NULL;
  67 objArrayOop 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 _shared_protection_domains->obj_at(index);
 652 }
 653 
 654 oop SystemDictionaryShared::shared_jar_url(int index) {
 655   return _shared_jar_urls->obj_at(index);
 656 }
 657 
 658 oop SystemDictionaryShared::shared_jar_manifest(int index) {
 659   return _shared_jar_manifests->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::oops_do(OopClosure* f) {
1118   f->do_oop((oop*)&_shared_protection_domains);
1119   f->do_oop((oop*)&_shared_jar_urls);
1120   f->do_oop((oop*)&_shared_jar_manifests);
1121 }
1122 
1123 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) {
1124   if (_shared_protection_domains == NULL) {
1125     _shared_protection_domains = oopFactory::new_objArray(
1126         SystemDictionary::ProtectionDomain_klass(), size, CHECK);
1127   }
1128 }
1129 
1130 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) {
1131   if (_shared_jar_urls == NULL) {
1132     _shared_jar_urls = oopFactory::new_objArray(
1133         SystemDictionary::URL_klass(), size, CHECK);
1134   }
1135 }
1136 
1137 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) {
1138   if (_shared_jar_manifests == NULL) {
1139     _shared_jar_manifests = oopFactory::new_objArray(
1140         SystemDictionary::Jar_Manifest_klass(), size, CHECK);
1141   }
1142 }
1143 
1144 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) {
1145   allocate_shared_protection_domain_array(size, CHECK);
1146   allocate_shared_jar_url_array(size, CHECK);
1147   allocate_shared_jar_manifest_array(size, CHECK);
1148 }
1149 
1150 // This function is called for loading only UNREGISTERED classes
1151 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
1152                                                           Handle class_loader,
1153                                                           Handle protection_domain,
1154                                                           const ClassFileStream* cfs,
1155                                                           TRAPS) {
1156   if (!UseSharedSpaces) {
1157     return NULL;
1158   }
1159   if (class_name == NULL) {  // don't do this for hidden and unsafe anonymous classes
1160     return NULL;
1161   }
1162   if (class_loader.is_null() ||
1163       SystemDictionary::is_system_class_loader(class_loader()) ||
1164       SystemDictionary::is_platform_class_loader(class_loader())) {
1165     // Do nothing for the BUILTIN loaders.
1166     return NULL;
1167   }
1168 
1169   const RunTimeSharedClassInfo* record = find_record(&_unregistered_dictionary, &_dynamic_unregistered_dictionary, class_name);
1170   if (record == NULL) {
1171     return NULL;
1172   }
1173 
1174   int clsfile_size  = cfs->length();
1175   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
1176 
1177   if (!record->matches(clsfile_size, clsfile_crc32)) {
1178     return NULL;
1179   }
1180 
1181   return acquire_class_for_current_thread(record->_klass, class_loader,
1182                                           protection_domain, cfs,
1183                                           THREAD);
1184 }
1185 
1186 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
1187                    InstanceKlass *ik,
1188                    Handle class_loader,
1189                    Handle protection_domain,
1190                    const ClassFileStream *cfs,
1191                    TRAPS) {
1192   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1193 
1194   {
1195     MutexLocker mu(THREAD, SharedDictionary_lock);
1196     if (ik->class_loader_data() != NULL) {
1197       //    ik is already loaded (by this loader or by a different loader)
1198       // or ik is being loaded by a different thread (by this loader or by a different loader)
1199       return NULL;
1200     }
1201 
1202     // No other thread has acquired this yet, so give it to *this thread*
1203     ik->set_class_loader_data(loader_data);
1204   }
1205 
1206   // No longer holding SharedDictionary_lock
1207   // No need to lock, as <ik> can be held only by a single thread.
1208   loader_data->add_class(ik);
1209 
1210   // Get the package entry.
1211   PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, ik->name());
1212 
1213   // Load and check super/interfaces, restore unsharable info
1214   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
1215                                                   cfs, pkg_entry, THREAD);
1216   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
1217     // TODO: clean up <ik> so it can be used again
1218     return NULL;
1219   }
1220 
1221   return shared_klass;
1222 }
1223 
1224 static ResourceHashtable<
1225   Symbol*, bool,
1226   primitive_hash<Symbol*>,
1227   primitive_equals<Symbol*>,
1228   6661,                             // prime number
1229   ResourceObj::C_HEAP> _loaded_unregistered_classes;
1230 
1231 bool SystemDictionaryShared::add_unregistered_class(InstanceKlass* k, TRAPS) {
1232   // We don't allow duplicated unregistered classes of the same name.
1233   assert(DumpSharedSpaces, "only when dumping");
1234   Symbol* name = k->name();
1235   bool created = false;
1236   _loaded_unregistered_classes.put_if_absent(name, true, &created);
1237   if (created) {
1238     MutexLocker mu_r(THREAD, Compile_lock); // add_to_hierarchy asserts this.
1239     SystemDictionary::add_to_hierarchy(k, CHECK_false);
1240   }
1241   return created;
1242 }
1243 
1244 // This function is called to resolve the super/interfaces of shared classes for
1245 // non-built-in loaders. E.g., ChildClass in the below example
1246 // where "super:" (and optionally "interface:") have been specified.
1247 //
1248 // java/lang/Object id: 0
1249 // Interface   id: 2 super: 0 source: cust.jar
1250 // ChildClass  id: 4 super: 0 interfaces: 2 source: cust.jar
1251 InstanceKlass* SystemDictionaryShared::dump_time_resolve_super_or_fail(
1252     Symbol* child_name, Symbol* class_name, Handle class_loader,
1253     Handle protection_domain, bool is_superclass, TRAPS) {
1254 
1255   assert(DumpSharedSpaces, "only when dumping");
1256 
1257   ClassListParser* parser = ClassListParser::instance();
1258   if (parser == NULL) {
1259     // We're still loading the well-known classes, before the ClassListParser is created.
1260     return NULL;
1261   }
1262   if (child_name->equals(parser->current_class_name())) {
1263     // When this function is called, all the numbered super and interface types
1264     // must have already been loaded. Hence this function is never recursively called.
1265     if (is_superclass) {
1266       return parser->lookup_super_for_current_class(class_name);
1267     } else {
1268       return parser->lookup_interface_for_current_class(class_name);
1269     }
1270   } else {
1271     // The VM is not trying to resolve a super type of parser->current_class_name().
1272     // Instead, it's resolving an error class (because parser->current_class_name() has
1273     // failed parsing or verification). Don't do anything here.
1274     return NULL;
1275   }
1276 }
1277 
1278 DumpTimeSharedClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) {
1279   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1280   if (_dumptime_table == NULL) {
1281     _dumptime_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeSharedClassTable();
1282   }
1283   return _dumptime_table->find_or_allocate_info_for(k);
1284 }
1285 
1286 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
1287   Arguments::assert_is_dumping_archive();
1288   assert(!is_builtin(k), "must be unregistered class");
1289   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1290   info->_clsfile_size  = cfs->length();
1291   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
1292 }
1293 
1294 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
1295   (void)find_or_allocate_info_for(k);
1296 }
1297 
1298 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
1299   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1300   DumpTimeSharedClassInfo* p = _dumptime_table->get(k);
1301   if (p == NULL) {
1302     return;
1303   }
1304   if (p->_verifier_constraints != NULL) {
1305     for (int i = 0; i < p->_verifier_constraints->length(); i++) {
1306       DumpTimeSharedClassInfo::DTVerifierConstraint constraint = p->_verifier_constraints->at(i);
1307       if (constraint._name != NULL ) {
1308         constraint._name->decrement_refcount();
1309       }
1310       if (constraint._from_name != NULL ) {
1311         constraint._from_name->decrement_refcount();
1312       }
1313     }
1314     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTVerifierConstraint, p->_verifier_constraints);
1315     p->_verifier_constraints = NULL;
1316     FREE_C_HEAP_ARRAY(char, p->_verifier_constraint_flags);
1317     p->_verifier_constraint_flags = NULL;
1318   }
1319   if (p->_loader_constraints != NULL) {
1320     for (int i = 0; i < p->_loader_constraints->length(); i++) {
1321       DumpTimeSharedClassInfo::DTLoaderConstraint ld =  p->_loader_constraints->at(i);
1322       if (ld._name != NULL) {
1323         ld._name->decrement_refcount();
1324       }
1325     }
1326     FREE_C_HEAP_ARRAY(DumpTimeSharedClassInfo::DTLoaderConstraint, p->_loader_constraints);
1327     p->_loader_constraints = NULL;
1328   }
1329   _dumptime_table->remove(k);
1330 }
1331 
1332 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
1333   while (k) {
1334     if (k->name()->equals("jdk/internal/event/Event")) {
1335       return true;
1336     }
1337     k = k->java_super();
1338   }
1339   return false;
1340 }
1341 
1342 bool SystemDictionaryShared::is_registered_lambda_proxy_class(InstanceKlass* ik) {
1343   DumpTimeSharedClassInfo* info = _dumptime_table->get(ik);
1344   return (info != NULL) ? info->_is_archived_lambda_proxy && !ik->is_non_strong_hidden() : false;
1345 }
1346 
1347 bool SystemDictionaryShared::is_in_shared_lambda_proxy_table(InstanceKlass* ik) {
1348   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1349   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(ik);
1350   if (record != NULL && record->nest_host() != NULL) {
1351     return true;
1352   } else {
1353     return false;
1354   }
1355 }
1356 
1357 bool SystemDictionaryShared::is_hidden_lambda_proxy(InstanceKlass* ik) {
1358   assert(ik->is_shared(), "applicable to only a shared class");
1359   if (ik->is_hidden()) {
1360     assert(is_in_shared_lambda_proxy_table(ik), "we don't archive other hidden classes");
1361     return true;
1362   } else {
1363     return false;
1364   }
1365 }
1366 
1367 void SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
1368   ResourceMark rm;
1369   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
1370 }
1371 
1372 bool SystemDictionaryShared::should_be_excluded(InstanceKlass* k) {
1373 
1374   if (k->is_unsafe_anonymous()) {
1375     warn_excluded(k, "Unsafe anonymous class");
1376     return true; // unsafe anonymous classes are not archived, skip
1377   }
1378 
1379   if (k->is_in_error_state()) {
1380     warn_excluded(k, "In error state");
1381     return true;
1382   }
1383   if (k->has_been_redefined()) {
1384     warn_excluded(k, "Has been redefined");
1385     return true;
1386   }
1387   if (!k->is_hidden() && k->shared_classpath_index() < 0 && is_builtin(k)) {
1388     // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
1389     // agent during dump time).
1390     warn_excluded(k, "Unsupported location");
1391     return true;
1392   }
1393   if (k->signers() != NULL) {
1394     // We cannot include signed classes in the archive because the certificates
1395     // used during dump time may be different than those used during
1396     // runtime (due to expiration, etc).
1397     warn_excluded(k, "Signed JAR");
1398     return true;
1399   }
1400   if (is_jfr_event_class(k)) {
1401     // We cannot include JFR event classes because they need runtime-specific
1402     // instrumentation in order to work with -XX:FlightRecorderOptions=retransform=false.
1403     // There are only a small number of these classes, so it's not worthwhile to
1404     // support them and make CDS more complicated.
1405     warn_excluded(k, "JFR event class");
1406     return true;
1407   }
1408   if (k->init_state() < InstanceKlass::linked) {
1409     // In CDS dumping, we will attempt to link all classes. Those that fail to link will
1410     // be recorded in DumpTimeSharedClassInfo.
1411     Arguments::assert_is_dumping_archive();
1412 
1413     // TODO -- rethink how this can be handled.
1414     // We should try to link ik, however, we can't do it here because
1415     // 1. We are at VM exit
1416     // 2. linking a class may cause other classes to be loaded, which means
1417     //    a custom ClassLoader.loadClass() may be called, at a point where the
1418     //    class loader doesn't expect it.
1419     if (has_class_failed_verification(k)) {
1420       warn_excluded(k, "Failed verification");
1421     } else {
1422       warn_excluded(k, "Not linked");
1423     }
1424     return true;
1425   }
1426   if (k->major_version() < 50 /*JAVA_6_VERSION*/) {
1427     ResourceMark rm;
1428     log_warning(cds)("Pre JDK 6 class not supported by CDS: %u.%u %s",
1429                      k->major_version(),  k->minor_version(), k->name()->as_C_string());
1430     return true;
1431   }
1432 
1433   InstanceKlass* super = k->java_super();
1434   if (super != NULL && should_be_excluded(super)) {
1435     ResourceMark rm;
1436     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
1437     return true;
1438   }
1439 
1440   if (k->is_hidden() && !is_registered_lambda_proxy_class(k)) {
1441     warn_excluded(k, "Hidden class");
1442     return true;
1443   }
1444 
1445   Array<InstanceKlass*>* interfaces = k->local_interfaces();
1446   int len = interfaces->length();
1447   for (int i = 0; i < len; i++) {
1448     InstanceKlass* intf = interfaces->at(i);
1449     if (should_be_excluded(intf)) {
1450       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
1451       return true;
1452     }
1453   }
1454 
1455   return false;
1456 }
1457 
1458 // k is a class before relocating by ArchiveCompactor
1459 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
1460   ResourceMark rm;
1461   const char* name = k->name()->as_C_string();
1462   DumpTimeSharedClassInfo* info = _dumptime_table->get(k);
1463   assert(_no_class_loading_should_happen, "class loading must be disabled");
1464   guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name);
1465   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
1466   if (is_builtin(k)) {
1467     if (k->is_hidden()) {
1468       assert(is_registered_lambda_proxy_class(k), "unexpected hidden class %s", name);
1469     }
1470     guarantee(!k->is_shared_unregistered_class(),
1471               "Class loader type must be set for BUILTIN class %s", name);
1472 
1473   } else {
1474     guarantee(k->is_shared_unregistered_class(),
1475               "Class loader type must not be set for UNREGISTERED class %s", name);
1476   }
1477 }
1478 
1479 class ExcludeDumpTimeSharedClasses : StackObj {
1480 public:
1481   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1482     if (SystemDictionaryShared::should_be_excluded(k)) {
1483       info.set_excluded();
1484     }
1485     return true; // keep on iterating
1486   }
1487 };
1488 
1489 void SystemDictionaryShared::check_excluded_classes() {
1490   ExcludeDumpTimeSharedClasses excl;
1491   _dumptime_table->iterate(&excl);
1492   _dumptime_table->update_counts();
1493 }
1494 
1495 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
1496   assert(_no_class_loading_should_happen, "sanity");
1497   Arguments::assert_is_dumping_archive();
1498   return find_or_allocate_info_for(k)->is_excluded();
1499 }
1500 
1501 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
1502   Arguments::assert_is_dumping_archive();
1503   find_or_allocate_info_for(ik)->set_failed_verification();
1504 }
1505 
1506 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
1507   Arguments::assert_is_dumping_archive();
1508   if (_dumptime_table == NULL) {
1509     assert(DynamicDumpSharedSpaces, "sanity");
1510     assert(ik->is_shared(), "must be a shared class in the static archive");
1511     return false;
1512   }
1513   DumpTimeSharedClassInfo* p = _dumptime_table->get(ik);
1514   return (p == NULL) ? false : p->failed_verification();
1515 }
1516 
1517 class IterateDumpTimeSharedClassTable : StackObj {
1518   MetaspaceClosure *_it;
1519 public:
1520   IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {}
1521 
1522   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1523     if (!info.is_excluded()) {
1524       info.metaspace_pointers_do(_it);
1525     }
1526     return true; // keep on iterating
1527   }
1528 };
1529 
1530 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
1531   IterateDumpTimeSharedClassTable iter(it);
1532   _dumptime_table->iterate(&iter);
1533 }
1534 
1535 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1536          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1537   Arguments::assert_is_dumping_archive();
1538   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1539   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
1540                                     from_is_array, from_is_object);
1541 
1542   if (DynamicDumpSharedSpaces) {
1543     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
1544     // the initial run prior to creating the archive before vm exit. We will also perform verification
1545     // check when running with the archive.
1546     return false;
1547   } else {
1548     if (is_builtin(k)) {
1549       // For builtin class loaders, we can try to complete the verification check at dump time,
1550       // because we can resolve all the constraint classes. We will also perform verification check
1551       // when running with the archive.
1552       return false;
1553     } else {
1554       // For non-builtin class loaders, we cannot complete the verification check at dump time,
1555       // because at dump time we don't know how to resolve classes for such loaders.
1556       return true;
1557     }
1558   }
1559 }
1560 
1561 void DumpTimeSharedClassInfo::add_verification_constraint(InstanceKlass* k, Symbol* name,
1562          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1563   if (_verifier_constraints == NULL) {
1564     _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<DTVerifierConstraint>(4, true, mtClass);
1565   }
1566   if (_verifier_constraint_flags == NULL) {
1567     _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, true, mtClass);
1568   }
1569   GrowableArray<DTVerifierConstraint>* vc_array = _verifier_constraints;
1570   for (int i = 0; i < vc_array->length(); i++) {
1571     DTVerifierConstraint* p = vc_array->adr_at(i);
1572     if (name == p->_name && from_name == p->_from_name) {
1573       return;
1574     }
1575   }
1576   DTVerifierConstraint cons(name, from_name);
1577   vc_array->append(cons);
1578 
1579   GrowableArray<char>* vcflags_array = _verifier_constraint_flags;
1580   char c = 0;
1581   c |= from_field_is_protected ? SystemDictionaryShared::FROM_FIELD_IS_PROTECTED : 0;
1582   c |= from_is_array           ? SystemDictionaryShared::FROM_IS_ARRAY           : 0;
1583   c |= from_is_object          ? SystemDictionaryShared::FROM_IS_OBJECT          : 0;
1584   vcflags_array->append(c);
1585 
1586   if (log_is_enabled(Trace, cds, verification)) {
1587     ResourceMark rm;
1588     log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s [0x%x] array len %d flags len %d",
1589                                  k->external_name(), from_name->as_klass_external_name(),
1590                                  name->as_klass_external_name(), c, vc_array->length(), vcflags_array->length());
1591   }
1592 }
1593 
1594 void SystemDictionaryShared::add_lambda_proxy_class(InstanceKlass* caller_ik,
1595                                                     InstanceKlass* lambda_ik,
1596                                                     Symbol* invoked_name,
1597                                                     Symbol* invoked_type,
1598                                                     Symbol* method_type,
1599                                                     Method* member_method,
1600                                                     Symbol* instantiated_method_type) {
1601 
1602   assert(caller_ik->class_loader() == lambda_ik->class_loader(), "mismatched class loader");
1603   assert(caller_ik->class_loader_data() == lambda_ik->class_loader_data(), "mismatched class loader data");
1604 
1605   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1606 
1607   lambda_ik->assign_class_loader_type();
1608 
1609   DumpTimeSharedClassInfo* info = _dumptime_table->get(lambda_ik);
1610   if (info != NULL) {
1611     // Set _is_archived_lambda_proxy in DumpTimeSharedClassInfo so that the lambda_ik
1612     // won't be excluded during dumping of shared archive. See ExcludeDumpTimeSharedClasses.
1613     info->_is_archived_lambda_proxy = true;
1614   }
1615 
1616   LambdaProxyClassKey key(caller_ik,
1617                           invoked_name,
1618                           invoked_type,
1619                           method_type,
1620                           member_method,
1621                           instantiated_method_type);
1622   add_to_dump_time_lambda_proxy_class_dictionary(key, lambda_ik);
1623 }
1624 
1625 InstanceKlass* SystemDictionaryShared::get_shared_lambda_proxy_class(InstanceKlass* caller_ik,
1626                                                                      Symbol* invoked_name,
1627                                                                      Symbol* invoked_type,
1628                                                                      Symbol* method_type,
1629                                                                      Method* member_method,
1630                                                                      Symbol* instantiated_method_type) {
1631   MutexLocker ml(CDSLambda_lock, Mutex::_no_safepoint_check_flag);
1632   LambdaProxyClassKey key(caller_ik, invoked_name, invoked_type,
1633                           method_type, member_method, instantiated_method_type);
1634   const RunTimeLambdaProxyClassInfo* info = _lambda_proxy_class_dictionary.lookup(&key, key.hash(), 0);
1635   InstanceKlass* proxy_klass = NULL;
1636   if (info != NULL) {
1637     InstanceKlass* curr_klass = info->proxy_klass();
1638     InstanceKlass* prev_klass = curr_klass;
1639     if (curr_klass->lambda_proxy_is_available()) {
1640       while (curr_klass->next_link() != NULL) {
1641         prev_klass = curr_klass;
1642         curr_klass = InstanceKlass::cast(curr_klass->next_link());
1643       }
1644       assert(curr_klass->is_hidden(), "must be");
1645       assert(curr_klass->lambda_proxy_is_available(), "must be");
1646 
1647       prev_klass->set_next_link(NULL);
1648       proxy_klass = curr_klass;
1649       proxy_klass->clear_lambda_proxy_is_available();
1650       if (log_is_enabled(Debug, cds)) {
1651         ResourceMark rm;
1652         log_debug(cds)("Loaded lambda proxy: %s", proxy_klass->external_name());
1653       }
1654     } else {
1655       if (log_is_enabled(Debug, cds)) {
1656         ResourceMark rm;
1657         log_debug(cds)("Used all archived lambda proxy classes for: %s %s%s",
1658                        caller_ik->external_name(), invoked_name->as_C_string(), invoked_type->as_C_string());
1659       }
1660     }
1661   }
1662   return proxy_klass;
1663 }
1664 
1665 InstanceKlass* SystemDictionaryShared::get_shared_nest_host(InstanceKlass* lambda_ik) {
1666   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1667   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(lambda_ik);
1668   return record->nest_host();
1669 }
1670 
1671 InstanceKlass* SystemDictionaryShared::prepare_shared_lambda_proxy_class(InstanceKlass* lambda_ik,
1672                                                                          InstanceKlass* caller_ik,
1673                                                                          bool initialize, TRAPS) {
1674   Handle class_loader(THREAD, caller_ik->class_loader());
1675   Handle protection_domain;
1676   PackageEntry* pkg_entry = get_package_entry_from_class_name(class_loader, caller_ik->name());
1677   if (caller_ik->class_loader() != NULL) {
1678     protection_domain = SystemDictionaryShared::init_security_info(class_loader, caller_ik, pkg_entry, CHECK_NULL);
1679   }
1680 
1681   InstanceKlass* shared_nest_host = get_shared_nest_host(lambda_ik);
1682   assert(shared_nest_host != NULL, "unexpected NULL _nest_host");
1683 
1684   InstanceKlass* loaded_lambda =
1685     SystemDictionary::load_shared_lambda_proxy_class(lambda_ik, class_loader, protection_domain, pkg_entry, CHECK_NULL);
1686 
1687   // Ensures the nest host is the same as the lambda proxy's
1688   // nest host recorded at dump time.
1689   InstanceKlass* nest_host = caller_ik->nest_host(THREAD);
1690   assert(nest_host == shared_nest_host, "mismatched nest host");
1691 
1692   EventClassLoad class_load_start_event;
1693   {
1694     MutexLocker mu_r(THREAD, Compile_lock);
1695 
1696     // Add to class hierarchy, initialize vtables, and do possible
1697     // deoptimizations.
1698     SystemDictionary::add_to_hierarchy(loaded_lambda, CHECK_NULL); // No exception, but can block
1699     // But, do not add to dictionary.
1700   }
1701   loaded_lambda->link_class(CHECK_NULL);
1702   // notify jvmti
1703   if (JvmtiExport::should_post_class_load()) {
1704       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1705       JvmtiExport::post_class_load((JavaThread *) THREAD, loaded_lambda);
1706   }
1707   if (class_load_start_event.should_commit()) {
1708     SystemDictionary::post_class_load_event(&class_load_start_event, loaded_lambda, ClassLoaderData::class_loader_data(class_loader()));
1709   }
1710 
1711   if (initialize) {
1712     loaded_lambda->initialize(CHECK_NULL);
1713   }
1714 
1715   return loaded_lambda;
1716 }
1717 
1718 static char get_loader_type_by(oop  loader) {
1719   assert(SystemDictionary::is_builtin_class_loader(loader), "Must be built-in loader");
1720   if (SystemDictionary::is_boot_class_loader(loader)) {
1721     return (char)ClassLoader::BOOT_LOADER;
1722   } else if (SystemDictionary::is_platform_class_loader(loader)) {
1723     return (char)ClassLoader::PLATFORM_LOADER;
1724   } else {
1725     assert(SystemDictionary::is_system_class_loader(loader), "Class loader mismatch");
1726     return (char)ClassLoader::APP_LOADER;
1727   }
1728 }
1729 
1730 static oop get_class_loader_by(char type) {
1731   if (type == (char)ClassLoader::BOOT_LOADER) {
1732     return (oop)NULL;
1733   } else if (type == (char)ClassLoader::PLATFORM_LOADER) {
1734     return SystemDictionary::java_platform_loader();
1735   } else {
1736     assert (type == (char)ClassLoader::APP_LOADER, "Sanity");
1737     return SystemDictionary::java_system_loader();
1738   }
1739 }
1740 
1741 void DumpTimeSharedClassInfo::record_linking_constraint(Symbol* name, Handle loader1, Handle loader2) {
1742   assert(loader1 != loader2, "sanity");
1743   LogTarget(Info, class, loader, constraints) log;
1744   if (_loader_constraints == NULL) {
1745     _loader_constraints = new (ResourceObj::C_HEAP, mtClass) GrowableArray<DTLoaderConstraint>(4, true, mtClass);
1746   }
1747   char lt1 = get_loader_type_by(loader1());
1748   char lt2 = get_loader_type_by(loader2());
1749   DTLoaderConstraint lc(name, lt1, lt2);
1750   for (int i = 0; i < _loader_constraints->length(); i++) {
1751     DTLoaderConstraint dt = _loader_constraints->at(i);
1752     if (lc.equals(dt)) {
1753       if (log.is_enabled()) {
1754         ResourceMark rm;
1755         // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1756         log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s already added]",
1757                   _klass->external_name(), name->as_C_string(),
1758                   ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1759                   ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1760       }
1761       return;
1762     }
1763   }
1764   _loader_constraints->append(lc);
1765   if (log.is_enabled()) {
1766     ResourceMark rm;
1767     // Use loader[0]/loader[1] to be consistent with the logs in loaderConstraints.cpp
1768     log.print("[CDS record loader constraint for class: %s constraint_name: %s loader[0]: %s loader[1]: %s total %d]",
1769               _klass->external_name(), name->as_C_string(),
1770               ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1771               ClassLoaderData::class_loader_data(loader2())->loader_name_and_id(),
1772               _loader_constraints->length());
1773   }
1774 }
1775 
1776 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1777                                                             TRAPS) {
1778   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1779   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(klass);
1780 
1781   int length = record->_num_verifier_constraints;
1782   if (length > 0) {
1783     for (int i = 0; i < length; i++) {
1784       RunTimeSharedClassInfo::RTVerifierConstraint* vc = record->verifier_constraint_at(i);
1785       Symbol* name      = vc->name();
1786       Symbol* from_name = vc->from_name();
1787       char c            = record->verifier_constraint_flag(i);
1788 
1789       if (log_is_enabled(Trace, cds, verification)) {
1790         ResourceMark rm(THREAD);
1791         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1792                                      klass->external_name(), from_name->as_klass_external_name(),
1793                                      name->as_klass_external_name(), c);
1794       }
1795 
1796       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
1797       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
1798       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
1799 
1800       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
1801          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
1802       if (!ok) {
1803         ResourceMark rm(THREAD);
1804         stringStream ss;
1805 
1806         ss.print_cr("Bad type on operand stack");
1807         ss.print_cr("Exception Details:");
1808         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1809         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1810                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1811         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1812       }
1813     }
1814   }
1815 }
1816 
1817 // Record class loader constraints that are checked inside
1818 // InstanceKlass::link_class(), so that these can be checked quickly
1819 // at runtime without laying out the vtable/itables.
1820 void SystemDictionaryShared::record_linking_constraint(Symbol* name, InstanceKlass* klass,
1821                                                     Handle loader1, Handle loader2, TRAPS) {
1822   // A linking constraint check is executed when:
1823   //   - klass extends or implements type S
1824   //   - klass overrides method S.M(...) with X.M
1825   //     - If klass defines the method M, X is
1826   //       the same as klass.
1827   //     - If klass does not define the method M,
1828   //       X must be a supertype of klass and X.M is
1829   //       a default method defined by X.
1830   //   - loader1 = X->class_loader()
1831   //   - loader2 = S->class_loader()
1832   //   - loader1 != loader2
1833   //   - M's paramater(s) include an object type T
1834   // We require that
1835   //   - whenever loader1 and loader2 try to
1836   //     resolve the type T, they must always resolve to
1837   //     the same InstanceKlass.
1838   // NOTE: type T may or may not be currently resolved in
1839   // either of these two loaders. The check itself does not
1840   // try to resolve T.
1841   oop klass_loader = klass->class_loader();
1842   assert(klass_loader != NULL, "should not be called for boot loader");
1843   assert(loader1 != loader2, "must be");
1844 
1845   if (!is_system_class_loader(klass_loader) &&
1846       !is_platform_class_loader(klass_loader)) {
1847     // If klass is loaded by system/platform loaders, we can
1848     // guarantee that klass and S must be loaded by the same
1849     // respective loader between dump time and run time, and
1850     // the exact same check on (name, loader1, loader2) will
1851     // be executed. Hence, we can cache this check and execute
1852     // it at runtime without walking the vtable/itables.
1853     //
1854     // This cannot be guaranteed for classes loaded by other
1855     // loaders, so we bail.
1856     return;
1857   }
1858 
1859   if (THREAD->is_VM_thread()) {
1860     assert(DynamicDumpSharedSpaces, "must be");
1861     // We are re-laying out the vtable/itables of the *copy* of
1862     // a class during the final stage of dynamic dumping. The
1863     // linking constraints for this class has already been recorded.
1864     return;
1865   }
1866   Arguments::assert_is_dumping_archive();
1867   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(klass);
1868   info->record_linking_constraint(name, loader1, loader2);
1869 }
1870 
1871 // returns true IFF there's no need to re-initialize the i/v-tables for klass for
1872 // the purpose of checking class loader constraints.
1873 bool SystemDictionaryShared::check_linking_constraints(InstanceKlass* klass, TRAPS) {
1874   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1875   LogTarget(Info, class, loader, constraints) log;
1876   if (klass->is_shared_boot_class()) {
1877     // No class loader constraint check performed for boot classes.
1878     return true;
1879   }
1880   if (klass->is_shared_platform_class() || klass->is_shared_app_class()) {
1881     RunTimeSharedClassInfo* info = RunTimeSharedClassInfo::get_for(klass);
1882     assert(info != NULL, "Sanity");
1883     if (info->_num_loader_constraints > 0) {
1884       HandleMark hm;
1885       for (int i = 0; i < info->_num_loader_constraints; i++) {
1886         RunTimeSharedClassInfo::RTLoaderConstraint* lc = info->loader_constraint_at(i);
1887         Symbol* name = lc->constraint_name();
1888         Handle loader1(THREAD, get_class_loader_by(lc->_loader_type1));
1889         Handle loader2(THREAD, get_class_loader_by(lc->_loader_type2));
1890         if (log.is_enabled()) {
1891           ResourceMark rm(THREAD);
1892           log.print("[CDS add loader constraint for class %s symbol %s loader[0] %s loader[1] %s",
1893                     klass->external_name(), name->as_C_string(),
1894                     ClassLoaderData::class_loader_data(loader1())->loader_name_and_id(),
1895                     ClassLoaderData::class_loader_data(loader2())->loader_name_and_id());
1896         }
1897         if (!SystemDictionary::add_loader_constraint(name, klass, loader1, loader2, THREAD)) {
1898           // Loader constraint violation has been found. The caller
1899           // will re-layout the vtable/itables to produce the correct
1900           // exception.
1901           if (log.is_enabled()) {
1902             log.print(" failed]");
1903           }
1904           return false;
1905         }
1906         if (log.is_enabled()) {
1907             log.print(" succeeded]");
1908         }
1909       }
1910       return true; // for all recorded constraints added successully.
1911     }
1912   }
1913   if (log.is_enabled()) {
1914     ResourceMark rm(THREAD);
1915     log.print("[CDS has not recorded loader constraint for class %s]", klass->external_name());
1916   }
1917   return false;
1918 }
1919 
1920 class EstimateSizeForArchive : StackObj {
1921   size_t _shared_class_info_size;
1922   int _num_builtin_klasses;
1923   int _num_unregistered_klasses;
1924 
1925 public:
1926   EstimateSizeForArchive() {
1927     _shared_class_info_size = 0;
1928     _num_builtin_klasses = 0;
1929     _num_unregistered_klasses = 0;
1930   }
1931 
1932   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1933     if (!info.is_excluded()) {
1934       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
1935       _shared_class_info_size += align_up(byte_size, BytesPerWord);
1936     }
1937     return true; // keep on iterating
1938   }
1939 
1940   size_t total() {
1941     return _shared_class_info_size;
1942   }
1943 };
1944 
1945 size_t SystemDictionaryShared::estimate_size_for_archive() {
1946   EstimateSizeForArchive est;
1947   _dumptime_table->iterate(&est);
1948   size_t total_size = est.total() +
1949     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1950     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1951   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
1952     total_size +=
1953       (sizeof(RunTimeLambdaProxyClassInfo) * _dumptime_lambda_proxy_class_dictionary->_count) +
1954       CompactHashtableWriter::estimate_size(_dumptime_lambda_proxy_class_dictionary->_count);
1955   } else {
1956     total_size += CompactHashtableWriter::estimate_size(0);
1957   }
1958   return total_size;
1959 }
1960 
1961 class CopyLambdaProxyClassInfoToArchive : StackObj {
1962   CompactHashtableWriter* _writer;
1963 public:
1964   CopyLambdaProxyClassInfoToArchive(CompactHashtableWriter* writer)
1965     : _writer(writer) {}
1966   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1967     if (SystemDictionaryShared::is_excluded_class(info._proxy_klass->at(0))) {
1968       return true;
1969     }
1970     ResourceMark rm;
1971     log_info(cds,dynamic)("Archiving hidden %s", info._proxy_klass->at(0)->external_name());
1972     size_t byte_size = sizeof(RunTimeLambdaProxyClassInfo);
1973     RunTimeLambdaProxyClassInfo* runtime_info =
1974         (RunTimeLambdaProxyClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
1975     runtime_info->init(key, info);
1976     unsigned int hash = runtime_info->hash(); // Fields in runtime_info->_key already point to target space.
1977     u4 delta = MetaspaceShared::object_delta_u4(DynamicArchive::buffer_to_target(runtime_info));
1978     _writer->add(hash, delta);
1979     return true;
1980   }
1981 };
1982 
1983 class AdjustLambdaProxyClassInfo : StackObj {
1984 public:
1985   AdjustLambdaProxyClassInfo() {}
1986   bool do_entry(LambdaProxyClassKey& key, DumpTimeLambdaProxyClassInfo& info) {
1987     if (SystemDictionaryShared::is_excluded_class(info._proxy_klass->at(0))) {
1988       return true;
1989     }
1990     int len = info._proxy_klass->length();
1991     if (len > 1) {
1992       for (int i = 0; i < len-1; i++) {
1993         InstanceKlass* ok0 = info._proxy_klass->at(i+0); // this is original klass
1994         InstanceKlass* ok1 = info._proxy_klass->at(i+1); // this is original klass
1995         InstanceKlass* bk0 = DynamicArchive::original_to_buffer(ok0);
1996         InstanceKlass* bk1 = DynamicArchive::original_to_buffer(ok1);
1997         assert(bk0->next_link() == 0, "must be called after Klass::remove_unshareable_info()");
1998         assert(bk1->next_link() == 0, "must be called after Klass::remove_unshareable_info()");
1999         bk0->set_next_link(bk1);
2000         bk1->set_lambda_proxy_is_available();
2001         ArchivePtrMarker::mark_pointer(bk0->next_link_addr());
2002       }
2003     }
2004     DynamicArchive::original_to_buffer(info._proxy_klass->at(0))->set_lambda_proxy_is_available();
2005     return true;
2006   }
2007 };
2008 
2009 class CopySharedClassInfoToArchive : StackObj {
2010   CompactHashtableWriter* _writer;
2011   bool _is_builtin;
2012 public:
2013   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
2014                                bool is_builtin,
2015                                bool is_static_archive)
2016     : _writer(writer), _is_builtin(is_builtin) {}
2017 
2018   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
2019     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
2020       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_verifier_constraints(), info.num_loader_constraints());
2021       RunTimeSharedClassInfo* record;
2022       record = (RunTimeSharedClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
2023       record->init(info);
2024 
2025       unsigned int hash;
2026       Symbol* name = info._klass->name();
2027       if (DynamicDumpSharedSpaces) {
2028         name = DynamicArchive::original_to_target(name);
2029       }
2030       hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
2031       u4 delta;
2032       if (DynamicDumpSharedSpaces) {
2033         delta = MetaspaceShared::object_delta_u4(DynamicArchive::buffer_to_target(record));
2034       } else {
2035         delta = MetaspaceShared::object_delta_u4(record);
2036       }
2037       if (_is_builtin && info._klass->is_hidden()) {
2038         // skip
2039       } else {
2040         _writer->add(hash, delta);
2041       }
2042       if (log_is_enabled(Trace, cds, hashtables)) {
2043         ResourceMark rm;
2044         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
2045       }
2046 
2047       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeSharedClassInfo*
2048       RunTimeSharedClassInfo::set_for(info._klass, record);
2049     }
2050     return true; // keep on iterating
2051   }
2052 };
2053 
2054 void SystemDictionaryShared::write_lambda_proxy_class_dictionary(LambdaProxyClassDictionary *dictionary) {
2055   CompactHashtableStats stats;
2056   dictionary->reset();
2057   CompactHashtableWriter writer(_dumptime_lambda_proxy_class_dictionary->_count, &stats);
2058   CopyLambdaProxyClassInfoToArchive copy(&writer);
2059   _dumptime_lambda_proxy_class_dictionary->iterate(&copy);
2060   writer.dump(dictionary, "lambda proxy class dictionary");
2061 }
2062 
2063 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
2064                                               bool is_builtin,
2065                                               bool is_static_archive) {
2066   CompactHashtableStats stats;
2067   dictionary->reset();
2068   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
2069   CopySharedClassInfoToArchive copy(&writer, is_builtin, is_static_archive);
2070   _dumptime_table->iterate(&copy);
2071   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
2072 }
2073 
2074 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
2075   if (is_static_archive) {
2076     write_dictionary(&_builtin_dictionary, true);
2077     write_dictionary(&_unregistered_dictionary, false);
2078   } else {
2079     write_dictionary(&_dynamic_builtin_dictionary, true);
2080     write_dictionary(&_dynamic_unregistered_dictionary, false);
2081   }
2082   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
2083     write_lambda_proxy_class_dictionary(&_lambda_proxy_class_dictionary);
2084   }
2085 }
2086 
2087 void SystemDictionaryShared::adjust_lambda_proxy_class_dictionary() {
2088   if (_dumptime_lambda_proxy_class_dictionary != NULL) {
2089     AdjustLambdaProxyClassInfo adjuster;
2090     _dumptime_lambda_proxy_class_dictionary->iterate(&adjuster);
2091   }
2092 }
2093 
2094 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
2095                                                           bool is_static_archive) {
2096   if (is_static_archive) {
2097     _builtin_dictionary.serialize_header(soc);
2098     _unregistered_dictionary.serialize_header(soc);
2099   } else {
2100     _dynamic_builtin_dictionary.serialize_header(soc);
2101     _dynamic_unregistered_dictionary.serialize_header(soc);
2102     _lambda_proxy_class_dictionary.serialize_header(soc);
2103   }
2104 }
2105 
2106 void SystemDictionaryShared::serialize_well_known_klasses(SerializeClosure* soc) {
2107   for (int i = FIRST_WKID; i < WKID_LIMIT; i++) {
2108     soc->do_ptr((void**)&_well_known_klasses[i]);
2109   }
2110 }
2111 
2112 const RunTimeSharedClassInfo*
2113 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
2114   if (!UseSharedSpaces || !name->is_shared()) {
2115     // The names of all shared classes must also be a shared Symbol.
2116     return NULL;
2117   }
2118 
2119   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
2120   const RunTimeSharedClassInfo* record = NULL;
2121   if (!MetaspaceShared::is_shared_dynamic(name)) {
2122     // The names of all shared classes in the static dict must also be in the
2123     // static archive
2124     record = static_dict->lookup(name, hash, 0);
2125   }
2126 
2127   if (record == NULL && DynamicArchive::is_mapped()) {
2128     record = dynamic_dict->lookup(name, hash, 0);
2129   }
2130 
2131   return record;
2132 }
2133 
2134 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
2135   const RunTimeSharedClassInfo* record = find_record(&_builtin_dictionary, &_dynamic_builtin_dictionary, name);
2136   if (record != NULL) {
2137     assert(!record->_klass->is_hidden(), "hidden class cannot be looked up by name");
2138     return record->_klass;
2139   } else {
2140     return NULL;
2141   }
2142 }
2143 
2144 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
2145   assert(DumpSharedSpaces, "supported only when dumping");
2146   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
2147   info->_id = id;
2148 }
2149 
2150 class SharedDictionaryPrinter : StackObj {
2151   outputStream* _st;
2152   int _index;
2153 public:
2154   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
2155 
2156   void do_value(const RunTimeSharedClassInfo* record) {
2157     ResourceMark rm;
2158     _st->print_cr("%4d:  %s", (_index++), record->_klass->external_name());
2159   }
2160 };
2161 
2162 class SharedLambdaDictionaryPrinter : StackObj {
2163   outputStream* _st;
2164   int _index;
2165 public:
2166   SharedLambdaDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
2167 
2168   void do_value(const RunTimeLambdaProxyClassInfo* record) {
2169     ResourceMark rm;
2170     _st->print_cr("%4d:  %s", (_index++), record->proxy_klass()->external_name());
2171     Klass* k = record->proxy_klass()->next_link();
2172     while (k != NULL) {
2173       _st->print_cr("%4d:  %s", (_index++), k->external_name());
2174       k = k->next_link();
2175     }
2176   }
2177 };
2178 
2179 void SystemDictionaryShared::print_on(outputStream* st) {
2180   if (UseSharedSpaces) {
2181     st->print_cr("Shared Dictionary");
2182     SharedDictionaryPrinter p(st);
2183     _builtin_dictionary.iterate(&p);
2184     _unregistered_dictionary.iterate(&p);
2185     if (DynamicArchive::is_mapped()) {
2186       _dynamic_builtin_dictionary.iterate(&p);
2187       _unregistered_dictionary.iterate(&p);
2188       if (!_lambda_proxy_class_dictionary.empty()) {
2189         st->print_cr("Shared Lambda Dictionary");
2190         SharedLambdaDictionaryPrinter ldp(st);
2191         _lambda_proxy_class_dictionary.iterate(&ldp);
2192       }
2193     }
2194   }
2195 }
2196 
2197 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
2198   if (UseSharedSpaces) {
2199     _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
2200     _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
2201     if (DynamicArchive::is_mapped()) {
2202       _dynamic_builtin_dictionary.print_table_statistics(st, "Dynamic Builtin Shared Dictionary");
2203       _dynamic_unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
2204       _lambda_proxy_class_dictionary.print_table_statistics(st, "Lambda Shared Dictionary");
2205     }
2206   }
2207 }
2208 
2209 bool SystemDictionaryShared::empty_dumptime_table() {
2210   if (_dumptime_table == NULL) {
2211     return true;
2212   }
2213   _dumptime_table->update_counts();
2214   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
2215     return true;
2216   }
2217   return false;
2218 }
2219 
2220 #if INCLUDE_CDS_JAVA_HEAP
2221 
2222 class ArchivedMirrorPatcher {
2223   static void update(Klass* k) {
2224     if (k->has_raw_archived_mirror()) {
2225       oop m = HeapShared::materialize_archived_object(k->archived_java_mirror_raw_narrow());
2226       if (m != NULL) {
2227         java_lang_Class::update_archived_mirror_native_pointers(m);
2228       }
2229     }
2230   }
2231 
2232 public:
2233   static void update_array_klasses(Klass* ak) {
2234     while (ak != NULL) {
2235       update(ak);
2236       ak = ArrayKlass::cast(ak)->higher_dimension();
2237     }
2238   }
2239 
2240   void do_value(const RunTimeSharedClassInfo* info) {
2241     InstanceKlass* ik = info->_klass;
2242     update(ik);
2243     update_array_klasses(ik->array_klasses());
2244   }
2245 };
2246 
2247 void SystemDictionaryShared::update_archived_mirror_native_pointers_for(RunTimeSharedDictionary* dict) {
2248   ArchivedMirrorPatcher patcher;
2249   dict->iterate(&patcher);
2250 }
2251 
2252 void SystemDictionaryShared::update_archived_mirror_native_pointers() {
2253   if (!HeapShared::open_archive_heap_region_mapped()) {
2254     return;
2255   }
2256   if (MetaspaceShared::relocation_delta() == 0) {
2257     return;
2258   }
2259   update_archived_mirror_native_pointers_for(&_builtin_dictionary);
2260   update_archived_mirror_native_pointers_for(&_unregistered_dictionary);
2261 
2262   for (int t = T_BOOLEAN; t <= T_LONG; t++) {
2263     Klass* k = Universe::typeArrayKlassObj((BasicType)t);
2264     ArchivedMirrorPatcher::update_array_klasses(k);
2265   }
2266 }
2267 #endif