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