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