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 #include "utilities/stack.inline.hpp"
  37 #if INCLUDE_ALL_GCS
  38 #include "gc_implementation/parallelScavenge/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 PRAGMA_FORMAT_NONLITERAL_IGNORED_EXTERNAL
 290 void KlassInfoHisto::print_title(outputStream* st, bool csv_format,
 291                                  bool selected[], int width_table[],
 292                                  const char *name_table[]) {
 293   if (csv_format) {
 294     st->print("Index,Super");
 295     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 296        if (selected[c]) {st->print(",%s", name_table[c]);}
 297     }
 298     st->print(",ClassName");
 299   } else {
 300     st->print("Index Super");
 301     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 302 PRAGMA_DIAG_PUSH
 303 PRAGMA_FORMAT_NONLITERAL_IGNORED_INTERNAL
 304       if (selected[c]) {st->print(str_fmt(width_table[c]), name_table[c]);}
 305 PRAGMA_DIAG_POP
 306     }
 307     st->print(" ClassName");
 308   }
 309 
 310   if (is_selected("ClassLoader")) {
 311     st->print(",ClassLoader");
 312   }
 313   st->cr();
 314 }
 315 
 316 class HierarchyClosure : public KlassInfoClosure {
 317 private:
 318   GrowableArray<KlassInfoEntry*> *_elements;
 319 public:
 320   HierarchyClosure(GrowableArray<KlassInfoEntry*> *_elements) : _elements(_elements) {}
 321 
 322   void do_cinfo(KlassInfoEntry* cie) {
 323     // ignore array classes
 324     if (cie->klass()->oop_is_instance()) {
 325       _elements->append(cie);
 326     }
 327   }
 328 };
 329 
 330 void KlassHierarchy::print_class_hierarchy(outputStream* st, bool print_interfaces,
 331                                            bool print_subclasses, char* classname) {
 332   ResourceMark rm;
 333   Stack <KlassInfoEntry*, mtClass> class_stack;
 334   GrowableArray<KlassInfoEntry*> elements;
 335 
 336   // Add all classes to the KlassInfoTable, which allows for quick lookup.
 337   // A KlassInfoEntry will be created for each class.
 338   KlassInfoTable cit(true);
 339   if (cit.allocation_failed()) {
 340     st->print_cr("ERROR: Ran out of C-heap; hierarchy not generated");
 341     return;
 342   }
 343 
 344   // Add all created KlassInfoEntry instances to the elements array for easy
 345   // iteration, and to allow each KlassInfoEntry instance to have a unique index.
 346   HierarchyClosure hc(&elements);
 347   cit.iterate(&hc);
 348 
 349   for(int i = 0; i < elements.length(); i++) {
 350     KlassInfoEntry* cie = elements.at(i);
 351     const InstanceKlass* k = (InstanceKlass*)cie->klass();
 352     Klass* super = ((InstanceKlass*)k)->java_super();
 353 
 354     // Set the index for the class.
 355     cie->set_index(i + 1);
 356 
 357     // Add the class to the subclass array of its superclass.
 358     if (super != NULL) {
 359       KlassInfoEntry* super_cie = cit.lookup(super);
 360       assert(super_cie != NULL, "could not lookup superclass");
 361       super_cie->add_subclass(cie);
 362     }
 363   }
 364 
 365   // Set the do_print flag for each class that should be printed.
 366   for(int i = 0; i < elements.length(); i++) {
 367     KlassInfoEntry* cie = elements.at(i);
 368     if (classname == NULL) {
 369       // We are printing all classes.
 370       cie->set_do_print(true);
 371     } else {
 372       // We are only printing the hierarchy of a specific class.
 373       if (strcmp(classname, cie->klass()->external_name()) == 0) {
 374         KlassHierarchy::set_do_print_for_class_hierarchy(cie, &cit, print_subclasses);
 375       }
 376     }
 377   }
 378 
 379   // Now we do a depth first traversal of the class hierachry. The class_stack will
 380   // maintain the list of classes we still need to process. Start things off
 381   // by priming it with java.lang.Object.
 382   KlassInfoEntry* jlo_cie = cit.lookup(SystemDictionary::Object_klass());
 383   assert(jlo_cie != NULL, "could not lookup java.lang.Object");
 384   class_stack.push(jlo_cie);
 385 
 386   // Repeatedly pop the top item off the stack, print its class info,
 387   // and push all of its subclasses on to the stack. Do this until there
 388   // are no classes left on the stack.
 389   while (!class_stack.is_empty()) {
 390     KlassInfoEntry* curr_cie = class_stack.pop();
 391     if (curr_cie->do_print()) {
 392       print_class(st, curr_cie, print_interfaces);
 393       if (curr_cie->subclasses() != NULL) {
 394         // Current class has subclasses, so push all of them onto the stack.
 395         for (int i = 0; i < curr_cie->subclasses()->length(); i++) {
 396           KlassInfoEntry* cie = curr_cie->subclasses()->at(i);
 397           if (cie->do_print()) {
 398             class_stack.push(cie);
 399           }
 400         }
 401       }
 402     }
 403   }
 404 
 405   st->flush();
 406 }
 407 
 408 // Sets the do_print flag for every superclass and subclass of the specified class.
 409 void KlassHierarchy::set_do_print_for_class_hierarchy(KlassInfoEntry* cie, KlassInfoTable* cit,
 410                                                       bool print_subclasses) {
 411   // Set do_print for all superclasses of this class.
 412   Klass* super = ((InstanceKlass*)cie->klass())->java_super();
 413   while (super != NULL) {
 414     KlassInfoEntry* super_cie = cit->lookup(super);
 415     super_cie->set_do_print(true);
 416     super = super->super();
 417   }
 418 
 419   // Set do_print for this class and all of its subclasses.
 420   Stack <KlassInfoEntry*, mtClass> class_stack;
 421   class_stack.push(cie);
 422   while (!class_stack.is_empty()) {
 423     KlassInfoEntry* curr_cie = class_stack.pop();
 424     curr_cie->set_do_print(true);
 425     if (print_subclasses && curr_cie->subclasses() != NULL) {
 426       // Current class has subclasses, so push all of them onto the stack.
 427       for (int i = 0; i < curr_cie->subclasses()->length(); i++) {
 428         KlassInfoEntry* cie = curr_cie->subclasses()->at(i);
 429         class_stack.push(cie);
 430       }
 431     }
 432   }
 433 }
 434 
 435 static void print_indent(outputStream* st, int indent) {
 436   while (indent != 0) {
 437     st->print("|");
 438     indent--;
 439     if (indent != 0) {
 440       st->print("  ");
 441     }
 442   }
 443 }
 444 
 445 // Print the class name and its unique ClassLoader identifer.
 446 static void print_classname(outputStream* st, Klass* klass) {
 447   oop loader_oop = klass->class_loader_data()->class_loader();
 448   st->print("%s/", klass->external_name());
 449   if (loader_oop == NULL) {
 450     st->print("null");
 451   } else {
 452     st->print(INTPTR_FORMAT, p2i(klass->class_loader_data()));
 453   }
 454 }
 455 
 456 static void print_interface(outputStream* st, Klass* intf_klass, const char* intf_type, int indent) {
 457   print_indent(st, indent);
 458   st->print("  implements ");
 459   print_classname(st, intf_klass);
 460   st->print(" (%s intf)\n", intf_type);
 461 }
 462 
 463 void KlassHierarchy::print_class(outputStream* st, KlassInfoEntry* cie, bool print_interfaces) {
 464   ResourceMark rm;
 465   InstanceKlass* klass = (InstanceKlass*)cie->klass();
 466   int indent = 0;
 467 
 468   // Print indentation with proper indicators of superclass.
 469   Klass* super = klass->super();
 470   while (super != NULL) {
 471     super = super->super();
 472     indent++;
 473   }
 474   print_indent(st, indent);
 475   if (indent != 0) st->print("--");
 476 
 477   // Print the class name, its unique ClassLoader identifer, and if it is an interface.
 478   print_classname(st, klass);
 479   if (klass->is_interface()) {
 480     st->print(" (intf)");
 481   }
 482   st->print("\n");
 483 
 484   // Print any interfaces the class has.
 485   if (print_interfaces) {
 486     Array<Klass*>* local_intfs = klass->local_interfaces();
 487     Array<Klass*>* trans_intfs = klass->transitive_interfaces();
 488     for (int i = 0; i < local_intfs->length(); i++) {
 489       print_interface(st, local_intfs->at(i), "declared", indent);
 490     }
 491     for (int i = 0; i < trans_intfs->length(); i++) {
 492       Klass* trans_interface = trans_intfs->at(i);
 493       // Only print transitive interfaces if they are not also declared.
 494       if (!local_intfs->contains(trans_interface)) {
 495         print_interface(st, trans_interface, "inherited", indent);
 496       }
 497     }
 498   }
 499 }
 500 
 501 void KlassInfoHisto::print_class_stats(outputStream* st,
 502                                       bool csv_format, const char *columns) {
 503   ResourceMark rm;
 504   KlassSizeStats sz, sz_sum;
 505   int i;
 506   julong *col_table = (julong*)(&sz);
 507   julong *colsum_table = (julong*)(&sz_sum);
 508   int width_table[KlassSizeStats::_num_columns];
 509   bool selected[KlassSizeStats::_num_columns];
 510 
 511   _selected_columns = columns;
 512 
 513   memset(&sz_sum, 0, sizeof(sz_sum));
 514   for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 515     selected[c] = is_selected(name_table[c]);
 516   }
 517 
 518   for(i=0; i < elements()->length(); i++) {
 519     elements()->at(i)->set_index(i+1);
 520   }
 521 
 522   // First iteration is for accumulating stats totals in colsum_table[].
 523   // Second iteration is for printing stats for each class.
 524   for (int pass=1; pass<=2; pass++) {
 525     if (pass == 2) {
 526       print_title(st, csv_format, selected, width_table, name_table);
 527     }
 528     for(i=0; i < elements()->length(); i++) {
 529       KlassInfoEntry* e = (KlassInfoEntry*)elements()->at(i);
 530       const Klass* k = e->klass();
 531 
 532       // Get the stats for this class.
 533       memset(&sz, 0, sizeof(sz));
 534       sz._inst_count = e->count();
 535       sz._inst_bytes = HeapWordSize * e->words();
 536       k->collect_statistics(&sz);
 537       sz._total_bytes = sz._ro_bytes + sz._rw_bytes;
 538 
 539       if (pass == 1) {
 540         // Add the stats for this class to the overall totals.
 541         for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 542           colsum_table[c] += col_table[c];
 543         }
 544       } else {
 545         int super_index = -1;
 546         // Print the stats for this class.
 547         if (k->oop_is_instance()) {
 548           Klass* super = ((InstanceKlass*)k)->java_super();
 549           if (super) {
 550             KlassInfoEntry* super_e = _cit->lookup(super);
 551             if (super_e) {
 552               super_index = super_e->index();
 553             }
 554           }
 555         }
 556 
 557         if (csv_format) {
 558           st->print("%ld,%d", e->index(), super_index);
 559           for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 560             if (selected[c]) {st->print("," JULONG_FORMAT, col_table[c]);}
 561           }
 562           st->print(",%s",e->name());
 563         } else {
 564           st->print("%5ld %5d", e->index(), super_index);
 565           for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 566             if (selected[c]) {print_julong(st, width_table[c], col_table[c]);}
 567           }
 568           st->print(" %s", e->name());
 569         }
 570         if (is_selected("ClassLoader")) {
 571           ClassLoaderData* loader_data = k->class_loader_data();
 572           st->print(",");
 573           loader_data->print_value_on(st);
 574         }
 575         st->cr();
 576       }
 577     }
 578 
 579     if (pass == 1) {
 580       // Calculate the minimum width needed for the column by accounting for the
 581       // column header width and the width of the largest value in the column.
 582       for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 583         width_table[c] = col_width(colsum_table[c], name_table[c]);
 584       }
 585     }
 586   }
 587 
 588   sz_sum._inst_size = 0;
 589 
 590   // Print the column totals.
 591   if (csv_format) {
 592     st->print(",");
 593     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 594       if (selected[c]) {st->print("," JULONG_FORMAT, colsum_table[c]);}
 595     }
 596   } else {
 597     st->print("           ");
 598     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 599       if (selected[c]) {print_julong(st, width_table[c], colsum_table[c]);}
 600     }
 601     st->print(" Total");
 602     if (sz_sum._total_bytes > 0) {
 603       st->cr();
 604       st->print("           ");
 605       for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 606         if (selected[c]) {
 607           switch (c) {
 608           case KlassSizeStats::_index_inst_size:
 609           case KlassSizeStats::_index_inst_count:
 610           case KlassSizeStats::_index_method_count:
 611 PRAGMA_DIAG_PUSH
 612 PRAGMA_FORMAT_NONLITERAL_IGNORED_INTERNAL
 613             st->print(str_fmt(width_table[c]), "-");
 614 PRAGMA_DIAG_POP
 615             break;
 616           default:
 617             {
 618               double perc = (double)(100) * (double)(colsum_table[c]) / (double)sz_sum._total_bytes;
 619 PRAGMA_DIAG_PUSH
 620 PRAGMA_FORMAT_NONLITERAL_IGNORED_INTERNAL
 621               st->print(perc_fmt(width_table[c]), perc);
 622 PRAGMA_DIAG_POP
 623             }
 624           }
 625         }
 626       }
 627     }
 628   }
 629   st->cr();
 630 
 631   if (!csv_format) {
 632     print_title(st, csv_format, selected, width_table, name_table);
 633   }
 634 }
 635 
 636 julong KlassInfoHisto::annotations_bytes(Array<AnnotationArray*>* p) const {
 637   julong bytes = 0;
 638   if (p != NULL) {
 639     for (int i = 0; i < p->length(); i++) {
 640       bytes += count_bytes_array(p->at(i));
 641     }
 642     bytes += count_bytes_array(p);
 643   }
 644   return bytes;
 645 }
 646 
 647 void KlassInfoHisto::print_histo_on(outputStream* st, bool print_stats,
 648                                     bool csv_format, const char *columns) {
 649   if (print_stats) {
 650     print_class_stats(st, csv_format, columns);
 651   } else {
 652     st->print_cr("%s",title());
 653     print_elements(st);
 654   }
 655 }
 656 
 657 class HistoClosure : public KlassInfoClosure {
 658  private:
 659   KlassInfoHisto* _cih;
 660  public:
 661   HistoClosure(KlassInfoHisto* cih) : _cih(cih) {}
 662 
 663   void do_cinfo(KlassInfoEntry* cie) {
 664     _cih->add(cie);
 665   }
 666 };
 667 
 668 class RecordInstanceClosure : public ObjectClosure {
 669  private:
 670   KlassInfoTable* _cit;
 671   size_t _missed_count;
 672   BoolObjectClosure* _filter;
 673  public:
 674   RecordInstanceClosure(KlassInfoTable* cit, BoolObjectClosure* filter) :
 675     _cit(cit), _missed_count(0), _filter(filter) {}
 676 
 677   void do_object(oop obj) {
 678     if (should_visit(obj)) {
 679       if (!_cit->record_instance(obj)) {
 680         _missed_count++;
 681       }
 682     }
 683   }
 684 
 685   size_t missed_count() { return _missed_count; }
 686 
 687  private:
 688   bool should_visit(oop obj) {
 689     return _filter == NULL || _filter->do_object_b(obj);
 690   }
 691 };
 692 
 693 size_t HeapInspection::populate_table(KlassInfoTable* cit, BoolObjectClosure *filter) {
 694   ResourceMark rm;
 695 
 696   RecordInstanceClosure ric(cit, filter);
 697   Universe::heap()->object_iterate(&ric);
 698   return ric.missed_count();
 699 }
 700 
 701 void HeapInspection::heap_inspection(outputStream* st) {
 702   ResourceMark rm;
 703 
 704   if (_print_help) {
 705     for (int c=0; c<KlassSizeStats::_num_columns; c++) {
 706       st->print("%s:\n\t", name_table[c]);
 707       const int max_col = 60;
 708       int col = 0;
 709       for (const char *p = help_table[c]; *p; p++,col++) {
 710         if (col >= max_col && *p == ' ') {
 711           st->print("\n\t");
 712           col = 0;
 713         } else {
 714           st->print("%c", *p);
 715         }
 716       }
 717       st->print_cr(".\n");
 718     }
 719     return;
 720   }
 721 
 722   KlassInfoTable cit(_print_class_stats);
 723   if (!cit.allocation_failed()) {
 724     // populate table with object allocation info
 725     size_t missed_count = populate_table(&cit);
 726     if (missed_count != 0) {
 727       st->print_cr("WARNING: Ran out of C-heap; undercounted " SIZE_FORMAT
 728                    " total instances in data below",
 729                    missed_count);
 730     }
 731 
 732     // Sort and print klass instance info
 733     const char *title = "\n"
 734               " num     #instances         #bytes  class name\n"
 735               "----------------------------------------------";
 736     KlassInfoHisto histo(&cit, title);
 737     HistoClosure hc(&histo);
 738 
 739     cit.iterate(&hc);
 740 
 741     histo.sort();
 742     histo.print_histo_on(st, _print_class_stats, _csv_format, _columns);
 743   } else {
 744     st->print_cr("ERROR: Ran out of C-heap; histogram not generated");
 745   }
 746   st->flush();
 747 }
 748 
 749 class FindInstanceClosure : public ObjectClosure {
 750  private:
 751   Klass* _klass;
 752   GrowableArray<oop>* _result;
 753 
 754  public:
 755   FindInstanceClosure(Klass* k, GrowableArray<oop>* result) : _klass(k), _result(result) {};
 756 
 757   void do_object(oop obj) {
 758     if (obj->is_a(_klass)) {
 759       _result->append(obj);
 760     }
 761   }
 762 };
 763 
 764 void HeapInspection::find_instances_at_safepoint(Klass* k, GrowableArray<oop>* result) {
 765   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 766   assert(Heap_lock->is_locked(), "should have the Heap_lock");
 767 
 768   // Ensure that the heap is parsable
 769   Universe::heap()->ensure_parsability(false);  // no need to retire TALBs
 770 
 771   // Iterate over objects in the heap
 772   FindInstanceClosure fic(k, result);
 773   // If this operation encounters a bad object when using CMS,
 774   // consider using safe_object_iterate() which avoids metadata
 775   // objects that may contain bad references.
 776   Universe::heap()->object_iterate(&fic);
 777 }