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