heapInspection.cpp 16.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2002, 2019, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25
#include "precompiled.hpp"
26
#include "classfile/classLoaderData.hpp"
27 28
#include "gc_interface/collectedHeap.hpp"
#include "memory/genCollectedHeap.hpp"
29
#include "memory/generation.hpp"
30 31 32 33
#include "memory/heapInspection.hpp"
#include "memory/resourceArea.hpp"
#include "runtime/os.hpp"
#include "utilities/globalDefinitions.hpp"
34 35
#include "utilities/macros.hpp"
#if INCLUDE_ALL_GCS
36
#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
37
#endif // INCLUDE_ALL_GCS
D
duke 已提交
38

39 40
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

D
duke 已提交
41 42 43 44 45 46 47 48
// HeapInspection

int KlassInfoEntry::compare(KlassInfoEntry* e1, KlassInfoEntry* e2) {
  if(e1->_instance_words > e2->_instance_words) {
    return -1;
  } else if(e1->_instance_words < e2->_instance_words) {
    return 1;
  }
49 50 51 52 53 54 55 56 57 58 59 60 61 62
  // Sort alphabetically, note 'Z' < '[' < 'a', but it's better to group
  // the array classes before all the instance classes.
  ResourceMark rm;
  const char* name1 = e1->klass()->external_name();
  const char* name2 = e2->klass()->external_name();
  bool d1 = (name1[0] == '[');
  bool d2 = (name2[0] == '[');
  if (d1 && !d2) {
    return -1;
  } else if (d2 && !d1) {
    return 1;
  } else {
    return strcmp(name1, name2);
  }
D
duke 已提交
63 64
}

65 66
const char* KlassInfoEntry::name() const {
  const char* name;
67 68
  if (_klass->name() != NULL) {
    name = _klass->external_name();
D
duke 已提交
69 70 71 72 73 74 75 76 77 78 79
  } else {
    if (_klass == Universe::boolArrayKlassObj())         name = "<boolArrayKlass>";         else
    if (_klass == Universe::charArrayKlassObj())         name = "<charArrayKlass>";         else
    if (_klass == Universe::singleArrayKlassObj())       name = "<singleArrayKlass>";       else
    if (_klass == Universe::doubleArrayKlassObj())       name = "<doubleArrayKlass>";       else
    if (_klass == Universe::byteArrayKlassObj())         name = "<byteArrayKlass>";         else
    if (_klass == Universe::shortArrayKlassObj())        name = "<shortArrayKlass>";        else
    if (_klass == Universe::intArrayKlassObj())          name = "<intArrayKlass>";          else
    if (_klass == Universe::longArrayKlassObj())         name = "<longArrayKlass>";         else
      name = "<no name>";
  }
80 81 82 83 84 85
  return name;
}

void KlassInfoEntry::print_on(outputStream* st) const {
  ResourceMark rm;

D
duke 已提交
86
  // simplify the formatting (ILP32 vs LP64) - always cast the numbers to 64-bit
87
  st->print_cr(INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13) "  %s",
D
duke 已提交
88 89
               (jlong)  _instance_count,
               (julong) _instance_words * HeapWordSize,
90
               name());
D
duke 已提交
91 92
}

93
KlassInfoEntry* KlassInfoBucket::lookup(Klass* const k) {
D
duke 已提交
94 95 96 97 98 99 100
  KlassInfoEntry* elt = _list;
  while (elt != NULL) {
    if (elt->is_equal(k)) {
      return elt;
    }
    elt = elt->next();
  }
S
sla 已提交
101
  elt = new (std::nothrow) KlassInfoEntry(k, list());
102 103 104 105
  // We may be out of space to allocate the new entry.
  if (elt != NULL) {
    set_list(elt);
  }
D
duke 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  return elt;
}

void KlassInfoBucket::iterate(KlassInfoClosure* cic) {
  KlassInfoEntry* elt = _list;
  while (elt != NULL) {
    cic->do_cinfo(elt);
    elt = elt->next();
  }
}

void KlassInfoBucket::empty() {
  KlassInfoEntry* elt = _list;
  _list = NULL;
  while (elt != NULL) {
    KlassInfoEntry* next = elt->next();
    delete elt;
    elt = next;
  }
}

