1 /*
   2 * Copyright (c) 2016, 2025, 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 "cds/archiveBuilder.hpp"
  26 #include "cds/cdsConfig.hpp"
  27 #include "cds/metaspaceShared.hpp"
  28 #include "classfile/classFileParser.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"
  31 #include "classfile/classLoaderDataShared.hpp"
  32 #include "classfile/classLoaderExt.hpp"
  33 #include "classfile/javaAssertions.hpp"
  34 #include "classfile/javaClasses.hpp"
  35 #include "classfile/javaClasses.inline.hpp"
  36 #include "classfile/moduleEntry.hpp"
  37 #include "classfile/modules.hpp"
  38 #include "classfile/packageEntry.hpp"
  39 #include "classfile/stringTable.hpp"
  40 #include "classfile/symbolTable.hpp"
  41 #include "classfile/systemDictionary.hpp"
  42 #include "classfile/vmClasses.hpp"
  43 #include "classfile/vmSymbols.hpp"
  44 #include "jvm.h"
  45 #include "logging/log.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "prims/jvmtiExport.hpp"
  49 #include "runtime/arguments.hpp"
  50 #include "runtime/globals_extension.hpp"
  51 #include "runtime/handles.inline.hpp"
  52 #include "runtime/javaCalls.hpp"
  53 #include "runtime/jniHandles.inline.hpp"
  54 #include "utilities/formatBuffer.hpp"
  55 #include "utilities/stringUtils.hpp"
  56 #include "utilities/utf8.hpp"
  57 
  58 static bool verify_module_name(const char *module_name, int len) {
  59   assert(module_name != nullptr, "invariant");
  60   return (len > 0 && len <= Symbol::max_length());
  61 }
  62 
  63 static bool verify_package_name(const char* package_name, int len) {
  64   assert(package_name != nullptr, "Package name derived from non-null jstring can't be null");
  65   return (len > 0 && len <= Symbol::max_length() &&
  66     ClassFileParser::verify_unqualified_name(package_name, len,
  67     ClassFileParser::LegalClass));
  68 }
  69 
  70 static char* get_module_name(oop module, int& len, TRAPS) {
  71   oop name_oop = java_lang_Module::name(module);
  72   if (name_oop == nullptr) {
  73     THROW_MSG_NULL(vmSymbols::java_lang_NullPointerException(), "Null module name");
  74   }
  75   size_t utf8_len;
  76   char* module_name = java_lang_String::as_utf8_string(name_oop, utf8_len);
  77   len = checked_cast<int>(utf8_len); // module names are < 64K
  78   if (!verify_module_name(module_name, len)) {
  79     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
  80                    err_msg("Invalid module name: %s", module_name));
  81   }
  82   return module_name;
  83 }
  84 
  85 static Symbol* as_symbol(jstring str_object) {
  86   if (str_object == nullptr) {
  87     return nullptr;
  88   }
  89   size_t len;
  90   char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(str_object), len);
  91   return SymbolTable::new_symbol(str, checked_cast<int>(len));
  92 }
  93 
  94 ModuleEntryTable* Modules::get_module_entry_table(Handle h_loader) {
  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);
  98   return loader_cld->modules();
  99 }
 100 
 101 static PackageEntryTable* get_package_entry_table(Handle h_loader) {
 102   // This code can be called during start-up, before the classLoader's classLoader data got
 103   // created.  So, call register_loader() to make sure the classLoader data gets created.
 104   ClassLoaderData *loader_cld = SystemDictionary::register_loader(h_loader);
 105   return loader_cld->packages();
 106 }
 107 
 108 static ModuleEntry* get_module_entry(Handle module, TRAPS) {
 109   if (!java_lang_Module::is_instance(module())) {
 110     THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
 111                    "module is not an instance of type java.lang.Module");
 112   }
 113   return java_lang_Module::module_entry(module());
 114 }
 115 
 116 
 117 static PackageEntry* get_locked_package_entry(ModuleEntry* module_entry, const char* package_name, int len) {
 118   assert(Module_lock->owned_by_self(), "should have the Module_lock");
 119   assert(package_name != nullptr, "Precondition");
 120   TempNewSymbol pkg_symbol = SymbolTable::new_symbol(package_name, len);
 121   PackageEntryTable* package_entry_table = module_entry->loader_data()->packages();
 122   assert(package_entry_table != nullptr, "Unexpected null package entry table");
 123   PackageEntry* package_entry = package_entry_table->locked_lookup_only(pkg_symbol);
 124   assert(package_entry == nullptr || package_entry->module() == module_entry, "Unexpectedly found a package linked to another module");
 125   return package_entry;
 126 }
 127 
 128 static PackageEntry* get_package_entry_by_name(Symbol* package, Handle h_loader) {
 129   if (package != nullptr) {
 130     PackageEntryTable* const package_entry_table =
 131       get_package_entry_table(h_loader);
 132     assert(package_entry_table != nullptr, "Unexpected null package entry table");
 133     return package_entry_table->lookup_only(package);
 134   }
 135   return nullptr;
 136 }
 137 
 138 bool Modules::is_package_defined(Symbol* package, Handle h_loader) {
 139   PackageEntry* res = get_package_entry_by_name(package, h_loader);
 140   return res != nullptr;
 141 }
 142 
 143 // Converts the String oop to an internal package
 144 // Will use the provided buffer if it's sufficiently large, otherwise allocates
 145 // a resource array
 146 // The length of the resulting string will be assigned to utf8_len
 147 static const char* as_internal_package(oop package_string, char* buf, size_t buflen, int& utf8_len) {
 148   size_t full_utf8_len;
 149   char* package_name = java_lang_String::as_utf8_string_full(package_string, buf, buflen, full_utf8_len);
 150   utf8_len = checked_cast<int>(full_utf8_len); // package names are < 64K
 151 
 152   // Turn all '/'s into '.'s
 153   for (int index = 0; index < utf8_len; index++) {
 154     if (package_name[index] == JVM_SIGNATURE_DOT) {
 155       package_name[index] = JVM_SIGNATURE_SLASH;
 156     }
 157   }
 158   return package_name;
 159 }
 160 
 161 static void define_javabase_module(Handle module_handle, jstring version, jstring location,
 162                                    objArrayHandle pkgs, int num_packages, TRAPS) {
 163   ResourceMark rm(THREAD);
 164 
 165   // Obtain java.base's module version
 166   TempNewSymbol version_symbol = as_symbol(version);
 167 
 168   // Obtain java.base's location
 169   TempNewSymbol location_symbol = as_symbol(location);
 170 
 171   // Check that the packages are syntactically ok.
 172   char buf[128];
 173   GrowableArray<Symbol*>* pkg_list = new GrowableArray<Symbol*>(num_packages);
 174   for (int x = 0; x < num_packages; x++) {
 175     oop pkg_str = pkgs->obj_at(x);
 176 
 177     if (pkg_str == nullptr || pkg_str->klass() != vmClasses::String_klass()) {
 178       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 179                 err_msg("Bad package name"));
 180     }
 181 
 182     int package_len;
 183     const char* package_name = as_internal_package(pkg_str, buf, sizeof(buf), package_len);
 184     if (!verify_package_name(package_name, package_len)) {
 185       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 186                 err_msg("Invalid package name: %s for module: " JAVA_BASE_NAME, package_name));
 187     }
 188     Symbol* pkg_symbol = SymbolTable::new_symbol(package_name, package_len);
 189     pkg_list->append(pkg_symbol);
 190   }
 191 
 192   // Validate java_base's loader is the boot loader.
 193   oop loader = java_lang_Module::loader(module_handle());
 194   if (loader != nullptr) {
 195     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 196               "Class loader must be the boot class loader");
 197   }
 198   Handle h_loader(THREAD, loader);
 199 
 200   // Ensure the boot loader's PackageEntryTable has been created
 201   PackageEntryTable* package_table = get_package_entry_table(h_loader);
 202   assert(pkg_list->length() == 0 || package_table != nullptr, "Bad package_table");
 203 
 204   // Ensure java.base's ModuleEntry has been created
 205   assert(ModuleEntryTable::javabase_moduleEntry() != nullptr, "No ModuleEntry for " JAVA_BASE_NAME);
 206 
 207   bool duplicate_javabase = false;
 208   {
 209     MutexLocker m1(THREAD, Module_lock);
 210 
 211     if (ModuleEntryTable::javabase_defined()) {
 212       duplicate_javabase = true;
 213     } else {
 214 
 215       // Verify that all java.base packages created during bootstrapping are in
 216       // pkg_list.  If any are not in pkg_list, than a non-java.base class was
 217       // loaded erroneously pre java.base module definition.
 218       package_table->verify_javabase_packages(pkg_list);
 219 
 220       // loop through and add any new packages for java.base
 221       for (int x = 0; x < pkg_list->length(); x++) {
 222         // Some of java.base's packages were added early in bootstrapping, ignore duplicates.
 223         package_table->locked_create_entry_if_absent(pkg_list->at(x),
 224                                                      ModuleEntryTable::javabase_moduleEntry());
 225         assert(package_table->locked_lookup_only(pkg_list->at(x)) != nullptr,
 226                "Unable to create a " JAVA_BASE_NAME " package entry");
 227         // Unable to have a GrowableArray of TempNewSymbol.  Must decrement the refcount of
 228         // the Symbol* that was created above for each package. The refcount was incremented
 229         // by SymbolTable::new_symbol and as well by the PackageEntry creation.
 230         pkg_list->at(x)->decrement_refcount();
 231       }
 232 
 233       // Finish defining java.base's ModuleEntry
 234       ModuleEntryTable::finalize_javabase(module_handle, version_symbol, location_symbol);
 235     }
 236   }
 237   if (duplicate_javabase) {
 238     THROW_MSG(vmSymbols::java_lang_InternalError(),
 239               "Module " JAVA_BASE_NAME " is already defined");
 240   }
 241 
 242   // Only the thread that actually defined the base module will get here,
 243   // so no locking is needed.
 244 
 245   // Patch any previously loaded class's module field with java.base's java.lang.Module.
 246   ModuleEntryTable::patch_javabase_entries(THREAD, module_handle);
 247 
 248   log_info(module, load)(JAVA_BASE_NAME " location: %s",
 249                          location_symbol != nullptr ? location_symbol->as_C_string() : "nullptr");
 250   log_debug(module)("define_javabase_module(): Definition of module: "
 251                     JAVA_BASE_NAME ", version: %s, location: %s, package #: %d",
 252                     version_symbol != nullptr ? version_symbol->as_C_string() : "nullptr",
 253                     location_symbol != nullptr ? location_symbol->as_C_string() : "nullptr",
 254                     pkg_list->length());
 255 
 256   // packages defined to java.base
 257   if (log_is_enabled(Trace, module)) {
 258     for (int x = 0; x < pkg_list->length(); x++) {
 259       log_trace(module)("define_javabase_module(): creation of package %s for module " JAVA_BASE_NAME,
 260                         (pkg_list->at(x))->as_C_string());
 261     }
 262   }
 263 }
 264 
 265 // Caller needs ResourceMark.
 266 static void throw_dup_pkg_exception(const char* module_name, PackageEntry* package, TRAPS) {
 267   const char* package_name = package->name()->as_C_string();
 268   if (package->module()->is_named()) {
 269     THROW_MSG(vmSymbols::java_lang_IllegalStateException(),
 270       err_msg("Package %s for module %s is already in another module, %s, defined to the class loader",
 271               package_name, module_name, package->module()->name()->as_C_string()));
 272   } else {
 273     THROW_MSG(vmSymbols::java_lang_IllegalStateException(),
 274       err_msg("Package %s for module %s is already in the unnamed module defined to the class loader",
 275               package_name, module_name));
 276   }
 277 }
 278 
 279 void Modules::define_module(Handle module, jboolean is_open, jstring version,
 280                             jstring location, jobjectArray packages, TRAPS) {
 281   ResourceMark rm(THREAD);
 282 
 283   if (module.is_null()) {
 284     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "Null module object");
 285   }
 286 
 287   if (!java_lang_Module::is_instance(module())) {
 288     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 289               "module is not an instance of type java.lang.Module");
 290   }
 291 
 292   int module_name_len;
 293   char* module_name = get_module_name(module(), module_name_len, CHECK);
 294   if (module_name == nullptr) {
 295     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 296               "Module name cannot be null");
 297   }
 298 
 299   // Resolve packages
 300   objArrayHandle packages_h(THREAD, objArrayOop(JNIHandles::resolve(packages)));
 301   int num_packages = (packages_h.is_null() ? 0 : packages_h->length());
 302   if (strncmp(module_name, "jdk.proxy", 9) != 0) {
 303     check_cds_restrictions(Handle(), Handle(), CHECK);
 304   }
 305 
 306   // Special handling of java.base definition
 307   if (strcmp(module_name, JAVA_BASE_NAME) == 0) {
 308     assert(is_open == JNI_FALSE, "java.base module cannot be open");
 309     define_javabase_module(module, version, location, packages_h, num_packages, CHECK);
 310     return;
 311   }
 312 
 313   oop loader = java_lang_Module::loader(module());
 314   Handle h_loader = Handle(THREAD, loader);
 315   // define_module can be called during start-up, before the class loader's ClassLoaderData
 316   // has been created.  SystemDictionary::register_loader ensures creation, if needed.
 317   ClassLoaderData* loader_data = SystemDictionary::register_loader(h_loader);
 318   assert(loader_data != nullptr, "class loader data shouldn't be null");
 319 
 320   // Only modules defined to either the boot or platform class loader, can define a "java/" package.
 321   bool java_pkg_disallowed = !h_loader.is_null() &&
 322         !SystemDictionary::is_platform_class_loader(h_loader());
 323 
 324   // Check that the list of packages has no duplicates and that the
 325   // packages are syntactically ok.
 326   char buf[128];
 327   GrowableArray<Symbol*>* pkg_list = new GrowableArray<Symbol*>(num_packages);
 328   for (int x = 0; x < num_packages; x++) {
 329     oop pkg_str = packages_h->obj_at(x);
 330     if (pkg_str == nullptr || pkg_str->klass() != vmClasses::String_klass()) {
 331       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 332                 err_msg("Bad package name"));
 333     }
 334 
 335     int package_len;
 336     const char* package_name = as_internal_package(pkg_str, buf, sizeof(buf), package_len);
 337     if (!verify_package_name(package_name, package_len)) {
 338       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 339                 err_msg("Invalid package name: %s for module: %s",
 340                         package_name, module_name));
 341     }
 342 
 343     // Only modules defined to either the boot or platform class loader, can define a "java/" package.
 344     if (java_pkg_disallowed &&
 345         (strncmp(package_name, JAVAPKG, JAVAPKG_LEN) == 0 &&
 346           (package_name[JAVAPKG_LEN] == JVM_SIGNATURE_SLASH || package_name[JAVAPKG_LEN] == '\0'))) {
 347       const char* class_loader_name = loader_data->loader_name_and_id();
 348       size_t pkg_len = strlen(package_name);
 349       char* pkg_name = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, pkg_len + 1);
 350       strncpy(pkg_name, package_name, pkg_len + 1);
 351       StringUtils::replace_no_expand(pkg_name, "/", ".");
 352       const char* msg_text1 = "Class loader (instance of): ";
 353       const char* msg_text2 = " tried to define prohibited package name: ";
 354       size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + pkg_len + 1;
 355       char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
 356       jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, pkg_name);
 357       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), message);
 358     }
 359 
 360     Symbol* pkg_symbol = SymbolTable::new_symbol(package_name, package_len);
 361     pkg_list->append(pkg_symbol);
 362   }
 363 
 364   ModuleEntryTable* module_table = get_module_entry_table(h_loader);
 365   assert(module_table != nullptr, "module entry table shouldn't be null");
 366 
 367   // Create symbol* entry for module name.
 368   TempNewSymbol module_symbol = SymbolTable::new_symbol(module_name, module_name_len);
 369 
 370   bool dupl_modules = false;
 371 
 372   // Create symbol for module version.
 373   TempNewSymbol version_symbol = as_symbol(version);
 374 
 375   // Create symbol* entry for module location.
 376   TempNewSymbol location_symbol = as_symbol(location);
 377 
 378   PackageEntryTable* package_table = nullptr;
 379   PackageEntry* existing_pkg = nullptr;
 380   {
 381     MutexLocker ml(THREAD, Module_lock);
 382 
 383     if (num_packages > 0) {
 384       package_table = get_package_entry_table(h_loader);
 385       assert(package_table != nullptr, "Missing package_table");
 386 
 387       // Check that none of the packages exist in the class loader's package table.
 388       for (int x = 0; x < pkg_list->length(); x++) {
 389         existing_pkg = package_table->locked_lookup_only(pkg_list->at(x));
 390         if (existing_pkg != nullptr) {
 391           // This could be because the module was already defined.  If so,
 392           // report that error instead of the package error.
 393           if (module_table->lookup_only(module_symbol) != nullptr) {
 394             dupl_modules = true;
 395           }
 396           break;
 397         }
 398       }
 399     }  // if (num_packages > 0)...
 400 
 401     // Add the module and its packages.
 402     if (!dupl_modules && existing_pkg == nullptr) {
 403       if (module_table->lookup_only(module_symbol) == nullptr) {
 404         // Create the entry for this module in the class loader's module entry table.
 405         ModuleEntry* module_entry = module_table->locked_create_entry(module,
 406                                     (is_open == JNI_TRUE), module_symbol,
 407                                     version_symbol, location_symbol, loader_data);
 408         assert(module_entry != nullptr, "module_entry creation failed");
 409 
 410         // Add the packages.
 411         assert(pkg_list->length() == 0 || package_table != nullptr, "Bad package table");
 412         for (int y = 0; y < pkg_list->length(); y++) {
 413           package_table->locked_create_entry(pkg_list->at(y), module_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.Module object.
 422         java_lang_Module::set_module_entry(module(), module_entry);
 423       } else {
 424          dupl_modules = true;
 425       }
 426     }
 427   }  // Release the lock
 428 
 429   // any errors ?
 430   if (dupl_modules) {
 431      THROW_MSG(vmSymbols::java_lang_IllegalStateException(),
 432                err_msg("Module %s is already defined", module_name));
 433   } else if (existing_pkg != nullptr) {
 434       throw_dup_pkg_exception(module_name, existing_pkg, CHECK);
 435   }
 436 
 437   log_info(module, load)("%s location: %s", module_name,
 438                          location_symbol != nullptr ? location_symbol->as_C_string() : "null");
 439   LogTarget(Debug, module) lt;
 440   if (lt.is_enabled()) {
 441     LogStream ls(lt);
 442     ls.print("define_module(): creation of module: %s, version: %s, location: %s, ",
 443                  module_name, version_symbol != nullptr ? version_symbol->as_C_string() : "null",
 444                  location_symbol != nullptr ? location_symbol->as_C_string() : "null");
 445     loader_data->print_value_on(&ls);
 446     ls.print_cr(", package #: %d", pkg_list->length());
 447     for (int y = 0; y < pkg_list->length(); y++) {
 448       log_trace(module)("define_module(): creation of package %s for module %s",
 449                         (pkg_list->at(y))->as_C_string(), module_name);
 450     }
 451   }
 452 
 453   // If the module is defined to the boot loader and an exploded build is being
 454   // used, prepend <java.home>/modules/modules_name to the boot class path.
 455   if (h_loader.is_null() && !ClassLoader::has_jrt_entry()) {
 456     ClassLoader::add_to_exploded_build_list(THREAD, module_symbol);
 457   }
 458 
 459 #if COMPILER2_OR_JVMCI
 460   // Special handling of jdk.incubator.vector
 461   if (strcmp(module_name, "jdk.incubator.vector") == 0) {
 462     if (FLAG_IS_DEFAULT(EnableVectorSupport)) {
 463       FLAG_SET_DEFAULT(EnableVectorSupport, true);
 464     }
 465     if (EnableVectorSupport && FLAG_IS_DEFAULT(EnableVectorReboxing)) {
 466       FLAG_SET_DEFAULT(EnableVectorReboxing, true);
 467     }
 468     if (EnableVectorSupport && EnableVectorReboxing && FLAG_IS_DEFAULT(EnableVectorAggressiveReboxing)) {
 469       FLAG_SET_DEFAULT(EnableVectorAggressiveReboxing, true);
 470     }
 471     log_info(compilation)("EnableVectorSupport=%s",            (EnableVectorSupport            ? "true" : "false"));
 472     log_info(compilation)("EnableVectorReboxing=%s",           (EnableVectorReboxing           ? "true" : "false"));
 473     log_info(compilation)("EnableVectorAggressiveReboxing=%s", (EnableVectorAggressiveReboxing ? "true" : "false"));
 474   }
 475 #endif // COMPILER2_OR_JVMCI
 476 }
 477 
 478 #if INCLUDE_CDS_JAVA_HEAP
 479 static bool _seen_platform_unnamed_module = false;
 480 static bool _seen_system_unnamed_module = false;
 481 
 482 // Validate the states of an java.lang.Module oop to be archived.
 483 void Modules::check_archived_module_oop(oop orig_module_obj) {
 484   assert(CDSConfig::is_dumping_full_module_graph(), "must be");
 485   assert(java_lang_Module::is_instance(orig_module_obj), "must be");
 486 
 487   ModuleEntry* orig_module_ent = java_lang_Module::module_entry_raw(orig_module_obj);
 488   if (orig_module_ent == nullptr) {
 489     // These special java.lang.Module oops are created in Java code. They are not
 490     // defined via Modules::define_module(), so they don't have a ModuleEntry:
 491     //     java.lang.Module::ALL_UNNAMED_MODULE
 492     //     java.lang.Module::EVERYONE_MODULE
 493     //     jdk.internal.loader.ClassLoaders$BootClassLoader::unnamedModule
 494     log_info(cds, module)("Archived java.lang.Module oop " PTR_FORMAT " with no ModuleEntry*", p2i(orig_module_obj));
 495     assert(java_lang_Module::name(orig_module_obj) == nullptr, "must be unnamed");
 496   } else {
 497     // This java.lang.Module oop has an ModuleEntry*. Check if the latter is archived.
 498     if (log_is_enabled(Info, cds, module)) {
 499       ResourceMark rm;
 500       LogStream ls(Log(cds, module)::info());
 501       ls.print("Archived java.lang.Module oop " PTR_FORMAT " for ", p2i(orig_module_obj));
 502       orig_module_ent->print(&ls);
 503     }
 504 
 505     // We only archive the default module graph, which should contain only java.lang.Module oops
 506     // for the 3 built-in loaders (boot/platform/system)
 507     ClassLoaderData* loader_data = orig_module_ent->loader_data();
 508     assert(loader_data->is_builtin_class_loader_data(), "must be");
 509 
 510     if (orig_module_ent->name() != nullptr) {
 511       // For each named module, we archive both the java.lang.Module oop and the ModuleEntry.
 512       assert(orig_module_ent->has_been_archived(), "sanity");
 513     } else {
 514       // We only archive two unnamed module oops (for platform and system loaders). These do NOT have an archived
 515       // ModuleEntry.
 516       //
 517       // At runtime, these oops are fetched from java_lang_ClassLoader::unnamedModule(loader) and
 518       // are initialized in ClassLoaderData::ClassLoaderData() => ModuleEntry::create_unnamed_module(), where
 519       // a new ModuleEntry is allocated.
 520       assert(!loader_data->is_boot_class_loader_data(), "unnamed module for boot loader should be not archived");
 521       assert(!orig_module_ent->has_been_archived(), "sanity");
 522 
 523       if (SystemDictionary::is_platform_class_loader(loader_data->class_loader())) {
 524         assert(!_seen_platform_unnamed_module, "only once");
 525         _seen_platform_unnamed_module = true;
 526       } else if (SystemDictionary::is_system_class_loader(loader_data->class_loader())) {
 527         assert(!_seen_system_unnamed_module, "only once");
 528         _seen_system_unnamed_module = true;
 529       } else {
 530         // The java.lang.Module oop and ModuleEntry of the unnamed module of the boot loader are
 531         // not in the archived module graph. These are always allocated at runtime.
 532         ShouldNotReachHere();
 533       }
 534     }
 535   }
 536 }
 537 
 538 void Modules::verify_archived_modules() {
 539   ModuleEntry::verify_archived_module_entries();
 540 }
 541 
 542 class Modules::ArchivedProperty {
 543   const char* _prop;
 544   const bool _numbered;
 545   const char* _archived_value;
 546 
 547   const char* get_flattened_value() const {
 548     if (_numbered) {
 549       return get_numbered_property_as_sorted_string();
 550     } else {
 551       return Arguments::get_property(_prop);
 552     }
 553   }
 554 
 555   void runtime_check() const;
 556   const char* get_numbered_property_as_sorted_string() const;
 557 
 558 public:
 559   ArchivedProperty(const char* prop, bool numbered)
 560     : _prop(prop), _numbered(numbered), _archived_value(nullptr) {}
 561 
 562   void dump() {
 563     ResourceMark rm;
 564     const char* str = get_flattened_value();
 565     if (str != nullptr) {
 566       _archived_value = ArchiveBuilder::current()->ro_strdup(str);
 567     }
 568   }
 569 
 570   void serialize(SerializeClosure* soc) {
 571     soc->do_ptr(&_archived_value);
 572     if (soc->reading()) {
 573       runtime_check();
 574       // Don't hold onto the pointer, in case we might decide to unmap the archive.
 575       _archived_value = nullptr;
 576     }
 577   }
 578 };
 579 
 580 Modules::ArchivedProperty Modules::_archived_props[] = {
 581   // non-numbered
 582   {"jdk.module.main", false},
 583 
 584   // numbered
 585   {"jdk.module.addexports", true},             // --add-exports
 586   {"jdk.module.addmods", true},                // --add-modules
 587   {"jdk.module.enable.native.access", true},   // --enable-native-access
 588   {"jdk.module.addopens", true},               // --add-opens
 589 };
 590 
 591 constexpr size_t Modules::num_archived_props() {
 592   return sizeof(_archived_props) / sizeof(_archived_props[0]);
 593 }
 594 
 595 Modules::ArchivedProperty& Modules::archived_prop(size_t i) {
 596   assert(i < num_archived_props(), "oob");
 597   return _archived_props[i];
 598 }
 599 
 600 void Modules::ArchivedProperty::runtime_check() const {
 601   ResourceMark rm;
 602   const char* runtime_value = get_flattened_value();
 603   log_info(cds)("archived module property %s: %s", _prop,
 604                 _archived_value != nullptr ? _archived_value : "(null)");
 605 
 606   bool disable = false;
 607   if (runtime_value == nullptr) {
 608     if (_archived_value != nullptr) {
 609       log_info(cds)("Mismatched values for property %s: %s specified during dump time but not during runtime", _prop, _archived_value);
 610       disable = true;
 611     }
 612   } else {
 613     if (_archived_value == nullptr) {
 614       log_info(cds)("Mismatched values for property %s: %s specified during runtime but not during dump time", _prop, runtime_value);
 615       disable = true;
 616     } else if (strcmp(runtime_value, _archived_value) != 0) {
 617       log_info(cds)("Mismatched values for property %s: runtime %s dump time %s", _prop, runtime_value, _archived_value);
 618       disable = true;
 619     }
 620   }
 621 
 622   if (disable) {
 623     log_info(cds)("Disabling optimized module handling");
 624     CDSConfig::stop_using_optimized_module_handling();
 625   }
 626 }
 627 
 628 // Caller needs ResourceMark
 629 const char* Modules::ArchivedProperty::get_numbered_property_as_sorted_string() const {
 630   assert(_numbered, "sanity");
 631   // theoretical string size limit for decimal int, but the following loop will end much sooner due to
 632   // OS command-line size limit.
 633   const int max_digits = 10;
 634   const int extra_symbols_count = 2; // includes '.', '\0'
 635   size_t prop_len = strlen(_prop) + max_digits + extra_symbols_count;
 636   char* prop_name = resource_allocate_bytes(prop_len);
 637   GrowableArray<const char*> list;
 638   for (unsigned int i = 0;; i++) {
 639     jio_snprintf(prop_name, prop_len, "%s.%d", _prop, i);
 640     const char* prop_value = Arguments::get_property(prop_name);
 641     if (prop_value == nullptr) {
 642       break;
 643     }
 644     char* p = resource_allocate_bytes(strlen(prop_value) + 1);
 645     strcpy(p, prop_value);
 646     while (*p == ',') p++; // skip leading commas
 647     while (*p) {
 648       char* next = strchr(p, ',');
 649       if (next == nullptr) {
 650         // no more commas, p is the last element
 651         list.append(p);
 652         break;
 653       } else {
 654         *next = 0;
 655         list.append(p);
 656         p = next + 1;
 657       }
 658     }
 659   }
 660 
 661   // Example:
 662   // --add-modules=java.compiler --add-modules=java.base,java.base,,
 663   //
 664   // list[0] = "java.compiler"
 665   // list[1] = "java.base"
 666   // list[2] = "java.base"
 667   // list[3] = ""
 668   // list[4] = ""
 669   list.sort(ClassLoaderExt::compare_module_names);
 670 
 671   const char* prefix = "";
 672   stringStream st;
 673   const char* last_string = ""; // This also filters out all empty strings
 674   for (int i = 0; i < list.length(); i++) {
 675     const char* m = list.at(i);
 676     if (strcmp(m, last_string) != 0) { // filter out duplicates
 677       st.print("%s%s", prefix, m);
 678       last_string = m;
 679       prefix = ",";
 680     }
 681   }
 682 
 683   return (st.size() > 0) ? st.as_string() : nullptr;  // Example: "java.base,java.compiler"
 684 }
 685 
 686 void Modules::dump_archived_module_info() {
 687   for (size_t i = 0; i < num_archived_props(); i++) {
 688     archived_prop(i).dump();
 689   }
 690 }
 691 
 692 void Modules::serialize_archived_module_info(SerializeClosure* soc) {
 693   for (size_t i = 0; i < num_archived_props(); i++) {
 694     archived_prop(i).serialize(soc);
 695   }
 696   if (soc->reading()) {
 697     log_info(cds)("optimized module handling: %s", CDSConfig::is_using_optimized_module_handling() ? "enabled" : "disabled");
 698     log_info(cds)("full module graph: %s", CDSConfig::is_using_full_module_graph() ? "enabled" : "disabled");
 699   }
 700 }
 701 
 702 void Modules::define_archived_modules(Handle h_platform_loader, Handle h_system_loader, TRAPS) {
 703   assert(CDSConfig::is_using_full_module_graph(), "must be");
 704 
 705   // We don't want the classes used by the archived full module graph to be redefined by JVMTI.
 706   // Luckily, such classes are loaded in the JVMTI "early" phase, and CDS is disabled if a JVMTI
 707   // agent wants to redefine classes in this phase.
 708   JVMTI_ONLY(assert(JvmtiExport::is_early_phase(), "must be"));
 709   assert(!(JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()),
 710          "CDS should be disabled if early class hooks are enabled");
 711 
 712   Handle java_base_module(THREAD, ClassLoaderDataShared::restore_archived_oops_for_null_class_loader_data());
 713   // Patch any previously loaded class's module field with java.base's java.lang.Module.
 714   ModuleEntryTable::patch_javabase_entries(THREAD, java_base_module);
 715 
 716   if (h_platform_loader.is_null()) {
 717     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "Null platform loader object");
 718   }
 719 
 720   if (h_system_loader.is_null()) {
 721     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "Null system loader object");
 722   }
 723 
 724   ClassLoaderData* platform_loader_data = SystemDictionary::register_loader(h_platform_loader);
 725   SystemDictionary::set_platform_loader(platform_loader_data);
 726   ClassLoaderDataShared::restore_java_platform_loader_from_archive(platform_loader_data);
 727 
 728   ClassLoaderData* system_loader_data = SystemDictionary::register_loader(h_system_loader);
 729   SystemDictionary::set_system_loader(system_loader_data);
 730   // system_loader_data here is always an instance of jdk.internal.loader.ClassLoader$AppClassLoader.
 731   // However, if -Djava.system.class.loader=xxx is specified, java_platform_loader() would
 732   // be an instance of a user-defined class, so make sure this never happens.
 733   assert(Arguments::get_property("java.system.class.loader") == nullptr,
 734            "archived full module should have been disabled if -Djava.system.class.loader is specified");
 735   ClassLoaderDataShared::restore_java_system_loader_from_archive(system_loader_data);
 736 }
 737 
 738 void Modules::check_cds_restrictions(Handle module1, Handle module2, TRAPS) {
 739   if (CDSConfig::is_dumping_full_module_graph() && Universe::is_module_initialized()) {
 740     if (CDSConfig::is_dumping_dynamic_proxies() && (is_dynamic_proxy_module(module1) || is_dynamic_proxy_module(module2))) {
 741       // The only the we allow is to add or modify the jdk.proxy?? modules that are used for dynamic proxies.
 742     } else {
 743       THROW_MSG(vmSymbols::java_lang_UnsupportedOperationException(),
 744                 "During -Xshare:dump, module system cannot be modified after it's initialized");
 745     }
 746   }
 747 }
 748 
 749 #endif // INCLUDE_CDS_JAVA_HEAP
 750 
 751 bool Modules::is_dynamic_proxy_module(Handle module) {
 752   if (!module.is_null()) {
 753     ModuleEntry* module_entry = java_lang_Module::module_entry(module());
 754     return is_dynamic_proxy_module(module_entry);
 755   }
 756   return false;
 757 }
 758 
 759 bool Modules::is_dynamic_proxy_module(ModuleEntry* module_entry) {
 760   return (module_entry != nullptr && module_entry->is_named() && module_entry->name()->starts_with("jdk.proxy"));
 761 }
 762 
 763 void Modules::set_bootloader_unnamed_module(Handle module, TRAPS) {
 764   ResourceMark rm(THREAD);
 765 
 766   if (module.is_null()) {
 767     THROW_MSG(vmSymbols::java_lang_NullPointerException(), "Null module object");
 768   }
 769   if (!java_lang_Module::is_instance(module())) {
 770     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 771               "module is not an instance of type java.lang.Module");
 772   }
 773 
 774   // Ensure that this is an unnamed module
 775   oop name = java_lang_Module::name(module());
 776   if (name != nullptr) {
 777     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 778               "boot loader's unnamed module's java.lang.Module has a name");
 779   }
 780 
 781   // Validate java_base's loader is the boot loader.
 782   oop loader = java_lang_Module::loader(module());
 783   if (loader != nullptr) {
 784     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 785               "Class loader must be the boot class loader");
 786   }
 787 
 788   log_debug(module)("set_bootloader_unnamed_module(): recording unnamed module for boot loader");
 789 
 790   // Set java.lang.Module for the boot loader's unnamed module
 791   ClassLoaderData* boot_loader_data = ClassLoaderData::the_null_class_loader_data();
 792   ModuleEntry* unnamed_module = boot_loader_data->unnamed_module();
 793   assert(unnamed_module != nullptr, "boot loader's unnamed ModuleEntry not defined");
 794   unnamed_module->set_module(boot_loader_data->add_handle(module));
 795   // Store pointer to the ModuleEntry in the unnamed module's java.lang.Module object.
 796   java_lang_Module::set_module_entry(module(), unnamed_module);
 797 }
 798 
 799 void Modules::add_module_exports(Handle from_module, jstring package_name, Handle to_module, TRAPS) {
 800   check_cds_restrictions(from_module, to_module, CHECK);
 801 
 802   if (package_name == nullptr) {
 803     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 804               "package is null");
 805   }
 806   if (from_module.is_null()) {
 807     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 808               "from_module is null");
 809   }
 810   ModuleEntry* from_module_entry = get_module_entry(from_module, CHECK);
 811   if (from_module_entry == nullptr) {
 812     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 813               "from_module cannot be found");
 814   }
 815 
 816   // All packages in unnamed and open modules are exported by default.
 817   if (!from_module_entry->is_named() || from_module_entry->is_open()) return;
 818 
 819   ModuleEntry* to_module_entry;
 820   if (to_module.is_null()) {
 821     to_module_entry = nullptr;  // It's an unqualified export.
 822   } else {
 823     to_module_entry = get_module_entry(to_module, CHECK);
 824     if (to_module_entry == nullptr) {
 825       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 826                 "to_module is invalid");
 827     }
 828   }
 829 
 830   PackageEntry* package_entry = nullptr;
 831   char buf[128];
 832   int package_len;
 833 
 834   ResourceMark rm(THREAD);
 835   const char* pkg = as_internal_package(JNIHandles::resolve_non_null(package_name), buf, sizeof(buf), package_len);
 836   {
 837     MutexLocker ml(THREAD, Module_lock);
 838     package_entry = get_locked_package_entry(from_module_entry, pkg, package_len);
 839     // Do nothing if modules are the same
 840     // If the package is not found we'll throw an exception later
 841     if (from_module_entry != to_module_entry &&
 842         package_entry != nullptr) {
 843       package_entry->set_exported(to_module_entry);
 844     }
 845   }
 846 
 847   // Handle errors and logging outside locked section
 848   if (package_entry == nullptr) {
 849     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 850               err_msg("Package %s not found in from_module %s",
 851                       pkg != nullptr ? pkg : "",
 852                       from_module_entry->name()->as_C_string()));
 853   }
 854 
 855   if (log_is_enabled(Debug, module)) {
 856     log_debug(module)("add_module_exports(): package %s in module %s is exported to module %s",
 857                       package_entry->name()->as_C_string(),
 858                       from_module_entry->name()->as_C_string(),
 859                       to_module_entry == nullptr ? "null" :
 860                       to_module_entry->is_named() ?
 861                       to_module_entry->name()->as_C_string() : UNNAMED_MODULE);
 862   }
 863 }
 864 
 865 
 866 void Modules::add_module_exports_qualified(Handle from_module, jstring package,
 867                                            Handle to_module, TRAPS) {
 868   check_cds_restrictions(from_module, to_module, CHECK);
 869   if (to_module.is_null()) {
 870     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 871               "to_module is null");
 872   }
 873   add_module_exports(from_module, package, to_module, CHECK);
 874 }
 875 
 876 void Modules::add_reads_module(Handle from_module, Handle to_module, TRAPS) {
 877   check_cds_restrictions(from_module, to_module, CHECK);
 878   if (from_module.is_null()) {
 879     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 880               "from_module is null");
 881   }
 882 
 883   ModuleEntry* from_module_entry = get_module_entry(from_module, CHECK);
 884   if (from_module_entry == nullptr) {
 885     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 886               "from_module is not valid");
 887   }
 888 
 889   ModuleEntry* to_module_entry;
 890   if (!to_module.is_null()) {
 891     to_module_entry = get_module_entry(to_module, CHECK);
 892     if (to_module_entry == nullptr) {
 893       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 894                 "to_module is invalid");
 895     }
 896   } else {
 897     to_module_entry = nullptr;
 898   }
 899 
 900   ResourceMark rm(THREAD);
 901   log_debug(module)("add_reads_module(): Adding read from module %s to module %s",
 902                     from_module_entry->is_named() ?
 903                     from_module_entry->name()->as_C_string() : UNNAMED_MODULE,
 904                     to_module_entry == nullptr ? "all unnamed" :
 905                       (to_module_entry->is_named() ?
 906                        to_module_entry->name()->as_C_string() : UNNAMED_MODULE));
 907 
 908   // if modules are the same or if from_module is unnamed then no need to add the read.
 909   if (from_module_entry != to_module_entry && from_module_entry->is_named()) {
 910     from_module_entry->add_read(to_module_entry);
 911   }
 912 }
 913 
 914 // This method is called by JFR and JNI.
 915 jobject Modules::get_module(jclass clazz, TRAPS) {
 916   assert(ModuleEntryTable::javabase_defined(),
 917          "Attempt to call get_module before " JAVA_BASE_NAME " is defined");
 918 
 919   if (clazz == nullptr) {
 920     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
 921                "class is null", nullptr);
 922   }
 923   oop mirror = JNIHandles::resolve_non_null(clazz);
 924   if (mirror == nullptr) {
 925     log_debug(module)("get_module(): no mirror, returning nullptr");
 926     return nullptr;
 927   }
 928   if (!java_lang_Class::is_instance(mirror)) {
 929     THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
 930                "Invalid class", nullptr);
 931   }
 932 
 933   oop module = java_lang_Class::module(mirror);
 934 
 935   assert(module != nullptr, "java.lang.Class module field not set");
 936   assert(java_lang_Module::is_instance(module), "module is not an instance of type java.lang.Module");
 937 
 938   LogTarget(Debug,module) lt;
 939   if (lt.is_enabled()) {
 940     LogStream ls(lt);
 941     Klass* klass = java_lang_Class::as_Klass(mirror);
 942     oop module_name = java_lang_Module::name(module);
 943     if (module_name != nullptr) {
 944       ls.print("get_module(): module ");
 945       java_lang_String::print(module_name, tty);
 946     } else {
 947       ls.print("get_module(): Unnamed Module");
 948     }
 949     if (klass != nullptr) {
 950       ResourceMark rm(THREAD);
 951       ls.print_cr(" for class %s", klass->external_name());
 952     } else {
 953       ls.print_cr(" for primitive class");
 954     }
 955   }
 956 
 957   return JNIHandles::make_local(THREAD, module);
 958 }
 959 
 960 oop Modules::get_named_module(Handle h_loader, const char* package_name) {
 961   assert(ModuleEntryTable::javabase_defined(),
 962          "Attempt to call get_named_module before " JAVA_BASE_NAME " is defined");
 963   assert(h_loader.is_null() || java_lang_ClassLoader::is_subclass(h_loader->klass()),
 964          "Class loader is not a subclass of java.lang.ClassLoader");
 965   assert(package_name != nullptr, "the package_name should not be null");
 966 
 967   if (strlen(package_name) == 0) {
 968     return nullptr;
 969   }
 970   TempNewSymbol package_sym = SymbolTable::new_symbol(package_name);
 971   const PackageEntry* const pkg_entry =
 972     get_package_entry_by_name(package_sym, h_loader);
 973   const ModuleEntry* const module_entry = (pkg_entry != nullptr ? pkg_entry->module() : nullptr);
 974 
 975   if (module_entry != nullptr && module_entry->module() != nullptr && module_entry->is_named()) {
 976     return module_entry->module();
 977   }
 978   return nullptr;
 979 }
 980 
 981 // Export package in module to all unnamed modules.
 982 void Modules::add_module_exports_to_all_unnamed(Handle module, jstring package_name, TRAPS) {
 983   check_cds_restrictions(Handle(), module, CHECK);
 984   if (module.is_null()) {
 985     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 986               "module is null");
 987   }
 988   if (package_name == nullptr) {
 989     THROW_MSG(vmSymbols::java_lang_NullPointerException(),
 990               "package is null");
 991   }
 992   ModuleEntry* module_entry = get_module_entry(module, CHECK);
 993   if (module_entry == nullptr) {
 994     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
 995               "module is invalid");
 996   }
 997 
 998   // No-op for unnamed module and open modules
 999   if (!module_entry->is_named() || module_entry->is_open())
1000     return;
1001 
1002   ResourceMark rm(THREAD);
1003   char buf[128];
1004   int pkg_len;
1005   const char* pkg = as_internal_package(JNIHandles::resolve_non_null(package_name), buf, sizeof(buf), pkg_len);
1006   PackageEntry* package_entry = nullptr;
1007   {
1008     MutexLocker m1(THREAD, Module_lock);
1009     package_entry = get_locked_package_entry(module_entry, pkg, pkg_len);
1010 
1011     // Mark package as exported to all unnamed modules.
1012     if (package_entry != nullptr) {
1013       package_entry->set_is_exported_allUnnamed();
1014     }
1015   }
1016 
1017   // Handle errors and logging outside locked section
1018   if (package_entry == nullptr) {
1019     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
1020               err_msg("Package %s not found in module %s",
1021                       pkg != nullptr ? pkg : "",
1022                       module_entry->name()->as_C_string()));
1023   }
1024 
1025   if (log_is_enabled(Debug, module)) {
1026     log_debug(module)("add_module_exports_to_all_unnamed(): package %s in module"
1027                       " %s is exported to all unnamed modules",
1028                        package_entry->name()->as_C_string(),
1029                        module_entry->name()->as_C_string());
1030   }
1031 }