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