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/aotGrowableArray.inline.hpp"
26 #include "cds/aotMetaspace.hpp"
27 #include "cds/archiveBuilder.hpp"
28 #include "cds/archiveUtils.hpp"
29 #include "cds/cdsConfig.hpp"
30 #include "classfile/classLoaderData.hpp"
31 #include "classfile/moduleEntry.hpp"
32 #include "classfile/packageEntry.hpp"
33 #include "classfile/vmSymbols.hpp"
34 #include "logging/log.hpp"
35 #include "logging/logStream.hpp"
36 #include "memory/metadataFactory.hpp"
37 #include "memory/resourceArea.hpp"
38 #include "oops/array.hpp"
39 #include "oops/symbol.hpp"
40 #include "runtime/handles.inline.hpp"
41 #include "runtime/java.hpp"
42 #include "utilities/events.hpp"
43 #include "utilities/hashTable.hpp"
44 #include "utilities/ostream.hpp"
45 #include "utilities/quickSort.hpp"
46
47 PackageEntry::PackageEntry(Symbol* name, ModuleEntry* module) :
48 _name(name),
49 _module(module),
50 _export_flags(0),
51 _classpath_index(-1),
52 _must_walk_exports(false),
53 _qualified_exports(nullptr),
54 _defined_by_cds_in_class_path(0)
55 {
56 // name can't be null -- a class in the default package gets a PackageEntry of nullptr.
57 _name->increment_refcount();
58
59 JFR_ONLY(INIT_ID(this);)
60 }
61
62 PackageEntry::~PackageEntry() {
63 delete_qualified_exports();
64 _name->decrement_refcount();
65 }
66
67 // Returns true if this package specifies m as a qualified export, including through an unnamed export
68 bool PackageEntry::is_qexported_to(ModuleEntry* m) const {
69 assert(Module_lock->owned_by_self(), "should have the Module_lock");
70 assert(m != nullptr, "No module to lookup in this package's qualified exports list");
71 if (is_exported_allUnnamed() && !m->is_named()) {
72 return true;
73 } else if (!has_qual_exports_list()) {
74 return false;
75 } else {
76 return _qualified_exports->contains(m);
77 }
78 }
79
80 // Add a module to the package's qualified export list.
81 void PackageEntry::add_qexport(ModuleEntry* m) {
82 assert(Module_lock->owned_by_self(), "should have the Module_lock");
83 if (!has_qual_exports_list()) {
84 // Lazily create a package's qualified exports list.
85 // Initial size is small, do not anticipate export lists to be large.
86 _qualified_exports = new (mtModule) AOTGrowableArray<ModuleEntry*>(QUAL_EXP_SIZE, mtModule);
87 }
88
89 // Determine, based on this newly established export to module m,
90 // if this package's export list should be walked at a GC safepoint.
91 set_export_walk_required(m->loader_data());
92
93 // Establish exportability to module m
94 _qualified_exports->append_if_missing(m);
95 }
96
97 // If the module's loader, that an export is being established to, is
98 // not the same loader as this module's and is not one of the 3 builtin
99 // class loaders, then this package's export list must be walked at GC
100 // safepoint. Modules have the same life cycle as their defining class
101 // loaders and should be removed if dead.
102 void PackageEntry::set_export_walk_required(ClassLoaderData* m_loader_data) {
103 assert_locked_or_safepoint(Module_lock);
104 ModuleEntry* this_pkg_mod = module();
105 if (!_must_walk_exports &&
106 (this_pkg_mod == nullptr || this_pkg_mod->loader_data() != m_loader_data) &&
107 !m_loader_data->is_builtin_class_loader_data()) {
108 _must_walk_exports = true;
109 if (log_is_enabled(Trace, module)) {
110 ResourceMark rm;
111 assert(name() != nullptr, "PackageEntry without a valid name");
112 log_trace(module)("PackageEntry::set_export_walk_required(): package %s defined in module %s, exports list must be walked",
113 name()->as_C_string(),
114 (this_pkg_mod == nullptr || this_pkg_mod->name() == nullptr) ?
115 UNNAMED_MODULE : this_pkg_mod->name()->as_C_string());
116 }
117 }
118 }
119
120 // Set the package's exported states based on the value of the ModuleEntry.
121 void PackageEntry::set_exported(ModuleEntry* m) {
122 assert(Module_lock->owned_by_self(), "should have the Module_lock");
123 if (is_unqual_exported()) {
124 // An exception could be thrown, but choose to simply ignore.
125 // Illegal to convert an unqualified exported package to be qualifiedly exported
126 return;
127 }
128
129 if (m == nullptr) {
130 // null indicates the package is being unqualifiedly exported. Clean up
131 // the qualified list at the next safepoint.
132 set_unqual_exported();
133 } else {
134 // Add the exported module
135 add_qexport(m);
136 }
137 }
138
139 // Set the package as exported to all unnamed modules unless the package is
140 // already unqualifiedly exported.
141 void PackageEntry::set_is_exported_allUnnamed() {
142 assert(!module()->is_open(), "should have been checked already");
143 assert(Module_lock->owned_by_self(), "should have the Module_lock");
144 if (!is_unqual_exported()) {
145 _export_flags = PKG_EXP_ALLUNNAMED;
146 }
147 }
148
149 // Remove dead module entries within the package's exported list. Note that
150 // if all of the modules on the _qualified_exports get purged the list does not
151 // get deleted. This prevents the package from illegally transitioning from
152 // exported to non-exported.
153 void PackageEntry::purge_qualified_exports() {
154 assert_locked_or_safepoint(Module_lock);
155 if (_must_walk_exports &&
156 _qualified_exports != nullptr &&
157 !_qualified_exports->is_empty()) {
158
159 // This package's _must_walk_exports flag will be reset based
160 // on the remaining live modules on the exports list.
161 _must_walk_exports = false;
162
163 if (log_is_enabled(Trace, module)) {
164 ResourceMark rm;
165 assert(name() != nullptr, "PackageEntry without a valid name");
166 ModuleEntry* pkg_mod = module();
167 log_trace(module)("PackageEntry::purge_qualified_exports(): package %s defined in module %s, exports list being walked",
168 name()->as_C_string(),
169 (pkg_mod == nullptr || pkg_mod->name() == nullptr) ? UNNAMED_MODULE : pkg_mod->name()->as_C_string());
170 }
171
172 // Go backwards because this removes entries that are dead.
173 int len = _qualified_exports->length();
174 for (int idx = len - 1; idx >= 0; idx--) {
175 ModuleEntry* module_idx = _qualified_exports->at(idx);
176 ClassLoaderData* cld_idx = module_idx->loader_data();
177 if (cld_idx->is_unloading()) {
178 _qualified_exports->delete_at(idx);
179 } else {
180 // Update the need to walk this package's exports based on live modules
181 set_export_walk_required(cld_idx);
182 }
183 }
184 }
185 }
186
187 void PackageEntry::delete_qualified_exports() {
188 if (_qualified_exports != nullptr && !AOTMetaspace::in_aot_cache(_qualified_exports)) {
189 delete _qualified_exports;
190 }
191 _qualified_exports = nullptr;
192 }
193
194 void PackageEntry::pack_qualified_exports() {
195 if (_qualified_exports != nullptr) {
196 _qualified_exports->shrink_to_fit();
197 }
198 }
199
200 void PackageEntry::metaspace_pointers_do(MetaspaceClosure* it) {
201 it->push(&_name);
202 it->push(&_module);
203 it->push(&_qualified_exports);
204 }
205
206 PackageEntryTable::PackageEntryTable() { }
207
208 PackageEntryTable::~PackageEntryTable() {
209 class PackageEntryTableDeleter : public StackObj {
210 public:
211 bool do_entry(const SymbolHandle& name, PackageEntry*& entry) {
212 if (log_is_enabled(Info, module, unload) || log_is_enabled(Debug, module)) {
213 ResourceMark rm;
214 const char* str = name->as_C_string();
215 log_info(module, unload)("unloading package %s", str);
216 log_debug(module)("PackageEntry: deleting package: %s", str);
217 }
218 delete entry;
219 return true;
220 }
221 };
222
223 PackageEntryTableDeleter deleter;
224 _table.unlink(&deleter);
225 assert(_table.number_of_entries() == 0, "should have removed all entries");
226 }
227
228 #if INCLUDE_CDS_JAVA_HEAP
229 bool PackageEntry::should_be_archived() const {
230 return module()->should_be_archived();
231 }
232
233 void PackageEntry::remove_unshareable_info() {
234 if (_qualified_exports != nullptr) {
235 _qualified_exports->set_in_aot_cache();
236 }
237 _defined_by_cds_in_class_path = 0;
238 JFR_ONLY(set_trace_id(0);) // re-init at runtime
239 }
240
241 void PackageEntry::load_from_archive() {
242 JFR_ONLY(INIT_ID(this);)
243 }
244
245 static int compare_package_by_name(PackageEntry* a, PackageEntry* b) {
246 assert(a == b || a->name() != b->name(), "no duplicated names");
247 return a->name()->fast_compare(b->name());
248 }
249
250 Array<PackageEntry*>* PackageEntryTable::build_aot_table(ClassLoaderData* loader_data, TRAPS) {
251 // First count the packages in named modules
252 int n = 0;
253 auto count = [&] (const SymbolHandle& key, PackageEntry*& p) {
254 if (p->should_be_archived()) {
255 n++;
256 }
257 };
258 _table.iterate_all(count);
259
260 Array<PackageEntry*>* archived_packages = MetadataFactory::new_array<PackageEntry*>(loader_data, n, nullptr, CHECK_NULL);
261 // reset n
262 n = 0;
263 auto grab = [&] (const SymbolHandle& key, PackageEntry*& p) {
264 if (p->should_be_archived()) {
265 p->pack_qualified_exports();
266 archived_packages->at_put(n++, p);
267
268 LogStreamHandle(Info, aot, package) st;
269 if (st.is_enabled()) {
270 st.print("archived ");
271 p->print(&st);
272 }
273 }
274 };
275 _table.iterate_all(grab);
276
277 if (n > 1) {
278 // Always allocate in the same order to produce deterministic archive.
279 QuickSort::sort(archived_packages->data(), n, compare_package_by_name);
280 }
281
282 return archived_packages;
283 }
284
285 void PackageEntryTable::load_archived_entries(Array<PackageEntry*>* archived_packages) {
286 assert(CDSConfig::is_using_archive(), "runtime only");
287
288 for (int i = 0; i < archived_packages->length(); i++) {
289 PackageEntry* archived_entry = archived_packages->at(i);
290 archived_entry->load_from_archive();
291 _table.put(archived_entry->name(), archived_entry);
292 }
293 }
294
295 #endif // INCLUDE_CDS_JAVA_HEAP
296
297 // Create package entry in loader's package entry table. Assume Module lock
298 // was taken by caller.
299 void PackageEntryTable::locked_create_entry(Symbol* name, ModuleEntry* module) {
300 assert(Module_lock->owned_by_self(), "should have the Module_lock");
301 assert(locked_lookup_only(name) == nullptr, "Package entry already exists");
302 PackageEntry* entry = new PackageEntry(name, module);
303 bool created = _table.put(name, entry);
304 assert(created, "must be");
305 }
306
307 // Create package entry in loader's package entry table if it does not already
308 // exist. Assume Module lock was taken by caller.
309 PackageEntry* PackageEntryTable::locked_create_entry_if_absent(Symbol* name, ModuleEntry* module) {
310 assert(Module_lock->owned_by_self(), "should have the Module_lock");
311 // Check if package entry already exists. If not, create it.
312 bool created;
313 PackageEntry* entry = new PackageEntry(name, module);
314 PackageEntry** old_entry = _table.put_if_absent(name, entry, &created);
315 if (created) {
316 return entry;
317 } else {
318 delete entry;
319 return *old_entry;
320 }
321 }
322
323 PackageEntry* PackageEntryTable::create_entry_if_absent(Symbol* name, ModuleEntry* module) {
324 MutexLocker ml(Module_lock);
325 return locked_create_entry_if_absent(name, module);
326 }
327
328 PackageEntry* PackageEntryTable::lookup_only(Symbol* name) {
329 assert(!Module_lock->owned_by_self(), "should not have the Module_lock - use locked_lookup_only");
330 MutexLocker ml(Module_lock);
331 return locked_lookup_only(name);
332 }
333
334 PackageEntry* PackageEntryTable::locked_lookup_only(Symbol* name) {
335 assert(Module_lock->owned_by_self(), "should have the Module_lock");
336 PackageEntry** entry = _table.get(name);
337 return entry == nullptr ? nullptr : *entry;
338 }
339
340 // Called when a define module for java.base is being processed.
341 // Verify the packages loaded thus far are in java.base's package list.
342 void PackageEntryTable::verify_javabase_packages(GrowableArray<Symbol*> *pkg_list) {
343 assert_lock_strong(Module_lock);
344 auto verifier = [&] (const SymbolHandle& name, PackageEntry*& entry) {
345 ModuleEntry* m = entry->module();
346 Symbol* module_name = (m == nullptr ? nullptr : m->name());
347 if (module_name != nullptr &&
348 (module_name->fast_compare(vmSymbols::java_base()) == 0) &&
349 !pkg_list->contains(entry->name())) {
350 ResourceMark rm;
351 vm_exit_during_initialization("A non-" JAVA_BASE_NAME " package was loaded prior to module system initialization",
352 entry->name()->as_C_string());
353 }
354 };
355 _table.iterate_all(verifier);
356 }
357
358 // iteration of qualified exports
359 void PackageEntry::package_exports_do(ModuleClosure* f) {
360 assert_locked_or_safepoint(Module_lock);
361 assert(f != nullptr, "invariant");
362
363 if (has_qual_exports_list()) {
364 int qe_len = _qualified_exports->length();
365
366 for (int i = 0; i < qe_len; ++i) {
367 f->do_module(_qualified_exports->at(i));
368 }
369 }
370 }
371
372 bool PackageEntry::exported_pending_delete() const {
373 assert_locked_or_safepoint(Module_lock);
374 return (is_unqual_exported() && _qualified_exports != nullptr);
375 }
376
377 // Remove dead entries from all packages' exported list
378 void PackageEntryTable::purge_all_package_exports() {
379 assert_locked_or_safepoint(Module_lock);
380 auto purge = [&] (const SymbolHandle& name, PackageEntry*& entry) {
381 if (entry->exported_pending_delete()) {
382 // exported list is pending deletion due to a transition
383 // from qualified to unqualified
384 entry->delete_qualified_exports();
385 } else if (entry->is_qual_exported()) {
386 entry->purge_qualified_exports();
387 }
388 };
389 _table.iterate_all(purge);
390 }
391
392 void PackageEntryTable::packages_do(void f(PackageEntry*)) {
393 auto doit = [&] (const SymbolHandle&name, PackageEntry*& entry) {
394 f(entry);
395 };
396 assert_locked_or_safepoint(Module_lock);
397 _table.iterate_all(doit);
398 }
399
400
401 GrowableArray<PackageEntry*>* PackageEntryTable::get_system_packages() {
402 GrowableArray<PackageEntry*>* loaded_class_pkgs = new GrowableArray<PackageEntry*>(50);
403 auto grab = [&] (const SymbolHandle& name, PackageEntry*& entry) {
404 if (entry->has_loaded_class()) {
405 loaded_class_pkgs->append(entry);
406 }
407 };
408
409 MutexLocker ml(Module_lock);
410 _table.iterate_all(grab);
411 // Returns a resource allocated object so caller must have ResourceMark
412 return loaded_class_pkgs;
413 }
414
415 void PackageEntryTable::print(outputStream* st) {
416 auto printer = [&] (const SymbolHandle& name, PackageEntry*& entry) {
417 entry->print(st);
418 };
419 st->print_cr("Package Entry Table (table_size=%d, entries=%d)",
420 _table.table_size(), _table.number_of_entries());
421 _table.iterate_all(printer);
422 }
423
424 // This function may be called from debuggers so access private fields directly
425 // to prevent triggering locking-related asserts that could result from calling
426 // getter methods.
427 void PackageEntry::print(outputStream* st) {
428 ResourceMark rm;
429 st->print_cr("package entry " PTR_FORMAT " name %s module %s classpath_index "
430 INT32_FORMAT " is_exported_unqualified %d is_exported_allUnnamed %d ",
431 p2i(this), name()->as_C_string(),
432 (module()->is_named() ? module()->name()->as_C_string() : UNNAMED_MODULE),
433 _classpath_index, _export_flags == PKG_EXP_UNQUALIFIED,
434 _export_flags == PKG_EXP_ALLUNNAMED);
435 }