1 /*
  2  * Copyright (c) 2012, 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 #ifndef SHARE_CLASSFILE_CLASSLOADERDATA_HPP
 26 #define SHARE_CLASSFILE_CLASSLOADERDATA_HPP
 27 
 28 #include "memory/allocation.hpp"
 29 #include "oops/oopHandle.hpp"
 30 #include "oops/weakHandle.hpp"
 31 #include "runtime/atomic.hpp"
 32 #include "runtime/mutex.hpp"
 33 #include "utilities/growableArray.hpp"
 34 #include "utilities/macros.hpp"
 35 #if INCLUDE_JFR
 36 #include "jfr/support/jfrTraceIdExtension.hpp"
 37 #endif
 38 
 39 // external name (synthetic) for the primordial "bootstrap" class loader instance
 40 #define BOOTSTRAP_LOADER_NAME "bootstrap"
 41 #define BOOTSTRAP_LOADER_NAME_LEN 9
 42 
 43 //
 44 // A class loader represents a linkset. Conceptually, a linkset identifies
 45 // the complete transitive closure of resolved links that a dynamic linker can
 46 // produce.
 47 //
 48 // A ClassLoaderData also encapsulates the allocation space, called a metaspace,
 49 // used by the dynamic linker to allocate the runtime representation of all
 50 // the types it defines.
 51 //
 52 // ClassLoaderData are stored in the runtime representation of classes,
 53 // and provides iterators for root tracing and other GC operations.
 54 
 55 class ClassLoaderDataGraph;
 56 class ModuleEntry;
 57 class PackageEntry;
 58 class ModuleEntryTable;
 59 class PackageEntryTable;
 60 class DictionaryEntry;
 61 class Dictionary;
 62 class ClassLoaderMetaspace;
 63 
 64 // ClassLoaderData class
 65 
 66 class ClassLoaderData : public CHeapObj<mtClass> {
 67   friend class VMStructs;
 68 
 69  private:
 70   class ChunkedHandleList {
 71     struct Chunk : public CHeapObj<mtClass> {
 72       static const size_t CAPACITY = 32;
 73 
 74       oop _data[CAPACITY];
 75       volatile juint _size;
 76       Chunk* _next;
 77 
 78       Chunk(Chunk* c) : _size(0), _next(c) { }
 79     };
 80 
 81     Chunk* volatile _head;
 82 
 83     void oops_do_chunk(OopClosure* f, Chunk* c, const juint size);
 84 
 85    public:
 86     ChunkedHandleList() : _head(nullptr) {}
 87     ~ChunkedHandleList();
 88 
 89     // Only one thread at a time can add, guarded by ClassLoaderData::metaspace_lock().
 90     // However, multiple threads can execute oops_do concurrently with add.
 91     OopHandle add(oop o);
 92     bool contains(oop p);
 93     NOT_PRODUCT(bool owner_of(oop* p);)
 94     void oops_do(OopClosure* f);
 95 
 96     int count() const;
 97   };
 98 
 99   friend class ClassLoaderDataGraph;
100   friend class ClassLoaderDataGraphKlassIteratorAtomic;
101   friend class Klass;
102   friend class MetaDataFactory;
103   friend class Method;
104 
105   static ClassLoaderData * _the_null_class_loader_data;
106 
107   WeakHandle _holder;       // The oop that determines lifetime of this class loader
108   OopHandle  _class_loader; // The instance of java/lang/ClassLoader associated with
109                             // this ClassLoaderData
110 
111   ClassLoaderMetaspace * volatile _metaspace;  // Meta-space where meta-data defined by the
112                                     // classes in the class loader are allocated.
113   Mutex* _metaspace_lock;  // Locks the metaspace for allocations and setup.
114   bool _unloading;         // true if this class loader goes away
115   bool _has_class_mirror_holder; // If true, CLD is dedicated to one class and that class determines
116                                  // the CLDs lifecycle.  For example, a non-strong hidden class.
117                                  // Arrays of these classes are also assigned
118                                  // to these class loader data.
119 
120   // Remembered sets support for the oops in the class loader data.
121   bool _modified_oops;     // Card Table Equivalent
122 
123   int _keep_alive_ref_count; // if this CLD should not be considered eligible for unloading.
124                              // Used for non-strong hidden classes and the
125                              // boot class loader. _keep_alive_ref_count does not need to be volatile or
126                              // atomic since there is one unique CLD per non-strong hidden class.
127 
128   volatile int _claim; // non-zero if claimed, for example during GC traces.
129                        // To avoid applying oop closure more than once.
130   ChunkedHandleList _handles; // Handles to constant pool arrays, Modules, etc, which
131                               // have the same life cycle of the corresponding ClassLoader.
132 
133   NOT_PRODUCT(volatile int _dependency_count;)  // number of class loader dependencies
134 
135   Klass* volatile _klasses;              // The classes defined by the class loader.
136   PackageEntryTable* volatile _packages; // The packages defined by the class loader.
137   ModuleEntryTable*  volatile _modules;  // The modules defined by the class loader.
138   ModuleEntry* _unnamed_module;          // This class loader's unnamed module.
139   Dictionary*  _dictionary;              // The loaded InstanceKlasses, including initiated by this class loader
140 
141   // These method IDs are created for the class loader and removed when the
142   // class loader is unloaded.
143   GrowableArray<jmethodID>*        _jmethod_ids;
144 
145   // Metadata to be deallocated when it's safe at class unloading, when
146   // this class loader isn't unloaded itself.
147   GrowableArray<Metadata*>*      _deallocate_list;
148 
149   // Support for walking class loader data objects
150   //
151   // The ClassLoaderDataGraph maintains two lists to keep track of CLDs.
152   //
153   // The first list [_head, _next] is where new CLDs are registered. The CLDs
154   // are only inserted at the _head, and the _next pointers are only rewritten
155   // from unlink_next() which unlinks one unloading CLD by setting _next to
156   // _next->_next. This allows GCs to concurrently walk the list while the CLDs
157   // are being concurrently unlinked.
158   //
159   // The second list [_unloading_head, _unloading_next] is where dead CLDs get
160   // moved to during class unloading. See: ClassLoaderDataGraph::do_unloading().
161   // This list is never modified while other threads are iterating over it.
162   //
163   // After all dead CLDs have been moved to the unloading list, there's a
164   // synchronization point (handshake) to ensure that all threads reading these
165   // CLDs finish their work. This ensures that we don't have a use-after-free
166   // when we later delete the CLDs.
167   //
168   // And finally, when no threads are using the unloading CLDs anymore, we
169   // remove them from the class unloading list and delete them. See:
170   // ClassLoaderDataGraph::purge();
171   ClassLoaderData* _next;
172   ClassLoaderData* _unloading_next;
173 
174   Klass*  _class_loader_klass;
175   Symbol* _name;
176   Symbol* _name_and_id;
177   JFR_ONLY(DEFINE_TRACE_ID_FIELD;)
178 
179   void set_next(ClassLoaderData* next);
180   ClassLoaderData* next() const;
181   void unlink_next();
182 
183   ClassLoaderData(Handle h_class_loader, bool has_class_mirror_holder);
184 
185 public:
186   ~ClassLoaderData();
187 
188   void set_unloading_next(ClassLoaderData* unloading_next);
189   ClassLoaderData* unloading_next() const;
190   void unload();
191 
192 private:
193   // The CLD are not placed in the Heap, so the Card Table or
194   // the Mod Union Table can't be used to mark when CLD have modified oops.
195   // The CT and MUT bits saves this information for the whole class loader data.
196   void clear_modified_oops()             { _modified_oops = false; }
197  public:
198   void record_modified_oops()            { _modified_oops = true; }
199   bool has_modified_oops()               { return _modified_oops; }
200 
201   oop holder_no_keepalive() const;
202   // Resolving the holder keeps this CLD alive for the current GC cycle.
203   oop holder() const;
204   void keep_alive() const { (void)holder(); }
205 
206   void classes_do(void f(Klass* const));
207 
208  private:
209   int keep_alive_ref_count() const { return _keep_alive_ref_count; }
210 
211   void loaded_classes_do(KlassClosure* klass_closure);
212   void classes_do(void f(InstanceKlass*));
213   void methods_do(void f(Method*));
214   void modules_do(void f(ModuleEntry*));
215   void packages_do(void f(PackageEntry*));
216 
217   // Deallocate free list during class unloading.
218   void free_deallocate_list();                      // for the classes that are not unloaded
219   void free_deallocate_list_C_heap_structures();    // for the classes that are unloaded
220 
221   Dictionary* create_dictionary();
222 
223   void demote_strong_roots();
224 
225   void initialize_name(Handle class_loader);
226 
227  public:
228   // GC interface.
229 
230   // The "claim" is typically used to check if oops_do needs to be applied on
231   // the CLD or not. Most GCs only perform strong marking during the marking phase.
232   enum Claim {
233     _claim_none              = 0,
234     _claim_finalizable       = 2,
235     _claim_strong            = 3,
236     _claim_stw_fullgc_mark   = 4,
237     _claim_stw_fullgc_adjust = 8,
238     _claim_other             = 16
239   };
240   void clear_claim() { _claim = 0; }
241   void clear_claim(int claim);
242   void verify_not_claimed(int claim) NOT_DEBUG_RETURN;
243   bool claimed() const { return _claim != 0; }
244   bool claimed(int claim) const { return (_claim & claim) == claim; }
245   bool try_claim(int claim);
246 
247   // Computes if the CLD is alive or not. This is safe to call in concurrent
248   // contexts.
249   bool is_alive() const;
250 
251   // Accessors
252   ClassLoaderMetaspace* metaspace_or_null() const { return _metaspace; }
253 
254   static ClassLoaderData* the_null_class_loader_data() {
255     return _the_null_class_loader_data;
256   }
257 
258   Mutex* metaspace_lock() const { return _metaspace_lock; }
259 
260   bool has_class_mirror_holder() const { return _has_class_mirror_holder; }
261 
262   static void init_null_class_loader_data();
263 
264   bool is_the_null_class_loader_data() const {
265     return this == _the_null_class_loader_data;
266   }
267 
268   // Returns true if this class loader data is for the system class loader.
269   // (Note that the class loader data may be for a non-strong hidden class)
270   bool is_system_class_loader_data() const;
271 
272   // Returns true if this class loader data is for the platform class loader.
273   // (Note that the class loader data may be for a non-strong hidden class)
274   bool is_platform_class_loader_data() const;
275 
276   // Returns true if this class loader data is for the boot class loader.
277   // (Note that the class loader data may be for a non-strong hidden class)
278   inline bool is_boot_class_loader_data() const;
279 
280   bool is_builtin_class_loader_data() const;
281   bool is_permanent_class_loader_data() const;
282 
283   OopHandle class_loader_handle() const { return _class_loader; }
284 
285   // The Metaspace is created lazily so may be null.  This
286   // method will allocate a Metaspace if needed.
287   ClassLoaderMetaspace* metaspace_non_null();
288 
289   inline oop class_loader() const;
290   inline oop class_loader_no_keepalive() const;
291 
292   // Returns true if this class loader data is for a loader going away.
293   // Note that this is only safe after the GC has computed if the CLD is
294   // unloading or not. In concurrent contexts where there are no such
295   // guarantees, is_alive() should be used instead.
296   bool is_unloading() const     {
297     assert(!(is_the_null_class_loader_data() && _unloading), "The null class loader can never be unloaded");
298     return _unloading;
299   }
300 
301   // Used to refcount a non-strong hidden class's CLD in order to force its aliveness during
302   // loading, when gc tracing may not find this CLD alive through the holder.
303   void inc_keep_alive_ref_count();
304   void dec_keep_alive_ref_count();
305 
306   void initialize_holder(Handle holder);
307 
308   void oops_do(OopClosure* f, int claim_value, bool clear_modified_oops = false);
309 
310   void classes_do(KlassClosure* klass_closure);
311   Klass* klasses() { return _klasses; }
312 
313   void add_jmethod_id(jmethodID id);
314   void remove_jmethod_ids();
315   GrowableArray<jmethodID>* jmethod_ids() const { return _jmethod_ids; }
316 
317   void print() const;
318   void print_on(outputStream* out) const PRODUCT_RETURN;
319   void print_value() const;
320   void print_value_on(outputStream* out) const;
321   void verify();
322 
323   OopHandle add_handle(Handle h);
324   void remove_handle(OopHandle h);
325   void init_handle_locked(OopHandle& pd, Handle h);  // used for concurrent access to ModuleEntry::_pd field
326   void add_class(Klass* k, bool publicize = true);
327   void remove_class(Klass* k);
328   bool contains_klass(Klass* k);
329   void record_dependency(const Klass* to);
330   PackageEntryTable* packages() { return _packages; }
331   ModuleEntry* unnamed_module() { return _unnamed_module; }
332   ModuleEntryTable* modules();
333   bool modules_defined() { return (_modules != nullptr); }
334 
335   // Offsets
336   static ByteSize holder_offset() { return byte_offset_of(ClassLoaderData, _holder); }
337   static ByteSize keep_alive_ref_count_offset() { return byte_offset_of(ClassLoaderData, _keep_alive_ref_count); }
338 
339   // Loaded class dictionary
340   Dictionary* dictionary() const { return _dictionary; }
341 
342   void add_to_deallocate_list(Metadata* m);
343 
344   static ClassLoaderData* class_loader_data(oop loader);
345   static ClassLoaderData* class_loader_data_or_null(oop loader);
346 
347   // Returns Klass* of associated class loader, or null if associated loader is 'bootstrap'.
348   // Also works if unloading.
349   Klass* class_loader_klass() const { return _class_loader_klass; }
350 
351   // Returns the class loader's explicit name as specified during
352   // construction or the class loader's qualified class name.
353   // Works during unloading.
354   const char* loader_name() const;
355   // Returns the explicitly specified class loader name or null.
356   Symbol* name() const { return _name; }
357 
358   // Obtain the class loader's _name_and_id, works during unloading.
359   const char* loader_name_and_id() const;
360   Symbol* name_and_id() const { return _name_and_id; }
361 
362   unsigned identity_hash() const {
363     return (unsigned)((uintptr_t)this >> LogBytesPerWord);
364   }
365 
366   JFR_ONLY(DEFINE_TRACE_ID_METHODS;)
367 };
368 
369 #endif // SHARE_CLASSFILE_CLASSLOADERDATA_HPP