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