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