1 /*
   2  * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoaderData.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "gc/shared/collectedHeap.hpp"
  29 #include "gc/shared/genCollectedHeap.hpp"
  30 #include "memory/heapInspection.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "oops/oop.inline.hpp"
  33 #include "runtime/os.hpp"
  34 #include "utilities/globalDefinitions.hpp"
  35 #include "utilities/macros.hpp"
  36 #include "utilities/stack.inline.hpp"
  37 #if INCLUDE_ALL_GCS
  38 #include "gc/parallel/parallelScavengeHeap.hpp"
  39 #endif // INCLUDE_ALL_GCS
  40 
  41 // HeapInspection
  42 
  43 inline KlassInfoEntry::~KlassInfoEntry() {
  44   if (_subclasses != NULL) {
  45     delete _subclasses;
  46   }
  47 }
  48 
  49 inline void KlassInfoEntry::add_subclass(KlassInfoEntry* cie) {
  50   if (_subclasses == NULL) {
  51     _subclasses = new  (ResourceObj::C_HEAP, mtInternal) GrowableArray<KlassInfoEntry*>(4, true);
  52   }
  53   _subclasses->append(cie);
  54 }
  55 
  56 int KlassInfoEntry::compare(KlassInfoEntry* e1, KlassInfoEntry* e2) {
  57   if(e1->_instance_words > e2->_instance_words) {
  58     return -1;
  59   } else if(e1->_instance_words < e2->_instance_words) {
  60     return 1;
  61   }
  62   // Sort alphabetically, note 'Z' < '[' < 'a', but it's better to group
  63   // the array classes before all the instance classes.
  64   ResourceMark rm;
  65   const char* name1 = e1->klass()->external_name();
  66   const char* name2 = e2->klass()->external_name();
  67   bool d1 = (name1[0] == '[');
  68   bool d2 = (name2[0] == '[');
  69   if (d1 && !d2) {
  70     return -1;
  71   } else if (d2 && !d1) {
  72     return 1;
  73   } else {
  74     return strcmp(name1, name2);
  75   }
  76 }
  77 
  78 const char* KlassInfoEntry::name() const {
  79   const char* name;
  80   if (_klass->name() != NULL) {
  81     name = _klass->external_name();
  82   } else {
  83     if (_klass == Universe::boolArrayKlassObj())         name = "<boolArrayKlass>";         else
  84     if (_klass == Universe::charArrayKlassObj())         name = "<charArrayKlass>";         else
  85     if (_klass == Universe::singleArrayKlassObj())       name = "<singleArrayKlass>";       else
  86     if (_klass == Universe::doubleArrayKlassObj())       name = "<doubleArrayKlass>";       else
  87     if (_klass == Universe::byteArrayKlassObj())         name = "<byteArrayKlass>";         else
  88     if (_klass == Universe::shortArrayKlassObj())        name = "<shortArrayKlass>";        else
  89     if (_klass == Universe::intArrayKlassObj())          name = "<intArrayKlass>";          else
  90     if (_klass == Universe::longArrayKlassObj())         name = "<longArrayKlass>";         else
  91       name = "<no name>";
  92   }
  93   return name;
  94 }
  95 
  96 void KlassInfoEntry::print_on(outputStream* st) const {
  97   ResourceMark rm;
  98 
  99   // simplify the formatting (ILP32 vs LP64) - always cast the numbers to 64-bit
 100   st->print_cr(INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13) "  %s",
 101                (int64_t)_instance_count,
 102                (uint64_t)_instance_words * HeapWordSize,
 103                name());
 104 }
 105 
 106 KlassInfoEntry* KlassInfoBucket::lookup(Klass* const k) {
 107   KlassInfoEntry* elt = _list;
 108   while (elt != NULL) {
 109     if (elt->is_equal(k)) {
 110       return elt;
 111     }
 112     elt = elt->next();
 113   }
 114   elt = new (std::nothrow) KlassInfoEntry(k, list());
 115   // We may be out of space to allocate the new entry.
 116   if (elt != NULL) {
 117     set_list(elt);
 118   }
 119   return elt;
 120 }
 121 
 122 void KlassInfoBucket::iterate(KlassInfoClosure* cic) {
 123   KlassInfoEntry* elt = _list;
 124   while (elt != NULL) {
 125     cic->do_cinfo(elt);
 126     elt = elt->next();
 127   }
 128 }
 129 
 130 void KlassInfoBucket::empty() {
 131   KlassInfoEntry* elt = _list;
 132   _list = NULL;
 133   while (elt != NULL) {
 134     KlassInfoEntry* next = elt->next();
 135     delete elt;
 136     elt = next;
 137   }
 138 }
 139 
 140 void KlassInfoTable::AllClassesFinder::do_klass(Klass* k) {
 141   // This has the SIDE EFFECT of creating a KlassInfoEntry
 142   // for <k>, if one doesn't exist yet.
 143   _table->lookup(k);
 144 }
 145 
 146 KlassInfoTable::KlassInfoTable(bool add_all_classes) {
 147   _size_of_instances_in_words = 0;
 148   _size = 0;
 149   _ref = (HeapWord*) Universe::boolArrayKlassObj();
 150   _buckets =
 151     (KlassInfoBucket*)  AllocateHeap(sizeof(KlassInfoBucket) * _num_buckets,
 152        mtInternal, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 153   if (_buckets != NULL) {
 154     _size = _num_buckets;
 155     for (int index = 0; index < _size; index++) {
 156       _buckets[index].initialize();
 157     }
 158     if (add_all_classes) {
 159       AllClassesFinder finder(this);
 160       ClassLoaderDataGraph::classes_do(&finder);
 161     }
 162   }
 163 }
 164 
 165 KlassInfoTable::~KlassInfoTable() {
 166   if (_buckets != NULL) {
 167     for (int index = 0; index < _size; index++) {
 168       _buckets[index].empty();
 169     }
 170     FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets);
 171     _size = 0;
 172   }
 173 }
 174 
 175 uint KlassInfoTable::hash(const Klass* p) {
 176   return (uint)(((uintptr_t)p - (uintptr_t)_ref) >> 2);
 177 }
 178 
 179 KlassInfoEntry* KlassInfoTable::lookup(Klass* k) {
 180   uint         idx = hash(k) % _size;
 181   assert(_buckets != NULL, "Allocation failure should have been caught");
 182   KlassInfoEntry*  e   = _buckets[idx].lookup(k);
 183   // Lookup may fail if this is a new klass for which we
 184   // could not allocate space for an new entry.
 185   assert(e == NULL || k == e->klass(), "must be equal");
 186   return e;
 187 }
 188 
 189 // Return false if the entry could not be recorded on account
 190 // of running out of space required to create a new entry.
 191 bool KlassInfoTable::record_instance(const oop obj) {
 192   Klass*        k = obj->klass();
 193   KlassInfoEntry* elt = lookup(k);
 194   // elt may be NULL if it's a new klass for which we
 195   // could not allocate space for a new entry in the hashtable.
 196   if (elt != NULL) {
 197     elt->set_count(elt->count() + 1);
 198     elt->set_words(elt->words() + obj->size());
 199     _size_of_instances_in_words += obj->size();
 200     return true;
 201   } else {
 202     return false;
 203   }
 204 }
 205 
 206 void KlassInfoTable::iterate(KlassInfoClosure* cic) {
 207   assert(_size == 0 || _buckets != NULL, "Allocation failure should have been caught");
 208   for (int index = 0; index < _size; index++) {
 209     _buckets[index].iterate(cic);
 210   }
 211 }
 212 
 213 size_t KlassInfoTable::size_of_instances_in_words() const {
 214   return _size_of_instances_in_words;
 215 }
 216 
 217 int KlassInfoHisto::sort_helper(KlassInfoEntry** e1, KlassInfoEntry** e2) {
 218   return (*e1)->compare(*e1,*e2);
 219 }
 220 
 221 KlassInfoHisto::KlassInfoHisto(KlassInfoTable* cit, const char* title) :
 222   _cit(cit),
 223   _title(title) {
 224   _elements = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<KlassInfoEntry*>(_histo_initial_size, true);
 225 }
 226 
 227 KlassInfoHisto::~KlassInfoHisto() {
 228   delete _elements;
 229 }
 230 
 231 void KlassInfoHisto::add(KlassInfoEntry* cie) {
 232   elements()->append(cie);
 233 }
 234 
 235 void KlassInfoHisto::sort() {
 236   elements()->sort(KlassInfoHisto::sort_helper);
 237 }
 238 
 239 void KlassInfoHisto::print_elements(outputStream* st) const {
 240   // simplify the formatting (ILP32 vs LP64) - store the sum in 64-bit
 241   int64_t total = 0;
 242   uint64_t totalw = 0;
 243   for(int i=0; i < elements()->length(); i++) {
 244     st->print("%4d: ", i+1);
 245     elements()->at(i)->print_on(st);
 246     total += elements()->at(i)->count();
 247     totalw += elements()->at(i)->words();
 248   }
 249   st->print_cr("Total " INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13),
 250                total, totalw * HeapWordSize);
 251 }
 252 
 253 #define MAKE_COL_NAME(field, name, help)     #name,
 254 #define MAKE_COL_HELP(field, name, help)     help,
 255 
 256 static const char *name_table[] = {
 257   HEAP_INSPECTION_COLUMNS_DO(MAKE_COL_NAME)
 258 };
 259 
 260 static const char *help_table[] = {
 261   HEAP_INSPECTION_COLUMNS_DO(MAKE_COL_HELP)
 262 };
 263 
 264 bool KlassInfoHisto::is_selected(const char *col_name) {
 265   if (_selected_columns == NULL) {
 266     return true;
 267   }
 268   if (strcmp(_selected_columns, col_name) == 0) {
 269     return true;
 270   }
 271 
 272   const char *start = strstr(_selected_columns, col_name);
 273   if (start == NULL) {
 274     return false;
 275   }
 276 
 277   // The following must be true, because _selected_columns != col_name
 278   if (start > _selected_columns && start[-1] != ',') {
 279     return false;
 280   }
 281   char x = start[strlen(col_name)];
 282   if (x != ',' && x != '\0') {
 283     return false;
 284   }
 285 
 286   return true;
 287 }
 288 
 289 void KlassInfoHisto::print_title(outputStream* st, bool csv_format,
 290                                  bool selected[], int width_table[],
 291                                  const char *name_table[]) {
 292   if (csv_format) {
 293     st->print("Index,Super");
 294     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 295        if (selected[c]) {st->print(",%s", name_table[c]);}
 296     }
 297     st->print(",ClassName");
 298   } else {
 299     st->print("Index Super");
 300     for (int c = 0; c < KlassSizeStats::_num_columns; c++) {
 301       if (selected[c]) {
 302         st->print("%*s", width_table[c], name_table[c]);
 303       }
 304     }
 305     st->print(" ClassName");
 306   }
 307 
 308   if (is_selected("ClassLoader")) {
 309     st->print(",ClassLoader");
 310   }
 311   st->cr();
 312 }
 313 
 314 class HierarchyClosure : public KlassInfoClosure {
 315 private:
 316   GrowableArray<KlassInfoEntry*> *_elements;
 317 public:
 318   HierarchyClosure(GrowableArray<KlassInfoEntry*> *_elements) : _elements(_elements) {}
 319 
 320   void do_cinfo(KlassInfoEntry* cie) {
 321     // ignore array classes
 322     if (cie->klass()->is_instance_klass()) {
 323       _elements->append(cie);
 324     }
 325   }
 326 };
 327 
 328 void KlassHierarchy::print_class_hierarchy(outputStream* st, bool print_interfaces,
 329                                            bool print_subclasses, char* classname) {
 330   ResourceMark rm;
 331   Stack <KlassInfoEntry*, mtClass> class_stack;
 332   GrowableArray<KlassInfoEntry*> elements;
 333 
 334   // Add all classes to the KlassInfoTable, which allows for quick lookup.
 335   // A KlassInfoEntry will be created for each class.
 336   KlassInfoTable cit(true);
 337   if (cit.allocation_failed()) {
 338     st->print_cr("ERROR: Ran out of C-heap; hierarchy not generated");
 339     return;
 340   }
 341 
 342   // Add all created KlassInfoEntry instances to the elements array for easy
 343   // iteration, and to allow each KlassInfoEntry instance to have a unique index.
 344   HierarchyClosure hc(&elements);
 345   cit.iterate(&hc);
 346 
 347   for(int i = 0; i < elements.length(); i++) {
 348     KlassInfoEntry* cie = elements.at(i);
 349     Klass* super = cie->klass()->super();
 350 
 351     // Set the index for the class.
 352     cie->set_index(i + 1);
 353 
 354     // Add the class to the subclass array of its superclass.
 355     if (super != NULL) {
 356       KlassInfoEntry* super_cie = cit.lookup(super);
 357       assert(super_cie != NULL, "could not lookup superclass");
 358       super_cie->add_subclass(cie);
 359     }
 360   }
 361 
 362   // Set the do_print flag for each class that should be printed.
 363   for(int i = 0; i < elements.length(); i++) {
 364     KlassInfoEntry* cie = elements.at(i);
 365     if (classname == NULL) {
 366       // We are printing all classes.
 367       cie->set_do_print(true);
 368     } else {
 369       // We are only printing the hierarchy of a specific class.
 370       if (strcmp(classname, cie->klass()->external_name()) == 0) {
 371         KlassHierarchy::set_do_print_for_class_hierarchy(cie, &cit, print_subclasses);
 372       }
 373     }
 374   }
 375 
 376   // Now we do a depth first traversal of the class hierachry. The class_stack will
 377   // maintain the list of classes we still need to process. Start things off
 378   // by priming it with java.lang.Object.
 379   KlassInfoEntry* jlo_cie = cit.lookup(SystemDictionary::Object_klass());
 380   assert(jlo_cie != NULL, "could not lookup java.lang.Object");
 381   class_stack.push(jlo_cie);
 382 
 383   // Repeatedly pop the top item off the stack, print its class info,
 384   // and push all of its subclasses on to the stack. Do this until there
 385   // are no classes left on the stack.
 386   while (!class_stack.is_empty()) {
 387     KlassInfoEntry* curr_cie = class_stack.pop();
 388     if (curr_cie->do_print()) {
 389       print_class(st, curr_cie, print_interfaces);
 390       if (curr_cie->subclasses() != NULL) {
 391         // Current class has subclasses, so push all of them onto the stack.
 392         for (int i = 0; i < curr_cie->subclasses()->length(); i++) {
 393           KlassInfoEntry* cie = curr_cie->subclasses()->at(i);
 394           if (cie->do_print()) {
 395             class_stack.push(cie);
 396           }
 397         }
 398       }
 399     }
 400   }
 401 
 402   st->flush();
 403 }
 404 
 405 // Sets the do_print flag for every superclass and subclass of the specified class.
 406 void KlassHierarchy::set_do_print_for_class_hierarchy(KlassInfoEntry* cie, KlassInfoTable* cit,
 407                                                       bool print_subclasses) {
 408   // Set do_print for all superclasses of this class.
 409   Klass* super = ((InstanceKlass*)cie->klass())->java_super();
 410   while (super != NULL) {
 411     KlassInfoEntry* super_cie = cit->lookup(super);
 412     super_cie->set_do_print(true);
 413     super = super->super();
 414   }
 415 
 416   // Set do_print for this class and all of its subclasses.
 417   Stack <KlassInfoEntry*, mtClass> class_stack;
 418   class_stack.push(cie);
 419   while (!class_stack.is_empty()) {
 420     KlassInfoEntry* curr_cie = class_stack.pop();
 421     curr_cie->set_do_print(true);
 422     if (print_subclasses && curr_cie->subclasses() != NULL) {
 423       // Current class has subclasses, so push all of them onto the stack.
 424       for (int i = 0; i < curr_cie->subclasses()->length(); i++) {
 425         KlassInfoEntry* cie = curr_cie->subclasses()->at(i);
 426         class_stack.push(cie);
 427       }
 428     }
 429   }
 430 }
 431 
 432 static void print_indent(outputStream* st, int indent) {
 433   while (indent != 0) {
 434     st->print("|");
 435     indent--;
 436     if (indent != 0) {
 437       st->print("  ");
 438     }
 439   }
 440 }
 441 
 442 // Print the class name and its unique ClassLoader identifer.
 443 static void print_classname(outputStream* st, Klass* klass) {
 444   oop loader_oop = klass->class_loader_data()->class_loader();
 445   st->print("%s/", klass->external_name());
 446   if (loader_oop == NULL) {
 447     st->print("null");
 448   } else {
 449     st->print(INTPTR_FORMAT, p2i(klass->class_loader_data()));
 450   }
 451 }
 452 
 453 static void print_interface(outputStream* st, Klass* intf_klass, const char* intf_type, int indent) {
 454   print_indent(st, indent);
 455   st->print("  implements ");
 456   print_classname(st, intf_klass);
 457   st->print(" (%s intf)\n", intf_type);
 458 }
 459 
 460 void KlassHierarchy::print_class(outputStream* st, KlassInfoEntry* cie, bool print_interfaces) {
 461   ResourceMark rm;
 462   InstanceKlass* klass = (InstanceKlass*)cie->klass();
 463   int indent = 0;
 464 
 465   // Print indentation with proper indicators of superclass.
 466   Klass* super = klass->super();
 467   while (super != NULL) {
 468     super = super->super();
 469     indent++;
 470   }
 471   print_indent(st, indent);
 472   if (indent != 0) st->print("--");
 473 
 474   // Print the class name, its unique ClassLoader identifer, and if it is an interface.
 475   print_classname(st, klass);
 476   if (klass->is_interface()) {
 477     st->print(" (intf)");
 478   }
 479   st->print("\n");
 480 
 481   // Print any interfaces the class has.
 482   if (print_interfaces) {
 483     Array<Klass*>* local_intfs = klass->local_interfaces();
 484     Array<Klass*>* trans_intfs = klass->transitive_interfaces();
 485     for (int i = 0; i < local_intfs->length(); i++) {
 486       print_interface(st, local_intfs->at(i), "declared", indent);
 487     }
 488     for (int i = 0; i < trans_intfs->length(); i++) {
 489       Klass* trans_interface = trans_intfs->at(i);
 490       // Only print transitive interfaces if they are not also declared.
 491       if (!local_intfs->contains(trans_interface)) {
 492         print_interface(st, trans_interface, "inherited", indent);
 493       }
 494     }
 495   }
 496 }
 497 
 498 void KlassInfoHisto::print_class_stats(outputStream* st,
 499                                       bool csv_format, const char *columns) {
 500   ResourceMark rm;
 501   KlassSizeStats sz, sz_sum;
 502   int i;
 503   julong *col_table = (julong*)(&sz);
 504   julong *colsum_table = (julong*)(&sz_sum);
 505   int width_table[KlassSizeStats::_num_columns];
 506   bool selected[KlassSizeStats::_num_columns];
 507 
 508   _selected_columns = columns;
 509 
 510   memset(&sz_sum, 0, sizeof(sz_sum));
 511   for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 512     selected[c] = is_selected(name_table[c]);
 513   }
 514 
 515   for(i=0; i < elements()->length(); i++) {
 516     elements()->at(i)->set_index(i+1);
 517   }
 518 
 519   // First iteration is for accumulating stats totals in colsum_table[].
 520   // Second iteration is for printing stats for each class.
 521   for (int pass=1; pass<=2; pass++) {
 522     if (pass == 2) {
 523       print_title(st, csv_format, selected, width_table, name_table);
 524     }
 525     for(i=0; i < elements()->length(); i++) {
 526       KlassInfoEntry* e = (KlassInfoEntry*)elements()->at(i);
 527       const Klass* k = e->klass();
 528 
 529       // Get the stats for this class.
 530       memset(&sz, 0, sizeof(sz));
 531       sz._inst_count = e->count();
 532       sz._inst_bytes = HeapWordSize * e->words();
 533       k->collect_statistics(&sz);
 534       sz._total_bytes = sz._ro_bytes + sz._rw_bytes;
 535 
 536       if (pass == 1) {
 537         // Add the stats for this class to the overall totals.
 538         for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 539           colsum_table[c] += col_table[c];
 540         }
 541       } else {
 542         int super_index = -1;
 543         // Print the stats for this class.
 544         if (k->is_instance_klass()) {
 545           Klass* super = k->super();
 546           if (super) {
 547             KlassInfoEntry* super_e = _cit->lookup(super);
 548             if (super_e) {
 549               super_index = super_e->index();
 550             }
 551           }
 552         }
 553 
 554         if (csv_format) {
 555           st->print("%ld,%d", e->index(), super_index);
 556           for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 557             if (selected[c]) {st->print("," JULONG_FORMAT, col_table[c]);}
 558           }
 559           st->print(",%s",e->name());
 560         } else {
 561           st->print("%5ld %5d", e->index(), super_index);
 562           for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 563             if (selected[c]) {print_julong(st, width_table[c], col_table[c]);}
 564           }
 565           st->print(" %s", e->name());
 566         }
 567         if (is_selected("ClassLoader")) {
 568           ClassLoaderData* loader_data = k->class_loader_data();
 569           st->print(",");
 570           loader_data->print_value_on(st);
 571         }
 572         st->cr();
 573       }
 574     }
 575 
 576     if (pass == 1) {
 577       // Calculate the minimum width needed for the column by accounting for the
 578       // column header width and the width of the largest value in the column.
 579       for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 580         width_table[c] = col_width(colsum_table[c], name_table[c]);
 581       }
 582     }
 583   }
 584 
 585   sz_sum._inst_size = 0;
 586 
 587   // Print the column totals.
 588   if (csv_format) {
 589     st->print(",");
 590     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 591       if (selected[c]) {st->print("," JULONG_FORMAT, colsum_table[c]);}
 592     }
 593   } else {
 594     st->print("           ");
 595     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 596       if (selected[c]) {print_julong(st, width_table[c], colsum_table[c]);}
 597     }
 598     st->print(" Total");
 599     if (sz_sum._total_bytes > 0) {
 600       st->cr();
 601       st->print("           ");
 602       for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 603         if (selected[c]) {
 604           switch (c) {
 605           case KlassSizeStats::_index_inst_size:
 606           case KlassSizeStats::_index_inst_count:
 607           case KlassSizeStats::_index_method_count:
 608             st->print("%*s", width_table[c], "-");
 609             break;
 610           default:
 611             {
 612               double perc = (double)(100) * (double)(colsum_table[c]) / (double)sz_sum._total_bytes;
 613               st->print("%*.1f%%", width_table[c]-1, perc);
 614             }
 615           }
 616         }
 617       }
 618     }
 619   }
 620   st->cr();
 621 
 622   if (!csv_format) {
 623     print_title(st, csv_format, selected, width_table, name_table);
 624   }
 625 }
 626 
 627 julong KlassInfoHisto::annotations_bytes(Array<AnnotationArray*>* p) const {
 628   julong bytes = 0;
 629   if (p != NULL) {
 630     for (int i = 0; i < p->length(); i++) {
 631       bytes += count_bytes_array(p->at(i));
 632     }
 633     bytes += count_bytes_array(p);
 634   }
 635   return bytes;
 636 }
 637 
 638 void KlassInfoHisto::print_histo_on(outputStream* st, bool print_stats,
 639                                     bool csv_format, const char *columns) {
 640   if (print_stats) {
 641     print_class_stats(st, csv_format, columns);
 642   } else {
 643     st->print_cr("%s",title());
 644     print_elements(st);
 645   }
 646 }
 647 
 648 class HistoClosure : public KlassInfoClosure {
 649  private:
 650   KlassInfoHisto* _cih;
 651  public:
 652   HistoClosure(KlassInfoHisto* cih) : _cih(cih) {}
 653 
 654   void do_cinfo(KlassInfoEntry* cie) {
 655     _cih->add(cie);
 656   }
 657 };
 658 
 659 class RecordInstanceClosure : public ObjectClosure {
 660  private:
 661   KlassInfoTable* _cit;
 662   size_t _missed_count;
 663   BoolObjectClosure* _filter;
 664  public:
 665   RecordInstanceClosure(KlassInfoTable* cit, BoolObjectClosure* filter) :
 666     _cit(cit), _missed_count(0), _filter(filter) {}
 667 
 668   void do_object(oop obj) {
 669     if (should_visit(obj)) {
 670       if (!_cit->record_instance(obj)) {
 671         _missed_count++;
 672       }
 673     }
 674   }
 675 
 676   size_t missed_count() { return _missed_count; }
 677 
 678  private:
 679   bool should_visit(oop obj) {
 680     return _filter == NULL || _filter->do_object_b(obj);
 681   }
 682 };
 683 
 684 size_t HeapInspection::populate_table(KlassInfoTable* cit, BoolObjectClosure *filter) {
 685   ResourceMark rm;
 686 
 687   RecordInstanceClosure ric(cit, filter);
 688   Universe::heap()->object_iterate(&ric);
 689   return ric.missed_count();
 690 }
 691 
 692 void HeapInspection::heap_inspection(outputStream* st) {
 693   ResourceMark rm;
 694 
 695   if (_print_help) {
 696     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 697       st->print("%s:\n\t", name_table[c]);
 698       const int max_col = 60;
 699       int col = 0;
 700       for (const char *p = help_table[c]; *p; p++,col++) {
 701         if (col >= max_col && *p == ' ') {
 702           st->print("\n\t");
 703           col = 0;
 704         } else {
 705           st->print("%c", *p);
 706         }
 707       }
 708       st->print_cr(".\n");
 709     }
 710     return;
 711   }
 712 
 713   KlassInfoTable cit(_print_class_stats);
 714   if (!cit.allocation_failed()) {
 715     // populate table with object allocation info
 716     size_t missed_count = populate_table(&cit);
 717     if (missed_count != 0) {
 718       st->print_cr("WARNING: Ran out of C-heap; undercounted " SIZE_FORMAT
 719                    " total instances in data below",
 720                    missed_count);
 721     }
 722 
 723     // Sort and print klass instance info
 724     const char *title = "\n"
 725               " num     #instances         #bytes  class name\n"
 726               "----------------------------------------------";
 727     KlassInfoHisto histo(&cit, title);
 728     HistoClosure hc(&histo);
 729 
 730     cit.iterate(&hc);
 731 
 732     histo.sort();
 733     histo.print_histo_on(st, _print_class_stats, _csv_format, _columns);
 734   } else {
 735     st->print_cr("ERROR: Ran out of C-heap; histogram not generated");
 736   }
 737   st->flush();
 738 }
 739 
 740 class FindInstanceClosure : public ObjectClosure {
 741  private:
 742   Klass* _klass;
 743   GrowableArray<oop>* _result;
 744 
 745  public:
 746   FindInstanceClosure(Klass* k, GrowableArray<oop>* result) : _klass(k), _result(result) {};
 747 
 748   void do_object(oop obj) {
 749     if (obj->is_a(_klass)) {
 750       _result->append(obj);
 751     }
 752   }
 753 };
 754 
 755 void HeapInspection::find_instances_at_safepoint(Klass* k, GrowableArray<oop>* result) {
 756   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 757   assert(Heap_lock->is_locked(), "should have the Heap_lock");
 758 
 759   // Ensure that the heap is parsable
 760   Universe::heap()->ensure_parsability(false);  // no need to retire TALBs
 761 
 762   // Iterate over objects in the heap
 763   FindInstanceClosure fic(k, result);
 764   // If this operation encounters a bad object when using CMS,
 765   // consider using safe_object_iterate() which avoids metadata
 766   // objects that may contain bad references.
 767   Universe::heap()->object_iterate(&fic);
 768 }