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