1 /*
  2  * Copyright (c) 2003, 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 #include "precompiled.hpp"
 26 #include "classfile/systemDictionary.hpp"
 27 #include "gc/shared/collectedHeap.hpp"
 28 #include "memory/universe.inline.hpp"
 29 #include "prims/jvmtiGetLoadedClasses.hpp"
 30 #include "runtime/thread.hpp"
 31 #include "utilities/stack.inline.hpp"
 32 #if INCLUDE_ALL_GCS
 33 #include "gc/g1/g1BarrierSet.hpp"
 34 #endif
 35 
 36 
 37 // The closure for GetLoadedClasses
 38 class LoadedClassesClosure : public KlassClosure {
 39 private:
 40   Stack<jclass, mtInternal> _classStack;
 41   JvmtiEnv* _env;
 42   Thread*   _cur_thread;
 43 
 44 // Tell the GC to keep this klass alive
 45 static void ensure_klass_alive(oop o) {
 46   // A klass that was previously considered dead can be looked up in the
 47   // CLD/SD, and its _java_mirror or _class_loader can be stored in a root
 48   // or a reachable object making it alive again. The SATB part of G1 needs
 49   // to get notified about this potential resurrection, otherwise the marking
 50   // might not find the object.
 51 #if INCLUDE_ALL_GCS
 52   if (UseG1GC && o != NULL) {
 53     G1BarrierSet::enqueue(o);
 54   }
 55 #endif
 56 }
 57 
 58 public:
 59   LoadedClassesClosure(Thread* thread, JvmtiEnv* env) : _cur_thread(thread), _env(env) {
 60     assert(_cur_thread == Thread::current(), "must be current thread");
 61   }
 62 
 63   void do_klass(Klass* k) {
 64     // Collect all jclasses
 65     _classStack.push((jclass) _env->jni_reference(Handle(_cur_thread, k->java_mirror())));
 66     ensure_klass_alive(k->java_mirror());
 67   }
 68 
 69   int extract(jclass* result_list) {
 70     // The size of the Stack will be 0 after extract, so get it here
 71     int count = (int)_classStack.size();
 72     int i = count;
 73 
 74     // Pop all jclasses, fill backwards
 75     while (!_classStack.is_empty()) {
 76       result_list[--i] = _classStack.pop();
 77     }
 78 
 79     // Return the number of elements written
 80     return count;
 81   }
 82 
 83   // Return current size of the Stack
 84   int get_count() {
 85     return (int)_classStack.size();
 86   }
 87 };
 88 
 89 // The closure for GetClassLoaderClasses
 90 class JvmtiGetLoadedClassesClosure : public StackObj {
 91   // Since the ClassLoaderDataGraph::dictionary_all_entries_do callback
 92   // doesn't pass a closureData pointer,
 93   // we use a thread-local slot to hold a pointer to
 94   // a stack allocated instance of this structure.
 95  private:
 96   jobject _initiatingLoader;
 97   int     _count;
 98   Handle* _list;
 99   int     _index;
100 
101  private:
102   // Getting and setting the thread local pointer
103   static JvmtiGetLoadedClassesClosure* get_this() {
104     JvmtiGetLoadedClassesClosure* result = NULL;
105     JavaThread* thread = JavaThread::current();
106     result = thread->get_jvmti_get_loaded_classes_closure();
107     return result;
108   }
109   static void set_this(JvmtiGetLoadedClassesClosure* that) {
110     JavaThread* thread = JavaThread::current();
111     thread->set_jvmti_get_loaded_classes_closure(that);
112   }
113 
114  public:
115   // Constructor/Destructor
116   JvmtiGetLoadedClassesClosure() {
117     JvmtiGetLoadedClassesClosure* that = get_this();
118     assert(that == NULL, "JvmtiGetLoadedClassesClosure in use");
119     _initiatingLoader = NULL;
120     _count = 0;
121     _list = NULL;
122     _index = 0;
123     set_this(this);
124   }
125 
126   JvmtiGetLoadedClassesClosure(jobject initiatingLoader) {
127     JvmtiGetLoadedClassesClosure* that = get_this();
128     assert(that == NULL, "JvmtiGetLoadedClassesClosure in use");
129     _initiatingLoader = initiatingLoader;
130     _count = 0;
131     _list = NULL;
132     _index = 0;
133     set_this(this);
134   }
135 
136   ~JvmtiGetLoadedClassesClosure() {
137     JvmtiGetLoadedClassesClosure* that = get_this();
138     assert(that != NULL, "JvmtiGetLoadedClassesClosure not found");
139     set_this(NULL);
140     _initiatingLoader = NULL;
141     _count = 0;
142     if (_list != NULL) {
143       FreeHeap(_list);
144       _list = NULL;
145     }
146     _index = 0;
147   }
148 
149   // Accessors.
150   jobject get_initiatingLoader() {
151     return _initiatingLoader;
152   }
153 
154   int get_count() {
155     return _count;
156   }
157 
158   void set_count(int value) {
159     _count = value;
160   }
161 
162   Handle* get_list() {
163     return _list;
164   }
165 
166   void set_list(Handle* value) {
167     _list = value;
168   }
169 
170   int get_index() {
171     return _index;
172   }
173 
174   void set_index(int value) {
175     _index = value;
176   }
177 
178   Handle get_element(int index) {
179     if ((_list != NULL) && (index < _count)) {
180       return _list[index];
181     } else {
182       assert(false, "empty get_element");
183       return Handle();
184     }
185   }
186 
187   void set_element(int index, Handle value) {
188     if ((_list != NULL) && (index < _count)) {
189       _list[index] = value;
190     } else {
191       assert(false, "bad set_element");
192     }
193   }
194 
195   // Other predicates
196   bool available() {
197     return (_list != NULL);
198   }
199 
200 #ifdef ASSERT
201   // For debugging.
202   void check(int limit) {
203     for (int i = 0; i < limit; i += 1) {
204       assert(Universe::heap()->is_in(get_element(i)()), "check fails");
205     }
206   }
207 #endif
208 
209   // Public methods that get called within the scope of the closure
210   void allocate() {
211     _list = NEW_C_HEAP_ARRAY(Handle, _count, mtInternal);
212     assert(_list != NULL, "Out of memory");
213     if (_list == NULL) {
214       _count = 0;
215     }
216   }
217 
218   void extract(JvmtiEnv *env, jclass* result) {
219     for (int index = 0; index < _count; index += 1) {
220       result[index] = (jclass) env->jni_reference(get_element(index));
221     }
222   }
223 
224   static void increment_with_loader(InstanceKlass* k, ClassLoaderData* loader_data) {
225     JvmtiGetLoadedClassesClosure* that = JvmtiGetLoadedClassesClosure::get_this();
226     oop class_loader = loader_data->class_loader();
227     if (class_loader == JNIHandles::resolve(that->get_initiatingLoader())) {
228       for (Klass* l = k; l != NULL; l = l->array_klass_or_null()) {
229         that->set_count(that->get_count() + 1);
230       }
231     }
232   }
233 
234   static void add_with_loader(InstanceKlass* k, ClassLoaderData* loader_data) {
235     JvmtiGetLoadedClassesClosure* that = JvmtiGetLoadedClassesClosure::get_this();
236     if (that->available()) {
237       oop class_loader = loader_data->class_loader();
238       if (class_loader == JNIHandles::resolve(that->get_initiatingLoader())) {
239         Thread *thread = Thread::current();
240         for (Klass* l = k; l != NULL; l = l->array_klass_or_null()) {
241           Handle mirror(thread, l->java_mirror());
242           that->set_element(that->get_index(), mirror);
243           that->set_index(that->get_index() + 1);
244         }
245       }
246     }
247   }
248 
249   // increment the count for the given basic type array class (and any
250   // multi-dimensional arrays). For example, for [B we check for
251   // [[B, [[[B, .. and the count is incremented for each one that exists.
252   static void increment_for_basic_type_arrays(Klass* k) {
253     JvmtiGetLoadedClassesClosure* that = JvmtiGetLoadedClassesClosure::get_this();
254     assert(that != NULL, "no JvmtiGetLoadedClassesClosure");
255     for (Klass* l = k; l != NULL; l = l->array_klass_or_null()) {
256       that->set_count(that->get_count() + 1);
257     }
258   }
259 
260   // add the basic type array class and its multi-dimensional array classes to the list
261   static void add_for_basic_type_arrays(Klass* k) {
262     JvmtiGetLoadedClassesClosure* that = JvmtiGetLoadedClassesClosure::get_this();
263     assert(that != NULL, "no JvmtiGetLoadedClassesClosure");
264     assert(that->available(), "no list");
265     Thread *thread = Thread::current();
266     for (Klass* l = k; l != NULL; l = l->array_klass_or_null()) {
267       Handle mirror(thread, l->java_mirror());
268       that->set_element(that->get_index(), mirror);
269       that->set_index(that->get_index() + 1);
270     }
271   }
272 };
273 
274 
275 jvmtiError
276 JvmtiGetLoadedClasses::getLoadedClasses(JvmtiEnv *env, jint* classCountPtr, jclass** classesPtr) {
277 
278   LoadedClassesClosure closure(Thread::current(), env);
279   {
280     // To get a consistent list of classes we need MultiArray_lock to ensure
281     // array classes aren't created.
282     MutexLocker ma(MultiArray_lock);
283 
284     // Iterate through all classes in ClassLoaderDataGraph
285     // and collect them using the LoadedClassesClosure
286     ClassLoaderDataGraph::loaded_classes_do(&closure);
287   }
288 
289   // Return results by extracting the collected contents into a list
290   // allocated via JvmtiEnv
291   jclass* result_list;
292   jvmtiError error = env->Allocate(closure.get_count() * sizeof(jclass),
293                                (unsigned char**)&result_list);
294 
295   if (error == JVMTI_ERROR_NONE) {
296     int count = closure.extract(result_list);
297     *classCountPtr = count;
298     *classesPtr = result_list;
299   }
300   return error;
301 }
302 
303 jvmtiError
304 JvmtiGetLoadedClasses::getClassLoaderClasses(JvmtiEnv *env, jobject initiatingLoader,
305                                              jint* classCountPtr, jclass** classesPtr) {
306   // Since ClassLoaderDataGraph::dictionary_all_entries_do only takes a function pointer
307   // and doesn't call back with a closure data pointer,
308   // we can only pass static methods.
309   JvmtiGetLoadedClassesClosure closure(initiatingLoader);
310   {
311     // To get a consistent list of classes we need MultiArray_lock to ensure
312     // array classes aren't created, and SystemDictionary_lock to ensure that
313     // classes aren't added to the class loader data dictionaries.
314     MutexLocker ma(MultiArray_lock);
315     MutexLocker sd(SystemDictionary_lock);
316     // First, count the classes in the class loader data dictionaries which have this loader recorded
317     // as an initiating loader. For basic type arrays this information is not recorded
318     // so GetClassLoaderClasses will return all of the basic type arrays. This is okay
319     // because the defining loader for basic type arrays is always the boot class loader
320     // and these classes are "visible" to all loaders.
321     ClassLoaderDataGraph::dictionary_all_entries_do(&JvmtiGetLoadedClassesClosure::increment_with_loader);
322     Universe::basic_type_classes_do(&JvmtiGetLoadedClassesClosure::increment_for_basic_type_arrays);
323     // Next, fill in the classes
324     closure.allocate();
325     ClassLoaderDataGraph::dictionary_all_entries_do(&JvmtiGetLoadedClassesClosure::add_with_loader);
326     Universe::basic_type_classes_do(&JvmtiGetLoadedClassesClosure::add_for_basic_type_arrays);
327     // Drop the SystemDictionary_lock, so the results could be wrong from here,
328     // but we still have a snapshot.
329   }
330   // Post results
331   jclass* result_list;
332   jvmtiError err = env->Allocate(closure.get_count() * sizeof(jclass),
333                                  (unsigned char**)&result_list);
334   if (err != JVMTI_ERROR_NONE) {
335     return err;
336   }
337   closure.extract(env, result_list);
338   *classCountPtr = closure.get_count();
339   *classesPtr = result_list;
340   return JVMTI_ERROR_NONE;
341 }