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