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