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