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