1 /*
   2  * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classFileStream.hpp"
  27 #include "classfile/classListParser.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/classLoaderData.inline.hpp"
  30 #include "classfile/classLoaderDataGraph.hpp"
  31 #include "classfile/classLoaderExt.hpp"
  32 #include "classfile/dictionary.hpp"
  33 #include "classfile/javaClasses.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/systemDictionary.hpp"
  36 #include "classfile/systemDictionaryShared.hpp"
  37 #include "classfile/verificationType.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "logging/log.hpp"
  40 #include "memory/allocation.hpp"
  41 #include "memory/archiveUtils.hpp"
  42 #include "memory/filemap.hpp"
  43 #include "memory/metadataFactory.hpp"
  44 #include "memory/metaspaceClosure.hpp"
  45 #include "memory/oopFactory.hpp"
  46 #include "memory/resourceArea.hpp"
  47 #include "memory/universe.hpp"
  48 #include "memory/dynamicArchive.hpp"
  49 #include "oops/instanceKlass.hpp"
  50 #include "oops/klass.inline.hpp"
  51 #include "oops/objArrayOop.inline.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "oops/typeArrayOop.inline.hpp"
  54 #include "runtime/handles.inline.hpp"
  55 #include "runtime/java.hpp"
  56 #include "runtime/javaCalls.hpp"
  57 #include "runtime/mutexLocker.hpp"
  58 #include "utilities/hashtable.inline.hpp"
  59 #include "utilities/resourceHash.hpp"
  60 #include "utilities/stringUtils.hpp"
  61 
  62 
  63 objArrayOop SystemDictionaryShared::_shared_protection_domains  =  NULL;
  64 objArrayOop SystemDictionaryShared::_shared_jar_urls            =  NULL;
  65 objArrayOop SystemDictionaryShared::_shared_jar_manifests       =  NULL;
  66 DEBUG_ONLY(bool SystemDictionaryShared::_no_class_loading_should_happen = false;)
  67 
  68 class DumpTimeSharedClassInfo: public CHeapObj<mtClass> {
  69   bool                         _excluded;
  70 public:
  71   struct DTConstraint {
  72     Symbol* _name;
  73     Symbol* _from_name;
  74     DTConstraint() : _name(NULL), _from_name(NULL) {}
  75     DTConstraint(Symbol* n, Symbol* fn) : _name(n), _from_name(fn) {}
  76   };
  77 
  78   InstanceKlass*               _klass;
  79   bool                         _failed_verification;
  80   int                          _id;
  81   int                          _clsfile_size;
  82   int                          _clsfile_crc32;
  83   GrowableArray<DTConstraint>* _verifier_constraints;
  84   GrowableArray<char>*         _verifier_constraint_flags;
  85 
  86   DumpTimeSharedClassInfo() {
  87     _klass = NULL;
  88     _failed_verification = false;
  89     _id = -1;
  90     _clsfile_size = -1;
  91     _clsfile_crc32 = -1;
  92     _excluded = false;
  93     _verifier_constraints = NULL;
  94     _verifier_constraint_flags = NULL;
  95   }
  96 
  97   void add_verification_constraint(InstanceKlass* k, Symbol* name,
  98          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object);
  99 
 100   bool is_builtin() {
 101     return SystemDictionaryShared::is_builtin(_klass);
 102   }
 103 
 104   int num_constraints() {
 105     if (_verifier_constraint_flags != NULL) {
 106       return _verifier_constraint_flags->length();
 107     } else {
 108       return 0;
 109     }
 110   }
 111 
 112   void metaspace_pointers_do(MetaspaceClosure* it) {
 113     it->push(&_klass);
 114     if (_verifier_constraints != NULL) {
 115       for (int i = 0; i < _verifier_constraints->length(); i++) {
 116         DTConstraint* cons = _verifier_constraints->adr_at(i);
 117         it->push(&cons->_name);
 118         it->push(&cons->_from_name);
 119       }
 120     }
 121   }
 122 
 123   void set_excluded() {
 124     _excluded = true;
 125   }
 126 
 127   bool is_excluded() {
 128     // _klass may become NULL due to DynamicArchiveBuilder::set_to_null
 129     return _excluded || _failed_verification || _klass == NULL;
 130   }
 131 
 132   void set_failed_verification() {
 133     _failed_verification = true;
 134   }
 135 
 136   bool failed_verification() {
 137     return _failed_verification;
 138   }
 139 };
 140 
 141 class DumpTimeSharedClassTable: public ResourceHashtable<
 142   InstanceKlass*,
 143   DumpTimeSharedClassInfo,
 144   primitive_hash<InstanceKlass*>,
 145   primitive_equals<InstanceKlass*>,
 146   15889, // prime number
 147   ResourceObj::C_HEAP>
 148 {
 149   int _builtin_count;
 150   int _unregistered_count;
 151 public:
 152   DumpTimeSharedClassInfo* find_or_allocate_info_for(InstanceKlass* k) {
 153     DumpTimeSharedClassInfo* p = get(k);
 154     if (p == NULL) {
 155       assert(!SystemDictionaryShared::no_class_loading_should_happen(),
 156              "no new classes can be loaded while dumping archive");
 157       put(k, DumpTimeSharedClassInfo());
 158       p = get(k);
 159       assert(p != NULL, "sanity");
 160       p->_klass = k;
 161     }
 162     return p;
 163   }
 164 
 165   class CountClassByCategory : StackObj {
 166     DumpTimeSharedClassTable* _table;
 167   public:
 168     CountClassByCategory(DumpTimeSharedClassTable* table) : _table(table) {}
 169     bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
 170       if (!info.is_excluded()) {
 171         if (info.is_builtin()) {
 172           ++ _table->_builtin_count;
 173         } else {
 174           ++ _table->_unregistered_count;
 175         }
 176       }
 177       return true; // keep on iterating
 178     }
 179   };
 180 
 181   void update_counts() {
 182     _builtin_count = 0;
 183     _unregistered_count = 0;
 184     CountClassByCategory counter(this);
 185     iterate(&counter);
 186   }
 187 
 188   int count_of(bool is_builtin) const {
 189     if (is_builtin) {
 190       return _builtin_count;
 191     } else {
 192       return _unregistered_count;
 193     }
 194   }
 195 };
 196 
 197 class RunTimeSharedClassInfo {
 198 public:
 199   struct CrcInfo {
 200     int _clsfile_size;
 201     int _clsfile_crc32;
 202   };
 203 
 204   // This is different than  DumpTimeSharedClassInfo::DTConstraint. We use
 205   // u4 instead of Symbol* to save space on 64-bit CPU.
 206   struct RTConstraint {
 207     u4 _name;
 208     u4 _from_name;
 209   };
 210 
 211   InstanceKlass* _klass;
 212   int _num_constraints;
 213 
 214   // optional CrcInfo      _crc;  (only for UNREGISTERED classes)
 215   // optional RTConstraint _verifier_constraints[_num_constraints]
 216   // optional char         _verifier_constraint_flags[_num_constraints]
 217 
 218 private:
 219   static size_t header_size_size() {
 220     return sizeof(RunTimeSharedClassInfo);
 221   }
 222   static size_t crc_size(InstanceKlass* klass) {
 223     if (!SystemDictionaryShared::is_builtin(klass)) {
 224       return sizeof(CrcInfo);
 225     } else {
 226       return 0;
 227     }
 228   }
 229   static size_t verifier_constraints_size(int num_constraints) {
 230     return sizeof(RTConstraint) * num_constraints;
 231   }
 232   static size_t verifier_constraint_flags_size(int num_constraints) {
 233     return sizeof(char) * num_constraints;
 234   }
 235 
 236 public:
 237   static size_t byte_size(InstanceKlass* klass, int num_constraints) {
 238     return header_size_size() +
 239            crc_size(klass) +
 240            verifier_constraints_size(num_constraints) +
 241            verifier_constraint_flags_size(num_constraints);
 242   }
 243 
 244 private:
 245   size_t crc_offset() const {
 246     return header_size_size();
 247   }
 248   size_t verifier_constraints_offset() const {
 249     return crc_offset() + crc_size(_klass);
 250   }
 251   size_t verifier_constraint_flags_offset() const {
 252     return verifier_constraints_offset() + verifier_constraints_size(_num_constraints);
 253   }
 254 
 255   void check_constraint_offset(int i) const {
 256     assert(0 <= i && i < _num_constraints, "sanity");
 257   }
 258 
 259 public:
 260   CrcInfo* crc() const {
 261     assert(crc_size(_klass) > 0, "must be");
 262     return (CrcInfo*)(address(this) + crc_offset());
 263   }
 264   RTConstraint* verifier_constraints() {
 265     assert(_num_constraints > 0, "sanity");
 266     return (RTConstraint*)(address(this) + verifier_constraints_offset());
 267   }
 268   RTConstraint* verifier_constraint_at(int i) {
 269     check_constraint_offset(i);
 270     return verifier_constraints() + i;
 271   }
 272 
 273   char* verifier_constraint_flags() {
 274     assert(_num_constraints > 0, "sanity");
 275     return (char*)(address(this) + verifier_constraint_flags_offset());
 276   }
 277 
 278   static u4 object_delta_u4(Symbol* sym) {
 279     if (DynamicDumpSharedSpaces) {
 280       sym = DynamicArchive::original_to_target(sym);
 281     }
 282     return MetaspaceShared::object_delta_u4(sym);
 283   }
 284 
 285   void init(DumpTimeSharedClassInfo& info) {
 286     _klass = info._klass;
 287     if (!SystemDictionaryShared::is_builtin(_klass)) {
 288       CrcInfo* c = crc();
 289       c->_clsfile_size = info._clsfile_size;
 290       c->_clsfile_crc32 = info._clsfile_crc32;
 291     }
 292     _num_constraints = info.num_constraints();
 293     if (_num_constraints > 0) {
 294       RTConstraint* constraints = verifier_constraints();
 295       char* flags = verifier_constraint_flags();
 296       int i;
 297       for (i = 0; i < _num_constraints; i++) {
 298         constraints[i]._name      = object_delta_u4(info._verifier_constraints->at(i)._name);
 299         constraints[i]._from_name = object_delta_u4(info._verifier_constraints->at(i)._from_name);
 300       }
 301       for (i = 0; i < _num_constraints; i++) {
 302         flags[i] = info._verifier_constraint_flags->at(i);
 303       }
 304     }
 305     if (DynamicDumpSharedSpaces) {
 306       _klass = DynamicArchive::original_to_target(info._klass);
 307     }
 308     ArchivePtrMarker::mark_pointer(&_klass);
 309   }
 310 
 311   bool matches(int clsfile_size, int clsfile_crc32) const {
 312     return crc()->_clsfile_size  == clsfile_size &&
 313            crc()->_clsfile_crc32 == clsfile_crc32;
 314   }
 315 
 316   Symbol* get_constraint_name(int i) {
 317     return (Symbol*)(SharedBaseAddress + verifier_constraint_at(i)->_name);
 318   }
 319   Symbol* get_constraint_from_name(int i) {
 320     return (Symbol*)(SharedBaseAddress + verifier_constraint_at(i)->_from_name);
 321   }
 322 
 323   char get_constraint_flag(int i) {
 324     check_constraint_offset(i);
 325     return verifier_constraint_flags()[i];
 326   }
 327 
 328 private:
 329   // ArchiveCompactor::allocate() has reserved a pointer immediately before
 330   // archived InstanceKlasses. We can use this slot to do a quick
 331   // lookup of InstanceKlass* -> RunTimeSharedClassInfo* without
 332   // building a new hashtable.
 333   //
 334   //  info_pointer_addr(klass) --> 0x0100   RunTimeSharedClassInfo*
 335   //  InstanceKlass* klass     --> 0x0108   <C++ vtbl>
 336   //                               0x0110   fields from Klass ...
 337   static RunTimeSharedClassInfo** info_pointer_addr(InstanceKlass* klass) {
 338     return &((RunTimeSharedClassInfo**)klass)[-1];
 339   }
 340 
 341 public:
 342   static RunTimeSharedClassInfo* get_for(InstanceKlass* klass) {
 343     return *info_pointer_addr(klass);
 344   }
 345   static void set_for(InstanceKlass* klass, RunTimeSharedClassInfo* record) {
 346     if (DynamicDumpSharedSpaces) {
 347       klass = DynamicArchive::original_to_buffer(klass);
 348       *info_pointer_addr(klass) = DynamicArchive::buffer_to_target(record);
 349     } else {
 350       *info_pointer_addr(klass) = record;
 351     }
 352 
 353     ArchivePtrMarker::mark_pointer(info_pointer_addr(klass));
 354   }
 355 
 356   // Used by RunTimeSharedDictionary to implement OffsetCompactHashtable::EQUALS
 357   static inline bool EQUALS(
 358        const RunTimeSharedClassInfo* value, Symbol* key, int len_unused) {
 359     return (value->_klass->name() == key);
 360   }
 361 };
 362 
 363 class RunTimeSharedDictionary : public OffsetCompactHashtable<
 364   Symbol*,
 365   const RunTimeSharedClassInfo*,
 366   RunTimeSharedClassInfo::EQUALS> {};
 367 
 368 static DumpTimeSharedClassTable* _dumptime_table = NULL;
 369 // SystemDictionaries in the base layer static archive
 370 static RunTimeSharedDictionary _builtin_dictionary;
 371 static RunTimeSharedDictionary _unregistered_dictionary;
 372 // SystemDictionaries in the top layer dynamic archive
 373 static RunTimeSharedDictionary _dynamic_builtin_dictionary;
 374 static RunTimeSharedDictionary _dynamic_unregistered_dictionary;
 375 
 376 oop SystemDictionaryShared::shared_protection_domain(int index) {
 377   return _shared_protection_domains->obj_at(index);
 378 }
 379 
 380 oop SystemDictionaryShared::shared_jar_url(int index) {
 381   return _shared_jar_urls->obj_at(index);
 382 }
 383 
 384 oop SystemDictionaryShared::shared_jar_manifest(int index) {
 385   return _shared_jar_manifests->obj_at(index);
 386 }
 387 
 388 
 389 Handle SystemDictionaryShared::get_shared_jar_manifest(int shared_path_index, TRAPS) {
 390   Handle manifest ;
 391   if (shared_jar_manifest(shared_path_index) == NULL) {
 392     SharedClassPathEntry* ent = FileMapInfo::shared_path(shared_path_index);
 393     long size = ent->manifest_size();
 394     if (size <= 0) {
 395       return Handle();
 396     }
 397 
 398     // ByteArrayInputStream bais = new ByteArrayInputStream(buf);
 399     const char* src = ent->manifest();
 400     assert(src != NULL, "No Manifest data");
 401     typeArrayOop buf = oopFactory::new_byteArray(size, CHECK_NH);
 402     typeArrayHandle bufhandle(THREAD, buf);
 403     ArrayAccess<>::arraycopy_from_native(reinterpret_cast<const jbyte*>(src),
 404                                          buf, typeArrayOopDesc::element_offset<jbyte>(0), size);
 405 
 406     Handle bais = JavaCalls::construct_new_instance(SystemDictionary::ByteArrayInputStream_klass(),
 407                       vmSymbols::byte_array_void_signature(),
 408                       bufhandle, CHECK_NH);
 409 
 410     // manifest = new Manifest(bais)
 411     manifest = JavaCalls::construct_new_instance(SystemDictionary::Jar_Manifest_klass(),
 412                       vmSymbols::input_stream_void_signature(),
 413                       bais, CHECK_NH);
 414     atomic_set_shared_jar_manifest(shared_path_index, manifest());
 415   }
 416 
 417   manifest = Handle(THREAD, shared_jar_manifest(shared_path_index));
 418   assert(manifest.not_null(), "sanity");
 419   return manifest;
 420 }
 421 
 422 Handle SystemDictionaryShared::get_shared_jar_url(int shared_path_index, TRAPS) {
 423   Handle url_h;
 424   if (shared_jar_url(shared_path_index) == NULL) {
 425     JavaValue result(T_OBJECT);
 426     const char* path = FileMapInfo::shared_path_name(shared_path_index);
 427     Handle path_string = java_lang_String::create_from_str(path, CHECK_(url_h));
 428     Klass* classLoaders_klass =
 429         SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 430     JavaCalls::call_static(&result, classLoaders_klass,
 431                            vmSymbols::toFileURL_name(),
 432                            vmSymbols::toFileURL_signature(),
 433                            path_string, CHECK_(url_h));
 434 
 435     atomic_set_shared_jar_url(shared_path_index, (oop)result.get_jobject());
 436   }
 437 
 438   url_h = Handle(THREAD, shared_jar_url(shared_path_index));
 439   assert(url_h.not_null(), "sanity");
 440   return url_h;
 441 }
 442 
 443 Handle SystemDictionaryShared::get_package_name(Symbol* class_name, TRAPS) {
 444   ResourceMark rm(THREAD);
 445   Handle pkgname_string;
 446   Symbol* pkg = ClassLoader::package_from_class_name(class_name);
 447   if (pkg != NULL) { // Package prefix found
 448     const char* pkgname = pkg->as_klass_external_name();
 449     pkgname_string = java_lang_String::create_from_str(pkgname,
 450                                                        CHECK_(pkgname_string));
 451   }
 452   return pkgname_string;
 453 }
 454 
 455 // Define Package for shared app classes from JAR file and also checks for
 456 // package sealing (all done in Java code)
 457 // See http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html
 458 void SystemDictionaryShared::define_shared_package(Symbol*  class_name,
 459                                                    Handle class_loader,
 460                                                    Handle manifest,
 461                                                    Handle url,
 462                                                    TRAPS) {
 463   assert(SystemDictionary::is_system_class_loader(class_loader()), "unexpected class loader");
 464   // get_package_name() returns a NULL handle if the class is in unnamed package
 465   Handle pkgname_string = get_package_name(class_name, CHECK);
 466   if (pkgname_string.not_null()) {
 467     Klass* app_classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
 468     JavaValue result(T_OBJECT);
 469     JavaCallArguments args(3);
 470     args.set_receiver(class_loader);
 471     args.push_oop(pkgname_string);
 472     args.push_oop(manifest);
 473     args.push_oop(url);
 474     JavaCalls::call_virtual(&result, app_classLoader_klass,
 475                             vmSymbols::defineOrCheckPackage_name(),
 476                             vmSymbols::defineOrCheckPackage_signature(),
 477                             &args,
 478                             CHECK);
 479   }
 480 }
 481 
 482 // Define Package for shared app/platform classes from named module
 483 void SystemDictionaryShared::define_shared_package(Symbol* class_name,
 484                                                    Handle class_loader,
 485                                                    ModuleEntry* mod_entry,
 486                                                    TRAPS) {
 487   assert(mod_entry != NULL, "module_entry should not be NULL");
 488   Handle module_handle(THREAD, mod_entry->module());
 489 
 490   Handle pkg_name = get_package_name(class_name, CHECK);
 491   assert(pkg_name.not_null(), "Package should not be null for class in named module");
 492 
 493   Klass* classLoader_klass;
 494   if (SystemDictionary::is_system_class_loader(class_loader())) {
 495     classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass();
 496   } else {
 497     assert(SystemDictionary::is_platform_class_loader(class_loader()), "unexpected classloader");
 498     classLoader_klass = SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass();
 499   }
 500 
 501   JavaValue result(T_OBJECT);
 502   JavaCallArguments args(2);
 503   args.set_receiver(class_loader);
 504   args.push_oop(pkg_name);
 505   args.push_oop(module_handle);
 506   JavaCalls::call_virtual(&result, classLoader_klass,
 507                           vmSymbols::definePackage_name(),
 508                           vmSymbols::definePackage_signature(),
 509                           &args,
 510                           CHECK);
 511 }
 512 
 513 // Get the ProtectionDomain associated with the CodeSource from the classloader.
 514 Handle SystemDictionaryShared::get_protection_domain_from_classloader(Handle class_loader,
 515                                                                       Handle url, TRAPS) {
 516   // CodeSource cs = new CodeSource(url, null);
 517   Handle cs = JavaCalls::construct_new_instance(SystemDictionary::CodeSource_klass(),
 518                   vmSymbols::url_code_signer_array_void_signature(),
 519                   url, Handle(), CHECK_NH);
 520 
 521   // protection_domain = SecureClassLoader.getProtectionDomain(cs);
 522   Klass* secureClassLoader_klass = SystemDictionary::SecureClassLoader_klass();
 523   JavaValue obj_result(T_OBJECT);
 524   JavaCalls::call_virtual(&obj_result, class_loader, secureClassLoader_klass,
 525                           vmSymbols::getProtectionDomain_name(),
 526                           vmSymbols::getProtectionDomain_signature(),
 527                           cs, CHECK_NH);
 528   return Handle(THREAD, (oop)obj_result.get_jobject());
 529 }
 530 
 531 // Returns the ProtectionDomain associated with the JAR file identified by the url.
 532 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 533                                                             int shared_path_index,
 534                                                             Handle url,
 535                                                             TRAPS) {
 536   Handle protection_domain;
 537   if (shared_protection_domain(shared_path_index) == NULL) {
 538     Handle pd = get_protection_domain_from_classloader(class_loader, url, THREAD);
 539     atomic_set_shared_protection_domain(shared_path_index, pd());
 540   }
 541 
 542   // Acquire from the cache because if another thread beats the current one to
 543   // set the shared protection_domain and the atomic_set fails, the current thread
 544   // needs to get the updated protection_domain from the cache.
 545   protection_domain = Handle(THREAD, shared_protection_domain(shared_path_index));
 546   assert(protection_domain.not_null(), "sanity");
 547   return protection_domain;
 548 }
 549 
 550 // Returns the ProtectionDomain associated with the moduleEntry.
 551 Handle SystemDictionaryShared::get_shared_protection_domain(Handle class_loader,
 552                                                             ModuleEntry* mod, TRAPS) {
 553   ClassLoaderData *loader_data = mod->loader_data();
 554   if (mod->shared_protection_domain() == NULL) {
 555     Symbol* location = mod->location();
 556     if (location != NULL) {
 557       Handle location_string = java_lang_String::create_from_symbol(
 558                                      location, CHECK_NH);
 559       Handle url;
 560       JavaValue result(T_OBJECT);
 561       if (location->starts_with("jrt:/")) {
 562         url = JavaCalls::construct_new_instance(SystemDictionary::URL_klass(),
 563                                                 vmSymbols::string_void_signature(),
 564                                                 location_string, CHECK_NH);
 565       } else {
 566         Klass* classLoaders_klass =
 567           SystemDictionary::jdk_internal_loader_ClassLoaders_klass();
 568         JavaCalls::call_static(&result, classLoaders_klass, vmSymbols::toFileURL_name(),
 569                                vmSymbols::toFileURL_signature(),
 570                                location_string, CHECK_NH);
 571         url = Handle(THREAD, (oop)result.get_jobject());
 572       }
 573 
 574       Handle pd = get_protection_domain_from_classloader(class_loader, url,
 575                                                          CHECK_NH);
 576       mod->set_shared_protection_domain(loader_data, pd);
 577     }
 578   }
 579 
 580   Handle protection_domain(THREAD, mod->shared_protection_domain());
 581   assert(protection_domain.not_null(), "sanity");
 582   return protection_domain;
 583 }
 584 
 585 // Initializes the java.lang.Package and java.security.ProtectionDomain objects associated with
 586 // the given InstanceKlass.
 587 // Returns the ProtectionDomain for the InstanceKlass.
 588 Handle SystemDictionaryShared::init_security_info(Handle class_loader, InstanceKlass* ik, TRAPS) {
 589   Handle pd;
 590 
 591   if (ik != NULL) {
 592     int index = ik->shared_classpath_index();
 593     assert(index >= 0, "Sanity");
 594     SharedClassPathEntry* ent = FileMapInfo::shared_path(index);
 595     Symbol* class_name = ik->name();
 596 
 597     if (ent->is_modules_image()) {
 598       // For shared app/platform classes originated from the run-time image:
 599       //   The ProtectionDomains are cached in the corresponding ModuleEntries
 600       //   for fast access by the VM.
 601       ResourceMark rm;
 602       ClassLoaderData *loader_data =
 603                 ClassLoaderData::class_loader_data(class_loader());
 604       PackageEntryTable* pkgEntryTable = loader_data->packages();
 605       TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
 606       if (pkg_name != NULL) {
 607         PackageEntry* pkg_entry = pkgEntryTable->lookup_only(pkg_name);
 608         if (pkg_entry != NULL) {
 609           ModuleEntry* mod_entry = pkg_entry->module();
 610           pd = get_shared_protection_domain(class_loader, mod_entry, THREAD);
 611           define_shared_package(class_name, class_loader, mod_entry, CHECK_(pd));
 612         }
 613       }
 614     } else {
 615       // For shared app/platform classes originated from JAR files on the class path:
 616       //   Each of the 3 SystemDictionaryShared::_shared_xxx arrays has the same length
 617       //   as the shared classpath table in the shared archive (see
 618       //   FileMap::_shared_path_table in filemap.hpp for details).
 619       //
 620       //   If a shared InstanceKlass k is loaded from the class path, let
 621       //
 622       //     index = k->shared_classpath_index():
 623       //
 624       //   FileMap::_shared_path_table[index] identifies the JAR file that contains k.
 625       //
 626       //   k's protection domain is:
 627       //
 628       //     ProtectionDomain pd = _shared_protection_domains[index];
 629       //
 630       //   and k's Package is initialized using
 631       //
 632       //     manifest = _shared_jar_manifests[index];
 633       //     url = _shared_jar_urls[index];
 634       //     define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 635       //
 636       //   Note that if an element of these 3 _shared_xxx arrays is NULL, it will be initialized by
 637       //   the corresponding SystemDictionaryShared::get_shared_xxx() function.
 638       Handle manifest = get_shared_jar_manifest(index, CHECK_(pd));
 639       Handle url = get_shared_jar_url(index, CHECK_(pd));
 640       define_shared_package(class_name, class_loader, manifest, url, CHECK_(pd));
 641       pd = get_shared_protection_domain(class_loader, index, url, CHECK_(pd));
 642     }
 643   }
 644   return pd;
 645 }
 646 
 647 bool SystemDictionaryShared::is_sharing_possible(ClassLoaderData* loader_data) {
 648   oop class_loader = loader_data->class_loader();
 649   return (class_loader == NULL ||
 650           SystemDictionary::is_system_class_loader(class_loader) ||
 651           SystemDictionary::is_platform_class_loader(class_loader));
 652 }
 653 
 654 // Currently AppCDS only archives classes from the run-time image, the
 655 // -Xbootclasspath/a path, the class path, and the module path.
 656 //
 657 // Check if a shared class can be loaded by the specific classloader. Following
 658 // are the "visible" archived classes for different classloaders.
 659 //
 660 // NULL classloader:
 661 //   - see SystemDictionary::is_shared_class_visible()
 662 // Platform classloader:
 663 //   - Module class from runtime image. ModuleEntry must be defined in the
 664 //     classloader.
 665 // App classloader:
 666 //   - Module Class from runtime image and module path. ModuleEntry must be defined in the
 667 //     classloader.
 668 //   - Class from -cp. The class must have no PackageEntry defined in any of the
 669 //     boot/platform/app classloader, or must be in the unnamed module defined in the
 670 //     AppClassLoader.
 671 bool SystemDictionaryShared::is_shared_class_visible_for_classloader(
 672                                                      InstanceKlass* ik,
 673                                                      Handle class_loader,
 674                                                      Symbol* pkg_name,
 675                                                      PackageEntry* pkg_entry,
 676                                                      ModuleEntry* mod_entry,
 677                                                      TRAPS) {
 678   assert(class_loader.not_null(), "Class loader should not be NULL");
 679   assert(Universe::is_module_initialized(), "Module system is not initialized");
 680   ResourceMark rm(THREAD);
 681 
 682   int path_index = ik->shared_classpath_index();
 683   SharedClassPathEntry* ent =
 684             (SharedClassPathEntry*)FileMapInfo::shared_path(path_index);
 685 
 686   if (SystemDictionary::is_platform_class_loader(class_loader())) {
 687     assert(ent != NULL, "shared class for PlatformClassLoader should have valid SharedClassPathEntry");
 688     // The PlatformClassLoader can only load archived class originated from the
 689     // run-time image. The class' PackageEntry/ModuleEntry must be
 690     // defined by the PlatformClassLoader.
 691     if (mod_entry != NULL) {
 692       // PackageEntry/ModuleEntry is found in the classloader. Check if the
 693       // ModuleEntry's location agrees with the archived class' origination.
 694       if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 695         return true; // Module class from the runtime image
 696       }
 697     }
 698   } else if (SystemDictionary::is_system_class_loader(class_loader())) {
 699     assert(ent != NULL, "shared class for system loader should have valid SharedClassPathEntry");
 700     if (pkg_name == NULL) {
 701       // The archived class is in the unnamed package. Currently, the boot image
 702       // does not contain any class in the unnamed package.
 703       assert(!ent->is_modules_image(), "Class in the unnamed package must be from the classpath");
 704       if (path_index >= ClassLoaderExt::app_class_paths_start_index()) {
 705         assert(path_index < ClassLoaderExt::app_module_paths_start_index(), "invalid path_index");
 706         return true;
 707       }
 708     } else {
 709       // Check if this is from a PackageEntry/ModuleEntry defined in the AppClassloader.
 710       if (pkg_entry == NULL) {
 711         // It's not guaranteed that the class is from the classpath if the
 712         // PackageEntry cannot be found from the AppClassloader. Need to check
 713         // the boot and platform classloader as well.
 714         if (get_package_entry(pkg_name, ClassLoaderData::class_loader_data_or_null(SystemDictionary::java_platform_loader())) == NULL &&
 715             get_package_entry(pkg_name, ClassLoaderData::the_null_class_loader_data()) == NULL) {
 716           // The PackageEntry is not defined in any of the boot/platform/app classloaders.
 717           // The archived class must from -cp path and not from the runtime image.
 718           if (!ent->is_modules_image() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 719                                           path_index < ClassLoaderExt::app_module_paths_start_index()) {
 720             return true;
 721           }
 722         }
 723       } else if (mod_entry != NULL) {
 724         // The package/module is defined in the AppClassLoader. We support
 725         // archiving application module class from the runtime image or from
 726         // a named module from a module path.
 727         // Packages from the -cp path are in the unnamed_module.
 728         if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
 729           // shared module class from runtime image
 730           return true;
 731         } else if (pkg_entry->in_unnamed_module() && path_index >= ClassLoaderExt::app_class_paths_start_index() &&
 732             path_index < ClassLoaderExt::app_module_paths_start_index()) {
 733           // shared class from -cp
 734           DEBUG_ONLY( \
 735             ClassLoaderData* loader_data = class_loader_data(class_loader); \
 736             assert(mod_entry == loader_data->unnamed_module(), "the unnamed module is not defined in the classloader");)
 737           return true;
 738         } else {
 739           if(!pkg_entry->in_unnamed_module() &&
 740               (path_index >= ClassLoaderExt::app_module_paths_start_index())&&
 741               (path_index < FileMapInfo::get_number_of_shared_paths()) &&
 742               (strcmp(ent->name(), ClassLoader::skip_uri_protocol(mod_entry->location()->as_C_string())) == 0)) {
 743             // shared module class from module path
 744             return true;
 745           } else {
 746             assert(path_index < FileMapInfo::get_number_of_shared_paths(), "invalid path_index");
 747           }
 748         }
 749       }
 750     }
 751   } else {
 752     // TEMP: if a shared class can be found by a custom loader, consider it visible now.
 753     // FIXME: is this actually correct?
 754     return true;
 755   }
 756   return false;
 757 }
 758 
 759 bool SystemDictionaryShared::has_platform_or_app_classes() {
 760   if (FileMapInfo::current_info()->has_platform_or_app_classes()) {
 761     return true;
 762   }
 763   if (DynamicArchive::is_mapped() &&
 764       FileMapInfo::dynamic_info()->has_platform_or_app_classes()) {
 765     return true;
 766   }
 767   return false;
 768 }
 769 
 770 // The following stack shows how this code is reached:
 771 //
 772 //   [0] SystemDictionaryShared::find_or_load_shared_class()
 773 //   [1] JVM_FindLoadedClass
 774 //   [2] java.lang.ClassLoader.findLoadedClass0()
 775 //   [3] java.lang.ClassLoader.findLoadedClass()
 776 //   [4] jdk.internal.loader.BuiltinClassLoader.loadClassOrNull()
 777 //   [5] jdk.internal.loader.BuiltinClassLoader.loadClass()
 778 //   [6] jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(), or
 779 //       jdk.internal.loader.ClassLoaders$PlatformClassLoader.loadClass()
 780 //
 781 // AppCDS supports fast class loading for these 2 built-in class loaders:
 782 //    jdk.internal.loader.ClassLoaders$PlatformClassLoader
 783 //    jdk.internal.loader.ClassLoaders$AppClassLoader
 784 // with the following assumptions (based on the JDK core library source code):
 785 //
 786 // [a] these two loaders use the BuiltinClassLoader.loadClassOrNull() to
 787 //     load the named class.
 788 // [b] BuiltinClassLoader.loadClassOrNull() first calls findLoadedClass(name).
 789 // [c] At this point, if we can find the named class inside the
 790 //     shared_dictionary, we can perform further checks (see
 791 //     is_shared_class_visible_for_classloader() to ensure that this class
 792 //     was loaded by the same class loader during dump time.
 793 //
 794 // Given these assumptions, we intercept the findLoadedClass() call to invoke
 795 // SystemDictionaryShared::find_or_load_shared_class() to load the shared class from
 796 // the archive for the 2 built-in class loaders. This way,
 797 // we can improve start-up because we avoid decoding the classfile,
 798 // and avoid delegating to the parent loader.
 799 //
 800 // NOTE: there's a lot of assumption about the Java code. If any of that change, this
 801 // needs to be redesigned.
 802 
 803 InstanceKlass* SystemDictionaryShared::find_or_load_shared_class(
 804                  Symbol* name, Handle class_loader, TRAPS) {
 805   InstanceKlass* k = NULL;
 806   if (UseSharedSpaces) {
 807     if (!has_platform_or_app_classes()) {
 808       return NULL;
 809     }
 810 
 811     if (SystemDictionary::is_system_class_loader(class_loader()) ||
 812         SystemDictionary::is_platform_class_loader(class_loader())) {
 813       // Fix for 4474172; see evaluation for more details
 814       class_loader = Handle(
 815         THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 816       ClassLoaderData *loader_data = register_loader(class_loader);
 817       Dictionary* dictionary = loader_data->dictionary();
 818 
 819       unsigned int d_hash = dictionary->compute_hash(name);
 820 
 821       bool DoObjectLock = true;
 822       if (is_parallelCapable(class_loader)) {
 823         DoObjectLock = false;
 824       }
 825 
 826       // Make sure we are synchronized on the class loader before we proceed
 827       //
 828       // Note: currently, find_or_load_shared_class is called only from
 829       // JVM_FindLoadedClass and used for PlatformClassLoader and AppClassLoader,
 830       // which are parallel-capable loaders, so this lock is NOT taken.
 831       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 832       check_loader_lock_contention(lockObject, THREAD);
 833       ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 834 
 835       {
 836         MutexLocker mu(THREAD, SystemDictionary_lock);
 837         InstanceKlass* check = find_class(d_hash, name, dictionary);
 838         if (check != NULL) {
 839           return check;
 840         }
 841       }
 842 
 843       k = load_shared_class_for_builtin_loader(name, class_loader, THREAD);
 844       if (k != NULL) {
 845         define_instance_class(k, CHECK_NULL);
 846       }
 847     }
 848   }
 849   return k;
 850 }
 851 
 852 InstanceKlass* SystemDictionaryShared::load_shared_class_for_builtin_loader(
 853                  Symbol* class_name, Handle class_loader, TRAPS) {
 854   assert(UseSharedSpaces, "must be");
 855   InstanceKlass* ik = find_builtin_class(class_name);
 856 
 857   if (ik != NULL) {
 858     if ((ik->is_shared_app_class() &&
 859          SystemDictionary::is_system_class_loader(class_loader()))  ||
 860         (ik->is_shared_platform_class() &&
 861          SystemDictionary::is_platform_class_loader(class_loader()))) {
 862       Handle protection_domain =
 863         SystemDictionaryShared::init_security_info(class_loader, ik, CHECK_NULL);
 864       return load_shared_class(ik, class_loader, protection_domain, NULL, THREAD);
 865     }
 866   }
 867   return NULL;
 868 }
 869 
 870 void SystemDictionaryShared::oops_do(OopClosure* f) {
 871   f->do_oop((oop*)&_shared_protection_domains);
 872   f->do_oop((oop*)&_shared_jar_urls);
 873   f->do_oop((oop*)&_shared_jar_manifests);
 874 }
 875 
 876 void SystemDictionaryShared::allocate_shared_protection_domain_array(int size, TRAPS) {
 877   if (_shared_protection_domains == NULL) {
 878     _shared_protection_domains = oopFactory::new_objArray(
 879         SystemDictionary::ProtectionDomain_klass(), size, CHECK);
 880   }
 881 }
 882 
 883 void SystemDictionaryShared::allocate_shared_jar_url_array(int size, TRAPS) {
 884   if (_shared_jar_urls == NULL) {
 885     _shared_jar_urls = oopFactory::new_objArray(
 886         SystemDictionary::URL_klass(), size, CHECK);
 887   }
 888 }
 889 
 890 void SystemDictionaryShared::allocate_shared_jar_manifest_array(int size, TRAPS) {
 891   if (_shared_jar_manifests == NULL) {
 892     _shared_jar_manifests = oopFactory::new_objArray(
 893         SystemDictionary::Jar_Manifest_klass(), size, CHECK);
 894   }
 895 }
 896 
 897 void SystemDictionaryShared::allocate_shared_data_arrays(int size, TRAPS) {
 898   allocate_shared_protection_domain_array(size, CHECK);
 899   allocate_shared_jar_url_array(size, CHECK);
 900   allocate_shared_jar_manifest_array(size, CHECK);
 901 }
 902 
 903 // This function is called for loading only UNREGISTERED classes
 904 InstanceKlass* SystemDictionaryShared::lookup_from_stream(Symbol* class_name,
 905                                                           Handle class_loader,
 906                                                           Handle protection_domain,
 907                                                           const ClassFileStream* cfs,
 908                                                           TRAPS) {
 909   if (!UseSharedSpaces) {
 910     return NULL;
 911   }
 912   if (class_name == NULL) {  // don't do this for anonymous classes
 913     return NULL;
 914   }
 915   if (class_loader.is_null() ||
 916       SystemDictionary::is_system_class_loader(class_loader()) ||
 917       SystemDictionary::is_platform_class_loader(class_loader())) {
 918     // Do nothing for the BUILTIN loaders.
 919     return NULL;
 920   }
 921 
 922   const RunTimeSharedClassInfo* record = find_record(&_unregistered_dictionary, &_dynamic_unregistered_dictionary, class_name);
 923   if (record == NULL) {
 924     return NULL;
 925   }
 926 
 927   int clsfile_size  = cfs->length();
 928   int clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
 929 
 930   if (!record->matches(clsfile_size, clsfile_crc32)) {
 931     return NULL;
 932   }
 933 
 934   return acquire_class_for_current_thread(record->_klass, class_loader,
 935                                           protection_domain, cfs,
 936                                           THREAD);
 937 }
 938 
 939 InstanceKlass* SystemDictionaryShared::acquire_class_for_current_thread(
 940                    InstanceKlass *ik,
 941                    Handle class_loader,
 942                    Handle protection_domain,
 943                    const ClassFileStream *cfs,
 944                    TRAPS) {
 945   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
 946 
 947   {
 948     MutexLocker mu(THREAD, SharedDictionary_lock);
 949     if (ik->class_loader_data() != NULL) {
 950       //    ik is already loaded (by this loader or by a different loader)
 951       // or ik is being loaded by a different thread (by this loader or by a different loader)
 952       return NULL;
 953     }
 954 
 955     // No other thread has acquired this yet, so give it to *this thread*
 956     ik->set_class_loader_data(loader_data);
 957   }
 958 
 959   // No longer holding SharedDictionary_lock
 960   // No need to lock, as <ik> can be held only by a single thread.
 961   loader_data->add_class(ik);
 962 
 963   // Load and check super/interfaces, restore unsharable info
 964   InstanceKlass* shared_klass = load_shared_class(ik, class_loader, protection_domain,
 965                                                   cfs, THREAD);
 966   if (shared_klass == NULL || HAS_PENDING_EXCEPTION) {
 967     // TODO: clean up <ik> so it can be used again
 968     return NULL;
 969   }
 970 
 971   return shared_klass;
 972 }
 973 
 974 static ResourceHashtable<
 975   Symbol*, bool,
 976   primitive_hash<Symbol*>,
 977   primitive_equals<Symbol*>,
 978   6661,                             // prime number
 979   ResourceObj::C_HEAP> _loaded_unregistered_classes;
 980 
 981 bool SystemDictionaryShared::add_unregistered_class(InstanceKlass* k, TRAPS) {
 982   assert(DumpSharedSpaces, "only when dumping");
 983 
 984   Symbol* name = k->name();
 985   if (_loaded_unregistered_classes.get(name) != NULL) {
 986     // We don't allow duplicated unregistered classes of the same name.
 987     return false;
 988   } else {
 989     bool isnew = _loaded_unregistered_classes.put(name, true);
 990     assert(isnew, "sanity");
 991     MutexLocker mu_r(THREAD, Compile_lock); // add_to_hierarchy asserts this.
 992     SystemDictionary::add_to_hierarchy(k, CHECK_false);
 993     return true;
 994   }
 995 }
 996 
 997 // This function is called to resolve the super/interfaces of shared classes for
 998 // non-built-in loaders. E.g., ChildClass in the below example
 999 // where "super:" (and optionally "interface:") have been specified.
1000 //
1001 // java/lang/Object id: 0
1002 // Interface   id: 2 super: 0 source: cust.jar
1003 // ChildClass  id: 4 super: 0 interfaces: 2 source: cust.jar
1004 InstanceKlass* SystemDictionaryShared::dump_time_resolve_super_or_fail(
1005     Symbol* child_name, Symbol* class_name, Handle class_loader,
1006     Handle protection_domain, bool is_superclass, TRAPS) {
1007 
1008   assert(DumpSharedSpaces, "only when dumping");
1009 
1010   ClassListParser* parser = ClassListParser::instance();
1011   if (parser == NULL) {
1012     // We're still loading the well-known classes, before the ClassListParser is created.
1013     return NULL;
1014   }
1015   if (child_name->equals(parser->current_class_name())) {
1016     // When this function is called, all the numbered super and interface types
1017     // must have already been loaded. Hence this function is never recursively called.
1018     if (is_superclass) {
1019       return parser->lookup_super_for_current_class(class_name);
1020     } else {
1021       return parser->lookup_interface_for_current_class(class_name);
1022     }
1023   } else {
1024     // The VM is not trying to resolve a super type of parser->current_class_name().
1025     // Instead, it's resolving an error class (because parser->current_class_name() has
1026     // failed parsing or verification). Don't do anything here.
1027     return NULL;
1028   }
1029 }
1030 
1031 DumpTimeSharedClassInfo* SystemDictionaryShared::find_or_allocate_info_for(InstanceKlass* k) {
1032   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1033   if (_dumptime_table == NULL) {
1034     _dumptime_table = new (ResourceObj::C_HEAP, mtClass)DumpTimeSharedClassTable();
1035   }
1036   return _dumptime_table->find_or_allocate_info_for(k);
1037 }
1038 
1039 void SystemDictionaryShared::set_shared_class_misc_info(InstanceKlass* k, ClassFileStream* cfs) {
1040   Arguments::assert_is_dumping_archive();
1041   assert(!is_builtin(k), "must be unregistered class");
1042   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1043   info->_clsfile_size  = cfs->length();
1044   info->_clsfile_crc32 = ClassLoader::crc32(0, (const char*)cfs->buffer(), cfs->length());
1045 }
1046 
1047 void SystemDictionaryShared::init_dumptime_info(InstanceKlass* k) {
1048   (void)find_or_allocate_info_for(k);
1049 }
1050 
1051 void SystemDictionaryShared::remove_dumptime_info(InstanceKlass* k) {
1052   MutexLocker ml(DumpTimeTable_lock, Mutex::_no_safepoint_check_flag);
1053   DumpTimeSharedClassInfo* p = _dumptime_table->get(k);
1054   if (p == NULL) {
1055     return;
1056   }
1057   if (p->_verifier_constraints != NULL) {
1058     for (int i = 0; i < p->_verifier_constraints->length(); i++) {
1059       DumpTimeSharedClassInfo::DTConstraint constraint = p->_verifier_constraints->at(i);
1060       if (constraint._name != NULL ) {
1061         constraint._name->decrement_refcount();
1062       }
1063       if (constraint._from_name != NULL ) {
1064         constraint._from_name->decrement_refcount();
1065       }
1066     }
1067     FREE_C_HEAP_ARRAY(DTConstraint, p->_verifier_constraints);
1068     p->_verifier_constraints = NULL;
1069   }
1070   FREE_C_HEAP_ARRAY(char, p->_verifier_constraint_flags);
1071   p->_verifier_constraint_flags = NULL;
1072   _dumptime_table->remove(k);
1073 }
1074 
1075 bool SystemDictionaryShared::is_jfr_event_class(InstanceKlass *k) {
1076   while (k) {
1077     if (k->name()->equals("jdk/internal/event/Event")) {
1078       return true;
1079     }
1080     k = k->java_super();
1081   }
1082   return false;
1083 }
1084 
1085 void SystemDictionaryShared::warn_excluded(InstanceKlass* k, const char* reason) {
1086   ResourceMark rm;
1087   log_warning(cds)("Skipping %s: %s", k->name()->as_C_string(), reason);
1088 }
1089 
1090 bool SystemDictionaryShared::should_be_excluded(InstanceKlass* k) {
1091   if (k->class_loader_data()->is_unsafe_anonymous()) {
1092     warn_excluded(k, "Unsafe anonymous class");
1093     return true; // unsafe anonymous classes are not archived, skip
1094   }
1095   if (k->is_in_error_state()) {
1096     warn_excluded(k, "In error state");
1097     return true;
1098   }
1099   if (k->has_been_redefined()) {
1100     warn_excluded(k, "Has been redefined");
1101     return true;
1102   }
1103   if (k->shared_classpath_index() < 0 && is_builtin(k)) {
1104     // These are classes loaded from unsupported locations (such as those loaded by JVMTI native
1105     // agent during dump time).
1106     warn_excluded(k, "Unsupported location");
1107     return true;
1108   }
1109   if (k->signers() != NULL) {
1110     // We cannot include signed classes in the archive because the certificates
1111     // used during dump time may be different than those used during
1112     // runtime (due to expiration, etc).
1113     warn_excluded(k, "Signed JAR");
1114     return true;
1115   }
1116   if (is_jfr_event_class(k)) {
1117     // We cannot include JFR event classes because they need runtime-specific
1118     // instrumentation in order to work with -XX:FlightRecorderOptions=retransform=false.
1119     // There are only a small number of these classes, so it's not worthwhile to
1120     // support them and make CDS more complicated.
1121     warn_excluded(k, "JFR event class");
1122     return true;
1123   }
1124   if (k->init_state() < InstanceKlass::linked) {
1125     // In CDS dumping, we will attempt to link all classes. Those that fail to link will
1126     // be recorded in DumpTimeSharedClassInfo.
1127     Arguments::assert_is_dumping_archive();
1128 
1129     // TODO -- rethink how this can be handled.
1130     // We should try to link ik, however, we can't do it here because
1131     // 1. We are at VM exit
1132     // 2. linking a class may cause other classes to be loaded, which means
1133     //    a custom ClassLoader.loadClass() may be called, at a point where the
1134     //    class loader doesn't expect it.
1135     if (has_class_failed_verification(k)) {
1136       warn_excluded(k, "Failed verification");
1137     } else {
1138       warn_excluded(k, "Not linked");
1139     }
1140     return true;
1141   }
1142   if (k->major_version() < 50 /*JAVA_6_VERSION*/) {
1143     ResourceMark rm;
1144     log_warning(cds)("Pre JDK 6 class not supported by CDS: %u.%u %s",
1145                      k->major_version(),  k->minor_version(), k->name()->as_C_string());
1146     return true;
1147   }
1148 
1149   InstanceKlass* super = k->java_super();
1150   if (super != NULL && should_be_excluded(super)) {
1151     ResourceMark rm;
1152     log_warning(cds)("Skipping %s: super class %s is excluded", k->name()->as_C_string(), super->name()->as_C_string());
1153     return true;
1154   }
1155 
1156   Array<InstanceKlass*>* interfaces = k->local_interfaces();
1157   int len = interfaces->length();
1158   for (int i = 0; i < len; i++) {
1159     InstanceKlass* intf = interfaces->at(i);
1160     if (should_be_excluded(intf)) {
1161       log_warning(cds)("Skipping %s: interface %s is excluded", k->name()->as_C_string(), intf->name()->as_C_string());
1162       return true;
1163     }
1164   }
1165 
1166   return false;
1167 }
1168 
1169 // k is a class before relocating by ArchiveCompactor
1170 void SystemDictionaryShared::validate_before_archiving(InstanceKlass* k) {
1171   ResourceMark rm;
1172   const char* name = k->name()->as_C_string();
1173   DumpTimeSharedClassInfo* info = _dumptime_table->get(k);
1174   assert(_no_class_loading_should_happen, "class loading must be disabled");
1175   guarantee(info != NULL, "Class %s must be entered into _dumptime_table", name);
1176   guarantee(!info->is_excluded(), "Should not attempt to archive excluded class %s", name);
1177   if (is_builtin(k)) {
1178     guarantee(!k->is_shared_unregistered_class(),
1179               "Class loader type must be set for BUILTIN class %s", name);
1180   } else {
1181     guarantee(k->is_shared_unregistered_class(),
1182               "Class loader type must not be set for UNREGISTERED class %s", name);
1183   }
1184 }
1185 
1186 class ExcludeDumpTimeSharedClasses : StackObj {
1187 public:
1188   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1189     if (SystemDictionaryShared::should_be_excluded(k)) {
1190       info.set_excluded();
1191     }
1192     return true; // keep on iterating
1193   }
1194 };
1195 
1196 void SystemDictionaryShared::check_excluded_classes() {
1197   ExcludeDumpTimeSharedClasses excl;
1198   _dumptime_table->iterate(&excl);
1199   _dumptime_table->update_counts();
1200 }
1201 
1202 bool SystemDictionaryShared::is_excluded_class(InstanceKlass* k) {
1203   assert(_no_class_loading_should_happen, "sanity");
1204   Arguments::assert_is_dumping_archive();
1205   return find_or_allocate_info_for(k)->is_excluded();
1206 }
1207 
1208 void SystemDictionaryShared::set_class_has_failed_verification(InstanceKlass* ik) {
1209   Arguments::assert_is_dumping_archive();
1210   find_or_allocate_info_for(ik)->set_failed_verification();
1211 }
1212 
1213 bool SystemDictionaryShared::has_class_failed_verification(InstanceKlass* ik) {
1214   Arguments::assert_is_dumping_archive();
1215   if (_dumptime_table == NULL) {
1216     assert(DynamicDumpSharedSpaces, "sanity");
1217     assert(ik->is_shared(), "must be a shared class in the static archive");
1218     return false;
1219   }
1220   DumpTimeSharedClassInfo* p = _dumptime_table->get(ik);
1221   return (p == NULL) ? false : p->failed_verification();
1222 }
1223 
1224 class IterateDumpTimeSharedClassTable : StackObj {
1225   MetaspaceClosure *_it;
1226 public:
1227   IterateDumpTimeSharedClassTable(MetaspaceClosure* it) : _it(it) {}
1228 
1229   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1230     if (!info.is_excluded()) {
1231       info.metaspace_pointers_do(_it);
1232     }
1233     return true; // keep on iterating
1234   }
1235 };
1236 
1237 void SystemDictionaryShared::dumptime_classes_do(class MetaspaceClosure* it) {
1238   IterateDumpTimeSharedClassTable iter(it);
1239   _dumptime_table->iterate(&iter);
1240 }
1241 
1242 bool SystemDictionaryShared::add_verification_constraint(InstanceKlass* k, Symbol* name,
1243          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1244   Arguments::assert_is_dumping_archive();
1245   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1246   info->add_verification_constraint(k, name, from_name, from_field_is_protected,
1247                                     from_is_array, from_is_object);
1248 
1249   if (DynamicDumpSharedSpaces) {
1250     // For dynamic dumping, we can resolve all the constraint classes for all class loaders during
1251     // the initial run prior to creating the archive before vm exit. We will also perform verification
1252     // check when running with the archive.
1253     return false;
1254   } else {
1255     if (is_builtin(k)) {
1256       // For builtin class loaders, we can try to complete the verification check at dump time,
1257       // because we can resolve all the constraint classes. We will also perform verification check
1258       // when running with the archive.
1259       return false;
1260     } else {
1261       // For non-builtin class loaders, we cannot complete the verification check at dump time,
1262       // because at dump time we don't know how to resolve classes for such loaders.
1263       return true;
1264     }
1265   }
1266 }
1267 
1268 void DumpTimeSharedClassInfo::add_verification_constraint(InstanceKlass* k, Symbol* name,
1269          Symbol* from_name, bool from_field_is_protected, bool from_is_array, bool from_is_object) {
1270   if (_verifier_constraints == NULL) {
1271     _verifier_constraints = new(ResourceObj::C_HEAP, mtClass) GrowableArray<DTConstraint>(4, true, mtClass);
1272   }
1273   if (_verifier_constraint_flags == NULL) {
1274     _verifier_constraint_flags = new(ResourceObj::C_HEAP, mtClass) GrowableArray<char>(4, true, mtClass);
1275   }
1276   GrowableArray<DTConstraint>* vc_array = _verifier_constraints;
1277   for (int i = 0; i < vc_array->length(); i++) {
1278     DTConstraint* p = vc_array->adr_at(i);
1279     if (name == p->_name && from_name == p->_from_name) {
1280       return;
1281     }
1282   }
1283   DTConstraint cons(name, from_name);
1284   vc_array->append(cons);
1285 
1286   GrowableArray<char>* vcflags_array = _verifier_constraint_flags;
1287   char c = 0;
1288   c |= from_field_is_protected ? SystemDictionaryShared::FROM_FIELD_IS_PROTECTED : 0;
1289   c |= from_is_array           ? SystemDictionaryShared::FROM_IS_ARRAY           : 0;
1290   c |= from_is_object          ? SystemDictionaryShared::FROM_IS_OBJECT          : 0;
1291   vcflags_array->append(c);
1292 
1293   if (log_is_enabled(Trace, cds, verification)) {
1294     ResourceMark rm;
1295     log_trace(cds, verification)("add_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1296                                  k->external_name(), from_name->as_klass_external_name(),
1297                                  name->as_klass_external_name(), c);
1298   }
1299 }
1300 
1301 void SystemDictionaryShared::check_verification_constraints(InstanceKlass* klass,
1302                                                             TRAPS) {
1303   assert(!DumpSharedSpaces && UseSharedSpaces, "called at run time with CDS enabled only");
1304   RunTimeSharedClassInfo* record = RunTimeSharedClassInfo::get_for(klass);
1305 
1306   int length = record->_num_constraints;
1307   if (length > 0) {
1308     for (int i = 0; i < length; i++) {
1309       Symbol* name      = record->get_constraint_name(i);
1310       Symbol* from_name = record->get_constraint_from_name(i);
1311       char c            = record->get_constraint_flag(i);
1312 
1313       if (log_is_enabled(Trace, cds, verification)) {
1314         ResourceMark rm(THREAD);
1315         log_trace(cds, verification)("check_verification_constraint: %s: %s must be subclass of %s [0x%x]",
1316                                      klass->external_name(), from_name->as_klass_external_name(),
1317                                      name->as_klass_external_name(), c);
1318       }
1319 
1320       bool from_field_is_protected = (c & SystemDictionaryShared::FROM_FIELD_IS_PROTECTED) ? true : false;
1321       bool from_is_array           = (c & SystemDictionaryShared::FROM_IS_ARRAY)           ? true : false;
1322       bool from_is_object          = (c & SystemDictionaryShared::FROM_IS_OBJECT)          ? true : false;
1323 
1324       bool ok = VerificationType::resolve_and_check_assignability(klass, name,
1325          from_name, from_field_is_protected, from_is_array, from_is_object, CHECK);
1326       if (!ok) {
1327         ResourceMark rm(THREAD);
1328         stringStream ss;
1329 
1330         ss.print_cr("Bad type on operand stack");
1331         ss.print_cr("Exception Details:");
1332         ss.print_cr("  Location:\n    %s", klass->name()->as_C_string());
1333         ss.print_cr("  Reason:\n    Type '%s' is not assignable to '%s'",
1334                     from_name->as_quoted_ascii(), name->as_quoted_ascii());
1335         THROW_MSG(vmSymbols::java_lang_VerifyError(), ss.as_string());
1336       }
1337     }
1338   }
1339 }
1340 
1341 class EstimateSizeForArchive : StackObj {
1342   size_t _shared_class_info_size;
1343   int _num_builtin_klasses;
1344   int _num_unregistered_klasses;
1345 
1346 public:
1347   EstimateSizeForArchive() {
1348     _shared_class_info_size = 0;
1349     _num_builtin_klasses = 0;
1350     _num_unregistered_klasses = 0;
1351   }
1352 
1353   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1354     if (!info.is_excluded()) {
1355       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_constraints());
1356       _shared_class_info_size += align_up(byte_size, BytesPerWord);
1357     }
1358     return true; // keep on iterating
1359   }
1360 
1361   size_t total() {
1362     return _shared_class_info_size;
1363   }
1364 };
1365 
1366 size_t SystemDictionaryShared::estimate_size_for_archive() {
1367   EstimateSizeForArchive est;
1368   _dumptime_table->iterate(&est);
1369   return est.total() +
1370     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(true)) +
1371     CompactHashtableWriter::estimate_size(_dumptime_table->count_of(false));
1372 }
1373 
1374 class CopySharedClassInfoToArchive : StackObj {
1375   CompactHashtableWriter* _writer;
1376   bool _is_builtin;
1377 public:
1378   CopySharedClassInfoToArchive(CompactHashtableWriter* writer,
1379                                bool is_builtin,
1380                                bool is_static_archive)
1381     : _writer(writer), _is_builtin(is_builtin) {}
1382 
1383   bool do_entry(InstanceKlass* k, DumpTimeSharedClassInfo& info) {
1384     if (!info.is_excluded() && info.is_builtin() == _is_builtin) {
1385       size_t byte_size = RunTimeSharedClassInfo::byte_size(info._klass, info.num_constraints());
1386       RunTimeSharedClassInfo* record;
1387       record = (RunTimeSharedClassInfo*)MetaspaceShared::read_only_space_alloc(byte_size);
1388       record->init(info);
1389 
1390       unsigned int hash;
1391       Symbol* name = info._klass->name();
1392       if (DynamicDumpSharedSpaces) {
1393         name = DynamicArchive::original_to_target(name);
1394       }
1395       hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
1396       u4 delta;
1397       if (DynamicDumpSharedSpaces) {
1398         delta = MetaspaceShared::object_delta_u4(DynamicArchive::buffer_to_target(record));
1399       } else {
1400         delta = MetaspaceShared::object_delta_u4(record);
1401       }
1402       _writer->add(hash, delta);
1403       if (log_is_enabled(Trace, cds, hashtables)) {
1404         ResourceMark rm;
1405         log_trace(cds,hashtables)("%s dictionary: %s", (_is_builtin ? "builtin" : "unregistered"), info._klass->external_name());
1406       }
1407 
1408       // Save this for quick runtime lookup of InstanceKlass* -> RunTimeSharedClassInfo*
1409       RunTimeSharedClassInfo::set_for(info._klass, record);
1410     }
1411     return true; // keep on iterating
1412   }
1413 };
1414 
1415 void SystemDictionaryShared::write_dictionary(RunTimeSharedDictionary* dictionary,
1416                                               bool is_builtin,
1417                                               bool is_static_archive) {
1418   CompactHashtableStats stats;
1419   dictionary->reset();
1420   CompactHashtableWriter writer(_dumptime_table->count_of(is_builtin), &stats);
1421   CopySharedClassInfoToArchive copy(&writer, is_builtin, is_static_archive);
1422   _dumptime_table->iterate(&copy);
1423   writer.dump(dictionary, is_builtin ? "builtin dictionary" : "unregistered dictionary");
1424 }
1425 
1426 void SystemDictionaryShared::write_to_archive(bool is_static_archive) {
1427   if (is_static_archive) {
1428     write_dictionary(&_builtin_dictionary, true);
1429     write_dictionary(&_unregistered_dictionary, false);
1430   } else {
1431     write_dictionary(&_dynamic_builtin_dictionary, true);
1432     write_dictionary(&_dynamic_unregistered_dictionary, false);
1433   }
1434 }
1435 
1436 void SystemDictionaryShared::serialize_dictionary_headers(SerializeClosure* soc,
1437                                                           bool is_static_archive) {
1438   if (is_static_archive) {
1439     _builtin_dictionary.serialize_header(soc);
1440     _unregistered_dictionary.serialize_header(soc);
1441   } else {
1442     _dynamic_builtin_dictionary.serialize_header(soc);
1443     _dynamic_unregistered_dictionary.serialize_header(soc);
1444   }
1445 }
1446 
1447 void SystemDictionaryShared::serialize_well_known_klasses(SerializeClosure* soc) {
1448   for (int i = FIRST_WKID; i < WKID_LIMIT; i++) {
1449     soc->do_ptr((void**)&_well_known_klasses[i]);
1450   }
1451 }
1452 
1453 const RunTimeSharedClassInfo*
1454 SystemDictionaryShared::find_record(RunTimeSharedDictionary* static_dict, RunTimeSharedDictionary* dynamic_dict, Symbol* name) {
1455   if (!UseSharedSpaces || !name->is_shared()) {
1456     // The names of all shared classes must also be a shared Symbol.
1457     return NULL;
1458   }
1459 
1460   unsigned int hash = SystemDictionaryShared::hash_for_shared_dictionary(name);
1461   const RunTimeSharedClassInfo* record = NULL;
1462   if (!MetaspaceShared::is_shared_dynamic(name)) {
1463     // The names of all shared classes in the static dict must also be in the
1464     // static archive
1465     record = static_dict->lookup(name, hash, 0);
1466   }
1467 
1468   if (record == NULL && DynamicArchive::is_mapped()) {
1469     record = dynamic_dict->lookup(name, hash, 0);
1470   }
1471 
1472   return record;
1473 }
1474 
1475 InstanceKlass* SystemDictionaryShared::find_builtin_class(Symbol* name) {
1476   const RunTimeSharedClassInfo* record = find_record(&_builtin_dictionary, &_dynamic_builtin_dictionary, name);
1477   if (record != NULL) {
1478     return record->_klass;
1479   } else {
1480     return NULL;
1481   }
1482 }
1483 
1484 void SystemDictionaryShared::update_shared_entry(InstanceKlass* k, int id) {
1485   assert(DumpSharedSpaces, "supported only when dumping");
1486   DumpTimeSharedClassInfo* info = find_or_allocate_info_for(k);
1487   info->_id = id;
1488 }
1489 
1490 class SharedDictionaryPrinter : StackObj {
1491   outputStream* _st;
1492   int _index;
1493 public:
1494   SharedDictionaryPrinter(outputStream* st) : _st(st), _index(0) {}
1495 
1496   void do_value(const RunTimeSharedClassInfo* record) {
1497     ResourceMark rm;
1498     _st->print_cr("%4d:  %s", (_index++), record->_klass->external_name());
1499   }
1500 };
1501 
1502 void SystemDictionaryShared::print_on(outputStream* st) {
1503   if (UseSharedSpaces) {
1504     st->print_cr("Shared Dictionary");
1505     SharedDictionaryPrinter p(st);
1506     _builtin_dictionary.iterate(&p);
1507     _unregistered_dictionary.iterate(&p);
1508     if (DynamicArchive::is_mapped()) {
1509       _dynamic_builtin_dictionary.iterate(&p);
1510       _unregistered_dictionary.iterate(&p);
1511     }
1512   }
1513 }
1514 
1515 void SystemDictionaryShared::print_table_statistics(outputStream* st) {
1516   if (UseSharedSpaces) {
1517     _builtin_dictionary.print_table_statistics(st, "Builtin Shared Dictionary");
1518     _unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1519     if (DynamicArchive::is_mapped()) {
1520       _dynamic_builtin_dictionary.print_table_statistics(st, "Dynamic Builtin Shared Dictionary");
1521       _dynamic_unregistered_dictionary.print_table_statistics(st, "Unregistered Shared Dictionary");
1522     }
1523   }
1524 }
1525 
1526 bool SystemDictionaryShared::empty_dumptime_table() {
1527   if (_dumptime_table == NULL) {
1528     return true;
1529   }
1530   _dumptime_table->update_counts();
1531   if (_dumptime_table->count_of(true) == 0 && _dumptime_table->count_of(false) == 0){
1532     return true;
1533   }
1534   return false;
1535 }