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