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