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