1 /*
   2  * Copyright (c) 2016, 2018, 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/classLoaderData.inline.hpp"
  28 #include "classfile/javaClasses.inline.hpp"
  29 #include "classfile/moduleEntry.hpp"
  30 #include "logging/log.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "oops/oopHandle.inline.hpp"
  33 #include "oops/symbol.hpp"
  34 #include "runtime/handles.inline.hpp"
  35 #include "runtime/safepoint.hpp"
  36 #include "utilities/events.hpp"
  37 #include "utilities/growableArray.hpp"
  38 #include "utilities/hashtable.inline.hpp"
  39 #include "utilities/ostream.hpp"
  40 
  41 ModuleEntry* ModuleEntryTable::_javabase_module = NULL;
  42 
  43 oop ModuleEntry::module() const { return _module.resolve(); }
  44 
  45 void ModuleEntry::set_location(Symbol* location) {
  46   if (_location != NULL) {
  47     // _location symbol's refcounts are managed by ModuleEntry,
  48     // must decrement the old one before updating.
  49     _location->decrement_refcount();
  50   }
  51 
  52   _location = location;
  53 
  54   if (location != NULL) {
  55     location->increment_refcount();
  56   }
  57 }
  58 
  59 // Return true if the module's version should be displayed in error messages,
  60 // logging, etc.
  61 // Return false if the module's version is null, if it is unnamed, or if the
  62 // module is not an upgradeable module.
  63 // Detect if the module is not upgradeable by checking:
  64 //     1. Module location is "jrt:/java." and its loader is boot or platform
  65 //     2. Module location is "jrt:/jdk.", its loader is one of the builtin loaders
  66 //        and its version is the same as module java.base's version
  67 // The above check is imprecise but should work in almost all cases.
  68 bool ModuleEntry::should_show_version() {
  69   if (version() == NULL || !is_named()) return false;
  70 
  71   if (location() != NULL) {
  72     ResourceMark rm;
  73     const char* loc = location()->as_C_string();
  74     ClassLoaderData* cld = loader_data();
  75 
  76     if ((cld->is_the_null_class_loader_data() || cld->is_platform_class_loader_data()) &&
  77         (strncmp(loc, "jrt:/java.", 10) == 0)) {
  78       return false;
  79     }
  80     if ((ModuleEntryTable::javabase_moduleEntry()->version()->fast_compare(version()) == 0) &&
  81         cld->is_permanent_class_loader_data() && (strncmp(loc, "jrt:/jdk.", 9) == 0)) {
  82       return false;
  83     }
  84   }
  85   return true;
  86 }
  87 
  88 void ModuleEntry::set_version(Symbol* version) {
  89   if (_version != NULL) {
  90     // _version symbol's refcounts are managed by ModuleEntry,
  91     // must decrement the old one before updating.
  92     _version->decrement_refcount();
  93   }
  94 
  95   _version = version;
  96 
  97   if (version != NULL) {
  98     version->increment_refcount();
  99   }
 100 }
 101 
 102 // Returns the shared ProtectionDomain
 103 oop ModuleEntry::shared_protection_domain() {
 104   return _pd.resolve();
 105 }
 106 
 107 // Set the shared ProtectionDomain atomically
 108 void ModuleEntry::set_shared_protection_domain(ClassLoaderData *loader_data,
 109                                                Handle pd_h) {
 110   // Create a handle for the shared ProtectionDomain and save it atomically.
 111   // init_handle_locked checks if someone beats us setting the _pd cache.
 112   loader_data->init_handle_locked(_pd, pd_h);
 113 }
 114 
 115 // Returns true if this module can read module m
 116 bool ModuleEntry::can_read(ModuleEntry* m) const {
 117   assert(m != NULL, "No module to lookup in this module's reads list");
 118 
 119   // Unnamed modules read everyone and all modules
 120   // read java.base.  If either of these conditions
 121   // hold, readability has been established.
 122   if (!this->is_named() ||
 123       (m == ModuleEntryTable::javabase_moduleEntry())) {
 124     return true;
 125   }
 126 
 127   MutexLocker m1(Module_lock);
 128   // This is a guard against possible race between agent threads that redefine
 129   // or retransform classes in this module. Only one of them is adding the
 130   // default read edges to the unnamed modules of the boot and app class loaders
 131   // with an upcall to jdk.internal.module.Modules.transformedByAgent.
 132   // At the same time, another thread can instrument the module classes by
 133   // injecting dependencies that require the default read edges for resolution.
 134   if (this->has_default_read_edges() && !m->is_named()) {
 135     ClassLoaderData* cld = m->loader_data();
 136     if (cld->is_the_null_class_loader_data() || cld->is_system_class_loader_data()) {
 137       return true; // default read edge
 138     }
 139   }
 140   if (!has_reads_list()) {
 141     return false;
 142   } else {
 143     return _reads->contains(m);
 144   }
 145 }
 146 
 147 // Add a new module to this module's reads list
 148 void ModuleEntry::add_read(ModuleEntry* m) {
 149   // Unnamed module is special cased and can read all modules
 150   if (!is_named()) {
 151     return;
 152   }
 153 
 154   MutexLocker m1(Module_lock);
 155   if (m == NULL) {
 156     set_can_read_all_unnamed();
 157   } else {
 158     if (_reads == NULL) {
 159       // Lazily create a module's reads list
 160       _reads = new (ResourceObj::C_HEAP, mtModule)GrowableArray<ModuleEntry*>(MODULE_READS_SIZE, true);
 161     }
 162 
 163     // Determine, based on this newly established read edge to module m,
 164     // if this module's read list should be walked at a GC safepoint.
 165     set_read_walk_required(m->loader_data());
 166 
 167     // Establish readability to module m
 168     _reads->append_if_missing(m);
 169   }
 170 }
 171 
 172 // If the module's loader, that a read edge is being established to, is
 173 // not the same loader as this module's and is not one of the 3 builtin
 174 // class loaders, then this module's reads list must be walked at GC
 175 // safepoint. Modules have the same life cycle as their defining class
 176 // loaders and should be removed if dead.
 177 void ModuleEntry::set_read_walk_required(ClassLoaderData* m_loader_data) {
 178   assert(is_named(), "Cannot call set_read_walk_required on unnamed module");
 179   assert_locked_or_safepoint(Module_lock);
 180   if (!_must_walk_reads &&
 181       loader_data() != m_loader_data &&
 182       !m_loader_data->is_builtin_class_loader_data()) {
 183     _must_walk_reads = true;
 184     if (log_is_enabled(Trace, module)) {
 185       ResourceMark rm;
 186       log_trace(module)("ModuleEntry::set_read_walk_required(): module %s reads list must be walked",
 187                         (name() != NULL) ? name()->as_C_string() : UNNAMED_MODULE);
 188     }
 189   }
 190 }
 191 
 192 // Set whether the module is open, i.e. all its packages are unqualifiedly exported
 193 void ModuleEntry::set_is_open(bool is_open) {
 194   assert_lock_strong(Module_lock);
 195   _is_open = is_open;
 196 }
 197 
 198 // Returns true if the module has a non-empty reads list. As such, the unnamed
 199 // module will return false.
 200 bool ModuleEntry::has_reads_list() const {
 201   assert_locked_or_safepoint(Module_lock);
 202   return ((_reads != NULL) && !_reads->is_empty());
 203 }
 204 
 205 // Purge dead module entries out of reads list.
 206 void ModuleEntry::purge_reads() {
 207   assert_locked_or_safepoint(Module_lock);
 208 
 209   if (_must_walk_reads && has_reads_list()) {
 210     // This module's _must_walk_reads flag will be reset based
 211     // on the remaining live modules on the reads list.
 212     _must_walk_reads = false;
 213 
 214     if (log_is_enabled(Trace, module)) {
 215       ResourceMark rm;
 216       log_trace(module)("ModuleEntry::purge_reads(): module %s reads list being walked",
 217                         (name() != NULL) ? name()->as_C_string() : UNNAMED_MODULE);
 218     }
 219 
 220     // Go backwards because this removes entries that are dead.
 221     int len = _reads->length();
 222     for (int idx = len - 1; idx >= 0; idx--) {
 223       ModuleEntry* module_idx = _reads->at(idx);
 224       ClassLoaderData* cld_idx = module_idx->loader_data();
 225       if (cld_idx->is_unloading()) {
 226         _reads->delete_at(idx);
 227       } else {
 228         // Update the need to walk this module's reads based on live modules
 229         set_read_walk_required(cld_idx);
 230       }
 231     }
 232   }
 233 }
 234 
 235 void ModuleEntry::module_reads_do(ModuleClosure* f) {
 236   assert_locked_or_safepoint(Module_lock);
 237   assert(f != NULL, "invariant");
 238 
 239   if (has_reads_list()) {
 240     int reads_len = _reads->length();
 241     for (int i = 0; i < reads_len; ++i) {
 242       f->do_module(_reads->at(i));
 243     }
 244   }
 245 }
 246 
 247 void ModuleEntry::delete_reads() {
 248   delete _reads;
 249   _reads = NULL;
 250 }
 251 
 252 ModuleEntry* ModuleEntry::create_unnamed_module(ClassLoaderData* cld) {
 253   // The java.lang.Module for this loader's
 254   // corresponding unnamed module can be found in the java.lang.ClassLoader object.
 255   oop module = java_lang_ClassLoader::unnamedModule(cld->class_loader());
 256 
 257   // Ensure that the unnamed module was correctly set when the class loader was constructed.
 258   // Guarantee will cause a recognizable crash if the user code has circumvented calling the ClassLoader constructor.
 259   ResourceMark rm;
 260   guarantee(java_lang_Module::is_instance(module),
 261             "The unnamed module for ClassLoader %s, is null or not an instance of java.lang.Module. The class loader has not been initialized correctly.",
 262             cld->loader_name_and_id());
 263 
 264   ModuleEntry* unnamed_module = new_unnamed_module_entry(Handle(Thread::current(), module), cld);
 265 
 266   // Store pointer to the ModuleEntry in the unnamed module's java.lang.Module object.
 267   java_lang_Module::set_module_entry(module, unnamed_module);
 268 
 269   return unnamed_module;
 270 }
 271 
 272 ModuleEntry* ModuleEntry::create_boot_unnamed_module(ClassLoaderData* cld) {
 273   // For the boot loader, the java.lang.Module for the unnamed module
 274   // is not known until a call to JVM_SetBootLoaderUnnamedModule is made. At
 275   // this point initially create the ModuleEntry for the unnamed module.
 276   ModuleEntry* unnamed_module = new_unnamed_module_entry(Handle(), cld);
 277   assert(unnamed_module != NULL, "boot loader unnamed module should not be null");
 278   return unnamed_module;
 279 }
 280 
 281 // When creating an unnamed module, this is called without holding the Module_lock.
 282 // This is okay because the unnamed module gets created before the ClassLoaderData
 283 // is available to other threads.
 284 ModuleEntry* ModuleEntry::new_unnamed_module_entry(Handle module_handle, ClassLoaderData* cld) {
 285   ModuleEntry* entry = (ModuleEntry*) NEW_C_HEAP_ARRAY(char, sizeof(ModuleEntry), mtModule);
 286 
 287   // Initialize everything BasicHashtable would
 288   entry->set_next(NULL);
 289   entry->set_hash(0);
 290   entry->set_literal(NULL);
 291 
 292   // Initialize fields specific to a ModuleEntry
 293   entry->init();
 294 
 295   // Unnamed modules can read all other unnamed modules.
 296   entry->set_can_read_all_unnamed();
 297 
 298   if (!module_handle.is_null()) {
 299     entry->set_module(cld->add_handle(module_handle));
 300   }
 301 
 302   entry->set_loader_data(cld);
 303   entry->_is_open = true;
 304 
 305   JFR_ONLY(INIT_ID(entry);)
 306 
 307   return entry;
 308 }
 309 
 310 void ModuleEntry::delete_unnamed_module() {
 311   // Do not need unlink_entry() since the unnamed module is not in the hashtable
 312   FREE_C_HEAP_ARRAY(char, this);
 313 }
 314 
 315 ModuleEntryTable::ModuleEntryTable(int table_size)
 316   : Hashtable<Symbol*, mtModule>(table_size, sizeof(ModuleEntry))
 317 {
 318 }
 319 
 320 ModuleEntryTable::~ModuleEntryTable() {
 321   // Walk through all buckets and all entries in each bucket,
 322   // freeing each entry.
 323   for (int i = 0; i < table_size(); ++i) {
 324     for (ModuleEntry* m = bucket(i); m != NULL;) {
 325       ModuleEntry* to_remove = m;
 326       // read next before freeing.
 327       m = m->next();
 328 
 329       ResourceMark rm;
 330       if (to_remove->name() != NULL) {
 331         log_info(module, unload)("unloading module %s", to_remove->name()->as_C_string());
 332       }
 333       log_debug(module)("ModuleEntryTable: deleting module: %s", to_remove->name() != NULL ?
 334                         to_remove->name()->as_C_string() : UNNAMED_MODULE);
 335 
 336       // Clean out the C heap allocated reads list first before freeing the entry
 337       to_remove->delete_reads();
 338       if (to_remove->name() != NULL) {
 339         to_remove->name()->decrement_refcount();
 340       }
 341       if (to_remove->version() != NULL) {
 342         to_remove->version()->decrement_refcount();
 343       }
 344       if (to_remove->location() != NULL) {
 345         to_remove->location()->decrement_refcount();
 346       }
 347 
 348       // Unlink from the Hashtable prior to freeing
 349       unlink_entry(to_remove);
 350       FREE_C_HEAP_ARRAY(char, to_remove);
 351     }
 352   }
 353   assert(number_of_entries() == 0, "should have removed all entries");
 354   assert(new_entry_free_list() == NULL, "entry present on ModuleEntryTable's free list");
 355 }
 356 
 357 ModuleEntry* ModuleEntryTable::new_entry(unsigned int hash, Handle module_handle,
 358                                          bool is_open, Symbol* name,
 359                                          Symbol* version, Symbol* location,
 360                                          ClassLoaderData* loader_data) {
 361   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 362   ModuleEntry* entry = (ModuleEntry*)Hashtable<Symbol*, mtModule>::allocate_new_entry(hash, name);
 363 
 364   // Initialize fields specific to a ModuleEntry
 365   entry->init();
 366   if (name != NULL) {
 367     name->increment_refcount();
 368   } else {
 369     // Unnamed modules can read all other unnamed modules.
 370     entry->set_can_read_all_unnamed();
 371   }
 372 
 373   if (!module_handle.is_null()) {
 374     entry->set_module(loader_data->add_handle(module_handle));
 375   }
 376 
 377   entry->set_loader_data(loader_data);
 378   entry->set_version(version);
 379   entry->set_location(location);
 380   entry->set_is_open(is_open);
 381 
 382   if (ClassLoader::is_in_patch_mod_entries(name)) {
 383     entry->set_is_patched();
 384     if (log_is_enabled(Trace, module, patch)) {
 385       ResourceMark rm;
 386       log_trace(module, patch)("Marked module %s as patched from --patch-module",
 387                                name != NULL ? name->as_C_string() : UNNAMED_MODULE);
 388     }
 389   }
 390 
 391   JFR_ONLY(INIT_ID(entry);)
 392 
 393   return entry;
 394 }
 395 
 396 void ModuleEntryTable::add_entry(int index, ModuleEntry* new_entry) {
 397   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 398   Hashtable<Symbol*, mtModule>::add_entry(index, (HashtableEntry<Symbol*, mtModule>*)new_entry);
 399 }
 400 
 401 ModuleEntry* ModuleEntryTable::locked_create_entry_or_null(Handle module_handle,
 402                                                            bool is_open,
 403                                                            Symbol* module_name,
 404                                                            Symbol* module_version,
 405                                                            Symbol* module_location,
 406                                                            ClassLoaderData* loader_data) {
 407   assert(module_name != NULL, "ModuleEntryTable locked_create_entry_or_null should never be called for unnamed module.");
 408   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 409   // Check if module already exists.
 410   if (lookup_only(module_name) != NULL) {
 411     return NULL;
 412   } else {
 413     ModuleEntry* entry = new_entry(compute_hash(module_name), module_handle, is_open, module_name,
 414                                    module_version, module_location, loader_data);
 415     add_entry(index_for(module_name), entry);
 416     return entry;
 417   }
 418 }
 419 
 420 // lookup_only by Symbol* to find a ModuleEntry.
 421 ModuleEntry* ModuleEntryTable::lookup_only(Symbol* name) {
 422   assert(name != NULL, "name cannot be NULL");
 423   int index = index_for(name);
 424   for (ModuleEntry* m = bucket(index); m != NULL; m = m->next()) {
 425     if (m->name()->fast_compare(name) == 0) {
 426       return m;
 427     }
 428   }
 429   return NULL;
 430 }
 431 
 432 // Remove dead modules from all other alive modules' reads list.
 433 // This should only occur at class unloading.
 434 void ModuleEntryTable::purge_all_module_reads() {
 435   assert_locked_or_safepoint(Module_lock);
 436   for (int i = 0; i < table_size(); i++) {
 437     for (ModuleEntry* entry = bucket(i);
 438                       entry != NULL;
 439                       entry = entry->next()) {
 440       entry->purge_reads();
 441     }
 442   }
 443 }
 444 
 445 void ModuleEntryTable::finalize_javabase(Handle module_handle, Symbol* version, Symbol* location) {
 446   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 447   ClassLoaderData* boot_loader_data = ClassLoaderData::the_null_class_loader_data();
 448   ModuleEntryTable* module_table = boot_loader_data->modules();
 449 
 450   assert(module_table != NULL, "boot loader's ModuleEntryTable not defined");
 451 
 452   if (module_handle.is_null()) {
 453     fatal("Unable to finalize module definition for " JAVA_BASE_NAME);
 454   }
 455 
 456   // Set java.lang.Module, version and location for java.base
 457   ModuleEntry* jb_module = javabase_moduleEntry();
 458   assert(jb_module != NULL, JAVA_BASE_NAME " ModuleEntry not defined");
 459   jb_module->set_version(version);
 460   jb_module->set_location(location);
 461   // Once java.base's ModuleEntry _module field is set with the known
 462   // java.lang.Module, java.base is considered "defined" to the VM.
 463   jb_module->set_module(boot_loader_data->add_handle(module_handle));
 464 
 465   // Store pointer to the ModuleEntry for java.base in the java.lang.Module object.
 466   java_lang_Module::set_module_entry(module_handle(), jb_module);
 467 }
 468 
 469 // Within java.lang.Class instances there is a java.lang.Module field that must
 470 // be set with the defining module.  During startup, prior to java.base's definition,
 471 // classes needing their module field set are added to the fixup_module_list.
 472 // Their module field is set once java.base's java.lang.Module is known to the VM.
 473 void ModuleEntryTable::patch_javabase_entries(Handle module_handle) {
 474   if (module_handle.is_null()) {
 475     fatal("Unable to patch the module field of classes loaded prior to "
 476           JAVA_BASE_NAME "'s definition, invalid java.lang.Module");
 477   }
 478 
 479   // Do the fixups for the basic primitive types
 480   java_lang_Class::set_module(Universe::int_mirror(), module_handle());
 481   java_lang_Class::set_module(Universe::float_mirror(), module_handle());
 482   java_lang_Class::set_module(Universe::double_mirror(), module_handle());
 483   java_lang_Class::set_module(Universe::byte_mirror(), module_handle());
 484   java_lang_Class::set_module(Universe::bool_mirror(), module_handle());
 485   java_lang_Class::set_module(Universe::char_mirror(), module_handle());
 486   java_lang_Class::set_module(Universe::long_mirror(), module_handle());
 487   java_lang_Class::set_module(Universe::short_mirror(), module_handle());
 488   java_lang_Class::set_module(Universe::void_mirror(), module_handle());
 489 
 490   // Do the fixups for classes that have already been created.
 491   GrowableArray <Klass*>* list = java_lang_Class::fixup_module_field_list();
 492   int list_length = list->length();
 493   for (int i = 0; i < list_length; i++) {
 494     Klass* k = list->at(i);
 495     assert(k->is_klass(), "List should only hold classes");
 496     java_lang_Class::fixup_module_field(k, module_handle);
 497     k->class_loader_data()->dec_keep_alive();
 498   }
 499 
 500   delete java_lang_Class::fixup_module_field_list();
 501   java_lang_Class::set_fixup_module_field_list(NULL);
 502 }
 503 
 504 void ModuleEntryTable::print(outputStream* st) {
 505   st->print_cr("Module Entry Table (table_size=%d, entries=%d)",
 506                table_size(), number_of_entries());
 507   for (int i = 0; i < table_size(); i++) {
 508     for (ModuleEntry* probe = bucket(i);
 509                               probe != NULL;
 510                               probe = probe->next()) {
 511       probe->print(st);
 512     }
 513   }
 514 }
 515 
 516 void ModuleEntry::print(outputStream* st) {
 517   ResourceMark rm;
 518   st->print_cr("entry " PTR_FORMAT " name %s module " PTR_FORMAT " loader %s version %s location %s strict %s next " PTR_FORMAT,
 519                p2i(this),
 520                name() == NULL ? UNNAMED_MODULE : name()->as_C_string(),
 521                p2i(module()),
 522                loader_data()->loader_name_and_id(),
 523                version() != NULL ? version()->as_C_string() : "NULL",
 524                location() != NULL ? location()->as_C_string() : "NULL",
 525                BOOL_TO_STR(!can_read_all_unnamed()), p2i(next()));
 526 }
 527 
 528 void ModuleEntryTable::verify() {
 529   verify_table<ModuleEntry>("Module Entry Table");
 530 }
 531 
 532 void ModuleEntry::verify() {
 533   guarantee(loader_data() != NULL, "A module entry must be associated with a loader.");
 534 }