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