1 /*
   2  * Copyright (c) 2016, 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 "classfile/classLoaderData.hpp"
  27 #include "classfile/javaClasses.hpp"
  28 #include "classfile/moduleEntry.hpp"
  29 #include "logging/log.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/symbol.hpp"
  32 #include "prims/jni.h"
  33 #include "runtime/handles.inline.hpp"
  34 #include "runtime/safepoint.hpp"
  35 #include "trace/traceMacros.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 void ModuleEntry::set_location(Symbol* location) {
  44   if (_location != NULL) {
  45     // _location symbol's refcounts are managed by ModuleEntry,
  46     // must decrement the old one before updating.
  47     _location->decrement_refcount();
  48   }
  49 
  50   _location = location;
  51 
  52   if (location != NULL) {
  53     location->increment_refcount();
  54   }
  55 }
  56 
  57 bool ModuleEntry::is_non_jdk_module() {
  58   ResourceMark rm;
  59   if (location() != NULL) {
  60     const char* loc = location()->as_C_string();
  61     if (strncmp(loc, "jrt:/java.", 10) != 0 && strncmp(loc, "jrt:/jdk.", 9) != 0) {
  62       return true;
  63     }
  64   }
  65   return false;
  66 }
  67 
  68 void ModuleEntry::set_version(Symbol* version) {
  69   if (_version != NULL) {
  70     // _version symbol's refcounts are managed by ModuleEntry,
  71     // must decrement the old one before updating.
  72     _version->decrement_refcount();
  73   }
  74 
  75   _version = version;
  76 
  77   if (version != NULL) {
  78     version->increment_refcount();
  79   }
  80 }
  81 
  82 // Returns the shared ProtectionDomain
  83 Handle ModuleEntry::shared_protection_domain() {
  84   return Handle(JNIHandles::resolve(_pd));
  85 }
  86 
  87 // Set the shared ProtectionDomain atomically
  88 void ModuleEntry::set_shared_protection_domain(ClassLoaderData *loader_data,
  89                                                Handle pd_h) {
  90   // Create a JNI handle for the shared ProtectionDomain and save it atomically.
  91   // If someone beats us setting the _pd cache, the created JNI handle is destroyed.
  92   jobject obj = loader_data->add_handle(pd_h);
  93   if (Atomic::cmpxchg_ptr(obj, &_pd, NULL) != NULL) {
  94     loader_data->remove_handle(obj);
  95   }
  96 }
  97 
  98 // Returns true if this module can read module m
  99 bool ModuleEntry::can_read(ModuleEntry* m) const {
 100   assert(m != NULL, "No module to lookup in this module's reads list");
 101 
 102   // Unnamed modules read everyone and all modules
 103   // read java.base.  If either of these conditions
 104   // hold, readability has been established.
 105   if (!this->is_named() ||
 106       (m == ModuleEntryTable::javabase_moduleEntry())) {
 107     return true;
 108   }
 109 
 110   MutexLocker m1(Module_lock);
 111   if (!has_reads()) {
 112     return false;
 113   } else {
 114     return _reads->contains(m);
 115   }
 116 }
 117 
 118 // Add a new module to this module's reads list
 119 void ModuleEntry::add_read(ModuleEntry* m) {
 120   MutexLocker m1(Module_lock);
 121   if (m == NULL) {
 122     set_can_read_all_unnamed();
 123   } else {
 124     if (_reads == NULL) {
 125       // Lazily create a module's reads list
 126       _reads = new (ResourceObj::C_HEAP, mtModule)GrowableArray<ModuleEntry*>(MODULE_READS_SIZE, true);
 127     }
 128 
 129     // Determine, based on this newly established read edge to module m,
 130     // if this module's read list should be walked at a GC safepoint.
 131     set_read_walk_required(m->loader_data());
 132 
 133     // Establish readability to module m
 134     _reads->append_if_missing(m);
 135   }
 136 }
 137 
 138 // If the module's loader, that a read edge is being established to, is
 139 // not the same loader as this module's and is not one of the 3 builtin
 140 // class loaders, then this module's reads list must be walked at GC
 141 // safepoint. Modules have the same life cycle as their defining class
 142 // loaders and should be removed if dead.
 143 void ModuleEntry::set_read_walk_required(ClassLoaderData* m_loader_data) {
 144   assert_locked_or_safepoint(Module_lock);
 145   if (!_must_walk_reads &&
 146       loader_data() != m_loader_data &&
 147       !m_loader_data->is_builtin_class_loader_data()) {
 148     _must_walk_reads = true;
 149     if (log_is_enabled(Trace, modules)) {
 150       ResourceMark rm;
 151       log_trace(modules)("ModuleEntry::set_read_walk_required(): module %s reads list must be walked",
 152                          (name() != NULL) ? name()->as_C_string() : UNNAMED_MODULE);
 153     }
 154   }
 155 }
 156 
 157 bool ModuleEntry::has_reads() const {
 158   assert_locked_or_safepoint(Module_lock);
 159   return ((_reads != NULL) && !_reads->is_empty());
 160 }
 161 
 162 // Purge dead module entries out of reads list.
 163 void ModuleEntry::purge_reads() {
 164   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 165 
 166   if (_must_walk_reads && has_reads()) {
 167     // This module's _must_walk_reads flag will be reset based
 168     // on the remaining live modules on the reads list.
 169     _must_walk_reads = false;
 170 
 171     if (log_is_enabled(Trace, modules)) {
 172       ResourceMark rm;
 173       log_trace(modules)("ModuleEntry::purge_reads(): module %s reads list being walked",
 174                          (name() != NULL) ? name()->as_C_string() : UNNAMED_MODULE);
 175     }
 176 
 177     // Go backwards because this removes entries that are dead.
 178     int len = _reads->length();
 179     for (int idx = len - 1; idx >= 0; idx--) {
 180       ModuleEntry* module_idx = _reads->at(idx);
 181       ClassLoaderData* cld_idx = module_idx->loader_data();
 182       if (cld_idx->is_unloading()) {
 183         _reads->delete_at(idx);
 184       } else {
 185         // Update the need to walk this module's reads based on live modules
 186         set_read_walk_required(cld_idx);
 187       }
 188     }
 189   }
 190 }
 191 
 192 void ModuleEntry::module_reads_do(ModuleClosure* const f) {
 193   assert_locked_or_safepoint(Module_lock);
 194   assert(f != NULL, "invariant");
 195 
 196   if (has_reads()) {
 197     int reads_len = _reads->length();
 198     for (int i = 0; i < reads_len; ++i) {
 199       f->do_module(_reads->at(i));
 200     }
 201   }
 202 }
 203 
 204 void ModuleEntry::delete_reads() {
 205   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 206   delete _reads;
 207   _reads = NULL;
 208 }
 209 
 210 ModuleEntryTable::ModuleEntryTable(int table_size)
 211   : Hashtable<Symbol*, mtModule>(table_size, sizeof(ModuleEntry)), _unnamed_module(NULL)
 212 {
 213 }
 214 
 215 ModuleEntryTable::~ModuleEntryTable() {
 216   assert_locked_or_safepoint(Module_lock);
 217 
 218   // Walk through all buckets and all entries in each bucket,
 219   // freeing each entry.
 220   for (int i = 0; i < table_size(); ++i) {
 221     for (ModuleEntry* m = bucket(i); m != NULL;) {
 222       ModuleEntry* to_remove = m;
 223       // read next before freeing.
 224       m = m->next();
 225 
 226       ResourceMark rm;
 227       log_debug(modules)("ModuleEntryTable: deleting module: %s", to_remove->name() != NULL ?
 228                          to_remove->name()->as_C_string() : UNNAMED_MODULE);
 229 
 230       // Clean out the C heap allocated reads list first before freeing the entry
 231       to_remove->delete_reads();
 232       if (to_remove->name() != NULL) {
 233         to_remove->name()->decrement_refcount();
 234       }
 235       if (to_remove->version() != NULL) {
 236         to_remove->version()->decrement_refcount();
 237       }
 238       if (to_remove->location() != NULL) {
 239         to_remove->location()->decrement_refcount();
 240       }
 241 
 242       // Unlink from the Hashtable prior to freeing
 243       unlink_entry(to_remove);
 244       FREE_C_HEAP_ARRAY(char, to_remove);
 245     }
 246   }
 247   assert(number_of_entries() == 0, "should have removed all entries");
 248   assert(new_entry_free_list() == NULL, "entry present on ModuleEntryTable's free list");
 249   free_buckets();
 250 }
 251 
 252 void ModuleEntryTable::create_unnamed_module(ClassLoaderData* loader_data) {
 253   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 254 
 255   // Each ModuleEntryTable has exactly one unnamed module
 256   if (loader_data->is_the_null_class_loader_data()) {
 257     // For the boot loader, the java.lang.reflect.Module for the unnamed module
 258     // is not known until a call to JVM_SetBootLoaderUnnamedModule is made. At
 259     // this point initially create the ModuleEntry for the unnamed module.
 260     _unnamed_module = new_entry(0, Handle(NULL), NULL, NULL, NULL, loader_data);
 261   } else {
 262     // For all other class loaders the java.lang.reflect.Module for their
 263     // corresponding unnamed module can be found in the java.lang.ClassLoader object.
 264     oop module = java_lang_ClassLoader::unnamedModule(loader_data->class_loader());
 265     _unnamed_module = new_entry(0, Handle(module), NULL, NULL, NULL, loader_data);
 266 
 267     // Store pointer to the ModuleEntry in the unnamed module's java.lang.reflect.Module
 268     // object.
 269     java_lang_reflect_Module::set_module_entry(module, _unnamed_module);
 270   }
 271 
 272   // Add to bucket 0, no name to hash on
 273   add_entry(0, _unnamed_module);
 274 }
 275 
 276 ModuleEntry* ModuleEntryTable::new_entry(unsigned int hash, Handle module_handle, Symbol* name,
 277                                          Symbol* version, Symbol* location,
 278                                          ClassLoaderData* loader_data) {
 279   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 280   ModuleEntry* entry = (ModuleEntry*) NEW_C_HEAP_ARRAY(char, entry_size(), mtModule);
 281 
 282   // Initialize everything BasicHashtable would
 283   entry->set_next(NULL);
 284   entry->set_hash(hash);
 285   entry->set_literal(name);
 286 
 287   // Initialize fields specific to a ModuleEntry
 288   entry->init();
 289   if (name != NULL) {
 290     name->increment_refcount();
 291   } else {
 292     // Unnamed modules can read all other unnamed modules.
 293     entry->set_can_read_all_unnamed();
 294   }
 295 
 296   if (!module_handle.is_null()) {
 297     entry->set_module(loader_data->add_handle(module_handle));
 298   }
 299 
 300   entry->set_loader_data(loader_data);
 301   entry->set_version(version);
 302   entry->set_location(location);
 303 
 304   TRACE_INIT_MODULE_ID(entry);
 305 
 306   return entry;
 307 }
 308 
 309 void ModuleEntryTable::add_entry(int index, ModuleEntry* new_entry) {
 310   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 311   Hashtable<Symbol*, mtModule>::add_entry(index, (HashtableEntry<Symbol*, mtModule>*)new_entry);
 312 }
 313 
 314 ModuleEntry* ModuleEntryTable::locked_create_entry_or_null(Handle module_handle,
 315                                                            Symbol* module_name,
 316                                                            Symbol* module_version,
 317                                                            Symbol* module_location,
 318                                                            ClassLoaderData* loader_data) {
 319   assert(module_name != NULL, "ModuleEntryTable locked_create_entry_or_null should never be called for unnamed module.");
 320   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 321   // Check if module already exists.
 322   if (lookup_only(module_name) != NULL) {
 323     return NULL;
 324   } else {
 325     ModuleEntry* entry = new_entry(compute_hash(module_name), module_handle, module_name,
 326                                    module_version, module_location, loader_data);
 327     add_entry(index_for(module_name), entry);
 328     return entry;
 329   }
 330 }
 331 
 332 // lookup_only by Symbol* to find a ModuleEntry.
 333 ModuleEntry* ModuleEntryTable::lookup_only(Symbol* name) {
 334   if (name == NULL) {
 335     // Return this table's unnamed module
 336     return unnamed_module();
 337   }
 338   int index = index_for(name);
 339   for (ModuleEntry* m = bucket(index); m != NULL; m = m->next()) {
 340     if (m->name()->fast_compare(name) == 0) {
 341       return m;
 342     }
 343   }
 344   return NULL;
 345 }
 346 
 347 // Remove dead modules from all other alive modules' reads list.
 348 // This should only occur at class unloading.
 349 void ModuleEntryTable::purge_all_module_reads() {
 350   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 351   for (int i = 0; i < table_size(); i++) {
 352     for (ModuleEntry* entry = bucket(i);
 353                       entry != NULL;
 354                       entry = entry->next()) {
 355       entry->purge_reads();
 356     }
 357   }
 358 }
 359 
 360 void ModuleEntryTable::finalize_javabase(Handle module_handle, Symbol* version, Symbol* location) {
 361   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 362   ClassLoaderData* boot_loader_data = ClassLoaderData::the_null_class_loader_data();
 363   ModuleEntryTable* module_table = boot_loader_data->modules();
 364 
 365   assert(module_table != NULL, "boot loader's ModuleEntryTable not defined");
 366 
 367   if (module_handle.is_null()) {
 368     fatal("Unable to finalize module definition for java.base");
 369   }
 370 
 371   // Set java.lang.reflect.Module, version and location for java.base
 372   ModuleEntry* jb_module = javabase_moduleEntry();
 373   assert(jb_module != NULL, "java.base ModuleEntry not defined");
 374   jb_module->set_version(version);
 375   jb_module->set_location(location);
 376   // Once java.base's ModuleEntry _module field is set with the known
 377   // java.lang.reflect.Module, java.base is considered "defined" to the VM.
 378   jb_module->set_module(boot_loader_data->add_handle(module_handle));
 379 
 380   // Store pointer to the ModuleEntry for java.base in the java.lang.reflect.Module object.
 381   java_lang_reflect_Module::set_module_entry(module_handle(), jb_module);
 382 }
 383 
 384 // Within java.lang.Class instances there is a java.lang.reflect.Module field
 385 // that must be set with the defining module.  During startup, prior to java.base's
 386 // definition, classes needing their module field set are added to the fixup_module_list.
 387 // Their module field is set once java.base's java.lang.reflect.Module is known to the VM.
 388 void ModuleEntryTable::patch_javabase_entries(Handle module_handle) {
 389   if (module_handle.is_null()) {
 390     fatal("Unable to patch the module field of classes loaded prior to java.base's definition, invalid java.lang.reflect.Module");
 391   }
 392 
 393   // Do the fixups for the basic primitive types
 394   java_lang_Class::set_module(Universe::int_mirror(), module_handle());
 395   java_lang_Class::set_module(Universe::float_mirror(), module_handle());
 396   java_lang_Class::set_module(Universe::double_mirror(), module_handle());
 397   java_lang_Class::set_module(Universe::byte_mirror(), module_handle());
 398   java_lang_Class::set_module(Universe::bool_mirror(), module_handle());
 399   java_lang_Class::set_module(Universe::char_mirror(), module_handle());
 400   java_lang_Class::set_module(Universe::long_mirror(), module_handle());
 401   java_lang_Class::set_module(Universe::short_mirror(), module_handle());
 402   java_lang_Class::set_module(Universe::void_mirror(), module_handle());
 403 
 404   // Do the fixups for classes that have already been created.
 405   GrowableArray <Klass*>* list = java_lang_Class::fixup_module_field_list();
 406   int list_length = list->length();
 407   for (int i = 0; i < list_length; i++) {
 408     Klass* k = list->at(i);
 409     assert(k->is_klass(), "List should only hold classes");
 410     java_lang_Class::fixup_module_field(KlassHandle(k), module_handle);
 411     k->class_loader_data()->dec_keep_alive();
 412   }
 413 
 414   delete java_lang_Class::fixup_module_field_list();
 415   java_lang_Class::set_fixup_module_field_list(NULL);
 416 }
 417 
 418 void ModuleEntryTable::print(outputStream* st) {
 419   st->print_cr("Module Entry Table (table_size=%d, entries=%d)",
 420                table_size(), number_of_entries());
 421   for (int i = 0; i < table_size(); i++) {
 422     for (ModuleEntry* probe = bucket(i);
 423                               probe != NULL;
 424                               probe = probe->next()) {
 425       probe->print(st);
 426     }
 427   }
 428 }
 429 
 430 void ModuleEntry::print(outputStream* st) {
 431   ResourceMark rm;
 432   st->print_cr("entry " PTR_FORMAT " name %s module " PTR_FORMAT " loader %s version %s location %s strict %s next " PTR_FORMAT,
 433                p2i(this),
 434                name() == NULL ? UNNAMED_MODULE : name()->as_C_string(),
 435                p2i(module()),
 436                loader_data()->loader_name(),
 437                version() != NULL ? version()->as_C_string() : "NULL",
 438                location() != NULL ? location()->as_C_string() : "NULL",
 439                BOOL_TO_STR(!can_read_all_unnamed()), p2i(next()));
 440 }
 441 
 442 void ModuleEntryTable::verify() {
 443   int element_count = 0;
 444   for (int i = 0; i < table_size(); i++) {
 445     for (ModuleEntry* probe = bucket(i);
 446                               probe != NULL;
 447                               probe = probe->next()) {
 448       probe->verify();
 449       element_count++;
 450     }
 451   }
 452   guarantee(number_of_entries() == element_count,
 453             "Verify of Module Entry Table failed");
 454   DEBUG_ONLY(verify_lookup_length((double)number_of_entries() / table_size(), "Module Entry Table"));
 455 }
 456 
 457 void ModuleEntry::verify() {
 458   guarantee(loader_data() != NULL, "A module entry must be associated with a loader.");
 459 }
--- EOF ---