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