1 /*
  2  * Copyright (c) 2016, 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.hpp"
 28 #include "cds/cdsConfig.hpp"
 29 #include "cds/filemap.hpp"
 30 #include "cds/heapShared.hpp"
 31 #include "classfile/classLoader.hpp"
 32 #include "classfile/classLoaderData.inline.hpp"
 33 #include "classfile/javaClasses.inline.hpp"
 34 #include "classfile/moduleEntry.hpp"
 35 #include "classfile/modules.hpp"
 36 #include "classfile/systemDictionary.hpp"
 37 #include "jni.h"
 38 #include "logging/log.hpp"
 39 #include "logging/logStream.hpp"
 40 #include "memory/resourceArea.hpp"
 41 #include "memory/universe.hpp"
 42 #include "oops/oopHandle.inline.hpp"
 43 #include "oops/symbol.hpp"
 44 #include "runtime/handles.inline.hpp"
 45 #include "runtime/safepoint.hpp"
 46 #include "utilities/events.hpp"
 47 #include "utilities/growableArray.hpp"
 48 #include "utilities/ostream.hpp"
 49 #include "utilities/quickSort.hpp"
 50 #include "utilities/resourceHash.hpp"
 51 
 52 ModuleEntry* ModuleEntryTable::_javabase_module = nullptr;
 53 
 54 oop ModuleEntry::module() const { return _module.resolve(); }
 55 
 56 void ModuleEntry::set_location(Symbol* location) {
 57   // _location symbol's refcounts are managed by ModuleEntry,
 58   // must decrement the old one before updating.
 59   Symbol::maybe_decrement_refcount(_location);
 60 
 61   _location = location;
 62 
 63   if (location != nullptr) {
 64     location->increment_refcount();
 65     CDS_ONLY(if (CDSConfig::is_using_archive()) {
 66         _shared_path_index = FileMapInfo::get_module_shared_path_index(location);
 67       });
 68   }
 69 }
 70 
 71 // Return true if the module's version should be displayed in error messages,
 72 // logging, etc.
 73 // Return false if the module's version is null, if it is unnamed, or if the
 74 // module is not an upgradeable module.
 75 // Detect if the module is not upgradeable by checking:
 76 //     1. Module location is "jrt:/java." and its loader is boot or platform
 77 //     2. Module location is "jrt:/jdk.", its loader is one of the builtin loaders
 78 //        and its version is the same as module java.base's version
 79 // The above check is imprecise but should work in almost all cases.
 80 bool ModuleEntry::should_show_version() {
 81   if (version() == nullptr || !is_named()) return false;
 82 
 83   if (location() != nullptr) {
 84     ResourceMark rm;
 85     const char* loc = location()->as_C_string();
 86     ClassLoaderData* cld = loader_data();
 87 
 88     assert(!cld->has_class_mirror_holder(), "module's cld should have a ClassLoader holder not a Class holder");
 89     if ((cld->is_the_null_class_loader_data() || cld->is_platform_class_loader_data()) &&
 90         (strncmp(loc, "jrt:/java.", 10) == 0)) {
 91       return false;
 92     }
 93     if ((ModuleEntryTable::javabase_moduleEntry()->version()->fast_compare(version()) == 0) &&
 94         cld->is_permanent_class_loader_data() && (strncmp(loc, "jrt:/jdk.", 9) == 0)) {
 95       return false;
 96     }
 97   }
 98   return true;
 99 }
100 
101 void ModuleEntry::set_version(Symbol* version) {
102   // _version symbol's refcounts are managed by ModuleEntry,
103   // must decrement the old one before updating.
104   Symbol::maybe_decrement_refcount(_version);
105 
106   _version = version;
107 
108   Symbol::maybe_increment_refcount(version);
109 }
110 
111 // Returns the shared ProtectionDomain
112 oop ModuleEntry::shared_protection_domain() {
113   return _shared_pd.resolve();
114 }
115 
116 // Set the shared ProtectionDomain atomically
117 void ModuleEntry::set_shared_protection_domain(ClassLoaderData *loader_data,
118                                                Handle pd_h) {
119   // Create a handle for the shared ProtectionDomain and save it atomically.
120   // init_handle_locked checks if someone beats us setting the _shared_pd cache.
121   loader_data->init_handle_locked(_shared_pd, pd_h);
122 }
123 
124 // Returns true if this module can read module m
125 bool ModuleEntry::can_read(ModuleEntry* m) const {
126   assert(m != nullptr, "No module to lookup in this module's reads list");
127 
128   // Unnamed modules read everyone and all modules
129   // read java.base.  If either of these conditions
130   // hold, readability has been established.
131   if (!this->is_named() ||
132       (m == ModuleEntryTable::javabase_moduleEntry())) {
133     return true;
134   }
135 
136   MutexLocker m1(Module_lock);
137   // This is a guard against possible race between agent threads that redefine
138   // or retransform classes in this module. Only one of them is adding the
139   // default read edges to the unnamed modules of the boot and app class loaders
140   // with an upcall to jdk.internal.module.Modules.transformedByAgent.
141   // At the same time, another thread can instrument the module classes by
142   // injecting dependencies that require the default read edges for resolution.
143   if (this->has_default_read_edges() && !m->is_named()) {
144     ClassLoaderData* cld = m->loader_data();
145     assert(!cld->has_class_mirror_holder(), "module's cld should have a ClassLoader holder not a Class holder");
146     if (cld->is_the_null_class_loader_data() || cld->is_system_class_loader_data()) {
147       return true; // default read edge
148     }
149   }
150   if (!has_reads_list()) {
151     return false;
152   } else {
153     return reads()->contains(m);
154   }
155 }
156 
157 // Add a new module to this module's reads list
158 void ModuleEntry::add_read(ModuleEntry* m) {
159   // Unnamed module is special cased and can read all modules
160   if (!is_named()) {
161     return;
162   }
163 
164   MutexLocker m1(Module_lock);
165   if (m == nullptr) {
166     set_can_read_all_unnamed();
167   } else {
168     if (reads() == nullptr) {
169       // Lazily create a module's reads list
170       GrowableArray<ModuleEntry*>* new_reads = new (mtModule) GrowableArray<ModuleEntry*>(MODULE_READS_SIZE, mtModule);
171       set_reads(new_reads);
172     }
173 
174     // Determine, based on this newly established read edge to module m,
175     // if this module's read list should be walked at a GC safepoint.
176     set_read_walk_required(m->loader_data());
177 
178     // Establish readability to module m
179     reads()->append_if_missing(m);
180   }
181 }
182 
183 // If the module's loader, that a read edge is being established to, is
184 // not the same loader as this module's and is not one of the 3 builtin
185 // class loaders, then this module's reads list must be walked at GC
186 // safepoint. Modules have the same life cycle as their defining class
187 // loaders and should be removed if dead.
188 void ModuleEntry::set_read_walk_required(ClassLoaderData* m_loader_data) {
189   assert(is_named(), "Cannot call set_read_walk_required on unnamed module");
190   assert_locked_or_safepoint(Module_lock);
191   if (!_must_walk_reads &&
192       loader_data() != m_loader_data &&
193       !m_loader_data->is_builtin_class_loader_data()) {
194     _must_walk_reads = true;
195     if (log_is_enabled(Trace, module)) {
196       ResourceMark rm;
197       log_trace(module)("ModuleEntry::set_read_walk_required(): module %s reads list must be walked",
198                         (name() != nullptr) ? name()->as_C_string() : UNNAMED_MODULE);
199     }
200   }
201 }
202 
203 // Set whether the module is open, i.e. all its packages are unqualifiedly exported
204 void ModuleEntry::set_is_open(bool is_open) {
205   assert_lock_strong(Module_lock);
206   _is_open = is_open;
207 }
208 
209 // Returns true if the module has a non-empty reads list. As such, the unnamed
210 // module will return false.
211 bool ModuleEntry::has_reads_list() const {
212   assert_locked_or_safepoint(Module_lock);
213   return ((reads() != nullptr) && !reads()->is_empty());
214 }
215 
216 // Purge dead module entries out of reads list.
217 void ModuleEntry::purge_reads() {
218   assert_locked_or_safepoint(Module_lock);
219 
220   if (_must_walk_reads && has_reads_list()) {
221     // This module's _must_walk_reads flag will be reset based
222     // on the remaining live modules on the reads list.
223     _must_walk_reads = false;
224 
225     if (log_is_enabled(Trace, module)) {
226       ResourceMark rm;
227       log_trace(module)("ModuleEntry::purge_reads(): module %s reads list being walked",
228                         (name() != nullptr) ? name()->as_C_string() : UNNAMED_MODULE);
229     }
230 
231     // Go backwards because this removes entries that are dead.
232     int len = reads()->length();
233     for (int idx = len - 1; idx >= 0; idx--) {
234       ModuleEntry* module_idx = reads()->at(idx);
235       ClassLoaderData* cld_idx = module_idx->loader_data();
236       if (cld_idx->is_unloading()) {
237         reads()->delete_at(idx);
238       } else {
239         // Update the need to walk this module's reads based on live modules
240         set_read_walk_required(cld_idx);
241       }
242     }
243   }
244 }
245 
246 void ModuleEntry::module_reads_do(ModuleClosure* f) {
247   assert_locked_or_safepoint(Module_lock);
248   assert(f != nullptr, "invariant");
249 
250   if (has_reads_list()) {
251     int reads_len = reads()->length();
252     for (ModuleEntry* m : *reads()) {
253       f->do_module(m);
254     }
255   }
256 }
257 
258 void ModuleEntry::delete_reads() {
259   delete reads();
260   _reads = nullptr;
261 }
262 
263 ModuleEntry::ModuleEntry(Handle module_handle,
264                          bool is_open, Symbol* name,
265                          Symbol* version, Symbol* location,
266                          ClassLoaderData* loader_data) :
267     _name(name),
268     _loader_data(loader_data),
269     _reads(nullptr),
270     _version(nullptr),
271     _location(nullptr),
272     CDS_ONLY(_shared_path_index(-1) COMMA)
273     _can_read_all_unnamed(false),
274     _has_default_read_edges(false),
275     _must_walk_reads(false),
276     _is_open(is_open),
277     _is_patched(false)
278     DEBUG_ONLY(COMMA _reads_is_archived(false)) {
279 
280   // Initialize fields specific to a ModuleEntry
281   if (_name == nullptr) {
282     // Unnamed modules can read all other unnamed modules.
283     set_can_read_all_unnamed();
284   } else {
285     _name->increment_refcount();
286   }
287 
288   if (!module_handle.is_null()) {
289     _module = loader_data->add_handle(module_handle);
290   }
291 
292   set_version(version);
293 
294   // may need to add CDS info
295   set_location(location);
296 
297   if (name != nullptr && ClassLoader::is_in_patch_mod_entries(name)) {
298     set_is_patched();
299     if (log_is_enabled(Trace, module, patch)) {
300       ResourceMark rm;
301       log_trace(module, patch)("Marked module %s as patched from --patch-module",
302                                name != nullptr ? name->as_C_string() : UNNAMED_MODULE);
303     }
304   }
305 
306   JFR_ONLY(INIT_ID(this);)
307 }
308 
309 ModuleEntry::~ModuleEntry() {
310   // Clean out the C heap allocated reads list first before freeing the entry
311   delete_reads();
312   Symbol::maybe_decrement_refcount(_name);
313   Symbol::maybe_decrement_refcount(_version);
314   Symbol::maybe_decrement_refcount(_location);
315 }
316 
317 ModuleEntry* ModuleEntry::create_unnamed_module(ClassLoaderData* cld) {
318   // The java.lang.Module for this loader's
319   // corresponding unnamed module can be found in the java.lang.ClassLoader object.
320   oop module = java_lang_ClassLoader::unnamedModule(cld->class_loader());
321 
322   // Ensure that the unnamed module was correctly set when the class loader was constructed.
323   // Guarantee will cause a recognizable crash if the user code has circumvented calling the ClassLoader constructor.
324   ResourceMark rm;
325   guarantee(java_lang_Module::is_instance(module),
326             "The unnamed module for ClassLoader %s, is null or not an instance of java.lang.Module. The class loader has not been initialized correctly.",
327             cld->loader_name_and_id());
328 
329   ModuleEntry* unnamed_module = new_unnamed_module_entry(Handle(Thread::current(), module), cld);
330 
331   // Store pointer to the ModuleEntry in the unnamed module's java.lang.Module object.
332   java_lang_Module::set_module_entry(module, unnamed_module);
333 
334   return unnamed_module;
335 }
336 
337 ModuleEntry* ModuleEntry::create_boot_unnamed_module(ClassLoaderData* cld) {
338   // For the boot loader, the java.lang.Module for the unnamed module
339   // is not known until a call to JVM_SetBootLoaderUnnamedModule is made. At
340   // this point initially create the ModuleEntry for the unnamed module.
341   ModuleEntry* unnamed_module = new_unnamed_module_entry(Handle(), cld);
342   assert(unnamed_module != nullptr, "boot loader unnamed module should not be null");
343   return unnamed_module;
344 }
345 
346 // When creating an unnamed module, this is called without holding the Module_lock.
347 // This is okay because the unnamed module gets created before the ClassLoaderData
348 // is available to other threads.
349 ModuleEntry* ModuleEntry::new_unnamed_module_entry(Handle module_handle, ClassLoaderData* cld) {
350 
351   ModuleEntry* entry = new ModuleEntry(module_handle, /*is_open*/true, /*name*/nullptr,
352                                        /*version*/ nullptr, /*location*/ nullptr,
353                                        cld);
354   // Unnamed modules can read all other unnamed modules.
355   assert(entry->can_read_all_unnamed(), "constructor set that");
356   return entry;
357 }
358 
359 ModuleEntryTable::ModuleEntryTable() { }
360 
361 ModuleEntryTable::~ModuleEntryTable() {
362   class ModuleEntryTableDeleter : public StackObj {
363    public:
364     bool do_entry(const SymbolHandle& name, ModuleEntry*& entry) {
365       if (log_is_enabled(Info, module, unload) || log_is_enabled(Debug, module)) {
366         ResourceMark rm;
367         const char* str = name->as_C_string();
368         log_info(module, unload)("unloading module %s", str);
369         log_debug(module)("ModuleEntryTable: deleting module: %s", str);
370       }
371       delete entry;
372       return true;
373     }
374   };
375 
376   ModuleEntryTableDeleter deleter;
377   _table.unlink(&deleter);
378   assert(_table.number_of_entries() == 0, "should have removed all entries");
379 
380 }
381 
382 void ModuleEntry::set_loader_data(ClassLoaderData* cld) {
383   assert(!cld->has_class_mirror_holder(), "Unexpected has_class_mirror_holder cld");
384   _loader_data = cld;
385 }
386 
387 #if INCLUDE_CDS_JAVA_HEAP
388 typedef ResourceHashtable<
389   const ModuleEntry*,
390   ModuleEntry*,
391   557, // prime number
392   AnyObj::C_HEAP> ArchivedModuleEntries;
393 static ArchivedModuleEntries* _archive_modules_entries = nullptr;
394 
395 #ifndef PRODUCT
396 static int _num_archived_module_entries = 0;
397 static int _num_inited_module_entries = 0;
398 #endif
399 
400 ModuleEntry* ModuleEntry::allocate_archived_entry() const {
401   assert(is_named(), "unnamed packages/modules are not archived");
402   ModuleEntry* archived_entry = (ModuleEntry*)ArchiveBuilder::rw_region_alloc(sizeof(ModuleEntry));
403   memcpy((void*)archived_entry, (void*)this, sizeof(ModuleEntry));
404   archived_entry->_archived_module_index = -1;
405 
406   if (_archive_modules_entries == nullptr) {
407     _archive_modules_entries = new (mtClass)ArchivedModuleEntries();
408   }
409   assert(_archive_modules_entries->get(this) == nullptr, "Each ModuleEntry must not be shared across ModuleEntryTables");
410   _archive_modules_entries->put(this, archived_entry);
411   DEBUG_ONLY(_num_archived_module_entries++);
412 
413   if (log_is_enabled(Info, cds, module)) {
414     ResourceMark rm;
415     LogStream ls(Log(cds, module)::info());
416     ls.print("Stored in archive: ");
417     archived_entry->print(&ls);
418   }
419   return archived_entry;
420 }
421 
422 bool ModuleEntry::has_been_archived() {
423   assert(!ArchiveBuilder::current()->is_in_buffer_space(this), "must be called on original ModuleEntry");
424   return _archive_modules_entries->contains(this);
425 }
426 
427 ModuleEntry* ModuleEntry::get_archived_entry(ModuleEntry* orig_entry) {
428   ModuleEntry** ptr = _archive_modules_entries->get(orig_entry);
429   assert(ptr != nullptr && *ptr != nullptr, "must have been allocated");
430   return *ptr;
431 }
432 
433 // This function is used to archive ModuleEntry::_reads and PackageEntry::_qualified_exports.
434 // GrowableArray cannot be directly archived, as it needs to be expandable at runtime.
435 // Write it out as an Array, and convert it back to GrowableArray at runtime.
436 Array<ModuleEntry*>* ModuleEntry::write_growable_array(ModuleEntry* module, GrowableArray<ModuleEntry*>* array) {
437   Array<ModuleEntry*>* archived_array = nullptr;
438   int length = (array == nullptr) ? 0 : array->length();
439   if (module->is_named()) {
440     if (Modules::is_dynamic_proxy_module(module)) {
441       // This is a dynamically generated module. Its opens and exports will be
442       // restored at runtime in the Java code. See comments in ArchivedData::restore().
443       return nullptr;
444     }
445   }
446   if (length > 0) {
447     archived_array = ArchiveBuilder::new_ro_array<ModuleEntry*>(length);
448     for (int i = 0; i < length; i++) {
449       ModuleEntry* archived_entry = get_archived_entry(array->at(i));
450       archived_array->at_put(i, archived_entry);
451       ArchivePtrMarker::mark_pointer((address*)archived_array->adr_at(i));
452     }
453   }
454 
455   return archived_array;
456 }
457 
458 GrowableArray<ModuleEntry*>* ModuleEntry::restore_growable_array(Array<ModuleEntry*>* archived_array) {
459   GrowableArray<ModuleEntry*>* array = nullptr;
460   int length = (archived_array == nullptr) ? 0 : archived_array->length();
461   if (length > 0) {
462     array = new (mtModule) GrowableArray<ModuleEntry*>(length, mtModule);
463     for (int i = 0; i < length; i++) {
464       ModuleEntry* archived_entry = archived_array->at(i);
465       array->append(archived_entry);
466     }
467   }
468 
469   return array;
470 }
471 
472 void ModuleEntry::iterate_symbols(MetaspaceClosure* closure) {
473   closure->push(&_name);
474   closure->push(&_version);
475   closure->push(&_location);
476 }
477 
478 void ModuleEntry::init_as_archived_entry() {
479   set_archived_reads(write_growable_array(this, reads()));
480 
481   _loader_data = nullptr;  // re-init at runtime
482   _shared_path_index = FileMapInfo::get_module_shared_path_index(_location);
483   if (name() != nullptr) {
484     _name = ArchiveBuilder::get_buffered_symbol(_name);
485     ArchivePtrMarker::mark_pointer((address*)&_name);
486   }
487   if (_version != nullptr) {
488     _version = ArchiveBuilder::get_buffered_symbol(_version);
489   }
490   if (_location != nullptr) {
491     _location = ArchiveBuilder::get_buffered_symbol(_location);
492   }
493   JFR_ONLY(set_trace_id(0);) // re-init at runtime
494 
495   ArchivePtrMarker::mark_pointer((address*)&_reads);
496   ArchivePtrMarker::mark_pointer((address*)&_version);
497   ArchivePtrMarker::mark_pointer((address*)&_location);
498 }
499 
500 void ModuleEntry::update_oops_in_archived_module(int root_oop_index) {
501   assert(CDSConfig::is_dumping_full_module_graph(), "sanity");
502   assert(_archived_module_index == -1, "must be set exactly once");
503   assert(root_oop_index >= 0, "sanity");
504 
505   _archived_module_index = root_oop_index;
506 
507   if (CDSConfig::is_dumping_final_static_archive()) {
508     OopHandle null_handle;
509     _shared_pd = null_handle;
510   } else {    
511     assert(shared_protection_domain() == nullptr, "never set during -Xshare:dump");
512   }
513   // Clear handles and restore at run time. Handles cannot be archived.
514   OopHandle null_handle;
515   _module = null_handle;
516 
517   // For verify_archived_module_entries()
518   DEBUG_ONLY(_num_inited_module_entries++);
519 }
520 
521 #ifndef PRODUCT
522 void ModuleEntry::verify_archived_module_entries() {
523   assert(_num_archived_module_entries == _num_inited_module_entries,
524          "%d ModuleEntries have been archived but %d of them have been properly initialized with archived java.lang.Module objects",
525          _num_archived_module_entries, _num_inited_module_entries);
526 }
527 #endif // PRODUCT
528 
529 void ModuleEntry::load_from_archive(ClassLoaderData* loader_data) {
530   assert(CDSConfig::is_using_full_module_graph(), "runtime only");
531   set_loader_data(loader_data);
532   set_reads(restore_growable_array(archived_reads()));
533   JFR_ONLY(INIT_ID(this);)
534 }
535 
536 void ModuleEntry::restore_archived_oops(ClassLoaderData* loader_data) {
537   assert(CDSConfig::is_using_full_module_graph(), "runtime only");
538   Handle module_handle(Thread::current(), HeapShared::get_root(_archived_module_index, /*clear=*/true));
539   assert(module_handle.not_null(), "huh");
540   set_module(loader_data->add_handle(module_handle));
541 
542   // This was cleared to zero during dump time -- we didn't save the value
543   // because it may be affected by archive relocation.
544   java_lang_Module::set_module_entry(module_handle(), this);
545 
546   assert(java_lang_Module::loader(module_handle()) == loader_data->class_loader(),
547          "must be set in dump time");
548 
549   if (log_is_enabled(Info, cds, module)) {
550     ResourceMark rm;
551     LogStream ls(Log(cds, module)::info());
552     ls.print("Restored from archive: ");
553     print(&ls);
554   }
555 }
556 
557 void ModuleEntry::clear_archived_oops() {
558   assert(CDSConfig::is_using_archive() && !CDSConfig::is_using_full_module_graph(), "runtime only");
559   HeapShared::clear_root(_archived_module_index);
560 }
561 
562 static int compare_module_by_name(ModuleEntry* a, ModuleEntry* b) {
563   assert(a == b || a->name() != b->name(), "no duplicated names");
564   return a->name()->fast_compare(b->name());
565 }
566 
567 void ModuleEntryTable::iterate_symbols(MetaspaceClosure* closure) {
568   auto syms = [&] (const SymbolHandle& key, ModuleEntry*& m) {
569       m->iterate_symbols(closure);
570   };
571   _table.iterate_all(syms);
572 }
573 
574 Array<ModuleEntry*>* ModuleEntryTable::allocate_archived_entries() {
575   Array<ModuleEntry*>* archived_modules = ArchiveBuilder::new_rw_array<ModuleEntry*>(_table.number_of_entries());
576   int n = 0;
577   auto grab = [&] (const SymbolHandle& key, ModuleEntry*& m) {
578     archived_modules->at_put(n++, m);
579   };
580   _table.iterate_all(grab);
581 
582   if (n > 1) {
583     // Always allocate in the same order to produce deterministic archive.
584     QuickSort::sort(archived_modules->data(), n, compare_module_by_name);
585   }
586   for (int i = 0; i < n; i++) {
587     archived_modules->at_put(i, archived_modules->at(i)->allocate_archived_entry());
588     ArchivePtrMarker::mark_pointer((address*)archived_modules->adr_at(i));
589   }
590   return archived_modules;
591 }
592 
593 void ModuleEntryTable::init_archived_entries(Array<ModuleEntry*>* archived_modules) {
594   assert(CDSConfig::is_dumping_full_module_graph(), "sanity");
595   for (int i = 0; i < archived_modules->length(); i++) {
596     ModuleEntry* archived_entry = archived_modules->at(i);
597     archived_entry->init_as_archived_entry();
598   }
599 }
600 
601 void ModuleEntryTable::load_archived_entries(ClassLoaderData* loader_data,
602                                              Array<ModuleEntry*>* archived_modules) {
603   assert(CDSConfig::is_using_full_module_graph(), "runtime only");
604 
605   for (int i = 0; i < archived_modules->length(); i++) {
606     ModuleEntry* archived_entry = archived_modules->at(i);
607     archived_entry->load_from_archive(loader_data);
608     _table.put(archived_entry->name(), archived_entry);
609   }
610 }
611 
612 void ModuleEntryTable::restore_archived_oops(ClassLoaderData* loader_data, Array<ModuleEntry*>* archived_modules) {
613   assert(CDSConfig::is_using_full_module_graph(), "runtime only");
614   for (int i = 0; i < archived_modules->length(); i++) {
615     ModuleEntry* archived_entry = archived_modules->at(i);
616     archived_entry->restore_archived_oops(loader_data);
617   }
618 }
619 #endif // INCLUDE_CDS_JAVA_HEAP
620 
621 // Create an entry in the class loader's module_entry_table.  It is the
622 // caller's responsibility to ensure that the entry has not already been
623 // created.
624 ModuleEntry* ModuleEntryTable::locked_create_entry(Handle module_handle,
625                                                    bool is_open,
626                                                    Symbol* module_name,
627                                                    Symbol* module_version,
628                                                    Symbol* module_location,
629                                                    ClassLoaderData* loader_data) {
630   assert(module_name != nullptr, "ModuleEntryTable locked_create_entry should never be called for unnamed module.");
631   assert(Module_lock->owned_by_self(), "should have the Module_lock");
632   assert(lookup_only(module_name) == nullptr, "Module already exists");
633   ModuleEntry* entry = new ModuleEntry(module_handle, is_open, module_name,
634                                        module_version, module_location, loader_data);
635   bool created = _table.put(module_name, entry);
636   assert(created, "should be");
637   return entry;
638 }
639 
640 // lookup_only by Symbol* to find a ModuleEntry.
641 ModuleEntry* ModuleEntryTable::lookup_only(Symbol* name) {
642   assert_locked_or_safepoint(Module_lock);
643   assert(name != nullptr, "name cannot be nullptr");
644   ModuleEntry** entry = _table.get(name);
645   return (entry == nullptr) ? nullptr : *entry;
646 }
647 
648 // Remove dead modules from all other alive modules' reads list.
649 // This should only occur at class unloading.
650 void ModuleEntryTable::purge_all_module_reads() {
651   assert_locked_or_safepoint(Module_lock);
652   auto purge = [&] (const SymbolHandle& key, ModuleEntry*& entry) {
653     entry->purge_reads();
654   };
655   _table.iterate_all(purge);
656 }
657 
658 void ModuleEntryTable::finalize_javabase(Handle module_handle, Symbol* version, Symbol* location) {
659   assert(Module_lock->owned_by_self(), "should have the Module_lock");
660   ClassLoaderData* boot_loader_data = ClassLoaderData::the_null_class_loader_data();
661   ModuleEntryTable* module_table = boot_loader_data->modules();
662 
663   assert(module_table != nullptr, "boot loader's ModuleEntryTable not defined");
664 
665   if (module_handle.is_null()) {
666     fatal("Unable to finalize module definition for " JAVA_BASE_NAME);
667   }
668 
669   // Set java.lang.Module, version and location for java.base
670   ModuleEntry* jb_module = javabase_moduleEntry();
671   assert(jb_module != nullptr, JAVA_BASE_NAME " ModuleEntry not defined");
672   jb_module->set_version(version);
673   jb_module->set_location(location);
674   // Once java.base's ModuleEntry _module field is set with the known
675   // java.lang.Module, java.base is considered "defined" to the VM.
676   jb_module->set_module(boot_loader_data->add_handle(module_handle));
677 
678   // Store pointer to the ModuleEntry for java.base in the java.lang.Module object.
679   java_lang_Module::set_module_entry(module_handle(), jb_module);
680 }
681 
682 // Within java.lang.Class instances there is a java.lang.Module field that must
683 // be set with the defining module.  During startup, prior to java.base's definition,
684 // classes needing their module field set are added to the fixup_module_list.
685 // Their module field is set once java.base's java.lang.Module is known to the VM.
686 void ModuleEntryTable::patch_javabase_entries(JavaThread* current, Handle module_handle) {
687   if (module_handle.is_null()) {
688     fatal("Unable to patch the module field of classes loaded prior to "
689           JAVA_BASE_NAME "'s definition, invalid java.lang.Module");
690   }
691 
692   // Do the fixups for the basic primitive types
693   java_lang_Class::set_module(Universe::int_mirror(), module_handle());
694   java_lang_Class::set_module(Universe::float_mirror(), module_handle());
695   java_lang_Class::set_module(Universe::double_mirror(), module_handle());
696   java_lang_Class::set_module(Universe::byte_mirror(), module_handle());
697   java_lang_Class::set_module(Universe::bool_mirror(), module_handle());
698   java_lang_Class::set_module(Universe::char_mirror(), module_handle());
699   java_lang_Class::set_module(Universe::long_mirror(), module_handle());
700   java_lang_Class::set_module(Universe::short_mirror(), module_handle());
701   java_lang_Class::set_module(Universe::void_mirror(), module_handle());
702 
703   // Do the fixups for classes that have already been created.
704   GrowableArray <Klass*>* list = java_lang_Class::fixup_module_field_list();
705   int list_length = list->length();
706   for (int i = 0; i < list_length; i++) {
707     Klass* k = list->at(i);
708     assert(k->is_klass(), "List should only hold classes");
709 #ifndef PRODUCT
710     if (HeapShared::is_a_test_class_in_unnamed_module(k)) {
711       // We allow -XX:ArchiveHeapTestClass to archive additional classes
712       // into the CDS heap, but these must be in the unnamed module.
713       ModuleEntry* unnamed_module = ClassLoaderData::the_null_class_loader_data()->unnamed_module();
714       Handle unnamed_module_handle(current, unnamed_module->module());
715       java_lang_Class::fixup_module_field(k, unnamed_module_handle);
716     } else
717 #endif
718     {
719       java_lang_Class::fixup_module_field(k, module_handle);
720     }
721     k->class_loader_data()->dec_keep_alive_ref_count();
722   }
723 
724   delete java_lang_Class::fixup_module_field_list();
725   java_lang_Class::set_fixup_module_field_list(nullptr);
726 }
727 
728 void ModuleEntryTable::print(outputStream* st) {
729   ResourceMark rm;
730   auto printer = [&] (const SymbolHandle& name, ModuleEntry*& entry) {
731     entry->print(st);
732   };
733   st->print_cr("Module Entry Table (table_size=%d, entries=%d)",
734                _table.table_size(), _table.number_of_entries());
735   assert_locked_or_safepoint(Module_lock);
736   _table.iterate_all(printer);
737 }
738 
739 void ModuleEntryTable::modules_do(void f(ModuleEntry*)) {
740   auto do_f = [&] (const SymbolHandle& key, ModuleEntry*& entry) {
741     f(entry);
742   };
743   assert_lock_strong(Module_lock);
744   _table.iterate_all(do_f);
745 }
746 
747 void ModuleEntryTable::modules_do(ModuleClosure* closure) {
748   auto do_f = [&] (const SymbolHandle& key, ModuleEntry*& entry) {
749     closure->do_module(entry);
750   };
751   assert_lock_strong(Module_lock);
752   _table.iterate_all(do_f);
753 }
754 
755 void ModuleEntry::print(outputStream* st) {
756   st->print_cr("entry " PTR_FORMAT " name %s module " PTR_FORMAT " loader %s version %s location %s strict %s",
757                p2i(this),
758                name() == nullptr ? UNNAMED_MODULE : name()->as_C_string(),
759                p2i(module()),
760                loader_data()->loader_name_and_id(),
761                version() != nullptr ? version()->as_C_string() : "nullptr",
762                location() != nullptr ? location()->as_C_string() : "nullptr",
763                BOOL_TO_STR(!can_read_all_unnamed()));
764 }
765 
766 void ModuleEntryTable::verify() {
767   auto do_f = [&] (const SymbolHandle& key, ModuleEntry*& entry) {
768     entry->verify();
769   };
770   assert_locked_or_safepoint(Module_lock);
771   _table.iterate_all(do_f);
772 }
773 
774 void ModuleEntry::verify() {
775   guarantee(loader_data() != nullptr, "A module entry must be associated with a loader.");
776 }