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