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