127 128 129 130 131 132
void KlassInfoTable::AllClassesFinder::do_klass(Klass* k) {
  // This has the SIDE EFFECT of creating a KlassInfoEntry
  // for <k>, if one doesn't exist yet.
  _table->lookup(k);
}

S
sla 已提交
133 134
KlassInfoTable::KlassInfoTable(bool need_class_stats) {
  _size_of_instances_in_words = 0;
135
  _size = 0;
S
sla 已提交
136 137 138
  _ref = (HeapWord*) Universe::boolArrayKlassObj();
  _buckets =
    (KlassInfoBucket*)  AllocateHeap(sizeof(KlassInfoBucket) * _num_buckets,
139
       mtInternal, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
140
  if (_buckets != NULL) {
S
sla 已提交
141
    _size = _num_buckets;
142 143 144
    for (int index = 0; index < _size; index++) {
      _buckets[index].initialize();
    }
145 146 147 148
    if (need_class_stats) {
      AllClassesFinder finder(this);
      ClassLoaderDataGraph::classes_do(&finder);
    }
D
duke 已提交
149 150 151 152
  }
}

KlassInfoTable::~KlassInfoTable() {
153 154 155 156
  if (_buckets != NULL) {
    for (int index = 0; index < _size; index++) {
      _buckets[index].empty();
    }
Z
zgu 已提交
157
    FREE_C_HEAP_ARRAY(KlassInfoBucket, _buckets, mtInternal);
158
    _size = 0;
D
duke 已提交
159 160 161
  }
}

162
uint KlassInfoTable::hash(const Klass* p) {
D
duke 已提交
163 164 165
  return (uint)(((uintptr_t)p - (uintptr_t)_ref) >> 2);
}

166
KlassInfoEntry* KlassInfoTable::lookup(Klass* k) {
D
duke 已提交
167
  uint         idx = hash(k) % _size;
168
  assert(_buckets != NULL, "Allocation failure should have been caught");
D
duke 已提交
169
  KlassInfoEntry*  e   = _buckets[idx].lookup(k);
170 171 172
  // Lookup may fail if this is a new klass for which we
  // could not allocate space for an new entry.
  assert(e == NULL || k == e->klass(), "must be equal");
D
duke 已提交
173 174 175
  return e;
}

176 177 178
// Return false if the entry could not be recorded on account
// of running out of space required to create a new entry.
bool KlassInfoTable::record_instance(const oop obj) {
179
  Klass*        k = obj->klass();
D
duke 已提交
180
  KlassInfoEntry* elt = lookup(k);
181 182 183 184 185
  // elt may be NULL if it's a new klass for which we
  // could not allocate space for a new entry in the hashtable.
  if (elt != NULL) {
    elt->set_count(elt->count() + 1);
    elt->set_words(elt->words() + obj->size());
S
sla 已提交
186
    _size_of_instances_in_words += obj->size();
187 188 189 190
    return true;
  } else {
    return false;
  }
D
duke 已提交
191 192 193
}

void KlassInfoTable::iterate(KlassInfoClosure* cic) {
194
  assert(_size == 0 || _buckets != NULL, "Allocation failure should have been caught");
D
duke 已提交
195 196 197 198 199
  for (int index = 0; index < _size; index++) {
    _buckets[index].iterate(cic);
  }
}

S
sla 已提交
200 201 202 203
size_t KlassInfoTable::size_of_instances_in_words() const {
  return _size_of_instances_in_words;
}

D
duke 已提交
204 205 206 207
int KlassInfoHisto::sort_helper(KlassInfoEntry** e1, KlassInfoEntry** e2) {
  return (*e1)->compare(*e1,*e2);
}

S
sla 已提交
208
KlassInfoHisto::KlassInfoHisto(KlassInfoTable* cit, const char* title) :
209
  _cit(cit),
D
duke 已提交
210
  _title(title) {
S
sla 已提交
211
  _elements = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<KlassInfoEntry*>(_histo_initial_size, true);
D
duke 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
}

KlassInfoHisto::~KlassInfoHisto() {
  delete _elements;
}

void KlassInfoHisto::add(KlassInfoEntry* cie) {
  elements()->append(cie);
}

void KlassInfoHisto::sort() {
  elements()->sort(KlassInfoHisto::sort_helper);
}

void KlassInfoHisto::print_elements(outputStream* st) const {
  // simplify the formatting (ILP32 vs LP64) - store the sum in 64-bit
  jlong total = 0;
  julong totalw = 0;
  for(int i=0; i < elements()->length(); i++) {
    st->print("%4d: ", i+1);
    elements()->at(i)->print_on(st);
    total += elements()->at(i)->count();
    totalw += elements()->at(i)->words();
  }
236
  st->print_cr("Total " INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13),
D
duke 已提交
237 238 239
               total, totalw * HeapWordSize);
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
#define MAKE_COL_NAME(field, name, help)     #name,
#define MAKE_COL_HELP(field, name, help)     help,

static const char *name_table[] = {
  HEAP_INSPECTION_COLUMNS_DO(MAKE_COL_NAME)
};

static const char *help_table[] = {
  HEAP_INSPECTION_COLUMNS_DO(MAKE_COL_HELP)
};

bool KlassInfoHisto::is_selected(const char *col_name) {
  if (_selected_columns == NULL) {
    return true;
  }
  if (strcmp(_selected_columns, col_name) == 0) {
    return true;
  }

  const char *start = strstr(_selected_columns, col_name);
  if (start == NULL) {
    return false;
  }

  // The following must be true, because _selected_columns != col_name
  if (start > _selected_columns && start[-1] != ',') {
    return false;
  }
  char x = start[strlen(col_name)];
  if (x != ',' && x != '\0') {
    return false;
  }

  return true;
}

276
PRAGMA_FORMAT_NONLITERAL_IGNORED_EXTERNAL
277 278 279 280 281 282 283 284 285 286 287 288
void KlassInfoHisto::print_title(outputStream* st, bool csv_format,
                                 bool selected[], int width_table[],
                                 const char *name_table[]) {
  if (csv_format) {
    st->print("Index,Super");
    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
       if (selected[c]) {st->print(",%s", name_table[c]);}
    }
    st->print(",ClassName");
  } else {
    st->print("Index Super");
    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
289 290
PRAGMA_DIAG_PUSH
PRAGMA_FORMAT_NONLITERAL_IGNORED_INTERNAL
291
      if (selected[c]) {st->print(str_fmt(width_table[c]), name_table[c]);}
292
PRAGMA_DIAG_POP
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    }
    st->print(" ClassName");
  }

  if (is_selected("ClassLoader")) {
    st->print(",ClassLoader");
  }
  st->cr();
}

