1 /*
  2  * Copyright (c) 2012, 2018, 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_VM_CLASSFILE_CLASSLOADERDATA_HPP
 26 #define SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP
 27 
 28 #include "memory/allocation.hpp"
 29 #include "memory/memRegion.hpp"
 30 #include "memory/metaspace.hpp"
 31 #include "oops/oopHandle.hpp"
 32 #include "oops/weakHandle.hpp"
 33 #include "runtime/mutex.hpp"
 34 #include "utilities/growableArray.hpp"
 35 #include "utilities/macros.hpp"
 36 #if INCLUDE_JFR
 37 #include "jfr/support/jfrTraceIdExtension.hpp"
 38 #endif
 39 
 40 // external name (synthetic) for the primordial "bootstrap" class loader instance
 41 #define BOOTSTRAP_LOADER_NAME "bootstrap"
 42 #define BOOTSTRAP_LOADER_NAME_LEN 9
 43 
 44 //
 45 // A class loader represents a linkset. Conceptually, a linkset identifies
 46 // the complete transitive closure of resolved links that a dynamic linker can
 47 // produce.
 48 //
 49 // A ClassLoaderData also encapsulates the allocation space, called a metaspace,
 50 // used by the dynamic linker to allocate the runtime representation of all
 51 // the types it defines.
 52 //
 53 // ClassLoaderData are stored in the runtime representation of classes,
 54 // and provides iterators for root tracing and other GC operations.
 55 
 56 class ClassLoaderData;
 57 class JNIMethodBlock;
 58 class Metadebug;
 59 class ModuleEntry;
 60 class PackageEntry;
 61 class ModuleEntryTable;
 62 class PackageEntryTable;
 63 class DictionaryEntry;
 64 class Dictionary;
 65 
 66 // GC root for walking class loader data created
 67 
 68 class ClassLoaderDataGraph : public AllStatic {
 69   friend class ClassLoaderData;
 70   friend class ClassLoaderDataGraphMetaspaceIterator;
 71   friend class ClassLoaderDataGraphKlassIteratorAtomic;
 72   friend class ClassLoaderDataGraphKlassIteratorStatic;
 73   friend class VMStructs;
 74  private:
 75   // All CLDs (except the null CLD) can be reached by walking _head->_next->...
 76   static ClassLoaderData* _head;
 77   static ClassLoaderData* _unloading;
 78   // CMS support.
 79   static ClassLoaderData* _saved_head;
 80   static ClassLoaderData* _saved_unloading;
 81   static bool _should_purge;
 82 
 83   // Set if there's anything to purge in the deallocate lists or previous versions
 84   // during a safepoint after class unloading in a full GC.
 85   static bool _should_clean_deallocate_lists;
 86   static bool _safepoint_cleanup_needed;
 87 
 88   // OOM has been seen in metaspace allocation. Used to prevent some
 89   // allocations until class unloading
 90   static bool _metaspace_oom;
 91 
 92   static volatile size_t  _num_instance_classes;
 93   static volatile size_t  _num_array_classes;
 94 
 95   static ClassLoaderData* add_to_graph(Handle class_loader, bool anonymous);
 96   static ClassLoaderData* add(Handle class_loader, bool anonymous);
 97 
 98  public:
 99   static ClassLoaderData* find_or_create(Handle class_loader);
100   static void clean_module_and_package_info();
101   static void purge();
102   static void clear_claimed_marks();
103   // oops do
104   static void oops_do(OopClosure* f, bool must_claim);
105   static void keep_alive_oops_do(OopClosure* blk, bool must_claim);
106   static void always_strong_oops_do(OopClosure* blk, bool must_claim);
107   // cld do
108   static void cld_do(CLDClosure* cl);
109   static void cld_unloading_do(CLDClosure* cl);
110   static void roots_cld_do(CLDClosure* strong, CLDClosure* weak);
111   static void keep_alive_cld_do(CLDClosure* cl);
112   static void always_strong_cld_do(CLDClosure* cl);
113   // klass do
114   // Walking classes through the ClassLoaderDataGraph include array classes.  It also includes
115   // classes that are allocated but not loaded, classes that have errors, and scratch classes
116   // for redefinition.  These classes are removed during the next class unloading.
117   // Walking the ClassLoaderDataGraph also includes anonymous classes.
118   static void classes_do(KlassClosure* klass_closure);
119   static void classes_do(void f(Klass* const));
120   static void methods_do(void f(Method*));
121   static void modules_do(void f(ModuleEntry*));
122   static void modules_unloading_do(void f(ModuleEntry*));
123   static void packages_do(void f(PackageEntry*));
124   static void packages_unloading_do(void f(PackageEntry*));
125   static void loaded_classes_do(KlassClosure* klass_closure);
126   static void classes_unloading_do(void f(Klass* const));
127   static bool do_unloading(bool do_cleaning);
128 
129   // Expose state to avoid logging overhead in safepoint cleanup tasks.
130   static inline bool should_clean_metaspaces_and_reset();
131   static void set_should_clean_deallocate_lists() { _should_clean_deallocate_lists = true; }
132   static void clean_deallocate_lists(bool purge_previous_versions);
133   static void walk_metadata_and_clean_metaspaces();
134 
135   // dictionary do
136   // Iterate over all klasses in dictionary, but
137   // just the classes from defining class loaders.
138   static void dictionary_classes_do(void f(InstanceKlass*));
139   // Added for initialize_itable_for_klass to handle exceptions.
140   static void dictionary_classes_do(void f(InstanceKlass*, TRAPS), TRAPS);
141 
142   // Iterate all classes and their class loaders, including initiating class loaders.
143   static void dictionary_all_entries_do(void f(InstanceKlass*, ClassLoaderData*));
144 
145   // VM_CounterDecay iteration support
146   static InstanceKlass* try_get_next_class();
147 
148   static void verify_dictionary();
149   static void print_dictionary(outputStream* st);
150   static void print_dictionary_statistics(outputStream* st);
151 
152   // CMS support.
153   static void remember_new_clds(bool remember) { _saved_head = (remember ? _head : NULL); }
154   static GrowableArray<ClassLoaderData*>* new_clds();
155 
156   static void set_should_purge(bool b) { _should_purge = b; }
157   static void purge_if_needed() {
158     // Only purge the CLDG for CMS if concurrent sweep is complete.
159     if (_should_purge) {
160       purge();
161       // reset for next time.
162       set_should_purge(false);
163     }
164   }
165 
166   static int resize_if_needed();
167 
168   static bool has_metaspace_oom()           { return _metaspace_oom; }
169   static void set_metaspace_oom(bool value) { _metaspace_oom = value; }
170 
171   static void print_on(outputStream * const out) PRODUCT_RETURN;
172   static void print() { print_on(tty); }
173   static void verify();
174 
175   // instance and array class counters
176   static inline size_t num_instance_classes();
177   static inline size_t num_array_classes();
178   static inline void inc_instance_classes(size_t count);
179   static inline void dec_instance_classes(size_t count);
180   static inline void inc_array_classes(size_t count);
181   static inline void dec_array_classes(size_t count);
182 
183 #ifndef PRODUCT
184   static bool contains_loader_data(ClassLoaderData* loader_data);
185 #endif
186 };
187 
188 // ClassLoaderData class
189 
190 class ClassLoaderData : public CHeapObj<mtClass> {
191   friend class VMStructs;
192 
193  private:
194   class ChunkedHandleList {
195     struct Chunk : public CHeapObj<mtClass> {
196       static const size_t CAPACITY = 32;
197 
198       oop _data[CAPACITY];
199       volatile juint _size;
200       Chunk* _next;
201 
202       Chunk(Chunk* c) : _size(0), _next(c) { }
203     };
204 
205     Chunk* volatile _head;
206 
207     void oops_do_chunk(OopClosure* f, Chunk* c, const juint size);
208 
209    public:
210     ChunkedHandleList() : _head(NULL) {}
211     ~ChunkedHandleList();
212 
213     // Only one thread at a time can add, guarded by ClassLoaderData::metaspace_lock().
214     // However, multiple threads can execute oops_do concurrently with add.
215     oop* add(oop o);
216     bool contains(oop p);
217     NOT_PRODUCT(bool owner_of(oop* p);)
218     void oops_do(OopClosure* f);
219 
220     int count() const;
221   };
222 
223   friend class ClassLoaderDataGraph;
224   friend class ClassLoaderDataGraphKlassIteratorAtomic;
225   friend class ClassLoaderDataGraphKlassIteratorStatic;
226   friend class ClassLoaderDataGraphMetaspaceIterator;
227   friend class Klass;
228   friend class MetaDataFactory;
229   friend class Method;
230 
231   static ClassLoaderData * _the_null_class_loader_data;
232 
233   WeakHandle<vm_class_loader_data> _holder; // The oop that determines lifetime of this class loader
234   OopHandle _class_loader;    // The instance of java/lang/ClassLoader associated with
235                               // this ClassLoaderData
236 
237   ClassLoaderMetaspace * volatile _metaspace;  // Meta-space where meta-data defined by the
238                                     // classes in the class loader are allocated.
239   Mutex* _metaspace_lock;  // Locks the metaspace for allocations and setup.
240   bool _unloading;         // true if this class loader goes away
241   bool _is_anonymous;      // if this CLD is for an anonymous class
242 
243   // Remembered sets support for the oops in the class loader data.
244   bool _modified_oops;             // Card Table Equivalent (YC/CMS support)
245   bool _accumulated_modified_oops; // Mod Union Equivalent (CMS support)
246 
247   s2 _keep_alive;          // if this CLD is kept alive.
248                            // Used for anonymous classes and the boot class
249                            // loader. _keep_alive does not need to be volatile or
250                            // atomic since there is one unique CLD per anonymous class.
251 
252   volatile int _claimed;   // true if claimed, for example during GC traces.
253                            // To avoid applying oop closure more than once.
254                            // Has to be an int because we cas it.
255   ChunkedHandleList _handles; // Handles to constant pool arrays, Modules, etc, which
256                               // have the same life cycle of the corresponding ClassLoader.
257 
258   NOT_PRODUCT(volatile int _dependency_count;)  // number of class loader dependencies
259 
260   Klass* volatile _klasses;              // The classes defined by the class loader.
261   PackageEntryTable* volatile _packages; // The packages defined by the class loader.
262   ModuleEntryTable*  volatile _modules;  // The modules defined by the class loader.
263   ModuleEntry* _unnamed_module;          // This class loader's unnamed module.
264   Dictionary*  _dictionary;              // The loaded InstanceKlasses, including initiated by this class loader
265 
266   // These method IDs are created for the class loader and set to NULL when the
267   // class loader is unloaded.  They are rarely freed, only for redefine classes
268   // and if they lose a data race in InstanceKlass.
269   JNIMethodBlock*                  _jmethod_ids;
270 
271   // Metadata to be deallocated when it's safe at class unloading, when
272   // this class loader isn't unloaded itself.
273   GrowableArray<Metadata*>*      _deallocate_list;
274 
275   // Support for walking class loader data objects
276   ClassLoaderData* _next; /// Next loader_datas created
277 
278   Klass*  _class_loader_klass;
279   Symbol* _name;
280   Symbol* _name_and_id;
281   JFR_ONLY(DEFINE_TRACE_ID_FIELD;)
282 
283   void set_next(ClassLoaderData* next) { _next = next; }
284   ClassLoaderData* next() const        { return _next; }
285 
286   ClassLoaderData(Handle h_class_loader, bool is_anonymous);
287   ~ClassLoaderData();
288 
289   // The CLD are not placed in the Heap, so the Card Table or
290   // the Mod Union Table can't be used to mark when CLD have modified oops.
291   // The CT and MUT bits saves this information for the whole class loader data.
292   void clear_modified_oops()             { _modified_oops = false; }
293  public:
294   void record_modified_oops()            { _modified_oops = true; }
295   bool has_modified_oops()               { return _modified_oops; }
296 
297   void accumulate_modified_oops()        { if (has_modified_oops()) _accumulated_modified_oops = true; }
298   void clear_accumulated_modified_oops() { _accumulated_modified_oops = false; }
299   bool has_accumulated_modified_oops()   { return _accumulated_modified_oops; }
300 
301   oop holder_no_keepalive() const;
302   bool keep_alive() const       { return _keep_alive > 0; }
303 
304 private:
305   void unload();
306   oop holder_phantom() const;
307 
308   void classes_do(void f(Klass*));
309   void loaded_classes_do(KlassClosure* klass_closure);
310   void classes_do(void f(InstanceKlass*));
311   void methods_do(void f(Method*));
312   void modules_do(void f(ModuleEntry*));
313   void packages_do(void f(PackageEntry*));
314 
315   // Deallocate free list during class unloading.
316   void free_deallocate_list();                      // for the classes that are not unloaded
317   void free_deallocate_list_C_heap_structures();    // for the classes that are unloaded
318 
319   // Allocate out of this class loader data
320   MetaWord* allocate(size_t size);
321 
322   Dictionary* create_dictionary();
323 
324   void initialize_name(Handle class_loader);
325  public:
326   // GC interface.
327   void clear_claimed() { _claimed = 0; }
328   bool claimed() const { return _claimed != 0; }
329   bool claim(bool finalizable = false);
330 
331   bool is_alive() const;
332 
333   // Accessors
334   ClassLoaderMetaspace* metaspace_or_null() const { return _metaspace; }
335 
336   static ClassLoaderData* the_null_class_loader_data() {
337     return _the_null_class_loader_data;
338   }
339 
340   Mutex* metaspace_lock() const { return _metaspace_lock; }
341 
342   bool is_anonymous() const { return _is_anonymous; }
343 
344   static void init_null_class_loader_data();
345 
346   bool is_the_null_class_loader_data() const {
347     return this == _the_null_class_loader_data;
348   }
349 
350   // Returns true if this class loader data is for the system class loader.
351   // (Note that the class loader data may be anonymous.)
352   bool is_system_class_loader_data() const;
353 
354   // Returns true if this class loader data is for the platform class loader.
355   // (Note that the class loader data may be anonymous.)
356   bool is_platform_class_loader_data() const;
357 
358   // Returns true if this class loader data is for the boot class loader.
359   // (Note that the class loader data may be anonymous.)
360   bool is_boot_class_loader_data() const;
361   bool is_builtin_class_loader_data() const;
362   bool is_permanent_class_loader_data() const;
363 
364   // The Metaspace is created lazily so may be NULL.  This
365   // method will allocate a Metaspace if needed.
366   ClassLoaderMetaspace* metaspace_non_null();
367 
368   oop class_loader() const;
369 
370   // Returns true if this class loader data is for a loader going away.
371   bool is_unloading() const     {
372     assert(!(is_the_null_class_loader_data() && _unloading), "The null class loader can never be unloaded");
373     return _unloading;
374   }
375 
376   // Used to refcount an anonymous class's CLD in order to
377   // indicate their aliveness.
378   void inc_keep_alive();
379   void dec_keep_alive();
380 
381   void initialize_holder(Handle holder);
382 
383   void oops_do(OopClosure* f, bool must_claim, bool clear_modified_oops = false);
384 
385   void classes_do(KlassClosure* klass_closure);
386   Klass* klasses() { return _klasses; }
387 
388   JNIMethodBlock* jmethod_ids() const              { return _jmethod_ids; }
389   void set_jmethod_ids(JNIMethodBlock* new_block)  { _jmethod_ids = new_block; }
390 
391   void print()                                     { print_on(tty); }
392   void print_on(outputStream* out) const PRODUCT_RETURN;
393   void print_value()                               { print_value_on(tty); }
394   void print_value_on(outputStream* out) const;
395   void verify();
396 
397   OopHandle add_handle(Handle h);
398   void remove_handle(OopHandle h);
399   void init_handle_locked(OopHandle& pd, Handle h);  // used for concurrent access to ModuleEntry::_pd field
400   void add_class(Klass* k, bool publicize = true);
401   void remove_class(Klass* k);
402   bool contains_klass(Klass* k);
403   void record_dependency(const Klass* to);
404   PackageEntryTable* packages() { return _packages; }
405   ModuleEntry* unnamed_module() { return _unnamed_module; }
406   ModuleEntryTable* modules();
407   bool modules_defined() { return (_modules != NULL); }
408 
409   // Loaded class dictionary
410   Dictionary* dictionary() const { return _dictionary; }
411 
412   void add_to_deallocate_list(Metadata* m);
413 
414   static ClassLoaderData* class_loader_data(oop loader);
415   static ClassLoaderData* class_loader_data_or_null(oop loader);
416   static ClassLoaderData* anonymous_class_loader_data(Handle loader);
417 
418   // Returns Klass* of associated class loader, or NULL if associated loader is 'bootstrap'.
419   // Also works if unloading.
420   Klass* class_loader_klass() const { return _class_loader_klass; }
421 
422   // Returns the class loader's explict name as specified during
423   // construction or the class loader's qualified class name.
424   // Works during unloading.
425   const char* loader_name() const;
426   // Returns the explicitly specified class loader name or NULL.
427   Symbol* name() const { return _name; }
428 
429   // Obtain the class loader's _name_and_id, works during unloading.
430   const char* loader_name_and_id() const;
431   Symbol* name_and_id() const { return _name_and_id; }
432 
433   JFR_ONLY(DEFINE_TRACE_ID_METHODS;)
434 };
435 
436 // An iterator that distributes Klasses to parallel worker threads.
437 class ClassLoaderDataGraphKlassIteratorAtomic : public StackObj {
438  Klass* volatile _next_klass;
439  public:
440   ClassLoaderDataGraphKlassIteratorAtomic();
441   Klass* next_klass();
442  private:
443   static Klass* next_klass_in_cldg(Klass* klass);
444 };
445 
446 class ClassLoaderDataGraphMetaspaceIterator : public StackObj {
447   ClassLoaderData* _data;
448  public:
449   ClassLoaderDataGraphMetaspaceIterator();
450   ~ClassLoaderDataGraphMetaspaceIterator();
451   bool repeat() { return _data != NULL; }
452   ClassLoaderMetaspace* get_next() {
453     assert(_data != NULL, "Should not be NULL in call to the iterator");
454     ClassLoaderMetaspace* result = _data->metaspace_or_null();
455     _data = _data->next();
456     // This result might be NULL for class loaders without metaspace
457     // yet.  It would be nice to return only non-null results but
458     // there is no guarantee that there will be a non-null result
459     // down the list so the caller is going to have to check.
460     return result;
461   }
462 };
463 #endif // SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP