< prev index next >

src/hotspot/share/prims/jvmtiTagMap.cpp

Print this page

  53 #include "runtime/deoptimization.hpp"
  54 #include "runtime/frame.inline.hpp"
  55 #include "runtime/handles.inline.hpp"
  56 #include "runtime/interfaceSupport.inline.hpp"
  57 #include "runtime/javaCalls.hpp"
  58 #include "runtime/javaThread.inline.hpp"
  59 #include "runtime/jniHandles.inline.hpp"
  60 #include "runtime/mutex.hpp"
  61 #include "runtime/mutexLocker.hpp"
  62 #include "runtime/safepoint.hpp"
  63 #include "runtime/threadSMR.hpp"
  64 #include "runtime/timerTrace.hpp"
  65 #include "runtime/vframe.hpp"
  66 #include "runtime/vmOperations.hpp"
  67 #include "runtime/vmThread.hpp"
  68 #include "utilities/macros.hpp"
  69 #include "utilities/objectBitSet.inline.hpp"
  70 
  71 typedef ObjectBitSet<mtServiceability> JVMTIBitSet;
  72 





























































  73 bool JvmtiTagMap::_has_object_free_events = false;
  74 
  75 // create a JvmtiTagMap
  76 JvmtiTagMap::JvmtiTagMap(JvmtiEnv* env) :
  77   _env(env),
  78   _lock(Mutex::nosafepoint, "JvmtiTagMap_lock"),
  79   _needs_cleaning(false),
  80   _posting_events(false) {

  81 
  82   assert(JvmtiThreadState_lock->is_locked(), "sanity check");
  83   assert(((JvmtiEnvBase *)env)->tag_map() == nullptr, "tag map already exists for environment");
  84 
  85   _hashmap = new JvmtiTagMapTable();

  86 
  87   // finally add us to the environment
  88   ((JvmtiEnvBase *)env)->release_set_tag_map(this);
  89 }
  90 
  91 // destroy a JvmtiTagMap
  92 JvmtiTagMap::~JvmtiTagMap() {
  93 
  94   // no lock acquired as we assume the enclosing environment is
  95   // also being destroyed.
  96   ((JvmtiEnvBase *)_env)->set_tag_map(nullptr);
  97 
  98   // finally destroy the hashmap
  99   delete _hashmap;
 100   _hashmap = nullptr;

 101 }
 102 
 103 // Called by env_dispose() to reclaim memory before deallocation.
 104 // Remove all the entries but keep the empty table intact.
 105 // This needs the table lock.
 106 void JvmtiTagMap::clear() {
 107   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 108   _hashmap->clear();

 109 }
 110 
 111 // returns the tag map for the given environments. If the tag map
 112 // doesn't exist then it is created.
 113 JvmtiTagMap* JvmtiTagMap::tag_map_for(JvmtiEnv* env) {
 114   JvmtiTagMap* tag_map = ((JvmtiEnvBase*)env)->tag_map_acquire();
 115   if (tag_map == nullptr) {
 116     MutexLocker mu(JvmtiThreadState_lock);
 117     tag_map = ((JvmtiEnvBase*)env)->tag_map();
 118     if (tag_map == nullptr) {
 119       tag_map = new JvmtiTagMap(env);
 120     }
 121   } else {
 122     DEBUG_ONLY(JavaThread::current()->check_possible_safepoint());
 123   }
 124   return tag_map;
 125 }
 126 
 127 // iterate over all entries in the tag map.
 128 void JvmtiTagMap::entry_iterate(JvmtiTagMapKeyClosure* closure) {
 129   hashmap()->entry_iterate(closure);
 130 }
 131 
 132 // returns true if the hashmaps are empty
 133 bool JvmtiTagMap::is_empty() {
 134   assert(SafepointSynchronize::is_at_safepoint() || is_locked(), "checking");
 135   return hashmap()->is_empty();
 136 }
 137 
 138 // This checks for posting before operations that use
 139 // this tagmap table.
 140 void JvmtiTagMap::check_hashmap(GrowableArray<jlong>* objects) {
 141   assert(is_locked(), "checking");
 142 
 143   if (is_empty()) { return; }
 144 
 145   if (_needs_cleaning &&
 146       objects != nullptr &&
 147       env()->is_enabled(JVMTI_EVENT_OBJECT_FREE)) {
 148     remove_dead_entries_locked(objects);
 149   }
 150 }
 151 
 152 // This checks for posting and is called from the heap walks.
 153 void JvmtiTagMap::check_hashmaps_for_heapwalk(GrowableArray<jlong>* objects) {
 154   assert(SafepointSynchronize::is_at_safepoint(), "called from safepoints");
 155 
 156   // Verify that the tag map tables are valid and unconditionally post events
 157   // that are expected to be posted before gc_notification.
 158   JvmtiEnvIterator it;
 159   for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
 160     JvmtiTagMap* tag_map = env->tag_map_acquire();
 161     if (tag_map != nullptr) {
 162       // The ZDriver may be walking the hashmaps concurrently so this lock is needed.
 163       MutexLocker ml(tag_map->lock(), Mutex::_no_safepoint_check_flag);
 164       tag_map->check_hashmap(objects);
 165     }
 166   }
 167 }
 168 
 169 // Return the tag value for an object, or 0 if the object is
 170 // not tagged
 171 //
 172 static inline jlong tag_for(JvmtiTagMap* tag_map, oop o) {
 173   return tag_map->hashmap()->find(o);

















































































































































 174 }
 175 





























 176 // A CallbackWrapper is a support class for querying and tagging an object
 177 // around a callback to a profiler. The constructor does pre-callback
 178 // work to get the tag value, klass tag value, ... and the destructor
 179 // does the post-callback work of tagging or untagging the object.
 180 //
 181 // {
 182 //   CallbackWrapper wrapper(tag_map, o);
 183 //
 184 //   (*callback)(wrapper.klass_tag(), wrapper.obj_size(), wrapper.obj_tag_p(), ...)
 185 //
 186 // }
 187 // wrapper goes out of scope here which results in the destructor
 188 // checking to see if the object has been tagged, untagged, or the
 189 // tag value has changed.
 190 //
 191 class CallbackWrapper : public StackObj {
 192  private:
 193   JvmtiTagMap* _tag_map;
 194   JvmtiTagMapTable* _hashmap;
 195   oop _o;
 196   jlong _obj_size;
 197   jlong _obj_tag;
 198   jlong _klass_tag;
 199 
 200  protected:
 201   JvmtiTagMap* tag_map() const { return _tag_map; }
 202 
 203   // invoked post-callback to tag, untag, or update the tag of an object
 204   void inline post_callback_tag_update(oop o, JvmtiTagMapTable* hashmap,
 205                                        jlong obj_tag);
 206  public:
 207   CallbackWrapper(JvmtiTagMap* tag_map, oop o) {


 208     assert(Thread::current()->is_VM_thread() || tag_map->is_locked(),
 209            "MT unsafe or must be VM thread");
 210 
 211     // object to tag
 212     _o = o;
 213 
 214     // object size
 215     _obj_size = (jlong)_o->size() * wordSize;
 216 
 217     // record the context
 218     _tag_map = tag_map;
 219     _hashmap = tag_map->hashmap();



 220 
 221     // get object tag
 222     _obj_tag = _hashmap->find(_o);
 223 
 224     // get the class and the class's tag value
 225     assert(vmClasses::Class_klass()->is_mirror_instance_klass(), "Is not?");
 226 
 227     _klass_tag = tag_for(tag_map, _o->klass()->java_mirror());
 228   }
 229 
 230   ~CallbackWrapper() {
 231     post_callback_tag_update(_o, _hashmap, _obj_tag);
 232   }
 233 
 234   inline jlong* obj_tag_p()                     { return &_obj_tag; }
 235   inline jlong obj_size() const                 { return _obj_size; }
 236   inline jlong obj_tag() const                  { return _obj_tag; }
 237   inline jlong klass_tag() const                { return _klass_tag; }
 238 };
 239 
 240 // callback post-callback to tag, untag, or update the tag of an object
 241 void inline CallbackWrapper::post_callback_tag_update(oop o,
 242                                                       JvmtiTagMapTable* hashmap,
 243                                                       jlong obj_tag) {
 244   if (obj_tag == 0) {
 245     // callback has untagged the object, remove the entry if present
 246     hashmap->remove(o);
 247   } else {
 248     // object was previously tagged or not present - the callback may have
 249     // changed the tag value
 250     assert(Thread::current()->is_VM_thread(), "must be VMThread");
 251     hashmap->add(o, obj_tag);
 252   }
 253 }
 254 
 255 // An extended CallbackWrapper used when reporting an object reference
 256 // to the agent.
 257 //
 258 // {
 259 //   TwoOopCallbackWrapper wrapper(tag_map, referrer, o);
 260 //
 261 //   (*callback)(wrapper.klass_tag(),
 262 //               wrapper.obj_size(),
 263 //               wrapper.obj_tag_p()
 264 //               wrapper.referrer_tag_p(), ...)
 265 //
 266 // }
 267 // wrapper goes out of scope here which results in the destructor
 268 // checking to see if the referrer object has been tagged, untagged,
 269 // or the tag value has changed.
 270 //
 271 class TwoOopCallbackWrapper : public CallbackWrapper {
 272  private:

 273   bool _is_reference_to_self;
 274   JvmtiTagMapTable* _referrer_hashmap;
 275   oop _referrer;
 276   jlong _referrer_obj_tag;
 277   jlong _referrer_klass_tag;
 278   jlong* _referrer_tag_p;
 279 
 280   bool is_reference_to_self() const             { return _is_reference_to_self; }
 281 
 282  public:
 283   TwoOopCallbackWrapper(JvmtiTagMap* tag_map, oop referrer, oop o) :
 284     CallbackWrapper(tag_map, o)
 285   {
 286     // self reference needs to be handled in a special way
 287     _is_reference_to_self = (referrer == o);
 288 
 289     if (_is_reference_to_self) {
 290       _referrer_klass_tag = klass_tag();
 291       _referrer_tag_p = obj_tag_p();
 292     } else {
 293       _referrer = referrer;
 294       // record the context
 295       _referrer_hashmap = tag_map->hashmap();
 296 
 297       // get object tag
 298       _referrer_obj_tag = _referrer_hashmap->find(_referrer);
 299 
 300       _referrer_tag_p = &_referrer_obj_tag;
 301 
 302       // get referrer class tag.
 303       _referrer_klass_tag = tag_for(tag_map, _referrer->klass()->java_mirror());
 304     }
 305   }
 306 
 307   ~TwoOopCallbackWrapper() {
 308     if (!is_reference_to_self()) {
 309       post_callback_tag_update(_referrer,
 310                                _referrer_hashmap,
 311                                _referrer_obj_tag);
 312     }
 313   }
 314 
 315   // address of referrer tag
 316   // (for a self reference this will return the same thing as obj_tag_p())
 317   inline jlong* referrer_tag_p() { return _referrer_tag_p; }
 318 
 319   // referrer's class tag
 320   inline jlong referrer_klass_tag() { return _referrer_klass_tag; }
 321 };
 322 
 323 // tag an object
 324 //
 325 // This function is performance critical. If many threads attempt to tag objects
 326 // around the same time then it's possible that the Mutex associated with the
 327 // tag map will be a hot lock.
 328 void JvmtiTagMap::set_tag(jobject object, jlong tag) {
 329   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 330 
 331   // SetTag should not post events because the JavaThread has to
 332   // transition to native for the callback and this cannot stop for
 333   // safepoints with the hashmap lock held.
 334   check_hashmap(nullptr);  /* don't collect dead objects */
 335 
 336   // resolve the object
 337   oop o = JNIHandles::resolve_non_null(object);
 338 
 339   // see if the object is already tagged
 340   JvmtiTagMapTable* hashmap = _hashmap;
 341 
 342   if (tag == 0) {
 343     // remove the entry if present
 344     hashmap->remove(o);
 345   } else {
 346     // if the object is already tagged or not present then we add/update
 347     // the tag
 348     hashmap->add(o, tag);
 349   }
 350 }
 351 
 352 // get the tag for an object
 353 jlong JvmtiTagMap::get_tag(jobject object) {
 354   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 355 
 356   // GetTag should not post events because the JavaThread has to
 357   // transition to native for the callback and this cannot stop for
 358   // safepoints with the hashmap lock held.
 359   check_hashmap(nullptr); /* don't collect dead objects */
 360 
 361   // resolve the object
 362   oop o = JNIHandles::resolve_non_null(object);
 363 
 364   return tag_for(this, o);
 365 }
 366 
 367 
 368 // Helper class used to describe the static or instance fields of a class.
 369 // For each field it holds the field index (as defined by the JVMTI specification),
 370 // the field type, and the offset.
 371 
 372 class ClassFieldDescriptor: public CHeapObj<mtInternal> {
 373  private:
 374   int _field_index;
 375   int _field_offset;
 376   char _field_type;


 377  public:
 378   ClassFieldDescriptor(int index, char type, int offset) :
 379     _field_index(index), _field_offset(offset), _field_type(type) {










 380   }
 381   int field_index()  const  { return _field_index; }
 382   char field_type()  const  { return _field_type; }
 383   int field_offset() const  { return _field_offset; }



 384 };
 385 
 386 class ClassFieldMap: public CHeapObj<mtInternal> {
 387  private:
 388   enum {
 389     initial_field_count = 5
 390   };
 391 
 392   // list of field descriptors
 393   GrowableArray<ClassFieldDescriptor*>* _fields;
 394 
 395   // constructor
 396   ClassFieldMap();
 397 
 398   // calculates number of fields in all interfaces
 399   static int interfaces_field_count(InstanceKlass* ik);
 400 
 401   // add a field
 402   void add(int index, char type, int offset);
 403 
 404  public:
 405   ~ClassFieldMap();
 406 
 407   // access
 408   int field_count()                     { return _fields->length(); }
 409   ClassFieldDescriptor* field_at(int i) { return _fields->at(i); }
 410 
 411   // functions to create maps of static or instance fields
 412   static ClassFieldMap* create_map_of_static_fields(Klass* k);
 413   static ClassFieldMap* create_map_of_instance_fields(oop obj);
 414 };
 415 
 416 ClassFieldMap::ClassFieldMap() {
 417   _fields = new (mtServiceability)
 418     GrowableArray<ClassFieldDescriptor*>(initial_field_count, mtServiceability);
 419 }
 420 
 421 ClassFieldMap::~ClassFieldMap() {
 422   for (int i=0; i<_fields->length(); i++) {
 423     delete _fields->at(i);
 424   }
 425   delete _fields;
 426 }
 427 
 428 int ClassFieldMap::interfaces_field_count(InstanceKlass* ik) {
 429   const Array<InstanceKlass*>* interfaces = ik->transitive_interfaces();
 430   int count = 0;
 431   for (int i = 0; i < interfaces->length(); i++) {
 432     count += interfaces->at(i)->java_fields_count();
 433 
 434   }
 435   return count;
 436 }
 437 
 438 void ClassFieldMap::add(int index, char type, int offset) {
 439   ClassFieldDescriptor* field = new ClassFieldDescriptor(index, type, offset);
 440   _fields->append(field);
 441 }
 442 
 443 // Returns a heap allocated ClassFieldMap to describe the static fields
 444 // of the given class.
 445 ClassFieldMap* ClassFieldMap::create_map_of_static_fields(Klass* k) {
 446   InstanceKlass* ik = InstanceKlass::cast(k);
 447 
 448   // create the field map
 449   ClassFieldMap* field_map = new ClassFieldMap();
 450 
 451   // Static fields of interfaces and superclasses are reported as references from the interfaces/superclasses.
 452   // Need to calculate start index of this class fields: number of fields in all interfaces and superclasses.
 453   int index = interfaces_field_count(ik);
 454   for (InstanceKlass* super_klass = ik->super(); super_klass != nullptr; super_klass = super_klass->super()) {
 455     index += super_klass->java_fields_count();
 456   }
 457 
 458   for (JavaFieldStream fld(ik); !fld.done(); fld.next(), index++) {
 459     // ignore instance fields
 460     if (!fld.access_flags().is_static()) {
 461       continue;
 462     }
 463     field_map->add(index, fld.signature()->char_at(0), fld.offset());
 464   }
 465 
 466   return field_map;
 467 }
 468 
 469 // Returns a heap allocated ClassFieldMap to describe the instance fields
 470 // of the given class. All instance fields are included (this means public
 471 // and private fields declared in superclasses too).
 472 ClassFieldMap* ClassFieldMap::create_map_of_instance_fields(oop obj) {
 473   InstanceKlass* ik = InstanceKlass::cast(obj->klass());
 474 
 475   // create the field map
 476   ClassFieldMap* field_map = new ClassFieldMap();
 477 
 478   // fields of the superclasses are reported first, so need to know total field number to calculate field indices
 479   int total_field_number = interfaces_field_count(ik);
 480   for (InstanceKlass* klass = ik; klass != nullptr; klass = klass->super()) {
 481     total_field_number += klass->java_fields_count();
 482   }
 483 
 484   for (InstanceKlass* klass = ik; klass != nullptr; klass = klass->super()) {
 485     JavaFieldStream fld(klass);
 486     int start_index = total_field_number - klass->java_fields_count();
 487     for (int index = 0; !fld.done(); fld.next(), index++) {
 488       // ignore static fields
 489       if (fld.access_flags().is_static()) {
 490         continue;
 491       }
 492       field_map->add(start_index + index, fld.signature()->char_at(0), fld.offset());
 493     }
 494     // update total_field_number for superclass (decrease by the field count in the current class)
 495     total_field_number = start_index;
 496   }
 497 
 498   return field_map;
 499 }
 500 
 501 // Helper class used to cache a ClassFileMap for the instance fields of
 502 // a cache. A JvmtiCachedClassFieldMap can be cached by an InstanceKlass during
 503 // heap iteration and avoid creating a field map for each object in the heap
 504 // (only need to create the map when the first instance of a class is encountered).
 505 //
 506 class JvmtiCachedClassFieldMap : public CHeapObj<mtInternal> {
 507  private:
 508   enum {
 509      initial_class_count = 200
 510   };
 511   ClassFieldMap* _field_map;
 512 
 513   ClassFieldMap* field_map() const { return _field_map; }
 514 
 515   JvmtiCachedClassFieldMap(ClassFieldMap* field_map);
 516   ~JvmtiCachedClassFieldMap();
 517 
 518   static GrowableArray<InstanceKlass*>* _class_list;
 519   static void add_to_class_list(InstanceKlass* ik);
 520 
 521  public:
 522   // returns the field map for a given object (returning map cached
 523   // by InstanceKlass if possible
 524   static ClassFieldMap* get_map_of_instance_fields(oop obj);
 525 
 526   // removes the field map from all instanceKlasses - should be
 527   // called before VM operation completes
 528   static void clear_cache();
 529 
 530   // returns the number of ClassFieldMap cached by instanceKlasses
 531   static int cached_field_map_count();
 532 };
 533 
 534 GrowableArray<InstanceKlass*>* JvmtiCachedClassFieldMap::_class_list;
 535 
 536 JvmtiCachedClassFieldMap::JvmtiCachedClassFieldMap(ClassFieldMap* field_map) {
 537   _field_map = field_map;
 538 }
 539 
 540 JvmtiCachedClassFieldMap::~JvmtiCachedClassFieldMap() {
 541   if (_field_map != nullptr) {
 542     delete _field_map;
 543   }
 544 }

 556      _is_active = true;
 557    }
 558    ~ClassFieldMapCacheMark() {
 559      JvmtiCachedClassFieldMap::clear_cache();
 560      _is_active = false;
 561    }
 562    static bool is_active() { return _is_active; }
 563 };
 564 
 565 bool ClassFieldMapCacheMark::_is_active;
 566 
 567 // record that the given InstanceKlass is caching a field map
 568 void JvmtiCachedClassFieldMap::add_to_class_list(InstanceKlass* ik) {
 569   if (_class_list == nullptr) {
 570     _class_list = new (mtServiceability)
 571       GrowableArray<InstanceKlass*>(initial_class_count, mtServiceability);
 572   }
 573   _class_list->push(ik);
 574 }
 575 
 576 // returns the instance field map for the given object
 577 // (returns field map cached by the InstanceKlass if possible)
 578 ClassFieldMap* JvmtiCachedClassFieldMap::get_map_of_instance_fields(oop obj) {
 579   assert(Thread::current()->is_VM_thread(), "must be VMThread");
 580   assert(ClassFieldMapCacheMark::is_active(), "ClassFieldMapCacheMark not active");
 581 
 582   Klass* k = obj->klass();
 583   InstanceKlass* ik = InstanceKlass::cast(k);
 584 
 585   // return cached map if possible
 586   JvmtiCachedClassFieldMap* cached_map = ik->jvmti_cached_class_field_map();
 587   if (cached_map != nullptr) {
 588     assert(cached_map->field_map() != nullptr, "missing field list");
 589     return cached_map->field_map();
 590   } else {
 591     ClassFieldMap* field_map = ClassFieldMap::create_map_of_instance_fields(obj);
 592     cached_map = new JvmtiCachedClassFieldMap(field_map);
 593     ik->set_jvmti_cached_class_field_map(cached_map);
 594     add_to_class_list(ik);
 595     return field_map;
 596   }
 597 }
 598 
 599 // remove the fields maps cached from all instanceKlasses
 600 void JvmtiCachedClassFieldMap::clear_cache() {
 601   assert(Thread::current()->is_VM_thread(), "must be VMThread");
 602   if (_class_list != nullptr) {
 603     for (int i = 0; i < _class_list->length(); i++) {
 604       InstanceKlass* ik = _class_list->at(i);
 605       JvmtiCachedClassFieldMap* cached_map = ik->jvmti_cached_class_field_map();
 606       assert(cached_map != nullptr, "should not be null");
 607       ik->set_jvmti_cached_class_field_map(nullptr);
 608       delete cached_map;  // deletes the encapsulated field map
 609     }
 610     delete _class_list;
 611     _class_list = nullptr;

 623                                               int heap_filter) {
 624   // apply the heap filter
 625   if (obj_tag != 0) {
 626     // filter out tagged objects
 627     if (heap_filter & JVMTI_HEAP_FILTER_TAGGED) return true;
 628   } else {
 629     // filter out untagged objects
 630     if (heap_filter & JVMTI_HEAP_FILTER_UNTAGGED) return true;
 631   }
 632   if (klass_tag != 0) {
 633     // filter out objects with tagged classes
 634     if (heap_filter & JVMTI_HEAP_FILTER_CLASS_TAGGED) return true;
 635   } else {
 636     // filter out objects with untagged classes.
 637     if (heap_filter & JVMTI_HEAP_FILTER_CLASS_UNTAGGED) return true;
 638   }
 639   return false;
 640 }
 641 
 642 // helper function to indicate if an object is filtered by a klass filter
 643 static inline bool is_filtered_by_klass_filter(oop obj, Klass* klass_filter) {
 644   if (klass_filter != nullptr) {
 645     if (obj->klass() != klass_filter) {
 646       return true;
 647     }
 648   }
 649   return false;
 650 }
 651 
 652 // helper function to tell if a field is a primitive field or not
 653 static inline bool is_primitive_field_type(char type) {
 654   return (type != JVM_SIGNATURE_CLASS && type != JVM_SIGNATURE_ARRAY);
 655 }
 656 
 657 // helper function to copy the value from location addr to jvalue.
 658 static inline void copy_to_jvalue(jvalue *v, address addr, jvmtiPrimitiveType value_type) {
 659   switch (value_type) {
 660     case JVMTI_PRIMITIVE_TYPE_BOOLEAN : { v->z = *(jboolean*)addr; break; }
 661     case JVMTI_PRIMITIVE_TYPE_BYTE    : { v->b = *(jbyte*)addr;    break; }
 662     case JVMTI_PRIMITIVE_TYPE_CHAR    : { v->c = *(jchar*)addr;    break; }
 663     case JVMTI_PRIMITIVE_TYPE_SHORT   : { v->s = *(jshort*)addr;   break; }
 664     case JVMTI_PRIMITIVE_TYPE_INT     : { v->i = *(jint*)addr;     break; }
 665     case JVMTI_PRIMITIVE_TYPE_LONG    : { v->j = *(jlong*)addr;    break; }
 666     case JVMTI_PRIMITIVE_TYPE_FLOAT   : { v->f = *(jfloat*)addr;   break; }
 667     case JVMTI_PRIMITIVE_TYPE_DOUBLE  : { v->d = *(jdouble*)addr;  break; }
 668     default: ShouldNotReachHere();
 669   }
 670 }
 671 
 672 // helper function to invoke string primitive value callback
 673 // returns visit control flags
 674 static jint invoke_string_value_callback(jvmtiStringPrimitiveValueCallback cb,
 675                                          CallbackWrapper* wrapper,
 676                                          oop str,
 677                                          void* user_data)
 678 {


 679   assert(str->klass() == vmClasses::String_klass(), "not a string");
 680 
 681   typeArrayOop s_value = java_lang_String::value(str);
 682 
 683   // JDK-6584008: the value field may be null if a String instance is
 684   // partially constructed.
 685   if (s_value == nullptr) {
 686     return 0;
 687   }
 688   // get the string value and length
 689   // (string value may be offset from the base)
 690   int s_len = java_lang_String::length(str);
 691   bool is_latin1 = java_lang_String::is_latin1(str);
 692   jchar* value;
 693   if (s_len > 0) {
 694     if (!is_latin1) {
 695       value = s_value->char_at_addr(0);
 696     } else {
 697       // Inflate latin1 encoded string to UTF16
 698       jchar* buf = NEW_C_HEAP_ARRAY(jchar, s_len, mtInternal);

 707   }
 708 
 709   // invoke the callback
 710   jint res = (*cb)(wrapper->klass_tag(),
 711                    wrapper->obj_size(),
 712                    wrapper->obj_tag_p(),
 713                    value,
 714                    (jint)s_len,
 715                    user_data);
 716 
 717   if (is_latin1 && s_len > 0) {
 718     FREE_C_HEAP_ARRAY(jchar, value);
 719   }
 720   return res;
 721 }
 722 
 723 // helper function to invoke string primitive value callback
 724 // returns visit control flags
 725 static jint invoke_array_primitive_value_callback(jvmtiArrayPrimitiveValueCallback cb,
 726                                                   CallbackWrapper* wrapper,
 727                                                   oop obj,
 728                                                   void* user_data)
 729 {
 730   assert(obj->is_typeArray(), "not a primitive array");

 731 
 732   // get base address of first element
 733   typeArrayOop array = typeArrayOop(obj);
 734   BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
 735   void* elements = array->base(type);
 736 
 737   // jvmtiPrimitiveType is defined so this mapping is always correct
 738   jvmtiPrimitiveType elem_type = (jvmtiPrimitiveType)type2char(type);
 739 
 740   return (*cb)(wrapper->klass_tag(),
 741                wrapper->obj_size(),
 742                wrapper->obj_tag_p(),
 743                (jint)array->length(),
 744                elem_type,
 745                elements,
 746                user_data);
 747 }
 748 
 749 // helper function to invoke the primitive field callback for all static fields
 750 // of a given class
 751 static jint invoke_primitive_field_callback_for_static_fields
 752   (CallbackWrapper* wrapper,
 753    oop obj,

 803                      &reference_info,
 804                      wrapper->klass_tag(),
 805                      wrapper->obj_tag_p(),
 806                      value,
 807                      value_type,
 808                      user_data);
 809     if (res & JVMTI_VISIT_ABORT) {
 810       delete field_map;
 811       return res;
 812     }
 813   }
 814 
 815   delete field_map;
 816   return 0;
 817 }
 818 
 819 // helper function to invoke the primitive field callback for all instance fields
 820 // of a given object
 821 static jint invoke_primitive_field_callback_for_instance_fields(
 822   CallbackWrapper* wrapper,
 823   oop obj,
 824   jvmtiPrimitiveFieldCallback cb,
 825   void* user_data)
 826 {
 827   // for instance fields only the index will be set
 828   static jvmtiHeapReferenceInfo reference_info = { 0 };
 829 
 830   // get the map of the instance fields
 831   ClassFieldMap* fields = JvmtiCachedClassFieldMap::get_map_of_instance_fields(obj);
 832 
 833   // invoke the callback for each instance primitive field
 834   for (int i=0; i<fields->field_count(); i++) {
 835     ClassFieldDescriptor* field = fields->field_at(i);
 836 
 837     // ignore non-primitive fields
 838     char type = field->field_type();
 839     if (!is_primitive_field_type(type)) {
 840       continue;
 841     }
 842     // one-to-one mapping
 843     jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type;
 844 
 845     // get offset and field value
 846     int offset = field->field_offset();
 847     address addr = cast_from_oop<address>(obj) + offset;
 848     jvalue value;
 849     copy_to_jvalue(&value, addr, value_type);
 850 
 851     // field index
 852     reference_info.field.index = field->field_index();
 853 
 854     // invoke the callback
 855     jint res = (*cb)(JVMTI_HEAP_REFERENCE_FIELD,
 856                      &reference_info,
 857                      wrapper->klass_tag(),
 858                      wrapper->obj_tag_p(),
 859                      value,
 860                      value_type,
 861                      user_data);
 862     if (res & JVMTI_VISIT_ABORT) {
 863       return res;
 864     }
 865   }
 866   return 0;
 867 }

 941 
 942 // invoked for each object in the heap
 943 void IterateOverHeapObjectClosure::do_object(oop o) {
 944   assert(o != nullptr, "Heap iteration should never produce null!");
 945   // check if iteration has been halted
 946   if (is_iteration_aborted()) return;
 947 
 948   // instanceof check when filtering by klass
 949   if (klass() != nullptr && !o->is_a(klass())) {
 950     return;
 951   }
 952 
 953   // skip if object is a dormant shared object whose mirror hasn't been loaded
 954   if (o->klass()->java_mirror() == nullptr) {
 955     log_debug(aot, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(o),
 956                          o->klass()->external_name());
 957     return;
 958   }
 959 
 960   // prepare for the calllback
 961   CallbackWrapper wrapper(tag_map(), o);

 962 
 963   // if the object is tagged and we're only interested in untagged objects
 964   // then don't invoke the callback. Similarly, if the object is untagged
 965   // and we're only interested in tagged objects we skip the callback.
 966   if (wrapper.obj_tag() != 0) {
 967     if (object_filter() == JVMTI_HEAP_OBJECT_UNTAGGED) return;
 968   } else {
 969     if (object_filter() == JVMTI_HEAP_OBJECT_TAGGED) return;
 970   }
 971 
 972   // invoke the agent's callback
 973   jvmtiIterationControl control = (*object_callback())(wrapper.klass_tag(),
 974                                                        wrapper.obj_size(),
 975                                                        wrapper.obj_tag_p(),
 976                                                        (void*)user_data());
 977   if (control == JVMTI_ITERATION_ABORT) {
 978     set_iteration_aborted(true);
 979   }
 980 }
 981 

 993   int heap_filter() const                          { return _heap_filter; }
 994   const jvmtiHeapCallbacks* callbacks() const      { return _callbacks; }
 995   Klass* klass() const                             { return _klass; }
 996   const void* user_data() const                    { return _user_data; }
 997 
 998   // indicates if the iteration has been aborted
 999   bool _iteration_aborted;
