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