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