1000   bool is_iteration_aborted() const                { return _iteration_aborted; }
1001 
1002   // used to check the visit control flags. If the abort flag is set
1003   // then we set the iteration aborted flag so that the iteration completes
1004   // without processing any further objects
1005   bool check_flags_for_abort(jint flags) {
1006     bool is_abort = (flags & JVMTI_VISIT_ABORT) != 0;
1007     if (is_abort) {
1008       _iteration_aborted = true;
1009     }
1010     return is_abort;
1011   }
1012 




1013  public:
1014   IterateThroughHeapObjectClosure(JvmtiTagMap* tag_map,
1015                                   Klass* klass,
1016                                   int heap_filter,
1017                                   const jvmtiHeapCallbacks* heap_callbacks,
1018                                   const void* user_data) :
1019     _tag_map(tag_map),
1020     _klass(klass),
1021     _heap_filter(heap_filter),
1022     _callbacks(heap_callbacks),
1023     _user_data(user_data),
1024     _iteration_aborted(false)
1025   {
1026   }
1027 
1028   void do_object(oop o);
1029 };
1030 
1031 // invoked for each object in the heap
1032 void IterateThroughHeapObjectClosure::do_object(oop obj) {
1033   assert(obj != nullptr, "Heap iteration should never produce null!");
1034   // check if iteration has been halted
1035   if (is_iteration_aborted()) return;
1036 
1037   // apply class filter
1038   if (is_filtered_by_klass_filter(obj, klass())) return;
1039 
1040   // skip if object is a dormant shared object whose mirror hasn't been loaded
1041   if (obj->klass()->java_mirror() == nullptr) {
1042     log_debug(aot, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(obj),
1043                          obj->klass()->external_name());
1044     return;
1045   }
1046 







1047   // prepare for callback
1048   CallbackWrapper wrapper(tag_map(), obj);
1049 
1050   // check if filtered by the heap filter
1051   if (is_filtered_by_heap_filter(wrapper.obj_tag(), wrapper.klass_tag(), heap_filter())) {
1052     return;
1053   }
1054 
1055   // for arrays we need the length, otherwise -1
1056   bool is_array = obj->is_array();
1057   int len = is_array ? arrayOop(obj)->length() : -1;
1058 
1059   // invoke the object callback (if callback is provided)
1060   if (callbacks()->heap_iteration_callback != nullptr) {
1061     jvmtiHeapIterationCallback cb = callbacks()->heap_iteration_callback;
1062     jint res = (*cb)(wrapper.klass_tag(),
1063                      wrapper.obj_size(),
1064                      wrapper.obj_tag_p(),
1065                      (jint)len,
1066                      (void*)user_data());
1067     if (check_flags_for_abort(res)) return;
1068   }
1069 
1070   // for objects and classes we report primitive fields if callback provided
1071   if (callbacks()->primitive_field_callback != nullptr && obj->is_instance()) {
1072     jint res;
1073     jvmtiPrimitiveFieldCallback cb = callbacks()->primitive_field_callback;
1074     if (obj->klass() == vmClasses::Class_klass()) {

1075       res = invoke_primitive_field_callback_for_static_fields(&wrapper,
1076                                                                     obj,
1077                                                                     cb,
1078                                                                     (void*)user_data());
1079     } else {
1080       res = invoke_primitive_field_callback_for_instance_fields(&wrapper,
1081                                                                       obj,
1082                                                                       cb,
1083                                                                       (void*)user_data());
1084     }
1085     if (check_flags_for_abort(res)) return;
1086   }
1087 
1088   // string callback
1089   if (!is_array &&
1090       callbacks()->string_primitive_value_callback != nullptr &&
1091       obj->klass() == vmClasses::String_klass()) {
1092     jint res = invoke_string_value_callback(
1093                 callbacks()->string_primitive_value_callback,
1094                 &wrapper,
1095                 obj,
1096                 (void*)user_data() );
1097     if (check_flags_for_abort(res)) return;
1098   }
1099 
1100   // array callback
1101   if (is_array &&
1102       callbacks()->array_primitive_value_callback != nullptr &&
1103       obj->is_typeArray()) {
1104     jint res = invoke_array_primitive_value_callback(
1105                callbacks()->array_primitive_value_callback,
1106                &wrapper,
1107                obj,
1108                (void*)user_data() );
1109     if (check_flags_for_abort(res)) return;
1110   }
1111 };
1112 

















































































1113 
1114 // Deprecated function to iterate over all objects in the heap
1115 void JvmtiTagMap::iterate_over_heap(jvmtiHeapObjectFilter object_filter,
1116                                     Klass* klass,
1117                                     jvmtiHeapObjectCallback heap_object_callback,
1118                                     const void* user_data)
1119 {
1120   // EA based optimizations on tagged objects are already reverted.
1121   EscapeBarrier eb(object_filter == JVMTI_HEAP_OBJECT_UNTAGGED ||
1122                    object_filter == JVMTI_HEAP_OBJECT_EITHER,
1123                    JavaThread::current());
1124   eb.deoptimize_objects_all_threads();
1125   Arena dead_object_arena(mtServiceability);
1126   GrowableArray <jlong> dead_objects(&dead_object_arena, 10, 0, 0);
1127   {
1128     MutexLocker ml(Heap_lock);
1129     IterateOverHeapObjectClosure blk(this,
1130                                      klass,
1131                                      object_filter,
1132                                      heap_object_callback,
1133                                      user_data);
1134     VM_HeapIterateOperation op(&blk, &dead_objects);
1135     VMThread::execute(&op);
1136   }


1137   // Post events outside of Heap_lock
1138   post_dead_objects(&dead_objects);
1139 }
1140 
1141 
1142 // Iterates over all objects in the heap
1143 void JvmtiTagMap::iterate_through_heap(jint heap_filter,
1144                                        Klass* klass,
1145                                        const jvmtiHeapCallbacks* callbacks,
1146                                        const void* user_data)
1147 {
1148   // EA based optimizations on tagged objects are already reverted.
1149   EscapeBarrier eb(!(heap_filter & JVMTI_HEAP_FILTER_UNTAGGED), JavaThread::current());
1150   eb.deoptimize_objects_all_threads();
1151 
1152   Arena dead_object_arena(mtServiceability);
1153   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
1154   {
1155     MutexLocker ml(Heap_lock);
1156     IterateThroughHeapObjectClosure blk(this,
1157                                         klass,
1158                                         heap_filter,
1159                                         callbacks,
1160                                         user_data);
1161     VM_HeapIterateOperation op(&blk, &dead_objects);
1162     VMThread::execute(&op);
1163   }


1164   // Post events outside of Heap_lock
1165   post_dead_objects(&dead_objects);
1166 }
1167 
1168 void JvmtiTagMap::remove_dead_entries_locked(GrowableArray<jlong>* objects) {
1169   assert(is_locked(), "precondition");
1170   if (_needs_cleaning) {
1171     // Recheck whether to post object free events under the lock.
1172     if (!env()->is_enabled(JVMTI_EVENT_OBJECT_FREE)) {
1173       objects = nullptr;
1174     }
1175     log_info(jvmti, table)("TagMap table needs cleaning%s",
1176                            ((objects != nullptr) ? " and posting" : ""));
1177     hashmap()->remove_dead_entries(objects);
1178     _needs_cleaning = false;
1179   }
1180 }
1181 
1182 void JvmtiTagMap::remove_dead_entries(GrowableArray<jlong>* objects) {
1183   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1184   remove_dead_entries_locked(objects);
1185 }
1186 
1187 void JvmtiTagMap::post_dead_objects(GrowableArray<jlong>* const objects) {
1188   assert(Thread::current()->is_Java_thread(), "Must post from JavaThread");
1189   if (objects != nullptr && objects->length() > 0) {
1190     JvmtiExport::post_object_free(env(), objects);
1191     log_info(jvmti, table)("%d free object posted", objects->length());
1192   }
1193 }
1194 
1195 void JvmtiTagMap::remove_and_post_dead_objects() {
1196   ResourceMark rm;
1197   GrowableArray<jlong> objects;

1310       if (error != JVMTI_ERROR_NONE) {
1311         if (object_result_ptr != nullptr) {
1312           _env->Deallocate((unsigned char*)object_result_ptr);
1313         }
1314         return error;
1315       }
1316       for (int i=0; i<count; i++) {
1317         (*tag_result_ptr)[i] = (jlong)_tag_results->at(i);
1318       }
1319     }
1320 
1321     *count_ptr = count;
1322     return JVMTI_ERROR_NONE;
1323   }
1324 };
1325 
1326 // return the list of objects with the specified tags
1327 jvmtiError JvmtiTagMap::get_objects_with_tags(const jlong* tags,
1328   jint count, jint* count_ptr, jobject** object_result_ptr, jlong** tag_result_ptr) {
1329 



1330   TagObjectCollector collector(env(), tags, count);
1331   {
1332     // iterate over all tagged objects
1333     MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1334     // Can't post ObjectFree events here from a JavaThread, so this
1335     // will race with the gc_notification thread in the tiny
1336     // window where the object is not marked but hasn't been notified that
1337     // it is collected yet.
1338     entry_iterate(&collector);
1339   }
1340   return collector.result(count_ptr, object_result_ptr, tag_result_ptr);
1341 }
1342 
1343 // helper to map a jvmtiHeapReferenceKind to an old style jvmtiHeapRootKind
1344 // (not performance critical as only used for roots)
1345 static jvmtiHeapRootKind toJvmtiHeapRootKind(jvmtiHeapReferenceKind kind) {
1346   switch (kind) {
1347     case JVMTI_HEAP_REFERENCE_JNI_GLOBAL:   return JVMTI_HEAP_ROOT_JNI_GLOBAL;
1348     case JVMTI_HEAP_REFERENCE_SYSTEM_CLASS: return JVMTI_HEAP_ROOT_SYSTEM_CLASS;
1349     case JVMTI_HEAP_REFERENCE_STACK_LOCAL:  return JVMTI_HEAP_ROOT_STACK_LOCAL;
1350     case JVMTI_HEAP_REFERENCE_JNI_LOCAL:    return JVMTI_HEAP_ROOT_JNI_LOCAL;
1351     case JVMTI_HEAP_REFERENCE_THREAD:       return JVMTI_HEAP_ROOT_THREAD;
1352     case JVMTI_HEAP_REFERENCE_OTHER:        return JVMTI_HEAP_ROOT_OTHER;
1353     default: ShouldNotReachHere();          return JVMTI_HEAP_ROOT_OTHER;
1354   }
1355 }
1356 
1357 // Base class for all heap walk contexts. The base class maintains a flag
1358 // to indicate if the context is valid or not.
1359 class HeapWalkContext {
1360  private:
1361   bool _valid;
1362  public:
1363   HeapWalkContext(bool valid)                   { _valid = valid; }
1364   void invalidate()                             { _valid = false; }
1365   bool is_valid() const                         { return _valid; }
1366 };
1367 
1368 // A basic heap walk context for the deprecated heap walking functions.
1369 // The context for a basic heap walk are the callbacks and fields used by
1370 // the referrer caching scheme.
1371 class BasicHeapWalkContext: public HeapWalkContext {
1372  private:
1373   jvmtiHeapRootCallback _heap_root_callback;
1374   jvmtiStackReferenceCallback _stack_ref_callback;
1375   jvmtiObjectReferenceCallback _object_ref_callback;
1376 
1377   // used for caching
1378   oop _last_referrer;
1379   jlong _last_referrer_tag;
1380 
1381  public:
1382   BasicHeapWalkContext() : HeapWalkContext(false) { }
1383 
1384   BasicHeapWalkContext(jvmtiHeapRootCallback heap_root_callback,
1385                        jvmtiStackReferenceCallback stack_ref_callback,
1386                        jvmtiObjectReferenceCallback object_ref_callback) :
1387     HeapWalkContext(true),
1388     _heap_root_callback(heap_root_callback),
1389     _stack_ref_callback(stack_ref_callback),
1390     _object_ref_callback(object_ref_callback),
1391     _last_referrer(nullptr),
1392     _last_referrer_tag(0) {
1393   }
1394 
1395   // accessors
1396   jvmtiHeapRootCallback heap_root_callback() const         { return _heap_root_callback; }
1397   jvmtiStackReferenceCallback stack_ref_callback() const   { return _stack_ref_callback; }
1398   jvmtiObjectReferenceCallback object_ref_callback() const { return _object_ref_callback;  }
1399 
1400   oop last_referrer() const               { return _last_referrer; }
1401   void set_last_referrer(oop referrer)    { _last_referrer = referrer; }
1402   jlong last_referrer_tag() const         { return _last_referrer_tag; }
1403   void set_last_referrer_tag(jlong value) { _last_referrer_tag = value; }
1404 };
1405 
1406 // The advanced heap walk context for the FollowReferences functions.
1407 // The context is the callbacks, and the fields used for filtering.
1408 class AdvancedHeapWalkContext: public HeapWalkContext {
1409  private:
1410   jint _heap_filter;
1411   Klass* _klass_filter;
1412   const jvmtiHeapCallbacks* _heap_callbacks;
1413 
1414  public:
1415   AdvancedHeapWalkContext() : HeapWalkContext(false) { }
1416 
1417   AdvancedHeapWalkContext(jint heap_filter,
1418                            Klass* klass_filter,
1419                            const jvmtiHeapCallbacks* heap_callbacks) :
1420     HeapWalkContext(true),
1421     _heap_filter(heap_filter),

1454   static bool is_basic_heap_walk()           { return _heap_walk_type == basic; }
1455   static bool is_advanced_heap_walk()        { return _heap_walk_type == advanced; }
1456 
1457   // context for basic style heap walk
1458   static BasicHeapWalkContext _basic_context;
1459   static BasicHeapWalkContext* basic_context() {
1460     assert(_basic_context.is_valid(), "invalid");
1461     return &_basic_context;
1462   }
1463 
1464   // context for advanced style heap walk
1465   static AdvancedHeapWalkContext _advanced_context;
1466   static AdvancedHeapWalkContext* advanced_context() {
1467     assert(_advanced_context.is_valid(), "invalid");
1468     return &_advanced_context;
1469   }
1470 
1471   // context needed for all heap walks
1472   static JvmtiTagMap* _tag_map;
1473   static const void* _user_data;
1474   static GrowableArray<oop>* _visit_stack;
1475   static JVMTIBitSet* _bitset;
1476 
1477   // accessors
1478   static JvmtiTagMap* tag_map()                        { return _tag_map; }
1479   static const void* user_data()                       { return _user_data; }
1480   static GrowableArray<oop>* visit_stack()             { return _visit_stack; }
1481 
1482   // if the object hasn't been visited then push it onto the visit stack
1483   // so that it will be visited later
1484   static inline bool check_for_visit(oop obj) {
1485     if (!_bitset->is_marked(obj)) visit_stack()->push(obj);
1486     return true;
1487   }
1488 










1489   // invoke basic style callbacks
1490   static inline bool invoke_basic_heap_root_callback
1491     (jvmtiHeapRootKind root_kind, oop obj);
1492   static inline bool invoke_basic_stack_ref_callback
1493     (jvmtiHeapRootKind root_kind, jlong thread_tag, jint depth, jmethodID method,
1494      int slot, oop obj);
1495   static inline bool invoke_basic_object_reference_callback
1496     (jvmtiObjectReferenceKind ref_kind, oop referrer, oop referree, jint index);
1497 
1498   // invoke advanced style callbacks
1499   static inline bool invoke_advanced_heap_root_callback
1500     (jvmtiHeapReferenceKind ref_kind, oop obj);
1501   static inline bool invoke_advanced_stack_ref_callback
1502     (jvmtiHeapReferenceKind ref_kind, jlong thread_tag, jlong tid, int depth,
1503      jmethodID method, jlocation bci, jint slot, oop obj);
1504   static inline bool invoke_advanced_object_reference_callback
1505     (jvmtiHeapReferenceKind ref_kind, oop referrer, oop referree, jint index);
1506 
1507   // used to report the value of primitive fields
1508   static inline bool report_primitive_field
1509     (jvmtiHeapReferenceKind ref_kind, oop obj, jint index, address addr, char type);
1510 
1511  public:
1512   // initialize for basic mode
1513   static void initialize_for_basic_heap_walk(JvmtiTagMap* tag_map,
1514                                              GrowableArray<oop>* visit_stack,
1515                                              const void* user_data,
1516                                              BasicHeapWalkContext context,
1517                                              JVMTIBitSet* bitset);
1518 
1519   // initialize for advanced mode
1520   static void initialize_for_advanced_heap_walk(JvmtiTagMap* tag_map,
1521                                                 GrowableArray<oop>* visit_stack,
1522                                                 const void* user_data,
1523                                                 AdvancedHeapWalkContext context,
1524                                                 JVMTIBitSet* bitset);
1525 
1526    // functions to report roots
1527   static inline bool report_simple_root(jvmtiHeapReferenceKind kind, oop o);
1528   static inline bool report_jni_local_root(jlong thread_tag, jlong tid, jint depth,
1529     jmethodID m, oop o);
1530   static inline bool report_stack_ref_root(jlong thread_tag, jlong tid, jint depth,
1531     jmethodID method, jlocation bci, jint slot, oop o);
1532 
1533   // functions to report references
1534   static inline bool report_array_element_reference(oop referrer, oop referree, jint index);
1535   static inline bool report_class_reference(oop referrer, oop referree);
1536   static inline bool report_class_loader_reference(oop referrer, oop referree);
1537   static inline bool report_signers_reference(oop referrer, oop referree);
1538   static inline bool report_protection_domain_reference(oop referrer, oop referree);
1539   static inline bool report_superclass_reference(oop referrer, oop referree);
1540   static inline bool report_interface_reference(oop referrer, oop referree);
1541   static inline bool report_static_field_reference(oop referrer, oop referree, jint slot);
1542   static inline bool report_field_reference(oop referrer, oop referree, jint slot);
1543   static inline bool report_constant_pool_reference(oop referrer, oop referree, jint index);
1544   static inline bool report_primitive_array_values(oop array);
1545   static inline bool report_string_value(oop str);
1546   static inline bool report_primitive_instance_field(oop o, jint index, address value, char type);
1547   static inline bool report_primitive_static_field(oop o, jint index, address value, char type);
1548 };
1549 
1550 // statics
1551 int CallbackInvoker::_heap_walk_type;
1552 BasicHeapWalkContext CallbackInvoker::_basic_context;
1553 AdvancedHeapWalkContext CallbackInvoker::_advanced_context;
1554 JvmtiTagMap* CallbackInvoker::_tag_map;
1555 const void* CallbackInvoker::_user_data;
1556 GrowableArray<oop>* CallbackInvoker::_visit_stack;
1557 JVMTIBitSet* CallbackInvoker::_bitset;
1558 
1559 // initialize for basic heap walk (IterateOverReachableObjects et al)
1560 void CallbackInvoker::initialize_for_basic_heap_walk(JvmtiTagMap* tag_map,
1561                                                      GrowableArray<oop>* visit_stack,
1562                                                      const void* user_data,
1563                                                      BasicHeapWalkContext context,
1564                                                      JVMTIBitSet* bitset) {
1565   _tag_map = tag_map;
1566   _visit_stack = visit_stack;
1567   _user_data = user_data;
1568   _basic_context = context;
1569   _advanced_context.invalidate();       // will trigger assertion if used
1570   _heap_walk_type = basic;
1571   _bitset = bitset;
1572 }
1573 
1574 // initialize for advanced heap walk (FollowReferences)
1575 void CallbackInvoker::initialize_for_advanced_heap_walk(JvmtiTagMap* tag_map,
1576                                                         GrowableArray<oop>* visit_stack,
1577                                                         const void* user_data,
1578                                                         AdvancedHeapWalkContext context,
1579                                                         JVMTIBitSet* bitset) {
1580   _tag_map = tag_map;
1581   _visit_stack = visit_stack;
1582   _user_data = user_data;
1583   _advanced_context = context;
1584   _basic_context.invalidate();      // will trigger assertion if used
1585   _heap_walk_type = advanced;
1586   _bitset = bitset;
1587 }
1588 
1589 
1590 // invoke basic style heap root callback
1591 inline bool CallbackInvoker::invoke_basic_heap_root_callback(jvmtiHeapRootKind root_kind, oop obj) {
1592   // if we heap roots should be reported
1593   jvmtiHeapRootCallback cb = basic_context()->heap_root_callback();
1594   if (cb == nullptr) {
1595     return check_for_visit(obj);
1596   }
1597 
1598   CallbackWrapper wrapper(tag_map(), obj);
1599   jvmtiIterationControl control = (*cb)(root_kind,
1600                                         wrapper.klass_tag(),
1601                                         wrapper.obj_size(),
1602                                         wrapper.obj_tag_p(),
1603                                         (void*)user_data());
1604   // push root to visit stack when following references
1605   if (control == JVMTI_ITERATION_CONTINUE &&
1606       basic_context()->object_ref_callback() != nullptr) {
1607     visit_stack()->push(obj);
1608   }
1609   return control != JVMTI_ITERATION_ABORT;
1610 }
1611 
1612 // invoke basic style stack ref callback
1613 inline bool CallbackInvoker::invoke_basic_stack_ref_callback(jvmtiHeapRootKind root_kind,
1614                                                              jlong thread_tag,
1615                                                              jint depth,
1616                                                              jmethodID method,
1617                                                              int slot,
1618                                                              oop obj) {
1619   // if we stack refs should be reported
1620   jvmtiStackReferenceCallback cb = basic_context()->stack_ref_callback();
1621   if (cb == nullptr) {
1622     return check_for_visit(obj);
1623   }
1624 
1625   CallbackWrapper wrapper(tag_map(), obj);
1626   jvmtiIterationControl control = (*cb)(root_kind,
1627                                         wrapper.klass_tag(),
1628                                         wrapper.obj_size(),
1629                                         wrapper.obj_tag_p(),
1630                                         thread_tag,
1631                                         depth,
1632                                         method,
1633                                         slot,
1634                                         (void*)user_data());
1635   // push root to visit stack when following references
1636   if (control == JVMTI_ITERATION_CONTINUE &&
1637       basic_context()->object_ref_callback() != nullptr) {
1638     visit_stack()->push(obj);
1639   }
1640   return control != JVMTI_ITERATION_ABORT;
1641 }
1642 
1643 // invoke basic style object reference callback
1644 inline bool CallbackInvoker::invoke_basic_object_reference_callback(jvmtiObjectReferenceKind ref_kind,
1645                                                                     oop referrer,
1646                                                                     oop referree,
1647                                                                     jint index) {
1648 
1649   BasicHeapWalkContext* context = basic_context();
1650 
1651   // callback requires the referrer's tag. If it's the same referrer
1652   // as the last call then we use the cached value.
1653   jlong referrer_tag;
1654   if (referrer == context->last_referrer()) {
1655     referrer_tag = context->last_referrer_tag();
1656   } else {
1657     referrer_tag = tag_for(tag_map(), referrer);
1658   }
1659 
1660   // do the callback
1661   CallbackWrapper wrapper(tag_map(), referree);
1662   jvmtiObjectReferenceCallback cb = context->object_ref_callback();
1663   jvmtiIterationControl control = (*cb)(ref_kind,
1664                                         wrapper.klass_tag(),
1665                                         wrapper.obj_size(),
1666                                         wrapper.obj_tag_p(),
1667                                         referrer_tag,
1668                                         index,
1669                                         (void*)user_data());
1670 
1671   // record referrer and referrer tag. For self-references record the
1672   // tag value from the callback as this might differ from referrer_tag.
1673   context->set_last_referrer(referrer);
1674   if (referrer == referree) {
1675     context->set_last_referrer_tag(*wrapper.obj_tag_p());
1676   } else {
1677     context->set_last_referrer_tag(referrer_tag);
1678   }
1679 
1680   if (control == JVMTI_ITERATION_CONTINUE) {
1681     return check_for_visit(referree);
1682   } else {
1683     return control != JVMTI_ITERATION_ABORT;
1684   }
1685 }
1686 
1687 // invoke advanced style heap root callback
1688 inline bool CallbackInvoker::invoke_advanced_heap_root_callback(jvmtiHeapReferenceKind ref_kind,
1689                                                                 oop obj) {
1690   AdvancedHeapWalkContext* context = advanced_context();
1691 
1692   // check that callback is provided
1693   jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
1694   if (cb == nullptr) {
1695     return check_for_visit(obj);
1696   }
1697 
1698   // apply class filter
1699   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1700     return check_for_visit(obj);
1701   }
1702 
1703   // setup the callback wrapper
1704   CallbackWrapper wrapper(tag_map(), obj);
1705 
1706   // apply tag filter
1707   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1708                                  wrapper.klass_tag(),
1709                                  context->heap_filter())) {
1710     return check_for_visit(obj);
1711   }
1712 
1713   // for arrays we need the length, otherwise -1
1714   jint len = (jint)(obj->is_array() ? arrayOop(obj)->length() : -1);
1715 
1716   // invoke the callback
1717   jint res  = (*cb)(ref_kind,
1718                     nullptr, // referrer info
1719                     wrapper.klass_tag(),
1720                     0,    // referrer_class_tag is 0 for heap root
1721                     wrapper.obj_size(),
1722                     wrapper.obj_tag_p(),
1723                     nullptr, // referrer_tag_p
1724                     len,
1725                     (void*)user_data());
1726   if (res & JVMTI_VISIT_ABORT) {
1727     return false;// referrer class tag
1728   }
1729   if (res & JVMTI_VISIT_OBJECTS) {
1730     check_for_visit(obj);
1731   }
1732   return true;
1733 }
1734 
1735 // report a reference from a thread stack to an object
1736 inline bool CallbackInvoker::invoke_advanced_stack_ref_callback(jvmtiHeapReferenceKind ref_kind,
1737                                                                 jlong thread_tag,
1738                                                                 jlong tid,
1739                                                                 int depth,
1740                                                                 jmethodID method,
1741                                                                 jlocation bci,
1742                                                                 jint slot,
1743                                                                 oop obj) {
1744   AdvancedHeapWalkContext* context = advanced_context();
1745 
1746   // check that callback is provider
1747   jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
1748   if (cb == nullptr) {
1749     return check_for_visit(obj);
1750   }
1751 
1752   // apply class filter
1753   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1754     return check_for_visit(obj);
1755   }
1756 
1757   // setup the callback wrapper
1758   CallbackWrapper wrapper(tag_map(), obj);
1759 
1760   // apply tag filter
1761   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1762                                  wrapper.klass_tag(),
1763                                  context->heap_filter())) {
1764     return check_for_visit(obj);
1765   }
1766 
1767   // setup the referrer info
1768   jvmtiHeapReferenceInfo reference_info;
1769   reference_info.stack_local.thread_tag = thread_tag;
1770   reference_info.stack_local.thread_id = tid;
1771   reference_info.stack_local.depth = depth;
1772   reference_info.stack_local.method = method;
1773   reference_info.stack_local.location = bci;
1774   reference_info.stack_local.slot = slot;
1775 
1776   // for arrays we need the length, otherwise -1
1777   jint len = (jint)(obj->is_array() ? arrayOop(obj)->length() : -1);
1778 
1779   // call into the agent
1780   int res = (*cb)(ref_kind,
1781                   &reference_info,
1782                   wrapper.klass_tag(),
1783                   0,    // referrer_class_tag is 0 for heap root (stack)
1784                   wrapper.obj_size(),
1785                   wrapper.obj_tag_p(),
1786                   nullptr, // referrer_tag is 0 for root
1787                   len,
1788                   (void*)user_data());
1789 
1790   if (res & JVMTI_VISIT_ABORT) {
1791     return false;
1792   }
1793   if (res & JVMTI_VISIT_OBJECTS) {
1794     check_for_visit(obj);
1795   }
1796   return true;
1797 }
1798 
1799 // This mask is used to pass reference_info to a jvmtiHeapReferenceCallback
1800 // only for ref_kinds defined by the JVM TI spec. Otherwise, null is passed.
1801 #define REF_INFO_MASK  ((1 << JVMTI_HEAP_REFERENCE_FIELD)         \
1802                       | (1 << JVMTI_HEAP_REFERENCE_STATIC_FIELD)  \
1803                       | (1 << JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT) \
1804                       | (1 << JVMTI_HEAP_REFERENCE_CONSTANT_POOL) \
1805                       | (1 << JVMTI_HEAP_REFERENCE_STACK_LOCAL)   \
1806                       | (1 << JVMTI_HEAP_REFERENCE_JNI_LOCAL))
1807 
1808 // invoke the object reference callback to report a reference
1809 inline bool CallbackInvoker::invoke_advanced_object_reference_callback(jvmtiHeapReferenceKind ref_kind,
1810                                                                        oop referrer,
1811                                                                        oop obj,
1812                                                                        jint index)
1813 {
1814   // field index is only valid field in reference_info
1815   static jvmtiHeapReferenceInfo reference_info = { 0 };
1816 
1817   AdvancedHeapWalkContext* context = advanced_context();
1818 
1819   // check that callback is provider
1820   jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
1821   if (cb == nullptr) {
1822     return check_for_visit(obj);
1823   }
1824 
1825   // apply class filter
1826   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1827     return check_for_visit(obj);
1828   }
1829 
1830   // setup the callback wrapper
1831   TwoOopCallbackWrapper wrapper(tag_map(), referrer, obj);
1832 
1833   // apply tag filter
1834   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1835                                  wrapper.klass_tag(),
1836                                  context->heap_filter())) {
1837     return check_for_visit(obj);
1838   }
1839 
1840   // field index is only valid field in reference_info
1841   reference_info.field.index = index;
1842 
1843   // for arrays we need the length, otherwise -1
1844   jint len = (jint)(obj->is_array() ? arrayOop(obj)->length() : -1);
1845 
1846   // invoke the callback
1847   int res = (*cb)(ref_kind,
1848                   (REF_INFO_MASK & (1 << ref_kind)) ? &reference_info : nullptr,
1849                   wrapper.klass_tag(),
1850                   wrapper.referrer_klass_tag(),
1851                   wrapper.obj_size(),
1852                   wrapper.obj_tag_p(),
1853                   wrapper.referrer_tag_p(),
1854                   len,
1855                   (void*)user_data());
1856 
1857   if (res & JVMTI_VISIT_ABORT) {
1858     return false;
1859   }
1860   if (res & JVMTI_VISIT_OBJECTS) {
1861     check_for_visit(obj);
1862   }
1863   return true;
1864 }
1865 
1866 // report a "simple root"
1867 inline bool CallbackInvoker::report_simple_root(jvmtiHeapReferenceKind kind, oop obj) {
1868   assert(kind != JVMTI_HEAP_REFERENCE_STACK_LOCAL &&
1869          kind != JVMTI_HEAP_REFERENCE_JNI_LOCAL, "not a simple root");
1870 
1871   if (is_basic_heap_walk()) {
1872     // map to old style root kind
1873     jvmtiHeapRootKind root_kind = toJvmtiHeapRootKind(kind);
1874     return invoke_basic_heap_root_callback(root_kind, obj);
1875   } else {
1876     assert(is_advanced_heap_walk(), "wrong heap walk type");
1877     return invoke_advanced_heap_root_callback(kind, obj);
1878   }
1879 }
1880 
1881 
1882 // invoke the primitive array values
1883 inline bool CallbackInvoker::report_primitive_array_values(oop obj) {
1884   assert(obj->is_typeArray(), "not a primitive array");
1885 
1886   AdvancedHeapWalkContext* context = advanced_context();
1887   assert(context->array_primitive_value_callback() != nullptr, "no callback");
1888 
1889   // apply class filter
1890   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1891     return true;
1892   }
1893 
1894   CallbackWrapper wrapper(tag_map(), obj);
1895 
1896   // apply tag filter
1897   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1898                                  wrapper.klass_tag(),
1899                                  context->heap_filter())) {
1900     return true;
1901   }
1902 
1903   // invoke the callback
1904   int res = invoke_array_primitive_value_callback(context->array_primitive_value_callback(),
1905                                                   &wrapper,
1906                                                   obj,
1907                                                   (void*)user_data());
1908   return (!(res & JVMTI_VISIT_ABORT));
1909 }
1910 
1911 // invoke the string value callback
1912 inline bool CallbackInvoker::report_string_value(oop str) {
1913   assert(str->klass() == vmClasses::String_klass(), "not a string");
1914 
1915   AdvancedHeapWalkContext* context = advanced_context();
1916   assert(context->string_primitive_value_callback() != nullptr, "no callback");
1917 
1918   // apply class filter
1919   if (is_filtered_by_klass_filter(str, context->klass_filter())) {
1920     return true;
1921   }
1922 
1923   CallbackWrapper wrapper(tag_map(), str);
1924 
1925   // apply tag filter
1926   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1927                                  wrapper.klass_tag(),
1928                                  context->heap_filter())) {
1929     return true;
1930   }
1931 
1932   // invoke the callback
1933   int res = invoke_string_value_callback(context->string_primitive_value_callback(),
1934                                          &wrapper,
1935                                          str,
1936                                          (void*)user_data());
1937   return (!(res & JVMTI_VISIT_ABORT));
1938 }
1939 
1940 // invoke the primitive field callback
1941 inline bool CallbackInvoker::report_primitive_field(jvmtiHeapReferenceKind ref_kind,
1942                                                     oop obj,
1943                                                     jint index,
1944                                                     address addr,
1945                                                     char type)
1946 {
1947   // for primitive fields only the index will be set
1948   static jvmtiHeapReferenceInfo reference_info = { 0 };
1949 
1950   AdvancedHeapWalkContext* context = advanced_context();
1951   assert(context->primitive_field_callback() != nullptr, "no callback");
1952 
1953   // apply class filter
1954   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
1955     return true;
1956   }
1957 
1958   CallbackWrapper wrapper(tag_map(), obj);
1959 
1960   // apply tag filter
1961   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
1962                                  wrapper.klass_tag(),

