1 #ifdef USE_PRAGMA_IDENT_SRC
   2 #pragma ident "@(#)heapInspection.cpp   1.21 07/05/29 09:44:16 JVM"
   3 #endif
   4 /*
   5  * Copyright 2002-2008 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 # include "incls/_precompiled.incl"
  29 # include "incls/_heapInspection.cpp.incl"
  30 
  31 // HeapInspection
  32 
  33 int KlassInfoEntry::compare(KlassInfoEntry* e1, KlassInfoEntry* e2) {
  34   if(e1->_instance_words > e2->_instance_words) {
  35     return -1;
  36   } else if(e1->_instance_words < e2->_instance_words) {
  37     return 1;
  38   }
  39   return 0;
  40 }
  41 
  42 void KlassInfoEntry::print_on(outputStream* st) const {
  43   ResourceMark rm;
  44   const char* name;;
  45   if (_klass->klass_part()->name() != NULL) {
  46     name = _klass->klass_part()->external_name();
  47   } else {
  48     if (_klass == Universe::klassKlassObj())             name = "<klassKlass>";             else
  49     if (_klass == Universe::arrayKlassKlassObj())        name = "<arrayKlassKlass>";        else
  50     if (_klass == Universe::objArrayKlassKlassObj())     name = "<objArrayKlassKlass>";     else
  51     if (_klass == Universe::instanceKlassKlassObj())     name = "<instanceKlassKlass>";     else
  52     if (_klass == Universe::typeArrayKlassKlassObj())    name = "<typeArrayKlassKlass>";    else
  53     if (_klass == Universe::symbolKlassObj())            name = "<symbolKlass>";            else
  54     if (_klass == Universe::boolArrayKlassObj())         name = "<boolArrayKlass>";         else
  55     if (_klass == Universe::charArrayKlassObj())         name = "<charArrayKlass>";         else
  56     if (_klass == Universe::singleArrayKlassObj())       name = "<singleArrayKlass>";       else
  57     if (_klass == Universe::doubleArrayKlassObj())       name = "<doubleArrayKlass>";       else
  58     if (_klass == Universe::byteArrayKlassObj())         name = "<byteArrayKlass>";         else
  59     if (_klass == Universe::shortArrayKlassObj())        name = "<shortArrayKlass>";        else
  60     if (_klass == Universe::intArrayKlassObj())          name = "<intArrayKlass>";          else
  61     if (_klass == Universe::longArrayKlassObj())         name = "<longArrayKlass>";         else
  62     if (_klass == Universe::methodKlassObj())            name = "<methodKlass>";            else
  63     if (_klass == Universe::constMethodKlassObj())       name = "<constMethodKlass>";       else
  64     if (_klass == Universe::methodDataKlassObj())        name = "<methodDataKlass>";        else
  65     if (_klass == Universe::constantPoolKlassObj())      name = "<constantPoolKlass>";      else
  66     if (_klass == Universe::constantPoolCacheKlassObj()) name = "<constantPoolCacheKlass>"; else
  67     if (_klass == Universe::compiledICHolderKlassObj())  name = "<compiledICHolderKlass>";  else
  68       name = "<no name>";
  69   }
  70   // simplify the formatting (ILP32 vs LP64) - always cast the numbers to 64-bit
  71   st->print_cr(INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13) "  %s",
  72                (jlong)  _instance_count,
  73                (julong) _instance_words * HeapWordSize,
  74                name);
  75 }
  76 
  77 KlassInfoEntry* KlassInfoBucket::lookup(const klassOop k) {
  78   KlassInfoEntry* elt = _list;
  79   while (elt != NULL) {
  80     if (elt->is_equal(k)) {
  81       return elt;
  82     }
  83     elt = elt->next();
  84   }
  85   elt = new KlassInfoEntry(k, list());
  86   // We may be out of space to allocate the new entry.
  87   if (elt != NULL) {
  88     set_list(elt);
  89   }
  90   return elt;
  91 }
  92 
  93 void KlassInfoBucket::iterate(KlassInfoClosure* cic) {
  94   KlassInfoEntry* elt = _list;
  95   while (elt != NULL) {
  96     cic->do_cinfo(elt);
  97     elt = elt->next();
  98   }
  99 }
 100 
 101 void KlassInfoBucket::empty() {
 102   KlassInfoEntry* elt = _list;
 103   _list = NULL;
 104   while (elt != NULL) {
 105     KlassInfoEntry* next = elt->next();
 106     delete elt;
 107     elt = next;
 108   }
 109 }
 110 
 111 KlassInfoTable::KlassInfoTable(int size, HeapWord* ref) {
 112   _size = 0;
 113   _ref = ref;
 114   _buckets = NEW_C_HEAP_ARRAY(KlassInfoBucket, size);
 115   if (_buckets != NULL) {
 116     _size = size;
 117     for (int index = 0; index < _size; index++) {
 118       _buckets[index].initialize();
 119     }
 120   }
 121 }
 122 
 123 KlassInfoTable::~KlassInfoTable() {
 124   if (_buckets != NULL) {
 125     for (int index = 0; index < _size; index++) {
 126       _buckets[index].empty();
 127     }
 128     FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets);
 129     _size = 0;
 130   }
 131 }
 132 
 133 uint KlassInfoTable::hash(klassOop p) {
 134   assert(Universe::heap()->is_in_permanent((HeapWord*)p), "all klasses in permgen");
 135   return (uint)(((uintptr_t)p - (uintptr_t)_ref) >> 2);
 136 }
 137 
 138 KlassInfoEntry* KlassInfoTable::lookup(const klassOop k) {
 139   uint         idx = hash(k) % _size;
 140   assert(_buckets != NULL, "Allocation failure should have been caught");
 141   KlassInfoEntry*  e   = _buckets[idx].lookup(k);
 142   // Lookup may fail if this is a new klass for which we
 143   // could not allocate space for an new entry.
 144   assert(e == NULL || k == e->klass(), "must be equal");
 145   return e;
 146 }
 147 
 148 // Return false if the entry could not be recorded on account
 149 // of running out of space required to create a new entry.
 150 bool KlassInfoTable::record_instance(const oop obj) {
 151   klassOop      k = obj->klass();
 152   KlassInfoEntry* elt = lookup(k);
 153   // elt may be NULL if it's a new klass for which we
 154   // could not allocate space for a new entry in the hashtable.
 155   if (elt != NULL) {
 156     elt->set_count(elt->count() + 1);
 157     elt->set_words(elt->words() + obj->size());
 158     return true;
 159   } else {
 160     return false;
 161   }
 162 }
 163 
 164 void KlassInfoTable::iterate(KlassInfoClosure* cic) {
 165   assert(_size == 0 || _buckets != NULL, "Allocation failure should have been caught");
 166   for (int index = 0; index < _size; index++) {
 167     _buckets[index].iterate(cic);
 168   }
 169 }
 170 
 171 int KlassInfoHisto::sort_helper(KlassInfoEntry** e1, KlassInfoEntry** e2) {
 172   return (*e1)->compare(*e1,*e2);
 173 }
 174   
 175 KlassInfoHisto::KlassInfoHisto(const char* title, int estimatedCount) :
 176   _title(title) {
 177   _elements = new (ResourceObj::C_HEAP) GrowableArray<KlassInfoEntry*>(estimatedCount,true);
 178 }
 179 
 180 KlassInfoHisto::~KlassInfoHisto() {
 181   delete _elements;
 182 }
 183 
 184 void KlassInfoHisto::add(KlassInfoEntry* cie) {
 185   elements()->append(cie);
 186 }
 187 
 188 void KlassInfoHisto::sort() {
 189   elements()->sort(KlassInfoHisto::sort_helper);
 190 }
 191 
 192 void KlassInfoHisto::print_elements(outputStream* st) const {
 193   // simplify the formatting (ILP32 vs LP64) - store the sum in 64-bit
 194   jlong total = 0;
 195   julong totalw = 0;
 196   for(int i=0; i < elements()->length(); i++) {
 197     st->print("%4d: ", i+1);
 198     elements()->at(i)->print_on(st);
 199     total += elements()->at(i)->count();
 200     totalw += elements()->at(i)->words();
 201   }
 202   st->print_cr("Total " INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13),
 203                total, totalw * HeapWordSize);
 204 }
 205 
 206 void KlassInfoHisto::print_on(outputStream* st) const {
 207   st->print_cr("%s",title());
 208   print_elements(st);
 209 }
 210 
 211 class HistoClosure : public KlassInfoClosure {
 212  private:
 213   KlassInfoHisto* _cih;
 214  public:
 215   HistoClosure(KlassInfoHisto* cih) : _cih(cih) {}
 216 
 217   void do_cinfo(KlassInfoEntry* cie) {
 218     _cih->add(cie);
 219   }
 220 };
 221 
 222 class RecordInstanceClosure : public ObjectClosure {
 223  private:
 224   KlassInfoTable* _cit;
 225   size_t _missed_count;
 226  public:
 227   RecordInstanceClosure(KlassInfoTable* cit) :
 228     _cit(cit), _missed_count(0) {}
 229 
 230   void do_object(oop obj) {
 231     if (!_cit->record_instance(obj)) {
 232       _missed_count++;
 233     }
 234   }
 235 
 236   size_t missed_count() { return _missed_count; }
 237 };
 238 
 239 void HeapInspection::heap_inspection(outputStream* st) {
 240   ResourceMark rm;
 241   HeapWord* ref;
 242 
 243   CollectedHeap* heap = Universe::heap();
 244   bool is_shared_heap = false;
 245   switch (heap->kind()) {
 246     case CollectedHeap::G1CollectedHeap:
 247     case CollectedHeap::GenCollectedHeap: {
 248       is_shared_heap = true;
 249       SharedHeap* sh = (SharedHeap*)heap;
 250       sh->gc_prologue(false /* !full */); // get any necessary locks, etc.
 251       ref = sh->perm_gen()->used_region().start();
 252       break;
 253     }
 254 #ifndef SERIALGC
 255     case CollectedHeap::ParallelScavengeHeap: {
 256       ParallelScavengeHeap* psh = (ParallelScavengeHeap*)heap;
 257       ref = psh->perm_gen()->object_space()->used_region().start();
 258       break;
 259     }
 260 #endif // SERIALGC
 261     default: 
 262       ShouldNotReachHere(); // Unexpected heap kind for this op
 263   }
 264   // Collect klass instance info
 265   KlassInfoTable cit(KlassInfoTable::cit_size, ref);
 266   if (!cit.allocation_failed()) {
 267     // Iterate over objects in the heap
 268     RecordInstanceClosure ric(&cit);
 269     Universe::heap()->object_iterate(&ric);
 270 
 271     // Report if certain classes are not counted because of
 272     // running out of C-heap for the histogram.
 273     size_t missed_count = ric.missed_count();
 274     if (missed_count != 0) {
 275       st->print_cr("WARNING: Ran out of C-heap; undercounted " SIZE_FORMAT
 276                    " total instances in data below",
 277                    missed_count);
 278     }
 279     // Sort and print klass instance info
 280     KlassInfoHisto histo("\n"
 281                      " num     #instances         #bytes  class name\n"
 282                      "----------------------------------------------",
 283                      KlassInfoHisto::histo_initial_size);
 284     HistoClosure hc(&histo);
 285     cit.iterate(&hc);
 286     histo.sort();
 287     histo.print_on(st);
 288   } else {
 289     st->print_cr("WARNING: Ran out of C-heap; histogram not generated");
 290   }
 291   st->flush();
 292 
 293   if (is_shared_heap) {
 294     SharedHeap* sh = (SharedHeap*)heap;
 295     sh->gc_epilogue(false /* !full */); // release all acquired locks, etc.
 296   }
 297 }
 298 
 299 class FindInstanceClosure : public ObjectClosure {
 300  private:
 301   klassOop _klass;
 302   GrowableArray<oop>* _result;
 303 
 304  public:
 305   FindInstanceClosure(klassOop k, GrowableArray<oop>* result) : _klass(k), _result(result) {};
 306 
 307   void do_object(oop obj) {
 308     if (obj->is_a(_klass)) {
 309       _result->append(obj);
 310     }
 311   }
 312 };
 313 
 314 void HeapInspection::find_instances_at_safepoint(klassOop k, GrowableArray<oop>* result) {
 315   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 316   assert(Heap_lock->is_locked(), "should have the Heap_lock")
 317 
 318   // Ensure that the heap is parsable
 319   Universe::heap()->ensure_parsability(false);  // no need to retire TALBs
 320  
 321   // Iterate over objects in the heap
 322   FindInstanceClosure fic(k, result);
 323   Universe::heap()->object_iterate(&fic);
 324 }