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