< prev index next >

src/hotspot/share/cds/classPrelinker.cpp

Print this page

   1 /*
   2  * Copyright (c) 2022, 2023, 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 "cds/archiveBuilder.hpp"


  27 #include "cds/cdsConfig.hpp"

  28 #include "cds/classPrelinker.hpp"









  29 #include "classfile/systemDictionary.hpp"

  30 #include "classfile/vmClasses.hpp"







  31 #include "memory/resourceArea.hpp"
  32 #include "oops/constantPool.inline.hpp"

  33 #include "oops/instanceKlass.hpp"
  34 #include "oops/klass.inline.hpp"

  35 #include "runtime/handles.inline.hpp"






  36 
  37 ClassPrelinker::ClassesTable* ClassPrelinker::_processed_classes = nullptr;
  38 ClassPrelinker::ClassesTable* ClassPrelinker::_vm_classes = nullptr;












  39 
  40 bool ClassPrelinker::is_vm_class(InstanceKlass* ik) {
  41   return (_vm_classes->get(ik) != nullptr);
  42 }
  43 




  44 void ClassPrelinker::add_one_vm_class(InstanceKlass* ik) {
  45   bool created;

  46   _vm_classes->put_if_absent(ik, &created);
  47   if (created) {

  48     InstanceKlass* super = ik->java_super();
  49     if (super != nullptr) {
  50       add_one_vm_class(super);
  51     }
  52     Array<InstanceKlass*>* ifs = ik->local_interfaces();
  53     for (int i = 0; i < ifs->length(); i++) {
  54       add_one_vm_class(ifs->at(i));
  55     }
  56   }
  57 }
  58 
  59 void ClassPrelinker::initialize() {
  60   assert(_vm_classes == nullptr, "must be");
  61   _vm_classes = new (mtClass)ClassesTable();

  62   _processed_classes = new (mtClass)ClassesTable();


  63   for (auto id : EnumRange<vmClassID>{}) {
  64     add_one_vm_class(vmClasses::klass_at(id));
  65   }





































































































  66 }
  67 
  68 void ClassPrelinker::dispose() {
  69   assert(_vm_classes != nullptr, "must be");
  70   delete _vm_classes;
  71   delete _processed_classes;


  72   _vm_classes = nullptr;
  73   _processed_classes = nullptr;


  74 }
  75 
  76 bool ClassPrelinker::can_archive_resolved_klass(ConstantPool* cp, int cp_index) {
  77   assert(!is_in_archivebuilder_buffer(cp), "sanity");
  78   assert(cp->tag_at(cp_index).is_klass(), "must be resolved");
  79 
  80   Klass* resolved_klass = cp->resolved_klass_at(cp_index);
  81   assert(resolved_klass != nullptr, "must be");
  82 
  83   return can_archive_resolved_klass(cp->pool_holder(), resolved_klass);
  84 }
  85 
  86 bool ClassPrelinker::can_archive_resolved_klass(InstanceKlass* cp_holder, Klass* resolved_klass) {
  87   assert(!is_in_archivebuilder_buffer(cp_holder), "sanity");
  88   assert(!is_in_archivebuilder_buffer(resolved_klass), "sanity");
  89 
















  90   if (resolved_klass->is_instance_klass()) {
  91     InstanceKlass* ik = InstanceKlass::cast(resolved_klass);
  92     if (is_vm_class(ik)) { // These are safe to resolve. See is_vm_class declaration.
  93       assert(ik->is_shared_boot_class(), "vmClasses must be loaded by boot loader");
  94       if (cp_holder->is_shared_boot_class()) {
  95         // For now, do this for boot loader only. Other loaders
  96         // must go through ConstantPool::klass_at_impl at runtime
  97         // to put this class in their directory.
  98 
  99         // TODO: we can support the platform and app loaders as well, if we
 100         // preload the vmClasses into these two loaders during VM bootstrap.
 101         return true;
 102       }
 103     }
 104 
 105     if (cp_holder->is_subtype_of(ik)) {
 106       // All super types of ik will be resolved in ik->class_loader() before
 107       // ik is defined in this loader, so it's safe to archive the resolved klass reference.
 108       return true;
 109     }
 110 

















 111     // TODO -- allow objArray classes, too
 112   }
 113 
 114   return false;
 115 }
 116 









































 117 void ClassPrelinker::dumptime_resolve_constants(InstanceKlass* ik, TRAPS) {
 118   constantPoolHandle cp(THREAD, ik->constants());
 119   if (cp->cache() == nullptr || cp->reference_map() == nullptr) {
 120     // The cache may be null if the pool_holder klass fails verification
 121     // at dump time due to missing dependencies.
 122     return;
 123   }
 124 
 125   bool first_time;
 126   _processed_classes->put_if_absent(ik, &first_time);
 127   if (!first_time) {
 128     // We have already resolved the constants in class, so no need to do it again.
 129     return;
 130   }
 131 

 132   for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
 133     switch (cp->tag_at(cp_index).value()) {
 134     case JVM_CONSTANT_UnresolvedClass:
 135       maybe_resolve_class(cp, cp_index, CHECK);
 136       break;
 137 
 138     case JVM_CONSTANT_String:
 139       resolve_string(cp, cp_index, CHECK); // may throw OOM when interning strings.
 140       break;






















 141     }
 142   }
 143 }
 144 
 145 Klass* ClassPrelinker::find_loaded_class(JavaThread* THREAD, oop class_loader, Symbol* name) {
 146   HandleMark hm(THREAD);
 147   Handle h_loader(THREAD, class_loader);
 148   Klass* k = SystemDictionary::find_instance_or_array_klass(THREAD, name,

 149                                                             h_loader,
 150                                                             Handle());
 151   if (k != nullptr) {
 152     return k;
 153   }
 154   if (class_loader == SystemDictionary::java_system_loader()) {
 155     return find_loaded_class(THREAD, SystemDictionary::java_platform_loader(), name);
 156   } else if (class_loader == SystemDictionary::java_platform_loader()) {
 157     return find_loaded_class(THREAD, nullptr, name);





 158   }
 159 
 160   return nullptr;
 161 }
 162 
 163 Klass* ClassPrelinker::maybe_resolve_class(constantPoolHandle cp, int cp_index, TRAPS) {
 164   assert(!is_in_archivebuilder_buffer(cp()), "sanity");
 165   InstanceKlass* cp_holder = cp->pool_holder();
 166   if (!cp_holder->is_shared_boot_class() &&
 167       !cp_holder->is_shared_platform_class() &&
 168       !cp_holder->is_shared_app_class()) {
 169     // Don't trust custom loaders, as they may not be well-behaved
 170     // when resolving classes.
 171     return nullptr;
 172   }
 173 
 174   Symbol* name = cp->klass_name_at(cp_index);
 175   Klass* resolved_klass = find_loaded_class(THREAD, cp_holder->class_loader(), name);
 176   if (resolved_klass != nullptr && can_archive_resolved_klass(cp_holder, resolved_klass)) {
 177     Klass* k = cp->klass_at(cp_index, CHECK_NULL); // Should fail only with OOM
 178     assert(k == resolved_klass, "must be");
 179   }
 180 
 181   return resolved_klass;
 182 }
 183 
 184 #if INCLUDE_CDS_JAVA_HEAP
 185 void ClassPrelinker::resolve_string(constantPoolHandle cp, int cp_index, TRAPS) {
 186   if (CDSConfig::is_dumping_heap()) {
 187     int cache_index = cp->cp_to_object_index(cp_index);
 188     ConstantPool::string_at_impl(cp, cp_index, cache_index, CHECK);
 189   }
 190 }
 191 #endif
 192 















































































































































































































































































 193 #ifdef ASSERT
 194 bool ClassPrelinker::is_in_archivebuilder_buffer(address p) {
 195   if (!Thread::current()->is_VM_thread() || ArchiveBuilder::current() == nullptr) {
 196     return false;
 197   } else {
 198     return ArchiveBuilder::current()->is_in_buffer_space(p);
 199   }
 200 }
 201 #endif


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































   1 /*
   2  * Copyright (c) 2022, 2024, 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 "cds/archiveBuilder.hpp"
  27 #include "cds/archiveUtils.inline.hpp"
  28 #include "cds/cdsAccess.hpp"
  29 #include "cds/cdsConfig.hpp"
  30 #include "cds/cdsProtectionDomain.hpp"
  31 #include "cds/classPrelinker.hpp"
  32 #include "cds/classListWriter.hpp"
  33 #include "cds/heapShared.hpp"
  34 #include "cds/lambdaFormInvokers.inline.hpp"
  35 #include "cds/regeneratedClasses.hpp"
  36 #include "classfile/classLoader.hpp"
  37 #include "classfile/classLoaderDataGraph.hpp"
  38 #include "classfile/classLoaderExt.hpp"
  39 #include "classfile/dictionary.hpp"
  40 #include "classfile/symbolTable.hpp"
  41 #include "classfile/systemDictionary.hpp"
  42 #include "classfile/systemDictionaryShared.hpp"
  43 #include "classfile/vmClasses.hpp"
  44 #include "compiler/compilationPolicy.hpp"
  45 #include "gc/shared/gcVMOperations.hpp"
  46 #include "interpreter/bytecode.hpp"
  47 #include "interpreter/bytecodeStream.hpp"
  48 #include "interpreter/interpreterRuntime.hpp"
  49 #include "interpreter/linkResolver.hpp"
  50 #include "memory/oopFactory.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "oops/constantPool.inline.hpp"
  53 #include "oops/fieldStreams.inline.hpp"
  54 #include "oops/instanceKlass.hpp"
  55 #include "oops/klass.inline.hpp"
  56 #include "oops/trainingData.hpp"
  57 #include "runtime/handles.inline.hpp"
  58 #include "runtime/javaCalls.hpp"
  59 #include "runtime/perfData.inline.hpp"
  60 #include "runtime/timer.hpp"
  61 #include "runtime/signature.hpp"
  62 #include "runtime/vmOperations.hpp"
  63 #include "services/management.hpp"
  64 
  65 ClassPrelinker::ClassesTable* ClassPrelinker::_processed_classes = nullptr;
  66 ClassPrelinker::ClassesTable* ClassPrelinker::_vm_classes = nullptr;
  67 ClassPrelinker::ClassesTable* ClassPrelinker::_preloaded_classes = nullptr;
  68 ClassPrelinker::ClassesTable* ClassPrelinker::_platform_initiated_classes = nullptr;
  69 ClassPrelinker::ClassesTable* ClassPrelinker::_app_initiated_classes = nullptr;
  70 int ClassPrelinker::_num_vm_klasses = 0;
  71 bool ClassPrelinker::_record_javabase_only = true;
  72 bool ClassPrelinker::_preload_javabase_only = true;
  73 ClassPrelinker::PreloadedKlasses ClassPrelinker::_static_preloaded_klasses;
  74 ClassPrelinker::PreloadedKlasses ClassPrelinker::_dynamic_preloaded_klasses;
  75 Array<InstanceKlass*>* ClassPrelinker::_unregistered_klasses_from_preimage = nullptr;
  76 
  77 static PerfCounter* _perf_classes_preloaded = nullptr;
  78 static PerfTickCounters* _perf_class_preload_counters = nullptr;
  79 
  80 bool ClassPrelinker::is_vm_class(InstanceKlass* ik) {
  81   return (_vm_classes->get(ik) != nullptr);
  82 }
  83 
  84 bool ClassPrelinker::is_preloaded_class(InstanceKlass* ik) {
  85   return (_preloaded_classes->get(ik) != nullptr);
  86 }
  87 
  88 void ClassPrelinker::add_one_vm_class(InstanceKlass* ik) {
  89   bool created;
  90   _preloaded_classes->put_if_absent(ik, &created);
  91   _vm_classes->put_if_absent(ik, &created);
  92   if (created) {
  93     ++ _num_vm_klasses;
  94     InstanceKlass* super = ik->java_super();
  95     if (super != nullptr) {
  96       add_one_vm_class(super);
  97     }
  98     Array<InstanceKlass*>* ifs = ik->local_interfaces();
  99     for (int i = 0; i < ifs->length(); i++) {
 100       add_one_vm_class(ifs->at(i));
 101     }
 102   }
 103 }
 104 
 105 void ClassPrelinker::initialize() {
 106   assert(_vm_classes == nullptr, "must be");
 107   _vm_classes = new (mtClass)ClassesTable();
 108   _preloaded_classes = new (mtClass)ClassesTable();
 109   _processed_classes = new (mtClass)ClassesTable();
 110   _platform_initiated_classes = new (mtClass)ClassesTable();
 111   _app_initiated_classes = new (mtClass)ClassesTable();
 112   for (auto id : EnumRange<vmClassID>{}) {
 113     add_one_vm_class(vmClasses::klass_at(id));
 114   }
 115   if (_static_preloaded_klasses._boot != nullptr && !CDSConfig::is_dumping_final_static_archive()) {
 116     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
 117     add_preloaded_klasses(_static_preloaded_klasses._boot);
 118     add_preloaded_klasses(_static_preloaded_klasses._boot2);
 119     add_preloaded_klasses(_static_preloaded_klasses._platform);
 120     add_preloaded_klasses(_static_preloaded_klasses._app);
 121 
 122     add_unrecorded_initiated_klasses(_platform_initiated_classes, _static_preloaded_klasses._platform_initiated);
 123     add_unrecorded_initiated_klasses(_app_initiated_classes, _static_preloaded_klasses._app_initiated);
 124   }
 125 
 126   // Record all the initiated classes that we used during dump time. This covers the verification constraints and
 127   // (resolved) class loader constraints.
 128   add_initiated_klasses_for_loader(ClassLoaderData::class_loader_data_or_null(SystemDictionary::java_platform_loader()),
 129                                    "platform", _platform_initiated_classes);
 130   add_initiated_klasses_for_loader(ClassLoaderData::class_loader_data_or_null(SystemDictionary::java_system_loader()),
 131                                    "app", _app_initiated_classes);
 132 }
 133 
 134 void ClassPrelinker::add_preloaded_klasses(Array<InstanceKlass*>* klasses) {
 135   for (int i = 0; i < klasses->length(); i++) {
 136     assert(klasses->at(i)->is_shared() && klasses->at(i)->is_loaded(), "must be");
 137     _preloaded_classes->put_when_absent(klasses->at(i), true);
 138   }
 139 }
 140 
 141 void ClassPrelinker::add_unrecorded_initiated_klasses(ClassesTable* table, Array<InstanceKlass*>* klasses) {
 142   // These initiated classes are already recorded in the static archive. There's no need to
 143   // record them again for the dynamic archive.
 144   assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
 145   bool need_to_record = false;
 146   for (int i = 0; i < klasses->length(); i++) {
 147     InstanceKlass* ik = klasses->at(i);
 148     table->put_when_absent(ik, need_to_record);
 149   }
 150 }
 151 
 152 void ClassPrelinker::add_extra_initiated_klasses(PreloadedKlasses* table) {
 153   if (table->_app->length() > 0) {
 154     // Add all public classes in boot/platform to the app loader. This speeds up
 155     // Class.forName() operations in frameworks.
 156     GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 157     for (GrowableArrayIterator<Klass*> it = klasses->begin(); it != klasses->end(); ++it) {
 158       Klass* k = *it;
 159       if (k->is_instance_klass() && !k->name()->starts_with("jdk/proxy")) { // FIXME add SystemDictionaryShared::is_archived_dynamic_proxy_class(ik)
 160         // TODO: only add classes that are visible to unnamed module in app loader.
 161         InstanceKlass* ik = InstanceKlass::cast(k);
 162         if (ik->is_public() && (ik->is_shared_boot_class() || ik->is_shared_platform_class())) {
 163           add_initiated_klass(_app_initiated_classes, "app", ik);
 164         }
 165       }
 166     }
 167   }
 168 }
 169 
 170 class ClassPrelinker::RecordInitiatedClassesClosure : public KlassClosure {
 171   ClassLoaderData* _loader_data;
 172   const char* _loader_name;
 173   ClassesTable* _table;
 174  public:
 175   RecordInitiatedClassesClosure(ClassLoaderData* loader_data, const char* loader_name, ClassesTable* table) :
 176     _loader_data(loader_data), _loader_name(loader_name), _table(table) {}
 177   virtual void do_klass(Klass* k) {
 178     if (k->is_instance_klass() && k->class_loader_data() != _loader_data) {
 179       add_initiated_klass(_table, _loader_name, InstanceKlass::cast(k));
 180     }
 181   }
 182 };
 183 
 184 void ClassPrelinker::add_initiated_klasses_for_loader(ClassLoaderData* loader_data, const char* loader_name, ClassesTable* table) {
 185   if (loader_data != nullptr) {
 186     MonitorLocker mu1(SystemDictionary_lock);
 187     RecordInitiatedClassesClosure mk(loader_data, loader_name, table);  
 188     loader_data->dictionary()->all_entries_do(&mk);
 189   }
 190 }
 191 
 192 // ik has a reference to target:
 193 //    - target is a declared supertype of ik, or
 194 //    - one of the constant pool entries in ik references target
 195 void ClassPrelinker::add_initiated_klass(InstanceKlass* ik, InstanceKlass* target) {
 196   if (ik->shared_class_loader_type() == target->shared_class_loader_type()) {
 197     return;
 198   }
 199 
 200   if (SystemDictionary::is_platform_class_loader(ik->class_loader())) {
 201     add_initiated_klass(_platform_initiated_classes, "platform", target);
 202   } else {
 203     assert(SystemDictionary::is_system_class_loader(ik->class_loader()), "must be");
 204     add_initiated_klass(_app_initiated_classes, "app", target);
 205   }
 206 }
 207 
 208 void ClassPrelinker::add_initiated_klass(ClassesTable* initiated_classes, const char* loader_name, InstanceKlass* target) {
 209   bool need_to_record = true;
 210   bool created;
 211   initiated_classes->put_if_absent(target, need_to_record, &created);
 212   if (created && log_is_enabled(Trace, cds, resolve)) {
 213     ResourceMark rm;
 214     log_trace(cds, resolve)("%s loader initiated %s", loader_name, target->external_name());
 215   }
 216 }
 217 
 218 void ClassPrelinker::dispose() {
 219   assert(_vm_classes != nullptr, "must be");
 220   delete _vm_classes;
 221   delete _processed_classes;
 222   delete _platform_initiated_classes;
 223   delete _app_initiated_classes;
 224   _vm_classes = nullptr;
 225   _processed_classes = nullptr;
 226   _platform_initiated_classes = nullptr;
 227   _app_initiated_classes = nullptr;
 228 }
 229 
 230 bool ClassPrelinker::can_archive_resolved_klass(ConstantPool* cp, int cp_index) {
 231   assert(!is_in_archivebuilder_buffer(cp), "sanity");
 232   assert(cp->tag_at(cp_index).is_klass(), "must be resolved");
 233 
 234   Klass* resolved_klass = cp->resolved_klass_at(cp_index);
 235   assert(resolved_klass != nullptr, "must be");
 236 
 237   return can_archive_resolved_klass(cp->pool_holder(), resolved_klass);
 238 }
 239 
 240 bool ClassPrelinker::can_archive_resolved_klass(InstanceKlass* cp_holder, Klass* resolved_klass) {
 241   assert(!is_in_archivebuilder_buffer(cp_holder), "sanity");
 242   assert(!is_in_archivebuilder_buffer(resolved_klass), "sanity");
 243 
 244 #if 0
 245   if (cp_holder->is_hidden()) {
 246     // TODO - what is needed for hidden classes?
 247     return false;
 248   }
 249 #endif
 250 
 251 #if 0
 252   if (DumpSharedSpaces && LambdaFormInvokers::may_be_regenerated_class(resolved_klass->name())) {
 253     // Hack -- there's a copy of the regenerated class in both dynamic and static archive.
 254     // When dynamic archive is loaded, we don't want pre-resolved CP entries in the static
 255     // archive to point to the wrong class.
 256     return false;
 257   }
 258 #endif
 259 
 260   if (resolved_klass->is_instance_klass()) {
 261     InstanceKlass* ik = InstanceKlass::cast(resolved_klass);












 262 
 263     if (cp_holder->is_subtype_of(ik)) {
 264       // All super types of ik will be resolved in ik->class_loader() before
 265       // ik is defined in this loader, so it's safe to archive the resolved klass reference.
 266       return true;
 267     }
 268 
 269     if (is_vm_class(cp_holder)) {
 270       return is_vm_class(ik);
 271     } else if (is_preloaded_class(ik)) {
 272       if (cp_holder->is_shared_platform_class()) {
 273         add_initiated_klass(cp_holder, ik);
 274         return true;
 275       } else if (cp_holder->is_shared_app_class()) {
 276         add_initiated_klass(cp_holder, ik);
 277         return true;
 278       } else if (cp_holder->is_shared_boot_class()) {
 279         assert(ik->class_loader() == nullptr, "a boot class can reference only boot classes");
 280         return true;
 281       } else if (cp_holder->is_hidden() && cp_holder->class_loader() == nullptr) { // FIXME -- use better checks!
 282         return true;
 283       }
 284     }
 285 
 286     // TODO -- allow objArray classes, too
 287   }
 288 
 289   return false;
 290 }
 291 
 292 Klass* ClassPrelinker::get_fmi_ref_resolved_archivable_klass(ConstantPool* cp, int cp_index) {
 293   assert(!is_in_archivebuilder_buffer(cp), "sanity");
 294 
 295   int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
 296   if (!cp->tag_at(klass_cp_index).is_klass()) {
 297     // Not yet resolved
 298     return nullptr;
 299   }
 300   Klass* k = cp->resolved_klass_at(klass_cp_index);
 301   if (!can_archive_resolved_klass(cp->pool_holder(), k)) {
 302     // When we access this field at runtime, the target klass may
 303     // have a different definition.
 304     return nullptr;
 305   }
 306   return k;
 307 }
 308 
 309 bool ClassPrelinker::can_archive_resolved_method(ConstantPool* cp, int cp_index) {
 310   assert(cp->tag_at(cp_index).is_method() ||
 311          cp->tag_at(cp_index).is_interface_method(), "must be");
 312   return get_fmi_ref_resolved_archivable_klass(cp, cp_index) != nullptr;
 313 }
 314 
 315 bool ClassPrelinker::can_archive_resolved_field(ConstantPool* cp, int cp_index) {
 316   assert(cp->tag_at(cp_index).is_field(), "must be");
 317 
 318   Klass* k = get_fmi_ref_resolved_archivable_klass(cp, cp_index);
 319   if (k == nullptr) {
 320     return false;
 321   }
 322 
 323   Symbol* field_name = cp->uncached_name_ref_at(cp_index);
 324   Symbol* field_sig = cp->uncached_signature_ref_at(cp_index);
 325   fieldDescriptor fd;
 326   if (k->find_field(field_name, field_sig, &fd) == NULL) {
 327     return false;
 328   }
 329 
 330   return true;
 331 }
 332 
 333 void ClassPrelinker::dumptime_resolve_constants(InstanceKlass* ik, TRAPS) {
 334   if (!ik->is_linked()) {



 335     return;
 336   }

 337   bool first_time;
 338   _processed_classes->put_if_absent(ik, &first_time);
 339   if (!first_time) {
 340     // We have already resolved the constants in class, so no need to do it again.
 341     return;
 342   }
 343 
 344   constantPoolHandle cp(THREAD, ik->constants());
 345   for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
 346     if (cp->tag_at(cp_index).value() == JVM_CONSTANT_String) {





 347       resolve_string(cp, cp_index, CHECK); // may throw OOM when interning strings.
 348     }
 349   }
 350 
 351   // Normally, we don't want to archive any CP entries that were not resolved
 352   // in the training run. Otherwise the AOT/JIT may inline too much code that has not
 353   // been executed.
 354   //
 355   // However, we want to aggressively resolve all klass/field/method constants for
 356   // LambdaForm Invoker Holder classes, Lambda Proxy classes, and LambdaForm classes,
 357   // so that the compiler can inline through them.
 358   if (SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
 359     bool eager_resolve = false;
 360 
 361     if (LambdaFormInvokers::may_be_regenerated_class(ik->name())) {
 362       eager_resolve = true;
 363     }
 364     if (ik->is_hidden() && HeapShared::is_archivable_hidden_klass(ik)) {
 365       eager_resolve = true;
 366     }
 367 
 368     if (eager_resolve) {
 369       preresolve_class_cp_entries(THREAD, ik, nullptr);
 370       preresolve_field_and_method_cp_entries(THREAD, ik, nullptr);
 371     }
 372   }
 373 }
 374 
 375 // This works only for the boot/platform/app loaders
 376 Klass* ClassPrelinker::find_loaded_class(Thread* current, oop class_loader, Symbol* name) {
 377   HandleMark hm(current);
 378   Handle h_loader(current, class_loader);
 379   Klass* k = SystemDictionary::find_instance_or_array_klass(current, name,
 380                                                             h_loader,
 381                                                             Handle());
 382   if (k != nullptr) {
 383     return k;
 384   }
 385   if (h_loader() == SystemDictionary::java_system_loader()) {
 386     return find_loaded_class(current, SystemDictionary::java_platform_loader(), name);
 387   } else if (h_loader() == SystemDictionary::java_platform_loader()) {
 388     return find_loaded_class(current, nullptr, name);
 389   } else {
 390     assert(h_loader() == nullptr, "This function only works for boot/platform/app loaders %p %p %p",
 391            cast_from_oop<address>(h_loader()),
 392            cast_from_oop<address>(SystemDictionary::java_system_loader()),
 393            cast_from_oop<address>(SystemDictionary::java_platform_loader()));
 394   }
 395 
 396   return nullptr;
 397 }
 398 
 399 Klass* ClassPrelinker::find_loaded_class(Thread* current, ConstantPool* cp, int class_cp_index) {
 400   Symbol* name = cp->klass_name_at(class_cp_index);
 401   return find_loaded_class(current, cp->pool_holder()->class_loader(), name);
















 402 }
 403 
 404 #if INCLUDE_CDS_JAVA_HEAP
 405 void ClassPrelinker::resolve_string(constantPoolHandle cp, int cp_index, TRAPS) {
 406   if (CDSConfig::is_dumping_heap()) {
 407     int cache_index = cp->cp_to_object_index(cp_index);
 408     ConstantPool::string_at_impl(cp, cp_index, cache_index, CHECK);
 409   }
 410 }
 411 #endif
 412 
 413 void ClassPrelinker::preresolve_class_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
 414   if (!PreloadSharedClasses) {
 415     return;
 416   }
 417   if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
 418     return;
 419   }
 420 
 421   JavaThread* THREAD = current;
 422   constantPoolHandle cp(THREAD, ik->constants());
 423   for (int cp_index = 1; cp_index < cp->length(); cp_index++) {
 424     if (cp->tag_at(cp_index).value() == JVM_CONSTANT_UnresolvedClass) {
 425       if (preresolve_list != nullptr && preresolve_list->at(cp_index) == false) {
 426         // This class was not resolved during trial run. Don't attempt to resolve it. Otherwise
 427         // the compiler may generate less efficient code.
 428         continue;
 429       }
 430       if (find_loaded_class(current, cp(), cp_index) == nullptr) {
 431         // Do not resolve any class that has not been loaded yet
 432         continue;
 433       }
 434       Klass* resolved_klass = cp->klass_at(cp_index, THREAD);
 435       if (HAS_PENDING_EXCEPTION) {
 436         CLEAR_PENDING_EXCEPTION; // just ignore
 437       } else {
 438         log_trace(cds, resolve)("Resolved class  [%3d] %s -> %s", cp_index, ik->external_name(),
 439                                 resolved_klass->external_name());
 440       }
 441     }
 442   }
 443 }
 444 
 445 void ClassPrelinker::preresolve_field_and_method_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
 446   JavaThread* THREAD = current;
 447   constantPoolHandle cp(THREAD, ik->constants());
 448   if (cp->cache() == nullptr) {
 449     return;
 450   }
 451   for (int i = 0; i < ik->methods()->length(); i++) {
 452     Method* m = ik->methods()->at(i);
 453     BytecodeStream bcs(methodHandle(THREAD, m));
 454     while (!bcs.is_last_bytecode()) {
 455       bcs.next();
 456       Bytecodes::Code raw_bc = bcs.raw_code();
 457       switch (raw_bc) {
 458       case Bytecodes::_getstatic:
 459       case Bytecodes::_putstatic:
 460       case Bytecodes::_getfield:
 461       case Bytecodes::_putfield:
 462         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
 463         if (HAS_PENDING_EXCEPTION) {
 464           CLEAR_PENDING_EXCEPTION; // just ignore
 465         }
 466         break;
 467       case Bytecodes::_invokehandle:
 468       case Bytecodes::_invokespecial:
 469       case Bytecodes::_invokevirtual:
 470       case Bytecodes::_invokeinterface:
 471       case Bytecodes::_invokestatic:
 472         maybe_resolve_fmi_ref(ik, m, raw_bc, bcs.get_index_u2(), preresolve_list, THREAD);
 473         if (HAS_PENDING_EXCEPTION) {
 474           CLEAR_PENDING_EXCEPTION; // just ignore
 475         }
 476         break;
 477       default:
 478         break;
 479       }
 480     }
 481   }
 482 }
 483 
 484 void ClassPrelinker::maybe_resolve_fmi_ref(InstanceKlass* ik, Method* m, Bytecodes::Code bc, int raw_index,
 485                                            GrowableArray<bool>* preresolve_list, TRAPS) {
 486   methodHandle mh(THREAD, m);
 487   constantPoolHandle cp(THREAD, ik->constants());
 488   HandleMark hm(THREAD);
 489   int cp_index;
 490 
 491   if (bc == Bytecodes::_invokehandle  ||
 492       bc == Bytecodes::_invokestatic  ||
 493       bc == Bytecodes::_invokespecial ||
 494       bc == Bytecodes::_invokevirtual ||
 495       bc == Bytecodes::_invokeinterface) {
 496     ResolvedMethodEntry* method_entry = cp->cache()->resolved_method_entry_at(raw_index);
 497     if (method_entry->is_resolved(bc)) {
 498       return;
 499     }
 500     cp_index = method_entry->constant_pool_index();
 501   } else {
 502     assert(bc == Bytecodes::_getfield  || bc == Bytecodes::_putfield ||
 503            bc == Bytecodes::_getstatic || bc == Bytecodes::_putstatic, "must be");
 504     cp_index = cp->cache()->resolved_field_entry_at(raw_index)->constant_pool_index();
 505   }
 506 
 507   if (preresolve_list != nullptr && preresolve_list->at(cp_index) == false) {
 508     // This field wasn't resolved during the trial run. Don't attempt to resolve it. Otherwise
 509     // the compiler may generate less efficient code.
 510     return;
 511   }
 512 
 513   int klass_cp_index = cp->uncached_klass_ref_index_at(cp_index);
 514   if (find_loaded_class(THREAD, cp(), klass_cp_index) == nullptr) {
 515     // Do not resolve any field/methods from a class that has not been loaded yet.
 516     return;
 517   }
 518   Klass* resolved_klass = cp->klass_ref_at(raw_index, bc, CHECK);
 519 
 520   const char* ref_kind = "";
 521   const char* is_static = "";
 522   const char* is_regen = "";
 523 
 524   if (RegeneratedClasses::is_a_regenerated_object((address)ik)) {
 525     is_regen = " (regenerated)";
 526   }
 527 
 528   switch (bc) {
 529   case Bytecodes::_getstatic:
 530   case Bytecodes::_putstatic:
 531     if (!VM_Version::supports_fast_class_init_checks()) {
 532       return; // Do not resolve since interpreter lacks fast clinit barriers support
 533     }
 534     InterpreterRuntime::resolve_get_put(bc, raw_index, mh, cp, false /*initialize_holder*/, CHECK);
 535     ref_kind = "field ";
 536     is_static = " *** static";
 537     break;
 538   case Bytecodes::_getfield:
 539   case Bytecodes::_putfield:
 540     InterpreterRuntime::resolve_get_put(bc, raw_index, mh, cp, false /*initialize_holder*/, CHECK);
 541     ref_kind = "field ";
 542     break;
 543 
 544   case Bytecodes::_invokestatic:
 545     if (!VM_Version::supports_fast_class_init_checks()) {
 546       return; // Do not resolve since interpreter lacks fast clinit barriers support
 547     }
 548     InterpreterRuntime::cds_resolve_invoke(bc, raw_index, mh, cp, CHECK);
 549     ref_kind = "method";
 550     is_static = " *** static";
 551     break;
 552 
 553   case Bytecodes::_invokevirtual:
 554   case Bytecodes::_invokespecial:
 555     InterpreterRuntime::cds_resolve_invoke(bc, raw_index, mh, cp, CHECK);
 556     ref_kind = "method";
 557     break;
 558 
 559   case Bytecodes::_invokeinterface:
 560     InterpreterRuntime::cds_resolve_invoke(bc, raw_index, mh, cp, CHECK);
 561     ref_kind = "interface method";
 562     break;
 563 
 564   case Bytecodes::_invokehandle:
 565     InterpreterRuntime::cds_resolve_invokehandle(raw_index, cp, CHECK);
 566     ref_kind = "method";
 567     break;
 568     break;
 569 
 570   default:
 571     ShouldNotReachHere();
 572   }
 573 
 574   if (log_is_enabled(Trace, cds, resolve)) {
 575     ResourceMark rm(THREAD);
 576     Symbol* name = cp->name_ref_at(raw_index, bc);
 577     Symbol* signature = cp->signature_ref_at(raw_index, bc);
 578     log_trace(cds, resolve)("Resolved %s [%3d] %s%s -> %s.%s:%s%s", ref_kind, cp_index,
 579                             ik->external_name(), is_regen,
 580                             resolved_klass->external_name(),
 581                             name->as_C_string(), signature->as_C_string(), is_static);
 582   }
 583 }
 584 
 585 void ClassPrelinker::preresolve_indy_cp_entries(JavaThread* current, InstanceKlass* ik, GrowableArray<bool>* preresolve_list) {
 586   JavaThread* THREAD = current;
 587   constantPoolHandle cp(THREAD, ik->constants());
 588   if (!ArchiveInvokeDynamic || cp->cache() == nullptr) {
 589     return;
 590   }
 591 
 592   assert(preresolve_list != nullptr, "preresolve_indy_cp_entries() should not be called for "
 593          "regenerated LambdaForm Invoker classes, which should not have indys anyway.");
 594 
 595   Array<ResolvedIndyEntry>* indy_entries = cp->cache()->resolved_indy_entries();
 596   for (int i = 0; i < indy_entries->length(); i++) {
 597     ResolvedIndyEntry* rie = indy_entries->adr_at(i);
 598     int cp_index = rie->constant_pool_index();
 599     if (preresolve_list->at(cp_index) == true && !rie->is_resolved() && is_indy_archivable(cp(), cp_index)) {
 600       InterpreterRuntime::cds_resolve_invokedynamic(ConstantPool::encode_invokedynamic_index(i), cp, THREAD);
 601       if (HAS_PENDING_EXCEPTION) {
 602         CLEAR_PENDING_EXCEPTION; // just ignore
 603       }
 604     }
 605   }
 606 }
 607 
 608 static GrowableArrayCHeap<char*, mtClassShared>* _invokedynamic_filter = nullptr;
 609 
 610 static bool has_clinit(InstanceKlass* ik) {
 611   if (ik->class_initializer() != nullptr) {
 612     return true;
 613   }
 614   InstanceKlass* super = ik->java_super();
 615   if (super != nullptr && has_clinit(super)) {
 616     return true;
 617   }
 618   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 619   int num_interfaces = interfaces->length();
 620   for (int index = 0; index < num_interfaces; index++) {
 621     InstanceKlass* intf = interfaces->at(index);
 622     if (has_clinit(intf)) {
 623       return true;
 624     }
 625   }
 626   return false;
 627 }
 628 
 629 bool ClassPrelinker::is_indy_archivable(ConstantPool* cp, int cp_index) {
 630   if (!ArchiveInvokeDynamic || !HeapShared::can_write()) {
 631     return false;
 632   }
 633 
 634   if (!SystemDictionaryShared::is_builtin(cp->pool_holder())) {
 635     return false;
 636   }
 637 
 638   int bsm = cp->bootstrap_method_ref_index_at(cp_index);
 639   int bsm_ref = cp->method_handle_index_at(bsm);
 640   Symbol* bsm_name = cp->uncached_name_ref_at(bsm_ref);
 641   Symbol* bsm_signature = cp->uncached_signature_ref_at(bsm_ref);
 642   Symbol* bsm_klass = cp->klass_name_at(cp->uncached_klass_ref_index_at(bsm_ref));
 643 
 644   // We currently support only string concat and LambdaMetafactory::metafactory()
 645 
 646   if (bsm_klass->equals("java/lang/invoke/StringConcatFactory") &&
 647       bsm_name->equals("makeConcatWithConstants")) {
 648     return true;
 649   }
 650 
 651   if (bsm_klass->equals("java/lang/invoke/LambdaMetafactory") &&
 652       ((bsm_name->equals("metafactory")    && bsm_signature->equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;")) ||
 653        (bsm_name->equals("altMetafactory") && bsm_signature->equals("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;")))) {
 654     SignatureStream ss(cp->uncached_signature_ref_at(cp_index));
 655     ss.skip_to_return_type();
 656     Symbol* type = ss.as_symbol(); // This is the interface type implemented by the lambda proxy
 657     InstanceKlass* holder = cp->pool_holder();
 658     Klass* k = find_loaded_class(Thread::current(), holder->class_loader(), type);
 659     if (k == nullptr) {
 660       return false;
 661     }
 662     if (!k->is_interface()) {
 663       // Might be a class not generated by javac
 664       return false;
 665     }
 666 
 667     if (has_clinit(InstanceKlass::cast(k))) {
 668       // We initialize the class of the archived lambda proxy at VM start-up, which will also initialize
 669       // the interface that it implements. If that interface has a clinit method, we can potentially
 670       // change program execution order. See test/hotspot/jtreg/runtime/cds/appcds/indy/IndyMiscTests.java
 671       if (log_is_enabled(Debug, cds, resolve)) {
 672         ResourceMark rm;
 673         log_debug(cds, resolve)("Cannot resolve Lambda proxy of interface type %s", k->external_name());
 674       }
 675       return false;
 676     }
 677 
 678     return true;
 679   }
 680 
 681   return false;
 682 }
 683 
 684 #ifdef ASSERT
 685 bool ClassPrelinker::is_in_archivebuilder_buffer(address p) {
 686   if (!Thread::current()->is_VM_thread() || ArchiveBuilder::current() == nullptr) {
 687     return false;
 688   } else {
 689     return ArchiveBuilder::current()->is_in_buffer_space(p);
 690   }
 691 }
 692 #endif
 693 
 694 bool ClassPrelinker::is_in_javabase(InstanceKlass* ik) {
 695   if (ik->is_hidden() && HeapShared::is_lambda_form_klass(ik)) {
 696     return true;
 697   }
 698 
 699   return (ik->module() != nullptr &&
 700           ik->module()->name() != nullptr &&
 701           ik->module()->name()->equals("java.base"));
 702 }
 703 
 704 class ClassPrelinker::PreloadedKlassRecorder : StackObj {
 705   int _loader_type;
 706   ResourceHashtable<InstanceKlass*, bool, 15889, AnyObj::RESOURCE_AREA, mtClassShared> _seen_klasses;
 707   GrowableArray<InstanceKlass*> _list;
 708   bool loader_type_matches(InstanceKlass* ik) {
 709     InstanceKlass* buffered_ik = ArchiveBuilder::current()->get_buffered_addr(ik);
 710     return buffered_ik->shared_class_loader_type() == _loader_type;
 711   }
 712 
 713   void maybe_record(InstanceKlass* ik) {
 714     bool created;
 715     _seen_klasses.put_if_absent(ik, true, &created);
 716     if (!created) {
 717       // Already seen this class when we walked the hierarchy of a previous class
 718       return;
 719     }
 720     if (!loader_type_matches(ik)) {
 721       return;
 722     }
 723 
 724     if (ik->is_hidden()) {
 725       assert(ik->shared_class_loader_type() != ClassLoader::OTHER, "must have been set");
 726       if (!CDSConfig::is_dumping_invokedynamic()) {
 727         return;
 728       }
 729       assert(HeapShared::is_lambda_form_klass(ik) || HeapShared::is_lambda_proxy_klass(ik), "must be");
 730     }
 731 
 732     if (ClassPrelinker::is_vm_class(ik)) {
 733       // vmClasses are loaded in vmClasses::resolve_all() at the very beginning
 734       // of VM bootstrap, before ClassPrelinker::runtime_preload() is called.
 735       return;
 736     }
 737 
 738     if (_loader_type == ClassLoader::BOOT_LOADER) {
 739       if (_record_javabase_only != is_in_javabase(ik)) {
 740         return;
 741       }
 742     }
 743 
 744     if (MetaspaceObj::is_shared(ik)) {
 745       if (CDSConfig::is_dumping_dynamic_archive()) {
 746         return;
 747       } else {
 748         assert(CDSConfig::is_dumping_final_static_archive(), "must be");
 749       }
 750     }
 751 
 752     if (!ik->is_hidden()) {
 753       // Do not preload any module classes that are not from the modules images,
 754       // since such classes may not be loadable at runtime
 755       int scp_index = ik->shared_classpath_index();
 756       assert(scp_index >= 0, "must be");
 757       SharedClassPathEntry* scp_entry = FileMapInfo::shared_path(scp_index);
 758       if (scp_entry->in_named_module() && !scp_entry->is_modules_image()) {
 759         return;
 760       }
 761     }
 762 
 763     InstanceKlass* s = ik->java_super();
 764     if (s != nullptr) {
 765       maybe_record(s);
 766       add_initiated_klass(ik, s);
 767     }
 768 
 769     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
 770     int num_interfaces = interfaces->length();
 771     for (int index = 0; index < num_interfaces; index++) {
 772       InstanceKlass* intf = interfaces->at(index);
 773       maybe_record(intf);
 774       add_initiated_klass(ik, intf);
 775     }
 776 
 777     _list.append((InstanceKlass*)ArchiveBuilder::get_buffered_klass(ik));
 778     _preloaded_classes->put_when_absent(ik, true);
 779 
 780     if (log_is_enabled(Info, cds, preload)) {
 781       ResourceMark rm;
 782       const char* loader_name;
 783       if (_loader_type  == ClassLoader::BOOT_LOADER) {
 784         if (_record_javabase_only) {
 785           loader_name = "boot ";
 786         } else {
 787           loader_name = "boot2";
 788         }
 789       } else if (_loader_type  == ClassLoader::PLATFORM_LOADER) {
 790         loader_name = "plat ";
 791       } else {
 792         loader_name = "app  ";
 793       }
 794 
 795       log_info(cds, preload)("%s %s", loader_name, ik->external_name());
 796     }
 797   }
 798 
 799 public:
 800   PreloadedKlassRecorder(int loader_type) : _loader_type(loader_type),  _seen_klasses(), _list() {}
 801 
 802   void iterate() {
 803     GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 804     for (GrowableArrayIterator<Klass*> it = klasses->begin(); it != klasses->end(); ++it) {
 805       Klass* k = *it;
 806       //assert(!k->is_shared(), "must be");
 807       if (k->is_instance_klass()) {
 808         maybe_record(InstanceKlass::cast(k));
 809       }
 810     }
 811   }
 812 
 813   Array<InstanceKlass*>* to_array() {
 814     return ArchiveUtils::archive_array(&_list);
 815   }
 816 };
 817 
 818 Array<InstanceKlass*>* ClassPrelinker::record_preloaded_klasses(int loader_type) {
 819   ResourceMark rm;
 820   PreloadedKlassRecorder recorder(loader_type);
 821   recorder.iterate();
 822   return recorder.to_array();
 823 }
 824 
 825 void ClassPrelinker::record_preloaded_klasses(bool is_static_archive) {
 826   if (PreloadSharedClasses) {
 827     PreloadedKlasses* table = (is_static_archive) ? &_static_preloaded_klasses : &_dynamic_preloaded_klasses;
 828 
 829     _record_javabase_only = true;
 830     table->_boot     = record_preloaded_klasses(ClassLoader::BOOT_LOADER);
 831     _record_javabase_only = false;
 832     table->_boot2    = record_preloaded_klasses(ClassLoader::BOOT_LOADER);
 833 
 834     table->_platform = record_preloaded_klasses(ClassLoader::PLATFORM_LOADER);
 835     table->_app      = record_preloaded_klasses(ClassLoader::APP_LOADER);
 836 
 837     add_extra_initiated_klasses(table);
 838   }
 839 }
 840 
 841 Array<InstanceKlass*>* ClassPrelinker::record_initiated_klasses(ClassesTable* table) {
 842   ResourceMark rm;
 843   GrowableArray<InstanceKlass*> tmp_array;
 844 
 845   auto collector = [&] (InstanceKlass* ik, bool need_to_record) {
 846     if (!need_to_record) {
 847       return;
 848     }
 849 
 850     if (CDSConfig::is_dumping_final_static_archive() || !ik->is_shared()) {
 851       if (SystemDictionaryShared::is_excluded_class(ik)) {
 852         return;
 853       }
 854       ik = (InstanceKlass*)ArchiveBuilder::get_buffered_klass(ik);
 855     }
 856     tmp_array.append(ik);
 857     if (log_is_enabled(Info, cds, preload)) {
 858       ResourceMark rm;
 859       const char* loader_name;
 860       if (table == _platform_initiated_classes) {
 861         loader_name = "plat ";
 862       } else {
 863         loader_name = "app  ";
 864       }
 865       log_info(cds, preload)("%s %s (initiated)", loader_name, ik->external_name());
 866     }
 867   };
 868   table->iterate_all(collector);
 869 
 870   return ArchiveUtils::archive_array(&tmp_array);
 871 }
 872 
 873 void ClassPrelinker::record_initiated_klasses(bool is_static_archive) {
 874   if (PreloadSharedClasses) {
 875     PreloadedKlasses* table = (is_static_archive) ? &_static_preloaded_klasses : &_dynamic_preloaded_klasses;
 876     table->_platform_initiated = record_initiated_klasses(_platform_initiated_classes);
 877     table->_app_initiated = record_initiated_klasses(_app_initiated_classes);
 878   }
 879 }
 880 
 881 void ClassPrelinker::record_unregistered_klasses() {
 882   if (CDSConfig::is_dumping_preimage_static_archive()) {
 883     GrowableArray<InstanceKlass*> unreg_klasses;
 884     GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 885     for (int i = 0; i < klasses->length(); i++) {
 886       Klass* k = klasses->at(i);
 887       if (k->is_instance_klass()) {
 888         InstanceKlass* ik = InstanceKlass::cast(k);
 889         if (ik->is_shared_unregistered_class()) {
 890           unreg_klasses.append((InstanceKlass*)ArchiveBuilder::get_buffered_klass(ik));
 891         }
 892       }
 893     }
 894     _unregistered_klasses_from_preimage = ArchiveUtils::archive_array(&unreg_klasses);
 895   } else {
 896     _unregistered_klasses_from_preimage = nullptr;
 897   }
 898 }
 899 
 900 // This class is used only by the "one step training workflow". An instance of this
 901 // this class is stored in the pre-image. It contains information about the
 902 // class metadata that can be eagerly linked inside the final-image.
 903 class FinalImageEagerLinkage {
 904   // The klasses who have resolved at least one indy CP entry during the training run.
 905   // _indy_cp_indices[i] is a list of all resolved CP entries for _indy_klasses[i].
 906   Array<InstanceKlass*>* _indy_klasses;
 907   Array<Array<int>*>*    _indy_cp_indices;
 908 
 909   // The RefectionData for  _reflect_klasses[i] should be initialized with _reflect_flags[i]
 910   Array<InstanceKlass*>* _reflect_klasses;
 911   Array<int>*            _reflect_flags;
 912 
 913   static GrowableArray<InstanceKlass*>* _tmp_reflect_klasses;
 914   static GrowableArray<int>* _tmp_reflect_flags;
 915 
 916   struct TmpDynamicProxyClassInfo {
 917     int _loader_type;
 918     int _access_flags;
 919     const char* _proxy_name;
 920     GrowableArray<Klass*>* _interfaces;
 921   };
 922 
 923   struct DynamicProxyClassInfo {
 924     int _loader_type;
 925     int _access_flags;
 926     const char* _proxy_name;
 927     Array<Klass*>* _interfaces;
 928   };
 929 
 930   Array<DynamicProxyClassInfo>* _dynamic_proxy_classes;
 931 
 932   static GrowableArray<TmpDynamicProxyClassInfo>* _tmp_dynamic_proxy_classes;
 933 
 934 public:
 935   FinalImageEagerLinkage() : _indy_klasses(nullptr), _indy_cp_indices(nullptr),
 936                              _reflect_klasses(nullptr), _reflect_flags(nullptr),
 937                              _dynamic_proxy_classes(nullptr) {}
 938 
 939   void* operator new(size_t size) throw() {
 940     return ArchiveBuilder::current()->ro_region_alloc(size);
 941   }
 942 
 943   // These are called when dumping preimage
 944   static void record_reflection_data_flags_for_preimage(InstanceKlass* ik, TRAPS);
 945   static void record_dynamic_proxy_class(oop loader, const char* proxy_name, objArrayOop interfaces, int access_flags);
 946   void record_linkage_in_preimage();
 947 
 948   // Called when dumping final image
 949   void resolve_indys_in_final_image(TRAPS);
 950   void archive_reflection_data_in_final_image(JavaThread* current);
 951   void archive_dynamic_proxies(TRAPS);
 952 };
 953 
 954 static FinalImageEagerLinkage* _final_image_eager_linkage = nullptr;
 955 
 956 GrowableArray<InstanceKlass*>* FinalImageEagerLinkage::_tmp_reflect_klasses = nullptr;
 957 GrowableArray<int>* FinalImageEagerLinkage::_tmp_reflect_flags = nullptr;
 958 GrowableArray<FinalImageEagerLinkage::TmpDynamicProxyClassInfo>* FinalImageEagerLinkage::_tmp_dynamic_proxy_classes = nullptr;
 959 
 960 void FinalImageEagerLinkage::record_reflection_data_flags_for_preimage(InstanceKlass* ik, TRAPS) {
 961   assert(CDSConfig::is_dumping_preimage_static_archive(), "must be");
 962   if (SystemDictionaryShared::is_builtin_loader(ik->class_loader_data()) && !ik->is_hidden() &&
 963       java_lang_Class::has_reflection_data(ik->java_mirror())) {
 964     int rd_flags = ClassPrelinker::class_reflection_data_flags(ik, CHECK);
 965     if (_tmp_reflect_klasses == nullptr) {
 966       _tmp_reflect_klasses = new (mtClassShared) GrowableArray<InstanceKlass*>(100, mtClassShared);
 967       _tmp_reflect_flags = new (mtClassShared) GrowableArray<int>(100, mtClassShared);
 968     }
 969     _tmp_reflect_klasses->append(ik);
 970     _tmp_reflect_flags->append(rd_flags);
 971   }
 972 }
 973 
 974 void FinalImageEagerLinkage::record_linkage_in_preimage() {
 975   assert(CDSConfig::is_dumping_preimage_static_archive(), "must be");
 976   ResourceMark rm;
 977   GrowableArray<Klass*>* klasses = ArchiveBuilder::current()->klasses();
 978 
 979   // ArchiveInvokeDynamic
 980   GrowableArray<InstanceKlass*> tmp_indy_klasses;
 981   GrowableArray<Array<int>*> tmp_indy_cp_indices;
 982   int total_indys_to_resolve = 0;
 983   for (int i = 0; i < klasses->length(); i++) {
 984     Klass* k = klasses->at(i);
 985     if (k->is_instance_klass()) {
 986       InstanceKlass* ik = InstanceKlass::cast(k);
 987       GrowableArray<int> indices;
 988 
 989       if (ik->constants()->cache() != nullptr) {
 990         Array<ResolvedIndyEntry>* tmp_indy_entries = ik->constants()->cache()->resolved_indy_entries();
 991         if (tmp_indy_entries != nullptr) {
 992           for (int i = 0; i < tmp_indy_entries->length(); i++) {
 993             ResolvedIndyEntry* rie = tmp_indy_entries->adr_at(i);
 994             int cp_index = rie->constant_pool_index();
 995             if (rie->is_resolved()) {
 996               indices.append(cp_index);
 997             }
 998           }
 999         }
1000       }
1001 
1002       if (indices.length() > 0) {
1003         tmp_indy_klasses.append(ArchiveBuilder::current()->get_buffered_addr(ik));
1004         tmp_indy_cp_indices.append(ArchiveUtils::archive_array(&indices));
1005         total_indys_to_resolve += indices.length();
1006       }
1007     }
1008   }
1009 
1010   assert(tmp_indy_klasses.length() == tmp_indy_cp_indices.length(), "must be");
1011   if (tmp_indy_klasses.length() > 0) {
1012     _indy_klasses = ArchiveUtils::archive_array(&tmp_indy_klasses);
1013     _indy_cp_indices = ArchiveUtils::archive_array(&tmp_indy_cp_indices);
1014 
1015     ArchivePtrMarker::mark_pointer(&_indy_klasses);
1016     ArchivePtrMarker::mark_pointer(&_indy_cp_indices);
1017   }
1018   log_info(cds)("%d indies in %d classes will be resolved in final CDS image", total_indys_to_resolve, tmp_indy_klasses.length());
1019 
1020   // ArchiveReflectionData
1021   int reflect_count = 0;
1022   if (_tmp_reflect_klasses != nullptr) {
1023     for (int i = _tmp_reflect_klasses->length() - 1; i >= 0; i--) {
1024       InstanceKlass* ik = _tmp_reflect_klasses->at(i);
1025       if (SystemDictionaryShared::is_excluded_class(ik)) {
1026         _tmp_reflect_klasses->remove_at(i);
1027         _tmp_reflect_flags->remove_at(i);
1028       } else {
1029         _tmp_reflect_klasses->at_put(i, ArchiveBuilder::current()->get_buffered_addr(ik));
1030       }
1031     }
1032     if (_tmp_reflect_klasses->length() > 0) {
1033       _reflect_klasses = ArchiveUtils::archive_array(_tmp_reflect_klasses);
1034       _reflect_flags = ArchiveUtils::archive_array(_tmp_reflect_flags);
1035 
1036       ArchivePtrMarker::mark_pointer(&_reflect_klasses);
1037       ArchivePtrMarker::mark_pointer(&_reflect_flags);
1038       reflect_count = _tmp_reflect_klasses->length();
1039     }
1040   }
1041   log_info(cds)("ReflectionData of %d classes will be archived in final CDS image", reflect_count);
1042 
1043   // Dynamic Proxies
1044   if (_tmp_dynamic_proxy_classes != nullptr && ArchiveDynamicProxies) {
1045     int len = _tmp_dynamic_proxy_classes->length();
1046     _dynamic_proxy_classes = ArchiveBuilder::new_ro_array<DynamicProxyClassInfo>(len);
1047     ArchivePtrMarker::mark_pointer(&_dynamic_proxy_classes);
1048     for (int i = 0; i < len; i++) {
1049       TmpDynamicProxyClassInfo* tmp_info = _tmp_dynamic_proxy_classes->adr_at(i);
1050       DynamicProxyClassInfo* info = _dynamic_proxy_classes->adr_at(i);
1051       info->_loader_type = tmp_info->_loader_type;
1052       info->_access_flags = tmp_info->_access_flags;
1053       info->_proxy_name = ArchiveBuilder::current()->ro_strdup(tmp_info->_proxy_name);
1054 
1055       ResourceMark rm;
1056       GrowableArray<Klass*> buffered_interfaces;
1057       for (int j = 0; j < tmp_info->_interfaces->length(); j++) {
1058         buffered_interfaces.append(ArchiveBuilder::current()->get_buffered_addr(tmp_info->_interfaces->at(j)));
1059       }
1060       info->_interfaces = ArchiveUtils::archive_array(&buffered_interfaces);
1061 
1062       ArchivePtrMarker::mark_pointer(&info->_proxy_name);
1063       ArchivePtrMarker::mark_pointer(&info->_interfaces);
1064       ArchiveBuilder::alloc_stats()->record_dynamic_proxy_class();
1065     }
1066   }
1067 }
1068 
1069 void FinalImageEagerLinkage::resolve_indys_in_final_image(TRAPS) {
1070   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
1071 
1072   if (_indy_klasses != nullptr) {
1073     assert(_indy_cp_indices != nullptr, "must be");
1074     for (int i = 0; i < _indy_klasses->length(); i++) {
1075       InstanceKlass* ik = _indy_klasses->at(i);
1076       ConstantPool* cp = ik->constants();
1077       Array<int>* cp_indices = _indy_cp_indices->at(i);
1078       GrowableArray<bool> preresolve_list(cp->length(), cp->length(), false);
1079       for (int j = 0; j < cp_indices->length(); j++) {
1080         preresolve_list.at_put(cp_indices->at(j), true);
1081       }
1082       ClassPrelinker::preresolve_indy_cp_entries(THREAD, ik, &preresolve_list);
1083     }
1084   }
1085 }
1086 
1087 void FinalImageEagerLinkage::archive_reflection_data_in_final_image(JavaThread* current) {
1088   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
1089 
1090   if (_reflect_klasses != nullptr) {
1091     assert(_reflect_flags != nullptr, "must be");
1092     for (int i = 0; i < _reflect_klasses->length(); i++) {
1093       InstanceKlass* ik = _reflect_klasses->at(i);
1094       int rd_flags = _reflect_flags->at(i);
1095       ClassPrelinker::generate_reflection_data(current, ik, rd_flags);
1096     }
1097   }
1098 }
1099 
1100 void FinalImageEagerLinkage::record_dynamic_proxy_class(oop loader, const char* proxy_name, objArrayOop interfaces, int access_flags) {
1101   int loader_type;
1102   if (loader == nullptr) {
1103     loader_type = ClassLoader::BOOT_LOADER;
1104   } else if (loader == SystemDictionary::java_platform_loader()) {
1105     loader_type = ClassLoader::PLATFORM_LOADER;
1106   } else if (loader == SystemDictionary::java_system_loader()) {
1107     loader_type = ClassLoader::APP_LOADER;
1108   } else {
1109     return;
1110   }
1111 
1112   if (_tmp_dynamic_proxy_classes == nullptr) {
1113     _tmp_dynamic_proxy_classes = new (mtClassShared) GrowableArray<TmpDynamicProxyClassInfo>(32, mtClassShared);
1114   }
1115 
1116   TmpDynamicProxyClassInfo info;
1117   info._loader_type = loader_type;
1118   info._access_flags = access_flags;
1119   info._proxy_name = os::strdup(proxy_name);
1120   info._interfaces = new (mtClassShared) GrowableArray<Klass*>(interfaces->length(), mtClassShared);
1121   for (int i = 0; i < interfaces->length(); i++) {
1122     Klass* intf = java_lang_Class::as_Klass(interfaces->obj_at(i));
1123     info._interfaces->append(intf);
1124   }
1125   _tmp_dynamic_proxy_classes->append(info);
1126 }
1127 
1128 void FinalImageEagerLinkage::archive_dynamic_proxies(TRAPS) {
1129   if (ArchiveDynamicProxies && _dynamic_proxy_classes != nullptr) {
1130     for (int proxy_index = 0; proxy_index < _dynamic_proxy_classes->length(); proxy_index++) {
1131       DynamicProxyClassInfo* info = _dynamic_proxy_classes->adr_at(proxy_index);
1132 
1133       Handle loader(THREAD, ArchiveUtils::builtin_loader_from_type(info->_loader_type));
1134 
1135       oop proxy_name_oop = java_lang_String::create_oop_from_str(info->_proxy_name, CHECK);
1136       Handle proxy_name(THREAD, proxy_name_oop);
1137 
1138       int num_intfs = info->_interfaces->length();
1139       objArrayOop interfaces_oop = oopFactory::new_objArray(vmClasses::Class_klass(), num_intfs, CHECK);
1140       objArrayHandle interfaces(THREAD, interfaces_oop);
1141       for (int intf_index = 0; intf_index < num_intfs; intf_index++) {
1142         Klass* k = info->_interfaces->at(intf_index);
1143         assert(k->java_mirror() != nullptr, "must be loaded");
1144         interfaces()->obj_at_put(intf_index, k->java_mirror());
1145       }
1146 
1147       ClassPrelinker::define_dynamic_proxy_class(loader, proxy_name, interfaces, info->_access_flags, CHECK);
1148     }
1149   }
1150 }
1151 
1152 void ClassPrelinker::record_reflection_data_flags_for_preimage(InstanceKlass* ik, TRAPS) {
1153   FinalImageEagerLinkage::record_reflection_data_flags_for_preimage(ik, THREAD);
1154 }
1155 
1156 void ClassPrelinker::record_final_image_eager_linkage() {
1157   _final_image_eager_linkage = new FinalImageEagerLinkage();
1158   _final_image_eager_linkage->record_linkage_in_preimage();
1159 }
1160 
1161 void ClassPrelinker::apply_final_image_eager_linkage(TRAPS) {
1162   assert(CDSConfig::is_dumping_final_static_archive(), "must be");
1163 
1164   if (_final_image_eager_linkage != nullptr) {
1165     _final_image_eager_linkage->resolve_indys_in_final_image(CHECK);
1166     _final_image_eager_linkage->archive_reflection_data_in_final_image(THREAD);
1167     _final_image_eager_linkage->archive_dynamic_proxies(CHECK);
1168   }
1169 
1170   // Set it to null as we don't need to write this table into the final image.
1171   _final_image_eager_linkage = nullptr;
1172 }
1173 
1174 int ClassPrelinker::class_reflection_data_flags(InstanceKlass* ik, TRAPS) {
1175   assert(java_lang_Class::has_reflection_data(ik->java_mirror()), "must be");
1176 
1177   HandleMark hm(THREAD);
1178   JavaCallArguments args(Handle(THREAD, ik->java_mirror()));
1179   JavaValue result(T_INT);
1180   JavaCalls::call_special(&result,
1181                           vmClasses::Class_klass(),
1182                           vmSymbols::encodeReflectionData_name(),
1183                           vmSymbols::void_int_signature(),
1184                           &args, CHECK_0);
1185   int flags = result.get_jint();
1186   log_info(cds)("Encode ReflectionData: %s (flags=0x%x)", ik->external_name(), flags);
1187   return flags;
1188 }
1189 
1190 void ClassPrelinker::generate_reflection_data(JavaThread* current, InstanceKlass* ik, int rd_flags) {
1191   log_info(cds)("Generate ReflectionData: %s (flags=" INT32_FORMAT_X ")", ik->external_name(), rd_flags);
1192   JavaThread* THREAD = current; // for exception macros
1193   JavaCallArguments args(Handle(THREAD, ik->java_mirror()));
1194   args.push_int(rd_flags);
1195   JavaValue result(T_OBJECT);
1196   JavaCalls::call_special(&result,
1197                           vmClasses::Class_klass(),
1198                           vmSymbols::generateReflectionData_name(),
1199                           vmSymbols::int_void_signature(),
1200                           &args, THREAD);
1201   if (HAS_PENDING_EXCEPTION) {
1202     Handle exc_handle(THREAD, PENDING_EXCEPTION);
1203     CLEAR_PENDING_EXCEPTION;
1204 
1205     log_warning(cds)("Exception during Class::generateReflectionData() call for %s", ik->external_name());
1206     LogStreamHandle(Debug, cds) log;
1207     if (log.is_enabled()) {
1208       java_lang_Throwable::print_stack_trace(exc_handle, &log);
1209     }
1210   }
1211 }
1212 
1213 Klass* ClassPrelinker::resolve_boot_klass_or_fail(const char* class_name, TRAPS) {
1214   Handle class_loader;
1215   Handle protection_domain;
1216   TempNewSymbol class_name_sym = SymbolTable::new_symbol(class_name);
1217   return SystemDictionary::resolve_or_fail(class_name_sym, class_loader, protection_domain, true, THREAD);
1218 }
1219 
1220 void ClassPrelinker::trace_dynamic_proxy_class(oop loader, const char* proxy_name, objArrayOop interfaces, int access_flags) {
1221   if (interfaces->length() < 1) {
1222     return;
1223   }
1224   if (ClassListWriter::is_enabled()) {
1225     const char* loader_name = ArchiveUtils::builtin_loader_name_or_null(loader);
1226     if (loader_name != nullptr) {
1227       stringStream ss;
1228       ss.print("%s %s %d %d", loader_name, proxy_name, access_flags, interfaces->length());
1229       for (int i = 0; i < interfaces->length(); i++) {
1230         oop mirror = interfaces->obj_at(i);
1231         Klass* k = java_lang_Class::as_Klass(mirror);
1232         ss.print(" %s", k->name()->as_C_string());
1233       }
1234       ClassListWriter w;
1235       w.stream()->print_cr("@dynamic-proxy %s", ss.freeze());
1236     }
1237   }
1238   if (CDSConfig::is_dumping_preimage_static_archive()) {
1239     FinalImageEagerLinkage::record_dynamic_proxy_class(loader, proxy_name, interfaces, access_flags);
1240   }
1241 }
1242 
1243 void ClassPrelinker::init_dynamic_proxy_cache(TRAPS) {
1244   static bool inited = false;
1245   if (inited) {
1246     return;
1247   }
1248   inited = true;
1249 
1250   Klass* klass = resolve_boot_klass_or_fail("java/lang/reflect/Proxy", CHECK);
1251   TempNewSymbol method = SymbolTable::new_symbol("initCacheForCDS");
1252   TempNewSymbol signature = SymbolTable::new_symbol("(Ljava/lang/ClassLoader;Ljava/lang/ClassLoader;)V");
1253 
1254   JavaCallArguments args;
1255   args.push_oop(Handle(THREAD, SystemDictionary::java_platform_loader()));
1256   args.push_oop(Handle(THREAD, SystemDictionary::java_system_loader()));
1257   JavaValue result(T_VOID);
1258   JavaCalls::call_static(&result,
1259                          klass,
1260                          method,
1261                          signature,
1262                          &args, CHECK);
1263 }
1264 
1265 
1266 void ClassPrelinker::define_dynamic_proxy_class(Handle loader, Handle proxy_name, Handle interfaces, int access_flags, TRAPS) {
1267   if (!CDSConfig::is_dumping_dynamic_proxy() || !ArchiveDynamicProxies) {
1268     return;
1269   }
1270   init_dynamic_proxy_cache(CHECK);
1271 
1272   Klass* klass = resolve_boot_klass_or_fail("java/lang/reflect/Proxy$ProxyBuilder", CHECK);
1273   TempNewSymbol method = SymbolTable::new_symbol("defineProxyClassForCDS");
1274   TempNewSymbol signature = SymbolTable::new_symbol("(Ljava/lang/ClassLoader;Ljava/lang/String;[Ljava/lang/Class;I)Ljava/lang/Class;");
1275 
1276   JavaCallArguments args;
1277   args.push_oop(Handle(THREAD, loader()));
1278   args.push_oop(Handle(THREAD, proxy_name()));
1279   args.push_oop(Handle(THREAD, interfaces()));
1280   args.push_int(access_flags);
1281   JavaValue result(T_OBJECT);
1282   JavaCalls::call_static(&result,
1283                          klass,
1284                          method,
1285                          signature,
1286                          &args, CHECK);
1287 
1288   // Assumptions:
1289   // FMG is archived, which means -modulepath and -Xbootclasspath are both not specified.
1290   // All named modules are loaded from the system modules files.
1291   // TODO: test support for -Xbootclasspath after JDK-8322322. Some of the code below need to be changed.
1292   // TODO: we just give dummy shared_classpath_index for the generated class so that it will be archived.
1293   //       The index is not used at runtime (see SystemDictionaryShared::load_shared_class_for_builtin_loader, which
1294   //       uses a null ProtectionDomain for this class)
1295   oop mirror = result.get_oop();
1296   assert(mirror != nullptr, "class must have been generated if not OOM");
1297   InstanceKlass* ik = InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
1298   if (ik->is_shared_boot_class() || ik->is_shared_platform_class()) {
1299     assert(ik->module()->is_named(), "dynamic proxies defined in unnamed modules for boot/platform loaders not supported");
1300     ik->set_shared_classpath_index(0);
1301   } else {
1302     assert(ik->is_shared_app_class(), "must be");
1303     ik->set_shared_classpath_index(ClassLoaderExt::app_class_paths_start_index());
1304   }
1305 
1306   ArchiveBuilder::alloc_stats()->record_dynamic_proxy_class();
1307   if (log_is_enabled(Info, cds, dynamic, proxy)) {
1308     ResourceMark rm(THREAD);
1309     stringStream ss;
1310     const char* prefix = "";
1311     ss.print("%s (%-7s, cp index = %d) implements ", ik->external_name(),
1312              ArchiveUtils::builtin_loader_name(loader()), ik->shared_classpath_index());
1313     objArrayOop intfs = (objArrayOop)interfaces();
1314     for (int i = 0; i < intfs->length(); i++) {
1315       oop intf_mirror = intfs->obj_at(i);
1316       ss.print("%s%s", prefix, java_lang_Class::as_Klass(intf_mirror)->external_name());
1317       prefix = ", ";
1318     }
1319 
1320     log_info(cds, dynamic, proxy)("%s", ss.freeze());
1321   }
1322 }
1323 
1324 // Warning -- this is fragile!!!
1325 // This is a hard-coded list of classes that are safe to preinitialize at dump time. It needs
1326 // to be updated if the Java source code changes.
1327 bool ClassPrelinker::is_forced_preinit_class(InstanceKlass* ik) {
1328   if (!CDSConfig::is_dumping_invokedynamic()) {
1329     return false;
1330   }
1331 
1332   static const char* forced_preinit_classes[] = {
1333     "java/util/HexFormat",
1334     "jdk/internal/util/ClassFileDumper",
1335     "java/lang/reflect/ClassFileFormatVersion",
1336     "java/lang/Character$CharacterCache",
1337     "java/lang/invoke/Invokers",
1338     "java/lang/invoke/Invokers$Holder",
1339     "java/lang/invoke/MethodHandle",
1340     "java/lang/invoke/MethodHandleStatics",
1341     "java/lang/invoke/DelegatingMethodHandle",
1342     "java/lang/invoke/DelegatingMethodHandle$Holder",
1343     "java/lang/invoke/LambdaForm",
1344     "java/lang/invoke/LambdaForm$NamedFunction",
1345     "java/lang/invoke/ClassSpecializer",
1346     "java/lang/invoke/DirectMethodHandle",
1347     "java/lang/invoke/DirectMethodHandle$Holder",
1348     "java/lang/invoke/BoundMethodHandle$Specializer",
1349     "java/lang/invoke/MethodHandles$Lookup",
1350 
1351   //TODO: these use java.lang.ClassValue$Entry which is a subtype of WeakReference
1352   //"java/lang/reflect/Proxy$ProxyBuilder",
1353   //"java/lang/reflect/Proxy",
1354 
1355   // TODO -- need to clear internTable, etc
1356   //"java/lang/invoke/MethodType",
1357 
1358   // TODO -- these need to link to native code
1359   //"java/lang/invoke/BoundMethodHandle",
1360   //"java/lang/invoke/BoundMethodHandle$Holder",
1361   //"java/lang/invoke/MemberName",
1362   //"java/lang/invoke/MethodHandleNatives",
1363     nullptr
1364   };
1365 
1366   for (int i = 0; ; i++) {
1367     const char* class_name = forced_preinit_classes[i];
1368     if (class_name == nullptr) {
1369       return false;
1370     }
1371     if (ik->name()->equals(class_name)) {
1372       if (log_is_enabled(Info, cds, init)) {
1373         ResourceMark rm;
1374         log_info(cds, init)("Force initialization %s", ik->external_name());
1375       }
1376       return true;
1377     }
1378   }
1379 }
1380 
1381 // Initialize a class at dump time, if possible.
1382 void ClassPrelinker::maybe_preinit_class(InstanceKlass* ik, TRAPS) {
1383   if (!ik->is_initialized() && SystemDictionaryShared::can_be_preinited(ik)) {
1384     if (log_is_enabled(Info, cds, init)) {
1385       ResourceMark rm;
1386       log_info(cds, init)("preinitializing %s", ik->external_name());
1387     }
1388     ik->initialize(CHECK);
1389   }
1390 }
1391 
1392 bool ClassPrelinker::check_can_be_preinited(InstanceKlass* ik) {
1393   ResourceMark rm;
1394 
1395   if (!SystemDictionaryShared::is_builtin(ik)) {
1396     log_info(cds, init)("cannot initialize %s (not built-in loader)", ik->external_name());
1397     return false;
1398   }
1399 
1400   InstanceKlass* super = ik->java_super();
1401   if (super != nullptr && !SystemDictionaryShared::can_be_preinited_locked(super)) {
1402     log_info(cds, init)("cannot initialize %s (super %s not initable)", ik->external_name(), super->external_name());
1403     return false;
1404   }
1405 
1406   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1407   for (int i = 0; i < interfaces->length(); i++) {
1408     if (!SystemDictionaryShared::can_be_preinited_locked(interfaces->at(i))) {
1409       log_info(cds, init)("cannot initialize %s (interface %s not initable)",
1410                           ik->external_name(), interfaces->at(i)->external_name());
1411       return false;
1412     }
1413   }
1414 
1415   if (HeapShared::is_lambda_form_klass(ik) || ClassPrelinker::is_forced_preinit_class(ik)) {
1416     // We allow only these to have <clinit> or non-default static fields
1417   } else {
1418     if (ik->class_initializer() != nullptr) {
1419       log_info(cds, init)("cannot initialize %s (has <clinit>)", ik->external_name());
1420       return false;
1421     }
1422     if (ik->is_initialized() && !has_non_default_static_fields(ik)) {
1423       return false;
1424     }
1425   }
1426 
1427   return true;
1428 }
1429 
1430 bool ClassPrelinker::can_archive_preinitialized_mirror(InstanceKlass* ik) {
1431   assert(!ArchiveBuilder::current()->is_in_buffer_space(ik), "must be source klass");
1432   if (!CDSConfig::is_initing_classes_at_dump_time()) {
1433     return false;
1434   }
1435 
1436   if (ik->is_hidden()) {
1437     return HeapShared::is_archivable_hidden_klass(ik);
1438   } else {
1439     return SystemDictionaryShared::can_be_preinited_locked(ik);
1440   }
1441 }
1442 
1443 bool ClassPrelinker::has_non_default_static_fields(InstanceKlass* ik) {
1444   oop mirror = ik->java_mirror();
1445 
1446   for (JavaFieldStream fs(ik); !fs.done(); fs.next()) {
1447     if (fs.access_flags().is_static()) {
1448       fieldDescriptor& fd = fs.field_descriptor();
1449       int offset = fd.offset();
1450       bool is_default = true;
1451       bool has_initval = fd.has_initial_value();
1452       switch (fd.field_type()) {
1453       case T_OBJECT:
1454       case T_ARRAY:
1455         is_default = mirror->obj_field(offset) == nullptr;
1456         break;
1457       case T_BOOLEAN:
1458         is_default = mirror->bool_field(offset) == (has_initval ? fd.int_initial_value() : 0);
1459         break;
1460       case T_BYTE:
1461         is_default = mirror->byte_field(offset) == (has_initval ? fd.int_initial_value() : 0);
1462         break;
1463       case T_SHORT:
1464         is_default = mirror->short_field(offset) == (has_initval ? fd.int_initial_value() : 0);
1465         break;
1466       case T_CHAR:
1467         is_default = mirror->char_field(offset) == (has_initval ? fd.int_initial_value() : 0);
1468         break;
1469       case T_INT:
1470         is_default = mirror->int_field(offset) == (has_initval ? fd.int_initial_value() : 0);
1471         break;
1472       case T_LONG:
1473         is_default = mirror->long_field(offset) == (has_initval ? fd.long_initial_value() : 0);
1474         break;
1475       case T_FLOAT:
1476         is_default = mirror->float_field(offset) == (has_initval ? fd.float_initial_value() : 0);
1477         break;
1478       case T_DOUBLE:
1479         is_default = mirror->double_field(offset) == (has_initval ? fd.double_initial_value() : 0);
1480         break;
1481       default:
1482         ShouldNotReachHere();
1483       }
1484 
1485       if (!is_default) {
1486         log_info(cds, init)("cannot initialize %s (static field %s has non-default value)",
1487                             ik->external_name(), fd.name()->as_C_string());
1488         return false;
1489       }
1490     }
1491   }
1492 
1493   return true;
1494 }
1495 
1496 void ClassPrelinker::serialize(SerializeClosure* soc, bool is_static_archive) {
1497   PreloadedKlasses* table = (is_static_archive) ? &_static_preloaded_klasses : &_dynamic_preloaded_klasses;
1498 
1499   soc->do_ptr((void**)&table->_boot);
1500   soc->do_ptr((void**)&table->_boot2);
1501   soc->do_ptr((void**)&table->_platform);
1502   soc->do_ptr((void**)&table->_platform_initiated);
1503   soc->do_ptr((void**)&table->_app);
1504   soc->do_ptr((void**)&table->_app_initiated);
1505 
1506   if (is_static_archive) {
1507     soc->do_ptr((void**)&_final_image_eager_linkage);
1508     soc->do_ptr((void**)&_unregistered_klasses_from_preimage);
1509   }
1510 
1511   if (table->_boot != nullptr && table->_boot->length() > 0) {
1512     CDSConfig::set_has_preloaded_classes();
1513   }
1514 
1515   if (is_static_archive && soc->reading() && UsePerfData) {
1516     JavaThread* THREAD = JavaThread::current();
1517     NEWPERFEVENTCOUNTER(_perf_classes_preloaded, SUN_CLS, "preloadedClasses");
1518     NEWPERFTICKCOUNTERS(_perf_class_preload_counters, SUN_CLS, "classPreload");
1519   }
1520 }
1521 
1522 int ClassPrelinker::num_platform_initiated_classes() {
1523   if (PreloadSharedClasses) {
1524     PreloadedKlasses* table = CDSConfig::is_dumping_dynamic_archive() ? &_dynamic_preloaded_klasses : &_static_preloaded_klasses;
1525     return table->_platform_initiated->length();
1526   }
1527   return 0;
1528 }
1529 
1530 int ClassPrelinker::num_app_initiated_classes() {
1531   if (PreloadSharedClasses) {
1532     PreloadedKlasses* table = CDSConfig::is_dumping_dynamic_archive() ? &_dynamic_preloaded_klasses : &_static_preloaded_klasses;
1533     return table->_app_initiated->length();
1534   }
1535   return 0;
1536 }
1537 
1538 volatile bool _class_preloading_finished = false;
1539 
1540 bool ClassPrelinker::class_preloading_finished() {
1541   if (!UseSharedSpaces) {
1542     return true;
1543   } else {
1544     // The ConstantPools of preloaded classes have references to other preloaded classes. We don't
1545     // want any Java code (including JVMCI compiler) to use these classes until all of them
1546     // are loaded.
1547     return Atomic::load_acquire(&_class_preloading_finished);
1548   }
1549 }
1550 
1551 // This function is called 4 times:
1552 // preload only java.base classes
1553 // preload boot classes outside of java.base
1554 // preload classes for platform loader
1555 // preload classes for app loader
1556 void ClassPrelinker::runtime_preload(JavaThread* current, Handle loader) {
1557 #ifdef ASSERT
1558   if (loader() == nullptr) {
1559     static bool first_time = true;
1560     if (first_time) {
1561       // FIXME -- assert that no java code has been executed up to this point.
1562       //
1563       // Reason: Here, only vmClasses have been loaded. However, their CP might
1564       // have some pre-resolved entries that point to classes that are loaded
1565       // only by this function! Any Java bytecode that uses such entries will
1566       // fail.
1567     }
1568     first_time = false;
1569   }
1570 #endif // ASSERT
1571   if (UseSharedSpaces) {
1572     if (loader() != nullptr && !SystemDictionaryShared::has_platform_or_app_classes()) {
1573       // Non-boot classes might have been disabled due to command-line mismatch.
1574       Atomic::release_store(&_class_preloading_finished, true);
1575       return;
1576     }
1577     ResourceMark rm(current);
1578     ExceptionMark em(current);
1579     runtime_preload(&_static_preloaded_klasses, loader, current);
1580     if (!current->has_pending_exception()) {
1581       runtime_preload(&_dynamic_preloaded_klasses, loader, current);
1582     }
1583     _preload_javabase_only = false;
1584 
1585     if (loader() != nullptr && loader() == SystemDictionary::java_system_loader()) {
1586       Atomic::release_store(&_class_preloading_finished, true);
1587     }
1588   }
1589   assert(!current->has_pending_exception(), "VM should have exited due to ExceptionMark");
1590 
1591   if (loader() != nullptr && loader() == SystemDictionary::java_system_loader()) {
1592     if (PrintTrainingInfo) {
1593       tty->print_cr("==================== archived_training_data ** after all classes preloaded ====================");
1594       TrainingData::print_archived_training_data_on(tty);
1595     }
1596 
1597     if (log_is_enabled(Info, cds, jit)) {
1598       CDSAccess::test_heap_access_api();
1599     }
1600 
1601     if (CDSConfig::is_dumping_final_static_archive()) {
1602       assert(_unregistered_klasses_from_preimage != nullptr, "must be");
1603       for (int i = 0; i < _unregistered_klasses_from_preimage->length(); i++) {
1604         InstanceKlass* ik = _unregistered_klasses_from_preimage->at(i);
1605         SystemDictionaryShared::init_dumptime_info(ik);
1606         SystemDictionaryShared::add_unregistered_class(current, ik);
1607       }
1608     }
1609   }
1610 }
1611 
1612 void ClassPrelinker::jvmti_agent_error(InstanceKlass* expected, InstanceKlass* actual, const char* type) {
1613   if (actual->is_shared() && expected->name() == actual->name() &&
1614       LambdaFormInvokers::may_be_regenerated_class(expected->name())) {
1615     // For the 4 regenerated classes (such as java.lang.invoke.Invokers$Holder) there's one
1616     // in static archive and one in dynamic archive. If the dynamic archive is loaded, we
1617     // load the one from the dynamic archive.
1618     return;
1619   }
1620   ResourceMark rm;
1621   log_error(cds)("Unable to resolve %s class from CDS archive: %s", type, expected->external_name());
1622   log_error(cds)("Expected: " INTPTR_FORMAT ", actual: " INTPTR_FORMAT, p2i(expected), p2i(actual));
1623   log_error(cds)("JVMTI class retransformation is not supported when archive was generated with -XX:+PreloadSharedClasses.");
1624   MetaspaceShared::unrecoverable_loading_error();
1625 }
1626 
1627 void ClassPrelinker::runtime_preload(PreloadedKlasses* table, Handle loader, TRAPS) {
1628   PerfTraceTime timer(_perf_class_preload_counters);
1629   Array<InstanceKlass*>* preloaded_klasses;
1630   Array<InstanceKlass*>* initiated_klasses = nullptr;
1631   const char* loader_name;
1632   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(loader());
1633 
1634   // ResourceMark is missing in the code below due to JDK-8307315
1635   ResourceMark rm(THREAD);
1636   if (loader() == nullptr) {
1637     if (_preload_javabase_only) {
1638       loader_name = "boot ";
1639       preloaded_klasses = table->_boot;
1640     } else {
1641       loader_name = "boot2";
1642       preloaded_klasses = table->_boot2;
1643     }
1644   } else if (loader() == SystemDictionary::java_platform_loader()) {
1645     initiated_klasses = table->_platform_initiated;
1646     preloaded_klasses = table->_platform;
1647     loader_name = "plat ";
1648   } else {
1649     assert(loader() == SystemDictionary::java_system_loader(), "must be");
1650     initiated_klasses = table->_app_initiated;
1651     preloaded_klasses = table->_app;
1652     loader_name = "app  ";
1653   }
1654 
1655   if (initiated_klasses != nullptr) {
1656     MonitorLocker mu1(SystemDictionary_lock);
1657 
1658     for (int i = 0; i < initiated_klasses->length(); i++) {
1659       InstanceKlass* ik = initiated_klasses->at(i);
1660       assert(ik->is_loaded(), "must have already been loaded by a parent loader");
1661       if (log_is_enabled(Info, cds, preload)) {
1662         ResourceMark rm;
1663         const char* defining_loader = (ik->class_loader() == nullptr ? "boot" : "plat");
1664         log_info(cds, preload)("%s %s (initiated, defined by %s)", loader_name, ik->external_name(),
1665                                defining_loader);
1666       }
1667       SystemDictionary::preload_class(THREAD, ik, loader_data);
1668     }
1669   }
1670 
1671   if (preloaded_klasses != nullptr) {
1672     for (int i = 0; i < preloaded_klasses->length(); i++) {
1673       if (UsePerfData) {
1674         _perf_classes_preloaded->inc();
1675       }
1676       InstanceKlass* ik = preloaded_klasses->at(i);
1677       if (log_is_enabled(Info, cds, preload)) {
1678         ResourceMark rm;
1679         log_info(cds, preload)("%s %s%s", loader_name, ik->external_name(),
1680                                ik->is_loaded() ? " (already loaded)" : "");
1681       }
1682       // FIXME Do not load proxy classes if FMG is disabled.
1683 
1684       if (!ik->is_loaded()) {
1685         if (ik->is_hidden()) {
1686           preload_archived_hidden_class(loader, ik, loader_name, CHECK);
1687         } else {
1688           InstanceKlass* actual;
1689           if (loader() == nullptr) {
1690             actual = SystemDictionary::load_instance_class(ik->name(), loader, CHECK);
1691           } else {
1692             // Note: we are not adding the locker objects into java.lang.ClassLoader::parallelLockMap, but
1693             // that should be harmless.
1694             actual = SystemDictionaryShared::find_or_load_shared_class(ik->name(), loader, CHECK);
1695           }
1696 
1697           if (actual != ik) {
1698             jvmti_agent_error(ik, actual, "preloaded");
1699           }
1700           assert(actual->is_loaded(), "must be");
1701         }
1702       }
1703 
1704       // FIXME assert - if FMG, package must be archived
1705     }
1706 
1707     if (!_preload_javabase_only) {
1708       // The java.base classes needs to wait till ClassPrelinker::init_javabase_preloaded_classes()
1709       for (int i = 0; i < preloaded_klasses->length(); i++) {
1710         InstanceKlass* ik = preloaded_klasses->at(i);
1711         if (ik->has_preinitialized_mirror()) {
1712           ik->initialize_from_cds(CHECK);
1713         } else if (PrelinkSharedClasses && ik->verified_at_dump_time()) {
1714           ik->link_class(CHECK);
1715         }
1716       }
1717     }
1718   }
1719 
1720   if (!_preload_javabase_only) {
1721     HeapShared::initialize_default_subgraph_classes(loader, CHECK);
1722   }
1723 
1724 #if 0
1725   // Hmm, does JavacBench crash if this block is enabled??
1726   if (VerifyDuringStartup) {
1727     VM_Verify verify_op;
1728     VMThread::execute(&verify_op);
1729   }
1730 #endif
1731 }
1732 
1733 void ClassPrelinker::preload_archived_hidden_class(Handle class_loader, InstanceKlass* ik,
1734                                                    const char* loader_name, TRAPS) {
1735   DEBUG_ONLY({
1736       assert(ik->super() == vmClasses::Object_klass(), "must be");
1737       for (int i = 0; i < ik->local_interfaces()->length(); i++) {
1738         assert(ik->local_interfaces()->at(i)->is_loaded(), "must be");
1739       }
1740     });
1741 
1742   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1743   if (class_loader() == nullptr) {
1744     ik->restore_unshareable_info(loader_data, Handle(), NULL, CHECK);
1745   } else {
1746     PackageEntry* pkg_entry = CDSProtectionDomain::get_package_entry_from_class(ik, class_loader);
1747     Handle protection_domain =
1748         CDSProtectionDomain::init_security_info(class_loader, ik, pkg_entry, CHECK);
1749     ik->restore_unshareable_info(loader_data, protection_domain, pkg_entry, CHECK);
1750   }
1751   SystemDictionary::load_shared_class_misc(ik, loader_data);
1752   ik->add_to_hierarchy(THREAD);
1753 }
1754 
1755 void ClassPrelinker::init_javabase_preloaded_classes(TRAPS) {
1756   Array<InstanceKlass*>* preloaded_klasses = _static_preloaded_klasses._boot;
1757   if (preloaded_klasses != nullptr) {
1758     for (int i = 0; i < preloaded_klasses->length(); i++) {
1759       InstanceKlass* ik = preloaded_klasses->at(i);
1760       if (ik->has_preinitialized_mirror()) {
1761         ik->initialize_from_cds(CHECK);
1762       }
1763     }
1764   }
1765 
1766   // Initialize java.base classes in the default subgraph.
1767   HeapShared::initialize_default_subgraph_classes(Handle(), CHECK);
1768 }
1769 
1770 void ClassPrelinker::replay_training_at_init_for_javabase_preloaded_classes(TRAPS) {
1771   Array<InstanceKlass*>* preloaded_klasses = _static_preloaded_klasses._boot;
1772   if (preloaded_klasses != nullptr) {
1773     for (int i = 0; i < preloaded_klasses->length(); i++) {
1774       InstanceKlass* ik = preloaded_klasses->at(i);
1775       if (ik->is_initialized()) {
1776         if (log_is_enabled(Debug, cds, init)) {
1777           ResourceMark rm;
1778           log_debug(cds, init)("replay training %s", ik->external_name());
1779         }
1780         CompilationPolicy::replay_training_at_init(ik, CHECK);
1781       }
1782     }
1783   }
1784 }
1785 
1786 void ClassPrelinker::print_counters() {
1787   if (UsePerfData && _perf_class_preload_counters != nullptr) {
1788     LogStreamHandle(Info, init) log;
1789     if (log.is_enabled()) {
1790       log.print_cr("ClassPrelinker:");
1791       log.print_cr("  preload:           %ldms (elapsed) %ld (thread) / %ld events",
1792                    _perf_class_preload_counters->elapsed_counter_value_ms(),
1793                    _perf_class_preload_counters->thread_counter_value_ms(),
1794                    _perf_classes_preloaded->get_value());
1795     }
1796   }
1797 }
< prev index next >