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/classFileParser.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/javaAssertions.hpp"
  30 #include "classfile/javaClasses.hpp"
  31 #include "classfile/javaClasses.inline.hpp"
  32 #include "classfile/moduleEntry.hpp"
  33 #include "classfile/modules.hpp"
  34 #include "classfile/packageEntry.hpp"
  35 #include "classfile/stringTable.hpp"
  36 #include "classfile/symbolTable.hpp"
  37 #include "classfile/vmSymbols.hpp"
  38 #include "logging/log.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "oops/instanceKlass.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "oops/objArrayOop.inline.hpp"
  43 #include "runtime/arguments.hpp"
  44 #include "runtime/handles.inline.hpp"
  45 #include "runtime/javaCalls.hpp"
  46 #include "runtime/reflection.hpp"
  47 #include "utilities/utf8.hpp"
  48 
  49 static bool verify_module_name(char *module_name) {
  50   if (module_name == NULL) return false;
  51   int len = (int)strlen(module_name);
  52   return (len > 0 && len <= Symbol::max_length() &&
  53     UTF8::is_legal_utf8((unsigned char *)module_name, len, false) &&
  54     ClassFileParser::verify_unqualified_name(module_name, len,
  55     ClassFileParser::LegalModule));
  56 }
  57 
  58 bool Modules::verify_package_name(char *package_name) {
  59   if (package_name == NULL) return false;
  60   int len = (int)strlen(package_name);
  61   return (len > 0 && len <= Symbol::max_length() &&
  62     UTF8::is_legal_utf8((unsigned char *)package_name, len, false) &&
  63     ClassFileParser::verify_unqualified_name(package_name, len,
  64     ClassFileParser::LegalClass));
  65 }
  66 
  67 static char* get_module_name(oop module, TRAPS) {
  68   oop name_oop = java_lang_reflect_Module::name(module);
  69   if (name_oop == NULL) {
  70     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), "Null module name");
  71   }
  72   char* module_name = java_lang_String::as_utf8_string(name_oop);
  73   if (!verify_module_name(module_name)) {
  74     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
  75                    err_msg("Invalid module name: %s",
  76                            module_name != NULL ? module_name : "NULL"));
  77   }
  78   return module_name;
  79 }
  80 
  81 static const char* get_module_version(jstring version) {
  82   if (version == NULL) {
  83     return NULL;
  84   }
  85   return java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(version));
  86 }
  87 
  88 static ModuleEntryTable* get_module_entry_table(Handle h_loader, TRAPS) {
  89   // This code can be called during start-up, before the classLoader's classLoader data got
  90   // created.  So, call register_loader() to make sure the classLoader data gets created.
  91   ClassLoaderData *loader_cld = SystemDictionary::register_loader(h_loader, CHECK_NULL);
  92   return loader_cld->modules();
  93 }
  94 
  95 static PackageEntryTable* get_package_entry_table(Handle h_loader, TRAPS) {
  96   // This code can be called during start-up, before the classLoader's classLoader data got
  97   // created.  So, call register_loader() to make sure the classLoader data gets created.
  98   ClassLoaderData *loader_cld = SystemDictionary::register_loader(h_loader, CHECK_NULL);
  99   return loader_cld->packages();
 100 }
 101 
 102 static ModuleEntry* get_module_entry(jobject module, TRAPS) {
 103   Handle module_h(THREAD, JNIHandles::resolve(module));
 104   if (!java_lang_reflect_Module::is_instance(module_h())) {
 105     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
 106                    "module is not an instance of type java.lang.reflect.Module");
 107   }
 108   return java_lang_reflect_Module::module_entry(module_h(), CHECK_NULL);
 109 }
 110 
 111 static PackageEntry* get_package_entry(ModuleEntry* module_entry, jstring package, TRAPS) {
 112   ResourceMark rm(THREAD);
 113   if (package == NULL) return NULL;
 114   const char *package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
 115   if (package_name == NULL) return NULL;
 116   TempNewSymbol pkg_symbol = SymbolTable::new_symbol(package_name, CHECK_NULL);
 117   PackageEntryTable* package_entry_table = module_entry->loader_data()->packages();
 118   assert(package_entry_table != NULL, "Unexpected null package entry table");
 119   return package_entry_table->lookup_only(pkg_symbol);
 120 }
 121 
 122 static PackageEntry* get_package_entry_by_name(Symbol* package,
 123                                                Handle h_loader,
 124                                                TRAPS) {
 125   if (package != NULL) {
 126     ResourceMark rm(THREAD);
 127     if (Modules::verify_package_name(package->as_C_string())) {
 128       PackageEntryTable* const package_entry_table =
 129         get_package_entry_table(h_loader, CHECK_NULL);
 130       assert(package_entry_table != NULL, "Unexpected null package entry table");
 131       return package_entry_table->lookup_only(package);
 132     }
 133   }
 134   return NULL;
 135 }
 136 
 137 bool Modules::is_package_defined(Symbol* package, Handle h_loader, TRAPS) {
 138   PackageEntry* res = get_package_entry_by_name(package, h_loader, CHECK_false);
 139   return res != NULL;
 140 }
 141 
 142 static void define_javabase_module(jobject module, jstring version,
 143                                    jstring location, jobjectArray packages, TRAPS) {
 144   ResourceMark rm(THREAD);
 145 
 146   Handle module_handle(THREAD, JNIHandles::resolve(module));
 147 
 148   // Obtain java.base's module version
 149   const char* module_version = get_module_version(version);
 150   TempNewSymbol version_symbol;
 151   if (module_version != NULL) {
 152     version_symbol = SymbolTable::new_symbol(module_version, CHECK);
 153   } else {
 154     version_symbol = NULL;
 155   }
 156 
 157   // Obtain java.base's location
 158   const char* module_location = NULL;
 159   TempNewSymbol location_symbol = NULL;
 160   if (location != NULL) {
 161     module_location =
 162       java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(location));
 163     if (module_location != NULL) {
 164       location_symbol = SymbolTable::new_symbol(module_location, CHECK);
 165     }
 166   }
 167 
 168   objArrayOop packages_oop = objArrayOop(JNIHandles::resolve(packages));
 169   objArrayHandle packages_h(THREAD, packages_oop);
 170   int num_packages = (packages_h == NULL ? 0 : packages_h->length());
 171 
 172   // Check that the list of packages has no duplicates and that the
 173   // packages are syntactically ok.
 174   GrowableArray<Symbol*>* pkg_list = new GrowableArray<Symbol*>(num_packages);
 175   for (int x = 0; x < num_packages; x++) {
 176     oop string_obj = packages_h->obj_at(x);
 177 
 178     if (string_obj == NULL || !string_obj->is_a(SystemDictionary::String_klass())) {
 179       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 180                 "Bad package name for module: java.base");
 181     }
 182     char *package_name = java_lang_String::as_utf8_string(string_obj);
 183     if (!Modules::verify_package_name(package_name)) {
 184       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 185                 err_msg("Invalid package name: %s for module: java.base", package_name));
 186     }
 187     Symbol* pkg_symbol = SymbolTable::new_symbol(package_name, CHECK);
 188     // append_if_missing() returns FALSE if entry already exists.
 189     if (!pkg_list->append_if_missing(pkg_symbol)) {
 190       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 191                 err_msg("Duplicate package name: %s for module java.base",
 192                         package_name));
 193     }
 194   }
 195 
 196   // Validate java_base's loader is the boot loader.
 197   oop loader = java_lang_reflect_Module::loader(module_handle());
 198   if (loader != NULL) {
 199     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 200               "Class loader must be the boot class loader");
 201   }
 202   Handle h_loader = Handle(THREAD, loader);
 203 
 204   // Ensure the boot loader's PackageEntryTable has been created
 205   PackageEntryTable* package_table = get_package_entry_table(h_loader, CHECK);
 206   assert(pkg_list->length() == 0 || package_table != NULL, "Bad package_table");
 207 
 208   // Ensure java.base's ModuleEntry has been created
 209   assert(ModuleEntryTable::javabase_module() != NULL, "No ModuleEntry for java.base");
 210 
 211   bool duplicate_javabase = false;
 212   {
 213     MutexLocker m1(Module_lock, THREAD);
 214 
 215     if (ModuleEntryTable::javabase_defined()) {
 216       duplicate_javabase = true;
 217     } else {
 218 
 219       // Verify that all java.base packages created during bootstrapping are in
 220       // pkg_list.  If any are not in pkg_list, than a non-java.base class was
 221       // loaded erroneously pre java.base module definition.
 222       package_table->verify_javabase_packages(pkg_list);
 223 
 224       // loop through and add any new packages for java.base
 225       PackageEntry* pkg;
 226       for (int x = 0; x < pkg_list->length(); x++) {
 227         // Some of java.base's packages were added early in bootstrapping, ignore duplicates.
 228         if (package_table->lookup_only(pkg_list->at(x)) == NULL) {
 229           pkg = package_table->locked_create_entry_or_null(pkg_list->at(x), ModuleEntryTable::javabase_module());
 230           assert(pkg != NULL, "Unable to create a java.base package entry");
 231         }
 232         // Unable to have a GrowableArray of TempNewSymbol.  Must decrement the refcount of
 233         // the Symbol* that was created above for each package. The refcount was incremented
 234         // by SymbolTable::new_symbol and as well by the PackageEntry creation.
 235         pkg_list->at(x)->decrement_refcount();
 236       }
 237 
 238       // Finish defining java.base's ModuleEntry
 239       ModuleEntryTable::finalize_javabase(module_handle, version_symbol, location_symbol);
 240     }
 241   }
 242   if (duplicate_javabase) {
 243     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 244               "Module java.base is already defined");
 245   }
 246 
 247   log_debug(modules)("define_javabase_module(): Definition of module: java.base,"
 248                      " version: %s, location: %s, package #: %d",
 249                      module_version != NULL ? module_version : "NULL",
 250                      module_location != NULL ? module_location : "NULL",
 251                      pkg_list->length());
 252 
 253   // packages defined to java.base
 254   for (int x = 0; x < pkg_list->length(); x++) {
 255     log_trace(modules)("define_javabase_module(): creation of package %s for module java.base",
 256                        (pkg_list->at(x))->as_C_string());
 257   }
 258 
 259   // Patch any previously loaded classes' module field with java.base's jlr.Module.
 260   ModuleEntryTable::patch_javabase_entries(module_handle);
 261 }
 262 
 263 void Modules::define_module(jobject module, jstring version,
 264                             jstring location, jobjectArray packages, TRAPS) {
 265   ResourceMark rm(THREAD);
 266 
 267   if (module == NULL) {
 268     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "Null module object");
 269   }
 270   Handle module_handle(THREAD, JNIHandles::resolve(module));
 271   if (!java_lang_reflect_Module::is_instance(module_handle())) {
 272     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 273               "module is not an instance of type java.lang.reflect.Module");
 274   }
 275 
 276   char* module_name = get_module_name(module_handle(), CHECK);
 277   if (module_name == NULL) {
 278     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 279               "Module name cannot be null");
 280   }
 281 
 282   // Special handling of java.base definition
 283   if (strcmp(module_name, "java.base") == 0) {
 284     define_javabase_module(module, version, location, packages, CHECK);
 285     return;
 286   }
 287 
 288   const char* module_version = get_module_version(version);
 289 
 290   objArrayOop packages_oop = objArrayOop(JNIHandles::resolve(packages));
 291   objArrayHandle packages_h(THREAD, packages_oop);
 292   int num_packages = (packages_h == NULL ? 0 : packages_h->length());
 293 
 294   // Check that the list of packages has no duplicates and that the
 295   // packages are syntactically ok.
 296   GrowableArray<Symbol*>* pkg_list = new GrowableArray<Symbol*>(num_packages);
 297   for (int x = 0; x < num_packages; x++) {
 298     oop string_obj = packages_h->obj_at(x);
 299 
 300     if (string_obj == NULL || !string_obj->is_a(SystemDictionary::String_klass())) {
 301       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 302                 err_msg("Bad package name for module: %s", module_name));
 303     }
 304     char *package_name = java_lang_String::as_utf8_string(string_obj);
 305     if (!verify_package_name(package_name)) {
 306       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 307                 err_msg("Invalid package name: %s for module: %s",
 308                         package_name, module_name));
 309     }
 310     Symbol* pkg_symbol = SymbolTable::new_symbol(package_name, CHECK);
 311     // append_if_missing() returns FALSE if entry already exists.
 312     if (!pkg_list->append_if_missing(pkg_symbol)) {
 313       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 314                 err_msg("Duplicate package name: %s for module %s",
 315                         package_name, module_name));
 316     }
 317   }
 318 
 319   oop loader = java_lang_reflect_Module::loader(module_handle());
 320   // Make sure loader is not the sun.reflect.DelegatingClassLoader.
 321   if (loader != java_lang_ClassLoader::non_reflection_class_loader(loader)) {
 322     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 323               "Class loader is an invalid delegating class loader");
 324   }
 325   Handle h_loader = Handle(THREAD, loader);
 326 
 327   // Check that loader is a subclass of java.lang.ClassLoader.
 328   if (loader != NULL && !java_lang_ClassLoader::is_subclass(h_loader->klass())) {
 329     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 330               "Class loader is not a subclass of java.lang.ClassLoader");
 331   }
 332 
 333   ModuleEntryTable* module_table = get_module_entry_table(h_loader, CHECK);
 334   assert(module_table != NULL, "module entry table shouldn't be null");
 335 
 336   // Create symbol* entry for module name.
 337   TempNewSymbol module_symbol = SymbolTable::new_symbol(module_name, CHECK);
 338 
 339   int dupl_pkg_index = -1;
 340   bool dupl_modules = false;
 341 
 342   // Create symbol* entry for module version.
 343   TempNewSymbol version_symbol;
 344   if (module_version != NULL) {
 345     version_symbol = SymbolTable::new_symbol(module_version, CHECK);
 346   } else {
 347     version_symbol = NULL;
 348   }
 349 
 350   // Create symbol* entry for module location.
 351   const char* module_location = NULL;
 352   TempNewSymbol location_symbol = NULL;
 353   if (location != NULL) {
 354     module_location =
 355       java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(location));
 356     if (module_location != NULL) {
 357       location_symbol = SymbolTable::new_symbol(module_location, CHECK);
 358     }
 359   }
 360 
 361   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(h_loader());
 362   assert(loader_data != NULL, "class loader data shouldn't be null");
 363 
 364   PackageEntryTable* package_table = NULL;
 365   {
 366     MutexLocker ml(Module_lock, THREAD);
 367 
 368     if (num_packages > 0) {
 369       package_table = get_package_entry_table(h_loader, CHECK);
 370       assert(package_table != NULL, "Missing package_table");
 371 
 372       // Check that none of the packages exist in the class loader's package table.
 373       for (int x = 0; x < pkg_list->length(); x++) {
 374         if (package_table->lookup_only(pkg_list->at(x)) != NULL) {
 375           // This could be because the module was already defined.  If so,
 376           // report that error instead of the package error.
 377           if (module_table->lookup_only(module_symbol) != NULL) {
 378             dupl_modules = true;
 379           } else {
 380             dupl_pkg_index = x;
 381           }
 382           break;
 383         }
 384       }
 385     }  // if (num_packages > 0)...
 386 
 387     // Add the module and its packages.
 388     if (!dupl_modules && dupl_pkg_index == -1) {
 389       // Create the entry for this module in the class loader's module entry table.
 390 
 391       ModuleEntry* module_entry = module_table->locked_create_entry_or_null(module_handle, module_symbol,
 392                                     version_symbol, location_symbol, loader_data);
 393 
 394       if (module_entry == NULL) {
 395         dupl_modules = true;
 396       } else {
 397         // Add the packages.
 398         assert(pkg_list->length() == 0 || package_table != NULL, "Bad package table");
 399         PackageEntry* pkg;
 400         for (int y = 0; y < pkg_list->length(); y++) {
 401           pkg = package_table->locked_create_entry_or_null(pkg_list->at(y), module_entry);
 402           assert(pkg != NULL, "Unable to create a module's package entry");
 403 
 404           // Unable to have a GrowableArray of TempNewSymbol.  Must decrement the refcount of
 405           // the Symbol* that was created above for each package. The refcount was incremented
 406           // by SymbolTable::new_symbol and as well by the PackageEntry creation.
 407           pkg_list->at(y)->decrement_refcount();
 408         }
 409 
 410         // Store pointer to ModuleEntry record in java.lang.reflect.Module object.
 411         java_lang_reflect_Module::set_module_entry(module_handle(), module_entry);
 412       }
 413     }
 414   }  // Release the lock
 415 
 416   // any errors ?
 417   if (dupl_modules) {
 418      THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 419                err_msg("Module %s is already defined", module_name));
 420   }
 421   if (dupl_pkg_index != -1) {
 422     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 423               err_msg("Package %s for module %s already exists for class loader",
 424                       pkg_list->at(dupl_pkg_index)->as_C_string(), module_name));
 425   }
 426 
 427   if (log_is_enabled(Debug, modules)) {
 428     outputStream* logst = Log(modules)::debug_stream();
 429     logst->print("define_module(): creation of module: %s, version: %s, location: %s, ",
 430                  module_name, module_version != NULL ? module_version : "NULL",
 431                  module_location != NULL ? module_location : "NULL");
 432     loader_data->print_value_on(logst);
 433     logst->print_cr(", package #: %d", pkg_list->length());
 434     for (int y = 0; y < pkg_list->length(); y++) {
 435       log_trace(modules)("define_module(): creation of package %s for module %s",
 436                          (pkg_list->at(y))->as_C_string(), module_name);
 437     }
 438   }
 439 
 440   // If the module is defined to the boot loader and an exploded build is being
 441   // used, prepend <java.home>/modules/modules_name, if it exists, to the system boot class path.
 442   if (loader == NULL &&
 443       !Universe::is_module_initialized() &&
 444       !ClassLoader::has_jrt_entry()) {
 445     ClassLoader::add_to_exploded_build_list(module_symbol, CHECK);
 446   }
 447 }
 448 
 449 void Modules::set_bootloader_unnamed_module(jobject module, TRAPS) {
 450   ResourceMark rm(THREAD);
 451 
 452   if (module == NULL) {
 453     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "Null module object");
 454   }
 455   Handle module_handle(THREAD, JNIHandles::resolve(module));
 456   if (!java_lang_reflect_Module::is_instance(module_handle())) {
 457     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 458               "module is not an instance of type java.lang.reflect.Module");
 459   }
 460 
 461   // Ensure that this is an unnamed module
 462   oop name = java_lang_reflect_Module::name(module_handle());
 463   if (name != NULL) {
 464     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 465               "boot loader's unnamed module's java.lang.reflect.Module has a name");
 466   }
 467 
 468   // Validate java_base's loader is the boot loader.
 469   oop loader = java_lang_reflect_Module::loader(module_handle());
 470   if (loader != NULL) {
 471     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 472               "Class loader must be the boot class loader");
 473   }
 474   Handle h_loader = Handle(THREAD, loader);
 475 
 476   log_debug(modules)("set_bootloader_unnamed_module(): recording unnamed module for boot loader");
 477 
 478   // Ensure the boot loader's PackageEntryTable has been created
 479   ModuleEntryTable* module_table = get_module_entry_table(h_loader, CHECK);
 480 
 481   // Set java.lang.reflect.Module for the boot loader's unnamed module
 482   ModuleEntry* unnamed_module = module_table->unnamed_module();
 483   assert(unnamed_module != NULL, "boot loader's unnamed ModuleEntry not defined");
 484   unnamed_module->set_module(ClassLoaderData::the_null_class_loader_data()->add_handle(module_handle));
 485   // Store pointer to the ModuleEntry in the unnamed module's java.lang.reflect.Module object.
 486   java_lang_reflect_Module::set_module_entry(module_handle(), unnamed_module);
 487 }
 488 
 489 void Modules::add_module_exports(jobject from_module, jstring package, jobject to_module, TRAPS) {
 490   if (package == NULL) {
 491     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 492               "package is null");
 493   }
 494   if (from_module == NULL) {
 495     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 496               "from_module is null");
 497   }
 498   ModuleEntry* from_module_entry = get_module_entry(from_module, CHECK);
 499   if (from_module_entry == NULL) {
 500     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 501               "from_module cannot be found");
 502   }
 503 
 504   // All packages in unnamed are exported by default.
 505   if (!from_module_entry->is_named()) return;
 506 
 507   ModuleEntry* to_module_entry;
 508   if (to_module == NULL) {
 509     to_module_entry = NULL;  // It's an unqualified export.
 510   } else {
 511     to_module_entry = get_module_entry(to_module, CHECK);
 512     if (to_module_entry == NULL) {
 513       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 514                 "to_module is invalid");
 515     }
 516   }
 517 
 518   PackageEntry *package_entry = get_package_entry(from_module_entry, package, CHECK);
 519   ResourceMark rm(THREAD);
 520   if (package_entry == NULL) {
 521     const char *package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
 522     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 523               err_msg("Package %s not found in from_module %s",
 524                       package_name != NULL ? package_name : "",
 525                       from_module_entry->name()->as_C_string()));
 526   }
 527   if (package_entry->module() != from_module_entry) {
 528     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 529               err_msg("Package: %s found in module %s, not in from_module: %s",
 530                       package_entry->name()->as_C_string(),
 531                       package_entry->module()->name()->as_C_string(),
 532                       from_module_entry->name()->as_C_string()));
 533   }
 534 
 535   log_debug(modules)("add_module_exports(): package %s in module %s is exported to module %s",
 536                      package_entry->name()->as_C_string(),
 537                      from_module_entry->name()->as_C_string(),
 538                      to_module_entry == NULL ? "NULL" :
 539                       to_module_entry->is_named() ?
 540                         to_module_entry->name()->as_C_string() : UNNAMED_MODULE);
 541 
 542   // Do nothing if modules are the same.
 543   if (from_module_entry != to_module_entry) {
 544     package_entry->set_exported(to_module_entry);
 545   }
 546 }
 547 
 548 
 549 void Modules::add_module_exports_qualified(jobject from_module, jstring package,
 550                                            jobject to_module, TRAPS) {
 551   if (to_module == NULL) {
 552     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 553               "to_module is null");
 554   }
 555   add_module_exports(from_module, package, to_module, CHECK);
 556 }
 557 
 558 void Modules::add_reads_module(jobject from_module, jobject to_module, TRAPS) {
 559   if (from_module == NULL) {
 560     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 561               "from_module is null");
 562   }
 563 
 564   ModuleEntry* from_module_entry = get_module_entry(from_module, CHECK);
 565   if (from_module_entry == NULL) {
 566     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 567               "from_module is not valid");
 568   }
 569 
 570   ModuleEntry* to_module_entry;
 571   if (to_module != NULL) {
 572     to_module_entry = get_module_entry(to_module, CHECK);
 573     if (to_module_entry == NULL) {
 574       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 575                 "to_module is invalid");
 576     }
 577   } else {
 578     to_module_entry = NULL;
 579   }
 580 
 581   ResourceMark rm(THREAD);
 582   log_debug(modules)("add_reads_module(): Adding read from module %s to module %s",
 583                      from_module_entry->is_named() ?
 584                      from_module_entry->name()->as_C_string() : UNNAMED_MODULE,
 585                      to_module_entry == NULL ? "all unnamed" :
 586                        (to_module_entry->is_named() ?
 587                         to_module_entry->name()->as_C_string() : UNNAMED_MODULE));
 588 
 589   // if modules are the same or if from_module is unnamed then no need to add the read.
 590   if (from_module_entry != to_module_entry && from_module_entry->is_named()) {
 591     from_module_entry->add_read(to_module_entry);
 592   }
 593 }
 594 
 595 jboolean Modules::can_read_module(jobject asking_module, jobject target_module, TRAPS) {
 596   if (asking_module == NULL) {
 597     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
 598                "asking_module is null", JNI_FALSE);
 599   }
 600 
 601   ModuleEntry* asking_module_entry = get_module_entry(asking_module, CHECK_false);
 602   if (asking_module_entry == NULL) {
 603     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 604                "asking_module is invalid", JNI_FALSE);
 605   }
 606 
 607   // Calling can_read_all_unnamed() with NULL tests if a module is loose.
 608   if (target_module == NULL) {
 609     return asking_module_entry->can_read_all_unnamed();
 610   }
 611 
 612   ModuleEntry* target_module_entry = get_module_entry(target_module, CHECK_false);
 613   if (target_module_entry == NULL) {
 614     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 615                "target_module is invalid", JNI_FALSE);
 616   }
 617 
 618   ResourceMark rm(THREAD);
 619   log_debug(modules)("can_read_module(): module %s trying to read module %s, allowed = %s",
 620                      asking_module_entry->is_named() ?
 621                        asking_module_entry->name()->as_C_string() : UNNAMED_MODULE,
 622                      target_module_entry->is_named() ?
 623                        target_module_entry->name()->as_C_string() : UNNAMED_MODULE,
 624                      BOOL_TO_STR(asking_module_entry == target_module_entry ||
 625                                  (asking_module_entry->can_read_all_unnamed() &&
 626                                   !target_module_entry->is_named()) ||
 627                                   asking_module_entry->can_read(target_module_entry)));
 628 
 629   // Return true if:
 630   // 1. the modules are the same, or
 631   // 2. the asking_module is unnamed (because unnamed modules read everybody), or
 632   // 3. the asking_module is loose and the target module is unnamed, or
 633   // 4. if can_read() returns true.
 634   if (asking_module_entry == target_module_entry ||
 635       (asking_module_entry->can_read_all_unnamed() && !target_module_entry->is_named())) {
 636     return true;
 637   }
 638   return asking_module_entry->can_read(target_module_entry);
 639 }
 640 
 641 jboolean Modules::is_exported_to_module(jobject from_module, jstring package,
 642                                         jobject to_module, TRAPS) {
 643   if (package == NULL) {
 644     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
 645                "package is null", JNI_FALSE);
 646   }
 647   if (from_module == NULL) {
 648     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
 649                "from_module is null", JNI_FALSE);
 650   }
 651   ModuleEntry* from_module_entry = get_module_entry(from_module, CHECK_false);
 652   if (from_module_entry == NULL) {
 653     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 654                "from_module is invalid", JNI_FALSE);
 655   }
 656   ModuleEntry* to_module_entry;
 657   if (to_module == NULL) {
 658     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
 659                "to_module is null", JNI_FALSE);
 660   }
 661   to_module_entry = get_module_entry(to_module, CHECK_false);
 662   if (to_module_entry == NULL) {
 663     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 664                "to_module is invalid", JNI_FALSE);
 665   }
 666 
 667   PackageEntry *package_entry = get_package_entry(from_module_entry, package,
 668                                                   CHECK_false);
 669   ResourceMark rm(THREAD);
 670   if (package_entry == NULL) {
 671     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 672                err_msg("Package not found in from_module: %s",
 673                        from_module_entry->is_named() ?
 674                          from_module_entry->name()->as_C_string() : UNNAMED_MODULE),
 675                JNI_FALSE);
 676   }
 677   if (package_entry->module() != from_module_entry) {
 678     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 679                err_msg("Package: %s found in module %s, not in from_module: %s",
 680                        package_entry->name()->as_C_string(),
 681                        package_entry->module()->is_named() ?
 682                          package_entry->module()->name()->as_C_string() : UNNAMED_MODULE,
 683                        from_module_entry->is_named() ?
 684                          from_module_entry->name()->as_C_string() : UNNAMED_MODULE),
 685                JNI_FALSE);
 686   }
 687 
 688   log_debug(modules)("is_exported_to_module: package %s from module %s checking"
 689                      " if exported to module %s, exported? = %s",
 690                      package_entry->name()->as_C_string(),
 691                      from_module_entry->is_named() ?
 692                        from_module_entry->name()->as_C_string() : UNNAMED_MODULE,
 693                      to_module_entry->is_named() ?
 694                        to_module_entry->name()->as_C_string() : UNNAMED_MODULE,
 695                      BOOL_TO_STR(!from_module_entry->is_named() ||
 696                        package_entry->is_unqual_exported() ||
 697                        from_module_entry == to_module_entry ||
 698                        package_entry->is_qexported_to(to_module_entry)));
 699 
 700   // Return true if:
 701   // 1. from_module is unnamed because unnamed modules export all their packages (by default), or
 702   // 2. if the package is unqualifiedly exported, or
 703   // 3. if the modules are the same, or
 704   // 4. if the package is exported to to_module
 705   return (!from_module_entry->is_named() ||
 706           package_entry->is_unqual_exported() ||
 707           from_module_entry == to_module_entry ||
 708           package_entry->is_qexported_to(to_module_entry));
 709 }
 710 
 711 // This method is called by JFR and JNI.
 712 jobject Modules::get_module(jclass clazz, TRAPS) {
 713   assert(ModuleEntryTable::javabase_defined(), "Attempt to call get_module before java.base is defined");
 714 
 715   if (clazz == NULL) {
 716     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
 717                "class is null", JNI_FALSE);
 718   }
 719   oop mirror = JNIHandles::resolve_non_null(clazz);
 720   if (mirror == NULL) {
 721     log_debug(modules)("get_module(): no mirror, returning NULL");
 722     return NULL;
 723   }
 724   if (!java_lang_Class::is_instance(mirror)) {
 725     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 726                "Invalid class", JNI_FALSE);
 727   }
 728 
 729   oop module = java_lang_Class::module(mirror);
 730 
 731   assert(module != NULL, "java.lang.Class module field not set");
 732   assert(java_lang_reflect_Module::is_instance(module), "module is not an instance of type java.lang.reflect.Module");
 733 
 734   if (log_is_enabled(Debug, modules)) {
 735     ResourceMark rm(THREAD);
 736     outputStream* logst = Log(modules)::debug_stream();
 737     Klass* klass = java_lang_Class::as_Klass(mirror);
 738     oop module_name = java_lang_reflect_Module::name(module);
 739     if (module_name != NULL) {
 740       logst->print("get_module(): module ");
 741       java_lang_String::print(module_name, tty);
 742     } else {
 743       logst->print("get_module(): Unamed Module");
 744     }
 745     if (klass != NULL) {
 746       logst->print_cr(" for class %s", klass->external_name());
 747     } else {
 748       logst->print_cr(" for primitive class");
 749     }
 750   }
 751 
 752   return JNIHandles::make_local(THREAD, module);
 753 }
 754 
 755 
 756 jobject Modules::get_module_by_package_name(jobject loader, jstring package, TRAPS) {
 757   ResourceMark rm(THREAD);
 758   assert(ModuleEntryTable::javabase_defined(),
 759          "Attempt to call get_module_from_pkg before java.base is defined");
 760 
 761   if (NULL == package) {
 762     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
 763                "package is null", JNI_FALSE);
 764   }
 765   const char* package_str =
 766     java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
 767   if (NULL == package_str) {
 768     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 769                "Invalid package", JNI_FALSE);
 770   }
 771 
 772   Handle h_loader (THREAD, JNIHandles::resolve(loader));
 773   // Check that loader is a subclass of java.lang.ClassLoader.
 774   if (loader != NULL && !java_lang_ClassLoader::is_subclass(h_loader->klass())) {
 775     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 776                "Class loader is not a subclass of java.lang.ClassLoader", JNI_FALSE);
 777   }
 778 
 779   if (strlen(package_str) == 0) {
 780     // Return the unnamed module
 781     ModuleEntryTable* module_table = get_module_entry_table(h_loader, CHECK_NULL);
 782     if (NULL == module_table) return NULL;
 783     const ModuleEntry* const unnamed_module = module_table->unnamed_module();
 784     return JNIHandles::make_local(THREAD, JNIHandles::resolve(unnamed_module->module()));
 785 
 786   } else {
 787     TempNewSymbol package_sym = SymbolTable::new_symbol(package_str, CHECK_NULL);
 788     return get_module(package_sym, h_loader, CHECK_NULL);
 789   }
 790   return NULL;
 791 }
 792 
 793 
 794 jobject Modules::get_named_module(Handle h_loader, const char* package_str, TRAPS) {
 795   assert(ModuleEntryTable::javabase_defined(),
 796          "Attempt to call get_named_module before java.base is defined");
 797   assert(h_loader.is_null() || java_lang_ClassLoader::is_subclass(h_loader->klass()),
 798          "Class loader is not a subclass of java.lang.ClassLoader");
 799   assert(package_str != NULL, "the package_str should not be NULL");
 800 
 801   if (strlen(package_str) == 0) {
 802     return NULL;
 803   }
 804   TempNewSymbol package_sym = SymbolTable::new_symbol(package_str, CHECK_NULL);
 805   const PackageEntry* const pkg_entry =
 806     get_package_entry_by_name(package_sym, h_loader, THREAD);
 807   const ModuleEntry* const module_entry = (pkg_entry != NULL ? pkg_entry->module() : NULL);
 808 
 809   if (module_entry != NULL && module_entry->module() != NULL && module_entry->is_named()) {
 810     return JNIHandles::make_local(THREAD, JNIHandles::resolve(module_entry->module()));
 811   }
 812   return NULL;
 813 }
 814 
 815 
 816 // This method is called by JFR and by the above method.
 817 jobject Modules::get_module(Symbol* package_name, Handle h_loader, TRAPS) {
 818   const PackageEntry* const pkg_entry =
 819     get_package_entry_by_name(package_name, h_loader, THREAD);
 820   const ModuleEntry* const module_entry = (pkg_entry != NULL ? pkg_entry->module() : NULL);
 821 
 822   if (module_entry != NULL &&
 823       module_entry->module() != NULL) {
 824     return JNIHandles::make_local(THREAD, JNIHandles::resolve(module_entry->module()));
 825   }
 826 
 827   return NULL;
 828 }
 829 
 830 void Modules::add_module_package(jobject module, jstring package, TRAPS) {
 831   ResourceMark rm(THREAD);
 832 
 833   if (module == NULL) {
 834     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 835               "module is null");
 836   }
 837   if (package == NULL) {
 838     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 839               "package is null");
 840   }
 841   ModuleEntry* module_entry = get_module_entry(module, CHECK);
 842   if (module_entry == NULL) {
 843     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 844               "module is invalid");
 845   }
 846   if (!module_entry->is_named()) {
 847     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 848               "module cannot be an unnamed module");
 849   }
 850   char *package_name = java_lang_String::as_utf8_string(
 851     JNIHandles::resolve_non_null(package));
 852   if (package_name == NULL) {
 853     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Bad package");
 854   }
 855   if (!verify_package_name(package_name)) {
 856     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 857               err_msg("Invalid package name: %s", package_name));
 858   }
 859 
 860   log_debug(modules)("add_module_package(): Adding package %s to module %s",
 861                      package_name, module_entry->name()->as_C_string());
 862 
 863   TempNewSymbol pkg_symbol = SymbolTable::new_symbol(package_name, CHECK);
 864   PackageEntryTable* package_table = module_entry->loader_data()->packages();
 865   assert(package_table != NULL, "Missing package_table");
 866 
 867   bool pkg_exists = false;
 868   {
 869     MutexLocker ml(Module_lock, THREAD);
 870 
 871     // Check that the package does not exist in the class loader's package table.
 872     if (!package_table->lookup_only(pkg_symbol)) {
 873       PackageEntry* pkg = package_table->locked_create_entry_or_null(pkg_symbol, module_entry);
 874       assert(pkg != NULL, "Unable to create a module's package entry");
 875     } else {
 876       pkg_exists = true;
 877     }
 878   }
 879   if (pkg_exists) {
 880     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 881               err_msg("Package %s already exists for class loader", package_name));
 882   }
 883 }
 884 
 885 // Export package in module to all unnamed modules.
 886 void Modules::add_module_exports_to_all_unnamed(jobject module, jstring package, TRAPS) {
 887   if (module == NULL) {
 888     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 889               "module is null");
 890   }
 891   if (package == NULL) {
 892     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 893               "package is null");
 894   }
 895   ModuleEntry* module_entry = get_module_entry(module, CHECK);
 896   if (module_entry == NULL) {
 897     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 898               "module is invalid");
 899   }
 900 
 901   if (module_entry->is_named()) { // No-op for unnamed module.
 902     PackageEntry *package_entry = get_package_entry(module_entry, package, CHECK);
 903     ResourceMark rm(THREAD);
 904     if (package_entry == NULL) {
 905       const char *package_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(package));
 906       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 907                 err_msg("Package %s not found in module %s",
 908                         package_name != NULL ? package_name : "",
 909                         module_entry->name()->as_C_string()));
 910     }
 911     if (package_entry->module() != module_entry) {
 912       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 913                 err_msg("Package: %s found in module %s, not in module: %s",
 914                         package_entry->name()->as_C_string(),
 915                         package_entry->module()->name()->as_C_string(),
 916                         module_entry->name()->as_C_string()));
 917     }
 918 
 919     log_debug(modules)("add_module_exports_to_all_unnamed(): package %s in module"
 920                        " %s is exported to all unnamed modules",
 921                        package_entry->name()->as_C_string(),
 922                        module_entry->name()->as_C_string());
 923 
 924     // Mark package as exported to all unnamed modules, unless already
 925     // unqualifiedly exported.
 926     if (!package_entry->is_unqual_exported()) {
 927       package_entry->set_is_exported_allUnnamed();
 928     }
 929   }
 930 }