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_TRACE
  37 #include "utilities/ticks.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 post_class_unload_events(void);
  75   static void clean_metaspaces();
  76  public:
  77   static ClassLoaderData* find_or_create(Handle class_loader, TRAPS);
  78   static void purge();
  79   static void clear_claimed_marks();
  80   // oops do
  81   static void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim);
  82   static void keep_alive_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
  83   static void always_strong_oops_do(OopClosure* blk, KlassClosure* klass_closure, bool must_claim);
  84   // cld do
  85   static void cld_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 #if INCLUDE_TRACE
 122  private:
 123   static Ticks _class_unload_time;
 124   static void class_unload_event(Klass* const k);
 125 #endif
 126 };
 127 
 128 // ClassLoaderData class
 129 
 130 class ClassLoaderData : public CHeapObj<mtClass> {
 131   friend class VMStructs;
 132  private:
 133   class Dependencies VALUE_OBJ_CLASS_SPEC {
 134     objArrayOop _list_head;
 135     void locked_add(objArrayHandle last,
 136                     objArrayHandle new_dependency,
 137                     Thread* THREAD);
 138    public:
 139     Dependencies() : _list_head(NULL) {}
 140     Dependencies(TRAPS) : _list_head(NULL) {
 141       init(CHECK);
 142     }
 143     void add(Handle dependency, TRAPS);
 144     void init(TRAPS);
 145     void oops_do(OopClosure* f);
 146   };
 147 
 148   class ChunkedHandleList VALUE_OBJ_CLASS_SPEC {
 149     struct Chunk : public CHeapObj<mtClass> {
 150       static const size_t CAPACITY = 32;
 151 
 152       oop _data[CAPACITY];
 153       volatile juint _size;
 154       Chunk* _next;
 155 
 156       Chunk(Chunk* c) : _next(c), _size(0) { }
 157     };
 158 
 159     Chunk* _head;
 160 
 161     void oops_do_chunk(OopClosure* f, Chunk* c, const juint size);
 162 
 163    public:
 164     ChunkedHandleList() : _head(NULL) {}
 165     ~ChunkedHandleList();
 166 
 167     // Only one thread at a time can add, guarded by ClassLoaderData::metaspace_lock().
 168     // However, multiple threads can execute oops_do concurrently with add.
 169     oop* add(oop o);
 170     void oops_do(OopClosure* f);
 171   };
 172 
 173   friend class ClassLoaderDataGraph;
 174   friend class ClassLoaderDataGraphKlassIteratorAtomic;
 175   friend class ClassLoaderDataGraphMetaspaceIterator;
 176   friend class MetaDataFactory;
 177   friend class Method;
 178 
 179   static ClassLoaderData * _the_null_class_loader_data;
 180 
 181   oop _class_loader;          // oop used to uniquely identify a class loader
 182                               // class loader or a canonical class path
 183   Dependencies _dependencies; // holds dependencies from this class loader
 184                               // data to others.
 185 
 186   Metaspace * _metaspace;  // Meta-space where meta-data defined by the
 187                            // classes in the class loader are allocated.
 188   Mutex* _metaspace_lock;  // Locks the metaspace for allocations and setup.
 189   bool _unloading;         // true if this class loader goes away
 190   bool _keep_alive;        // if this CLD is kept alive without a keep_alive_object().
 191   bool _is_anonymous;      // if this CLD is for an anonymous class
 192   volatile int _claimed;   // true if claimed, for example during GC traces.
 193                            // To avoid applying oop closure more than once.
 194                            // Has to be an int because we cas it.
 195   Klass* _klasses;         // The classes defined by the class loader.
 196 
 197   ChunkedHandleList _handles; // Handles to constant pool arrays, etc, which
 198                               // have the same life cycle of the corresponding ClassLoader.
 199 
 200   // These method IDs are created for the class loader and set to NULL when the
 201   // class loader is unloaded.  They are rarely freed, only for redefine classes
 202   // and if they lose a data race in InstanceKlass.
 203   JNIMethodBlock*                  _jmethod_ids;
 204 
 205   // Metadata to be deallocated when it's safe at class unloading, when
 206   // this class loader isn't unloaded itself.
 207   GrowableArray<Metadata*>*      _deallocate_list;
 208 
 209   // Support for walking class loader data objects
 210   ClassLoaderData* _next; /// Next loader_datas created
 211 
 212   // ReadOnly and ReadWrite metaspaces (static because only on the null
 213   // class loader for now).
 214   static Metaspace* _ro_metaspace;
 215   static Metaspace* _rw_metaspace;
 216 
 217   void set_next(ClassLoaderData* next) { _next = next; }
 218   ClassLoaderData* next() const        { return _next; }
 219 
 220   ClassLoaderData(Handle h_class_loader, bool is_anonymous, Dependencies dependencies);
 221   ~ClassLoaderData();
 222 
 223   void set_metaspace(Metaspace* m) { _metaspace = m; }
 224 
 225   Mutex* metaspace_lock() const { return _metaspace_lock; }
 226 
 227   // GC interface.
 228   void clear_claimed()          { _claimed = 0; }
 229   bool claimed() const          { return _claimed == 1; }
 230   bool claim();
 231 
 232   void unload();
 233   bool keep_alive() const       { return _keep_alive; }
 234   void classes_do(void f(Klass*));
 235   void loaded_classes_do(KlassClosure* klass_closure);
 236   void classes_do(void f(InstanceKlass*));
 237 
 238   // Deallocate free list during class unloading.
 239   void free_deallocate_list();
 240 
 241   // Allocate out of this class loader data
 242   MetaWord* allocate(size_t size);
 243 
 244  public:
 245 
 246   bool is_alive(BoolObjectClosure* is_alive_closure) const;
 247 
 248   // Accessors
 249   Metaspace* metaspace_or_null() const     { return _metaspace; }
 250 
 251   static ClassLoaderData* the_null_class_loader_data() {
 252     return _the_null_class_loader_data;
 253   }
 254 
 255   bool is_anonymous() const { return _is_anonymous; }
 256 
 257   static void init_null_class_loader_data() {
 258     assert(_the_null_class_loader_data == NULL, "cannot initialize twice");
 259     assert(ClassLoaderDataGraph::_head == NULL, "cannot initialize twice");
 260 
 261     // We explicitly initialize the Dependencies object at a later phase in the initialization
 262     _the_null_class_loader_data = new ClassLoaderData((oop)NULL, false, Dependencies());
 263     ClassLoaderDataGraph::_head = _the_null_class_loader_data;
 264     assert(_the_null_class_loader_data->is_the_null_class_loader_data(), "Must be");
 265     if (DumpSharedSpaces) {
 266       _the_null_class_loader_data->initialize_shared_metaspaces();
 267     }
 268   }
 269 
 270   bool is_the_null_class_loader_data() const {
 271     return this == _the_null_class_loader_data;
 272   }
 273   bool is_ext_class_loader_data() const;
 274 
 275   // The Metaspace is created lazily so may be NULL.  This
 276   // method will allocate a Metaspace if needed.
 277   Metaspace* metaspace_non_null();
 278 
 279   oop class_loader() const      { return _class_loader; }
 280 
 281   // The object the GC is using to keep this ClassLoaderData alive.
 282   oop keep_alive_object() const;
 283 
 284   // Returns true if this class loader data is for a loader going away.
 285   bool is_unloading() const     {
 286     assert(!(is_the_null_class_loader_data() && _unloading), "The null class loader can never be unloaded");
 287     return _unloading;
 288   }
 289 
 290   // Used to make sure that this CLD is not unloaded.
 291   void set_keep_alive(bool value) { _keep_alive = value; }
 292 
 293   unsigned int identity_hash() {
 294     return _class_loader == NULL ? 0 : _class_loader->identity_hash();
 295   }
 296 
 297   // Used when tracing from klasses.
 298   void oops_do(OopClosure* f, KlassClosure* klass_closure, bool must_claim);
 299 
 300   void classes_do(KlassClosure* klass_closure);
 301 
 302   JNIMethodBlock* jmethod_ids() const              { return _jmethod_ids; }
 303   void set_jmethod_ids(JNIMethodBlock* new_block)  { _jmethod_ids = new_block; }
 304 
 305   void print_value() { print_value_on(tty); }
 306   void print_value_on(outputStream* out) const;
 307   void dump(outputStream * const out) PRODUCT_RETURN;
 308   void verify();
 309   const char* loader_name();
 310 
 311   jobject add_handle(Handle h);
 312   void add_class(Klass* k);
 313   void remove_class(Klass* k);
 314   bool contains_klass(Klass* k);
 315   void record_dependency(Klass* to, TRAPS);
 316   void init_dependencies(TRAPS);
 317 
 318   void add_to_deallocate_list(Metadata* m);
 319 
 320   static ClassLoaderData* class_loader_data(oop loader);
 321   static ClassLoaderData* class_loader_data_or_null(oop loader);
 322   static ClassLoaderData* anonymous_class_loader_data(oop loader, TRAPS);
 323   static void print_loader(ClassLoaderData *loader_data, outputStream *out);
 324 
 325   // CDS support
 326   Metaspace* ro_metaspace();
 327   Metaspace* rw_metaspace();
 328   void initialize_shared_metaspaces();
 329 };
 330 
 331 // An iterator that distributes Klasses to parallel worker threads.
 332 class ClassLoaderDataGraphKlassIteratorAtomic : public StackObj {
 333  Klass* volatile _next_klass;
 334  public:
 335   ClassLoaderDataGraphKlassIteratorAtomic();
 336   Klass* next_klass();
 337  private:
 338   static Klass* next_klass_in_cldg(Klass* klass);
 339 };
 340 
 341 class ClassLoaderDataGraphMetaspaceIterator : public StackObj {
 342   ClassLoaderData* _data;
 343  public:
 344   ClassLoaderDataGraphMetaspaceIterator();
 345   ~ClassLoaderDataGraphMetaspaceIterator();
 346   bool repeat() { return _data != NULL; }
 347   Metaspace* get_next() {
 348     assert(_data != NULL, "Should not be NULL in call to the iterator");
 349     Metaspace* result = _data->metaspace_or_null();
 350     _data = _data->next();
 351     // This result might be NULL for class loaders without metaspace
 352     // yet.  It would be nice to return only non-null results but
 353     // there is no guarantee that there will be a non-null result
 354     // down the list so the caller is going to have to check.
 355     return result;
 356   }
 357 };
 358 #endif // SHARE_VM_CLASSFILE_CLASSLOADERDATA_HPP