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