void KlassInfoHisto::print_class_stats(outputStream* st,
                                      bool csv_format, const char *columns) {
  ResourceMark rm;
  KlassSizeStats sz, sz_sum;
  int i;
  julong *col_table = (julong*)(&sz);
  julong *colsum_table = (julong*)(&sz_sum);
  int width_table[KlassSizeStats::_num_columns];
  bool selected[KlassSizeStats::_num_columns];

  _selected_columns = columns;

  memset(&sz_sum, 0, sizeof(sz_sum));
  for (int c=0; c<KlassSizeStats::_num_columns; c++) {
    selected[c] = is_selected(name_table[c]);
  }

  for(i=0; i < elements()->length(); i++) {
    elements()->at(i)->set_index(i+1);
  }

  for (int pass=1; pass<=2; pass++) {
    if (pass == 2) {
      print_title(st, csv_format, selected, width_table, name_table);
    }
    for(i=0; i < elements()->length(); i++) {
      KlassInfoEntry* e = (KlassInfoEntry*)elements()->at(i);
      const Klass* k = e->klass();

      memset(&sz, 0, sizeof(sz));
      sz._inst_count = e->count();
      sz._inst_bytes = HeapWordSize * e->words();
      k->collect_statistics(&sz);
      sz._total_bytes = sz._ro_bytes + sz._rw_bytes;

      if (pass == 1) {
        for (int c=0; c<KlassSizeStats::_num_columns; c++) {
          colsum_table[c] += col_table[c];
        }
      } else {
        int super_index = -1;
        if (k->oop_is_instance()) {
          Klass* super = ((InstanceKlass*)k)->java_super();
          if (super) {
            KlassInfoEntry* super_e = _cit->lookup(super);
            if (super_e) {
              super_index = super_e->index();
            }
          }
        }

        if (csv_format) {
          st->print("%d,%d", e->index(), super_index);
          for (int c=0; c<KlassSizeStats::_num_columns; c++) {
            if (selected[c]) {st->print("," JULONG_FORMAT, col_table[c]);}
          }
          st->print(",%s",e->name());
        } else {
          st->print("%5d %5d", e->index(), super_index);
          for (int c=0; c<KlassSizeStats::_num_columns; c++) {
            if (selected[c]) {print_julong(st, width_table[c], col_table[c]);}
          }
          st->print(" %s", e->name());
        }
        if (is_selected("ClassLoader")) {
          ClassLoaderData* loader_data = k->class_loader_data();
          st->print(",");
          loader_data->print_value_on(st);
        }
        st->cr();
      }
    }

    if (pass == 1) {
      for (int c=0; c<KlassSizeStats::_num_columns; c++) {
        width_table[c] = col_width(colsum_table[c], name_table[c]);
      }
    }
  }

  sz_sum._inst_size = 0;

  if (csv_format) {
    st->print(",");
    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
      if (selected[c]) {st->print("," JULONG_FORMAT, colsum_table[c]);}
    }
  } else {
    st->print("           ");
    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
      if (selected[c]) {print_julong(st, width_table[c], colsum_table[c]);}
    }
    st->print(" Total");
    if (sz_sum._total_bytes > 0) {
      st->cr();
      st->print("           ");
      for (int c=0; c<KlassSizeStats::_num_columns; c++) {
        if (selected[c]) {
          switch (c) {
          case KlassSizeStats::_index_inst_size:
          case KlassSizeStats::_index_inst_count:
          case KlassSizeStats::_index_method_count:
405 406
PRAGMA_DIAG_PUSH
PRAGMA_FORMAT_NONLITERAL_IGNORED_INTERNAL
407
            st->print(str_fmt(width_table[c]), "-");
408
PRAGMA_DIAG_POP
409 410 411 412
            break;
          default:
            {
              double perc = (double)(100) * (double)(colsum_table[c]) / (double)sz_sum._total_bytes;
413 414
PRAGMA_DIAG_PUSH
PRAGMA_FORMAT_NONLITERAL_IGNORED_INTERNAL
415
              st->print(perc_fmt(width_table[c]), perc);
416
PRAGMA_DIAG_POP
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
            }
          }
        }
      }
    }
  }
  st->cr();

  if (!csv_format) {
    print_title(st, csv_format, selected, width_table, name_table);
  }
}

