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