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