< prev index next >

src/hotspot/share/prims/jvmtiTagMap.cpp

Print this page

  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/reflectionUtils.hpp"
  63 #include "runtime/safepoint.hpp"
  64 #include "runtime/timerTrace.hpp"
  65 #include "runtime/threadSMR.hpp"
  66 #include "runtime/vframe.hpp"
  67 #include "runtime/vmThread.hpp"
  68 #include "runtime/vmOperations.hpp"
  69 #include "utilities/objectBitSet.inline.hpp"
  70 #include "utilities/macros.hpp"
  71 
  72 typedef ObjectBitSet<mtServiceability> JVMTIBitSet;
  73 





























































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

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

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

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

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

















































































































































 175 }
 176 





























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


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



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

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


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










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



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

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

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


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

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

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

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

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

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

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




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







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

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

















































































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


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


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

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



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

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










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

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

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

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

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

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






































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

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


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

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

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






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




2735           return false;
2736         }









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

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

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

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

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

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





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


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


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


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

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





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

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



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


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




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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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




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


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




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

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

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

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





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

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

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

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

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

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