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