1970   // map the type
1971   jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type;
1972 
1973   // setup the jvalue
1974   jvalue value;
1975   copy_to_jvalue(&value, addr, value_type);
1976 
1977   jvmtiPrimitiveFieldCallback cb = context->primitive_field_callback();
1978   int res = (*cb)(ref_kind,
1979                   &reference_info,
1980                   wrapper.klass_tag(),
1981                   wrapper.obj_tag_p(),
1982                   value,
1983                   value_type,
1984                   (void*)user_data());
1985   return (!(res & JVMTI_VISIT_ABORT));
1986 }
1987 
1988 
1989 // instance field
1990 inline bool CallbackInvoker::report_primitive_instance_field(oop obj,
1991                                                              jint index,
1992                                                              address value,
1993                                                              char type) {
1994   return report_primitive_field(JVMTI_HEAP_REFERENCE_FIELD,
1995                                 obj,
1996                                 index,
1997                                 value,
1998                                 type);
1999 }
2000 
2001 // static field
2002 inline bool CallbackInvoker::report_primitive_static_field(oop obj,
2003                                                            jint index,
2004                                                            address value,
2005                                                            char type) {
2006   return report_primitive_field(JVMTI_HEAP_REFERENCE_STATIC_FIELD,
2007                                 obj,
2008                                 index,
2009                                 value,
2010                                 type);
2011 }
2012 
2013 // report a JNI local (root object) to the profiler
2014 inline bool CallbackInvoker::report_jni_local_root(jlong thread_tag, jlong tid, jint depth, jmethodID m, oop obj) {
2015   if (is_basic_heap_walk()) {
2016     return invoke_basic_stack_ref_callback(JVMTI_HEAP_ROOT_JNI_LOCAL,
2017                                            thread_tag,
2018                                            depth,
2019                                            m,
2020                                            -1,
2021                                            obj);
2022   } else {
2023     return invoke_advanced_stack_ref_callback(JVMTI_HEAP_REFERENCE_JNI_LOCAL,
2024                                               thread_tag, tid,
2025                                               depth,
2026                                               m,
2027                                               (jlocation)-1,
2028                                               -1,
2029                                               obj);
2030   }
2031 }
2032 
2033 
2034 // report a local (stack reference, root object)
2035 inline bool CallbackInvoker::report_stack_ref_root(jlong thread_tag,
2036                                                    jlong tid,
2037                                                    jint depth,
2038                                                    jmethodID method,
2039                                                    jlocation bci,
2040                                                    jint slot,
2041                                                    oop obj) {
2042   if (is_basic_heap_walk()) {
2043     return invoke_basic_stack_ref_callback(JVMTI_HEAP_ROOT_STACK_LOCAL,
2044                                            thread_tag,
2045                                            depth,
2046                                            method,
2047                                            slot,
2048                                            obj);
2049   } else {
2050     return invoke_advanced_stack_ref_callback(JVMTI_HEAP_REFERENCE_STACK_LOCAL,
2051                                               thread_tag,
2052                                               tid,
2053                                               depth,
2054                                               method,
2055                                               bci,
2056                                               slot,
2057                                               obj);
2058   }
2059 }
2060 
2061 // report an object referencing a class.
2062 inline bool CallbackInvoker::report_class_reference(oop referrer, oop referree) {
2063   if (is_basic_heap_walk()) {
2064     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS, referrer, referree, -1);
2065   } else {
2066     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CLASS, referrer, referree, -1);
2067   }
2068 }
2069 
2070 // report a class referencing its class loader.
2071 inline bool CallbackInvoker::report_class_loader_reference(oop referrer, oop referree) {
2072   if (is_basic_heap_walk()) {
2073     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS_LOADER, referrer, referree, -1);
2074   } else {
2075     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CLASS_LOADER, referrer, referree, -1);
2076   }
2077 }
2078 
2079 // report a class referencing its signers.
2080 inline bool CallbackInvoker::report_signers_reference(oop referrer, oop referree) {
2081   if (is_basic_heap_walk()) {
2082     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_SIGNERS, referrer, referree, -1);
2083   } else {
2084     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_SIGNERS, referrer, referree, -1);
2085   }
2086 }
2087 
2088 // report a class referencing its protection domain..
2089 inline bool CallbackInvoker::report_protection_domain_reference(oop referrer, oop referree) {
2090   if (is_basic_heap_walk()) {
2091     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_PROTECTION_DOMAIN, referrer, referree, -1);
2092   } else {
2093     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_PROTECTION_DOMAIN, referrer, referree, -1);
2094   }
2095 }
2096 
2097 // report a class referencing its superclass.
2098 inline bool CallbackInvoker::report_superclass_reference(oop referrer, oop referree) {
2099   if (is_basic_heap_walk()) {
2100     // Send this to be consistent with past implementation
2101     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS, referrer, referree, -1);
2102   } else {
2103     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_SUPERCLASS, referrer, referree, -1);
2104   }
2105 }
2106 
2107 // report a class referencing one of its interfaces.
2108 inline bool CallbackInvoker::report_interface_reference(oop referrer, oop referree) {
2109   if (is_basic_heap_walk()) {
2110     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_INTERFACE, referrer, referree, -1);
2111   } else {
2112     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_INTERFACE, referrer, referree, -1);
2113   }
2114 }
2115 
2116 // report a class referencing one of its static fields.
2117 inline bool CallbackInvoker::report_static_field_reference(oop referrer, oop referree, jint slot) {
2118   if (is_basic_heap_walk()) {
2119     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_STATIC_FIELD, referrer, referree, slot);
2120   } else {
2121     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_STATIC_FIELD, referrer, referree, slot);
2122   }
2123 }
2124 
2125 // report an array referencing an element object
2126 inline bool CallbackInvoker::report_array_element_reference(oop referrer, oop referree, jint index) {
2127   if (is_basic_heap_walk()) {
2128     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_ARRAY_ELEMENT, referrer, referree, index);
2129   } else {
2130     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, referrer, referree, index);
2131   }
2132 }
2133 
2134 // report an object referencing an instance field object
2135 inline bool CallbackInvoker::report_field_reference(oop referrer, oop referree, jint slot) {
2136   if (is_basic_heap_walk()) {
2137     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_FIELD, referrer, referree, slot);
2138   } else {
2139     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_FIELD, referrer, referree, slot);
2140   }
2141 }
2142 
2143 // report an array referencing an element object
2144 inline bool CallbackInvoker::report_constant_pool_reference(oop referrer, oop referree, jint index) {
2145   if (is_basic_heap_walk()) {
2146     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CONSTANT_POOL, referrer, referree, index);
2147   } else {
2148     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CONSTANT_POOL, referrer, referree, index);
2149   }
2150 }
2151 
2152 // A supporting closure used to process simple roots
2153 class SimpleRootsClosure : public OopClosure {
2154  private:
2155   jvmtiHeapReferenceKind _kind;
2156   bool _continue;
2157 
2158   jvmtiHeapReferenceKind root_kind()    { return _kind; }
2159 
2160  public:
2161   void set_kind(jvmtiHeapReferenceKind kind) {
2162     _kind = kind;
2163     _continue = true;
2164   }

2251 
2252 public:
2253   StackRefCollector(JvmtiTagMap* tag_map, JNILocalRootsClosure* blk, JavaThread* java_thread)
2254     : _tag_map(tag_map), _blk(blk), _java_thread(java_thread),
2255       _threadObj(nullptr), _thread_tag(0), _tid(0),
2256       _is_top_frame(true), _depth(0), _last_entry_frame(nullptr)
2257   {
2258   }
2259 
2260   bool set_thread(oop o);
2261   // Sets the thread and reports the reference to it with the specified kind.
2262   bool set_thread(jvmtiHeapReferenceKind kind, oop o);
2263 
2264   bool do_frame(vframe* vf);
2265   // Handles frames until vf->sender() is null.
2266   bool process_frames(vframe* vf);
2267 };
2268 
2269 bool StackRefCollector::set_thread(oop o) {
2270   _threadObj = o;
2271   _thread_tag = tag_for(_tag_map, _threadObj);
2272   _tid = java_lang_Thread::thread_id(_threadObj);
2273 
2274   _is_top_frame = true;
2275   _depth = 0;
2276   _last_entry_frame = nullptr;
2277 
2278   return true;
2279 }
2280 
2281 bool StackRefCollector::set_thread(jvmtiHeapReferenceKind kind, oop o) {
2282   return set_thread(o)
2283          && CallbackInvoker::report_simple_root(kind, _threadObj);
2284 }
2285 
2286 bool StackRefCollector::report_java_stack_refs(StackValueCollection* values, jmethodID method, jlocation bci, jint slot_offset) {
2287   for (int index = 0; index < values->size(); index++) {
2288     if (values->at(index)->type() == T_OBJECT) {
2289       oop obj = values->obj_at(index)();
2290       if (obj == nullptr) {
2291         continue;

2384   return true;
2385 }
2386 
2387 
2388 // A VM operation to iterate over objects that are reachable from
2389 // a set of roots or an initial object.
2390 //
2391 // For VM_HeapWalkOperation the set of roots used is :-
2392 //
2393 // - All JNI global references
2394 // - All inflated monitors
2395 // - All classes loaded by the boot class loader (or all classes
2396 //     in the event that class unloading is disabled)
2397 // - All java threads
2398 // - For each java thread then all locals and JNI local references
2399 //      on the thread's execution stack
2400 // - All visible/explainable objects from Universes::oops_do
2401 //
2402 class VM_HeapWalkOperation: public VM_Operation {
2403  private:
2404   enum {
2405     initial_visit_stack_size = 4000
2406   };
2407 
2408   bool _is_advanced_heap_walk;                      // indicates FollowReferences
2409   JvmtiTagMap* _tag_map;
2410   Handle _initial_object;
2411   GrowableArray<oop>* _visit_stack;                 // the visit stack
2412 
2413   JVMTIBitSet _bitset;
2414 
2415   // Dead object tags in JvmtiTagMap
2416   GrowableArray<jlong>* _dead_objects;
2417 
2418   bool _following_object_refs;                      // are we following object references
2419 
2420   bool _reporting_primitive_fields;                 // optional reporting
2421   bool _reporting_primitive_array_values;
2422   bool _reporting_string_values;
2423 
2424   GrowableArray<oop>* create_visit_stack() {
2425     return new (mtServiceability) GrowableArray<oop>(initial_visit_stack_size, mtServiceability);
2426   }
2427 
2428   // accessors
2429   bool is_advanced_heap_walk() const               { return _is_advanced_heap_walk; }
2430   JvmtiTagMap* tag_map() const                     { return _tag_map; }
2431   Handle initial_object() const                    { return _initial_object; }
2432 
2433   bool is_following_references() const             { return _following_object_refs; }
2434 
2435   bool is_reporting_primitive_fields()  const      { return _reporting_primitive_fields; }
2436   bool is_reporting_primitive_array_values() const { return _reporting_primitive_array_values; }
2437   bool is_reporting_string_values() const          { return _reporting_string_values; }
2438 
2439   GrowableArray<oop>* visit_stack() const          { return _visit_stack; }
2440 
2441   // iterate over the various object types
2442   inline bool iterate_over_array(oop o);
2443   inline bool iterate_over_type_array(oop o);
2444   inline bool iterate_over_class(oop o);
2445   inline bool iterate_over_object(oop o);

2446 
2447   // root collection
2448   inline bool collect_simple_roots();
2449   inline bool collect_stack_roots();
2450   inline bool collect_stack_refs(JavaThread* java_thread, JNILocalRootsClosure* blk);
2451   inline bool collect_vthread_stack_refs(oop vt);
2452 
2453   // visit an object
2454   inline bool visit(oop o);
2455 
2456  public:
2457   VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2458                        Handle initial_object,
2459                        BasicHeapWalkContext callbacks,
2460                        const void* user_data,
2461                        GrowableArray<jlong>* objects);
2462 
2463   VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2464                        Handle initial_object,
2465                        AdvancedHeapWalkContext callbacks,
2466                        const void* user_data,
2467                        GrowableArray<jlong>* objects);
2468 
2469   ~VM_HeapWalkOperation();
2470 
2471   VMOp_Type type() const { return VMOp_HeapWalkOperation; }
2472   void doit();
2473 };
2474 
2475 
2476 VM_HeapWalkOperation::VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2477                                            Handle initial_object,
2478                                            BasicHeapWalkContext callbacks,
2479                                            const void* user_data,
2480                                            GrowableArray<jlong>* objects) {
2481   _is_advanced_heap_walk = false;
2482   _tag_map = tag_map;
2483   _initial_object = initial_object;
2484   _following_object_refs = (callbacks.object_ref_callback() != nullptr);
2485   _reporting_primitive_fields = false;
2486   _reporting_primitive_array_values = false;
2487   _reporting_string_values = false;
2488   _visit_stack = create_visit_stack();
2489   _dead_objects = objects;
2490 
2491   CallbackInvoker::initialize_for_basic_heap_walk(tag_map, _visit_stack, user_data, callbacks, &_bitset);
2492 }
2493 
2494 VM_HeapWalkOperation::VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2495                                            Handle initial_object,
2496                                            AdvancedHeapWalkContext callbacks,
2497                                            const void* user_data,
2498                                            GrowableArray<jlong>* objects) {
2499   _is_advanced_heap_walk = true;
2500   _tag_map = tag_map;
2501   _initial_object = initial_object;
2502   _following_object_refs = true;
2503   _reporting_primitive_fields = (callbacks.primitive_field_callback() != nullptr);;
2504   _reporting_primitive_array_values = (callbacks.array_primitive_value_callback() != nullptr);;
2505   _reporting_string_values = (callbacks.string_primitive_value_callback() != nullptr);;
2506   _visit_stack = create_visit_stack();
2507   _dead_objects = objects;
2508   CallbackInvoker::initialize_for_advanced_heap_walk(tag_map, _visit_stack, user_data, callbacks, &_bitset);
2509 }
2510 
2511 VM_HeapWalkOperation::~VM_HeapWalkOperation() {
2512   if (_following_object_refs) {
2513     assert(_visit_stack != nullptr, "checking");
2514     delete _visit_stack;
2515     _visit_stack = nullptr;
2516   }
2517 }
2518 
2519 // an array references its class and has a reference to
2520 // each element in the array
2521 inline bool VM_HeapWalkOperation::iterate_over_array(oop o) {
2522   objArrayOop array = objArrayOop(o);

2523 
2524   // array reference to its class
2525   oop mirror = ObjArrayKlass::cast(array->klass())->java_mirror();
2526   if (!CallbackInvoker::report_class_reference(o, mirror)) {
2527     return false;
2528   }
2529 
2530   // iterate over the array and report each reference to a
2531   // non-null element
2532   for (int index=0; index<array->length(); index++) {
2533     oop elem = array->obj_at(index);
2534     if (elem == nullptr) {
2535       continue;
2536     }
2537 
2538     // report the array reference o[index] = elem
2539     if (!CallbackInvoker::report_array_element_reference(o, elem, index)) {
2540       return false;
2541     }
2542   }
2543   return true;
2544 }
2545 






































