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