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