julong KlassInfoHisto::annotations_bytes(Array<AnnotationArray*>* p) const {
  julong bytes = 0;
  if (p != NULL) {
    for (int i = 0; i < p->length(); i++) {
      bytes += count_bytes_array(p->at(i));
    }
    bytes += count_bytes_array(p);
  }
  return bytes;
}

void KlassInfoHisto::print_histo_on(outputStream* st, bool print_stats,
                                    bool csv_format, const char *columns) {
  if (print_stats) {
    print_class_stats(st, csv_format, columns);
  } else {
    st->print_cr("%s",title());
    print_elements(st);
  }
D
duke 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
}

class HistoClosure : public KlassInfoClosure {
 private:
  KlassInfoHisto* _cih;
 public:
  HistoClosure(KlassInfoHisto* cih) : _cih(cih) {}

  void do_cinfo(KlassInfoEntry* cie) {
    _cih->add(cie);
  }
};

class RecordInstanceClosure : public ObjectClosure {
 private:
  KlassInfoTable* _cit;
465
  size_t _missed_count;
S
sla 已提交
466
  BoolObjectClosure* _filter;
D
duke 已提交
467
 public:
S
sla 已提交
468 469
  RecordInstanceClosure(KlassInfoTable* cit, BoolObjectClosure* filter) :
    _cit(cit), _missed_count(0), _filter(filter) {}
D
duke 已提交
470 471

  void do_object(oop obj) {
S
sla 已提交
472 473 474 475
    if (should_visit(obj)) {
      if (!_cit->record_instance(obj)) {
        _missed_count++;
      }
476
    }
D
duke 已提交
477
  }
478 479

  size_t missed_count() { return _missed_count; }
S
sla 已提交
480 481 482 483 484

 private:
  bool should_visit(oop obj) {
    return _filter == NULL || _filter->do_object_b(obj);
  }
D
duke 已提交
485 486
};

S
sla 已提交
487 488 489 490
size_t HeapInspection::populate_table(KlassInfoTable* cit, BoolObjectClosure *filter) {
  ResourceMark rm;

  RecordInstanceClosure ric(cit, filter);
491 492 493 494 495 496 497 498
  if (PrintYoungGenHistoAfterParNewGC && UseParNewGC) {
    assert(GenCollectedHeap::heap()->n_gens() == 2, "When using ParNew GC, there are only two generations");
    GenCollectedHeap::heap()->get_gen(0)->object_iterate(&ric);
    return ric.missed_count();
  } else {
    Universe::heap()->object_iterate(&ric);
    return ric.missed_count();
  }
S
sla 已提交
499 500 501
}

void HeapInspection::heap_inspection(outputStream* st) {
D
duke 已提交
502
  ResourceMark rm;
503

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
  if (_print_help) {
    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
      st->print("%s:\n\t", name_table[c]);
      const int max_col = 60;
      int col = 0;
      for (const char *p = help_table[c]; *p; p++,col++) {
        if (col >= max_col && *p == ' ') {
          st->print("\n\t");
          col = 0;
        } else {
          st->print("%c", *p);
        }
      }
      st->print_cr(".\n");
    }
    return;
  }

S
sla 已提交
522
  KlassInfoTable cit(_print_class_stats);
523
  if (!cit.allocation_failed()) {
S
sla 已提交
524
    size_t missed_count = populate_table(&cit);
525 526 527 528 529
    if (missed_count != 0) {
      st->print_cr("WARNING: Ran out of C-heap; undercounted " SIZE_FORMAT
                   " total instances in data below",
                   missed_count);
    }
S
sla 已提交
530

531
    // Sort and print klass instance info
532 533 534
    const char *title = "\n"
              " num     #instances         #bytes  class name\n"
              "----------------------------------------------";
S
sla 已提交
535
    KlassInfoHisto histo(&cit, title);
536
    HistoClosure hc(&histo);
S
sla 已提交
537

538
    cit.iterate(&hc);
S
sla 已提交
539

540
    histo.sort();
541
    histo.print_histo_on(st, _print_class_stats, _csv_format, _columns);
542 543 544
  } else {
    st->print_cr("WARNING: Ran out of C-heap; histogram not generated");
  }
D
duke 已提交
545 546 547 548 549
  st->flush();
}

class FindInstanceClosure : public ObjectClosure {
 private:
550
  Klass* _klass;
D
duke 已提交
551 552 553
  GrowableArray<oop>* _result;

 public:
554
  FindInstanceClosure(Klass* k, GrowableArray<oop>* result) : _klass(k), _result(result) {};
D
duke 已提交
555 556 557 558 559 560 561 562

  void do_object(oop obj) {
    if (obj->is_a(_klass)) {
      _result->append(obj);
    }
  }
};

563
void HeapInspection::find_instances_at_safepoint(Klass* k, GrowableArray<oop>* result) {
D
duke 已提交
564
  assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
565
  assert(Heap_lock->is_locked(), "should have the Heap_lock");
D
duke 已提交
566 567 568 569 570 571

  // Ensure that the heap is parsable
  Universe::heap()->ensure_parsability(false);  // no need to retire TALBs

  // Iterate over objects in the heap
  FindInstanceClosure fic(k, result);
572
  // If this operation encounters a bad object when using CMS,
573
  // consider using safe_object_iterate() which avoids metadata
574
  // objects that may contain bad references.
D
duke 已提交
575 576
  Universe::heap()->object_iterate(&fic);
}