2546 // a type array references its class
2547 inline bool VM_HeapWalkOperation::iterate_over_type_array(oop o) {
2548   Klass* k = o->klass();

2549   oop mirror = k->java_mirror();
2550   if (!CallbackInvoker::report_class_reference(o, mirror)) {
2551     return false;
2552   }
2553 
2554   // report the array contents if required
2555   if (is_reporting_primitive_array_values()) {
2556     if (!CallbackInvoker::report_primitive_array_values(o)) {
2557       return false;
2558     }
2559   }
2560   return true;
2561 }
2562 
2563 #ifdef ASSERT
2564 // verify that a static oop field is in range
2565 static inline bool verify_static_oop(InstanceKlass* ik,
2566                                      oop mirror, int offset) {
2567   address obj_p = cast_from_oop<address>(mirror) + offset;
2568   address start = (address)InstanceMirrorKlass::start_of_static_fields(mirror);
2569   address end = start + (java_lang_Class::static_oop_field_count(mirror) * heapOopSize);
2570   assert(end >= start, "sanity check");
2571 
2572   if (obj_p >= start && obj_p < end) {
2573     return true;
2574   } else {
2575     return false;
2576   }
2577 }
2578 #endif // #ifdef ASSERT
2579 
2580 // a class references its super class, interfaces, class loader, ...
2581 // and finally its static fields
2582 inline bool VM_HeapWalkOperation::iterate_over_class(oop java_class) {


2583   int i;
2584   Klass* klass = java_lang_Class::as_Klass(java_class);
2585 
2586   if (klass->is_instance_klass()) {
2587     InstanceKlass* ik = InstanceKlass::cast(klass);
2588 
2589     // Ignore the class if it hasn't been initialized yet
2590     if (!ik->is_linked()) {
2591       return true;
2592     }
2593 
2594     // get the java mirror
2595     oop mirror = klass->java_mirror();

2596 
2597     // super (only if something more interesting than java.lang.Object)
2598     InstanceKlass* super_klass = ik->super();
2599     if (super_klass != nullptr && super_klass != vmClasses::Object_klass()) {
2600       oop super_oop = super_klass->java_mirror();
2601       if (!CallbackInvoker::report_superclass_reference(mirror, super_oop)) {
2602         return false;
2603       }
2604     }
2605 
2606     // class loader
2607     oop cl = ik->class_loader();
2608     if (cl != nullptr) {
2609       if (!CallbackInvoker::report_class_loader_reference(mirror, cl)) {
2610         return false;
2611       }
2612     }
2613 
2614     // protection domain
2615     oop pd = ik->protection_domain();

2664     // (These will already have been reported as references from the constant pool
2665     //  but are specified by IterateOverReachableObjects and must be reported).
2666     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
2667     for (i = 0; i < interfaces->length(); i++) {
2668       oop interf = interfaces->at(i)->java_mirror();
2669       if (interf == nullptr) {
2670         continue;
2671       }
2672       if (!CallbackInvoker::report_interface_reference(mirror, interf)) {
2673         return false;
2674       }
2675     }
2676 
2677     // iterate over the static fields
2678 
2679     ClassFieldMap* field_map = ClassFieldMap::create_map_of_static_fields(klass);
2680     for (i=0; i<field_map->field_count(); i++) {
2681       ClassFieldDescriptor* field = field_map->field_at(i);
2682       char type = field->field_type();
2683       if (!is_primitive_field_type(type)) {
2684         oop fld_o = mirror->obj_field(field->field_offset());
2685         assert(verify_static_oop(ik, mirror, field->field_offset()), "sanity check");
2686         if (fld_o != nullptr) {
2687           int slot = field->field_index();
2688           if (!CallbackInvoker::report_static_field_reference(mirror, fld_o, slot)) {
2689             delete field_map;
2690             return false;
2691           }
2692         }
2693       } else {
2694          if (is_reporting_primitive_fields()) {
2695            address addr = cast_from_oop<address>(mirror) + field->field_offset();
2696            int slot = field->field_index();
2697            if (!CallbackInvoker::report_primitive_static_field(mirror, slot, addr, type)) {
2698              delete field_map;
2699              return false;
2700           }
2701         }
2702       }
2703     }
2704     delete field_map;
2705 
2706     return true;
2707   }
2708 
2709   return true;
2710 }
2711 
2712 // an object references a class and its instance fields
2713 // (static fields are ignored here as we report these as
2714 // references from the class).
2715 inline bool VM_HeapWalkOperation::iterate_over_object(oop o) {
2716   // reference to the class
2717   if (!CallbackInvoker::report_class_reference(o, o->klass()->java_mirror())) {
2718     return false;
2719   }
2720 
2721   // iterate over instance fields
2722   ClassFieldMap* field_map = JvmtiCachedClassFieldMap::get_map_of_instance_fields(o);
2723   for (int i=0; i<field_map->field_count(); i++) {
2724     ClassFieldDescriptor* field = field_map->field_at(i);
2725     char type = field->field_type();






2726     if (!is_primitive_field_type(type)) {
2727       oop fld_o = o->obj_field_access<AS_NO_KEEPALIVE | ON_UNKNOWN_OOP_REF>(field->field_offset());
2728       // ignore any objects that aren't visible to profiler
2729       if (fld_o != nullptr) {
2730         assert(Universe::heap()->is_in(fld_o), "unsafe code should not "
2731                "have references to Klass* anymore");
2732         int slot = field->field_index();
2733         if (!CallbackInvoker::report_field_reference(o, fld_o, slot)) {




2734           return false;
2735         }









2736       }
2737     } else {
2738       if (is_reporting_primitive_fields()) {
2739         // primitive instance field
2740         address addr = cast_from_oop<address>(o) + field->field_offset();
2741         int slot = field->field_index();
2742         if (!CallbackInvoker::report_primitive_instance_field(o, slot, addr, type)) {
2743           return false;
2744         }
2745       }
2746     }
2747   }
2748 
2749   // if the object is a java.lang.String
2750   if (is_reporting_string_values() &&
2751       o->klass() == vmClasses::String_klass()) {
2752     if (!CallbackInvoker::report_string_value(o)) {
2753       return false;
2754     }
2755   }
2756   return true;
2757 }
2758 
2759 
2760 // Collects all simple (non-stack) roots except for threads;
2761 // threads are handled in collect_stack_roots() as an optimization.
2762 // if there's a heap root callback provided then the callback is
2763 // invoked for each simple root.
2764 // if an object reference callback is provided then all simple
2765 // roots are pushed onto the marking stack so that they can be
2766 // processed later
2767 //
2768 inline bool VM_HeapWalkOperation::collect_simple_roots() {
2769   SimpleRootsClosure blk;
2770 
2771   // JNI globals

2800 // Reports the thread as JVMTI_HEAP_REFERENCE_THREAD,
2801 // walks the stack of the thread, finds all references (locals
2802 // and JNI calls) and reports these as stack references.
2803 inline bool VM_HeapWalkOperation::collect_stack_refs(JavaThread* java_thread,
2804                                                      JNILocalRootsClosure* blk)
2805 {
2806   oop threadObj = java_thread->threadObj();
2807   oop mounted_vt = java_thread->is_vthread_mounted() ? java_thread->vthread() : nullptr;
2808   if (mounted_vt != nullptr && !JvmtiEnvBase::is_vthread_alive(mounted_vt)) {
2809     mounted_vt = nullptr;
2810   }
2811   assert(threadObj != nullptr, "sanity check");
2812 
2813   StackRefCollector stack_collector(tag_map(), blk, java_thread);
2814 
2815   if (!java_thread->has_last_Java_frame()) {
2816     if (!stack_collector.set_thread(JVMTI_HEAP_REFERENCE_THREAD, threadObj)) {
2817       return false;
2818     }
2819     // no last java frame but there may be JNI locals
2820     blk->set_context(tag_for(_tag_map, threadObj), java_lang_Thread::thread_id(threadObj), 0, (jmethodID)nullptr);
2821     java_thread->active_handles()->oops_do(blk);
2822     return !blk->stopped();
2823   }
2824   // vframes are resource allocated
2825   Thread* current_thread = Thread::current();
2826   ResourceMark rm(current_thread);
2827   HandleMark hm(current_thread);
2828 
2829   RegisterMap reg_map(java_thread,
2830                       RegisterMap::UpdateMap::include,
2831                       RegisterMap::ProcessFrames::include,
2832                       RegisterMap::WalkContinuation::include);
2833 
2834   // first handle mounted vthread (if any)
2835   if (mounted_vt != nullptr) {
2836     frame f = java_thread->last_frame();
2837     vframe* vf = vframe::new_vframe(&f, &reg_map, java_thread);
2838     // report virtual thread as JVMTI_HEAP_REFERENCE_OTHER
2839     if (!stack_collector.set_thread(JVMTI_HEAP_REFERENCE_OTHER, mounted_vt)) {
2840       return false;

2900   RegisterMap reg_map(cont.continuation(), RegisterMap::UpdateMap::include);
2901 
2902   JNILocalRootsClosure blk;
2903   // JavaThread is not required for unmounted virtual threads
2904   StackRefCollector stack_collector(tag_map(), &blk, nullptr);
2905   // reference to the vthread is already reported
2906   if (!stack_collector.set_thread(vt)) {
2907     return false;
2908   }
2909 
2910   frame fr = chunk->top_frame(&reg_map);
2911   vframe* vf = vframe::new_vframe(&fr, &reg_map, nullptr);
2912   return stack_collector.process_frames(vf);
2913 }
2914 
2915 // visit an object
2916 // first mark the object as visited
2917 // second get all the outbound references from this object (in other words, all
2918 // the objects referenced by this object).
2919 //
2920 bool VM_HeapWalkOperation::visit(oop o) {
2921   // mark object as visited
2922   assert(!_bitset.is_marked(o), "can't visit same object more than once");
2923   _bitset.mark_obj(o);
2924 

2925   // instance
2926   if (o->is_instance()) {
2927     if (o->klass() == vmClasses::Class_klass()) {
2928       if (!java_lang_Class::is_primitive(o)) {

2929         // a java.lang.Class
2930         return iterate_over_class(o);
2931       }
2932     } else {
2933       // we report stack references only when initial object is not specified
2934       // (in the case we start from heap roots which include platform thread stack references)
2935       if (initial_object().is_null() && java_lang_VirtualThread::is_subclass(o->klass())) {
2936         if (!collect_vthread_stack_refs(o)) {

2937           return false;
2938         }
2939       }
2940       return iterate_over_object(o);
2941     }
2942   }
2943 





2944   // object array
2945   if (o->is_objArray()) {
2946     return iterate_over_array(o);
2947   }
2948 
2949   // type array
2950   if (o->is_typeArray()) {
2951     return iterate_over_type_array(o);
2952   }
2953 
2954   return true;
2955 }
2956 
2957 void VM_HeapWalkOperation::doit() {
2958   ResourceMark rm;
2959   ClassFieldMapCacheMark cm;
2960 
2961   JvmtiTagMap::check_hashmaps_for_heapwalk(_dead_objects);
2962 
2963   assert(visit_stack()->is_empty(), "visit stack must be empty");
2964 
2965   // the heap walk starts with an initial object or the heap roots
2966   if (initial_object().is_null()) {
2967     // can result in a big performance boost for an agent that is
2968     // focused on analyzing references in the thread stacks.
2969     if (!collect_stack_roots()) return;
2970 
2971     if (!collect_simple_roots()) return;
2972   } else {
2973     visit_stack()->push(initial_object()());
2974   }
2975 
2976   // object references required
2977   if (is_following_references()) {
2978 
2979     // visit each object until all reachable objects have been
2980     // visited or the callback asked to terminate the iteration.
2981     while (!visit_stack()->is_empty()) {
2982       oop o = visit_stack()->pop();
2983       if (!_bitset.is_marked(o)) {
2984         if (!visit(o)) {
2985           break;
2986         }
2987       }
2988     }
2989   }
2990 }
2991 
2992 // iterate over all objects that are reachable from a set of roots
2993 void JvmtiTagMap::iterate_over_reachable_objects(jvmtiHeapRootCallback heap_root_callback,
2994                                                  jvmtiStackReferenceCallback stack_ref_callback,
2995                                                  jvmtiObjectReferenceCallback object_ref_callback,
2996                                                  const void* user_data) {
2997   // VTMS transitions must be disabled before the EscapeBarrier.
2998   JvmtiVTMSTransitionDisabler disabler;
2999 
3000   JavaThread* jt = JavaThread::current();
3001   EscapeBarrier eb(true, jt);
3002   eb.deoptimize_objects_all_threads();
3003   Arena dead_object_arena(mtServiceability);
3004   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3005 
3006   {
3007     MutexLocker ml(Heap_lock);
3008     BasicHeapWalkContext context(heap_root_callback, stack_ref_callback, object_ref_callback);
3009     VM_HeapWalkOperation op(this, Handle(), context, user_data, &dead_objects);
3010     VMThread::execute(&op);
3011   }


3012   // Post events outside of Heap_lock
3013   post_dead_objects(&dead_objects);
3014 }
3015 
3016 // iterate over all objects that are reachable from a given object
3017 void JvmtiTagMap::iterate_over_objects_reachable_from_object(jobject object,
3018                                                              jvmtiObjectReferenceCallback object_ref_callback,
3019                                                              const void* user_data) {
3020   oop obj = JNIHandles::resolve(object);
3021   Handle initial_object(Thread::current(), obj);
3022 
3023   Arena dead_object_arena(mtServiceability);
3024   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3025 
3026   JvmtiVTMSTransitionDisabler disabler;
3027 
3028   {
3029     MutexLocker ml(Heap_lock);
3030     BasicHeapWalkContext context(nullptr, nullptr, object_ref_callback);
3031     VM_HeapWalkOperation op(this, initial_object, context, user_data, &dead_objects);
3032     VMThread::execute(&op);
3033   }


3034   // Post events outside of Heap_lock
3035   post_dead_objects(&dead_objects);
3036 }
3037 
3038 // follow references from an initial object or the GC roots
3039 void JvmtiTagMap::follow_references(jint heap_filter,
3040                                     Klass* klass,
3041                                     jobject object,
3042                                     const jvmtiHeapCallbacks* callbacks,
3043                                     const void* user_data)
3044 {
3045   // VTMS transitions must be disabled before the EscapeBarrier.
3046   JvmtiVTMSTransitionDisabler disabler;
3047 
3048   oop obj = JNIHandles::resolve(object);
3049   JavaThread* jt = JavaThread::current();
3050   Handle initial_object(jt, obj);
3051   // EA based optimizations that are tagged or reachable from initial_object are already reverted.
3052   EscapeBarrier eb(initial_object.is_null() &&
3053                    !(heap_filter & JVMTI_HEAP_FILTER_UNTAGGED),
3054                    jt);
3055   eb.deoptimize_objects_all_threads();
3056 
3057   Arena dead_object_arena(mtServiceability);
3058   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3059 
3060   {
3061     MutexLocker ml(Heap_lock);
3062     AdvancedHeapWalkContext context(heap_filter, klass, callbacks);
3063     VM_HeapWalkOperation op(this, initial_object, context, user_data, &dead_objects);
3064     VMThread::execute(&op);
3065   }


3066   // Post events outside of Heap_lock
3067   post_dead_objects(&dead_objects);
3068 }
3069 
3070 // Verify gc_notification follows set_needs_cleaning.
3071 DEBUG_ONLY(static bool notified_needs_cleaning = false;)
3072 
3073 void JvmtiTagMap::set_needs_cleaning() {
3074   assert(SafepointSynchronize::is_at_safepoint(), "called in gc pause");
3075   assert(Thread::current()->is_VM_thread(), "should be the VM thread");
3076   // Can't assert !notified_needs_cleaning; a partial GC might be upgraded
3077   // to a full GC and do this twice without intervening gc_notification.
3078   DEBUG_ONLY(notified_needs_cleaning = true;)
3079 
3080   JvmtiEnvIterator it;
3081   for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
3082     JvmtiTagMap* tag_map = env->tag_map_acquire();
3083     if (tag_map != nullptr) {
3084       tag_map->_needs_cleaning = !tag_map->is_empty();
3085     }

  53 #include "runtime/deoptimization.hpp"
  54 #include "runtime/frame.inline.hpp"
  55 #include "runtime/handles.inline.hpp"
  56 #include "runtime/interfaceSupport.inline.hpp"
  57 #include "runtime/javaCalls.hpp"
  58 #include "runtime/javaThread.inline.hpp"
  59 #include "runtime/jniHandles.inline.hpp"
  60 #include "runtime/mutex.hpp"
  61 #include "runtime/mutexLocker.hpp"
  62 #include "runtime/safepoint.hpp"
  63 #include "runtime/threadSMR.hpp"
  64 #include "runtime/timerTrace.hpp"
  65 #include "runtime/vframe.hpp"
  66 #include "runtime/vmOperations.hpp"
  67 #include "runtime/vmThread.hpp"
  68 #include "utilities/macros.hpp"
  69 #include "utilities/objectBitSet.inline.hpp"
  70 
  71 typedef ObjectBitSet<mtServiceability> JVMTIBitSet;
  72 
  73 
  74 // Helper class to store objects to visit.
  75 class JvmtiHeapwalkVisitStack {
  76 private:
  77   enum {
  78     initial_visit_stack_size = 4000
  79   };
  80 
  81   GrowableArray<JvmtiHeapwalkObject>* _visit_stack;
  82   JVMTIBitSet _bitset;
  83 
  84   static GrowableArray<JvmtiHeapwalkObject>* create_visit_stack() {
  85     return new (mtServiceability) GrowableArray<JvmtiHeapwalkObject>(initial_visit_stack_size, mtServiceability);
  86   }
  87 
  88 public:
  89   JvmtiHeapwalkVisitStack(): _visit_stack(create_visit_stack()) {
  90   }
  91   ~JvmtiHeapwalkVisitStack() {
  92     if (_visit_stack != nullptr) {
  93       delete _visit_stack;
  94     }
  95   }
  96 
  97   bool is_empty() const {
  98     return _visit_stack->is_empty();
  99   }
 100 
 101   void push(const JvmtiHeapwalkObject& obj) {
 102     _visit_stack->push(obj);
 103   }
 104 
 105   // If the object hasn't been visited then push it onto the visit stack
 106   // so that it will be visited later.
 107   void check_for_visit(const JvmtiHeapwalkObject& obj) {
 108     if (!is_visited(obj)) {
 109       _visit_stack->push(obj);
 110     }
 111   }
 112 
 113   JvmtiHeapwalkObject pop() {
 114     return _visit_stack->pop();
 115   }
 116 
 117   bool is_visited(const JvmtiHeapwalkObject& obj) /*const*/ { // TODO: _bitset.is_marked() should be const
 118     // The method is called only for objects from visit_stack to ensure an object is not visited twice.
 119     // Flat objects can be added to visit_stack only when we visit their holder object, so we cannot get duplicate reference to it.
 120     if (obj.is_flat()) {
 121       return false;
 122     }
 123     return _bitset.is_marked(obj.obj());
 124   }
 125 
 126   void mark_visited(const JvmtiHeapwalkObject& obj) {
 127     if (!obj.is_flat()) {
 128       _bitset.mark_obj(obj.obj());
 129     }
 130   }
 131 };
 132 
 133 
 134 bool JvmtiTagMap::_has_object_free_events = false;
 135 
 136 // create a JvmtiTagMap
 137 JvmtiTagMap::JvmtiTagMap(JvmtiEnv* env) :
 138   _env(env),
 139   _lock(Mutex::nosafepoint, "JvmtiTagMap_lock"),
 140   _needs_cleaning(false),
 141   _posting_events(false),
 142   _converting_flat_object(false) {
 143 
 144   assert(JvmtiThreadState_lock->is_locked(), "sanity check");
 145   assert(((JvmtiEnvBase *)env)->tag_map() == nullptr, "tag map already exists for environment");
 146 
 147   _hashmap = new JvmtiTagMapTable();
 148   _flat_hashmap = new JvmtiFlatTagMapTable();
 149 
 150   // finally add us to the environment
 151   ((JvmtiEnvBase *)env)->release_set_tag_map(this);
 152 }
 153 
 154 // destroy a JvmtiTagMap
 155 JvmtiTagMap::~JvmtiTagMap() {
 156 
 157   // no lock acquired as we assume the enclosing environment is
 158   // also being destroyed.
 159   ((JvmtiEnvBase *)_env)->set_tag_map(nullptr);
 160 
 161   // finally destroy the hashmap
 162   delete _hashmap;
 163   _hashmap = nullptr;
 164   delete _flat_hashmap;
 165 }
 166 
 167 // Called by env_dispose() to reclaim memory before deallocation.
 168 // Remove all the entries but keep the empty table intact.
 169 // This needs the table lock.
 170 void JvmtiTagMap::clear() {
 171   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 172   _hashmap->clear();
 173   _flat_hashmap->clear();
 174 }
 175 
 176 // returns the tag map for the given environments. If the tag map
 177 // doesn't exist then it is created.
 178 JvmtiTagMap* JvmtiTagMap::tag_map_for(JvmtiEnv* env) {
 179   JvmtiTagMap* tag_map = ((JvmtiEnvBase*)env)->tag_map_acquire();
 180   if (tag_map == nullptr) {
 181     MutexLocker mu(JvmtiThreadState_lock);
 182     tag_map = ((JvmtiEnvBase*)env)->tag_map();
 183     if (tag_map == nullptr) {
 184       tag_map = new JvmtiTagMap(env);
 185     }
 186   } else {
 187     DEBUG_ONLY(JavaThread::current()->check_possible_safepoint());
 188   }
 189   return tag_map;
 190 }
 191 





 192 // returns true if the hashmaps are empty
 193 bool JvmtiTagMap::is_empty() const {
 194   assert(SafepointSynchronize::is_at_safepoint() || is_locked(), "checking");
 195   return _hashmap->is_empty() && _flat_hashmap->is_empty();
 196 }
 197 
 198 // This checks for posting before operations that use
 199 // this tagmap table.
 200 void JvmtiTagMap::check_hashmap(GrowableArray<jlong>* objects) {
 201   assert(is_locked(), "checking");
 202 
 203   if (is_empty()) { return; }
 204 
 205   if (_needs_cleaning &&
 206       objects != nullptr &&
 207       env()->is_enabled(JVMTI_EVENT_OBJECT_FREE)) {
 208     remove_dead_entries_locked(objects);
 209   }
 210 }
 211 
 212 // This checks for posting and is called from the heap walks.
 213 void JvmtiTagMap::check_hashmaps_for_heapwalk(GrowableArray<jlong>* objects) {
 214   assert(SafepointSynchronize::is_at_safepoint(), "called from safepoints");
 215 
 216   // Verify that the tag map tables are valid and unconditionally post events
 217   // that are expected to be posted before gc_notification.
 218   JvmtiEnvIterator it;
 219   for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
 220     JvmtiTagMap* tag_map = env->tag_map_acquire();
 221     if (tag_map != nullptr) {
 222       // The ZDriver may be walking the hashmaps concurrently so this lock is needed.
 223       MutexLocker ml(tag_map->lock(), Mutex::_no_safepoint_check_flag);
 224       tag_map->check_hashmap(objects);
 225     }
 226   }
 227 }
 228 
 229 // Converts entries from JvmtiFlatTagMapTable to JvmtiTagMapTable in batches.
 230 //   1. (JvmtiTagMap is locked)
 231 //      reads entries from JvmtiFlatTagMapTable (describe flat value objects);
 232 //   2. (JvmtiTagMap is unlocked)
 233 //      creates heap-allocated copies of the flat object;
 234 //   3. (JvmtiTagMap is locked)
 235 //      ensures source entry still exists, removes it from JvmtiFlatTagMapTable, adds new entry to JvmtiTagMapTable.
 236 // If some error occurs in step 2 (OOM?), the process stops.
 237 class JvmtiTagMapFlatEntryConverter: public StackObj {
 238 private:
 239   struct Entry {
 240     // source flat value object
 241     Handle holder;
 242     int offset;
 243     InlineKlass* inline_klass;
 244     LayoutKind layout_kind;
 245     // converted heap-allocated object
 246     Handle dst;
 247 
 248     Entry(): holder(), offset(0), inline_klass(nullptr), dst() {}
 249     Entry(Handle holder, int offset, InlineKlass* inline_klass, LayoutKind lk)
 250       : holder(holder), offset(offset), inline_klass(inline_klass), layout_kind(lk), dst() {}
 251   };
 252 
 253   int _batch_size;
 254   GrowableArray<Entry> _entries;
 255   bool _has_error;
 256 
 257 public:
 258   JvmtiTagMapFlatEntryConverter(int batch_size): _batch_size(batch_size), _entries(batch_size, mtServiceability), _has_error(false) { }
 259   ~JvmtiTagMapFlatEntryConverter() {}
 260 
 261   // returns false if there is nothing to convert
 262   bool import_entries(JvmtiFlatTagMapTable* table) {
 263     if (_has_error) {
 264       // stop the process to avoid infinite loop
 265       return false;
 266     }
 267 
 268     class Importer: public JvmtiFlatTagMapKeyClosure {
 269     private:
 270       GrowableArray<Entry>& _entries;
 271       int _batch_size;
 272     public:
 273       Importer(GrowableArray<Entry>& entries, int batch_size): _entries(entries), _batch_size(batch_size) {}
 274 
 275       bool do_entry(JvmtiFlatTagMapKey& key, jlong& tag) {
 276         Entry entry(Handle(Thread::current(), key.holder()), key.offset(), key.inline_klass(), key.layout_kind());
 277         _entries.append(entry);
 278 
 279         return _entries.length() < _batch_size;
 280       }
 281     } importer(_entries, _batch_size);
 282     table->entry_iterate(&importer);
 283 
 284     return !_entries.is_empty();
 285   }
 286 
 287   void convert() {
 288     for (int i = 0; i < _entries.length(); i++) {
 289       EXCEPTION_MARK;
 290       Entry& entry = _entries.at(i);
 291       oop obj = entry.inline_klass->read_payload_from_addr(entry.holder(), entry.offset, entry.layout_kind, JavaThread::current());
 292 
 293       if (HAS_PENDING_EXCEPTION) {
 294         tty->print_cr("Exception in JvmtiTagMapFlatEntryConverter: ");
 295         java_lang_Throwable::print(PENDING_EXCEPTION, tty);
 296         tty->cr();
 297         CLEAR_PENDING_EXCEPTION;
 298         // stop the conversion
 299         _has_error = true;
 300       } else {
 301         entry.dst = Handle(Thread::current(), obj);
 302       }
 303     }
 304   }
 305 
 306   // returns number of converted entries
 307   int move(JvmtiFlatTagMapTable* src_table, JvmtiTagMapTable* dst_table) {
 308     int count = 0;
 309     for (int i = 0; i < _entries.length(); i++) {
 310       Entry& entry = _entries.at(i);
 311       if (entry.dst() == nullptr) {
 312         // some error during conversion, skip the entry
 313         continue;
 314       }
 315       JvmtiHeapwalkObject obj(entry.holder(), entry.offset, entry.inline_klass, entry.layout_kind);
 316       jlong tag = src_table->remove(obj);
 317 
 318       if (tag != 0) { // ensure the entry is still in the src_table
 319         dst_table->add(entry.dst(), tag);
 320         count++;
 321       } else {
 322 
 323       }
 324     }
 325     // and clean the array
 326     _entries.clear();
 327     return count;
 328   }
 329 };
 330 
 331 
 332 void JvmtiTagMap::convert_flat_object_entries() {
 333   Thread* current = Thread::current();
 334   assert(current->is_Java_thread(), "must be executed on JavaThread");
 335 
 336   log_debug(jvmti, table)("convert_flat_object_entries, main table size = %d, flat table size = %d",
 337                           _hashmap->number_of_entries(), _flat_hashmap->number_of_entries());
 338 
 339   {
 340     MonitorLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 341     // If another thread is converting, let it finish.
 342     while (_converting_flat_object) {
 343       ml.wait();
 344     }
 345     if (_flat_hashmap->is_empty()) {
 346       // nothing to convert
 347       return;
 348     }
 349     _converting_flat_object = true;
 350   }
 351 
 352   const int BATCH_SIZE = 1024;
 353   JvmtiTagMapFlatEntryConverter converter(BATCH_SIZE);
 354 
 355   int count = 0;
 356   while (true) {
 357     HandleMark hm(current);
 358     {
 359       MonitorLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 360       if (!converter.import_entries(_flat_hashmap)) {
 361         break;
 362       }
 363     }
 364     // Convert flat objects to heap-allocated without table lock (so agent callbacks can get/set tags).
 365     converter.convert();
 366     {
 367       MonitorLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 368       count += converter.move(_flat_hashmap, _hashmap);
 369     }
 370   }
 371 
 372   log_info(jvmti, table)("%d flat value objects are converted, flat table size = %d",
 373                          count, _flat_hashmap->number_of_entries());
 374   {
 375     MonitorLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 376     _converting_flat_object = false;
 377     ml.notify_all();
 378   }
 379 }
 380 
 381 jlong JvmtiTagMap::find(const JvmtiHeapwalkObject& obj) const {
 382   jlong tag = _hashmap->find(obj);
 383   if (tag == 0 && obj.is_value()) {
 384     tag = _flat_hashmap->find(obj);
 385   }
 386   return tag;
 387 }
 388 
 389 void JvmtiTagMap::add(const JvmtiHeapwalkObject& obj, jlong tag) {
 390   if (obj.is_flat()) {
 391     // we may have tag for equal (non-flat) object in _hashmap, try to update it 1st
 392     if (!_hashmap->update(obj, tag)) {
 393       // no entry in _hashmap, add to _flat_hashmap
 394       _flat_hashmap->add(obj, tag);
 395     }
 396   } else {
 397     _hashmap->add(obj, tag);
 398   }
 399 }
 400 
 401 void JvmtiTagMap::remove(const JvmtiHeapwalkObject& obj) {
 402   if (!_hashmap->remove(obj)) {
 403     if (obj.is_value()) {
 404       _flat_hashmap->remove(obj);
 405     }
 406   }
 407 }
 408 
 409 
 410 // A CallbackWrapper is a support class for querying and tagging an object
 411 // around a callback to a profiler. The constructor does pre-callback
 412 // work to get the tag value, klass tag value, ... and the destructor
 413 // does the post-callback work of tagging or untagging the object.
 414 //
 415 // {
 416 //   CallbackWrapper wrapper(tag_map, o);
 417 //
 418 //   (*callback)(wrapper.klass_tag(), wrapper.obj_size(), wrapper.obj_tag_p(), ...)
 419 //
 420 // }
 421 // wrapper goes out of scope here which results in the destructor
 422 // checking to see if the object has been tagged, untagged, or the
 423 // tag value has changed.
 424 //
 425 class CallbackWrapper : public StackObj {
 426  private:
 427   JvmtiTagMap* _tag_map;
 428   const JvmtiHeapwalkObject& _o;

 429   jlong _obj_size;
 430   jlong _obj_tag;
 431   jlong _klass_tag;
 432 
 433  protected:
 434   JvmtiTagMap* tag_map() const { return _tag_map; }
 435 
 436   // invoked post-callback to tag, untag, or update the tag of an object
 437   void inline post_callback_tag_update(const JvmtiHeapwalkObject& o, JvmtiTagMap* tag_map, jlong obj_tag);
 438 
 439  public:
 440   CallbackWrapper(JvmtiTagMap* tag_map, const JvmtiHeapwalkObject& o)
 441     : _tag_map(tag_map), _o(o)
 442   {
 443     assert(Thread::current()->is_VM_thread() || tag_map->is_locked(),
 444            "MT unsafe or must be VM thread");
 445 



 446     // object size
 447     if (!o.is_flat()) {
 448       // common case: we have oop
 449       _obj_size = (jlong)o.obj()->size() * wordSize;
 450     } else {
 451       // flat value object, we know its InstanceKlass
 452       assert(_o.inline_klass() != nullptr, "must be");
 453       _obj_size = _o.inline_klass()->size() * wordSize;;
 454     }
 455 
 456     // get object tag
 457     _obj_tag = _tag_map->find(_o);
 458 
 459     // get the class and the class's tag value
 460     assert(vmClasses::Class_klass()->is_mirror_instance_klass(), "Is not?");
 461 
 462     _klass_tag = _tag_map->find(_o.klass()->java_mirror());
 463   }
 464 
 465   ~CallbackWrapper() {
 466     post_callback_tag_update(_o, _tag_map, _obj_tag);
 467   }
 468 
 469   inline jlong* obj_tag_p()                     { return &_obj_tag; }
 470   inline jlong obj_size() const                 { return _obj_size; }
 471   inline jlong obj_tag() const                  { return _obj_tag; }
 472   inline jlong klass_tag() const                { return _klass_tag; }
 473 };
 474 
 475 // callback post-callback to tag, untag, or update the tag of an object
 476 void inline CallbackWrapper::post_callback_tag_update(const JvmtiHeapwalkObject& o,
 477                                                       JvmtiTagMap* tag_map,
 478                                                       jlong obj_tag) {
 479   if (obj_tag == 0) {
 480     // callback has untagged the object, remove the entry if present
 481     tag_map->remove(o);
 482   } else {
 483     // object was previously tagged or not present - the callback may have
 484     // changed the tag value
 485     assert(Thread::current()->is_VM_thread(), "must be VMThread");
 486     tag_map->add(o, obj_tag);
 487   }
 488 }
 489 
 490 // An extended CallbackWrapper used when reporting an object reference
 491 // to the agent.
 492 //
 493 // {
 494 //   TwoOopCallbackWrapper wrapper(tag_map, referrer, o);
 495 //
 496 //   (*callback)(wrapper.klass_tag(),
 497 //               wrapper.obj_size(),
 498 //               wrapper.obj_tag_p()
 499 //               wrapper.referrer_tag_p(), ...)
 500 //
 501 // }
 502 // wrapper goes out of scope here which results in the destructor
 503 // checking to see if the referrer object has been tagged, untagged,
 504 // or the tag value has changed.
 505 //
 506 class TwoOopCallbackWrapper : public CallbackWrapper {
 507  private:
 508   const JvmtiHeapwalkObject& _referrer;
 509   bool _is_reference_to_self;


 510   jlong _referrer_obj_tag;
 511   jlong _referrer_klass_tag;
 512   jlong* _referrer_tag_p;
 513 
 514   bool is_reference_to_self() const             { return _is_reference_to_self; }
 515 
 516  public:
 517   TwoOopCallbackWrapper(JvmtiTagMap* tag_map, const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& o) :
 518     CallbackWrapper(tag_map, o), _referrer(referrer)
 519   {
 520     // self reference needs to be handled in a special way
 521     _is_reference_to_self = (referrer == o);
 522 
 523     if (_is_reference_to_self) {
 524       _referrer_klass_tag = klass_tag();
 525       _referrer_tag_p = obj_tag_p();
 526     } else {




 527       // get object tag
 528       _referrer_obj_tag = tag_map->find(_referrer);
 529 
 530       _referrer_tag_p = &_referrer_obj_tag;
 531 
 532       // get referrer class tag.
 533       _referrer_klass_tag = tag_map->find(_referrer.klass()->java_mirror());
 534     }
 535   }
 536 
 537   ~TwoOopCallbackWrapper() {
 538     if (!is_reference_to_self()) {
 539       post_callback_tag_update(_referrer,
 540                                tag_map(),
 541                                _referrer_obj_tag);
 542     }
 543   }
 544 
 545   // address of referrer tag
 546   // (for a self reference this will return the same thing as obj_tag_p())
 547   inline jlong* referrer_tag_p() { return _referrer_tag_p; }
 548 
 549   // referrer's class tag
 550   inline jlong referrer_klass_tag() { return _referrer_klass_tag; }
 551 };
 552 
 553 // tag an object
 554 //
 555 // This function is performance critical. If many threads attempt to tag objects
 556 // around the same time then it's possible that the Mutex associated with the
 557 // tag map will be a hot lock.
 558 void JvmtiTagMap::set_tag(jobject object, jlong tag) {
 559   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 560 
 561   // SetTag should not post events because the JavaThread has to
 562   // transition to native for the callback and this cannot stop for
 563   // safepoints with the hashmap lock held.
 564   check_hashmap(nullptr);  /* don't collect dead objects */
 565 
 566   // resolve the object
 567   oop o = JNIHandles::resolve_non_null(object);

 568   // see if the object is already tagged
 569   JvmtiHeapwalkObject obj(o);

 570   if (tag == 0) {
 571     // remove the entry if present
 572     _hashmap->remove(obj);
 573   } else {
 574     // if the object is already tagged or not present then we add/update
 575     // the tag
 576     add(obj, tag);
 577   }
 578 }
 579 
 580 // get the tag for an object
 581 jlong JvmtiTagMap::get_tag(jobject object) {
 582   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
 583 
 584   // GetTag should not post events because the JavaThread has to
 585   // transition to native for the callback and this cannot stop for
 586   // safepoints with the hashmap lock held.
 587   check_hashmap(nullptr); /* don't collect dead objects */
 588 
 589   // resolve the object
 590   oop o = JNIHandles::resolve_non_null(object);
 591 
 592   return find(o);
 593 }
 594 
 595 
 596 // Helper class used to describe the static or instance fields of a class.
 597 // For each field it holds the field index (as defined by the JVMTI specification),
 598 // the field type, and the offset.
 599 
 600 class ClassFieldDescriptor: public CHeapObj<mtInternal> {
 601  private:
 602   int _field_index;
 603   int _field_offset;
 604   char _field_type;
 605   InlineKlass* _inline_klass; // nullptr for heap object
 606   LayoutKind _layout_kind;
 607  public:
 608   ClassFieldDescriptor(int index, const FieldStreamBase& fld) :
 609       _field_index(index), _field_offset(fld.offset()), _field_type(fld.signature()->char_at(0)) {
 610     if (fld.is_flat()) {
 611       const fieldDescriptor& fd = fld.field_descriptor();
 612       InstanceKlass* holder_klass = fd.field_holder();
 613       InlineLayoutInfo* layout_info = holder_klass->inline_layout_info_adr(fd.index());
 614       _inline_klass = layout_info->klass();
 615       _layout_kind = layout_info->kind();
 616     } else {
 617       _inline_klass = nullptr;
 618       _layout_kind = LayoutKind::REFERENCE;
 619     }
 620   }
 621   int field_index()  const  { return _field_index; }
 622   char field_type()  const  { return _field_type; }
 623   int field_offset() const  { return _field_offset; }
 624   bool is_flat()     const  { return _inline_klass != nullptr; }
 625   InlineKlass* inline_klass() const { return _inline_klass; }
 626   LayoutKind layout_kind() const { return _layout_kind; }
 627 };
 628 
 629 class ClassFieldMap: public CHeapObj<mtInternal> {
 630  private:
 631   enum {
 632     initial_field_count = 5
 633   };
 634 
 635   // list of field descriptors
 636   GrowableArray<ClassFieldDescriptor*>* _fields;
 637 
 638   // constructor
 639   ClassFieldMap();
 640 
 641   // calculates number of fields in all interfaces
 642   static int interfaces_field_count(InstanceKlass* ik);
 643 
 644   // add a field
 645   void add(int index, const FieldStreamBase& fld);
 646 
 647  public:
 648   ~ClassFieldMap();
 649 
 650   // access
 651   int field_count()                     { return _fields->length(); }
 652   ClassFieldDescriptor* field_at(int i) { return _fields->at(i); }
 653 
 654   // functions to create maps of static or instance fields
 655   static ClassFieldMap* create_map_of_static_fields(Klass* k);
 656   static ClassFieldMap* create_map_of_instance_fields(Klass* k);
 657 };
 658 
 659 ClassFieldMap::ClassFieldMap() {
 660   _fields = new (mtServiceability)
 661     GrowableArray<ClassFieldDescriptor*>(initial_field_count, mtServiceability);
 662 }
 663 
 664 ClassFieldMap::~ClassFieldMap() {
 665   for (int i=0; i<_fields->length(); i++) {
 666     delete _fields->at(i);
 667   }
 668   delete _fields;
 669 }
 670 
 671 int ClassFieldMap::interfaces_field_count(InstanceKlass* ik) {
 672   const Array<InstanceKlass*>* interfaces = ik->transitive_interfaces();
 673   int count = 0;
 674   for (int i = 0; i < interfaces->length(); i++) {
 675     count += interfaces->at(i)->java_fields_count();
 676 
 677   }
 678   return count;
 679 }
 680 
 681 void ClassFieldMap::add(int index, const FieldStreamBase& fld) {
 682   ClassFieldDescriptor* field = new ClassFieldDescriptor(index, fld);
 683   _fields->append(field);
 684 }
 685 
 686 // Returns a heap allocated ClassFieldMap to describe the static fields
 687 // of the given class.
 688 ClassFieldMap* ClassFieldMap::create_map_of_static_fields(Klass* k) {
 689   InstanceKlass* ik = InstanceKlass::cast(k);
 690 
 691   // create the field map
 692   ClassFieldMap* field_map = new ClassFieldMap();
 693 
 694   // Static fields of interfaces and superclasses are reported as references from the interfaces/superclasses.
 695   // Need to calculate start index of this class fields: number of fields in all interfaces and superclasses.
 696   int index = interfaces_field_count(ik);
 697   for (InstanceKlass* super_klass = ik->super(); super_klass != nullptr; super_klass = super_klass->super()) {
 698     index += super_klass->java_fields_count();
 699   }
 700 
 701   for (JavaFieldStream fld(ik); !fld.done(); fld.next(), index++) {
 702     // ignore instance fields
 703     if (!fld.access_flags().is_static()) {
 704       continue;
 705     }
 706     field_map->add(index, fld);
 707   }
 708 
 709   return field_map;
 710 }
 711 
 712 // Returns a heap allocated ClassFieldMap to describe the instance fields
 713 // of the given class. All instance fields are included (this means public
 714 // and private fields declared in superclasses too).
 715 ClassFieldMap* ClassFieldMap::create_map_of_instance_fields(Klass* k) {
 716   InstanceKlass* ik = InstanceKlass::cast(k);
 717 
 718   // create the field map
 719   ClassFieldMap* field_map = new ClassFieldMap();
 720 
 721   // fields of the superclasses are reported first, so need to know total field number to calculate field indices
 722   int total_field_number = interfaces_field_count(ik);
 723   for (InstanceKlass* klass = ik; klass != nullptr; klass = klass->super()) {
 724     total_field_number += klass->java_fields_count();
 725   }
 726 
 727   for (InstanceKlass* klass = ik; klass != nullptr; klass = klass->super()) {
 728     JavaFieldStream fld(klass);
 729     int start_index = total_field_number - klass->java_fields_count();
 730     for (int index = 0; !fld.done(); fld.next(), index++) {
 731       // ignore static fields
 732       if (fld.access_flags().is_static()) {
 733         continue;
 734       }
 735       field_map->add(start_index + index, fld);
 736     }
 737     // update total_field_number for superclass (decrease by the field count in the current class)
 738     total_field_number = start_index;
 739   }
 740 
 741   return field_map;
 742 }
 743 
 744 // Helper class used to cache a ClassFileMap for the instance fields of
 745 // a cache. A JvmtiCachedClassFieldMap can be cached by an InstanceKlass during
 746 // heap iteration and avoid creating a field map for each object in the heap
 747 // (only need to create the map when the first instance of a class is encountered).
 748 //
 749 class JvmtiCachedClassFieldMap : public CHeapObj<mtInternal> {
 750  private:
 751   enum {
 752      initial_class_count = 200
 753   };
 754   ClassFieldMap* _field_map;
 755 
 756   ClassFieldMap* field_map() const { return _field_map; }
 757 
 758   JvmtiCachedClassFieldMap(ClassFieldMap* field_map);
 759   ~JvmtiCachedClassFieldMap();
 760 
 761   static GrowableArray<InstanceKlass*>* _class_list;
 762   static void add_to_class_list(InstanceKlass* ik);
 763 
 764  public:
 765   // returns the field map for a given klass (returning map cached
 766   // by InstanceKlass if possible
 767   static ClassFieldMap* get_map_of_instance_fields(Klass* k);
 768 
 769   // removes the field map from all instanceKlasses - should be
 770   // called before VM operation completes
 771   static void clear_cache();
 772 
 773   // returns the number of ClassFieldMap cached by instanceKlasses
 774   static int cached_field_map_count();
 775 };
 776 
 777 GrowableArray<InstanceKlass*>* JvmtiCachedClassFieldMap::_class_list;
 778 
 779 JvmtiCachedClassFieldMap::JvmtiCachedClassFieldMap(ClassFieldMap* field_map) {
 780   _field_map = field_map;
 781 }
 782 
 783 JvmtiCachedClassFieldMap::~JvmtiCachedClassFieldMap() {
 784   if (_field_map != nullptr) {
 785     delete _field_map;
 786   }
 787 }

 799      _is_active = true;
 800    }
 801    ~ClassFieldMapCacheMark() {
 802      JvmtiCachedClassFieldMap::clear_cache();
 803      _is_active = false;
 804    }
 805    static bool is_active() { return _is_active; }
 806 };
 807 
 808 bool ClassFieldMapCacheMark::_is_active;
 809 
 810 // record that the given InstanceKlass is caching a field map
 811 void JvmtiCachedClassFieldMap::add_to_class_list(InstanceKlass* ik) {
 812   if (_class_list == nullptr) {
 813     _class_list = new (mtServiceability)
 814       GrowableArray<InstanceKlass*>(initial_class_count, mtServiceability);
 815   }
 816   _class_list->push(ik);
 817 }
 818 
 819 // returns the instance field map for the given klass
 820 // (returns field map cached by the InstanceKlass if possible)
 821 ClassFieldMap* JvmtiCachedClassFieldMap::get_map_of_instance_fields(Klass *k) {
 822   assert(Thread::current()->is_VM_thread(), "must be VMThread");
 823   assert(ClassFieldMapCacheMark::is_active(), "ClassFieldMapCacheMark not active");
 824 

 825   InstanceKlass* ik = InstanceKlass::cast(k);
 826 
 827   // return cached map if possible
 828   JvmtiCachedClassFieldMap* cached_map = ik->jvmti_cached_class_field_map();
 829   if (cached_map != nullptr) {
 830     assert(cached_map->field_map() != nullptr, "missing field list");
 831     return cached_map->field_map();
 832   } else {
 833     ClassFieldMap* field_map = ClassFieldMap::create_map_of_instance_fields(k);
 834     cached_map = new JvmtiCachedClassFieldMap(field_map);
 835     ik->set_jvmti_cached_class_field_map(cached_map);
 836     add_to_class_list(ik);
 837     return field_map;
 838   }
 839 }
 840 
 841 // remove the fields maps cached from all instanceKlasses
 842 void JvmtiCachedClassFieldMap::clear_cache() {
 843   assert(Thread::current()->is_VM_thread(), "must be VMThread");
 844   if (_class_list != nullptr) {
 845     for (int i = 0; i < _class_list->length(); i++) {
 846       InstanceKlass* ik = _class_list->at(i);
 847       JvmtiCachedClassFieldMap* cached_map = ik->jvmti_cached_class_field_map();
 848       assert(cached_map != nullptr, "should not be null");
 849       ik->set_jvmti_cached_class_field_map(nullptr);
 850       delete cached_map;  // deletes the encapsulated field map
 851     }
 852     delete _class_list;
 853     _class_list = nullptr;

 865                                               int heap_filter) {
 866   // apply the heap filter
 867   if (obj_tag != 0) {
 868     // filter out tagged objects
 869     if (heap_filter & JVMTI_HEAP_FILTER_TAGGED) return true;
 870   } else {
 871     // filter out untagged objects
 872     if (heap_filter & JVMTI_HEAP_FILTER_UNTAGGED) return true;
 873   }
 874   if (klass_tag != 0) {
 875     // filter out objects with tagged classes
 876     if (heap_filter & JVMTI_HEAP_FILTER_CLASS_TAGGED) return true;
 877   } else {
 878     // filter out objects with untagged classes.
 879     if (heap_filter & JVMTI_HEAP_FILTER_CLASS_UNTAGGED) return true;
 880   }
 881   return false;
 882 }
 883 
 884 // helper function to indicate if an object is filtered by a klass filter
 885 static inline bool is_filtered_by_klass_filter(const JvmtiHeapwalkObject& obj, Klass* klass_filter) {
 886   if (klass_filter != nullptr) {
 887     if (obj.klass() != klass_filter) {
 888       return true;
 889     }
 890   }
 891   return false;
 892 }
 893 
 894 // helper function to tell if a field is a primitive field or not
 895 static inline bool is_primitive_field_type(char type) {
 896   return (type != JVM_SIGNATURE_CLASS && type != JVM_SIGNATURE_ARRAY);
 897 }
 898 
 899 // helper function to copy the value from location addr to jvalue.
 900 static inline void copy_to_jvalue(jvalue *v, address addr, jvmtiPrimitiveType value_type) {
 901   switch (value_type) {
 902     case JVMTI_PRIMITIVE_TYPE_BOOLEAN : { v->z = *(jboolean*)addr; break; }
 903     case JVMTI_PRIMITIVE_TYPE_BYTE    : { v->b = *(jbyte*)addr;    break; }
 904     case JVMTI_PRIMITIVE_TYPE_CHAR    : { v->c = *(jchar*)addr;    break; }
 905     case JVMTI_PRIMITIVE_TYPE_SHORT   : { v->s = *(jshort*)addr;   break; }
 906     case JVMTI_PRIMITIVE_TYPE_INT     : { v->i = *(jint*)addr;     break; }
 907     case JVMTI_PRIMITIVE_TYPE_LONG    : { v->j = *(jlong*)addr;    break; }
 908     case JVMTI_PRIMITIVE_TYPE_FLOAT   : { v->f = *(jfloat*)addr;   break; }
 909     case JVMTI_PRIMITIVE_TYPE_DOUBLE  : { v->d = *(jdouble*)addr;  break; }
 910     default: ShouldNotReachHere();
 911   }
 912 }
 913 
 914 // helper function to invoke string primitive value callback
 915 // returns visit control flags
 916 static jint invoke_string_value_callback(jvmtiStringPrimitiveValueCallback cb,
 917                                          CallbackWrapper* wrapper,
 918                                          const JvmtiHeapwalkObject& obj,
 919                                          void* user_data)
 920 {
 921   assert(!obj.is_flat(), "cannot be flat");
 922   oop str = obj.obj();
 923   assert(str->klass() == vmClasses::String_klass(), "not a string");
 924 
 925   typeArrayOop s_value = java_lang_String::value(str);
 926 
 927   // JDK-6584008: the value field may be null if a String instance is
 928   // partially constructed.
 929   if (s_value == nullptr) {
 930     return 0;
 931   }
 932   // get the string value and length
 933   // (string value may be offset from the base)
 934   int s_len = java_lang_String::length(str);
 935   bool is_latin1 = java_lang_String::is_latin1(str);
 936   jchar* value;
 937   if (s_len > 0) {
 938     if (!is_latin1) {
 939       value = s_value->char_at_addr(0);
 940     } else {
 941       // Inflate latin1 encoded string to UTF16
 942       jchar* buf = NEW_C_HEAP_ARRAY(jchar, s_len, mtInternal);

 951   }
 952 
 953   // invoke the callback
 954   jint res = (*cb)(wrapper->klass_tag(),
 955                    wrapper->obj_size(),
 956                    wrapper->obj_tag_p(),
 957                    value,
 958                    (jint)s_len,
 959                    user_data);
 960 
 961   if (is_latin1 && s_len > 0) {
 962     FREE_C_HEAP_ARRAY(jchar, value);
 963   }
 964   return res;
 965 }
 966 
 967 // helper function to invoke string primitive value callback
 968 // returns visit control flags
 969 static jint invoke_array_primitive_value_callback(jvmtiArrayPrimitiveValueCallback cb,
 970                                                   CallbackWrapper* wrapper,
 971                                                   const JvmtiHeapwalkObject& obj,
 972                                                   void* user_data)
 973 {
 974   assert(!obj.is_flat(), "cannot be flat");
 975   assert(obj.obj()->is_typeArray(), "not a primitive array");
 976 
 977   // get base address of first element
 978   typeArrayOop array = typeArrayOop(obj.obj());
 979   BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
 980   void* elements = array->base(type);
 981 
 982   // jvmtiPrimitiveType is defined so this mapping is always correct
 983   jvmtiPrimitiveType elem_type = (jvmtiPrimitiveType)type2char(type);
 984 
 985   return (*cb)(wrapper->klass_tag(),
 986                wrapper->obj_size(),
 987                wrapper->obj_tag_p(),
 988                (jint)array->length(),
 989                elem_type,
 990                elements,
 991                user_data);
 992 }
 993 
 994 // helper function to invoke the primitive field callback for all static fields
 995 // of a given class
 996 static jint invoke_primitive_field_callback_for_static_fields
 997   (CallbackWrapper* wrapper,
 998    oop obj,

1048                      &reference_info,
1049                      wrapper->klass_tag(),
1050                      wrapper->obj_tag_p(),
1051                      value,
1052                      value_type,
1053                      user_data);
1054     if (res & JVMTI_VISIT_ABORT) {
1055       delete field_map;
1056       return res;
1057     }
1058   }
1059 
1060   delete field_map;
1061   return 0;
1062 }
1063 
1064 // helper function to invoke the primitive field callback for all instance fields
1065 // of a given object
1066 static jint invoke_primitive_field_callback_for_instance_fields(
1067   CallbackWrapper* wrapper,
1068   const JvmtiHeapwalkObject& obj,
1069   jvmtiPrimitiveFieldCallback cb,
1070   void* user_data)
1071 {
1072   // for instance fields only the index will be set
1073   static jvmtiHeapReferenceInfo reference_info = { 0 };
1074 
1075   // get the map of the instance fields
1076   ClassFieldMap* fields = JvmtiCachedClassFieldMap::get_map_of_instance_fields(obj.klass());
1077 
1078   // invoke the callback for each instance primitive field
1079   for (int i=0; i<fields->field_count(); i++) {
1080     ClassFieldDescriptor* field = fields->field_at(i);
1081 
1082     // ignore non-primitive fields
1083     char type = field->field_type();
1084     if (!is_primitive_field_type(type)) {
1085       continue;
1086     }
1087     // one-to-one mapping
1088     jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type;
1089 
1090     // get field value
1091     address addr = cast_from_oop<address>(obj.obj()) + obj.offset() + field->field_offset();

1092     jvalue value;
1093     copy_to_jvalue(&value, addr, value_type);
1094 
1095     // field index
1096     reference_info.field.index = field->field_index();
1097 
1098     // invoke the callback
1099     jint res = (*cb)(JVMTI_HEAP_REFERENCE_FIELD,
1100                      &reference_info,
1101                      wrapper->klass_tag(),
1102                      wrapper->obj_tag_p(),
1103                      value,
1104                      value_type,
1105                      user_data);
1106     if (res & JVMTI_VISIT_ABORT) {
1107       return res;
1108     }
1109   }
1110   return 0;
1111 }

1185 
1186 // invoked for each object in the heap
1187 void IterateOverHeapObjectClosure::do_object(oop o) {
1188   assert(o != nullptr, "Heap iteration should never produce null!");
1189   // check if iteration has been halted
1190   if (is_iteration_aborted()) return;
1191 
1192   // instanceof check when filtering by klass
1193   if (klass() != nullptr && !o->is_a(klass())) {
1194     return;
1195   }
1196 
1197   // skip if object is a dormant shared object whose mirror hasn't been loaded
1198   if (o->klass()->java_mirror() == nullptr) {
1199     log_debug(aot, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(o),
1200                          o->klass()->external_name());
1201     return;
1202   }
1203 
1204   // prepare for the calllback
1205   JvmtiHeapwalkObject wrapper_obj(o);
1206   CallbackWrapper wrapper(tag_map(), wrapper_obj);
1207 
1208   // if the object is tagged and we're only interested in untagged objects
1209   // then don't invoke the callback. Similarly, if the object is untagged
1210   // and we're only interested in tagged objects we skip the callback.
1211   if (wrapper.obj_tag() != 0) {
1212     if (object_filter() == JVMTI_HEAP_OBJECT_UNTAGGED) return;
1213   } else {
1214     if (object_filter() == JVMTI_HEAP_OBJECT_TAGGED) return;
1215   }
1216 
1217   // invoke the agent's callback
1218   jvmtiIterationControl control = (*object_callback())(wrapper.klass_tag(),
1219                                                        wrapper.obj_size(),
1220                                                        wrapper.obj_tag_p(),
1221                                                        (void*)user_data());
1222   if (control == JVMTI_ITERATION_ABORT) {
1223     set_iteration_aborted(true);
1224   }
1225 }
1226 

1238   int heap_filter() const                          { return _heap_filter; }
1239   const jvmtiHeapCallbacks* callbacks() const      { return _callbacks; }
1240   Klass* klass() const                             { return _klass; }
1241   const void* user_data() const                    { return _user_data; }
1242 
1243   // indicates if the iteration has been aborted
1244   bool _iteration_aborted;
1245   bool is_iteration_aborted() const                { return _iteration_aborted; }
1246 
1247   // used to check the visit control flags. If the abort flag is set
1248   // then we set the iteration aborted flag so that the iteration completes
1249   // without processing any further objects
1250   bool check_flags_for_abort(jint flags) {
1251     bool is_abort = (flags & JVMTI_VISIT_ABORT) != 0;
1252     if (is_abort) {
1253       _iteration_aborted = true;
1254     }
1255     return is_abort;
1256   }
1257 
1258   void visit_object(const JvmtiHeapwalkObject& obj);
1259   void visit_flat_fields(const JvmtiHeapwalkObject& obj);
1260   void visit_flat_array_elements(const JvmtiHeapwalkObject& obj);
1261 
1262  public:
1263   IterateThroughHeapObjectClosure(JvmtiTagMap* tag_map,
1264                                   Klass* klass,
1265                                   int heap_filter,
1266                                   const jvmtiHeapCallbacks* heap_callbacks,
1267                                   const void* user_data) :
1268     _tag_map(tag_map),
1269     _klass(klass),
1270     _heap_filter(heap_filter),
1271     _callbacks(heap_callbacks),
1272     _user_data(user_data),
1273     _iteration_aborted(false)
1274   {
1275   }
1276 
1277   void do_object(oop obj);
1278 };
1279 
1280 // invoked for each object in the heap
1281 void IterateThroughHeapObjectClosure::do_object(oop obj) {
1282   assert(obj != nullptr, "Heap iteration should never produce null!");
1283   // check if iteration has been halted
1284   if (is_iteration_aborted()) return;
1285 



1286   // skip if object is a dormant shared object whose mirror hasn't been loaded
1287   if (obj != nullptr && obj->klass()->java_mirror() == nullptr) {
1288     log_debug(aot, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(obj),
1289                          obj->klass()->external_name());
1290     return;
1291   }
1292 
1293   visit_object(obj);
1294 }
1295 
1296 void IterateThroughHeapObjectClosure::visit_object(const JvmtiHeapwalkObject& obj) {
1297   // apply class filter
1298   if (is_filtered_by_klass_filter(obj, klass())) return;
1299 
1300   // prepare for callback
1301   CallbackWrapper wrapper(tag_map(), obj);
1302 
1303   // check if filtered by the heap filter
1304   if (is_filtered_by_heap_filter(wrapper.obj_tag(), wrapper.klass_tag(), heap_filter())) {
1305     return;
1306   }
1307 
1308   // for arrays we need the length, otherwise -1
1309   bool is_array = obj.klass()->is_array_klass();
1310   int len = is_array ? arrayOop(obj.obj())->length() : -1;
1311 
1312   // invoke the object callback (if callback is provided)
1313   if (callbacks()->heap_iteration_callback != nullptr) {
1314     jvmtiHeapIterationCallback cb = callbacks()->heap_iteration_callback;
1315     jint res = (*cb)(wrapper.klass_tag(),
1316                      wrapper.obj_size(),
1317                      wrapper.obj_tag_p(),
1318                      (jint)len,
1319                      (void*)user_data());
1320     if (check_flags_for_abort(res)) return;
1321   }
1322 
1323   // for objects and classes we report primitive fields if callback provided
1324   if (callbacks()->primitive_field_callback != nullptr && obj.klass()->is_instance_klass()) {
1325     jint res;
1326     jvmtiPrimitiveFieldCallback cb = callbacks()->primitive_field_callback;
1327     if (obj.klass() == vmClasses::Class_klass()) {
1328       assert(!obj.is_flat(), "Class object cannot be flattened");
1329       res = invoke_primitive_field_callback_for_static_fields(&wrapper,
1330                                                               obj.obj(),
1331                                                               cb,
1332                                                               (void*)user_data());
1333     } else {
1334       res = invoke_primitive_field_callback_for_instance_fields(&wrapper,
1335                                                                 obj,
1336                                                                 cb,
1337                                                                 (void*)user_data());
1338     }
1339     if (check_flags_for_abort(res)) return;
1340   }
1341 
1342   // string callback
1343   if (!is_array &&
1344       callbacks()->string_primitive_value_callback != nullptr &&
1345       obj.klass() == vmClasses::String_klass()) {
1346     jint res = invoke_string_value_callback(
1347                 callbacks()->string_primitive_value_callback,
1348                 &wrapper,
1349                 obj,
1350                 (void*)user_data());
1351     if (check_flags_for_abort(res)) return;
1352   }
1353 
1354   // array callback
1355   if (is_array &&
1356       callbacks()->array_primitive_value_callback != nullptr &&
1357       obj.klass()->is_typeArray_klass()) {
1358     jint res = invoke_array_primitive_value_callback(
1359                callbacks()->array_primitive_value_callback,
1360                &wrapper,
1361                obj,
1362                (void*)user_data());
1363     if (check_flags_for_abort(res)) return;
1364   }

1365 
1366   // All info for the object is reported.
1367 
1368   // If the object has flat fields, report them as heap objects.
1369   if (obj.klass()->is_instance_klass()) {
1370     if (InstanceKlass::cast(obj.klass())->has_inline_type_fields()) {
1371       visit_flat_fields(obj);
1372       // check if iteration has been halted
1373       if (is_iteration_aborted()) {
1374         return;
1375       }
1376     }
1377   }
1378   // If the object is flat array, report all elements as heap objects.
1379   if (is_array && obj.obj()->is_flatArray()) {
1380     assert(!obj.is_flat(), "Array object cannot be flattened");
1381     visit_flat_array_elements(obj);
1382   }
1383 }
1384 
1385 void IterateThroughHeapObjectClosure::visit_flat_fields(const JvmtiHeapwalkObject& obj) {
1386   // iterate over instance fields
1387   ClassFieldMap* fields = JvmtiCachedClassFieldMap::get_map_of_instance_fields(obj.klass());
1388   for (int i = 0; i < fields->field_count(); i++) {
1389     ClassFieldDescriptor* field = fields->field_at(i);
1390     // skip non-flat and (for safety) primitive fields
1391     if (!field->is_flat() || is_primitive_field_type(field->field_type())) {
1392       continue;
1393     }
1394 
1395     int field_offset = field->field_offset();
1396     if (obj.is_flat()) {
1397       // the object is inlined, its fields are stored without the header
1398       field_offset += obj.offset() - obj.inline_klass()->payload_offset();
1399     }
1400     // check for possible nulls
1401     bool can_be_null = field->layout_kind() == LayoutKind::NULLABLE_ATOMIC_FLAT;
1402     if (can_be_null) {
1403       address payload = cast_from_oop<address>(obj.obj()) + field_offset;
1404       if (field->inline_klass()->is_payload_marked_as_null(payload)) {
1405         continue;
1406       }
1407     }
1408     JvmtiHeapwalkObject field_obj(obj.obj(), field_offset, field->inline_klass(), field->layout_kind());
1409 
1410     visit_object(field_obj);
1411 
1412     // check if iteration has been halted
1413     if (is_iteration_aborted()) {
1414       return;
1415     }
1416   }
1417 }
1418 
1419 void IterateThroughHeapObjectClosure::visit_flat_array_elements(const JvmtiHeapwalkObject& obj) {
1420   assert(!obj.is_flat() && obj.obj()->is_flatArray() , "sanity check");
1421   flatArrayOop array = flatArrayOop(obj.obj());
1422   FlatArrayKlass* faklass = FlatArrayKlass::cast(array->klass());
1423   InlineKlass* vk = InlineKlass::cast(faklass->element_klass());
1424   bool need_null_check = faklass->layout_kind() == LayoutKind::NULLABLE_ATOMIC_FLAT;
1425 
1426   for (int index = 0; index < array->length(); index++) {
1427     address addr = (address)array->value_at_addr(index, faklass->layout_helper());
1428     // check for null
1429     if (need_null_check) {
1430       if (vk->is_payload_marked_as_null(addr)) {
1431         continue;
1432       }
1433     }
1434 
1435     // offset in the array oop
1436     int offset = (int)(addr - cast_from_oop<address>(array));
1437     JvmtiHeapwalkObject elem(obj.obj(), offset, vk, faklass->layout_kind());
1438 
1439     visit_object(elem);
1440 
1441     // check if iteration has been halted
1442     if (is_iteration_aborted()) {
1443       return;
1444     }
1445   }
1446 }
1447 
1448 // Deprecated function to iterate over all objects in the heap
1449 void JvmtiTagMap::iterate_over_heap(jvmtiHeapObjectFilter object_filter,
1450                                     Klass* klass,
1451                                     jvmtiHeapObjectCallback heap_object_callback,
1452                                     const void* user_data)
1453 {
1454   // EA based optimizations on tagged objects are already reverted.
1455   EscapeBarrier eb(object_filter == JVMTI_HEAP_OBJECT_UNTAGGED ||
1456                    object_filter == JVMTI_HEAP_OBJECT_EITHER,
1457                    JavaThread::current());
1458   eb.deoptimize_objects_all_threads();
1459   Arena dead_object_arena(mtServiceability);
1460   GrowableArray <jlong> dead_objects(&dead_object_arena, 10, 0, 0);
1461   {
1462     MutexLocker ml(Heap_lock);
1463     IterateOverHeapObjectClosure blk(this,
1464                                      klass,
1465                                      object_filter,
1466                                      heap_object_callback,
1467                                      user_data);
1468     VM_HeapIterateOperation op(&blk, &dead_objects);
1469     VMThread::execute(&op);
1470   }
1471   convert_flat_object_entries();
1472 
1473   // Post events outside of Heap_lock
1474   post_dead_objects(&dead_objects);
1475 }
1476 
1477 
1478 // Iterates over all objects in the heap
1479 void JvmtiTagMap::iterate_through_heap(jint heap_filter,
1480                                        Klass* klass,
1481                                        const jvmtiHeapCallbacks* callbacks,
1482                                        const void* user_data)
1483 {
1484   // EA based optimizations on tagged objects are already reverted.
1485   EscapeBarrier eb(!(heap_filter & JVMTI_HEAP_FILTER_UNTAGGED), JavaThread::current());
1486   eb.deoptimize_objects_all_threads();
1487 
1488   Arena dead_object_arena(mtServiceability);
1489   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
1490   {
1491     MutexLocker ml(Heap_lock);
1492     IterateThroughHeapObjectClosure blk(this,
1493                                         klass,
1494                                         heap_filter,
1495                                         callbacks,
1496                                         user_data);
1497     VM_HeapIterateOperation op(&blk, &dead_objects);
1498     VMThread::execute(&op);
1499   }
1500   convert_flat_object_entries();
1501 
1502   // Post events outside of Heap_lock
1503   post_dead_objects(&dead_objects);
1504 }
1505 
1506 void JvmtiTagMap::remove_dead_entries_locked(GrowableArray<jlong>* objects) {
1507   assert(is_locked(), "precondition");
1508   if (_needs_cleaning) {
1509     // Recheck whether to post object free events under the lock.
1510     if (!env()->is_enabled(JVMTI_EVENT_OBJECT_FREE)) {
1511       objects = nullptr;
1512     }
1513     log_info(jvmti, table)("TagMap table needs cleaning%s",
1514                            ((objects != nullptr) ? " and posting" : ""));
1515     _hashmap->remove_dead_entries(objects);
1516     _needs_cleaning = false;
1517   }
1518 }
1519 
1520 void JvmtiTagMap::remove_dead_entries(GrowableArray<jlong>* objects) {
1521   MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1522   remove_dead_entries_locked(objects);
1523 }
1524 
1525 void JvmtiTagMap::post_dead_objects(GrowableArray<jlong>* const objects) {
1526   assert(Thread::current()->is_Java_thread(), "Must post from JavaThread");
1527   if (objects != nullptr && objects->length() > 0) {
1528     JvmtiExport::post_object_free(env(), objects);
1529     log_info(jvmti, table)("%d free object posted", objects->length());
1530   }
1531 }
1532 
1533 void JvmtiTagMap::remove_and_post_dead_objects() {
1534   ResourceMark rm;
1535   GrowableArray<jlong> objects;

1648       if (error != JVMTI_ERROR_NONE) {
1649         if (object_result_ptr != nullptr) {
1650           _env->Deallocate((unsigned char*)object_result_ptr);
1651         }
1652         return error;
1653       }
1654       for (int i=0; i<count; i++) {
1655         (*tag_result_ptr)[i] = (jlong)_tag_results->at(i);
1656       }
1657     }
1658 
1659     *count_ptr = count;
1660     return JVMTI_ERROR_NONE;
1661   }
1662 };
1663 
1664 // return the list of objects with the specified tags
1665 jvmtiError JvmtiTagMap::get_objects_with_tags(const jlong* tags,
1666   jint count, jint* count_ptr, jobject** object_result_ptr, jlong** tag_result_ptr) {
1667 
1668   // ensure flat object conversion is completed
1669   convert_flat_object_entries();
1670 
1671   TagObjectCollector collector(env(), tags, count);
1672   {
1673     // iterate over all tagged objects
1674     MutexLocker ml(lock(), Mutex::_no_safepoint_check_flag);
1675     // Can't post ObjectFree events here from a JavaThread, so this
1676     // will race with the gc_notification thread in the tiny
1677     // window where the object is not marked but hasn't been notified that
1678     // it is collected yet.
1679     _hashmap->entry_iterate(&collector);
1680   }
1681   return collector.result(count_ptr, object_result_ptr, tag_result_ptr);
1682 }
1683 
1684 // helper to map a jvmtiHeapReferenceKind to an old style jvmtiHeapRootKind
1685 // (not performance critical as only used for roots)
1686 static jvmtiHeapRootKind toJvmtiHeapRootKind(jvmtiHeapReferenceKind kind) {
1687   switch (kind) {
1688     case JVMTI_HEAP_REFERENCE_JNI_GLOBAL:   return JVMTI_HEAP_ROOT_JNI_GLOBAL;
1689     case JVMTI_HEAP_REFERENCE_SYSTEM_CLASS: return JVMTI_HEAP_ROOT_SYSTEM_CLASS;
1690     case JVMTI_HEAP_REFERENCE_STACK_LOCAL:  return JVMTI_HEAP_ROOT_STACK_LOCAL;
1691     case JVMTI_HEAP_REFERENCE_JNI_LOCAL:    return JVMTI_HEAP_ROOT_JNI_LOCAL;
1692     case JVMTI_HEAP_REFERENCE_THREAD:       return JVMTI_HEAP_ROOT_THREAD;
1693     case JVMTI_HEAP_REFERENCE_OTHER:        return JVMTI_HEAP_ROOT_OTHER;
1694     default: ShouldNotReachHere();          return JVMTI_HEAP_ROOT_OTHER;
1695   }
1696 }
1697 
1698 // Base class for all heap walk contexts. The base class maintains a flag
1699 // to indicate if the context is valid or not.
1700 class HeapWalkContext {
1701  private:
1702   bool _valid;
1703  public:
1704   HeapWalkContext(bool valid)                   { _valid = valid; }
1705   void invalidate()                             { _valid = false; }
1706   bool is_valid() const                         { return _valid; }
1707 };
1708 
1709 // A basic heap walk context for the deprecated heap walking functions.
1710 // The context for a basic heap walk are the callbacks and fields used by
1711 // the referrer caching scheme.
1712 class BasicHeapWalkContext: public HeapWalkContext {
1713  private:
1714   jvmtiHeapRootCallback _heap_root_callback;
1715   jvmtiStackReferenceCallback _stack_ref_callback;
1716   jvmtiObjectReferenceCallback _object_ref_callback;
1717 
1718   // used for caching
1719   JvmtiHeapwalkObject _last_referrer;
1720   jlong _last_referrer_tag;
1721 
1722  public:
1723   BasicHeapWalkContext() : HeapWalkContext(false) { }
1724 
1725   BasicHeapWalkContext(jvmtiHeapRootCallback heap_root_callback,
1726                        jvmtiStackReferenceCallback stack_ref_callback,
1727                        jvmtiObjectReferenceCallback object_ref_callback) :
1728     HeapWalkContext(true),
1729     _heap_root_callback(heap_root_callback),
1730     _stack_ref_callback(stack_ref_callback),
1731     _object_ref_callback(object_ref_callback),
1732     _last_referrer(),
1733     _last_referrer_tag(0) {
1734   }
1735 
1736   // accessors
1737   jvmtiHeapRootCallback heap_root_callback() const         { return _heap_root_callback; }
1738   jvmtiStackReferenceCallback stack_ref_callback() const   { return _stack_ref_callback; }
1739   jvmtiObjectReferenceCallback object_ref_callback() const { return _object_ref_callback;  }
1740 
1741   JvmtiHeapwalkObject last_referrer() const    { return _last_referrer; }
1742   void set_last_referrer(const JvmtiHeapwalkObject& referrer) { _last_referrer = referrer; }
1743   jlong last_referrer_tag() const         { return _last_referrer_tag; }
1744   void set_last_referrer_tag(jlong value) { _last_referrer_tag = value; }
1745 };
1746 
1747 // The advanced heap walk context for the FollowReferences functions.
1748 // The context is the callbacks, and the fields used for filtering.
1749 class AdvancedHeapWalkContext: public HeapWalkContext {
1750  private:
1751   jint _heap_filter;
1752   Klass* _klass_filter;
1753   const jvmtiHeapCallbacks* _heap_callbacks;
1754 
1755  public:
1756   AdvancedHeapWalkContext() : HeapWalkContext(false) { }
1757 
1758   AdvancedHeapWalkContext(jint heap_filter,
1759                            Klass* klass_filter,
1760                            const jvmtiHeapCallbacks* heap_callbacks) :
1761     HeapWalkContext(true),
1762     _heap_filter(heap_filter),

1795   static bool is_basic_heap_walk()           { return _heap_walk_type == basic; }
1796   static bool is_advanced_heap_walk()        { return _heap_walk_type == advanced; }
1797 
1798   // context for basic style heap walk
1799   static BasicHeapWalkContext _basic_context;
1800   static BasicHeapWalkContext* basic_context() {
1801     assert(_basic_context.is_valid(), "invalid");
1802     return &_basic_context;
1803   }
1804 
1805   // context for advanced style heap walk
1806   static AdvancedHeapWalkContext _advanced_context;
1807   static AdvancedHeapWalkContext* advanced_context() {
1808     assert(_advanced_context.is_valid(), "invalid");
1809     return &_advanced_context;
1810   }
1811 
1812   // context needed for all heap walks
1813   static JvmtiTagMap* _tag_map;
1814   static const void* _user_data;
1815   static JvmtiHeapwalkVisitStack* _visit_stack;

1816 
1817   // accessors
1818   static JvmtiTagMap* tag_map()                        { return _tag_map; }
1819   static const void* user_data()                       { return _user_data; }
1820   static JvmtiHeapwalkVisitStack* visit_stack()        { return _visit_stack; }
1821 
1822   // if the object hasn't been visited then push it onto the visit stack
1823   // so that it will be visited later
1824   static inline bool check_for_visit(const JvmtiHeapwalkObject&obj) {
1825     visit_stack()->check_for_visit(obj);
1826     return true;
1827   }
1828 
1829   // return element count if the obj is array, -1 otherwise
1830   static jint get_array_length(const JvmtiHeapwalkObject& obj) {
1831     if (!obj.klass()->is_array_klass()) {
1832       return -1;
1833     }
1834     assert(!obj.is_flat(), "array cannot be flat");
1835     return (jint)arrayOop(obj.obj())->length();
1836   }
1837 
1838 
1839   // invoke basic style callbacks
1840   static inline bool invoke_basic_heap_root_callback
1841     (jvmtiHeapRootKind root_kind, const JvmtiHeapwalkObject& obj);
1842   static inline bool invoke_basic_stack_ref_callback
1843     (jvmtiHeapRootKind root_kind, jlong thread_tag, jint depth, jmethodID method,
1844      int slot, const JvmtiHeapwalkObject& obj);
1845   static inline bool invoke_basic_object_reference_callback
1846     (jvmtiObjectReferenceKind ref_kind, const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint index);
1847 
1848   // invoke advanced style callbacks
1849   static inline bool invoke_advanced_heap_root_callback
1850     (jvmtiHeapReferenceKind ref_kind, const JvmtiHeapwalkObject& obj);
1851   static inline bool invoke_advanced_stack_ref_callback
1852     (jvmtiHeapReferenceKind ref_kind, jlong thread_tag, jlong tid, int depth,
1853      jmethodID method, jlocation bci, jint slot, const JvmtiHeapwalkObject& obj);
1854   static inline bool invoke_advanced_object_reference_callback
1855     (jvmtiHeapReferenceKind ref_kind, const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint index);
1856 
1857   // used to report the value of primitive fields
1858   static inline bool report_primitive_field
1859     (jvmtiHeapReferenceKind ref_kind, const JvmtiHeapwalkObject& obj, jint index, address addr, char type);
1860 
1861  public:
1862   // initialize for basic mode
1863   static void initialize_for_basic_heap_walk(JvmtiTagMap* tag_map,

1864                                              const void* user_data,
1865                                              BasicHeapWalkContext context,
1866                                              JvmtiHeapwalkVisitStack* visit_stack);
1867 
1868   // initialize for advanced mode
1869   static void initialize_for_advanced_heap_walk(JvmtiTagMap* tag_map,

1870                                                 const void* user_data,
1871                                                 AdvancedHeapWalkContext context,
1872                                                 JvmtiHeapwalkVisitStack* visit_stack);
1873 
1874    // functions to report roots
1875   static inline bool report_simple_root(jvmtiHeapReferenceKind kind, const JvmtiHeapwalkObject& o);
1876   static inline bool report_jni_local_root(jlong thread_tag, jlong tid, jint depth,
1877     jmethodID m, const JvmtiHeapwalkObject& o);
1878   static inline bool report_stack_ref_root(jlong thread_tag, jlong tid, jint depth,
1879     jmethodID method, jlocation bci, jint slot, const JvmtiHeapwalkObject& o);
1880 
1881   // functions to report references
1882   static inline bool report_array_element_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint index);
1883   static inline bool report_class_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree);
1884   static inline bool report_class_loader_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree);
1885   static inline bool report_signers_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree);
1886   static inline bool report_protection_domain_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree);
1887   static inline bool report_superclass_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree);
1888   static inline bool report_interface_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree);
1889   static inline bool report_static_field_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint slot);
1890   static inline bool report_field_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint slot);
1891   static inline bool report_constant_pool_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint index);
1892   static inline bool report_primitive_array_values(const JvmtiHeapwalkObject& array);
1893   static inline bool report_string_value(const JvmtiHeapwalkObject& str);
1894   static inline bool report_primitive_instance_field(const JvmtiHeapwalkObject& o, jint index, address value, char type);
1895   static inline bool report_primitive_static_field(const JvmtiHeapwalkObject& o, jint index, address value, char type);
1896 };
1897 
1898 // statics
1899 int CallbackInvoker::_heap_walk_type;
1900 BasicHeapWalkContext CallbackInvoker::_basic_context;
1901 AdvancedHeapWalkContext CallbackInvoker::_advanced_context;
1902 JvmtiTagMap* CallbackInvoker::_tag_map;
1903 const void* CallbackInvoker::_user_data;
1904 JvmtiHeapwalkVisitStack* CallbackInvoker::_visit_stack;

