src/share/vm/prims/jvmtiTagMap.cpp

Fri, 16 Jan 2015 09:15:22 +0100

author
aph
date
Fri, 16 Jan 2015 09:15:22 +0100
changeset 7577
9686a796c829
parent 6992
2c6ef90f030a
child 7994
04ff2f6cd0eb
child 9308
767e8338f749
permissions
-rw-r--r--

6584008: jvmtiStringPrimitiveCallback should not be invoked when string value is null
Reviewed-by: sla, sspitsyn

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

mercurial