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