1 /*
2 * Copyright (c) 2003, 2025, 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 "classfile/classLoaderDataGraph.hpp"
26 #include "classfile/javaClasses.inline.hpp"
27 #include "classfile/symbolTable.hpp"
28 #include "classfile/vmClasses.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "gc/shared/collectedHeap.hpp"
31 #include "jvmtifiles/jvmtiEnv.hpp"
32 #include "logging/log.hpp"
33 #include "memory/allocation.inline.hpp"
34 #include "memory/resourceArea.hpp"
35 #include "memory/universe.hpp"
36 #include "oops/access.inline.hpp"
37 #include "oops/arrayOop.hpp"
38 #include "oops/constantPool.inline.hpp"
39 #include "oops/fieldStreams.inline.hpp"
40 #include "oops/instanceMirrorKlass.hpp"
41 #include "oops/klass.inline.hpp"
42 #include "oops/objArrayKlass.hpp"
43 #include "oops/objArrayOop.inline.hpp"
44 #include "oops/oop.inline.hpp"
45 #include "oops/typeArrayOop.inline.hpp"
46 #include "prims/jvmtiEventController.inline.hpp"
47 #include "prims/jvmtiExport.hpp"
48 #include "prims/jvmtiImpl.hpp"
49 #include "prims/jvmtiTagMap.hpp"
50 #include "prims/jvmtiTagMapTable.hpp"
51 #include "prims/jvmtiThreadState.hpp"
52 #include "runtime/continuationWrapper.inline.hpp"
53 #include "runtime/deoptimization.hpp"
54 #include "runtime/frame.inline.hpp"
55 #include "runtime/handles.inline.hpp"
56 #include "runtime/interfaceSupport.inline.hpp"
57 #include "runtime/javaCalls.hpp"
58 #include "runtime/javaThread.inline.hpp"
59 #include "runtime/jniHandles.inline.hpp"
60 #include "runtime/mutex.hpp"
61 #include "runtime/mutexLocker.hpp"
62 #include "runtime/safepoint.hpp"
63 #include "runtime/threadSMR.hpp"
64 #include "runtime/timerTrace.hpp"
65 #include "runtime/vframe.hpp"
66 #include "runtime/vmOperations.hpp"
67 #include "runtime/vmThread.hpp"
68 #include "utilities/macros.hpp"
69 #include "utilities/objectBitSet.inline.hpp"
70
71 typedef ObjectBitSet<mtServiceability> JVMTIBitSet;
72
73 bool JvmtiTagMap::_has_object_free_events = false;
74
75 // create a JvmtiTagMap
76 JvmtiTagMap::JvmtiTagMap(JvmtiEnv* env) :
77 _env(env),
78 _lock(Mutex::nosafepoint, "JvmtiTagMap_lock"),
79 _needs_cleaning(false),
80 _posting_events(false) {
81
82 assert(JvmtiThreadState_lock->is_locked(), "sanity check");
83 assert(((JvmtiEnvBase *)env)->tag_map() == nullptr, "tag map already exists for environment");
84
85 _hashmap = new JvmtiTagMapTable();
86
87 // finally add us to the environment
88 ((JvmtiEnvBase *)env)->release_set_tag_map(this);
89 }
90
91 // destroy a JvmtiTagMap
92 JvmtiTagMap::~JvmtiTagMap() {
93
94 // no lock acquired as we assume the enclosing environment is
95 // also being destroyed.
96 ((JvmtiEnvBase *)_env)->set_tag_map(nullptr);
97
98 // finally destroy the hashmap
99 delete _hashmap;
100 _hashmap = nullptr;
101 }
102
103 // Called by env_dispose() to reclaim memory before deallocation.
104 // Remove all the entries but keep the empty table intact.
105 // This needs the table lock.
106 void JvmtiTagMap::clear() {
107 MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
108 _hashmap->clear();
109 }
110
111 // returns the tag map for the given environments. If the tag map
112 // doesn't exist then it is created.
113 JvmtiTagMap* JvmtiTagMap::tag_map_for(JvmtiEnv* env) {
114 JvmtiTagMap* tag_map = ((JvmtiEnvBase*)env)->tag_map_acquire();
115 if (tag_map == nullptr) {
116 MutexLocker mu(JvmtiThreadState_lock);
117 tag_map = ((JvmtiEnvBase*)env)->tag_map();
118 if (tag_map == nullptr) {
119 tag_map = new JvmtiTagMap(env);
120 }
121 } else {
122 DEBUG_ONLY(JavaThread::current()->check_possible_safepoint());
123 }
124 return tag_map;
125 }
126
127 // iterate over all entries in the tag map.
128 void JvmtiTagMap::entry_iterate(JvmtiTagMapKeyClosure* closure) {
129 hashmap()->entry_iterate(closure);
130 }
131
132 // returns true if the hashmaps are empty
133 bool JvmtiTagMap::is_empty() {
134 assert(SafepointSynchronize::is_at_safepoint() || is_locked(), "checking");
135 return hashmap()->is_empty();
136 }
137
138 // This checks for posting before operations that use
139 // this tagmap table.
140 void JvmtiTagMap::check_hashmap(GrowableArray<jlong>* objects) {
141 assert(is_locked(), "checking");
142
143 if (is_empty()) { return; }
144
145 if (_needs_cleaning &&
146 objects != nullptr &&
147 env()->is_enabled(JVMTI_EVENT_OBJECT_FREE)) {
148 remove_dead_entries_locked(objects);
149 }
150 }
151
152 // This checks for posting and is called from the heap walks.
153 void JvmtiTagMap::check_hashmaps_for_heapwalk(GrowableArray<jlong>* objects) {
154 assert(SafepointSynchronize::is_at_safepoint(), "called from safepoints");
155
156 // Verify that the tag map tables are valid and unconditionally post events
157 // that are expected to be posted before gc_notification.
158 JvmtiEnvIterator it;
159 for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
160 JvmtiTagMap* tag_map = env->tag_map_acquire();
161 if (tag_map != nullptr) {
162 // The ZDriver may be walking the hashmaps concurrently so this lock is needed.
163 MutexLocker ml(tag_map->lock(), Mutex::_no_safepoint_check_flag);
164 tag_map->check_hashmap(objects);
165 }
166 }
167 }
168
169 // Return the tag value for an object, or 0 if the object is
170 // not tagged
171 //
172 static inline jlong tag_for(JvmtiTagMap* tag_map, oop o) {
173 return tag_map->hashmap()->find(o);
174 }
175
176 // A CallbackWrapper is a support class for querying and tagging an object
177 // around a callback to a profiler. The constructor does pre-callback
178 // work to get the tag value, klass tag value, ... and the destructor
179 // does the post-callback work of tagging or untagging the object.
180 //
181 // {
182 // CallbackWrapper wrapper(tag_map, o);
183 //
184 // (*callback)(wrapper.klass_tag(), wrapper.obj_size(), wrapper.obj_tag_p(), ...)
185 //
186 // }
187 // wrapper goes out of scope here which results in the destructor
188 // checking to see if the object has been tagged, untagged, or the
189 // tag value has changed.
190 //
191 class CallbackWrapper : public StackObj {
192 private:
193 JvmtiTagMap* _tag_map;
194 JvmtiTagMapTable* _hashmap;
195 oop _o;
196 jlong _obj_size;
197 jlong _obj_tag;
198 jlong _klass_tag;
199
200 protected:
201 JvmtiTagMap* tag_map() const { return _tag_map; }
202
203 // invoked post-callback to tag, untag, or update the tag of an object
204 void inline post_callback_tag_update(oop o, JvmtiTagMapTable* hashmap,
205 jlong obj_tag);
206 public:
207 CallbackWrapper(JvmtiTagMap* tag_map, oop o) {
208 assert(Thread::current()->is_VM_thread() || tag_map->is_locked(),
209 "MT unsafe or must be VM thread");
210
211 // object to tag
212 _o = o;
213
214 // object size
215 _obj_size = (jlong)_o->size() * wordSize;
216
217 // record the context
218 _tag_map = tag_map;
219 _hashmap = tag_map->hashmap();
220
221 // get object tag
222 _obj_tag = _hashmap->find(_o);
223
224 // get the class and the class's tag value
225 assert(vmClasses::Class_klass()->is_mirror_instance_klass(), "Is not?");
226
227 _klass_tag = tag_for(tag_map, _o->klass()->java_mirror());
228 }
229
230 ~CallbackWrapper() {
231 post_callback_tag_update(_o, _hashmap, _obj_tag);
232 }
233
234 inline jlong* obj_tag_p() { return &_obj_tag; }
235 inline jlong obj_size() const { return _obj_size; }
236 inline jlong obj_tag() const { return _obj_tag; }
237 inline jlong klass_tag() const { return _klass_tag; }
238 };
239
240 // callback post-callback to tag, untag, or update the tag of an object
241 void inline CallbackWrapper::post_callback_tag_update(oop o,
242 JvmtiTagMapTable* hashmap,
243 jlong obj_tag) {
244 if (obj_tag == 0) {
245 // callback has untagged the object, remove the entry if present
246 hashmap->remove(o);
247 } else {
248 // object was previously tagged or not present - the callback may have
249 // changed the tag value
250 assert(Thread::current()->is_VM_thread(), "must be VMThread");
251 hashmap->add(o, obj_tag);
252 }
253 }
254
255 // An extended CallbackWrapper used when reporting an object reference
256 // to the agent.
257 //
258 // {
259 // TwoOopCallbackWrapper wrapper(tag_map, referrer, o);
260 //
261 // (*callback)(wrapper.klass_tag(),
262 // wrapper.obj_size(),
263 // wrapper.obj_tag_p()
264 // wrapper.referrer_tag_p(), ...)
265 //
266 // }
267 // wrapper goes out of scope here which results in the destructor
268 // checking to see if the referrer object has been tagged, untagged,
269 // or the tag value has changed.
270 //
271 class TwoOopCallbackWrapper : public CallbackWrapper {
272 private:
273 bool _is_reference_to_self;
274 JvmtiTagMapTable* _referrer_hashmap;
275 oop _referrer;
276 jlong _referrer_obj_tag;
277 jlong _referrer_klass_tag;
278 jlong* _referrer_tag_p;
279
280 bool is_reference_to_self() const { return _is_reference_to_self; }
281
282 public:
283 TwoOopCallbackWrapper(JvmtiTagMap* tag_map, oop referrer, oop o) :
284 CallbackWrapper(tag_map, o)
285 {
286 // self reference needs to be handled in a special way
287 _is_reference_to_self = (referrer == o);
288
289 if (_is_reference_to_self) {
290 _referrer_klass_tag = klass_tag();
291 _referrer_tag_p = obj_tag_p();
292 } else {
293 _referrer = referrer;
294 // record the context
295 _referrer_hashmap = tag_map->hashmap();
296
297 // get object tag
298 _referrer_obj_tag = _referrer_hashmap->find(_referrer);
299
300 _referrer_tag_p = &_referrer_obj_tag;
301
302 // get referrer class tag.
303 _referrer_klass_tag = tag_for(tag_map, _referrer->klass()->java_mirror());
304 }
305 }
306
307 ~TwoOopCallbackWrapper() {
308 if (!is_reference_to_self()) {
309 post_callback_tag_update(_referrer,
310 _referrer_hashmap,
311 _referrer_obj_tag);
312 }
313 }
314
315 // address of referrer tag
316 // (for a self reference this will return the same thing as obj_tag_p())
317 inline jlong* referrer_tag_p() { return _referrer_tag_p; }
318
319 // referrer's class tag
320 inline jlong referrer_klass_tag() { return _referrer_klass_tag; }
321 };
322
323 // tag an object
324 //
325 // This function is performance critical. If many threads attempt to tag objects
326 // around the same time then it's possible that the Mutex associated with the
327 // tag map will be a hot lock.
328 void JvmtiTagMap::set_tag(jobject object, jlong tag) {
329 MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
330
331 // SetTag should not post events because the JavaThread has to
332 // transition to native for the callback and this cannot stop for
333 // safepoints with the hashmap lock held.
334 check_hashmap(nullptr); /* don't collect dead objects */
335
336 // resolve the object
337 oop o = JNIHandles::resolve_non_null(object);
338
339 // see if the object is already tagged
340 JvmtiTagMapTable* hashmap = _hashmap;
341
342 if (tag == 0) {
343 // remove the entry if present
344 hashmap->remove(o);
345 } else {
346 // if the object is already tagged or not present then we add/update
347 // the tag
348 hashmap->add(o, tag);
349 }
350 }
351
352 // get the tag for an object
353 jlong JvmtiTagMap::get_tag(jobject object) {
354 MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
355
356 // GetTag should not post events because the JavaThread has to
357 // transition to native for the callback and this cannot stop for
358 // safepoints with the hashmap lock held.
359 check_hashmap(nullptr); /* don't collect dead objects */
360
361 // resolve the object
362 oop o = JNIHandles::resolve_non_null(object);
363
364 return tag_for(this, o);
365 }
366
367
368 // Helper class used to describe the static or instance fields of a class.
369 // For each field it holds the field index (as defined by the JVMTI specification),
370 // the field type, and the offset.
371
372 class ClassFieldDescriptor: public CHeapObj<mtInternal> {
373 private:
374 int _field_index;
375 int _field_offset;
376 char _field_type;
377 public:
378 ClassFieldDescriptor(int index, char type, int offset) :
379 _field_index(index), _field_offset(offset), _field_type(type) {
380 }
381 int field_index() const { return _field_index; }
382 char field_type() const { return _field_type; }
383 int field_offset() const { return _field_offset; }
384 };
385
386 class ClassFieldMap: public CHeapObj<mtInternal> {
387 private:
388 enum {
389 initial_field_count = 5
390 };
391
392 // list of field descriptors
393 GrowableArray<ClassFieldDescriptor*>* _fields;
394
395 // constructor
396 ClassFieldMap();
397
398 // calculates number of fields in all interfaces
399 static int interfaces_field_count(InstanceKlass* ik);
400
401 // add a field
402 void add(int index, char type, int offset);
403
404 public:
405 ~ClassFieldMap();
406
407 // access
408 int field_count() { return _fields->length(); }
409 ClassFieldDescriptor* field_at(int i) { return _fields->at(i); }
410
411 // functions to create maps of static or instance fields
412 static ClassFieldMap* create_map_of_static_fields(Klass* k);
413 static ClassFieldMap* create_map_of_instance_fields(oop obj);
414 };
415
416 ClassFieldMap::ClassFieldMap() {
417 _fields = new (mtServiceability)
418 GrowableArray<ClassFieldDescriptor*>(initial_field_count, mtServiceability);
419 }
420
421 ClassFieldMap::~ClassFieldMap() {
422 for (int i=0; i<_fields->length(); i++) {
423 delete _fields->at(i);
424 }
425 delete _fields;
426 }
427
428 int ClassFieldMap::interfaces_field_count(InstanceKlass* ik) {
429 const Array<InstanceKlass*>* interfaces = ik->transitive_interfaces();
430 int count = 0;
431 for (int i = 0; i < interfaces->length(); i++) {
432 count += interfaces->at(i)->java_fields_count();
433
434 }
435 return count;
436 }
437
438 void ClassFieldMap::add(int index, char type, int offset) {
439 ClassFieldDescriptor* field = new ClassFieldDescriptor(index, type, offset);
440 _fields->append(field);
441 }
442
443 // Returns a heap allocated ClassFieldMap to describe the static fields
444 // of the given class.
445 ClassFieldMap* ClassFieldMap::create_map_of_static_fields(Klass* k) {
446 InstanceKlass* ik = InstanceKlass::cast(k);
447
448 // create the field map
449 ClassFieldMap* field_map = new ClassFieldMap();
450
451 // Static fields of interfaces and superclasses are reported as references from the interfaces/superclasses.
452 // Need to calculate start index of this class fields: number of fields in all interfaces and superclasses.
453 int index = interfaces_field_count(ik);
454 for (InstanceKlass* super_klass = ik->super(); super_klass != nullptr; super_klass = super_klass->super()) {
455 index += super_klass->java_fields_count();
456 }
457
458 for (JavaFieldStream fld(ik); !fld.done(); fld.next(), index++) {
459 // ignore instance fields
460 if (!fld.access_flags().is_static()) {
461 continue;
462 }
463 field_map->add(index, fld.signature()->char_at(0), fld.offset());
464 }
465
466 return field_map;
467 }
468
469 // Returns a heap allocated ClassFieldMap to describe the instance fields
470 // of the given class. All instance fields are included (this means public
471 // and private fields declared in superclasses too).
472 ClassFieldMap* ClassFieldMap::create_map_of_instance_fields(oop obj) {
473 InstanceKlass* ik = InstanceKlass::cast(obj->klass());
474
475 // create the field map
476 ClassFieldMap* field_map = new ClassFieldMap();
477
478 // fields of the superclasses are reported first, so need to know total field number to calculate field indices
479 int total_field_number = interfaces_field_count(ik);
480 for (InstanceKlass* klass = ik; klass != nullptr; klass = klass->super()) {
481 total_field_number += klass->java_fields_count();
482 }
483
484 for (InstanceKlass* klass = ik; klass != nullptr; klass = klass->super()) {
485 JavaFieldStream fld(klass);
486 int start_index = total_field_number - klass->java_fields_count();
487 for (int index = 0; !fld.done(); fld.next(), index++) {
488 // ignore static fields
489 if (fld.access_flags().is_static()) {
490 continue;
491 }
492 field_map->add(start_index + index, fld.signature()->char_at(0), fld.offset());
493 }
494 // update total_field_number for superclass (decrease by the field count in the current class)
495 total_field_number = start_index;
496 }
497
498 return field_map;
499 }
500
501 // Helper class used to cache a ClassFileMap for the instance fields of
502 // a cache. A JvmtiCachedClassFieldMap can be cached by an InstanceKlass during
503 // heap iteration and avoid creating a field map for each object in the heap
504 // (only need to create the map when the first instance of a class is encountered).
505 //
506 class JvmtiCachedClassFieldMap : public CHeapObj<mtInternal> {
507 private:
508 enum {
509 initial_class_count = 200
510 };
511 ClassFieldMap* _field_map;
512
513 ClassFieldMap* field_map() const { return _field_map; }
514
515 JvmtiCachedClassFieldMap(ClassFieldMap* field_map);
516 ~JvmtiCachedClassFieldMap();
517
518 static GrowableArray<InstanceKlass*>* _class_list;
519 static void add_to_class_list(InstanceKlass* ik);
520
521 public:
522 // returns the field map for a given object (returning map cached
523 // by InstanceKlass if possible
524 static ClassFieldMap* get_map_of_instance_fields(oop obj);
525
526 // removes the field map from all instanceKlasses - should be
527 // called before VM operation completes
528 static void clear_cache();
529
530 // returns the number of ClassFieldMap cached by instanceKlasses
531 static int cached_field_map_count();
532 };
533
534 GrowableArray<InstanceKlass*>* JvmtiCachedClassFieldMap::_class_list;
535
536 JvmtiCachedClassFieldMap::JvmtiCachedClassFieldMap(ClassFieldMap* field_map) {
537 _field_map = field_map;
538 }
539
540 JvmtiCachedClassFieldMap::~JvmtiCachedClassFieldMap() {
541 if (_field_map != nullptr) {
542 delete _field_map;
543 }
544 }
545
546 // Marker class to ensure that the class file map cache is only used in a defined
547 // scope.
548 class ClassFieldMapCacheMark : public StackObj {
549 private:
550 static bool _is_active;
551 public:
552 ClassFieldMapCacheMark() {
553 assert(Thread::current()->is_VM_thread(), "must be VMThread");
554 assert(JvmtiCachedClassFieldMap::cached_field_map_count() == 0, "cache not empty");
555 assert(!_is_active, "ClassFieldMapCacheMark cannot be nested");
556 _is_active = true;
557 }
558 ~ClassFieldMapCacheMark() {
559 JvmtiCachedClassFieldMap::clear_cache();
560 _is_active = false;
561 }
562 static bool is_active() { return _is_active; }
563 };
564
565 bool ClassFieldMapCacheMark::_is_active;
566
567 // record that the given InstanceKlass is caching a field map
568 void JvmtiCachedClassFieldMap::add_to_class_list(InstanceKlass* ik) {
569 if (_class_list == nullptr) {
570 _class_list = new (mtServiceability)
571 GrowableArray<InstanceKlass*>(initial_class_count, mtServiceability);
572 }
573 _class_list->push(ik);
574 }
575
576 // returns the instance field map for the given object
577 // (returns field map cached by the InstanceKlass if possible)
578 ClassFieldMap* JvmtiCachedClassFieldMap::get_map_of_instance_fields(oop obj) {
579 assert(Thread::current()->is_VM_thread(), "must be VMThread");
580 assert(ClassFieldMapCacheMark::is_active(), "ClassFieldMapCacheMark not active");
581
582 Klass* k = obj->klass();
583 InstanceKlass* ik = InstanceKlass::cast(k);
584
585 // return cached map if possible
586 JvmtiCachedClassFieldMap* cached_map = ik->jvmti_cached_class_field_map();
587 if (cached_map != nullptr) {
588 assert(cached_map->field_map() != nullptr, "missing field list");
589 return cached_map->field_map();
590 } else {
591 ClassFieldMap* field_map = ClassFieldMap::create_map_of_instance_fields(obj);
592 cached_map = new JvmtiCachedClassFieldMap(field_map);
593 ik->set_jvmti_cached_class_field_map(cached_map);
594 add_to_class_list(ik);
595 return field_map;
596 }
597 }
598
599 // remove the fields maps cached from all instanceKlasses
600 void JvmtiCachedClassFieldMap::clear_cache() {
601 assert(Thread::current()->is_VM_thread(), "must be VMThread");
602 if (_class_list != nullptr) {
603 for (int i = 0; i < _class_list->length(); i++) {
604 InstanceKlass* ik = _class_list->at(i);
605 JvmtiCachedClassFieldMap* cached_map = ik->jvmti_cached_class_field_map();
606 assert(cached_map != nullptr, "should not be null");
607 ik->set_jvmti_cached_class_field_map(nullptr);
608 delete cached_map; // deletes the encapsulated field map
609 }
610 delete _class_list;
611 _class_list = nullptr;
612 }
613 }
614
615 // returns the number of ClassFieldMap cached by instanceKlasses
616 int JvmtiCachedClassFieldMap::cached_field_map_count() {
617 return (_class_list == nullptr) ? 0 : _class_list->length();
618 }
619
620 // helper function to indicate if an object is filtered by its tag or class tag
621 static inline bool is_filtered_by_heap_filter(jlong obj_tag,
622 jlong klass_tag,
623 int heap_filter) {
624 // apply the heap filter
625 if (obj_tag != 0) {
626 // filter out tagged objects
627 if (heap_filter & JVMTI_HEAP_FILTER_TAGGED) return true;
628 } else {
629 // filter out untagged objects
630 if (heap_filter & JVMTI_HEAP_FILTER_UNTAGGED) return true;
631 }
632 if (klass_tag != 0) {
633 // filter out objects with tagged classes
634 if (heap_filter & JVMTI_HEAP_FILTER_CLASS_TAGGED) return true;
635 } else {
636 // filter out objects with untagged classes.
637 if (heap_filter & JVMTI_HEAP_FILTER_CLASS_UNTAGGED) return true;
638 }
639 return false;
640 }
641
642 // helper function to indicate if an object is filtered by a klass filter
643 static inline bool is_filtered_by_klass_filter(oop obj, Klass* klass_filter) {
644 if (klass_filter != nullptr) {
645 if (obj->klass() != klass_filter) {
646 return true;
647 }
648 }
649 return false;
650 }
651
652 // helper function to tell if a field is a primitive field or not
653 static inline bool is_primitive_field_type(char type) {
654 return (type != JVM_SIGNATURE_CLASS && type != JVM_SIGNATURE_ARRAY);
655 }
656
657 // helper function to copy the value from location addr to jvalue.
658 static inline void copy_to_jvalue(jvalue *v, address addr, jvmtiPrimitiveType value_type) {
659 switch (value_type) {
660 case JVMTI_PRIMITIVE_TYPE_BOOLEAN : { v->z = *(jboolean*)addr; break; }
661 case JVMTI_PRIMITIVE_TYPE_BYTE : { v->b = *(jbyte*)addr; break; }
662 case JVMTI_PRIMITIVE_TYPE_CHAR : { v->c = *(jchar*)addr; break; }
663 case JVMTI_PRIMITIVE_TYPE_SHORT : { v->s = *(jshort*)addr; break; }
664 case JVMTI_PRIMITIVE_TYPE_INT : { v->i = *(jint*)addr; break; }
665 case JVMTI_PRIMITIVE_TYPE_LONG : { v->j = *(jlong*)addr; break; }
666 case JVMTI_PRIMITIVE_TYPE_FLOAT : { v->f = *(jfloat*)addr; break; }
667 case JVMTI_PRIMITIVE_TYPE_DOUBLE : { v->d = *(jdouble*)addr; break; }
668 default: ShouldNotReachHere();
669 }
670 }
671
672 // helper function to invoke string primitive value callback
673 // returns visit control flags
674 static jint invoke_string_value_callback(jvmtiStringPrimitiveValueCallback cb,
675 CallbackWrapper* wrapper,
676 oop str,
677 void* user_data)
678 {
679 assert(str->klass() == vmClasses::String_klass(), "not a string");
680
681 typeArrayOop s_value = java_lang_String::value(str);
682
683 // JDK-6584008: the value field may be null if a String instance is
684 // partially constructed.
685 if (s_value == nullptr) {
686 return 0;
687 }
688 // get the string value and length
689 // (string value may be offset from the base)
690 int s_len = java_lang_String::length(str);
691 bool is_latin1 = java_lang_String::is_latin1(str);
692 jchar* value;
693 if (s_len > 0) {
694 if (!is_latin1) {
695 value = s_value->char_at_addr(0);
696 } else {
697 // Inflate latin1 encoded string to UTF16
698 jchar* buf = NEW_C_HEAP_ARRAY(jchar, s_len, mtInternal);
699 for (int i = 0; i < s_len; i++) {
700 buf[i] = ((jchar) s_value->byte_at(i)) & 0xff;
701 }
702 value = &buf[0];
703 }
704 } else {
705 // Don't use char_at_addr(0) if length is 0
706 value = (jchar*) s_value->base(T_CHAR);
707 }
708
709 // invoke the callback
710 jint res = (*cb)(wrapper->klass_tag(),
711 wrapper->obj_size(),
712 wrapper->obj_tag_p(),
713 value,
714 (jint)s_len,
715 user_data);
716
717 if (is_latin1 && s_len > 0) {
718 FREE_C_HEAP_ARRAY(jchar, value);
719 }
720 return res;
721 }
722
723 // helper function to invoke string primitive value callback
724 // returns visit control flags
725 static jint invoke_array_primitive_value_callback(jvmtiArrayPrimitiveValueCallback cb,
726 CallbackWrapper* wrapper,
727 oop obj,
728 void* user_data)
729 {
730 assert(obj->is_typeArray(), "not a primitive array");
731
732 // get base address of first element
733 typeArrayOop array = typeArrayOop(obj);
734 BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
735 void* elements = array->base(type);
736
737 // jvmtiPrimitiveType is defined so this mapping is always correct
738 jvmtiPrimitiveType elem_type = (jvmtiPrimitiveType)type2char(type);
739
740 return (*cb)(wrapper->klass_tag(),
741 wrapper->obj_size(),
742 wrapper->obj_tag_p(),
743 (jint)array->length(),
744 elem_type,
745 elements,
746 user_data);
747 }
748
749 // helper function to invoke the primitive field callback for all static fields
750 // of a given class
751 static jint invoke_primitive_field_callback_for_static_fields
752 (CallbackWrapper* wrapper,
753 oop obj,
754 jvmtiPrimitiveFieldCallback cb,
755 void* user_data)
756 {
757 // for static fields only the index will be set
758 static jvmtiHeapReferenceInfo reference_info = { 0 };
759
760 assert(obj->klass() == vmClasses::Class_klass(), "not a class");
761 if (java_lang_Class::is_primitive(obj)) {
762 return 0;
763 }
764 Klass* klass = java_lang_Class::as_Klass(obj);
765
766 // ignore classes for object and type arrays
767 if (!klass->is_instance_klass()) {
768 return 0;
769 }
770
771 // ignore classes which aren't linked yet
772 InstanceKlass* ik = InstanceKlass::cast(klass);
773 if (!ik->is_linked()) {
774 return 0;
775 }
776
777 // get the field map
778 ClassFieldMap* field_map = ClassFieldMap::create_map_of_static_fields(klass);
779
780 // invoke the callback for each static primitive field
781 for (int i=0; i<field_map->field_count(); i++) {
782 ClassFieldDescriptor* field = field_map->field_at(i);
783
784 // ignore non-primitive fields
785 char type = field->field_type();
786 if (!is_primitive_field_type(type)) {
787 continue;
788 }
789 // one-to-one mapping
790 jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type;
791
792 // get offset and field value
793 int offset = field->field_offset();
794 address addr = cast_from_oop<address>(klass->java_mirror()) + offset;
795 jvalue value;
796 copy_to_jvalue(&value, addr, value_type);
797
798 // field index
799 reference_info.field.index = field->field_index();
800
801 // invoke the callback
802 jint res = (*cb)(JVMTI_HEAP_REFERENCE_STATIC_FIELD,
803 &reference_info,
804 wrapper->klass_tag(),
805 wrapper->obj_tag_p(),
806 value,
807 value_type,
808 user_data);
809 if (res & JVMTI_VISIT_ABORT) {
810 delete field_map;
811 return res;
812 }
813 }
814
815 delete field_map;
816 return 0;
817 }
818
819 // helper function to invoke the primitive field callback for all instance fields
820 // of a given object
821 static jint invoke_primitive_field_callback_for_instance_fields(
822 CallbackWrapper* wrapper,
823 oop obj,
824 jvmtiPrimitiveFieldCallback cb,
825 void* user_data)
826 {
827 // for instance fields only the index will be set
828 static jvmtiHeapReferenceInfo reference_info = { 0 };
829
830 // get the map of the instance fields
831 ClassFieldMap* fields = JvmtiCachedClassFieldMap::get_map_of_instance_fields(obj);
832
833 // invoke the callback for each instance primitive field
834 for (int i=0; i<fields->field_count(); i++) {
835 ClassFieldDescriptor* field = fields->field_at(i);
836
837 // ignore non-primitive fields
838 char type = field->field_type();
839 if (!is_primitive_field_type(type)) {
840 continue;
841 }
842 // one-to-one mapping
843 jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type;
844
845 // get offset and field value
846 int offset = field->field_offset();
847 address addr = cast_from_oop<address>(obj) + offset;
848 jvalue value;
849 copy_to_jvalue(&value, addr, value_type);
850
851 // field index
852 reference_info.field.index = field->field_index();
853
854 // invoke the callback
855 jint res = (*cb)(JVMTI_HEAP_REFERENCE_FIELD,
856 &reference_info,
857 wrapper->klass_tag(),
858 wrapper->obj_tag_p(),
859 value,
860 value_type,
861 user_data);
862 if (res & JVMTI_VISIT_ABORT) {
863 return res;
864 }
865 }
866 return 0;
867 }
868
869
870 // VM operation to iterate over all objects in the heap (both reachable
871 // and unreachable)
872 class VM_HeapIterateOperation: public VM_Operation {
873 private:
874 ObjectClosure* _blk;
875 GrowableArray<jlong>* const _dead_objects;
876 public:
877 VM_HeapIterateOperation(ObjectClosure* blk, GrowableArray<jlong>* objects) :
878 _blk(blk), _dead_objects(objects) { }
879
880 VMOp_Type type() const { return VMOp_HeapIterateOperation; }
881 void doit() {
882 // allows class files maps to be cached during iteration
883 ClassFieldMapCacheMark cm;
884
885 JvmtiTagMap::check_hashmaps_for_heapwalk(_dead_objects);
886
887 // make sure that heap is parsable (fills TLABs with filler objects)
888 Universe::heap()->ensure_parsability(false); // no need to retire TLABs
889
890 // Verify heap before iteration - if the heap gets corrupted then
891 // JVMTI's IterateOverHeap will crash.
892 if (VerifyBeforeIteration) {
893 Universe::verify();
894 }
895
896 // do the iteration
897 Universe::heap()->object_iterate(_blk);
898 }
899 };
900
901
902 // An ObjectClosure used to support the deprecated IterateOverHeap and
903 // IterateOverInstancesOfClass functions
904 class IterateOverHeapObjectClosure: public ObjectClosure {
905 private:
906 JvmtiTagMap* _tag_map;
907 Klass* _klass;
908 jvmtiHeapObjectFilter _object_filter;
909 jvmtiHeapObjectCallback _heap_object_callback;
910 const void* _user_data;
911
912 // accessors
913 JvmtiTagMap* tag_map() const { return _tag_map; }
914 jvmtiHeapObjectFilter object_filter() const { return _object_filter; }
915 jvmtiHeapObjectCallback object_callback() const { return _heap_object_callback; }
916 Klass* klass() const { return _klass; }
917 const void* user_data() const { return _user_data; }
918
919 // indicates if iteration has been aborted
920 bool _iteration_aborted;
921 bool is_iteration_aborted() const { return _iteration_aborted; }
922 void set_iteration_aborted(bool aborted) { _iteration_aborted = aborted; }
923
924 public:
925 IterateOverHeapObjectClosure(JvmtiTagMap* tag_map,
926 Klass* klass,
927 jvmtiHeapObjectFilter object_filter,
928 jvmtiHeapObjectCallback heap_object_callback,
929 const void* user_data) :
930 _tag_map(tag_map),
931 _klass(klass),
932 _object_filter(object_filter),
933 _heap_object_callback(heap_object_callback),
934 _user_data(user_data),
935 _iteration_aborted(false)
936 {
937 }
938
939 void do_object(oop o);
940 };
941
942 // invoked for each object in the heap
943 void IterateOverHeapObjectClosure::do_object(oop o) {
944 assert(o != nullptr, "Heap iteration should never produce null!");
945 // check if iteration has been halted
946 if (is_iteration_aborted()) return;
947
948 // instanceof check when filtering by klass
949 if (klass() != nullptr && !o->is_a(klass())) {
950 return;
951 }
952
953 // skip if object is a dormant shared object whose mirror hasn't been loaded
954 if (o->klass()->java_mirror() == nullptr) {
955 log_debug(aot, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(o),
956 o->klass()->external_name());
957 return;
958 }
959
960 // prepare for the calllback
961 CallbackWrapper wrapper(tag_map(), o);
962
963 // if the object is tagged and we're only interested in untagged objects
964 // then don't invoke the callback. Similarly, if the object is untagged
965 // and we're only interested in tagged objects we skip the callback.
966 if (wrapper.obj_tag() != 0) {
967 if (object_filter() == JVMTI_HEAP_OBJECT_UNTAGGED) return;
968 } else {
969 if (object_filter() == JVMTI_HEAP_OBJECT_TAGGED) return;
970 }
971
972 // invoke the agent's callback
973 jvmtiIterationControl control = (*object_callback())(wrapper.klass_tag(),
974 wrapper.obj_size(),
975 wrapper.obj_tag_p(),
976 (void*)user_data());
977 if (control == JVMTI_ITERATION_ABORT) {
978 set_iteration_aborted(true);
979 }
980 }
981
982 // An ObjectClosure used to support the IterateThroughHeap function
983 class IterateThroughHeapObjectClosure: public ObjectClosure {
984 private:
985 JvmtiTagMap* _tag_map;
986 Klass* _klass;
987 int _heap_filter;
988 const jvmtiHeapCallbacks* _callbacks;
989 const void* _user_data;
990
991 // accessor functions
992 JvmtiTagMap* tag_map() const { return _tag_map; }
993 int heap_filter() const { return _heap_filter; }
994 const jvmtiHeapCallbacks* callbacks() const { return _callbacks; }
995 Klass* klass() const { return _klass; }
996 const void* user_data() const { return _user_data; }
997
998 // indicates if the iteration has been aborted
999 bool _iteration_aborted;
1000 bool is_iteration_aborted() const { return _iteration_aborted; }
1001
1002 // used to check the visit control flags. If the abort flag is set
1003 // then we set the iteration aborted flag so that the iteration completes
1004 // without processing any further objects
1005 bool check_flags_for_abort(jint flags) {
1006 bool is_abort = (flags & JVMTI_VISIT_ABORT) != 0;
1007 if (is_abort) {
1008 _iteration_aborted = true;
1009 }
1010 return is_abort;
1011 }
1012
1013 public:
1014 IterateThroughHeapObjectClosure(JvmtiTagMap* tag_map,
1015 Klass* klass,
1016 int heap_filter,
1017 const jvmtiHeapCallbacks* heap_callbacks,
1018 const void* user_data) :
1019 _tag_map(tag_map),
1020 _klass(klass),
1021 _heap_filter(heap_filter),
1022 _callbacks(heap_callbacks),
1023 _user_data(user_data),
1024 _iteration_aborted(false)
1025 {
1026 }
1027
1028 void do_object(oop o);
1029 };
1030
1031 // invoked for each object in the heap
1032 void IterateThroughHeapObjectClosure::do_object(oop obj) {
1033 assert(obj != nullptr, "Heap iteration should never produce null!");
1034 // check if iteration has been halted
1035 if (is_iteration_aborted()) return;
1036
1037 // apply class filter
1038 if (is_filtered_by_klass_filter(obj, klass())) return;
1039
1040 // skip if object is a dormant shared object whose mirror hasn't been loaded
1041 if (obj->klass()->java_mirror() == nullptr) {
1042 log_debug(aot, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(obj),
1043 obj->klass()->external_name());
1044 return;
1045 }
1046
1047 // prepare for callback
1048 CallbackWrapper wrapper(tag_map(), obj);
1049
1050 // check if filtered by the heap filter
1051 if (is_filtered_by_heap_filter(wrapper.obj_tag(), wrapper.klass_tag(), heap_filter())) {
1052 return;
1053 }
1054
1055 // for arrays we need the length, otherwise -1
1056 bool is_array = obj->is_array();
1057 int len = is_array ? arrayOop(obj)->length() : -1;
1058
1059 // invoke the object callback (if callback is provided)
1060 if (callbacks()->heap_iteration_callback != nullptr) {
1061 jvmtiHeapIterationCallback cb = callbacks()->heap_iteration_callback;
1062 jint res = (*cb)(wrapper.klass_tag(),
1063 wrapper.obj_size(),
1064 wrapper.obj_tag_p(),
1065 (jint)len,
1066 (void*)user_data());
1067 if (check_flags_for_abort(res)) return;
1068 }
1069
1070 // for objects and classes we report primitive fields if callback provided
1071 if (callbacks()->primitive_field_callback != nullptr && obj->is_instance()) {
1072 jint res;
1073 jvmtiPrimitiveFieldCallback cb = callbacks()->primitive_field_callback;
1074 if (obj->klass() == vmClasses::Class_klass()) {
1075 res = invoke_primitive_field_callback_for_static_fields(&wrapper,
1076 obj,
1077 cb,
1078 (void*)user_data());
1079 } else {
1080 res = invoke_primitive_field_callback_for_instance_fields(&wrapper,
1081 obj,
1082 cb,
1083 (void*)user_data());
1084 }
1085 if (check_flags_for_abort(res)) return;
1086 }
1087
1088 // string callback
1089 if (!is_array &&
1090 callbacks()->string_primitive_value_callback != nullptr &&
1091 obj->klass() == vmClasses::String_klass()) {
1092 jint res = invoke_string_value_callback(
1093 callbacks()->string_primitive_value_callback,
1094 &wrapper,
1095 obj,
1096 (void*)user_data() );
1097 if (check_flags_for_abort(res)) return;
1098 }
1099
1100 // array callback
1101 if (is_array &&
1102 callbacks()->array_primitive_value_callback != nullptr &&
1103 obj->is_typeArray()) {
1104 jint res = invoke_array_primitive_value_callback(
1105 callbacks()->array_primitive_value_callback,
1106 &wrapper,
1107 obj,
1108 (void*)user_data() );
1109 if (check_flags_for_abort(res)) return;
1110 }
1111 };
1112
1113
1114 // Deprecated function to iterate over all objects in the heap
1115 void JvmtiTagMap::iterate_over_heap(jvmtiHeapObjectFilter object_filter,
1116 Klass* klass,
1117 jvmtiHeapObjectCallback heap_object_callback,
1118 const void* user_data)
1119 {
1120 // EA based optimizations on tagged objects are already reverted.
1121 EscapeBarrier eb(object_filter == JVMTI_HEAP_OBJECT_UNTAGGED ||
1122 object_filter == JVMTI_HEAP_OBJECT_EITHER,
1123 JavaThread::current());
1124 eb.deoptimize_objects_all_threads();
1125 Arena dead_object_arena(mtServiceability);
1126 GrowableArray <jlong> dead_objects(&dead_object_arena, 10, 0, 0);
1127 {
1128 MutexLocker ml(Heap_lock);
1129 IterateOverHeapObjectClosure blk(this,
1130 klass,
1131 object_filter,
1132 heap_object_callback,
1133 user_data);
1134 VM_HeapIterateOperation op(&blk, &dead_objects);
1135 VMThread::execute(&op);
1136 }
1137 // Post events outside of Heap_lock
1138 post_dead_objects(&dead_objects);
1139 }
1140
1141
1142 // Iterates over all objects in the heap
1143 void JvmtiTagMap::iterate_through_heap(jint heap_filter,
1144 Klass* klass,
1145 const jvmtiHeapCallbacks* callbacks,
1146 const void* user_data)
1147 {
1148 // EA based optimizations on tagged objects are already reverted.
1149 EscapeBarrier eb(!(heap_filter & JVMTI_HEAP_FILTER_UNTAGGED), JavaThread::current());
1150 eb.deoptimize_objects_all_threads();
1151
1152 Arena dead_object_arena(mtServiceability);
1153 GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
1154 {
1155 MutexLocker ml(Heap_lock);
1156 IterateThroughHeapObjectClosure blk(this,
1157 klass,
1158 heap_filter,
1159 callbacks,
1160 user_data);
1161 VM_HeapIterateOperation op(&blk, &dead_objects);
1162 VMThread::execute(&op);
1163 }
1164 // Post events outside of Heap_lock
1165 post_dead_objects(&dead_objects);
1166 }
1167
1168 void JvmtiTagMap::remove_dead_entries_locked(GrowableArray<jlong>* objects) {
1169 assert(is_locked(), "precondition");
1170 if (_needs_cleaning) {
1171 // Recheck whether to post object free events under the lock.
1172 if (!env()->is_enabled(JVMTI_EVENT_OBJECT_FREE)) {
1173 objects = nullptr;
1174 }
1175 log_info(jvmti, table)("TagMap table needs cleaning%s",
1176 ((objects != nullptr) ? " and posting" : ""));
1177 hashmap()->remove_dead_entries(objects);
1178 _needs_cleaning = false;
1179 }
1180 }
1181
1182 void JvmtiTagMap::remove_dead_entries(GrowableArray<jlong>* objects) {
1183 MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1184 remove_dead_entries_locked(objects);
1185 }
1186
1187 void JvmtiTagMap::post_dead_objects(GrowableArray<jlong>* const objects) {
1188 assert(Thread::current()->is_Java_thread(), "Must post from JavaThread");
1189 if (objects != nullptr && objects->length() > 0) {
1190 JvmtiExport::post_object_free(env(), objects);
1191 log_info(jvmti, table)("%d free object posted", objects->length());
1192 }
1193 }
1194
1195 void JvmtiTagMap::remove_and_post_dead_objects() {
1196 ResourceMark rm;
1197 GrowableArray<jlong> objects;
1198 remove_dead_entries(&objects);
1199 post_dead_objects(&objects);
1200 }
1201
1202 void JvmtiTagMap::flush_object_free_events() {
1203 assert_not_at_safepoint();
1204 if (env()->is_enabled(JVMTI_EVENT_OBJECT_FREE)) {
1205 {
1206 MonitorLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1207 // If another thread is posting events, let it finish
1208 while (_posting_events) {
1209 ml.wait();
1210 }
1211
1212 if (!_needs_cleaning || is_empty()) {
1213 _needs_cleaning = false;
1214 return;
1215 }
1216 _posting_events = true;
1217 } // Drop the lock so we can do the cleaning on the VM thread.
1218 // Needs both cleaning and event posting (up to some other thread
1219 // getting there first after we dropped the lock).
1220 remove_and_post_dead_objects();
1221 {
1222 MonitorLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1223 _posting_events = false;
1224 ml.notify_all();
1225 }
1226 } else {
1227 remove_dead_entries(nullptr);
1228 }
1229 }
1230
1231 // support class for get_objects_with_tags
1232
1233 class TagObjectCollector : public JvmtiTagMapKeyClosure {
1234 private:
1235 JvmtiEnv* _env;
1236 JavaThread* _thread;
1237 jlong* _tags;
1238 jint _tag_count;
1239 bool _some_dead_found;
1240
1241 GrowableArray<jobject>* _object_results; // collected objects (JNI weak refs)
1242 GrowableArray<uint64_t>* _tag_results; // collected tags
1243
1244 public:
1245 TagObjectCollector(JvmtiEnv* env, const jlong* tags, jint tag_count) :
1246 _env(env),
1247 _thread(JavaThread::current()),
1248 _tags((jlong*)tags),
1249 _tag_count(tag_count),
1250 _some_dead_found(false),
1251 _object_results(new (mtServiceability) GrowableArray<jobject>(1, mtServiceability)),
1252 _tag_results(new (mtServiceability) GrowableArray<uint64_t>(1, mtServiceability)) { }
1253
1254 ~TagObjectCollector() {
1255 delete _object_results;
1256 delete _tag_results;
1257 }
1258
1259 bool some_dead_found() const { return _some_dead_found; }
1260
1261 // for each tagged object check if the tag value matches
1262 // - if it matches then we create a JNI local reference to the object
1263 // and record the reference and tag value.
1264 // Always return true so the iteration continues.
1265 bool do_entry(JvmtiTagMapKey& key, jlong& value) {
1266 for (int i = 0; i < _tag_count; i++) {
1267 if (_tags[i] == value) {
1268 // The reference in this tag map could be the only (implicitly weak)
1269 // reference to that object. If we hand it out, we need to keep it live wrt
1270 // SATB marking similar to other j.l.ref.Reference referents. This is
1271 // achieved by using a phantom load in the object() accessor.
1272 oop o = key.object();
1273 if (o == nullptr) {
1274 _some_dead_found = true;
1275 // skip this whole entry
1276 return true;
1277 }
1278 assert(o != nullptr && Universe::heap()->is_in(o), "sanity check");
1279 jobject ref = JNIHandles::make_local(_thread, o);
1280 _object_results->append(ref);
1281 _tag_results->append(value);
1282 }
1283 }
1284 return true;
1285 }
1286
1287 // return the results from the collection
1288 //
1289 jvmtiError result(jint* count_ptr, jobject** object_result_ptr, jlong** tag_result_ptr) {
1290 jvmtiError error;
1291 int count = _object_results->length();
1292 assert(count >= 0, "sanity check");
1293
1294 // if object_result_ptr is not null then allocate the result and copy
1295 // in the object references.
1296 if (object_result_ptr != nullptr) {
1297 error = _env->Allocate(count * sizeof(jobject), (unsigned char**)object_result_ptr);
1298 if (error != JVMTI_ERROR_NONE) {
1299 return error;
1300 }
1301 for (int i=0; i<count; i++) {
1302 (*object_result_ptr)[i] = _object_results->at(i);
1303 }
1304 }
1305
1306 // if tag_result_ptr is not null then allocate the result and copy
1307 // in the tag values.
1308 if (tag_result_ptr != nullptr) {
1309 error = _env->Allocate(count * sizeof(jlong), (unsigned char**)tag_result_ptr);
1310 if (error != JVMTI_ERROR_NONE) {
1311 if (object_result_ptr != nullptr) {
1312 _env->Deallocate((unsigned char*)object_result_ptr);
1313 }
1314 return error;
1315 }
1316 for (int i=0; i<count; i++) {
1317 (*tag_result_ptr)[i] = (jlong)_tag_results->at(i);
1318 }
1319 }
1320
1321 *count_ptr = count;
1322 return JVMTI_ERROR_NONE;
1323 }
1324 };
1325
1326 // return the list of objects with the specified tags
1327 jvmtiError JvmtiTagMap::get_objects_with_tags(const jlong* tags,
1328 jint count, jint* count_ptr, jobject** object_result_ptr, jlong** tag_result_ptr) {
1329
1330 TagObjectCollector collector(env(), tags, count);
1331 {
1332 // iterate over all tagged objects
1333 MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1334 // Can't post ObjectFree events here from a JavaThread, so this
1335 // will race with the gc_notification thread in the tiny
1336 // window where the object is not marked but hasn't been notified that
1337 // it is collected yet.
1338 entry_iterate(&collector);
1339 }
1340 return collector.result(count_ptr, object_result_ptr, tag_result_ptr);
1341 }
1342
1343 // helper to map a jvmtiHeapReferenceKind to an old style jvmtiHeapRootKind
1344 // (not performance critical as only used for roots)
1345 static jvmtiHeapRootKind toJvmtiHeapRootKind(jvmtiHeapReferenceKind kind) {
1346 switch (kind) {
1347 case JVMTI_HEAP_REFERENCE_JNI_GLOBAL: return JVMTI_HEAP_ROOT_JNI_GLOBAL;
1348 case JVMTI_HEAP_REFERENCE_SYSTEM_CLASS: return JVMTI_HEAP_ROOT_SYSTEM_CLASS;
1349 case JVMTI_HEAP_REFERENCE_STACK_LOCAL: return JVMTI_HEAP_ROOT_STACK_LOCAL;
1350 case JVMTI_HEAP_REFERENCE_JNI_LOCAL: return JVMTI_HEAP_ROOT_JNI_LOCAL;
1351 case JVMTI_HEAP_REFERENCE_THREAD: return JVMTI_HEAP_ROOT_THREAD;
1352 case JVMTI_HEAP_REFERENCE_OTHER: return JVMTI_HEAP_ROOT_OTHER;
1353 default: ShouldNotReachHere(); return JVMTI_HEAP_ROOT_OTHER;
1354 }
1355 }
1356
1357 // Base class for all heap walk contexts. The base class maintains a flag
1358 // to indicate if the context is valid or not.
1359 class HeapWalkContext {
1360 private:
1361 bool _valid;
1362 public:
1363 HeapWalkContext(bool valid) { _valid = valid; }
1364 void invalidate() { _valid = false; }
1365 bool is_valid() const { return _valid; }
1366 };
1367
1368 // A basic heap walk context for the deprecated heap walking functions.
1369 // The context for a basic heap walk are the callbacks and fields used by
1370 // the referrer caching scheme.
1371 class BasicHeapWalkContext: public HeapWalkContext {
1372 private:
1373 jvmtiHeapRootCallback _heap_root_callback;
1374 jvmtiStackReferenceCallback _stack_ref_callback;
1375 jvmtiObjectReferenceCallback _object_ref_callback;
1376
1377 // used for caching
1378 oop _last_referrer;
1379 jlong _last_referrer_tag;
1380
1381 public:
1382 BasicHeapWalkContext() : HeapWalkContext(false) { }
1383
1384 BasicHeapWalkContext(jvmtiHeapRootCallback heap_root_callback,
1385 jvmtiStackReferenceCallback stack_ref_callback,
1386 jvmtiObjectReferenceCallback object_ref_callback) :
1387 HeapWalkContext(true),
1388 _heap_root_callback(heap_root_callback),
1389 _stack_ref_callback(stack_ref_callback),
1390 _object_ref_callback(object_ref_callback),
1391 _last_referrer(nullptr),
1392 _last_referrer_tag(0) {
1393 }
1394
1395 // accessors
1396 jvmtiHeapRootCallback heap_root_callback() const { return _heap_root_callback; }
1397 jvmtiStackReferenceCallback stack_ref_callback() const { return _stack_ref_callback; }
1398 jvmtiObjectReferenceCallback object_ref_callback() const { return _object_ref_callback; }
1399
1400 oop last_referrer() const { return _last_referrer; }
1401 void set_last_referrer(oop referrer) { _last_referrer = referrer; }
1402 jlong last_referrer_tag() const { return _last_referrer_tag; }
1403 void set_last_referrer_tag(jlong value) { _last_referrer_tag = value; }
1404 };
1405
1406 // The advanced heap walk context for the FollowReferences functions.
1407 // The context is the callbacks, and the fields used for filtering.
1408 class AdvancedHeapWalkContext: public HeapWalkContext {
1409 private:
1410 jint _heap_filter;
1411 Klass* _klass_filter;
1412 const jvmtiHeapCallbacks* _heap_callbacks;
1413
1414 public:
1415 AdvancedHeapWalkContext() : HeapWalkContext(false) { }
1416
1417 AdvancedHeapWalkContext(jint heap_filter,
1418 Klass* klass_filter,
1419 const jvmtiHeapCallbacks* heap_callbacks) :
1420 HeapWalkContext(true),
1421 _heap_filter(heap_filter),
1422 _klass_filter(klass_filter),
1423 _heap_callbacks(heap_callbacks) {
1424 }
1425
1426 // accessors
1427 jint heap_filter() const { return _heap_filter; }
1428 Klass* klass_filter() const { return _klass_filter; }
1429
1430 jvmtiHeapReferenceCallback heap_reference_callback() const {
1431 return _heap_callbacks->heap_reference_callback;
1432 };
1433 jvmtiPrimitiveFieldCallback primitive_field_callback() const {
1434 return _heap_callbacks->primitive_field_callback;
1435 }
1436 jvmtiArrayPrimitiveValueCallback array_primitive_value_callback() const {
1437 return _heap_callbacks->array_primitive_value_callback;
1438 }
1439 jvmtiStringPrimitiveValueCallback string_primitive_value_callback() const {
1440 return _heap_callbacks->string_primitive_value_callback;
1441 }
1442 };
1443
1444 // The CallbackInvoker is a class with static functions that the heap walk can call
1445 // into to invoke callbacks. It works in one of two modes. The "basic" mode is
1446 // used for the deprecated IterateOverReachableObjects functions. The "advanced"
1447 // mode is for the newer FollowReferences function which supports a lot of
1448 // additional callbacks.
1449 class CallbackInvoker : AllStatic {
1450 private:
1451 // heap walk styles
1452 enum { basic, advanced };
1453 static int _heap_walk_type;
1454 static bool is_basic_heap_walk() { return _heap_walk_type == basic; }
1455 static bool is_advanced_heap_walk() { return _heap_walk_type == advanced; }
1456
1457 // context for basic style heap walk
1458 static BasicHeapWalkContext _basic_context;
1459 static BasicHeapWalkContext* basic_context() {
1460 assert(_basic_context.is_valid(), "invalid");
1461 return &_basic_context;
1462 }
1463
1464 // context for advanced style heap walk
1465 static AdvancedHeapWalkContext _advanced_context;
1466 static AdvancedHeapWalkContext* advanced_context() {
1467 assert(_advanced_context.is_valid(), "invalid");
1468 return &_advanced_context;
1469 }
1470
1471 // context needed for all heap walks
1472 static JvmtiTagMap* _tag_map;
1473 static const void* _user_data;
1474 static GrowableArray<oop>* _visit_stack;
1475 static JVMTIBitSet* _bitset;
1476
1477 // accessors
1478 static JvmtiTagMap* tag_map() { return _tag_map; }
1479 static const void* user_data() { return _user_data; }
1480 static GrowableArray<oop>* visit_stack() { return _visit_stack; }
1481
1482 // if the object hasn't been visited then push it onto the visit stack
1483 // so that it will be visited later
1484 static inline bool check_for_visit(oop obj) {
1485 if (!_bitset->is_marked(obj)) visit_stack()->push(obj);
1486 return true;
1487 }
1488
1489 // invoke basic style callbacks
1490 static inline bool invoke_basic_heap_root_callback
1491 (jvmtiHeapRootKind root_kind, oop obj);
1492 static inline bool invoke_basic_stack_ref_callback
1493 (jvmtiHeapRootKind root_kind, jlong thread_tag, jint depth, jmethodID method,
1494 int slot, oop obj);
1495 static inline bool invoke_basic_object_reference_callback
1496 (jvmtiObjectReferenceKind ref_kind, oop referrer, oop referree, jint index);
1497
1498 // invoke advanced style callbacks
1499 static inline bool invoke_advanced_heap_root_callback
1500 (jvmtiHeapReferenceKind ref_kind, oop obj);
1501 static inline bool invoke_advanced_stack_ref_callback
1502 (jvmtiHeapReferenceKind ref_kind, jlong thread_tag, jlong tid, int depth,
1503 jmethodID method, jlocation bci, jint slot, oop obj);
1504 static inline bool invoke_advanced_object_reference_callback
1505 (jvmtiHeapReferenceKind ref_kind, oop referrer, oop referree, jint index);
1506
1507 // used to report the value of primitive fields
1508 static inline bool report_primitive_field
1509 (jvmtiHeapReferenceKind ref_kind, oop obj, jint index, address addr, char type);
1510
1511 public:
1512 // initialize for basic mode
1513 static void initialize_for_basic_heap_walk(JvmtiTagMap* tag_map,
1514 GrowableArray<oop>* visit_stack,
1515 const void* user_data,
1516 BasicHeapWalkContext context,
1517 JVMTIBitSet* bitset);
1518
1519 // initialize for advanced mode
1520 static void initialize_for_advanced_heap_walk(JvmtiTagMap* tag_map,
1521 GrowableArray<oop>* visit_stack,
1522 const void* user_data,
1523 AdvancedHeapWalkContext context,
1524 JVMTIBitSet* bitset);
1525
1526 // functions to report roots
1527 static inline bool report_simple_root(jvmtiHeapReferenceKind kind, oop o);
1528 static inline bool report_jni_local_root(jlong thread_tag, jlong tid, jint depth,
1529 jmethodID m, oop o);
1530 static inline bool report_stack_ref_root(jlong thread_tag, jlong tid, jint depth,
1531 jmethodID method, jlocation bci, jint slot, oop o);
1532
1533 // functions to report references
1534 static inline bool report_array_element_reference(oop referrer, oop referree, jint index);
1535 static inline bool report_class_reference(oop referrer, oop referree);
1536 static inline bool report_class_loader_reference(oop referrer, oop referree);
1537 static inline bool report_signers_reference(oop referrer, oop referree);
1538 static inline bool report_protection_domain_reference(oop referrer, oop referree);
1539 static inline bool report_superclass_reference(oop referrer, oop referree);
1540 static inline bool report_interface_reference(oop referrer, oop referree);
1541 static inline bool report_static_field_reference(oop referrer, oop referree, jint slot);
1542 static inline bool report_field_reference(oop referrer, oop referree, jint slot);
1543 static inline bool report_constant_pool_reference(oop referrer, oop referree, jint index);
1544 static inline bool report_primitive_array_values(oop array);
1545 static inline bool report_string_value(oop str);
1546 static inline bool report_primitive_instance_field(oop o, jint index, address value, char type);
1547 static inline bool report_primitive_static_field(oop o, jint index, address value, char type);
1548 };
1549
1550 // statics
1551 int CallbackInvoker::_heap_walk_type;
1552 BasicHeapWalkContext CallbackInvoker::_basic_context;
1553 AdvancedHeapWalkContext CallbackInvoker::_advanced_context;
1554 JvmtiTagMap* CallbackInvoker::_tag_map;
1555 const void* CallbackInvoker::_user_data;
1556 GrowableArray<oop>* CallbackInvoker::_visit_stack;
1557 JVMTIBitSet* CallbackInvoker::_bitset;
1558
1559 // initialize for basic heap walk (IterateOverReachableObjects et al)
1560 void CallbackInvoker::initialize_for_basic_heap_walk(JvmtiTagMap* tag_map,
1561 GrowableArray<oop>* visit_stack,
1562 const void* user_data,
1563 BasicHeapWalkContext context,
1564 JVMTIBitSet* bitset) {
1565 _tag_map = tag_map;
1566 _visit_stack = visit_stack;
1567 _user_data = user_data;
1568 _basic_context = context;
1569 _advanced_context.invalidate(); // will trigger assertion if used
1570 _heap_walk_type = basic;
1571 _bitset = bitset;
1572 }
1573
1574 // initialize for advanced heap walk (FollowReferences)
1575 void CallbackInvoker::initialize_for_advanced_heap_walk(JvmtiTagMap* tag_map,
1576 GrowableArray<oop>* visit_stack,
1577 const void* user_data,
1578 AdvancedHeapWalkContext context,
1579 JVMTIBitSet* bitset) {
1580 _tag_map = tag_map;
1581 _visit_stack = visit_stack;
1582 _user_data = user_data;
1583 _advanced_context = context;
1584 _basic_context.invalidate(); // will trigger assertion if used
1585 _heap_walk_type = advanced;
1586 _bitset = bitset;
1587 }
1588
1589
1590 // invoke basic style heap root callback
1591 inline bool CallbackInvoker::invoke_basic_heap_root_callback(jvmtiHeapRootKind root_kind, oop obj) {
1592 // if we heap roots should be reported
1593 jvmtiHeapRootCallback cb = basic_context()->heap_root_callback();
1594 if (cb == nullptr) {
1595 return check_for_visit(obj);
1596 }
1597
1598 CallbackWrapper wrapper(tag_map(), obj);
1599 jvmtiIterationControl control = (*cb)(root_kind,
1600 wrapper.klass_tag(),
1601 wrapper.obj_size(),
1602 wrapper.obj_tag_p(),
1603 (void*)user_data());
1604 // push root to visit stack when following references
1605 if (control == JVMTI_ITERATION_CONTINUE &&
1606 basic_context()->object_ref_callback() != nullptr) {
1607 visit_stack()->push(obj);
1608 }
1609 return control != JVMTI_ITERATION_ABORT;
1610 }
1611
1612 // invoke basic style stack ref callback
1613 inline bool CallbackInvoker::invoke_basic_stack_ref_callback(jvmtiHeapRootKind root_kind,
1614 jlong thread_tag,
1615 jint depth,
1616 jmethodID method,
1617 int slot,
1618 oop obj) {
1619 // if we stack refs should be reported
1620 jvmtiStackReferenceCallback cb = basic_context()->stack_ref_callback();
1621 if (cb == nullptr) {
1622 return check_for_visit(obj);
1623 }
1624
1625 CallbackWrapper wrapper(tag_map(), obj);
1626 jvmtiIterationControl control = (*cb)(root_kind,
1627 wrapper.klass_tag(),
1628 wrapper.obj_size(),
1629 wrapper.obj_tag_p(),
1630 thread_tag,
1631 depth,
1632 method,
1633 slot,
1634 (void*)user_data());
1635 // push root to visit stack when following references
1636 if (control == JVMTI_ITERATION_CONTINUE &&
1637 basic_context()->object_ref_callback() != nullptr) {
1638 visit_stack()->push(obj);
1639 }
1640 return control != JVMTI_ITERATION_ABORT;
1641 }
1642
1643 // invoke basic style object reference callback
1644 inline bool CallbackInvoker::invoke_basic_object_reference_callback(jvmtiObjectReferenceKind ref_kind,
1645 oop referrer,
1646 oop referree,
1647 jint index) {
1648
1649 BasicHeapWalkContext* context = basic_context();
1650
1651 // callback requires the referrer's tag. If it's the same referrer
1652 // as the last call then we use the cached value.
1653 jlong referrer_tag;
1654 if (referrer == context->last_referrer()) {
1655 referrer_tag = context->last_referrer_tag();
1656 } else {
1657 referrer_tag = tag_for(tag_map(), referrer);
1658 }
1659
1660 // do the callback
1661 CallbackWrapper wrapper(tag_map(), referree);
1662 jvmtiObjectReferenceCallback cb = context->object_ref_callback();
1663 jvmtiIterationControl control = (*cb)(ref_kind,
1664 wrapper.klass_tag(),
1665 wrapper.obj_size(),
1666 wrapper.obj_tag_p(),
1667 referrer_tag,
1668 index,
1669 (void*)user_data());
1670
1671 // record referrer and referrer tag. For self-references record the
1672 // tag value from the callback as this might differ from referrer_tag.
1673 context->set_last_referrer(referrer);
1674 if (referrer == referree) {
1675 context->set_last_referrer_tag(*wrapper.obj_tag_p());
1676 } else {
1677 context->set_last_referrer_tag(referrer_tag);
1678 }
1679
1680 if (control == JVMTI_ITERATION_CONTINUE) {
1681 return check_for_visit(referree);
1682 } else {
1683 return control != JVMTI_ITERATION_ABORT;
1684 }
1685 }
1686
1687 // invoke advanced style heap root callback
1688 inline bool CallbackInvoker::invoke_advanced_heap_root_callback(jvmtiHeapReferenceKind ref_kind,
1689 oop obj) {
1690 AdvancedHeapWalkContext* context = advanced_context();
1691
1692 // check that callback is provided
1693 jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
1694 if (cb == nullptr) {
1695 return check_for_visit(obj);
1696 }
1697
1698 // apply class filter
1699 if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1700 return check_for_visit(obj);
1701 }
1702
1703 // setup the callback wrapper
1704 CallbackWrapper wrapper(tag_map(), obj);
1705
1706 // apply tag filter
1707 if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1708 wrapper.klass_tag(),
1709 context->heap_filter())) {
1710 return check_for_visit(obj);
1711 }
1712
1713 // for arrays we need the length, otherwise -1
1714 jint len = (jint)(obj->is_array() ? arrayOop(obj)->length() : -1);
1715
1716 // invoke the callback
1717 jint res = (*cb)(ref_kind,
1718 nullptr, // referrer info
1719 wrapper.klass_tag(),
1720 0, // referrer_class_tag is 0 for heap root
1721 wrapper.obj_size(),
1722 wrapper.obj_tag_p(),
1723 nullptr, // referrer_tag_p
1724 len,
1725 (void*)user_data());
1726 if (res & JVMTI_VISIT_ABORT) {
1727 return false;// referrer class tag
1728 }
1729 if (res & JVMTI_VISIT_OBJECTS) {
1730 check_for_visit(obj);
1731 }
1732 return true;
1733 }
1734
1735 // report a reference from a thread stack to an object
1736 inline bool CallbackInvoker::invoke_advanced_stack_ref_callback(jvmtiHeapReferenceKind ref_kind,
1737 jlong thread_tag,
1738 jlong tid,
1739 int depth,
1740 jmethodID method,
1741 jlocation bci,
1742 jint slot,
1743 oop obj) {
1744 AdvancedHeapWalkContext* context = advanced_context();
1745
1746 // check that callback is provider
1747 jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
1748 if (cb == nullptr) {
1749 return check_for_visit(obj);
1750 }
1751
1752 // apply class filter
1753 if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1754 return check_for_visit(obj);
1755 }
1756
1757 // setup the callback wrapper
1758 CallbackWrapper wrapper(tag_map(), obj);
1759
1760 // apply tag filter
1761 if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1762 wrapper.klass_tag(),
1763 context->heap_filter())) {
1764 return check_for_visit(obj);
1765 }
1766
1767 // setup the referrer info
1768 jvmtiHeapReferenceInfo reference_info;
1769 reference_info.stack_local.thread_tag = thread_tag;
1770 reference_info.stack_local.thread_id = tid;
1771 reference_info.stack_local.depth = depth;
1772 reference_info.stack_local.method = method;
1773 reference_info.stack_local.location = bci;
1774 reference_info.stack_local.slot = slot;
1775
1776 // for arrays we need the length, otherwise -1
1777 jint len = (jint)(obj->is_array() ? arrayOop(obj)->length() : -1);
1778
1779 // call into the agent
1780 int res = (*cb)(ref_kind,
1781 &reference_info,
1782 wrapper.klass_tag(),
1783 0, // referrer_class_tag is 0 for heap root (stack)
1784 wrapper.obj_size(),
1785 wrapper.obj_tag_p(),
1786 nullptr, // referrer_tag is 0 for root
1787 len,
1788 (void*)user_data());
1789
1790 if (res & JVMTI_VISIT_ABORT) {
1791 return false;
1792 }
1793 if (res & JVMTI_VISIT_OBJECTS) {
1794 check_for_visit(obj);
1795 }
1796 return true;
1797 }
1798
1799 // This mask is used to pass reference_info to a jvmtiHeapReferenceCallback
1800 // only for ref_kinds defined by the JVM TI spec. Otherwise, null is passed.
1801 #define REF_INFO_MASK ((1 << JVMTI_HEAP_REFERENCE_FIELD) \
1802 | (1 << JVMTI_HEAP_REFERENCE_STATIC_FIELD) \
1803 | (1 << JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT) \
1804 | (1 << JVMTI_HEAP_REFERENCE_CONSTANT_POOL) \
1805 | (1 << JVMTI_HEAP_REFERENCE_STACK_LOCAL) \
1806 | (1 << JVMTI_HEAP_REFERENCE_JNI_LOCAL))
1807
1808 // invoke the object reference callback to report a reference
1809 inline bool CallbackInvoker::invoke_advanced_object_reference_callback(jvmtiHeapReferenceKind ref_kind,
1810 oop referrer,
1811 oop obj,
1812 jint index)
1813 {
1814 // field index is only valid field in reference_info
1815 static jvmtiHeapReferenceInfo reference_info = { 0 };
1816
1817 AdvancedHeapWalkContext* context = advanced_context();
1818
1819 // check that callback is provider
1820 jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
1821 if (cb == nullptr) {
1822 return check_for_visit(obj);
1823 }
1824
1825 // apply class filter
1826 if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1827 return check_for_visit(obj);
1828 }
1829
1830 // setup the callback wrapper
1831 TwoOopCallbackWrapper wrapper(tag_map(), referrer, obj);
1832
1833 // apply tag filter
1834 if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1835 wrapper.klass_tag(),
1836 context->heap_filter())) {
1837 return check_for_visit(obj);
1838 }
1839
1840 // field index is only valid field in reference_info
1841 reference_info.field.index = index;
1842
1843 // for arrays we need the length, otherwise -1
1844 jint len = (jint)(obj->is_array() ? arrayOop(obj)->length() : -1);
1845
1846 // invoke the callback
1847 int res = (*cb)(ref_kind,
1848 (REF_INFO_MASK & (1 << ref_kind)) ? &reference_info : nullptr,
1849 wrapper.klass_tag(),
1850 wrapper.referrer_klass_tag(),
1851 wrapper.obj_size(),
1852 wrapper.obj_tag_p(),
1853 wrapper.referrer_tag_p(),
1854 len,
1855 (void*)user_data());
1856
1857 if (res & JVMTI_VISIT_ABORT) {
1858 return false;
1859 }
1860 if (res & JVMTI_VISIT_OBJECTS) {
1861 check_for_visit(obj);
1862 }
1863 return true;
1864 }
1865
1866 // report a "simple root"
1867 inline bool CallbackInvoker::report_simple_root(jvmtiHeapReferenceKind kind, oop obj) {
1868 assert(kind != JVMTI_HEAP_REFERENCE_STACK_LOCAL &&
1869 kind != JVMTI_HEAP_REFERENCE_JNI_LOCAL, "not a simple root");
1870
1871 if (is_basic_heap_walk()) {
1872 // map to old style root kind
1873 jvmtiHeapRootKind root_kind = toJvmtiHeapRootKind(kind);
1874 return invoke_basic_heap_root_callback(root_kind, obj);
1875 } else {
1876 assert(is_advanced_heap_walk(), "wrong heap walk type");
1877 return invoke_advanced_heap_root_callback(kind, obj);
1878 }
1879 }
1880
1881
1882 // invoke the primitive array values
1883 inline bool CallbackInvoker::report_primitive_array_values(oop obj) {
1884 assert(obj->is_typeArray(), "not a primitive array");
1885
1886 AdvancedHeapWalkContext* context = advanced_context();
1887 assert(context->array_primitive_value_callback() != nullptr, "no callback");
1888
1889 // apply class filter
1890 if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1891 return true;
1892 }
1893
1894 CallbackWrapper wrapper(tag_map(), obj);
1895
1896 // apply tag filter
1897 if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1898 wrapper.klass_tag(),
1899 context->heap_filter())) {
1900 return true;
1901 }
1902
1903 // invoke the callback
1904 int res = invoke_array_primitive_value_callback(context->array_primitive_value_callback(),
1905 &wrapper,
1906 obj,
1907 (void*)user_data());
1908 return (!(res & JVMTI_VISIT_ABORT));
1909 }
1910
1911 // invoke the string value callback
1912 inline bool CallbackInvoker::report_string_value(oop str) {
1913 assert(str->klass() == vmClasses::String_klass(), "not a string");
1914
1915 AdvancedHeapWalkContext* context = advanced_context();
1916 assert(context->string_primitive_value_callback() != nullptr, "no callback");
1917
1918 // apply class filter
1919 if (is_filtered_by_klass_filter(str, context->klass_filter())) {
1920 return true;
1921 }
1922
1923 CallbackWrapper wrapper(tag_map(), str);
1924
1925 // apply tag filter
1926 if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1927 wrapper.klass_tag(),
1928 context->heap_filter())) {
1929 return true;
1930 }
1931
1932 // invoke the callback
1933 int res = invoke_string_value_callback(context->string_primitive_value_callback(),
1934 &wrapper,
1935 str,
1936 (void*)user_data());
1937 return (!(res & JVMTI_VISIT_ABORT));
1938 }
1939
1940 // invoke the primitive field callback
1941 inline bool CallbackInvoker::report_primitive_field(jvmtiHeapReferenceKind ref_kind,
1942 oop obj,
1943 jint index,
1944 address addr,
1945 char type)
1946 {
1947 // for primitive fields only the index will be set
1948 static jvmtiHeapReferenceInfo reference_info = { 0 };
1949
1950 AdvancedHeapWalkContext* context = advanced_context();
1951 assert(context->primitive_field_callback() != nullptr, "no callback");
1952
1953 // apply class filter
1954 if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1955 return true;
1956 }
1957
1958 CallbackWrapper wrapper(tag_map(), obj);
1959
1960 // apply tag filter
1961 if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1962 wrapper.klass_tag(),
1963 context->heap_filter())) {
1964 return true;
1965 }
1966
1967 // the field index in the referrer
1968 reference_info.field.index = index;
1969
1970 // map the type
1971 jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type;
1972
1973 // setup the jvalue
1974 jvalue value;
1975 copy_to_jvalue(&value, addr, value_type);
1976
1977 jvmtiPrimitiveFieldCallback cb = context->primitive_field_callback();
1978 int res = (*cb)(ref_kind,
1979 &reference_info,
1980 wrapper.klass_tag(),
1981 wrapper.obj_tag_p(),
1982 value,
1983 value_type,
1984 (void*)user_data());
1985 return (!(res & JVMTI_VISIT_ABORT));
1986 }
1987
1988
1989 // instance field
1990 inline bool CallbackInvoker::report_primitive_instance_field(oop obj,
1991 jint index,
1992 address value,
1993 char type) {
1994 return report_primitive_field(JVMTI_HEAP_REFERENCE_FIELD,
1995 obj,
1996 index,
1997 value,
1998 type);
1999 }
2000
2001 // static field
2002 inline bool CallbackInvoker::report_primitive_static_field(oop obj,
2003 jint index,
2004 address value,
2005 char type) {
2006 return report_primitive_field(JVMTI_HEAP_REFERENCE_STATIC_FIELD,
2007 obj,
2008 index,
2009 value,
2010 type);
2011 }
2012
2013 // report a JNI local (root object) to the profiler
2014 inline bool CallbackInvoker::report_jni_local_root(jlong thread_tag, jlong tid, jint depth, jmethodID m, oop obj) {
2015 if (is_basic_heap_walk()) {
2016 return invoke_basic_stack_ref_callback(JVMTI_HEAP_ROOT_JNI_LOCAL,
2017 thread_tag,
2018 depth,
2019 m,
2020 -1,
2021 obj);
2022 } else {
2023 return invoke_advanced_stack_ref_callback(JVMTI_HEAP_REFERENCE_JNI_LOCAL,
2024 thread_tag, tid,
2025 depth,
2026 m,
2027 (jlocation)-1,
2028 -1,
2029 obj);
2030 }
2031 }
2032
2033
2034 // report a local (stack reference, root object)
2035 inline bool CallbackInvoker::report_stack_ref_root(jlong thread_tag,
2036 jlong tid,
2037 jint depth,
2038 jmethodID method,
2039 jlocation bci,
2040 jint slot,
2041 oop obj) {
2042 if (is_basic_heap_walk()) {
2043 return invoke_basic_stack_ref_callback(JVMTI_HEAP_ROOT_STACK_LOCAL,
2044 thread_tag,
2045 depth,
2046 method,
2047 slot,
2048 obj);
2049 } else {
2050 return invoke_advanced_stack_ref_callback(JVMTI_HEAP_REFERENCE_STACK_LOCAL,
2051 thread_tag,
2052 tid,
2053 depth,
2054 method,
2055 bci,
2056 slot,
2057 obj);
2058 }
2059 }
2060
2061 // report an object referencing a class.
2062 inline bool CallbackInvoker::report_class_reference(oop referrer, oop referree) {
2063 if (is_basic_heap_walk()) {
2064 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS, referrer, referree, -1);
2065 } else {
2066 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CLASS, referrer, referree, -1);
2067 }
2068 }
2069
2070 // report a class referencing its class loader.
2071 inline bool CallbackInvoker::report_class_loader_reference(oop referrer, oop referree) {
2072 if (is_basic_heap_walk()) {
2073 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS_LOADER, referrer, referree, -1);
2074 } else {
2075 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CLASS_LOADER, referrer, referree, -1);
2076 }
2077 }
2078
2079 // report a class referencing its signers.
2080 inline bool CallbackInvoker::report_signers_reference(oop referrer, oop referree) {
2081 if (is_basic_heap_walk()) {
2082 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_SIGNERS, referrer, referree, -1);
2083 } else {
2084 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_SIGNERS, referrer, referree, -1);
2085 }
2086 }
2087
2088 // report a class referencing its protection domain..
2089 inline bool CallbackInvoker::report_protection_domain_reference(oop referrer, oop referree) {
2090 if (is_basic_heap_walk()) {
2091 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_PROTECTION_DOMAIN, referrer, referree, -1);
2092 } else {
2093 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_PROTECTION_DOMAIN, referrer, referree, -1);
2094 }
2095 }
2096
2097 // report a class referencing its superclass.
2098 inline bool CallbackInvoker::report_superclass_reference(oop referrer, oop referree) {
2099 if (is_basic_heap_walk()) {
2100 // Send this to be consistent with past implementation
2101 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS, referrer, referree, -1);
2102 } else {
2103 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_SUPERCLASS, referrer, referree, -1);
2104 }
2105 }
2106
2107 // report a class referencing one of its interfaces.
2108 inline bool CallbackInvoker::report_interface_reference(oop referrer, oop referree) {
2109 if (is_basic_heap_walk()) {
2110 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_INTERFACE, referrer, referree, -1);
2111 } else {
2112 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_INTERFACE, referrer, referree, -1);
2113 }
2114 }
2115
2116 // report a class referencing one of its static fields.
2117 inline bool CallbackInvoker::report_static_field_reference(oop referrer, oop referree, jint slot) {
2118 if (is_basic_heap_walk()) {
2119 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_STATIC_FIELD, referrer, referree, slot);
2120 } else {
2121 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_STATIC_FIELD, referrer, referree, slot);
2122 }
2123 }
2124
2125 // report an array referencing an element object
2126 inline bool CallbackInvoker::report_array_element_reference(oop referrer, oop referree, jint index) {
2127 if (is_basic_heap_walk()) {
2128 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_ARRAY_ELEMENT, referrer, referree, index);
2129 } else {
2130 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, referrer, referree, index);
2131 }
2132 }
2133
2134 // report an object referencing an instance field object
2135 inline bool CallbackInvoker::report_field_reference(oop referrer, oop referree, jint slot) {
2136 if (is_basic_heap_walk()) {
2137 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_FIELD, referrer, referree, slot);
2138 } else {
2139 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_FIELD, referrer, referree, slot);
2140 }
2141 }
2142
2143 // report an array referencing an element object
2144 inline bool CallbackInvoker::report_constant_pool_reference(oop referrer, oop referree, jint index) {
2145 if (is_basic_heap_walk()) {
2146 return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CONSTANT_POOL, referrer, referree, index);
2147 } else {
2148 return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CONSTANT_POOL, referrer, referree, index);
2149 }
2150 }
2151
2152 // A supporting closure used to process simple roots
2153 class SimpleRootsClosure : public OopClosure {
2154 private:
2155 jvmtiHeapReferenceKind _kind;
2156 bool _continue;
2157
2158 jvmtiHeapReferenceKind root_kind() { return _kind; }
2159
2160 public:
2161 void set_kind(jvmtiHeapReferenceKind kind) {
2162 _kind = kind;
2163 _continue = true;
2164 }
2165
2166 inline bool stopped() {
2167 return !_continue;
2168 }
2169
2170 void do_oop(oop* obj_p) {
2171 // iteration has terminated
2172 if (stopped()) {
2173 return;
2174 }
2175
2176 oop o = NativeAccess<AS_NO_KEEPALIVE>::oop_load(obj_p);
2177 // ignore null
2178 if (o == nullptr) {
2179 return;
2180 }
2181
2182 assert(Universe::heap()->is_in(o), "should be impossible");
2183
2184 jvmtiHeapReferenceKind kind = root_kind();
2185
2186 // invoke the callback
2187 _continue = CallbackInvoker::report_simple_root(kind, o);
2188
2189 }
2190 virtual void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
2191 };
2192
2193 // A supporting closure used to process JNI locals
2194 class JNILocalRootsClosure : public OopClosure {
2195 private:
2196 jlong _thread_tag;
2197 jlong _tid;
2198 jint _depth;
2199 jmethodID _method;
2200 bool _continue;
2201 public:
2202 void set_context(jlong thread_tag, jlong tid, jint depth, jmethodID method) {
2203 _thread_tag = thread_tag;
2204 _tid = tid;
2205 _depth = depth;
2206 _method = method;
2207 _continue = true;
2208 }
2209
2210 inline bool stopped() {
2211 return !_continue;
2212 }
2213
2214 void do_oop(oop* obj_p) {
2215 // iteration has terminated
2216 if (stopped()) {
2217 return;
2218 }
2219
2220 oop o = *obj_p;
2221 // ignore null
2222 if (o == nullptr) {
2223 return;
2224 }
2225
2226 // invoke the callback
2227 _continue = CallbackInvoker::report_jni_local_root(_thread_tag, _tid, _depth, _method, o);
2228 }
2229 virtual void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
2230 };
2231
2232 // Helper class to collect/report stack references.
2233 class StackRefCollector {
2234 private:
2235 JvmtiTagMap* _tag_map;
2236 JNILocalRootsClosure* _blk;
2237 // java_thread is needed only to report JNI local on top native frame;
2238 // I.e. it's required only for platform/carrier threads or mounted virtual threads.
2239 JavaThread* _java_thread;
2240
2241 oop _threadObj;
2242 jlong _thread_tag;
2243 jlong _tid;
2244
2245 bool _is_top_frame;
2246 int _depth;
2247 frame* _last_entry_frame;
2248
2249 bool report_java_stack_refs(StackValueCollection* values, jmethodID method, jlocation bci, jint slot_offset);
2250 bool report_native_stack_refs(jmethodID method);
2251
2252 public:
2253 StackRefCollector(JvmtiTagMap* tag_map, JNILocalRootsClosure* blk, JavaThread* java_thread)
2254 : _tag_map(tag_map), _blk(blk), _java_thread(java_thread),
2255 _threadObj(nullptr), _thread_tag(0), _tid(0),
2256 _is_top_frame(true), _depth(0), _last_entry_frame(nullptr)
2257 {
2258 }
2259
2260 bool set_thread(oop o);
2261 // Sets the thread and reports the reference to it with the specified kind.
2262 bool set_thread(jvmtiHeapReferenceKind kind, oop o);
2263
2264 bool do_frame(vframe* vf);
2265 // Handles frames until vf->sender() is null.
2266 bool process_frames(vframe* vf);
2267 };
2268
2269 bool StackRefCollector::set_thread(oop o) {
2270 _threadObj = o;
2271 _thread_tag = tag_for(_tag_map, _threadObj);
2272 _tid = java_lang_Thread::thread_id(_threadObj);
2273
2274 _is_top_frame = true;
2275 _depth = 0;
2276 _last_entry_frame = nullptr;
2277
2278 return true;
2279 }
2280
2281 bool StackRefCollector::set_thread(jvmtiHeapReferenceKind kind, oop o) {
2282 return set_thread(o)
2283 && CallbackInvoker::report_simple_root(kind, _threadObj);
2284 }
2285
2286 bool StackRefCollector::report_java_stack_refs(StackValueCollection* values, jmethodID method, jlocation bci, jint slot_offset) {
2287 for (int index = 0; index < values->size(); index++) {
2288 if (values->at(index)->type() == T_OBJECT) {
2289 oop obj = values->obj_at(index)();
2290 if (obj == nullptr) {
2291 continue;
2292 }
2293 // stack reference
2294 if (!CallbackInvoker::report_stack_ref_root(_thread_tag, _tid, _depth, method,
2295 bci, slot_offset + index, obj)) {
2296 return false;
2297 }
2298 }
2299 }
2300 return true;
2301 }
2302
2303 bool StackRefCollector::report_native_stack_refs(jmethodID method) {
2304 _blk->set_context(_thread_tag, _tid, _depth, method);
2305 if (_is_top_frame) {
2306 // JNI locals for the top frame.
2307 if (_java_thread != nullptr) {
2308 _java_thread->active_handles()->oops_do(_blk);
2309 if (_blk->stopped()) {
2310 return false;
2311 }
2312 }
2313 } else {
2314 if (_last_entry_frame != nullptr) {
2315 // JNI locals for the entry frame.
2316 assert(_last_entry_frame->is_entry_frame(), "checking");
2317 _last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(_blk);
2318 if (_blk->stopped()) {
2319 return false;
2320 }
2321 }
2322 }
2323 return true;
2324 }
2325
2326 bool StackRefCollector::do_frame(vframe* vf) {
2327 if (vf->is_java_frame()) {
2328 // java frame (interpreted, compiled, ...)
2329 javaVFrame* jvf = javaVFrame::cast(vf);
2330
2331 jmethodID method = jvf->method()->jmethod_id();
2332
2333 if (!(jvf->method()->is_native())) {
2334 jlocation bci = (jlocation)jvf->bci();
2335 StackValueCollection* locals = jvf->locals();
2336 if (!report_java_stack_refs(locals, method, bci, 0)) {
2337 return false;
2338 }
2339 if (!report_java_stack_refs(jvf->expressions(), method, bci, locals->size())) {
2340 return false;
2341 }
2342
2343 // Follow oops from compiled nmethod.
2344 if (jvf->cb() != nullptr && jvf->cb()->is_nmethod()) {
2345 _blk->set_context(_thread_tag, _tid, _depth, method);
2346 // Need to apply load barriers for unmounted vthreads.
2347 nmethod* nm = jvf->cb()->as_nmethod();
2348 nm->run_nmethod_entry_barrier();
2349 nm->oops_do(_blk);
2350 if (_blk->stopped()) {
2351 return false;
2352 }
2353 }
2354 } else {
2355 // native frame
2356 if (!report_native_stack_refs(method)) {
2357 return false;
2358 }
2359 }
2360 _last_entry_frame = nullptr;
2361 _depth++;
2362 } else {
2363 // externalVFrame - for an entry frame then we report the JNI locals
2364 // when we find the corresponding javaVFrame
2365 frame* fr = vf->frame_pointer();
2366 assert(fr != nullptr, "sanity check");
2367 if (fr->is_entry_frame()) {
2368 _last_entry_frame = fr;
2369 }
2370 }
2371
2372 _is_top_frame = false;
2373
2374 return true;
2375 }
2376
2377 bool StackRefCollector::process_frames(vframe* vf) {
2378 while (vf != nullptr) {
2379 if (!do_frame(vf)) {
2380 return false;
2381 }
2382 vf = vf->sender();
2383 }
2384 return true;
2385 }
2386
2387
2388 // A VM operation to iterate over objects that are reachable from
2389 // a set of roots or an initial object.
2390 //
2391 // For VM_HeapWalkOperation the set of roots used is :-
2392 //
2393 // - All JNI global references
2394 // - All inflated monitors
2395 // - All classes loaded by the boot class loader (or all classes
2396 // in the event that class unloading is disabled)
2397 // - All java threads
2398 // - For each java thread then all locals and JNI local references
2399 // on the thread's execution stack
2400 // - All visible/explainable objects from Universes::oops_do
2401 //
2402 class VM_HeapWalkOperation: public VM_Operation {
2403 private:
2404 enum {
2405 initial_visit_stack_size = 4000
2406 };
2407
2408 bool _is_advanced_heap_walk; // indicates FollowReferences
2409 JvmtiTagMap* _tag_map;
2410 Handle _initial_object;
2411 GrowableArray<oop>* _visit_stack; // the visit stack
2412
2413 JVMTIBitSet _bitset;
2414
2415 // Dead object tags in JvmtiTagMap
2416 GrowableArray<jlong>* _dead_objects;
2417
2418 bool _following_object_refs; // are we following object references
2419
2420 bool _reporting_primitive_fields; // optional reporting
2421 bool _reporting_primitive_array_values;
2422 bool _reporting_string_values;
2423
2424 GrowableArray<oop>* create_visit_stack() {
2425 return new (mtServiceability) GrowableArray<oop>(initial_visit_stack_size, mtServiceability);
2426 }
2427
2428 // accessors
2429 bool is_advanced_heap_walk() const { return _is_advanced_heap_walk; }
2430 JvmtiTagMap* tag_map() const { return _tag_map; }
2431 Handle initial_object() const { return _initial_object; }
2432
2433 bool is_following_references() const { return _following_object_refs; }
2434
2435 bool is_reporting_primitive_fields() const { return _reporting_primitive_fields; }
2436 bool is_reporting_primitive_array_values() const { return _reporting_primitive_array_values; }
2437 bool is_reporting_string_values() const { return _reporting_string_values; }
2438
2439 GrowableArray<oop>* visit_stack() const { return _visit_stack; }
2440
2441 // iterate over the various object types
2442 inline bool iterate_over_array(oop o);
2443 inline bool iterate_over_type_array(oop o);
2444 inline bool iterate_over_class(oop o);
2445 inline bool iterate_over_object(oop o);
2446
2447 // root collection
2448 inline bool collect_simple_roots();
2449 inline bool collect_stack_roots();
2450 inline bool collect_stack_refs(JavaThread* java_thread, JNILocalRootsClosure* blk);
2451 inline bool collect_vthread_stack_refs(oop vt);
2452
2453 // visit an object
2454 inline bool visit(oop o);
2455
2456 public:
2457 VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2458 Handle initial_object,
2459 BasicHeapWalkContext callbacks,
2460 const void* user_data,
2461 GrowableArray<jlong>* objects);
2462
2463 VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2464 Handle initial_object,
2465 AdvancedHeapWalkContext callbacks,
2466 const void* user_data,
2467 GrowableArray<jlong>* objects);
2468
2469 ~VM_HeapWalkOperation();
2470
2471 VMOp_Type type() const { return VMOp_HeapWalkOperation; }
2472 void doit();
2473 };
2474
2475
2476 VM_HeapWalkOperation::VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2477 Handle initial_object,
2478 BasicHeapWalkContext callbacks,
2479 const void* user_data,
2480 GrowableArray<jlong>* objects) {
2481 _is_advanced_heap_walk = false;
2482 _tag_map = tag_map;
2483 _initial_object = initial_object;
2484 _following_object_refs = (callbacks.object_ref_callback() != nullptr);
2485 _reporting_primitive_fields = false;
2486 _reporting_primitive_array_values = false;
2487 _reporting_string_values = false;
2488 _visit_stack = create_visit_stack();
2489 _dead_objects = objects;
2490
2491 CallbackInvoker::initialize_for_basic_heap_walk(tag_map, _visit_stack, user_data, callbacks, &_bitset);
2492 }
2493
2494 VM_HeapWalkOperation::VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2495 Handle initial_object,
2496 AdvancedHeapWalkContext callbacks,
2497 const void* user_data,
2498 GrowableArray<jlong>* objects) {
2499 _is_advanced_heap_walk = true;
2500 _tag_map = tag_map;
2501 _initial_object = initial_object;
2502 _following_object_refs = true;
2503 _reporting_primitive_fields = (callbacks.primitive_field_callback() != nullptr);;
2504 _reporting_primitive_array_values = (callbacks.array_primitive_value_callback() != nullptr);;
2505 _reporting_string_values = (callbacks.string_primitive_value_callback() != nullptr);;
2506 _visit_stack = create_visit_stack();
2507 _dead_objects = objects;
2508 CallbackInvoker::initialize_for_advanced_heap_walk(tag_map, _visit_stack, user_data, callbacks, &_bitset);
2509 }
2510
2511 VM_HeapWalkOperation::~VM_HeapWalkOperation() {
2512 if (_following_object_refs) {
2513 assert(_visit_stack != nullptr, "checking");
2514 delete _visit_stack;
2515 _visit_stack = nullptr;
2516 }
2517 }
2518
2519 // an array references its class and has a reference to
2520 // each element in the array
2521 inline bool VM_HeapWalkOperation::iterate_over_array(oop o) {
2522 objArrayOop array = objArrayOop(o);
2523
2524 // array reference to its class
2525 oop mirror = ObjArrayKlass::cast(array->klass())->java_mirror();
2526 if (!CallbackInvoker::report_class_reference(o, mirror)) {
2527 return false;
2528 }
2529
2530 // iterate over the array and report each reference to a
2531 // non-null element
2532 for (int index=0; index<array->length(); index++) {
2533 oop elem = array->obj_at(index);
2534 if (elem == nullptr) {
2535 continue;
2536 }
2537
2538 // report the array reference o[index] = elem
2539 if (!CallbackInvoker::report_array_element_reference(o, elem, index)) {
2540 return false;
2541 }
2542 }
2543 return true;
2544 }
2545
2546 // a type array references its class
2547 inline bool VM_HeapWalkOperation::iterate_over_type_array(oop o) {
2548 Klass* k = o->klass();
2549 oop mirror = k->java_mirror();
2550 if (!CallbackInvoker::report_class_reference(o, mirror)) {
2551 return false;
2552 }
2553
2554 // report the array contents if required
2555 if (is_reporting_primitive_array_values()) {
2556 if (!CallbackInvoker::report_primitive_array_values(o)) {
2557 return false;
2558 }
2559 }
2560 return true;
2561 }
2562
2563 #ifdef ASSERT
2564 // verify that a static oop field is in range
2565 static inline bool verify_static_oop(InstanceKlass* ik,
2566 oop mirror, int offset) {
2567 address obj_p = cast_from_oop<address>(mirror) + offset;
2568 address start = (address)InstanceMirrorKlass::start_of_static_fields(mirror);
2569 address end = start + (java_lang_Class::static_oop_field_count(mirror) * heapOopSize);
2570 assert(end >= start, "sanity check");
2571
2572 if (obj_p >= start && obj_p < end) {
2573 return true;
2574 } else {
2575 return false;
2576 }
2577 }
2578 #endif // #ifdef ASSERT
2579
2580 // a class references its super class, interfaces, class loader, ...
2581 // and finally its static fields
2582 inline bool VM_HeapWalkOperation::iterate_over_class(oop java_class) {
2583 int i;
2584 Klass* klass = java_lang_Class::as_Klass(java_class);
2585
2586 if (klass->is_instance_klass()) {
2587 InstanceKlass* ik = InstanceKlass::cast(klass);
2588
2589 // Ignore the class if it hasn't been initialized yet
2590 if (!ik->is_linked()) {
2591 return true;
2592 }
2593
2594 // get the java mirror
2595 oop mirror = klass->java_mirror();
2596
2597 // super (only if something more interesting than java.lang.Object)
2598 InstanceKlass* super_klass = ik->super();
2599 if (super_klass != nullptr && super_klass != vmClasses::Object_klass()) {
2600 oop super_oop = super_klass->java_mirror();
2601 if (!CallbackInvoker::report_superclass_reference(mirror, super_oop)) {
2602 return false;
2603 }
2604 }
2605
2606 // class loader
2607 oop cl = ik->class_loader();
2608 if (cl != nullptr) {
2609 if (!CallbackInvoker::report_class_loader_reference(mirror, cl)) {
2610 return false;
2611 }
2612 }
2613
2614 // protection domain
2615 oop pd = ik->protection_domain();
2616 if (pd != nullptr) {
2617 if (!CallbackInvoker::report_protection_domain_reference(mirror, pd)) {
2618 return false;
2619 }
2620 }
2621
2622 // signers
2623 oop signers = ik->signers();
2624 if (signers != nullptr) {
2625 if (!CallbackInvoker::report_signers_reference(mirror, signers)) {
2626 return false;
2627 }
2628 }
2629
2630 // references from the constant pool
2631 {
2632 ConstantPool* pool = ik->constants();
2633 for (int i = 1; i < pool->length(); i++) {
2634 constantTag tag = pool->tag_at(i).value();
2635 if (tag.is_string() || tag.is_klass() || tag.is_unresolved_klass()) {
2636 oop entry;
2637 if (tag.is_string()) {
2638 entry = pool->resolved_string_at(i);
2639 // If the entry is non-null it is resolved.
2640 if (entry == nullptr) {
2641 continue;
2642 }
2643 } else if (tag.is_klass()) {
2644 entry = pool->resolved_klass_at(i)->java_mirror();
2645 } else {
2646 // Code generated by JIT compilers might not resolve constant
2647 // pool entries. Treat them as resolved if they are loaded.
2648 assert(tag.is_unresolved_klass(), "must be");
2649 constantPoolHandle cp(Thread::current(), pool);
2650 Klass* klass = ConstantPool::klass_at_if_loaded(cp, i);
2651 if (klass == nullptr) {
2652 continue;
2653 }
2654 entry = klass->java_mirror();
2655 }
2656 if (!CallbackInvoker::report_constant_pool_reference(mirror, entry, (jint)i)) {
2657 return false;
2658 }
2659 }
2660 }
2661 }
2662
2663 // interfaces
2664 // (These will already have been reported as references from the constant pool
2665 // but are specified by IterateOverReachableObjects and must be reported).
2666 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
2667 for (i = 0; i < interfaces->length(); i++) {
2668 oop interf = interfaces->at(i)->java_mirror();
2669 if (interf == nullptr) {
2670 continue;
2671 }
2672 if (!CallbackInvoker::report_interface_reference(mirror, interf)) {
2673 return false;
2674 }
2675 }
2676
2677 // iterate over the static fields
2678
2679 ClassFieldMap* field_map = ClassFieldMap::create_map_of_static_fields(klass);
2680 for (i=0; i<field_map->field_count(); i++) {
2681 ClassFieldDescriptor* field = field_map->field_at(i);
2682 char type = field->field_type();
2683 if (!is_primitive_field_type(type)) {
2684 oop fld_o = mirror->obj_field(field->field_offset());
2685 assert(verify_static_oop(ik, mirror, field->field_offset()), "sanity check");
2686 if (fld_o != nullptr) {
2687 int slot = field->field_index();
2688 if (!CallbackInvoker::report_static_field_reference(mirror, fld_o, slot)) {
2689 delete field_map;
2690 return false;
2691 }
2692 }
2693 } else {
2694 if (is_reporting_primitive_fields()) {
2695 address addr = cast_from_oop<address>(mirror) + field->field_offset();
2696 int slot = field->field_index();
2697 if (!CallbackInvoker::report_primitive_static_field(mirror, slot, addr, type)) {
2698 delete field_map;
2699 return false;
2700 }
2701 }
2702 }
2703 }
2704 delete field_map;
2705
2706 return true;
2707 }
2708
2709 return true;
2710 }
2711
2712 // an object references a class and its instance fields
2713 // (static fields are ignored here as we report these as
2714 // references from the class).
2715 inline bool VM_HeapWalkOperation::iterate_over_object(oop o) {
2716 // reference to the class
2717 if (!CallbackInvoker::report_class_reference(o, o->klass()->java_mirror())) {
2718 return false;
2719 }
2720
2721 // iterate over instance fields
2722 ClassFieldMap* field_map = JvmtiCachedClassFieldMap::get_map_of_instance_fields(o);
2723 for (int i=0; i<field_map->field_count(); i++) {
2724 ClassFieldDescriptor* field = field_map->field_at(i);
2725 char type = field->field_type();
2726 if (!is_primitive_field_type(type)) {
2727 oop fld_o = o->obj_field_access<AS_NO_KEEPALIVE | ON_UNKNOWN_OOP_REF>(field->field_offset());
2728 // ignore any objects that aren't visible to profiler
2729 if (fld_o != nullptr) {
2730 assert(Universe::heap()->is_in(fld_o), "unsafe code should not "
2731 "have references to Klass* anymore");
2732 int slot = field->field_index();
2733 if (!CallbackInvoker::report_field_reference(o, fld_o, slot)) {
2734 return false;
2735 }
2736 }
2737 } else {
2738 if (is_reporting_primitive_fields()) {
2739 // primitive instance field
2740 address addr = cast_from_oop<address>(o) + field->field_offset();
2741 int slot = field->field_index();
2742 if (!CallbackInvoker::report_primitive_instance_field(o, slot, addr, type)) {
2743 return false;
2744 }
2745 }
2746 }
2747 }
2748
2749 // if the object is a java.lang.String
2750 if (is_reporting_string_values() &&
2751 o->klass() == vmClasses::String_klass()) {
2752 if (!CallbackInvoker::report_string_value(o)) {
2753 return false;
2754 }
2755 }
2756 return true;
2757 }
2758
2759
2760 // Collects all simple (non-stack) roots except for threads;
2761 // threads are handled in collect_stack_roots() as an optimization.
2762 // if there's a heap root callback provided then the callback is
2763 // invoked for each simple root.
2764 // if an object reference callback is provided then all simple
2765 // roots are pushed onto the marking stack so that they can be
2766 // processed later
2767 //
2768 inline bool VM_HeapWalkOperation::collect_simple_roots() {
2769 SimpleRootsClosure blk;
2770
2771 // JNI globals
2772 blk.set_kind(JVMTI_HEAP_REFERENCE_JNI_GLOBAL);
2773 JNIHandles::oops_do(&blk);
2774 if (blk.stopped()) {
2775 return false;
2776 }
2777
2778 // Preloaded classes and loader from the system dictionary
2779 blk.set_kind(JVMTI_HEAP_REFERENCE_SYSTEM_CLASS);
2780 CLDToOopClosure cld_closure(&blk, ClassLoaderData::_claim_none);
2781 ClassLoaderDataGraph::always_strong_cld_do(&cld_closure);
2782 if (blk.stopped()) {
2783 return false;
2784 }
2785
2786 // threads are now handled in collect_stack_roots()
2787
2788 // Other kinds of roots maintained by HotSpot
2789 // Many of these won't be visible but others (such as instances of important
2790 // exceptions) will be visible.
2791 blk.set_kind(JVMTI_HEAP_REFERENCE_OTHER);
2792 Universe::vm_global()->oops_do(&blk);
2793 if (blk.stopped()) {
2794 return false;
2795 }
2796
2797 return true;
2798 }
2799
2800 // Reports the thread as JVMTI_HEAP_REFERENCE_THREAD,
2801 // walks the stack of the thread, finds all references (locals
2802 // and JNI calls) and reports these as stack references.
2803 inline bool VM_HeapWalkOperation::collect_stack_refs(JavaThread* java_thread,
2804 JNILocalRootsClosure* blk)
2805 {
2806 oop threadObj = java_thread->threadObj();
2807 oop mounted_vt = java_thread->is_vthread_mounted() ? java_thread->vthread() : nullptr;
2808 if (mounted_vt != nullptr && !JvmtiEnvBase::is_vthread_alive(mounted_vt)) {
2809 mounted_vt = nullptr;
2810 }
2811 assert(threadObj != nullptr, "sanity check");
2812
2813 StackRefCollector stack_collector(tag_map(), blk, java_thread);
2814
2815 if (!java_thread->has_last_Java_frame()) {
2816 if (!stack_collector.set_thread(JVMTI_HEAP_REFERENCE_THREAD, threadObj)) {
2817 return false;
2818 }
2819 // no last java frame but there may be JNI locals
2820 blk->set_context(tag_for(_tag_map, threadObj), java_lang_Thread::thread_id(threadObj), 0, (jmethodID)nullptr);
2821 java_thread->active_handles()->oops_do(blk);
2822 return !blk->stopped();
2823 }
2824 // vframes are resource allocated
2825 Thread* current_thread = Thread::current();
2826 ResourceMark rm(current_thread);
2827 HandleMark hm(current_thread);
2828
2829 RegisterMap reg_map(java_thread,
2830 RegisterMap::UpdateMap::include,
2831 RegisterMap::ProcessFrames::include,
2832 RegisterMap::WalkContinuation::include);
2833
2834 // first handle mounted vthread (if any)
2835 if (mounted_vt != nullptr) {
2836 frame f = java_thread->last_frame();
2837 vframe* vf = vframe::new_vframe(&f, ®_map, java_thread);
2838 // report virtual thread as JVMTI_HEAP_REFERENCE_OTHER
2839 if (!stack_collector.set_thread(JVMTI_HEAP_REFERENCE_OTHER, mounted_vt)) {
2840 return false;
2841 }
2842 // split virtual thread and carrier thread stacks by vthread entry ("enterSpecial") frame,
2843 // consider vthread entry frame as the last vthread stack frame
2844 while (vf != nullptr) {
2845 if (!stack_collector.do_frame(vf)) {
2846 return false;
2847 }
2848 if (vf->is_vthread_entry()) {
2849 break;
2850 }
2851 vf = vf->sender();
2852 }
2853 }
2854 // Platform or carrier thread.
2855 vframe* vf = JvmtiEnvBase::get_cthread_last_java_vframe(java_thread, ®_map);
2856 if (!stack_collector.set_thread(JVMTI_HEAP_REFERENCE_THREAD, threadObj)) {
2857 return false;
2858 }
2859 return stack_collector.process_frames(vf);
2860 }
2861
2862
2863 // Collects the simple roots for all threads and collects all
2864 // stack roots - for each thread it walks the execution
2865 // stack to find all references and local JNI refs.
2866 inline bool VM_HeapWalkOperation::collect_stack_roots() {
2867 JNILocalRootsClosure blk;
2868 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
2869 oop threadObj = thread->threadObj();
2870 if (threadObj != nullptr && !thread->is_exiting() && !thread->is_hidden_from_external_view()) {
2871 if (!collect_stack_refs(thread, &blk)) {
2872 return false;
2873 }
2874 }
2875 }
2876 return true;
2877 }
2878
2879 // Reports stack references for the unmounted virtual thread.
2880 inline bool VM_HeapWalkOperation::collect_vthread_stack_refs(oop vt) {
2881 if (!JvmtiEnvBase::is_vthread_alive(vt)) {
2882 return true;
2883 }
2884 ContinuationWrapper cont(java_lang_VirtualThread::continuation(vt));
2885 if (cont.is_empty()) {
2886 return true;
2887 }
2888 assert(!cont.is_mounted(), "sanity check");
2889
2890 stackChunkOop chunk = cont.last_nonempty_chunk();
2891 if (chunk == nullptr || chunk->is_empty()) {
2892 return true;
2893 }
2894
2895 // vframes are resource allocated
2896 Thread* current_thread = Thread::current();
2897 ResourceMark rm(current_thread);
2898 HandleMark hm(current_thread);
2899
2900 RegisterMap reg_map(cont.continuation(), RegisterMap::UpdateMap::include);
2901
2902 JNILocalRootsClosure blk;
2903 // JavaThread is not required for unmounted virtual threads
2904 StackRefCollector stack_collector(tag_map(), &blk, nullptr);
2905 // reference to the vthread is already reported
2906 if (!stack_collector.set_thread(vt)) {
2907 return false;
2908 }
2909
2910 frame fr = chunk->top_frame(®_map);
2911 vframe* vf = vframe::new_vframe(&fr, ®_map, nullptr);
2912 return stack_collector.process_frames(vf);
2913 }
2914
2915 // visit an object
2916 // first mark the object as visited
2917 // second get all the outbound references from this object (in other words, all
2918 // the objects referenced by this object).
2919 //
2920 bool VM_HeapWalkOperation::visit(oop o) {
2921 // mark object as visited
2922 assert(!_bitset.is_marked(o), "can't visit same object more than once");
2923 _bitset.mark_obj(o);
2924
2925 // instance
2926 if (o->is_instance()) {
2927 if (o->klass() == vmClasses::Class_klass()) {
2928 if (!java_lang_Class::is_primitive(o)) {
2929 // a java.lang.Class
2930 return iterate_over_class(o);
2931 }
2932 } else {
2933 // we report stack references only when initial object is not specified
2934 // (in the case we start from heap roots which include platform thread stack references)
2935 if (initial_object().is_null() && java_lang_VirtualThread::is_subclass(o->klass())) {
2936 if (!collect_vthread_stack_refs(o)) {
2937 return false;
2938 }
2939 }
2940 return iterate_over_object(o);
2941 }
2942 }
2943
2944 // object array
2945 if (o->is_objArray()) {
2946 return iterate_over_array(o);
2947 }
2948
2949 // type array
2950 if (o->is_typeArray()) {
2951 return iterate_over_type_array(o);
2952 }
2953
2954 return true;
2955 }
2956
2957 void VM_HeapWalkOperation::doit() {
2958 ResourceMark rm;
2959 ClassFieldMapCacheMark cm;
2960
2961 JvmtiTagMap::check_hashmaps_for_heapwalk(_dead_objects);
2962
2963 assert(visit_stack()->is_empty(), "visit stack must be empty");
2964
2965 // the heap walk starts with an initial object or the heap roots
2966 if (initial_object().is_null()) {
2967 // can result in a big performance boost for an agent that is
2968 // focused on analyzing references in the thread stacks.
2969 if (!collect_stack_roots()) return;
2970
2971 if (!collect_simple_roots()) return;
2972 } else {
2973 visit_stack()->push(initial_object()());
2974 }
2975
2976 // object references required
2977 if (is_following_references()) {
2978
2979 // visit each object until all reachable objects have been
2980 // visited or the callback asked to terminate the iteration.
2981 while (!visit_stack()->is_empty()) {
2982 oop o = visit_stack()->pop();
2983 if (!_bitset.is_marked(o)) {
2984 if (!visit(o)) {
2985 break;
2986 }
2987 }
2988 }
2989 }
2990 }
2991
2992 // iterate over all objects that are reachable from a set of roots
2993 void JvmtiTagMap::iterate_over_reachable_objects(jvmtiHeapRootCallback heap_root_callback,
2994 jvmtiStackReferenceCallback stack_ref_callback,
2995 jvmtiObjectReferenceCallback object_ref_callback,
2996 const void* user_data) {
2997 // VTMS transitions must be disabled before the EscapeBarrier.
2998 JvmtiVTMSTransitionDisabler disabler;
2999
3000 JavaThread* jt = JavaThread::current();
3001 EscapeBarrier eb(true, jt);
3002 eb.deoptimize_objects_all_threads();
3003 Arena dead_object_arena(mtServiceability);
3004 GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3005
3006 {
3007 MutexLocker ml(Heap_lock);
3008 BasicHeapWalkContext context(heap_root_callback, stack_ref_callback, object_ref_callback);
3009 VM_HeapWalkOperation op(this, Handle(), context, user_data, &dead_objects);
3010 VMThread::execute(&op);
3011 }
3012 // Post events outside of Heap_lock
3013 post_dead_objects(&dead_objects);
3014 }
3015
3016 // iterate over all objects that are reachable from a given object
3017 void JvmtiTagMap::iterate_over_objects_reachable_from_object(jobject object,
3018 jvmtiObjectReferenceCallback object_ref_callback,
3019 const void* user_data) {
3020 oop obj = JNIHandles::resolve(object);
3021 Handle initial_object(Thread::current(), obj);
3022
3023 Arena dead_object_arena(mtServiceability);
3024 GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3025
3026 JvmtiVTMSTransitionDisabler disabler;
3027
3028 {
3029 MutexLocker ml(Heap_lock);
3030 BasicHeapWalkContext context(nullptr, nullptr, object_ref_callback);
3031 VM_HeapWalkOperation op(this, initial_object, context, user_data, &dead_objects);
3032 VMThread::execute(&op);
3033 }
3034 // Post events outside of Heap_lock
3035 post_dead_objects(&dead_objects);
3036 }
3037
3038 // follow references from an initial object or the GC roots
3039 void JvmtiTagMap::follow_references(jint heap_filter,
3040 Klass* klass,
3041 jobject object,
3042 const jvmtiHeapCallbacks* callbacks,
3043 const void* user_data)
3044 {
3045 // VTMS transitions must be disabled before the EscapeBarrier.
3046 JvmtiVTMSTransitionDisabler disabler;
3047
3048 oop obj = JNIHandles::resolve(object);
3049 JavaThread* jt = JavaThread::current();
3050 Handle initial_object(jt, obj);
3051 // EA based optimizations that are tagged or reachable from initial_object are already reverted.
3052 EscapeBarrier eb(initial_object.is_null() &&
3053 !(heap_filter & JVMTI_HEAP_FILTER_UNTAGGED),
3054 jt);
3055 eb.deoptimize_objects_all_threads();
3056
3057 Arena dead_object_arena(mtServiceability);
3058 GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3059
3060 {
3061 MutexLocker ml(Heap_lock);
3062 AdvancedHeapWalkContext context(heap_filter, klass, callbacks);
3063 VM_HeapWalkOperation op(this, initial_object, context, user_data, &dead_objects);
3064 VMThread::execute(&op);
3065 }
3066 // Post events outside of Heap_lock
3067 post_dead_objects(&dead_objects);
3068 }
3069
3070 // Verify gc_notification follows set_needs_cleaning.
3071 DEBUG_ONLY(static bool notified_needs_cleaning = false;)
3072
3073 void JvmtiTagMap::set_needs_cleaning() {
3074 assert(SafepointSynchronize::is_at_safepoint(), "called in gc pause");
3075 assert(Thread::current()->is_VM_thread(), "should be the VM thread");
3076 // Can't assert !notified_needs_cleaning; a partial GC might be upgraded
3077 // to a full GC and do this twice without intervening gc_notification.
3078 DEBUG_ONLY(notified_needs_cleaning = true;)
3079
3080 JvmtiEnvIterator it;
3081 for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
3082 JvmtiTagMap* tag_map = env->tag_map_acquire();
3083 if (tag_map != nullptr) {
3084 tag_map->_needs_cleaning = !tag_map->is_empty();
3085 }
3086 }
3087 }
3088
3089 void JvmtiTagMap::gc_notification(size_t num_dead_entries) {
3090 assert(notified_needs_cleaning, "missing GC notification");
3091 DEBUG_ONLY(notified_needs_cleaning = false;)
3092
3093 // Notify ServiceThread if there's work to do.
3094 {
3095 MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
3096 _has_object_free_events = (num_dead_entries != 0);
3097 if (_has_object_free_events) ml.notify_all();
3098 }
3099
3100 // If no dead entries then cancel cleaning requests.
3101 if (num_dead_entries == 0) {
3102 JvmtiEnvIterator it;
3103 for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
3104 JvmtiTagMap* tag_map = env->tag_map_acquire();
3105 if (tag_map != nullptr) {
3106 MutexLocker ml (tag_map->lock(), Mutex::_no_safepoint_check_flag);
3107 tag_map->_needs_cleaning = false;
3108 }
3109 }
3110 }
3111 }
3112
3113 // Used by ServiceThread to discover there is work to do.
3114 bool JvmtiTagMap::has_object_free_events_and_reset() {
3115 assert_lock_strong(Service_lock);
3116 bool result = _has_object_free_events;
3117 _has_object_free_events = false;
3118 return result;
3119 }
3120
3121 // Used by ServiceThread to clean up tagmaps.
3122 void JvmtiTagMap::flush_all_object_free_events() {
3123 JavaThread* thread = JavaThread::current();
3124 JvmtiEnvIterator it;
3125 for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
3126 JvmtiTagMap* tag_map = env->tag_map_acquire();
3127 if (tag_map != nullptr) {
3128 tag_map->flush_object_free_events();
3129 ThreadBlockInVM tbiv(thread); // Be safepoint-polite while looping.
3130 }
3131 }
3132 }