1 /*
   2  * Copyright (c) 2012, 2017, 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 "runtime/handles.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 //
  41 // A class loader represents a linkset. Conceptually, a linkset identifies
  42 // the complete transitive closure of resolved links that a dynamic linker can
  43 // produce.
  44 //
  45 // A ClassLoaderData also encapsulates the allocation space, called a metaspace,
  46 // used by the dynamic linker to allocate the runtime representation of all
  47 // the types it defines.
  48 //
  49 // ClassLoaderData are stored in the runtime representation of classes and the
  50 // system dictionary, are roots of garbage collection, and provides iterators
  51 // for root tracing and other GC operations.
  52 
  53 class ClassLoaderData;
  54 class JNIMethodBlock;
  55 class Metadebug;
  56 
  57 // GC root for walking class loader data created
  58 
  59 class ClassLoaderDataGraph : public AllStatic {
  60   friend class ClassLoaderData;
  61   friend class ClassLoaderDataGraphMetaspaceIterator;
  62   friend class ClassLoaderDataGraphKlassIteratorAtomic;
  63   friend class VMStructs;
  64  private:
  65   // All CLDs (except the null CLD) can be reached by walking _head->_next->...
  66   static ClassLoaderData* _head;
  67   static ClassLoaderData* _unloading;
  68   // CMS support.
  69   static ClassLoaderData* _saved_head;
  70   static ClassLoaderData* _saved_unloading;
  71   static bool _should_purge;
  72 
  73   static ClassLoaderData* add(Handle class_loader, bool anonymous, TRAPS);
  74   static void clean_metaspaces();
  75  public:
  76   static ClassLoaderData* find_or_create(Handle class_loader, TRAPS);
  77   static void purge();
  78   static void clear_claimed_marks();
  79   // oops do
  80   static void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim);
  81   static void keep_alive_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
  82   static void always_strong_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
  83   // cld do
  84   static void cld_do(CLDClosure* cl);
  85   static void cld_unloading_do(CLDClosure* cl);
  86   static void roots_cld_do(CLDClosure* strong, CLDClosure* weak);
  87   static void keep_alive_cld_do(CLDClosure* cl);
  88   static void always_strong_cld_do(CLDClosure* cl);
  89   // klass do
  90   static void classes_do(KlassClosure* klass_closure);
  91   static void classes_do(void f(Klass* const));
  92   static void loaded_classes_do(KlassClosure* klass_closure);
  93   static void classes_unloading_do(void f(Klass* const));
  94   static bool do_unloading(BoolObjectClosure* is_alive, bool clean_alive);
  95 
  96   // CMS support.
  97   static void remember_new_clds(bool remember) { _saved_head = (remember ? _head : NULL); }
  98   static GrowableArray<ClassLoaderData*>* new_clds();
  99 
 100   static void set_should_purge(bool b) { _should_purge = b; }
 101   static void purge_if_needed() {
 102     // Only purge the CLDG for CMS if concurrent sweep is complete.
 103     if (_should_purge) {
 104       purge();
 105       // reset for next time.
 106       set_should_purge(false);
 107     }
 108   }
 109 
 110   static void free_deallocate_lists();
 111 
 112   static void dump_on(outputStream * const out) PRODUCT_RETURN;
 113   static void dump() { dump_on(tty); }
 114   static void verify();
 115 
 116   static bool unload_list_contains(const void* x);
 117 #ifndef PRODUCT
 118   static bool contains_loader_data(ClassLoaderData* loader_data);
 119 #endif
 120 };
 121 
 122 // ClassLoaderData class
 123 
 124 class ClassLoaderData : public CHeapObj<mtClass> {
 125   friend class VMStructs;
 126  private:
 127   class Dependencies VALUE_OBJ_CLASS_SPEC {
 128     objArrayOop _list_head;
 129     void locked_add(objArrayHandle last,
 130                     objArrayHandle new_dependency,
 131                     Thread* THREAD);
 132    public:
 133     Dependencies() : _list_head(NULL) {}
 134     Dependencies(TRAPS) : _list_head(NULL) {
 135       init(CHECK);
 136     }
 137     void add(Handle dependency, TRAPS);
 138     void init(TRAPS);
 139     void oops_do(OopClosure* f);
 140   };
 141 
 142   class ChunkedHandleList VALUE_OBJ_CLASS_SPEC {
 143     struct Chunk : public CHeapObj<mtClass> {
 144       static const size_t CAPACITY = 32;
 145 
 146       oop _data[CAPACITY];
 147       volatile juint _size;
 148       Chunk* _next;
 149 
 150       Chunk(Chunk* c) : _next(c), _size(0) { }
 151     };
 152 
 153     Chunk* _head;
 154 
 155     void oops_do_chunk(OopClosure* f, Chunk* c, const juint size);
 156 
 157    public:
 158     ChunkedHandleList() : _head(NULL) {}
 159     ~ChunkedHandleList();
 160 
 161     // Only one thread at a time can add, guarded by ClassLoaderData::metaspace_lock().
 162     // However, multiple threads can execute oops_do concurrently with add.
 163     oop* add(oop o);
 164     void oops_do(OopClosure* f);
 165   };
 166 
 167   friend class ClassLoaderDataGraph;
 168   friend class ClassLoaderDataGraphKlassIteratorAtomic;
 169   friend class ClassLoaderDataGraphMetaspaceIterator;
 170   friend class MetaDataFactory;
 171   friend class Method;
 172 
 173   static ClassLoaderData * _the_null_class_loader_data;
 174 
 175   oop _class_loader;          // oop used to uniquely identify a class loader
 176                               // class loader or a canonical class path
 177   Dependencies _dependencies; // holds dependencies from this class loader
 178                               // data to others.
 179 
 180   Metaspace * _metaspace;  // Meta-space where meta-data defined by the
 181                            // classes in the class loader are allocated.
 182   Mutex* _metaspace_lock;  // Locks the metaspace for allocations and setup.
 183   bool _unloading;         // true if this class loader goes away
 184   bool _keep_alive;        // if this CLD is kept alive without a keep_alive_object().
 185   bool _is_anonymous;      // if this CLD is for an anonymous class
 186   volatile int _claimed;   // true if claimed, for example during GC traces.
 187                            // To avoid applying oop closure more than once.
 188                            // Has to be an int because we cas it.
 189   Klass* _klasses;         // The classes defined by the class loader.
 190 
 191   ChunkedHandleList _handles; // Handles to constant pool arrays, etc, which
 192                               // have the same life cycle of the corresponding ClassLoader.
 193 
 194   // These method IDs are created for the class loader and set to NULL when the
 195   // class loader is unloaded.  They are rarely freed, only for redefine classes
 196   // and if they lose a data race in InstanceKlass.
 197   JNIMethodBlock*                  _jmethod_ids;
 198 
 199   // Metadata to be deallocated when it's safe at class unloading, when
 200   // this class loader isn't unloaded itself.
 201   GrowableArray<Metadata*>*      _deallocate_list;
 202 
 203   // Support for walking class loader data objects
 204   ClassLoaderData* _next; /// Next loader_datas created
 205 
 206   // ReadOnly and ReadWrite metaspaces (static because only on the null
 207   // class loader for now).
 208   static Metaspace* _ro_metaspace;
 209   static Metaspace* _rw_metaspace;
 210 
 211   JFR_ONLY(DEFINE_TRACE_ID_FIELD;)
 212 
 213   void set_next(ClassLoaderData* next) { _next = next; }
 214   ClassLoaderData* next() const        { return _next; }
 215 
 216   ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies);
 217   ~ClassLoaderData();
 218 
 219   void set_metaspace(Metaspace* m) { _metaspace = m; }
 220 
 221   Mutex* metaspace_lock() const { return _metaspace_lock; }
 222 
 223   void unload();
 224   bool keep_alive() const       { return _keep_alive; }
 225   void classes_do(void f(Klass*));
 226   void loaded_classes_do(KlassClosure* klass_closure);
 227   void classes_do(void f(InstanceKlass*));
 228 
 229   // Deallocate free list during class unloading.
 230   void free_deallocate_list();
 231 
 232   // Allocate out of this class loader data
 233   MetaWord* allocate(size_t size);
 234 
 235  public:
 236 
 237   // GC interface.
 238   void clear_claimed()          { _claimed = 0; }
 239   bool claimed() const          { return _claimed == 1; }
 240   bool claim();
 241 
 242   bool is_alive(BoolObjectClosure* is_alive_closure) const;
 243 
 244   // Accessors
 245   Metaspace* metaspace_or_null() const     { return _metaspace; }
 246 
 247   static ClassLoaderData* the_null_class_loader_data() {
 248     return _the_null_class_loader_data;
 249   }
 250 
 251   bool is_anonymous() const { return _is_anonymous; }
 252 
 253   static void init_null_class_loader_data() {
 254     assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
 255     assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
 256 
 257     // We explicitly initialize the Dependencies object at a later phase in the initialization
 258     _the_null_class_loader_data = new ClassLoaderData((oop)NULL, false, Dependencies());
 259     ClassLoaderDataGraph::_head = _the_null_class_loader_data;
 260     assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
 261     if (DumpSharedSpaces) {
 262       _the_null_class_loader_data->initialize_shared_metaspaces();
 263     }
 264   }
 265 
 266   bool is_the_null_class_loader_data() const {
 267     return this == _the_null_class_loader_data;
 268   }
 269   bool is_ext_class_loader_data() const;
 270 
 271   // The Metaspace is created lazily so may be NULL.  This
 272   // method will allocate a Metaspace if needed.
 273   Metaspace* metaspace_non_null();
 274 
 275   oop class_loader() const      { return _class_loader; }
 276 
 277   // The object the GC is using to keep this ClassLoaderData alive.
 278   oop keep_alive_object() const;
 279 
 280   // Returns true if this class loader data is for a loader going away.
 281   bool is_unloading() const     {
 282     assert(!(is_the_null_class_loader_data() && _unloading), "The null class loader can never be unloaded");
 283     return _unloading;
 284   }
 285 
 286   // Used to make sure that this CLD is not unloaded.
 287   void set_keep_alive(bool value) { _keep_alive = value; }
 288 
 289   unsigned int identity_hash() {
 290     return _class_loader == NULL ? 0 : _class_loader->identity_hash();
 291   }
 292 
 293   // Used when tracing from klasses.
 294   void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim);
 295 
 296   void classes_do(KlassClosure* klass_closure);
 297 
 298   JNIMethodBlock* jmethod_ids() const              { return _jmethod_ids; }
 299   void set_jmethod_ids(JNIMethodBlock* new_block)  { _jmethod_ids = new_block; }
 300 
 301   void print_value() { print_value_on(tty); }
 302   void print_value_on(outputStream* out) const;
 303   void dump(outputStream * const out) PRODUCT_RETURN;
 304   void verify();
 305   const char* loader_name();
 306 
 307   jobject add_handle(Handle h);
 308   void add_class(Klass* k);
 309   void remove_class(Klass* k);
 310   bool contains_klass(Klass* k);
 311   void record_dependency(Klass* to, TRAPS);
 312   void init_dependencies(TRAPS);
 313 
 314   void add_to_deallocate_list(Metadata* m);
 315 
 316   static ClassLoaderData* class_loader_data(oop loader);
 317   static ClassLoaderData* class_loader_data_or_null(oop loader);
 318   static ClassLoaderData* anonymous_class_loader_data(oop loader, TRAPS);
 319   static void print_loader(ClassLoaderData *loader_data, outputStream *out);
 320 
 321   // CDS support
 322   Metaspace* ro_metaspace();
 323   Metaspace* rw_metaspace();
 324   void initialize_shared_metaspaces();
 325 
 326   JFR_ONLY(DEFINE_TRACE_ID_METHODS;)
 327 };
 328 
 329 // An iterator that distributes Klasses to parallel worker threads.
 330 class ClassLoaderDataGraphKlassIteratorAtomic : public StackObj {
 331  Klass* volatile _next_klass;
 332  public:
 333   ClassLoaderDataGraphKlassIteratorAtomic();
 334   Klass* next_klass();
 335  private:
 336   static Klass* next_klass_in_cldg(Klass* klass);
 337 };
 338 
 339 class ClassLoaderDataGraphMetaspaceIterator : public StackObj {
 340   ClassLoaderData* _data;
 341  public:
 342   ClassLoaderDataGraphMetaspaceIterator();
 343   ~ClassLoaderDataGraphMetaspaceIterator();
 344   bool repeat() { return _data != NULL; }
 345   Metaspace* get_next() {
 346     assert(_data != NULL, "Should not be NULL in call to the iterator");
 347     Metaspace* result = _data->metaspace_or_null();
 348     _data = _data->next();
 349     // This result might be NULL for class loaders without metaspace
 350     // yet.  It would be nice to return only non-null results but
 351     // there is no guarantee that there will be a non-null result
 352     // down the list so the caller is going to have to check.
 353     return result;
 354   }
 355 };
 356 #endif // SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP