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