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