1905 
1906 // initialize for basic heap walk (IterateOverReachableObjects et al)
1907 void CallbackInvoker::initialize_for_basic_heap_walk(JvmtiTagMap* tag_map,

1908                                                      const void* user_data,
1909                                                      BasicHeapWalkContext context,
1910                                                      JvmtiHeapwalkVisitStack* visit_stack) {
1911   _tag_map = tag_map;

1912   _user_data = user_data;
1913   _basic_context = context;
1914   _advanced_context.invalidate();       // will trigger assertion if used
1915   _heap_walk_type = basic;
1916   _visit_stack = visit_stack;
1917 }
1918 
1919 // initialize for advanced heap walk (FollowReferences)
1920 void CallbackInvoker::initialize_for_advanced_heap_walk(JvmtiTagMap* tag_map,

1921                                                         const void* user_data,
1922                                                         AdvancedHeapWalkContext context,
1923                                                         JvmtiHeapwalkVisitStack* visit_stack) {
1924   _tag_map = tag_map;

1925   _user_data = user_data;
1926   _advanced_context = context;
1927   _basic_context.invalidate();      // will trigger assertion if used
1928   _heap_walk_type = advanced;
1929   _visit_stack = visit_stack;
1930 }
1931 
1932 
1933 // invoke basic style heap root callback
1934 inline bool CallbackInvoker::invoke_basic_heap_root_callback(jvmtiHeapRootKind root_kind, const JvmtiHeapwalkObject& obj) {
1935   // if we heap roots should be reported
1936   jvmtiHeapRootCallback cb = basic_context()->heap_root_callback();
1937   if (cb == nullptr) {
1938     return check_for_visit(obj);
1939   }
1940 
1941   CallbackWrapper wrapper(tag_map(), obj);
1942   jvmtiIterationControl control = (*cb)(root_kind,
1943                                         wrapper.klass_tag(),
1944                                         wrapper.obj_size(),
1945                                         wrapper.obj_tag_p(),
1946                                         (void*)user_data());
1947   // push root to visit stack when following references
1948   if (control == JVMTI_ITERATION_CONTINUE &&
1949       basic_context()->object_ref_callback() != nullptr) {
1950     visit_stack()->push(obj);
1951   }
1952   return control != JVMTI_ITERATION_ABORT;
1953 }
1954 
1955 // invoke basic style stack ref callback
1956 inline bool CallbackInvoker::invoke_basic_stack_ref_callback(jvmtiHeapRootKind root_kind,
1957                                                              jlong thread_tag,
1958                                                              jint depth,
1959                                                              jmethodID method,
1960                                                              int slot,
1961                                                              const JvmtiHeapwalkObject& obj) {
1962   // if we stack refs should be reported
1963   jvmtiStackReferenceCallback cb = basic_context()->stack_ref_callback();
1964   if (cb == nullptr) {
1965     return check_for_visit(obj);
1966   }
1967 
1968   CallbackWrapper wrapper(tag_map(), obj);
1969   jvmtiIterationControl control = (*cb)(root_kind,
1970                                         wrapper.klass_tag(),
1971                                         wrapper.obj_size(),
1972                                         wrapper.obj_tag_p(),
1973                                         thread_tag,
1974                                         depth,
1975                                         method,
1976                                         slot,
1977                                         (void*)user_data());
1978   // push root to visit stack when following references
1979   if (control == JVMTI_ITERATION_CONTINUE &&
1980       basic_context()->object_ref_callback() != nullptr) {
1981     visit_stack()->push(obj);
1982   }
1983   return control != JVMTI_ITERATION_ABORT;
1984 }
1985 
1986 // invoke basic style object reference callback
1987 inline bool CallbackInvoker::invoke_basic_object_reference_callback(jvmtiObjectReferenceKind ref_kind,
1988                                                                     const JvmtiHeapwalkObject& referrer,
1989                                                                     const JvmtiHeapwalkObject& referree,
1990                                                                     jint index) {
1991 
1992   BasicHeapWalkContext* context = basic_context();
1993 
1994   // callback requires the referrer's tag. If it's the same referrer
1995   // as the last call then we use the cached value.
1996   jlong referrer_tag;
1997   if (referrer == context->last_referrer()) {
1998     referrer_tag = context->last_referrer_tag();
1999   } else {
2000     referrer_tag = tag_map()->find(referrer);
2001   }
2002 
2003   // do the callback
2004   CallbackWrapper wrapper(tag_map(), referree);
2005   jvmtiObjectReferenceCallback cb = context->object_ref_callback();
2006   jvmtiIterationControl control = (*cb)(ref_kind,
2007                                         wrapper.klass_tag(),
2008                                         wrapper.obj_size(),
2009                                         wrapper.obj_tag_p(),
2010                                         referrer_tag,
2011                                         index,
2012                                         (void*)user_data());
2013 
2014   // record referrer and referrer tag. For self-references record the
2015   // tag value from the callback as this might differ from referrer_tag.
2016   context->set_last_referrer(referrer);
2017   if (referrer == referree) {
2018     context->set_last_referrer_tag(*wrapper.obj_tag_p());
2019   } else {
2020     context->set_last_referrer_tag(referrer_tag);
2021   }
2022 
2023   if (control == JVMTI_ITERATION_CONTINUE) {
2024     return check_for_visit(referree);
2025   } else {
2026     return control != JVMTI_ITERATION_ABORT;
2027   }
2028 }
2029 
2030 // invoke advanced style heap root callback
2031 inline bool CallbackInvoker::invoke_advanced_heap_root_callback(jvmtiHeapReferenceKind ref_kind,
2032                                                                 const JvmtiHeapwalkObject& obj) {
2033   AdvancedHeapWalkContext* context = advanced_context();
2034 
2035   // check that callback is provided
2036   jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
2037   if (cb == nullptr) {
2038     return check_for_visit(obj);
2039   }
2040 
2041   // apply class filter
2042   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
2043     return check_for_visit(obj);
2044   }
2045 
2046   // setup the callback wrapper
2047   CallbackWrapper wrapper(tag_map(), obj);
2048 
2049   // apply tag filter
2050   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
2051                                  wrapper.klass_tag(),
2052                                  context->heap_filter())) {
2053     return check_for_visit(obj);
2054   }
2055 
2056   // for arrays we need the length, otherwise -1
2057   jint len = get_array_length(obj);
2058 
2059   // invoke the callback
2060   jint res  = (*cb)(ref_kind,
2061                     nullptr, // referrer info
2062                     wrapper.klass_tag(),
2063                     0,    // referrer_class_tag is 0 for heap root
2064                     wrapper.obj_size(),
2065                     wrapper.obj_tag_p(),
2066                     nullptr, // referrer_tag_p
2067                     len,
2068                     (void*)user_data());
2069   if (res & JVMTI_VISIT_ABORT) {
2070     return false;// referrer class tag
2071   }
2072   if (res & JVMTI_VISIT_OBJECTS) {
2073     check_for_visit(obj);
2074   }
2075   return true;
2076 }
2077 
2078 // report a reference from a thread stack to an object
2079 inline bool CallbackInvoker::invoke_advanced_stack_ref_callback(jvmtiHeapReferenceKind ref_kind,
2080                                                                 jlong thread_tag,
2081                                                                 jlong tid,
2082                                                                 int depth,
2083                                                                 jmethodID method,
2084                                                                 jlocation bci,
2085                                                                 jint slot,
2086                                                                 const JvmtiHeapwalkObject& obj) {
2087   AdvancedHeapWalkContext* context = advanced_context();
2088 
2089   // check that callback is provider
2090   jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
2091   if (cb == nullptr) {
2092     return check_for_visit(obj);
2093   }
2094 
2095   // apply class filter
2096   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
2097     return check_for_visit(obj);
2098   }
2099 
2100   // setup the callback wrapper
2101   CallbackWrapper wrapper(tag_map(), obj);
2102 
2103   // apply tag filter
2104   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
2105                                  wrapper.klass_tag(),
2106                                  context->heap_filter())) {
2107     return check_for_visit(obj);
2108   }
2109 
2110   // setup the referrer info
2111   jvmtiHeapReferenceInfo reference_info;
2112   reference_info.stack_local.thread_tag = thread_tag;
2113   reference_info.stack_local.thread_id = tid;
2114   reference_info.stack_local.depth = depth;
2115   reference_info.stack_local.method = method;
2116   reference_info.stack_local.location = bci;
2117   reference_info.stack_local.slot = slot;
2118 
2119   // for arrays we need the length, otherwise -1
2120   jint len = get_array_length(obj);
2121 
2122   // call into the agent
2123   int res = (*cb)(ref_kind,
2124                   &reference_info,
2125                   wrapper.klass_tag(),
2126                   0,    // referrer_class_tag is 0 for heap root (stack)
2127                   wrapper.obj_size(),
2128                   wrapper.obj_tag_p(),
2129                   nullptr, // referrer_tag is 0 for root
2130                   len,
2131                   (void*)user_data());
2132 
2133   if (res & JVMTI_VISIT_ABORT) {
2134     return false;
2135   }
2136   if (res & JVMTI_VISIT_OBJECTS) {
2137     check_for_visit(obj);
2138   }
2139   return true;
2140 }
2141 
2142 // This mask is used to pass reference_info to a jvmtiHeapReferenceCallback
2143 // only for ref_kinds defined by the JVM TI spec. Otherwise, null is passed.
2144 #define REF_INFO_MASK  ((1 << JVMTI_HEAP_REFERENCE_FIELD)         \
2145                       | (1 << JVMTI_HEAP_REFERENCE_STATIC_FIELD)  \
2146                       | (1 << JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT) \
2147                       | (1 << JVMTI_HEAP_REFERENCE_CONSTANT_POOL) \
2148                       | (1 << JVMTI_HEAP_REFERENCE_STACK_LOCAL)   \
2149                       | (1 << JVMTI_HEAP_REFERENCE_JNI_LOCAL))
2150 
2151 // invoke the object reference callback to report a reference
2152 inline bool CallbackInvoker::invoke_advanced_object_reference_callback(jvmtiHeapReferenceKind ref_kind,
2153                                                                        const JvmtiHeapwalkObject& referrer,
2154                                                                        const JvmtiHeapwalkObject& obj,
2155                                                                        jint index)
2156 {
2157   // field index is only valid field in reference_info
2158   static jvmtiHeapReferenceInfo reference_info = { 0 };
2159 
2160   AdvancedHeapWalkContext* context = advanced_context();
2161 
2162   // check that callback is provider
2163   jvmtiHeapReferenceCallback cb = context->heap_reference_callback();
2164   if (cb == nullptr) {
2165     return check_for_visit(obj);
2166   }
2167 
2168   // apply class filter
2169   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
2170     return check_for_visit(obj);
2171   }
2172 
2173   // setup the callback wrapper
2174   TwoOopCallbackWrapper wrapper(tag_map(), referrer, obj);
2175 
2176   // apply tag filter
2177   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
2178                                  wrapper.klass_tag(),
2179                                  context->heap_filter())) {
2180     return check_for_visit(obj);
2181   }
2182 
2183   // field index is only valid field in reference_info
2184   reference_info.field.index = index;
2185 
2186   // for arrays we need the length, otherwise -1
2187   jint len = get_array_length(obj);
2188 
2189   // invoke the callback
2190   int res = (*cb)(ref_kind,
2191                   (REF_INFO_MASK & (1 << ref_kind)) ? &reference_info : nullptr,
2192                   wrapper.klass_tag(),
2193                   wrapper.referrer_klass_tag(),
2194                   wrapper.obj_size(),
2195                   wrapper.obj_tag_p(),
2196                   wrapper.referrer_tag_p(),
2197                   len,
2198                   (void*)user_data());
2199 
2200   if (res & JVMTI_VISIT_ABORT) {
2201     return false;
2202   }
2203   if (res & JVMTI_VISIT_OBJECTS) {
2204     check_for_visit(obj);
2205   }
2206   return true;
2207 }
2208 
2209 // report a "simple root"
2210 inline bool CallbackInvoker::report_simple_root(jvmtiHeapReferenceKind kind, const JvmtiHeapwalkObject& obj) {
2211   assert(kind != JVMTI_HEAP_REFERENCE_STACK_LOCAL &&
2212          kind != JVMTI_HEAP_REFERENCE_JNI_LOCAL, "not a simple root");
2213 
2214   if (is_basic_heap_walk()) {
2215     // map to old style root kind
2216     jvmtiHeapRootKind root_kind = toJvmtiHeapRootKind(kind);
2217     return invoke_basic_heap_root_callback(root_kind, obj);
2218   } else {
2219     assert(is_advanced_heap_walk(), "wrong heap walk type");
2220     return invoke_advanced_heap_root_callback(kind, obj);
2221   }
2222 }
2223 
2224 
2225 // invoke the primitive array values
2226 inline bool CallbackInvoker::report_primitive_array_values(const JvmtiHeapwalkObject& obj) {
2227   assert(obj.klass()->is_typeArray_klass(), "not a primitive array");
2228 
2229   AdvancedHeapWalkContext* context = advanced_context();
2230   assert(context->array_primitive_value_callback() != nullptr, "no callback");
2231 
2232   // apply class filter
2233   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
2234     return true;
2235   }
2236 
2237   CallbackWrapper wrapper(tag_map(), obj);
2238 
2239   // apply tag filter
2240   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
2241                                  wrapper.klass_tag(),
2242                                  context->heap_filter())) {
2243     return true;
2244   }
2245 
2246   // invoke the callback
2247   int res = invoke_array_primitive_value_callback(context->array_primitive_value_callback(),
2248                                                   &wrapper,
2249                                                   obj,
2250                                                   (void*)user_data());
2251   return (!(res & JVMTI_VISIT_ABORT));
2252 }
2253 
2254 // invoke the string value callback
2255 inline bool CallbackInvoker::report_string_value(const JvmtiHeapwalkObject& str) {
2256   assert(str.klass() == vmClasses::String_klass(), "not a string");
2257 
2258   AdvancedHeapWalkContext* context = advanced_context();
2259   assert(context->string_primitive_value_callback() != nullptr, "no callback");
2260 
2261   // apply class filter
2262   if (is_filtered_by_klass_filter(str, context->klass_filter())) {
2263     return true;
2264   }
2265 
2266   CallbackWrapper wrapper(tag_map(), str);
2267 
2268   // apply tag filter
2269   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
2270                                  wrapper.klass_tag(),
2271                                  context->heap_filter())) {
2272     return true;
2273   }
2274 
2275   // invoke the callback
2276   int res = invoke_string_value_callback(context->string_primitive_value_callback(),
2277                                          &wrapper,
2278                                          str,
2279                                          (void*)user_data());
2280   return (!(res & JVMTI_VISIT_ABORT));
2281 }
2282 
2283 // invoke the primitive field callback
2284 inline bool CallbackInvoker::report_primitive_field(jvmtiHeapReferenceKind ref_kind,
2285                                                     const JvmtiHeapwalkObject& obj,
2286                                                     jint index,
2287                                                     address addr,
2288                                                     char type)
2289 {
2290   // for primitive fields only the index will be set
2291   static jvmtiHeapReferenceInfo reference_info = { 0 };
2292 
2293   AdvancedHeapWalkContext* context = advanced_context();
2294   assert(context->primitive_field_callback() != nullptr, "no callback");
2295 
2296   // apply class filter
2297   if (is_filtered_by_klass_filter(obj, context->klass_filter())) {
2298     return true;
2299   }
2300 
2301   CallbackWrapper wrapper(tag_map(), obj);
2302 
2303   // apply tag filter
2304   if (is_filtered_by_heap_filter(wrapper.obj_tag(),
2305                                  wrapper.klass_tag(),

2313   // map the type
2314   jvmtiPrimitiveType value_type = (jvmtiPrimitiveType)type;
2315 
2316   // setup the jvalue
2317   jvalue value;
2318   copy_to_jvalue(&value, addr, value_type);
2319 
2320   jvmtiPrimitiveFieldCallback cb = context->primitive_field_callback();
2321   int res = (*cb)(ref_kind,
2322                   &reference_info,
2323                   wrapper.klass_tag(),
2324                   wrapper.obj_tag_p(),
2325                   value,
2326                   value_type,
2327                   (void*)user_data());
2328   return (!(res & JVMTI_VISIT_ABORT));
2329 }
2330 
2331 
2332 // instance field
2333 inline bool CallbackInvoker::report_primitive_instance_field(const JvmtiHeapwalkObject& obj,
2334                                                              jint index,
2335                                                              address value,
2336                                                              char type) {
2337   return report_primitive_field(JVMTI_HEAP_REFERENCE_FIELD,
2338                                 obj,
2339                                 index,
2340                                 value,
2341                                 type);
2342 }
2343 
2344 // static field
2345 inline bool CallbackInvoker::report_primitive_static_field(const JvmtiHeapwalkObject& obj,
2346                                                            jint index,
2347                                                            address value,
2348                                                            char type) {
2349   return report_primitive_field(JVMTI_HEAP_REFERENCE_STATIC_FIELD,
2350                                 obj,
2351                                 index,
2352                                 value,
2353                                 type);
2354 }
2355 
2356 // report a JNI local (root object) to the profiler
2357 inline bool CallbackInvoker::report_jni_local_root(jlong thread_tag, jlong tid, jint depth, jmethodID m, const JvmtiHeapwalkObject& obj) {
2358   if (is_basic_heap_walk()) {
2359     return invoke_basic_stack_ref_callback(JVMTI_HEAP_ROOT_JNI_LOCAL,
2360                                            thread_tag,
2361                                            depth,
2362                                            m,
2363                                            -1,
2364                                            obj);
2365   } else {
2366     return invoke_advanced_stack_ref_callback(JVMTI_HEAP_REFERENCE_JNI_LOCAL,
2367                                               thread_tag, tid,
2368                                               depth,
2369                                               m,
2370                                               (jlocation)-1,
2371                                               -1,
2372                                               obj);
2373   }
2374 }
2375 
2376 
2377 // report a local (stack reference, root object)
2378 inline bool CallbackInvoker::report_stack_ref_root(jlong thread_tag,
2379                                                    jlong tid,
2380                                                    jint depth,
2381                                                    jmethodID method,
2382                                                    jlocation bci,
2383                                                    jint slot,
2384                                                    const JvmtiHeapwalkObject& obj) {
2385   if (is_basic_heap_walk()) {
2386     return invoke_basic_stack_ref_callback(JVMTI_HEAP_ROOT_STACK_LOCAL,
2387                                            thread_tag,
2388                                            depth,
2389                                            method,
2390                                            slot,
2391                                            obj);
2392   } else {
2393     return invoke_advanced_stack_ref_callback(JVMTI_HEAP_REFERENCE_STACK_LOCAL,
2394                                               thread_tag,
2395                                               tid,
2396                                               depth,
2397                                               method,
2398                                               bci,
2399                                               slot,
2400                                               obj);
2401   }
2402 }
2403 
2404 // report an object referencing a class.
2405 inline bool CallbackInvoker::report_class_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree) {
2406   if (is_basic_heap_walk()) {
2407     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS, referrer, referree, -1);
2408   } else {
2409     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CLASS, referrer, referree, -1);
2410   }
2411 }
2412 
2413 // report a class referencing its class loader.
2414 inline bool CallbackInvoker::report_class_loader_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree) {
2415   if (is_basic_heap_walk()) {
2416     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS_LOADER, referrer, referree, -1);
2417   } else {
2418     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CLASS_LOADER, referrer, referree, -1);
2419   }
2420 }
2421 
2422 // report a class referencing its signers.
2423 inline bool CallbackInvoker::report_signers_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree) {
2424   if (is_basic_heap_walk()) {
2425     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_SIGNERS, referrer, referree, -1);
2426   } else {
2427     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_SIGNERS, referrer, referree, -1);
2428   }
2429 }
2430 
2431 // report a class referencing its protection domain..
2432 inline bool CallbackInvoker::report_protection_domain_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree) {
2433   if (is_basic_heap_walk()) {
2434     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_PROTECTION_DOMAIN, referrer, referree, -1);
2435   } else {
2436     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_PROTECTION_DOMAIN, referrer, referree, -1);
2437   }
2438 }
2439 
2440 // report a class referencing its superclass.
2441 inline bool CallbackInvoker::report_superclass_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree) {
2442   if (is_basic_heap_walk()) {
2443     // Send this to be consistent with past implementation
2444     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CLASS, referrer, referree, -1);
2445   } else {
2446     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_SUPERCLASS, referrer, referree, -1);
2447   }
2448 }
2449 
2450 // report a class referencing one of its interfaces.
2451 inline bool CallbackInvoker::report_interface_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree) {
2452   if (is_basic_heap_walk()) {
2453     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_INTERFACE, referrer, referree, -1);
2454   } else {
2455     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_INTERFACE, referrer, referree, -1);
2456   }
2457 }
2458 
2459 // report a class referencing one of its static fields.
2460 inline bool CallbackInvoker::report_static_field_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint slot) {
2461   if (is_basic_heap_walk()) {
2462     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_STATIC_FIELD, referrer, referree, slot);
2463   } else {
2464     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_STATIC_FIELD, referrer, referree, slot);
2465   }
2466 }
2467 
2468 // report an array referencing an element object
2469 inline bool CallbackInvoker::report_array_element_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint index) {
2470   if (is_basic_heap_walk()) {
2471     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_ARRAY_ELEMENT, referrer, referree, index);
2472   } else {
2473     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, referrer, referree, index);
2474   }
2475 }
2476 
2477 // report an object referencing an instance field object
2478 inline bool CallbackInvoker::report_field_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint slot) {
2479   if (is_basic_heap_walk()) {
2480     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_FIELD, referrer, referree, slot);
2481   } else {
2482     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_FIELD, referrer, referree, slot);
2483   }
2484 }
2485 
2486 // report an array referencing an element object
2487 inline bool CallbackInvoker::report_constant_pool_reference(const JvmtiHeapwalkObject& referrer, const JvmtiHeapwalkObject& referree, jint index) {
2488   if (is_basic_heap_walk()) {
2489     return invoke_basic_object_reference_callback(JVMTI_REFERENCE_CONSTANT_POOL, referrer, referree, index);
2490   } else {
2491     return invoke_advanced_object_reference_callback(JVMTI_HEAP_REFERENCE_CONSTANT_POOL, referrer, referree, index);
2492   }
2493 }
2494 
2495 // A supporting closure used to process simple roots
2496 class SimpleRootsClosure : public OopClosure {
2497  private:
2498   jvmtiHeapReferenceKind _kind;
2499   bool _continue;
2500 
2501   jvmtiHeapReferenceKind root_kind()    { return _kind; }
2502 
2503  public:
2504   void set_kind(jvmtiHeapReferenceKind kind) {
2505     _kind = kind;
2506     _continue = true;
2507   }

2594 
2595 public:
2596   StackRefCollector(JvmtiTagMap* tag_map, JNILocalRootsClosure* blk, JavaThread* java_thread)
2597     : _tag_map(tag_map), _blk(blk), _java_thread(java_thread),
2598       _threadObj(nullptr), _thread_tag(0), _tid(0),
2599       _is_top_frame(true), _depth(0), _last_entry_frame(nullptr)
2600   {
2601   }
2602 
2603   bool set_thread(oop o);
2604   // Sets the thread and reports the reference to it with the specified kind.
2605   bool set_thread(jvmtiHeapReferenceKind kind, oop o);
2606 
2607   bool do_frame(vframe* vf);
2608   // Handles frames until vf->sender() is null.
2609   bool process_frames(vframe* vf);
2610 };
2611 
2612 bool StackRefCollector::set_thread(oop o) {
2613   _threadObj = o;
2614   _thread_tag = _tag_map->find(_threadObj);
2615   _tid = java_lang_Thread::thread_id(_threadObj);
2616 
2617   _is_top_frame = true;
2618   _depth = 0;
2619   _last_entry_frame = nullptr;
2620 
2621   return true;
2622 }
2623 
2624 bool StackRefCollector::set_thread(jvmtiHeapReferenceKind kind, oop o) {
2625   return set_thread(o)
2626          && CallbackInvoker::report_simple_root(kind, _threadObj);
2627 }
2628 
2629 bool StackRefCollector::report_java_stack_refs(StackValueCollection* values, jmethodID method, jlocation bci, jint slot_offset) {
2630   for (int index = 0; index < values->size(); index++) {
2631     if (values->at(index)->type() == T_OBJECT) {
2632       oop obj = values->obj_at(index)();
2633       if (obj == nullptr) {
2634         continue;

2727   return true;
2728 }
2729 
2730 
2731 // A VM operation to iterate over objects that are reachable from
2732 // a set of roots or an initial object.
2733 //
2734 // For VM_HeapWalkOperation the set of roots used is :-
2735 //
2736 // - All JNI global references
2737 // - All inflated monitors
2738 // - All classes loaded by the boot class loader (or all classes
2739 //     in the event that class unloading is disabled)
2740 // - All java threads
2741 // - For each java thread then all locals and JNI local references
2742 //      on the thread's execution stack
2743 // - All visible/explainable objects from Universes::oops_do
2744 //
2745 class VM_HeapWalkOperation: public VM_Operation {
2746  private:




2747   bool _is_advanced_heap_walk;                      // indicates FollowReferences
2748   JvmtiTagMap* _tag_map;
2749   Handle _initial_object;
2750   JvmtiHeapwalkVisitStack _visit_stack;


2751 
2752   // Dead object tags in JvmtiTagMap
2753   GrowableArray<jlong>* _dead_objects;
2754 
2755   bool _following_object_refs;                      // are we following object references
2756 
2757   bool _reporting_primitive_fields;                 // optional reporting
2758   bool _reporting_primitive_array_values;
2759   bool _reporting_string_values;
2760 




2761   // accessors
2762   bool is_advanced_heap_walk() const               { return _is_advanced_heap_walk; }
2763   JvmtiTagMap* tag_map() const                     { return _tag_map; }
2764   Handle initial_object() const                    { return _initial_object; }
2765 
2766   bool is_following_references() const             { return _following_object_refs; }
2767 
2768   bool is_reporting_primitive_fields()  const      { return _reporting_primitive_fields; }
2769   bool is_reporting_primitive_array_values() const { return _reporting_primitive_array_values; }
2770   bool is_reporting_string_values() const          { return _reporting_string_values; }
2771 
2772   JvmtiHeapwalkVisitStack* visit_stack()           { return &_visit_stack; }
2773 
2774   // iterate over the various object types
2775   inline bool iterate_over_array(const JvmtiHeapwalkObject& o);
2776   inline bool iterate_over_flat_array(const JvmtiHeapwalkObject& o);
2777   inline bool iterate_over_type_array(const JvmtiHeapwalkObject& o);
2778   inline bool iterate_over_class(const JvmtiHeapwalkObject& o);
2779   inline bool iterate_over_object(const JvmtiHeapwalkObject& o);
2780 
2781   // root collection
2782   inline bool collect_simple_roots();
2783   inline bool collect_stack_roots();
2784   inline bool collect_stack_refs(JavaThread* java_thread, JNILocalRootsClosure* blk);
2785   inline bool collect_vthread_stack_refs(oop vt);
2786 
2787   // visit an object
2788   inline bool visit(const JvmtiHeapwalkObject& o);
2789 
2790  public:
2791   VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2792                        Handle initial_object,
2793                        BasicHeapWalkContext callbacks,
2794                        const void* user_data,
2795                        GrowableArray<jlong>* objects);
2796 
2797   VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2798                        Handle initial_object,
2799                        AdvancedHeapWalkContext callbacks,
2800                        const void* user_data,
2801                        GrowableArray<jlong>* objects);
2802 
2803   ~VM_HeapWalkOperation();
2804 
2805   VMOp_Type type() const { return VMOp_HeapWalkOperation; }
2806   void doit();
2807 };
2808 
2809 
2810 VM_HeapWalkOperation::VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2811                                            Handle initial_object,
2812                                            BasicHeapWalkContext callbacks,
2813                                            const void* user_data,
2814                                            GrowableArray<jlong>* objects) {
2815   _is_advanced_heap_walk = false;
2816   _tag_map = tag_map;
2817   _initial_object = initial_object;
2818   _following_object_refs = (callbacks.object_ref_callback() != nullptr);
2819   _reporting_primitive_fields = false;
2820   _reporting_primitive_array_values = false;
2821   _reporting_string_values = false;

2822   _dead_objects = objects;
2823   CallbackInvoker::initialize_for_basic_heap_walk(tag_map, user_data, callbacks, &_visit_stack);

2824 }
2825 
2826 VM_HeapWalkOperation::VM_HeapWalkOperation(JvmtiTagMap* tag_map,
2827                                            Handle initial_object,
2828                                            AdvancedHeapWalkContext callbacks,
2829                                            const void* user_data,
2830                                            GrowableArray<jlong>* objects) {
2831   _is_advanced_heap_walk = true;
2832   _tag_map = tag_map;
2833   _initial_object = initial_object;
2834   _following_object_refs = true;
2835   _reporting_primitive_fields = (callbacks.primitive_field_callback() != nullptr);;
2836   _reporting_primitive_array_values = (callbacks.array_primitive_value_callback() != nullptr);;
2837   _reporting_string_values = (callbacks.string_primitive_value_callback() != nullptr);;

2838   _dead_objects = objects;
2839   CallbackInvoker::initialize_for_advanced_heap_walk(tag_map, user_data, callbacks, &_visit_stack);
2840 }
2841 
2842 VM_HeapWalkOperation::~VM_HeapWalkOperation() {





2843 }
2844 
2845 // an array references its class and has a reference to
2846 // each element in the array
2847 inline bool VM_HeapWalkOperation::iterate_over_array(const JvmtiHeapwalkObject& o) {
2848   assert(!o.is_flat(), "Array object cannot be flattened");
2849   objArrayOop array = objArrayOop(o.obj());
2850 
2851   // array reference to its class
2852   oop mirror = ObjArrayKlass::cast(array->klass())->java_mirror();
2853   if (!CallbackInvoker::report_class_reference(o, mirror)) {
2854     return false;
2855   }
2856 
2857   // iterate over the array and report each reference to a
2858   // non-null element
2859   for (int index=0; index<array->length(); index++) {
2860     oop elem = array->obj_at(index);
2861     if (elem == nullptr) {
2862       continue;
2863     }
2864 
2865     // report the array reference o[index] = elem
2866     if (!CallbackInvoker::report_array_element_reference(o, elem, index)) {
2867       return false;
2868     }
2869   }
2870   return true;
2871 }
2872 
2873 // similar to iterate_over_array(), but itrates over flat array
2874 inline bool VM_HeapWalkOperation::iterate_over_flat_array(const JvmtiHeapwalkObject& o) {
2875   assert(!o.is_flat(), "Array object cannot be flattened");
2876   flatArrayOop array = flatArrayOop(o.obj());
2877   FlatArrayKlass* faklass = FlatArrayKlass::cast(array->klass());
2878   InlineKlass* vk = InlineKlass::cast(faklass->element_klass());
2879   bool need_null_check = faklass->layout_kind() == LayoutKind::NULLABLE_ATOMIC_FLAT;
2880 
2881   // array reference to its class
2882   oop mirror = faklass->java_mirror();
2883   if (!CallbackInvoker::report_class_reference(o, mirror)) {
2884     return false;
2885   }
2886 
2887   // iterate over the array and report each reference to a
2888   // non-null element
2889   for (int index = 0; index < array->length(); index++) {
2890     address addr = (address)array->value_at_addr(index, faklass->layout_helper());
2891 
2892     // check for null
2893     if (need_null_check) {
2894       if (vk->is_payload_marked_as_null(addr)) {
2895         continue;
2896       }
2897     }
2898 
2899     // offset in the array oop
2900     int offset = (int)(addr - cast_from_oop<address>(array));
2901     JvmtiHeapwalkObject elem(o.obj(), offset, vk, faklass->layout_kind());
2902 
2903     // report the array reference
2904     if (!CallbackInvoker::report_array_element_reference(o, elem, index)) {
2905       return false;
2906     }
2907   }
2908   return true;
2909 }
2910 
2911 // a type array references its class
2912 inline bool VM_HeapWalkOperation::iterate_over_type_array(const JvmtiHeapwalkObject& o) {
2913   assert(!o.is_flat(), "Array object cannot be flattened");
2914   Klass* k = o.klass();
2915   oop mirror = k->java_mirror();
2916   if (!CallbackInvoker::report_class_reference(o, mirror)) {
2917     return false;
2918   }
2919 
2920   // report the array contents if required
2921   if (is_reporting_primitive_array_values()) {
2922     if (!CallbackInvoker::report_primitive_array_values(o)) {
2923       return false;
2924     }
2925   }
2926   return true;
2927 }
2928 
2929 #ifdef ASSERT
2930 // verify that a static oop field is in range
2931 static inline bool verify_static_oop(InstanceKlass* ik,
2932                                      oop mirror, int offset) {
2933   address obj_p = cast_from_oop<address>(mirror) + offset;
2934   address start = (address)InstanceMirrorKlass::start_of_static_fields(mirror);
2935   address end = start + (java_lang_Class::static_oop_field_count(mirror) * heapOopSize);
2936   assert(end >= start, "sanity check");
2937 
2938   if (obj_p >= start && obj_p < end) {
2939     return true;
2940   } else {
2941     return false;
2942   }
2943 }
2944 #endif // #ifdef ASSERT
2945 
2946 // a class references its super class, interfaces, class loader, ...
2947 // and finally its static fields
2948 inline bool VM_HeapWalkOperation::iterate_over_class(const JvmtiHeapwalkObject& o) {
2949   assert(!o.is_flat(), "Klass object cannot be flattened");
2950   Klass* klass = java_lang_Class::as_Klass(o.obj());
2951   int i;

2952 
2953   if (klass->is_instance_klass()) {
2954     InstanceKlass* ik = InstanceKlass::cast(klass);
2955 
2956     // Ignore the class if it hasn't been initialized yet
2957     if (!ik->is_linked()) {
2958       return true;
2959     }
2960 
2961     // get the java mirror
2962     oop mirror_oop = klass->java_mirror();
2963     JvmtiHeapwalkObject mirror(mirror_oop);
2964 
2965     // super (only if something more interesting than java.lang.Object)
2966     InstanceKlass* super_klass = ik->super();
2967     if (super_klass != nullptr && super_klass != vmClasses::Object_klass()) {
2968       oop super_oop = super_klass->java_mirror();
2969       if (!CallbackInvoker::report_superclass_reference(mirror, super_oop)) {
2970         return false;
2971       }
2972     }
2973 
2974     // class loader
2975     oop cl = ik->class_loader();
2976     if (cl != nullptr) {
2977       if (!CallbackInvoker::report_class_loader_reference(mirror, cl)) {
2978         return false;
2979       }
2980     }
2981 
2982     // protection domain
2983     oop pd = ik->protection_domain();

3032     // (These will already have been reported as references from the constant pool
3033     //  but are specified by IterateOverReachableObjects and must be reported).
3034     Array<InstanceKlass*>* interfaces = ik->local_interfaces();
3035     for (i = 0; i < interfaces->length(); i++) {
3036       oop interf = interfaces->at(i)->java_mirror();
3037       if (interf == nullptr) {
3038         continue;
3039       }
3040       if (!CallbackInvoker::report_interface_reference(mirror, interf)) {
3041         return false;
3042       }
3043     }
3044 
3045     // iterate over the static fields
3046 
3047     ClassFieldMap* field_map = ClassFieldMap::create_map_of_static_fields(klass);
3048     for (i=0; i<field_map->field_count(); i++) {
3049       ClassFieldDescriptor* field = field_map->field_at(i);
3050       char type = field->field_type();
3051       if (!is_primitive_field_type(type)) {
3052         oop fld_o = mirror_oop->obj_field(field->field_offset());
3053         assert(verify_static_oop(ik, mirror_oop, field->field_offset()), "sanity check");
3054         if (fld_o != nullptr) {
3055           int slot = field->field_index();
3056           if (!CallbackInvoker::report_static_field_reference(mirror, fld_o, slot)) {
3057             delete field_map;
3058             return false;
3059           }
3060         }
3061       } else {
3062          if (is_reporting_primitive_fields()) {
3063            address addr = cast_from_oop<address>(mirror_oop) + field->field_offset();
3064            int slot = field->field_index();
3065            if (!CallbackInvoker::report_primitive_static_field(mirror, slot, addr, type)) {
3066              delete field_map;
3067              return false;
3068           }
3069         }
3070       }
3071     }
3072     delete field_map;
3073 
3074     return true;
3075   }
3076 
3077   return true;
3078 }
3079 
3080 // an object references a class and its instance fields
3081 // (static fields are ignored here as we report these as
3082 // references from the class).
3083 inline bool VM_HeapWalkOperation::iterate_over_object(const JvmtiHeapwalkObject& o) {
3084   // reference to the class
3085   if (!CallbackInvoker::report_class_reference(o, o.klass()->java_mirror())) {
3086     return false;
3087   }
3088 
3089   // iterate over instance fields
3090   ClassFieldMap* field_map = JvmtiCachedClassFieldMap::get_map_of_instance_fields(o.klass());
3091   for (int i=0; i<field_map->field_count(); i++) {
3092     ClassFieldDescriptor* field = field_map->field_at(i);
3093     char type = field->field_type();
3094     int slot = field->field_index();
3095     int field_offset = field->field_offset();
3096     if (o.is_flat()) {
3097       // the object is inlined, its fields are stored without the header
3098       field_offset += o.offset() - o.inline_klass()->payload_offset();
3099     }
3100     if (!is_primitive_field_type(type)) {
3101       if (field->is_flat()) {
3102         // check for possible nulls
3103         bool can_be_null = field->layout_kind() == LayoutKind::NULLABLE_ATOMIC_FLAT;
3104         if (can_be_null) {
3105           address payload = cast_from_oop<address>(o.obj()) + field_offset;
3106           if (field->inline_klass()->is_payload_marked_as_null(payload)) {
3107             continue;
3108           }
3109         }
3110         JvmtiHeapwalkObject field_obj(o.obj(), field_offset, field->inline_klass(), field->layout_kind());
3111         if (!CallbackInvoker::report_field_reference(o, field_obj, slot)) {
3112           return false;
3113         }
3114       } else {
3115         oop fld_o = o.obj()->obj_field_access<AS_NO_KEEPALIVE | ON_UNKNOWN_OOP_REF>(field_offset);
3116         // ignore any objects that aren't visible to profiler
3117         if (fld_o != nullptr) {
3118           assert(Universe::heap()->is_in(fld_o), "unsafe code should not have references to Klass* anymore");
3119           if (!CallbackInvoker::report_field_reference(o, fld_o, slot)) {
3120             return false;
3121           }
3122         }
3123       }
3124     } else {
3125       if (is_reporting_primitive_fields()) {
3126         // primitive instance field
3127         address addr = cast_from_oop<address>(o.obj()) + field_offset;

3128         if (!CallbackInvoker::report_primitive_instance_field(o, slot, addr, type)) {
3129           return false;
3130         }
3131       }
3132     }
3133   }
3134 
3135   // if the object is a java.lang.String
3136   if (is_reporting_string_values() &&
3137       o.klass() == vmClasses::String_klass()) {
3138     if (!CallbackInvoker::report_string_value(o)) {
3139       return false;
3140     }
3141   }
3142   return true;
3143 }
3144 
3145 
3146 // Collects all simple (non-stack) roots except for threads;
3147 // threads are handled in collect_stack_roots() as an optimization.
3148 // if there's a heap root callback provided then the callback is
3149 // invoked for each simple root.
3150 // if an object reference callback is provided then all simple
3151 // roots are pushed onto the marking stack so that they can be
3152 // processed later
3153 //
3154 inline bool VM_HeapWalkOperation::collect_simple_roots() {
3155   SimpleRootsClosure blk;
3156 
3157   // JNI globals

3186 // Reports the thread as JVMTI_HEAP_REFERENCE_THREAD,
3187 // walks the stack of the thread, finds all references (locals
3188 // and JNI calls) and reports these as stack references.
3189 inline bool VM_HeapWalkOperation::collect_stack_refs(JavaThread* java_thread,
3190                                                      JNILocalRootsClosure* blk)
3191 {
3192   oop threadObj = java_thread->threadObj();
3193   oop mounted_vt = java_thread->is_vthread_mounted() ? java_thread->vthread() : nullptr;
3194   if (mounted_vt != nullptr && !JvmtiEnvBase::is_vthread_alive(mounted_vt)) {
3195     mounted_vt = nullptr;
3196   }
3197   assert(threadObj != nullptr, "sanity check");
3198 
3199   StackRefCollector stack_collector(tag_map(), blk, java_thread);
3200 
3201   if (!java_thread->has_last_Java_frame()) {
3202     if (!stack_collector.set_thread(JVMTI_HEAP_REFERENCE_THREAD, threadObj)) {
3203       return false;
3204     }
3205     // no last java frame but there may be JNI locals
3206     blk->set_context(_tag_map->find(threadObj), java_lang_Thread::thread_id(threadObj), 0, (jmethodID)nullptr);
3207     java_thread->active_handles()->oops_do(blk);
3208     return !blk->stopped();
3209   }
3210   // vframes are resource allocated
3211   Thread* current_thread = Thread::current();
3212   ResourceMark rm(current_thread);
3213   HandleMark hm(current_thread);
3214 
3215   RegisterMap reg_map(java_thread,
3216                       RegisterMap::UpdateMap::include,
3217                       RegisterMap::ProcessFrames::include,
3218                       RegisterMap::WalkContinuation::include);
3219 
3220   // first handle mounted vthread (if any)
3221   if (mounted_vt != nullptr) {
3222     frame f = java_thread->last_frame();
3223     vframe* vf = vframe::new_vframe(&f, &reg_map, java_thread);
3224     // report virtual thread as JVMTI_HEAP_REFERENCE_OTHER
3225     if (!stack_collector.set_thread(JVMTI_HEAP_REFERENCE_OTHER, mounted_vt)) {
3226       return false;

3286   RegisterMap reg_map(cont.continuation(), RegisterMap::UpdateMap::include);
3287 
3288   JNILocalRootsClosure blk;
3289   // JavaThread is not required for unmounted virtual threads
3290   StackRefCollector stack_collector(tag_map(), &blk, nullptr);
3291   // reference to the vthread is already reported
3292   if (!stack_collector.set_thread(vt)) {
3293     return false;
3294   }
3295 
3296   frame fr = chunk->top_frame(&reg_map);
3297   vframe* vf = vframe::new_vframe(&fr, &reg_map, nullptr);
3298   return stack_collector.process_frames(vf);
3299 }
3300 
3301 // visit an object
3302 // first mark the object as visited
3303 // second get all the outbound references from this object (in other words, all
3304 // the objects referenced by this object).
3305 //
3306 bool VM_HeapWalkOperation::visit(const JvmtiHeapwalkObject& o) {
3307   // mark object as visited
3308   assert(!visit_stack()->is_visited(o), "can't visit same object more than once");
3309   visit_stack()->mark_visited(o);
3310 
3311   Klass* klass = o.klass();
3312   // instance
3313   if (klass->is_instance_klass()) {
3314     if (klass == vmClasses::Class_klass()) {
3315       assert(!o.is_flat(), "Class object cannot be flattened");
3316       if (!java_lang_Class::is_primitive(o.obj())) {
3317         // a java.lang.Class
3318         return iterate_over_class(o);
3319       }
3320     } else {
3321       // we report stack references only when initial object is not specified
3322       // (in the case we start from heap roots which include platform thread stack references)
3323       if (initial_object().is_null() && java_lang_VirtualThread::is_subclass(klass)) {
3324         assert(!o.is_flat(), "VirtualThread object cannot be flattened");
3325         if (!collect_vthread_stack_refs(o.obj())) {
3326           return false;
3327         }
3328       }
3329       return iterate_over_object(o);
3330     }
3331   }
3332 
3333   // flat object array
3334   if (klass->is_flatArray_klass()) {
3335       return iterate_over_flat_array(o);
3336   }
3337 
3338   // object array
3339   if (klass->is_objArray_klass()) {
3340     return iterate_over_array(o);
3341   }
3342 
3343   // type array
3344   if (klass->is_typeArray_klass()) {
3345     return iterate_over_type_array(o);
3346   }
3347 
3348   return true;
3349 }
3350 
3351 void VM_HeapWalkOperation::doit() {
3352   ResourceMark rm;
3353   ClassFieldMapCacheMark cm;
3354 
3355   JvmtiTagMap::check_hashmaps_for_heapwalk(_dead_objects);
3356 
3357   assert(visit_stack()->is_empty(), "visit stack must be empty");
3358 
3359   // the heap walk starts with an initial object or the heap roots
3360   if (initial_object().is_null()) {
3361     // can result in a big performance boost for an agent that is
3362     // focused on analyzing references in the thread stacks.
3363     if (!collect_stack_roots()) return;
3364 
3365     if (!collect_simple_roots()) return;
3366   } else {
3367     visit_stack()->push(initial_object()());
3368   }
3369 
3370   // object references required
3371   if (is_following_references()) {
3372 
3373     // visit each object until all reachable objects have been
3374     // visited or the callback asked to terminate the iteration.
3375     while (!visit_stack()->is_empty()) {
3376       const JvmtiHeapwalkObject o = visit_stack()->pop();
3377       if (!visit_stack()->is_visited(o)) {
3378         if (!visit(o)) {
3379           break;
3380         }
3381       }
3382     }
3383   }
3384 }
3385 
3386 // iterate over all objects that are reachable from a set of roots
3387 void JvmtiTagMap::iterate_over_reachable_objects(jvmtiHeapRootCallback heap_root_callback,
3388                                                  jvmtiStackReferenceCallback stack_ref_callback,
3389                                                  jvmtiObjectReferenceCallback object_ref_callback,
3390                                                  const void* user_data) {
3391   // VTMS transitions must be disabled before the EscapeBarrier.
3392   JvmtiVTMSTransitionDisabler disabler;
3393 
3394   JavaThread* jt = JavaThread::current();
3395   EscapeBarrier eb(true, jt);
3396   eb.deoptimize_objects_all_threads();
3397   Arena dead_object_arena(mtServiceability);
3398   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3399 
3400   {
3401     MutexLocker ml(Heap_lock);
3402     BasicHeapWalkContext context(heap_root_callback, stack_ref_callback, object_ref_callback);
3403     VM_HeapWalkOperation op(this, Handle(), context, user_data, &dead_objects);
3404     VMThread::execute(&op);
3405   }
3406   convert_flat_object_entries();
3407 
3408   // Post events outside of Heap_lock
3409   post_dead_objects(&dead_objects);
3410 }
3411 
3412 // iterate over all objects that are reachable from a given object
3413 void JvmtiTagMap::iterate_over_objects_reachable_from_object(jobject object,
3414                                                              jvmtiObjectReferenceCallback object_ref_callback,
3415                                                              const void* user_data) {
3416   oop obj = JNIHandles::resolve(object);
3417   Handle initial_object(Thread::current(), obj);
3418 
3419   Arena dead_object_arena(mtServiceability);
3420   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3421 
3422   JvmtiVTMSTransitionDisabler disabler;
3423 
3424   {
3425     MutexLocker ml(Heap_lock);
3426     BasicHeapWalkContext context(nullptr, nullptr, object_ref_callback);
3427     VM_HeapWalkOperation op(this, initial_object, context, user_data, &dead_objects);
3428     VMThread::execute(&op);
3429   }
3430   convert_flat_object_entries();
3431 
3432   // Post events outside of Heap_lock
3433   post_dead_objects(&dead_objects);
3434 }
3435 
3436 // follow references from an initial object or the GC roots
3437 void JvmtiTagMap::follow_references(jint heap_filter,
3438                                     Klass* klass,
3439                                     jobject object,
3440                                     const jvmtiHeapCallbacks* callbacks,
3441                                     const void* user_data)
3442 {
3443   // VTMS transitions must be disabled before the EscapeBarrier.
3444   JvmtiVTMSTransitionDisabler disabler;
3445 
3446   oop obj = JNIHandles::resolve(object);
3447   JavaThread* jt = JavaThread::current();
3448   Handle initial_object(jt, obj);
3449   // EA based optimizations that are tagged or reachable from initial_object are already reverted.
3450   EscapeBarrier eb(initial_object.is_null() &&
3451                    !(heap_filter & JVMTI_HEAP_FILTER_UNTAGGED),
3452                    jt);
3453   eb.deoptimize_objects_all_threads();
3454 
3455   Arena dead_object_arena(mtServiceability);
3456   GrowableArray<jlong> dead_objects(&dead_object_arena, 10, 0, 0);
3457 
3458   {
3459     MutexLocker ml(Heap_lock);
3460     AdvancedHeapWalkContext context(heap_filter, klass, callbacks);
3461     VM_HeapWalkOperation op(this, initial_object, context, user_data, &dead_objects);
3462     VMThread::execute(&op);
3463   }
3464   convert_flat_object_entries();
3465 
3466   // Post events outside of Heap_lock
3467   post_dead_objects(&dead_objects);
3468 }
3469 
3470 // Verify gc_notification follows set_needs_cleaning.
3471 DEBUG_ONLY(static bool notified_needs_cleaning = false;)
3472 
3473 void JvmtiTagMap::set_needs_cleaning() {
3474   assert(SafepointSynchronize::is_at_safepoint(), "called in gc pause");
3475   assert(Thread::current()->is_VM_thread(), "should be the VM thread");
3476   // Can't assert !notified_needs_cleaning; a partial GC might be upgraded
3477   // to a full GC and do this twice without intervening gc_notification.
3478   DEBUG_ONLY(notified_needs_cleaning = true;)
3479 
3480   JvmtiEnvIterator it;
3481   for (JvmtiEnv* env = it.first(); env != nullptr; env = it.next(env)) {
3482     JvmtiTagMap* tag_map = env->tag_map_acquire();
3483     if (tag_map != nullptr) {
3484       tag_map->_needs_cleaning = !tag_map->is_empty();
3485     }
< prev index next >