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