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