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