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