1 /*
   2  * Copyright (c) 2002, 2020, 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 "logging/log.hpp"
  32 #include "logging/logTag.hpp"
  33 #include "memory/heapInspection.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "memory/universe.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "oops/reflectionAccessorImplKlassHelper.hpp"
  38 #include "runtime/os.hpp"
  39 #include "utilities/globalDefinitions.hpp"
  40 #include "utilities/macros.hpp"
  41 #include "utilities/stack.inline.hpp"
  42 
  43 // HeapInspection
  44 
  45 inline KlassInfoEntry::~KlassInfoEntry() {
  46   if (_subclasses != NULL) {
  47     delete _subclasses;
  48   }
  49 }
  50 
  51 inline void KlassInfoEntry::add_subclass(KlassInfoEntry* cie) {
  52   if (_subclasses == NULL) {
  53     _subclasses = new  (ResourceObj::C_HEAP, mtInternal) GrowableArray<KlassInfoEntry*>(4, true);
  54   }
  55   _subclasses->append(cie);
  56 }
  57 
  58 int KlassInfoEntry::compare(KlassInfoEntry* e1, KlassInfoEntry* e2) {
  59   if(e1->_instance_words > e2->_instance_words) {
  60     return -1;
  61   } else if(e1->_instance_words < e2->_instance_words) {
  62     return 1;
  63   }
  64   // Sort alphabetically, note 'Z' < '[' < 'a', but it's better to group
  65   // the array classes before all the instance classes.
  66   ResourceMark rm;
  67   const char* name1 = e1->klass()->external_name();
  68   const char* name2 = e2->klass()->external_name();
  69   bool d1 = (name1[0] == JVM_SIGNATURE_ARRAY);
  70   bool d2 = (name2[0] == JVM_SIGNATURE_ARRAY);
  71   if (d1 && !d2) {
  72     return -1;
  73   } else if (d2 && !d1) {
  74     return 1;
  75   } else {
  76     return strcmp(name1, name2);
  77   }
  78 }
  79 
  80 const char* KlassInfoEntry::name() const {
  81   const char* name;
  82   if (_klass->name() != NULL) {
  83     name = _klass->external_name();
  84   } else {
  85     if (_klass == Universe::boolArrayKlassObj())         name = "<boolArrayKlass>";         else
  86     if (_klass == Universe::charArrayKlassObj())         name = "<charArrayKlass>";         else
  87     if (_klass == Universe::floatArrayKlassObj())        name = "<floatArrayKlass>";        else
  88     if (_klass == Universe::doubleArrayKlassObj())       name = "<doubleArrayKlass>";       else
  89     if (_klass == Universe::byteArrayKlassObj())         name = "<byteArrayKlass>";         else
  90     if (_klass == Universe::shortArrayKlassObj())        name = "<shortArrayKlass>";        else
  91     if (_klass == Universe::intArrayKlassObj())          name = "<intArrayKlass>";          else
  92     if (_klass == Universe::longArrayKlassObj())         name = "<longArrayKlass>";         else
  93       name = "<no name>";
  94   }
  95   return name;
  96 }
  97 
  98 void KlassInfoEntry::print_on(outputStream* st) const {
  99   ResourceMark rm;
 100 
 101   // simplify the formatting (ILP32 vs LP64) - always cast the numbers to 64-bit
 102   ModuleEntry* module = _klass->module();
 103   if (module->is_named()) {
 104     st->print_cr(INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13) "  %s (%s@%s)",
 105                  (int64_t)_instance_count,
 106                  (uint64_t)_instance_words * HeapWordSize,
 107                  name(),
 108                  module->name()->as_C_string(),
 109                  module->version() != NULL ? module->version()->as_C_string() : "");
 110   } else {
 111     st->print_cr(INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13) "  %s",
 112                  (int64_t)_instance_count,
 113                  (uint64_t)_instance_words * HeapWordSize,
 114                  name());
 115   }
 116 }
 117 
 118 KlassInfoEntry* KlassInfoBucket::lookup(Klass* const k) {
 119   // Can happen if k is an archived class that we haven't loaded yet.
 120   if (k->java_mirror_no_keepalive() == NULL) {
 121     return NULL;
 122   }
 123 
 124   KlassInfoEntry* elt = _list;
 125   while (elt != NULL) {
 126     if (elt->is_equal(k)) {
 127       return elt;
 128     }
 129     elt = elt->next();
 130   }
 131   elt = new (std::nothrow) KlassInfoEntry(k, list());
 132   // We may be out of space to allocate the new entry.
 133   if (elt != NULL) {
 134     set_list(elt);
 135   }
 136   return elt;
 137 }
 138 
 139 void KlassInfoBucket::iterate(KlassInfoClosure* cic) {
 140   KlassInfoEntry* elt = _list;
 141   while (elt != NULL) {
 142     cic->do_cinfo(elt);
 143     elt = elt->next();
 144   }
 145 }
 146 
 147 void KlassInfoBucket::empty() {
 148   KlassInfoEntry* elt = _list;
 149   _list = NULL;
 150   while (elt != NULL) {
 151     KlassInfoEntry* next = elt->next();
 152     delete elt;
 153     elt = next;
 154   }
 155 }
 156 
 157 class KlassInfoTable::AllClassesFinder : public LockedClassesDo {
 158   KlassInfoTable *_table;
 159 public:
 160   AllClassesFinder(KlassInfoTable* table) : _table(table) {}
 161   virtual void do_klass(Klass* k) {
 162     // This has the SIDE EFFECT of creating a KlassInfoEntry
 163     // for <k>, if one doesn't exist yet.
 164     _table->lookup(k);
 165   }
 166 };
 167 
 168 
 169 KlassInfoTable::KlassInfoTable(bool add_all_classes) {
 170   _size_of_instances_in_words = 0;
 171   _ref = (HeapWord*) Universe::boolArrayKlassObj();
 172   _buckets =
 173     (KlassInfoBucket*)  AllocateHeap(sizeof(KlassInfoBucket) * _num_buckets,
 174        mtInternal, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 175   if (_buckets != NULL) {
 176     for (int index = 0; index < _num_buckets; index++) {
 177       _buckets[index].initialize();
 178     }
 179     if (add_all_classes) {
 180       AllClassesFinder finder(this);
 181       ClassLoaderDataGraph::classes_do(&finder);
 182     }
 183   }
 184 }
 185 
 186 KlassInfoTable::~KlassInfoTable() {
 187   if (_buckets != NULL) {
 188     for (int index = 0; index < _num_buckets; index++) {
 189       _buckets[index].empty();
 190     }
 191     FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets);
 192     _buckets = NULL;
 193   }
 194 }
 195 
 196 uint KlassInfoTable::hash(const Klass* p) {
 197   return (uint)(((uintptr_t)p - (uintptr_t)_ref) >> 2);
 198 }
 199 
 200 KlassInfoEntry* KlassInfoTable::lookup(Klass* k) {
 201   uint         idx = hash(k) % _num_buckets;
 202   assert(_buckets != NULL, "Allocation failure should have been caught");
 203   KlassInfoEntry*  e   = _buckets[idx].lookup(k);
 204   // Lookup may fail if this is a new klass for which we
 205   // could not allocate space for an new entry, or if it's
 206   // an archived class that we haven't loaded yet.
 207   assert(e == NULL || k == e->klass(), "must be equal");
 208   return e;
 209 }
 210 
 211 // Return false if the entry could not be recorded on account
 212 // of running out of space required to create a new entry.
 213 bool KlassInfoTable::record_instance(const oop obj) {
 214   Klass*        k = obj->klass();
 215   KlassInfoEntry* elt = lookup(k);
 216   // elt may be NULL if it's a new klass for which we
 217   // could not allocate space for a new entry in the hashtable.
 218   if (elt != NULL) {
 219     elt->set_count(elt->count() + 1);
 220     elt->set_words(elt->words() + obj->size());
 221     _size_of_instances_in_words += obj->size();
 222     return true;
 223   } else {
 224     return false;
 225   }
 226 }
 227 
 228 void KlassInfoTable::iterate(KlassInfoClosure* cic) {
 229   assert(_buckets != NULL, "Allocation failure should have been caught");
 230   for (int index = 0; index < _num_buckets; index++) {
 231     _buckets[index].iterate(cic);
 232   }
 233 }
 234 
 235 size_t KlassInfoTable::size_of_instances_in_words() const {
 236   return _size_of_instances_in_words;
 237 }
 238 
 239 int KlassInfoHisto::sort_helper(KlassInfoEntry** e1, KlassInfoEntry** e2) {
 240   return (*e1)->compare(*e1,*e2);
 241 }
 242 
 243 KlassInfoHisto::KlassInfoHisto(KlassInfoTable* cit) :
 244   _cit(cit) {
 245   _elements = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<KlassInfoEntry*>(_histo_initial_size, true);
 246 }
 247 
 248 KlassInfoHisto::~KlassInfoHisto() {
 249   delete _elements;
 250 }
 251 
 252 void KlassInfoHisto::add(KlassInfoEntry* cie) {
 253   elements()->append(cie);
 254 }
 255 
 256 void KlassInfoHisto::sort() {
 257   elements()->sort(KlassInfoHisto::sort_helper);
 258 }
 259 
 260 void KlassInfoHisto::print_elements(outputStream* st) const {
 261   // simplify the formatting (ILP32 vs LP64) - store the sum in 64-bit
 262   int64_t total = 0;
 263   uint64_t totalw = 0;
 264   for(int i=0; i < elements()->length(); i++) {
 265     st->print("%4d: ", i+1);
 266     elements()->at(i)->print_on(st);
 267     total += elements()->at(i)->count();
 268     totalw += elements()->at(i)->words();
 269   }
 270   st->print_cr("Total " INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13),
 271                total, totalw * HeapWordSize);
 272 }
 273 
 274 class HierarchyClosure : public KlassInfoClosure {
 275 private:
 276   GrowableArray<KlassInfoEntry*> *_elements;
 277 public:
 278   HierarchyClosure(GrowableArray<KlassInfoEntry*> *_elements) : _elements(_elements) {}
 279 
 280   void do_cinfo(KlassInfoEntry* cie) {
 281     // ignore array classes
 282     if (cie->klass()->is_instance_klass()) {
 283       _elements->append(cie);
 284     }
 285   }
 286 };
 287 
 288 void KlassHierarchy::print_class_hierarchy(outputStream* st, bool print_interfaces,
 289                                            bool print_subclasses, char* classname) {
 290   ResourceMark rm;
 291   Stack <KlassInfoEntry*, mtClass> class_stack;
 292   GrowableArray<KlassInfoEntry*> elements;
 293 
 294   // Add all classes to the KlassInfoTable, which allows for quick lookup.
 295   // A KlassInfoEntry will be created for each class.
 296   KlassInfoTable cit(true);
 297   if (cit.allocation_failed()) {
 298     st->print_cr("ERROR: Ran out of C-heap; hierarchy not generated");
 299     return;
 300   }
 301 
 302   // Add all created KlassInfoEntry instances to the elements array for easy
 303   // iteration, and to allow each KlassInfoEntry instance to have a unique index.
 304   HierarchyClosure hc(&elements);
 305   cit.iterate(&hc);
 306 
 307   for(int i = 0; i < elements.length(); i++) {
 308     KlassInfoEntry* cie = elements.at(i);
 309     Klass* super = cie->klass()->super();
 310 
 311     // Set the index for the class.
 312     cie->set_index(i + 1);
 313 
 314     // Add the class to the subclass array of its superclass.
 315     if (super != NULL) {
 316       KlassInfoEntry* super_cie = cit.lookup(super);
 317       assert(super_cie != NULL, "could not lookup superclass");
 318       super_cie->add_subclass(cie);
 319     }
 320   }
 321 
 322   // Set the do_print flag for each class that should be printed.
 323   for(int i = 0; i < elements.length(); i++) {
 324     KlassInfoEntry* cie = elements.at(i);
 325     if (classname == NULL) {
 326       // We are printing all classes.
 327       cie->set_do_print(true);
 328     } else {
 329       // We are only printing the hierarchy of a specific class.
 330       if (strcmp(classname, cie->klass()->external_name()) == 0) {
 331         KlassHierarchy::set_do_print_for_class_hierarchy(cie, &cit, print_subclasses);
 332       }
 333     }
 334   }
 335 
 336   // Now we do a depth first traversal of the class hierachry. The class_stack will
 337   // maintain the list of classes we still need to process. Start things off
 338   // by priming it with java.lang.Object.
 339   KlassInfoEntry* jlo_cie = cit.lookup(SystemDictionary::Object_klass());
 340   assert(jlo_cie != NULL, "could not lookup java.lang.Object");
 341   class_stack.push(jlo_cie);
 342 
 343   // Repeatedly pop the top item off the stack, print its class info,
 344   // and push all of its subclasses on to the stack. Do this until there
 345   // are no classes left on the stack.
 346   while (!class_stack.is_empty()) {
 347     KlassInfoEntry* curr_cie = class_stack.pop();
 348     if (curr_cie->do_print()) {
 349       print_class(st, curr_cie, print_interfaces);
 350       if (curr_cie->subclasses() != NULL) {
 351         // Current class has subclasses, so push all of them onto the stack.
 352         for (int i = 0; i < curr_cie->subclasses()->length(); i++) {
 353           KlassInfoEntry* cie = curr_cie->subclasses()->at(i);
 354           if (cie->do_print()) {
 355             class_stack.push(cie);
 356           }
 357         }
 358       }
 359     }
 360   }
 361 
 362   st->flush();
 363 }
 364 
 365 // Sets the do_print flag for every superclass and subclass of the specified class.
 366 void KlassHierarchy::set_do_print_for_class_hierarchy(KlassInfoEntry* cie, KlassInfoTable* cit,
 367                                                       bool print_subclasses) {
 368   // Set do_print for all superclasses of this class.
 369   Klass* super = ((InstanceKlass*)cie->klass())->java_super();
 370   while (super != NULL) {
 371     KlassInfoEntry* super_cie = cit->lookup(super);
 372     super_cie->set_do_print(true);
 373     super = super->super();
 374   }
 375 
 376   // Set do_print for this class and all of its subclasses.
 377   Stack <KlassInfoEntry*, mtClass> class_stack;
 378   class_stack.push(cie);
 379   while (!class_stack.is_empty()) {
 380     KlassInfoEntry* curr_cie = class_stack.pop();
 381     curr_cie->set_do_print(true);
 382     if (print_subclasses && curr_cie->subclasses() != NULL) {
 383       // Current class has subclasses, so push all of them onto the stack.
 384       for (int i = 0; i < curr_cie->subclasses()->length(); i++) {
 385         KlassInfoEntry* cie = curr_cie->subclasses()->at(i);
 386         class_stack.push(cie);
 387       }
 388     }
 389   }
 390 }
 391 
 392 static void print_indent(outputStream* st, int indent) {
 393   while (indent != 0) {
 394     st->print("|");
 395     indent--;
 396     if (indent != 0) {
 397       st->print("  ");
 398     }
 399   }
 400 }
 401 
 402 // Print the class name and its unique ClassLoader identifer.
 403 static void print_classname(outputStream* st, Klass* klass) {
 404   oop loader_oop = klass->class_loader_data()->class_loader();
 405   st->print("%s/", klass->external_name());
 406   if (loader_oop == NULL) {
 407     st->print("null");
 408   } else {
 409     st->print(INTPTR_FORMAT, p2i(klass->class_loader_data()));
 410   }
 411 }
 412 
 413 static void print_interface(outputStream* st, InstanceKlass* intf_klass, const char* intf_type, int indent) {
 414   print_indent(st, indent);
 415   st->print("  implements ");
 416   print_classname(st, intf_klass);
 417   st->print(" (%s intf)\n", intf_type);
 418 }
 419 
 420 void KlassHierarchy::print_class(outputStream* st, KlassInfoEntry* cie, bool print_interfaces) {
 421   ResourceMark rm;
 422   InstanceKlass* klass = (InstanceKlass*)cie->klass();
 423   int indent = 0;
 424 
 425   // Print indentation with proper indicators of superclass.
 426   Klass* super = klass->super();
 427   while (super != NULL) {
 428     super = super->super();
 429     indent++;
 430   }
 431   print_indent(st, indent);
 432   if (indent != 0) st->print("--");
 433 
 434   // Print the class name, its unique ClassLoader identifer, and if it is an interface.
 435   print_classname(st, klass);
 436   if (klass->is_interface()) {
 437     st->print(" (intf)");
 438   }
 439   // Special treatment for generated core reflection accessor classes: print invocation target.
 440   if (ReflectionAccessorImplKlassHelper::is_generated_accessor(klass)) {
 441     st->print(" (invokes: ");
 442     ReflectionAccessorImplKlassHelper::print_invocation_target(st, klass);
 443     st->print(")");
 444   }
 445   st->print("\n");
 446 
 447   // Print any interfaces the class has.
 448   if (print_interfaces) {
 449     Array<InstanceKlass*>* local_intfs = klass->local_interfaces();
 450     Array<InstanceKlass*>* trans_intfs = klass->transitive_interfaces();
 451     for (int i = 0; i < local_intfs->length(); i++) {
 452       print_interface(st, local_intfs->at(i), "declared", indent);
 453     }
 454     for (int i = 0; i < trans_intfs->length(); i++) {
 455       InstanceKlass* trans_interface = trans_intfs->at(i);
 456       // Only print transitive interfaces if they are not also declared.
 457       if (!local_intfs->contains(trans_interface)) {
 458         print_interface(st, trans_interface, "inherited", indent);
 459       }
 460     }
 461   }
 462 }
 463 
 464 void KlassInfoHisto::print_histo_on(outputStream* st) {
 465   st->print_cr(" num     #instances         #bytes  class name (module)");
 466   st->print_cr("-------------------------------------------------------");
 467   print_elements(st);
 468 }
 469 
 470 class HistoClosure : public KlassInfoClosure {
 471  private:
 472   KlassInfoHisto* _cih;
 473  public:
 474   HistoClosure(KlassInfoHisto* cih) : _cih(cih) {}
 475 
 476   void do_cinfo(KlassInfoEntry* cie) {
 477     _cih->add(cie);
 478   }
 479 };
 480 
 481 class RecordInstanceClosure : public ObjectClosure {
 482  private:
 483   KlassInfoTable* _cit;
 484   size_t _missed_count;
 485   BoolObjectClosure* _filter;
 486  public:
 487   RecordInstanceClosure(KlassInfoTable* cit, BoolObjectClosure* filter) :
 488     _cit(cit), _missed_count(0), _filter(filter) {}
 489 
 490   void do_object(oop obj) {
 491     if (should_visit(obj)) {
 492       if (!_cit->record_instance(obj)) {
 493         _missed_count++;
 494       }
 495     }
 496   }
 497 
 498   size_t missed_count() { return _missed_count; }
 499 
 500  private:
 501   bool should_visit(oop obj) {
 502     return _filter == NULL || _filter->do_object_b(obj);
 503   }
 504 };
 505 
 506 size_t HeapInspection::populate_table(KlassInfoTable* cit, BoolObjectClosure *filter) {
 507   ResourceMark rm;
 508 
 509   RecordInstanceClosure ric(cit, filter);
 510   Universe::heap()->object_iterate(&ric);
 511   return ric.missed_count();
 512 }
 513 
 514 void HeapInspection::heap_inspection(outputStream* st) {
 515   ResourceMark rm;
 516 
 517   KlassInfoTable cit(false);
 518   if (!cit.allocation_failed()) {
 519     // populate table with object allocation info
 520     size_t missed_count = populate_table(&cit);
 521     if (missed_count != 0) {
 522       log_info(gc, classhisto)("WARNING: Ran out of C-heap; undercounted " SIZE_FORMAT
 523                                " total instances in data below",
 524                                missed_count);
 525     }
 526 
 527     // Sort and print klass instance info
 528     KlassInfoHisto histo(&cit);
 529     HistoClosure hc(&histo);
 530 
 531     cit.iterate(&hc);
 532 
 533     histo.sort();
 534     histo.print_histo_on(st);
 535   } else {
 536     st->print_cr("ERROR: Ran out of C-heap; histogram not generated");
 537   }
 538   st->flush();
 539 }
 540 
 541 class FindInstanceClosure : public ObjectClosure {
 542  private:
 543   Klass* _klass;
 544   GrowableArray<oop>* _result;
 545 
 546  public:
 547   FindInstanceClosure(Klass* k, GrowableArray<oop>* result) : _klass(k), _result(result) {};
 548 
 549   void do_object(oop obj) {
 550     if (obj->is_a(_klass)) {
 551       // obj was read with AS_NO_KEEPALIVE, or equivalent.
 552       // The object needs to be kept alive when it is published.
 553       Universe::heap()->keep_alive(obj);
 554 
 555       _result->append(obj);
 556     }
 557   }
 558 };
 559 
 560 void HeapInspection::find_instances_at_safepoint(Klass* k, GrowableArray<oop>* result) {
 561   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
 562   assert(Heap_lock->is_locked(), "should have the Heap_lock");
 563 
 564   // Ensure that the heap is parsable
 565   Universe::heap()->ensure_parsability(false);  // no need to retire TALBs
 566 
 567   // Iterate over objects in the heap
 568   FindInstanceClosure fic(k, result);
 569   Universe::heap()->object_iterate(&fic);
 570 }