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