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