rev 54097 : 8216314: SIGILL in CodeHeapState::print_names()
Reviewed-by: thartmann, kvn

   1 /*
   2  * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2018, 2019 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "code/codeHeapState.hpp"
  28 #include "compiler/compileBroker.hpp"
  29 #include "runtime/sweeper.hpp"
  30 
  31 // -------------------------
  32 // |  General Description  |
  33 // -------------------------
  34 // The CodeHeap state analytics are divided in two parts.
  35 // The first part examines the entire CodeHeap and aggregates all
  36 // information that is believed useful/important.
  37 //
  38 // Aggregation condenses the information of a piece of the CodeHeap
  39 // (4096 bytes by default) into an analysis granule. These granules
  40 // contain enough detail to gain initial insight while keeping the
  41 // internal structure sizes in check.
  42 //





  43 // The second part, which consists of several, independent steps,
  44 // prints the previously collected information with emphasis on
  45 // various aspects.
  46 //
  47 // The CodeHeap is a living thing. Therefore, protection against concurrent
  48 // modification (by acquiring the CodeCache_lock) is necessary. It has
  49 // to be provided by the caller of the analysis functions.
  50 // If the CodeCache_lock is not held, the analysis functions may print
  51 // less detailed information or may just do nothing. It is by intention
  52 // that an unprotected invocation is not abnormally terminated.
  53 //
  54 // Data collection and printing is done on an "on request" basis.
  55 // While no request is being processed, there is no impact on performance.
  56 // The CodeHeap state analytics do have some memory footprint.
  57 // The "aggregate" step allocates some data structures to hold the aggregated
  58 // information for later output. These data structures live until they are
  59 // explicitly discarded (function "discard") or until the VM terminates.
  60 // There is one exception: the function "all" does not leave any data
  61 // structures allocated.
  62 //
  63 // Requests for real-time, on-the-fly analysis can be issued via
  64 //   jcmd <pid> Compiler.CodeHeap_Analytics [<function>] [<granularity>]
  65 //
  66 // If you are (only) interested in how the CodeHeap looks like after running
  67 // a sample workload, you can use the command line option
  68 //   -XX:+PrintCodeHeapAnalytics
  69 // It will cause a full analysis to be written to tty. In addition, a full
  70 // analysis will be written the first time a "CodeCache full" condition is
  71 // detected.
  72 //
  73 // The command line option produces output identical to the jcmd function
  74 //   jcmd <pid> Compiler.CodeHeap_Analytics all 4096
  75 // ---------------------------------------------------------------------------------
  76 
  77 // With this declaration macro, it is possible to switch between
  78 //  - direct output into an argument-passed outputStream and
  79 //  - buffered output into a bufferedStream with subsequent flush
  80 //    of the filled buffer to the outputStream.
  81 #define USE_STRINGSTREAM
  82 #define HEX32_FORMAT  "0x%x"  // just a helper format string used below multiple times
  83 //
  84 // Writing to a bufferedStream buffer first has a significant advantage:
  85 // It uses noticeably less cpu cycles and reduces (when wirting to a
  86 // network file) the required bandwidth by at least a factor of ten.
  87 // That clearly makes up for the increased code complexity.
  88 #if defined(USE_STRINGSTREAM)
  89 #define STRINGSTREAM_DECL(_anyst, _outst)                 \
  90     /* _anyst  name of the stream as used in the code */  \
  91     /* _outst  stream where final output will go to   */  \
  92     ResourceMark rm;                                      \
  93     bufferedStream   _sstobj(4*K);                        \
  94     bufferedStream*  _sstbuf = &_sstobj;                  \
  95     outputStream*    _outbuf = _outst;                    \
  96     bufferedStream*  _anyst  = &_sstobj; /* any stream. Use this to just print - no buffer flush.  */
  97 
  98 #define STRINGSTREAM_FLUSH(termString)                    \
  99     _sstbuf->print("%s", termString);                     \
 100     _outbuf->print("%s", _sstbuf->as_string());           \
 101     _sstbuf->reset();
 102 
 103 #define STRINGSTREAM_FLUSH_LOCKED(termString)             \
 104     { ttyLocker ttyl;/* keep this output block together */\
 105       STRINGSTREAM_FLUSH(termString)                      \
 106     }
 107 #else
 108 #define STRINGSTREAM_DECL(_anyst, _outst)                 \
 109     outputStream*  _outbuf = _outst;                      \
 110     outputStream*  _anyst  = _outst;   /* any stream. Use this to just print - no buffer flush.  */
 111 
 112 #define STRINGSTREAM_FLUSH(termString)                    \
 113     _outbuf->print("%s", termString);
 114 
 115 #define STRINGSTREAM_FLUSH_LOCKED(termString)             \
 116     _outbuf->print("%s", termString);
 117 #endif
 118 
 119 const char  blobTypeChar[] = {' ', 'C', 'N', 'I', 'X', 'Z', 'U', 'R', '?', 'D', 'T', 'E', 'S', 'A', 'M', 'B', 'L' };
 120 const char* blobTypeName[] = {"noType"
 121                              ,     "nMethod (under construction)"
 122                              ,          "nMethod (active)"
 123                              ,               "nMethod (inactive)"
 124                              ,                    "nMethod (deopt)"
 125                              ,                         "nMethod (zombie)"
 126                              ,                              "nMethod (unloaded)"
 127                              ,                                   "runtime stub"
 128                              ,                                        "ricochet stub"
 129                              ,                                             "deopt stub"
 130                              ,                                                  "uncommon trap stub"
 131                              ,                                                       "exception stub"
 132                              ,                                                            "safepoint stub"
 133                              ,                                                                 "adapter blob"
 134                              ,                                                                      "MH adapter blob"
 135                              ,                                                                           "buffer blob"
 136                              ,                                                                                "lastType"
 137                              };
 138 const char* compTypeName[] = { "none", "c1", "c2", "jvmci" };
 139 
 140 // Be prepared for ten different CodeHeap segments. Should be enough for a few years.
 141 const  unsigned int        nSizeDistElements = 31;  // logarithmic range growth, max size: 2**32
 142 const  unsigned int        maxTopSizeBlocks  = 50;
 143 const  unsigned int        tsbStopper        = 2 * maxTopSizeBlocks;
 144 const  unsigned int        maxHeaps          = 10;
 145 static unsigned int        nHeaps            = 0;
 146 static struct CodeHeapStat CodeHeapStatArray[maxHeaps];
 147 
 148 // static struct StatElement *StatArray      = NULL;
 149 static StatElement* StatArray             = NULL;
 150 static int          log2_seg_size         = 0;
 151 static size_t       seg_size              = 0;
 152 static size_t       alloc_granules        = 0;
 153 static size_t       granule_size          = 0;
 154 static bool         segment_granules      = false;
 155 static unsigned int nBlocks_t1            = 0;  // counting "in_use" nmethods only.
 156 static unsigned int nBlocks_t2            = 0;  // counting "in_use" nmethods only.
 157 static unsigned int nBlocks_alive         = 0;  // counting "not_used" and "not_entrant" nmethods only.
 158 static unsigned int nBlocks_dead          = 0;  // counting "zombie" and "unloaded" methods only.
 159 static unsigned int nBlocks_inconstr      = 0;  // counting "inconstruction" nmethods only. This is a transient state.
 160 static unsigned int nBlocks_unloaded      = 0;  // counting "unloaded" nmethods only. This is a transient state.
 161 static unsigned int nBlocks_stub          = 0;
 162 
 163 static struct FreeBlk*          FreeArray = NULL;
 164 static unsigned int      alloc_freeBlocks = 0;
 165 
 166 static struct TopSizeBlk*    TopSizeArray = NULL;
 167 static unsigned int   alloc_topSizeBlocks = 0;
 168 static unsigned int    used_topSizeBlocks = 0;
 169 
 170 static struct SizeDistributionElement*  SizeDistributionArray = NULL;
 171 
 172 // nMethod temperature (hotness) indicators.
 173 static int                     avgTemp    = 0;
 174 static int                     maxTemp    = 0;
 175 static int                     minTemp    = 0;
 176 
 177 static unsigned int  latest_compilation_id   = 0;
 178 static volatile bool initialization_complete = false;
 179 
 180 const char* CodeHeapState::get_heapName(CodeHeap* heap) {
 181   if (SegmentedCodeCache) {
 182     return heap->name();
 183   } else {
 184     return "CodeHeap";
 185   }
 186 }
 187 
 188 // returns the index for the heap being processed.
 189 unsigned int CodeHeapState::findHeapIndex(outputStream* out, const char* heapName) {
 190   if (heapName == NULL) {
 191     return maxHeaps;
 192   }
 193   if (SegmentedCodeCache) {
 194     // Search for a pre-existing entry. If found, return that index.
 195     for (unsigned int i = 0; i < nHeaps; i++) {
 196       if (CodeHeapStatArray[i].heapName != NULL && strcmp(heapName, CodeHeapStatArray[i].heapName) == 0) {
 197         return i;
 198       }
 199     }
 200 
 201     // check if there are more code heap segments than we can handle.
 202     if (nHeaps == maxHeaps) {
 203       out->print_cr("Too many heap segments for current limit(%d).", maxHeaps);
 204       return maxHeaps;
 205     }
 206 
 207     // allocate new slot in StatArray.
 208     CodeHeapStatArray[nHeaps].heapName = heapName;
 209     return nHeaps++;
 210   } else {
 211     nHeaps = 1;
 212     CodeHeapStatArray[0].heapName = heapName;
 213     return 0; // This is the default index if CodeCache is not segmented.
 214   }
 215 }
 216 
 217 void CodeHeapState::get_HeapStatGlobals(outputStream* out, const char* heapName) {
 218   unsigned int ix = findHeapIndex(out, heapName);
 219   if (ix < maxHeaps) {
 220     StatArray             = CodeHeapStatArray[ix].StatArray;
 221     seg_size              = CodeHeapStatArray[ix].segment_size;
 222     log2_seg_size         = seg_size == 0 ? 0 : exact_log2(seg_size);
 223     alloc_granules        = CodeHeapStatArray[ix].alloc_granules;
 224     granule_size          = CodeHeapStatArray[ix].granule_size;
 225     segment_granules      = CodeHeapStatArray[ix].segment_granules;
 226     nBlocks_t1            = CodeHeapStatArray[ix].nBlocks_t1;
 227     nBlocks_t2            = CodeHeapStatArray[ix].nBlocks_t2;
 228     nBlocks_alive         = CodeHeapStatArray[ix].nBlocks_alive;
 229     nBlocks_dead          = CodeHeapStatArray[ix].nBlocks_dead;
 230     nBlocks_inconstr      = CodeHeapStatArray[ix].nBlocks_inconstr;
 231     nBlocks_unloaded      = CodeHeapStatArray[ix].nBlocks_unloaded;
 232     nBlocks_stub          = CodeHeapStatArray[ix].nBlocks_stub;
 233     FreeArray             = CodeHeapStatArray[ix].FreeArray;
 234     alloc_freeBlocks      = CodeHeapStatArray[ix].alloc_freeBlocks;
 235     TopSizeArray          = CodeHeapStatArray[ix].TopSizeArray;
 236     alloc_topSizeBlocks   = CodeHeapStatArray[ix].alloc_topSizeBlocks;
 237     used_topSizeBlocks    = CodeHeapStatArray[ix].used_topSizeBlocks;
 238     SizeDistributionArray = CodeHeapStatArray[ix].SizeDistributionArray;
 239     avgTemp               = CodeHeapStatArray[ix].avgTemp;
 240     maxTemp               = CodeHeapStatArray[ix].maxTemp;
 241     minTemp               = CodeHeapStatArray[ix].minTemp;
 242   } else {
 243     StatArray             = NULL;
 244     seg_size              = 0;
 245     log2_seg_size         = 0;
 246     alloc_granules        = 0;
 247     granule_size          = 0;
 248     segment_granules      = false;
 249     nBlocks_t1            = 0;
 250     nBlocks_t2            = 0;
 251     nBlocks_alive         = 0;
 252     nBlocks_dead          = 0;
 253     nBlocks_inconstr      = 0;
 254     nBlocks_unloaded      = 0;
 255     nBlocks_stub          = 0;
 256     FreeArray             = NULL;
 257     alloc_freeBlocks      = 0;
 258     TopSizeArray          = NULL;
 259     alloc_topSizeBlocks   = 0;
 260     used_topSizeBlocks    = 0;
 261     SizeDistributionArray = NULL;
 262     avgTemp               = 0;
 263     maxTemp               = 0;
 264     minTemp               = 0;
 265   }
 266 }
 267 
 268 void CodeHeapState::set_HeapStatGlobals(outputStream* out, const char* heapName) {
 269   unsigned int ix = findHeapIndex(out, heapName);
 270   if (ix < maxHeaps) {
 271     CodeHeapStatArray[ix].StatArray             = StatArray;
 272     CodeHeapStatArray[ix].segment_size          = seg_size;
 273     CodeHeapStatArray[ix].alloc_granules        = alloc_granules;
 274     CodeHeapStatArray[ix].granule_size          = granule_size;
 275     CodeHeapStatArray[ix].segment_granules      = segment_granules;
 276     CodeHeapStatArray[ix].nBlocks_t1            = nBlocks_t1;
 277     CodeHeapStatArray[ix].nBlocks_t2            = nBlocks_t2;
 278     CodeHeapStatArray[ix].nBlocks_alive         = nBlocks_alive;
 279     CodeHeapStatArray[ix].nBlocks_dead          = nBlocks_dead;
 280     CodeHeapStatArray[ix].nBlocks_inconstr      = nBlocks_inconstr;
 281     CodeHeapStatArray[ix].nBlocks_unloaded      = nBlocks_unloaded;
 282     CodeHeapStatArray[ix].nBlocks_stub          = nBlocks_stub;
 283     CodeHeapStatArray[ix].FreeArray             = FreeArray;
 284     CodeHeapStatArray[ix].alloc_freeBlocks      = alloc_freeBlocks;
 285     CodeHeapStatArray[ix].TopSizeArray          = TopSizeArray;
 286     CodeHeapStatArray[ix].alloc_topSizeBlocks   = alloc_topSizeBlocks;
 287     CodeHeapStatArray[ix].used_topSizeBlocks    = used_topSizeBlocks;
 288     CodeHeapStatArray[ix].SizeDistributionArray = SizeDistributionArray;
 289     CodeHeapStatArray[ix].avgTemp               = avgTemp;
 290     CodeHeapStatArray[ix].maxTemp               = maxTemp;
 291     CodeHeapStatArray[ix].minTemp               = minTemp;
 292   }
 293 }
 294 
 295 //---<  get a new statistics array  >---
 296 void CodeHeapState::prepare_StatArray(outputStream* out, size_t nElem, size_t granularity, const char* heapName) {
 297   if (StatArray == NULL) {
 298     StatArray      = new StatElement[nElem];
 299     //---<  reset some counts  >---
 300     alloc_granules = nElem;
 301     granule_size   = granularity;
 302   }
 303 
 304   if (StatArray == NULL) {
 305     //---<  just do nothing if allocation failed  >---
 306     out->print_cr("Statistics could not be collected for %s, probably out of memory.", heapName);
 307     out->print_cr("Current granularity is " SIZE_FORMAT " bytes. Try a coarser granularity.", granularity);
 308     alloc_granules = 0;
 309     granule_size   = 0;
 310   } else {
 311     //---<  initialize statistics array  >---
 312     memset((void*)StatArray, 0, nElem*sizeof(StatElement));
 313   }
 314 }
 315 
 316 //---<  get a new free block array  >---
 317 void CodeHeapState::prepare_FreeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 318   if (FreeArray == NULL) {
 319     FreeArray      = new FreeBlk[nElem];
 320     //---<  reset some counts  >---
 321     alloc_freeBlocks = nElem;
 322   }
 323 
 324   if (FreeArray == NULL) {
 325     //---<  just do nothing if allocation failed  >---
 326     out->print_cr("Free space analysis cannot be done for %s, probably out of memory.", heapName);
 327     alloc_freeBlocks = 0;
 328   } else {
 329     //---<  initialize free block array  >---
 330     memset((void*)FreeArray, 0, alloc_freeBlocks*sizeof(FreeBlk));
 331   }
 332 }
 333 
 334 //---<  get a new TopSizeArray  >---
 335 void CodeHeapState::prepare_TopSizeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 336   if (TopSizeArray == NULL) {
 337     TopSizeArray   = new TopSizeBlk[nElem];
 338     //---<  reset some counts  >---
 339     alloc_topSizeBlocks = nElem;
 340     used_topSizeBlocks  = 0;
 341   }
 342 
 343   if (TopSizeArray == NULL) {
 344     //---<  just do nothing if allocation failed  >---
 345     out->print_cr("Top-%d list of largest CodeHeap blocks can not be collected for %s, probably out of memory.", nElem, heapName);
 346     alloc_topSizeBlocks = 0;
 347   } else {
 348     //---<  initialize TopSizeArray  >---
 349     memset((void*)TopSizeArray, 0, nElem*sizeof(TopSizeBlk));
 350     used_topSizeBlocks  = 0;
 351   }
 352 }
 353 
 354 //---<  get a new SizeDistributionArray  >---
 355 void CodeHeapState::prepare_SizeDistArray(outputStream* out, unsigned int nElem, const char* heapName) {
 356   if (SizeDistributionArray == NULL) {
 357     SizeDistributionArray = new SizeDistributionElement[nElem];
 358   }
 359 
 360   if (SizeDistributionArray == NULL) {
 361     //---<  just do nothing if allocation failed  >---
 362     out->print_cr("Size distribution can not be collected for %s, probably out of memory.", heapName);
 363   } else {
 364     //---<  initialize SizeDistArray  >---
 365     memset((void*)SizeDistributionArray, 0, nElem*sizeof(SizeDistributionElement));
 366     // Logarithmic range growth. First range starts at _segment_size.
 367     SizeDistributionArray[log2_seg_size-1].rangeEnd = 1U;
 368     for (unsigned int i = log2_seg_size; i < nElem; i++) {
 369       SizeDistributionArray[i].rangeStart = 1U << (i     - log2_seg_size);
 370       SizeDistributionArray[i].rangeEnd   = 1U << ((i+1) - log2_seg_size);
 371     }
 372   }
 373 }
 374 
 375 //---<  get a new SizeDistributionArray  >---
 376 void CodeHeapState::update_SizeDistArray(outputStream* out, unsigned int len) {
 377   if (SizeDistributionArray != NULL) {
 378     for (unsigned int i = log2_seg_size-1; i < nSizeDistElements; i++) {
 379       if ((SizeDistributionArray[i].rangeStart <= len) && (len < SizeDistributionArray[i].rangeEnd)) {
 380         SizeDistributionArray[i].lenSum += len;
 381         SizeDistributionArray[i].count++;
 382         break;
 383       }
 384     }
 385   }
 386 }
 387 
 388 void CodeHeapState::discard_StatArray(outputStream* out) {
 389   if (StatArray != NULL) {
 390     delete StatArray;
 391     StatArray        = NULL;
 392     alloc_granules   = 0;
 393     granule_size     = 0;
 394   }
 395 }
 396 
 397 void CodeHeapState::discard_FreeArray(outputStream* out) {
 398   if (FreeArray != NULL) {
 399     delete[] FreeArray;
 400     FreeArray        = NULL;
 401     alloc_freeBlocks = 0;
 402   }
 403 }
 404 
 405 void CodeHeapState::discard_TopSizeArray(outputStream* out) {
 406   if (TopSizeArray != NULL) {
 407     delete[] TopSizeArray;
 408     TopSizeArray        = NULL;
 409     alloc_topSizeBlocks = 0;
 410     used_topSizeBlocks  = 0;
 411   }
 412 }
 413 
 414 void CodeHeapState::discard_SizeDistArray(outputStream* out) {
 415   if (SizeDistributionArray != NULL) {
 416     delete[] SizeDistributionArray;
 417     SizeDistributionArray = NULL;
 418   }
 419 }
 420 
 421 // Discard all allocated internal data structures.
 422 // This should be done after an analysis session is completed.
 423 void CodeHeapState::discard(outputStream* out, CodeHeap* heap) {
 424   if (!initialization_complete) {
 425     return;
 426   }
 427 
 428   if (nHeaps > 0) {
 429     for (unsigned int ix = 0; ix < nHeaps; ix++) {
 430       get_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 431       discard_StatArray(out);
 432       discard_FreeArray(out);
 433       discard_TopSizeArray(out);
 434       discard_SizeDistArray(out);
 435       set_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 436       CodeHeapStatArray[ix].heapName = NULL;
 437     }
 438     nHeaps = 0;
 439   }
 440 }
 441 
 442 void CodeHeapState::aggregate(outputStream* out, CodeHeap* heap, size_t granularity) {
 443   unsigned int nBlocks_free    = 0;
 444   unsigned int nBlocks_used    = 0;
 445   unsigned int nBlocks_zomb    = 0;
 446   unsigned int nBlocks_disconn = 0;
 447   unsigned int nBlocks_notentr = 0;
 448 
 449   //---<  max & min of TopSizeArray  >---
 450   //  it is sufficient to have these sizes as 32bit unsigned ints.
 451   //  The CodeHeap is limited in size to 4GB. Furthermore, the sizes
 452   //  are stored in _segment_size units, scaling them down by a factor of 64 (at least).
 453   unsigned int  currMax          = 0;
 454   unsigned int  currMin          = 0;
 455   unsigned int  currMin_ix       = 0;
 456   unsigned long total_iterations = 0;
 457 
 458   bool  done             = false;
 459   const int min_granules = 256;
 460   const int max_granules = 512*K; // limits analyzable CodeHeap (with segment_granules) to 32M..128M
 461                                   // results in StatArray size of 24M (= max_granules * 48 Bytes per element)
 462                                   // For a 1GB CodeHeap, the granule size must be at least 2kB to not violate the max_granles limit.
 463   const char* heapName   = get_heapName(heap);
 464   STRINGSTREAM_DECL(ast, out)
 465 
 466   if (!initialization_complete) {
 467     memset(CodeHeapStatArray, 0, sizeof(CodeHeapStatArray));
 468     initialization_complete = true;
 469 
 470     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (general remarks)", NULL);
 471     ast->print_cr("   The code heap analysis function provides deep insights into\n"
 472                   "   the inner workings and the internal state of the Java VM's\n"
 473                   "   code cache - the place where all the JVM generated machine\n"
 474                   "   code is stored.\n"
 475                   "   \n"
 476                   "   This function is designed and provided for support engineers\n"
 477                   "   to help them understand and solve issues in customer systems.\n"
 478                   "   It is not intended for use and interpretation by other persons.\n"
 479                   "   \n");
 480     STRINGSTREAM_FLUSH("")
 481   }
 482   get_HeapStatGlobals(out, heapName);
 483 
 484 
 485   // Since we are (and must be) analyzing the CodeHeap contents under the CodeCache_lock,
 486   // all heap information is "constant" and can be safely extracted/calculated before we
 487   // enter the while() loop. Actually, the loop will only be iterated once.
 488   char*  low_bound     = heap->low_boundary();
 489   size_t size          = heap->capacity();
 490   size_t res_size      = heap->max_capacity();
 491   seg_size             = heap->segment_size();
 492   log2_seg_size        = seg_size == 0 ? 0 : exact_log2(seg_size);  // This is a global static value.
 493 
 494   if (seg_size == 0) {
 495     printBox(ast, '-', "Heap not fully initialized yet, segment size is zero for segment ", heapName);
 496     STRINGSTREAM_FLUSH("")
 497     return;
 498   }
 499 
 500   if (!CodeCache_lock->owned_by_self()) {
 501     printBox(ast, '-', "aggregate function called without holding the CodeCache_lock for ", heapName);
 502     STRINGSTREAM_FLUSH("")
 503     return;
 504   }
 505 
 506   // Calculate granularity of analysis (and output).
 507   //   The CodeHeap is managed (allocated) in segments (units) of CodeCacheSegmentSize.
 508   //   The CodeHeap can become fairly large, in particular in productive real-life systems.
 509   //
 510   //   It is often neither feasible nor desirable to aggregate the data with the highest possible
 511   //   level of detail, i.e. inspecting and printing each segment on its own.
 512   //
 513   //   The granularity parameter allows to specify the level of detail available in the analysis.
 514   //   It must be a positive multiple of the segment size and should be selected such that enough
 515   //   detail is provided while, at the same time, the printed output does not explode.
 516   //
 517   //   By manipulating the granularity value, we enforce that at least min_granules units
 518   //   of analysis are available. We also enforce an upper limit of max_granules units to
 519   //   keep the amount of allocated storage in check.
 520   //
 521   //   Finally, we adjust the granularity such that each granule covers at most 64k-1 segments.
 522   //   This is necessary to prevent an unsigned short overflow while accumulating space information.
 523   //
 524   assert(granularity > 0, "granularity should be positive.");
 525 
 526   if (granularity > size) {
 527     granularity = size;
 528   }
 529   if (size/granularity < min_granules) {
 530     granularity = size/min_granules;                                   // at least min_granules granules
 531   }
 532   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 533   if (granularity < seg_size) {
 534     granularity = seg_size;                                            // must be at least seg_size
 535   }
 536   if (size/granularity > max_granules) {
 537     granularity = size/max_granules;                                   // at most max_granules granules
 538   }
 539   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 540   if (granularity>>log2_seg_size >= (1L<<sizeof(unsigned short)*8)) {
 541     granularity = ((1L<<(sizeof(unsigned short)*8))-1)<<log2_seg_size; // Limit: (64k-1) * seg_size
 542   }
 543   segment_granules = granularity == seg_size;
 544   size_t granules  = (size + (granularity-1))/granularity;
 545 
 546   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (used blocks) for segment ", heapName);
 547   ast->print_cr("   The aggregate step takes an aggregated snapshot of the CodeHeap.\n"
 548                 "   Subsequent print functions create their output based on this snapshot.\n"
 549                 "   The CodeHeap is a living thing, and every effort has been made for the\n"
 550                 "   collected data to be consistent. Only the method names and signatures\n"
 551                 "   are retrieved at print time. That may lead to rare cases where the\n"
 552                 "   name of a method is no longer available, e.g. because it was unloaded.\n");
 553   ast->print_cr("   CodeHeap committed size " SIZE_FORMAT "K (" SIZE_FORMAT "M), reserved size " SIZE_FORMAT "K (" SIZE_FORMAT "M), %d%% occupied.",
 554                 size/(size_t)K, size/(size_t)M, res_size/(size_t)K, res_size/(size_t)M, (unsigned int)(100.0*size/res_size));
 555   ast->print_cr("   CodeHeap allocation segment size is " SIZE_FORMAT " bytes. This is the smallest possible granularity.", seg_size);
 556   ast->print_cr("   CodeHeap (committed part) is mapped to " SIZE_FORMAT " granules of size " SIZE_FORMAT " bytes.", granules, granularity);
 557   ast->print_cr("   Each granule takes " SIZE_FORMAT " bytes of C heap, that is " SIZE_FORMAT "K in total for statistics data.", sizeof(StatElement), (sizeof(StatElement)*granules)/(size_t)K);
 558   ast->print_cr("   The number of granules is limited to %dk, requiring a granules size of at least %d bytes for a 1GB heap.", (unsigned int)(max_granules/K), (unsigned int)(G/max_granules));
 559   STRINGSTREAM_FLUSH("\n")
 560 
 561 
 562   while (!done) {
 563     //---<  reset counters with every aggregation  >---
 564     nBlocks_t1       = 0;
 565     nBlocks_t2       = 0;
 566     nBlocks_alive    = 0;
 567     nBlocks_dead     = 0;
 568     nBlocks_inconstr = 0;
 569     nBlocks_unloaded = 0;
 570     nBlocks_stub     = 0;
 571 
 572     nBlocks_free     = 0;
 573     nBlocks_used     = 0;
 574     nBlocks_zomb     = 0;
 575     nBlocks_disconn  = 0;
 576     nBlocks_notentr  = 0;
 577 
 578     //---<  discard old arrays if size does not match  >---
 579     if (granules != alloc_granules) {
 580       discard_StatArray(out);
 581       discard_TopSizeArray(out);
 582     }
 583 
 584     //---<  allocate arrays if they don't yet exist, initialize  >---
 585     prepare_StatArray(out, granules, granularity, heapName);
 586     if (StatArray == NULL) {
 587       set_HeapStatGlobals(out, heapName);
 588       return;
 589     }
 590     prepare_TopSizeArray(out, maxTopSizeBlocks, heapName);
 591     prepare_SizeDistArray(out, nSizeDistElements, heapName);
 592 
 593     latest_compilation_id = CompileBroker::get_compilation_id();
 594     unsigned int highest_compilation_id = 0;
 595     size_t       usedSpace     = 0;
 596     size_t       t1Space       = 0;
 597     size_t       t2Space       = 0;
 598     size_t       aliveSpace    = 0;
 599     size_t       disconnSpace  = 0;
 600     size_t       notentrSpace  = 0;
 601     size_t       deadSpace     = 0;
 602     size_t       inconstrSpace = 0;
 603     size_t       unloadedSpace = 0;
 604     size_t       stubSpace     = 0;
 605     size_t       freeSpace     = 0;
 606     size_t       maxFreeSize   = 0;
 607     HeapBlock*   maxFreeBlock  = NULL;
 608     bool         insane        = false;
 609 
 610     int64_t hotnessAccumulator = 0;
 611     unsigned int n_methods     = 0;
 612     avgTemp       = 0;
 613     minTemp       = (int)(res_size > M ? (res_size/M)*2 : 1);
 614     maxTemp       = -minTemp;
 615 
 616     for (HeapBlock *h = heap->first_block(); h != NULL && !insane; h = heap->next_block(h)) {
 617       unsigned int hb_len     = (unsigned int)h->length();  // despite being size_t, length can never overflow an unsigned int.
 618       size_t       hb_bytelen = ((size_t)hb_len)<<log2_seg_size;
 619       unsigned int ix_beg     = (unsigned int)(((char*)h-low_bound)/granule_size);
 620       unsigned int ix_end     = (unsigned int)(((char*)h-low_bound+(hb_bytelen-1))/granule_size);
 621       unsigned int compile_id = 0;
 622       CompLevel    comp_lvl   = CompLevel_none;
 623       compType     cType      = noComp;
 624       blobType     cbType     = noType;
 625 
 626       //---<  some sanity checks  >---
 627       // Do not assert here, just check, print error message and return.
 628       // This is a diagnostic function. It is not supposed to tear down the VM.
 629       if ((char*)h <  low_bound) {
 630         insane = true; ast->print_cr("Sanity check: HeapBlock @%p below low bound (%p)", (char*)h, low_bound);
 631       }
 632       if ((char*)h >  (low_bound + res_size)) {
 633         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside reserved range (%p)", (char*)h, low_bound + res_size);
 634       }
 635       if ((char*)h >  (low_bound + size)) {
 636         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside used range (%p)", (char*)h, low_bound + size);
 637       }
 638       if (ix_end   >= granules) {
 639         insane = true; ast->print_cr("Sanity check: end index (%d) out of bounds (" SIZE_FORMAT ")", ix_end, granules);
 640       }
 641       if (size     != heap->capacity()) {
 642         insane = true; ast->print_cr("Sanity check: code heap capacity has changed (" SIZE_FORMAT "K to " SIZE_FORMAT "K)", size/(size_t)K, heap->capacity()/(size_t)K);
 643       }
 644       if (ix_beg   >  ix_end) {
 645         insane = true; ast->print_cr("Sanity check: end index (%d) lower than begin index (%d)", ix_end, ix_beg);
 646       }
 647       if (insane) {
 648         STRINGSTREAM_FLUSH("")
 649         continue;
 650       }
 651 
 652       if (h->free()) {
 653         nBlocks_free++;
 654         freeSpace    += hb_bytelen;
 655         if (hb_bytelen > maxFreeSize) {
 656           maxFreeSize   = hb_bytelen;
 657           maxFreeBlock  = h;
 658         }
 659       } else {
 660         update_SizeDistArray(out, hb_len);
 661         nBlocks_used++;
 662         usedSpace    += hb_bytelen;
 663         CodeBlob* cb  = (CodeBlob*)heap->find_start(h);
 664         if (cb != NULL) {
 665           cbType = get_cbType(cb);
 666           if (cb->is_nmethod()) {
 667             compile_id = ((nmethod*)cb)->compile_id();
 668             comp_lvl   = (CompLevel)((nmethod*)cb)->comp_level();
 669             if (((nmethod*)cb)->is_compiled_by_c1()) {
 670               cType = c1;
 671             }
 672             if (((nmethod*)cb)->is_compiled_by_c2()) {
 673               cType = c2;
 674             }
 675             if (((nmethod*)cb)->is_compiled_by_jvmci()) {
 676               cType = jvmci;
 677             }
 678             switch (cbType) {
 679               case nMethod_inuse: { // only for executable methods!!!
 680                 // space for these cbs is accounted for later.
 681                 int temperature = ((nmethod*)cb)->hotness_counter();
 682                 hotnessAccumulator += temperature;
 683                 n_methods++;
 684                 maxTemp = (temperature > maxTemp) ? temperature : maxTemp;
 685                 minTemp = (temperature < minTemp) ? temperature : minTemp;
 686                 break;
 687               }
 688               case nMethod_notused:
 689                 nBlocks_alive++;
 690                 nBlocks_disconn++;
 691                 aliveSpace     += hb_bytelen;
 692                 disconnSpace   += hb_bytelen;
 693                 break;
 694               case nMethod_notentrant:  // equivalent to nMethod_alive
 695                 nBlocks_alive++;
 696                 nBlocks_notentr++;
 697                 aliveSpace     += hb_bytelen;
 698                 notentrSpace   += hb_bytelen;
 699                 break;
 700               case nMethod_unloaded:
 701                 nBlocks_unloaded++;
 702                 unloadedSpace  += hb_bytelen;
 703                 break;
 704               case nMethod_dead:
 705                 nBlocks_dead++;
 706                 deadSpace      += hb_bytelen;
 707                 break;
 708               case nMethod_inconstruction:
 709                 nBlocks_inconstr++;
 710                 inconstrSpace  += hb_bytelen;
 711                 break;
 712               default:
 713                 break;
 714             }
 715           }
 716 
 717           //------------------------------------------
 718           //---<  register block in TopSizeArray  >---
 719           //------------------------------------------
 720           if (alloc_topSizeBlocks > 0) {
 721             if (used_topSizeBlocks == 0) {
 722               TopSizeArray[0].start    = h;
 723               TopSizeArray[0].len      = hb_len;
 724               TopSizeArray[0].index    = tsbStopper;
 725               TopSizeArray[0].compiler = cType;
 726               TopSizeArray[0].level    = comp_lvl;
 727               TopSizeArray[0].type     = cbType;
 728               currMax    = hb_len;
 729               currMin    = hb_len;
 730               currMin_ix = 0;
 731               used_topSizeBlocks++;
 732             // This check roughly cuts 5000 iterations (JVM98, mixed, dbg, termination stats):
 733             } else if ((used_topSizeBlocks < alloc_topSizeBlocks) && (hb_len < currMin)) {
 734               //---<  all blocks in list are larger, but there is room left in array  >---
 735               TopSizeArray[currMin_ix].index = used_topSizeBlocks;
 736               TopSizeArray[used_topSizeBlocks].start    = h;
 737               TopSizeArray[used_topSizeBlocks].len      = hb_len;
 738               TopSizeArray[used_topSizeBlocks].index    = tsbStopper;
 739               TopSizeArray[used_topSizeBlocks].compiler = cType;
 740               TopSizeArray[used_topSizeBlocks].level    = comp_lvl;
 741               TopSizeArray[used_topSizeBlocks].type     = cbType;
 742               currMin    = hb_len;
 743               currMin_ix = used_topSizeBlocks;
 744               used_topSizeBlocks++;
 745             } else {
 746               // This check cuts total_iterations by a factor of 6 (JVM98, mixed, dbg, termination stats):
 747               //   We don't need to search the list if we know beforehand that the current block size is
 748               //   smaller than the currently recorded minimum and there is no free entry left in the list.
 749               if (!((used_topSizeBlocks == alloc_topSizeBlocks) && (hb_len <= currMin))) {
 750                 if (currMax < hb_len) {
 751                   currMax = hb_len;
 752                 }
 753                 unsigned int i;
 754                 unsigned int prev_i  = tsbStopper;
 755                 unsigned int limit_i =  0;
 756                 for (i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
 757                   if (limit_i++ >= alloc_topSizeBlocks) {
 758                     insane = true; break; // emergency exit
 759                   }
 760                   if (i >= used_topSizeBlocks)  {
 761                     insane = true; break; // emergency exit
 762                   }
 763                   total_iterations++;
 764                   if (TopSizeArray[i].len < hb_len) {
 765                     //---<  We want to insert here, element <i> is smaller than the current one  >---
 766                     if (used_topSizeBlocks < alloc_topSizeBlocks) { // still room for a new entry to insert
 767                       // old entry gets moved to the next free element of the array.
 768                       // That's necessary to keep the entry for the largest block at index 0.
 769                       // This move might cause the current minimum to be moved to another place
 770                       if (i == currMin_ix) {
 771                         assert(TopSizeArray[i].len == currMin, "sort error");
 772                         currMin_ix = used_topSizeBlocks;
 773                       }
 774                       memcpy((void*)&TopSizeArray[used_topSizeBlocks], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 775                       TopSizeArray[i].start    = h;
 776                       TopSizeArray[i].len      = hb_len;
 777                       TopSizeArray[i].index    = used_topSizeBlocks;
 778                       TopSizeArray[i].compiler = cType;
 779                       TopSizeArray[i].level    = comp_lvl;
 780                       TopSizeArray[i].type     = cbType;
 781                       used_topSizeBlocks++;
 782                     } else { // no room for new entries, current block replaces entry for smallest block
 783                       //---<  Find last entry (entry for smallest remembered block)  >---
 784                       unsigned int      j  = i;
 785                       unsigned int prev_j  = tsbStopper;
 786                       unsigned int limit_j = 0;
 787                       while (TopSizeArray[j].index != tsbStopper) {
 788                         if (limit_j++ >= alloc_topSizeBlocks) {
 789                           insane = true; break; // emergency exit
 790                         }
 791                         if (j >= used_topSizeBlocks)  {
 792                           insane = true; break; // emergency exit
 793                         }
 794                         total_iterations++;
 795                         prev_j = j;
 796                         j      = TopSizeArray[j].index;
 797                       }
 798                       if (!insane) {
 799                         if (prev_j == tsbStopper) {
 800                           //---<  Above while loop did not iterate, we already are the min entry  >---
 801                           //---<  We have to just replace the smallest entry                      >---
 802                           currMin    = hb_len;
 803                           currMin_ix = j;
 804                           TopSizeArray[j].start    = h;
 805                           TopSizeArray[j].len      = hb_len;
 806                           TopSizeArray[j].index    = tsbStopper; // already set!!
 807                           TopSizeArray[j].compiler = cType;
 808                           TopSizeArray[j].level    = comp_lvl;
 809                           TopSizeArray[j].type     = cbType;
 810                         } else {
 811                           //---<  second-smallest entry is now smallest  >---
 812                           TopSizeArray[prev_j].index = tsbStopper;
 813                           currMin    = TopSizeArray[prev_j].len;
 814                           currMin_ix = prev_j;
 815                           //---<  smallest entry gets overwritten  >---
 816                           memcpy((void*)&TopSizeArray[j], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 817                           TopSizeArray[i].start    = h;
 818                           TopSizeArray[i].len      = hb_len;
 819                           TopSizeArray[i].index    = j;
 820                           TopSizeArray[i].compiler = cType;
 821                           TopSizeArray[i].level    = comp_lvl;
 822                           TopSizeArray[i].type     = cbType;
 823                         }
 824                       } // insane
 825                     }
 826                     break;
 827                   }
 828                   prev_i = i;
 829                 }
 830                 if (insane) {
 831                   // Note: regular analysis could probably continue by resetting "insane" flag.
 832                   out->print_cr("Possible loop in TopSizeBlocks list detected. Analysis aborted.");
 833                   discard_TopSizeArray(out);
 834                 }
 835               }
 836             }
 837           }
 838           //----------------------------------------------
 839           //---<  END register block in TopSizeArray  >---
 840           //----------------------------------------------
 841         } else {
 842           nBlocks_zomb++;
 843         }
 844 
 845         if (ix_beg == ix_end) {
 846           StatArray[ix_beg].type = cbType;
 847           switch (cbType) {
 848             case nMethod_inuse:
 849               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 850               if (comp_lvl < CompLevel_full_optimization) {
 851                 nBlocks_t1++;
 852                 t1Space   += hb_bytelen;
 853                 StatArray[ix_beg].t1_count++;
 854                 StatArray[ix_beg].t1_space += (unsigned short)hb_len;
 855                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 856               } else {
 857                 nBlocks_t2++;
 858                 t2Space   += hb_bytelen;
 859                 StatArray[ix_beg].t2_count++;
 860                 StatArray[ix_beg].t2_space += (unsigned short)hb_len;
 861                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 862               }
 863               StatArray[ix_beg].level     = comp_lvl;
 864               StatArray[ix_beg].compiler  = cType;
 865               break;
 866             case nMethod_inconstruction: // let's count "in construction" nmethods here.
 867             case nMethod_alive:
 868               StatArray[ix_beg].tx_count++;
 869               StatArray[ix_beg].tx_space += (unsigned short)hb_len;
 870               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
 871               StatArray[ix_beg].level     = comp_lvl;
 872               StatArray[ix_beg].compiler  = cType;
 873               break;
 874             case nMethod_dead:
 875             case nMethod_unloaded:
 876               StatArray[ix_beg].dead_count++;
 877               StatArray[ix_beg].dead_space += (unsigned short)hb_len;
 878               break;
 879             default:
 880               // must be a stub, if it's not a dead or alive nMethod
 881               nBlocks_stub++;
 882               stubSpace   += hb_bytelen;
 883               StatArray[ix_beg].stub_count++;
 884               StatArray[ix_beg].stub_space += (unsigned short)hb_len;
 885               break;
 886           }
 887         } else {
 888           unsigned int beg_space = (unsigned int)(granule_size - ((char*)h - low_bound - ix_beg*granule_size));
 889           unsigned int end_space = (unsigned int)(hb_bytelen - beg_space - (ix_end-ix_beg-1)*granule_size);
 890           beg_space = beg_space>>log2_seg_size;  // store in units of _segment_size
 891           end_space = end_space>>log2_seg_size;  // store in units of _segment_size
 892           StatArray[ix_beg].type = cbType;
 893           StatArray[ix_end].type = cbType;
 894           switch (cbType) {
 895             case nMethod_inuse:
 896               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 897               if (comp_lvl < CompLevel_full_optimization) {
 898                 nBlocks_t1++;
 899                 t1Space   += hb_bytelen;
 900                 StatArray[ix_beg].t1_count++;
 901                 StatArray[ix_beg].t1_space += (unsigned short)beg_space;
 902                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 903 
 904                 StatArray[ix_end].t1_count++;
 905                 StatArray[ix_end].t1_space += (unsigned short)end_space;
 906                 StatArray[ix_end].t1_age    = StatArray[ix_end].t1_age < compile_id ? compile_id : StatArray[ix_end].t1_age;
 907               } else {
 908                 nBlocks_t2++;
 909                 t2Space   += hb_bytelen;
 910                 StatArray[ix_beg].t2_count++;
 911                 StatArray[ix_beg].t2_space += (unsigned short)beg_space;
 912                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 913 
 914                 StatArray[ix_end].t2_count++;
 915                 StatArray[ix_end].t2_space += (unsigned short)end_space;
 916                 StatArray[ix_end].t2_age    = StatArray[ix_end].t2_age < compile_id ? compile_id : StatArray[ix_end].t2_age;
 917               }
 918               StatArray[ix_beg].level     = comp_lvl;
 919               StatArray[ix_beg].compiler  = cType;
 920               StatArray[ix_end].level     = comp_lvl;
 921               StatArray[ix_end].compiler  = cType;
 922               break;
 923             case nMethod_inconstruction: // let's count "in construction" nmethods here.
 924             case nMethod_alive:
 925               StatArray[ix_beg].tx_count++;
 926               StatArray[ix_beg].tx_space += (unsigned short)beg_space;
 927               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
 928 
 929               StatArray[ix_end].tx_count++;
 930               StatArray[ix_end].tx_space += (unsigned short)end_space;
 931               StatArray[ix_end].tx_age    = StatArray[ix_end].tx_age < compile_id ? compile_id : StatArray[ix_end].tx_age;
 932 
 933               StatArray[ix_beg].level     = comp_lvl;
 934               StatArray[ix_beg].compiler  = cType;
 935               StatArray[ix_end].level     = comp_lvl;
 936               StatArray[ix_end].compiler  = cType;
 937               break;
 938             case nMethod_dead:
 939             case nMethod_unloaded:
 940               StatArray[ix_beg].dead_count++;
 941               StatArray[ix_beg].dead_space += (unsigned short)beg_space;
 942               StatArray[ix_end].dead_count++;
 943               StatArray[ix_end].dead_space += (unsigned short)end_space;
 944               break;
 945             default:
 946               // must be a stub, if it's not a dead or alive nMethod
 947               nBlocks_stub++;
 948               stubSpace   += hb_bytelen;
 949               StatArray[ix_beg].stub_count++;
 950               StatArray[ix_beg].stub_space += (unsigned short)beg_space;
 951               StatArray[ix_end].stub_count++;
 952               StatArray[ix_end].stub_space += (unsigned short)end_space;
 953               break;
 954           }
 955           for (unsigned int ix = ix_beg+1; ix < ix_end; ix++) {
 956             StatArray[ix].type = cbType;
 957             switch (cbType) {
 958               case nMethod_inuse:
 959                 if (comp_lvl < CompLevel_full_optimization) {
 960                   StatArray[ix].t1_count++;
 961                   StatArray[ix].t1_space += (unsigned short)(granule_size>>log2_seg_size);
 962                   StatArray[ix].t1_age    = StatArray[ix].t1_age < compile_id ? compile_id : StatArray[ix].t1_age;
 963                 } else {
 964                   StatArray[ix].t2_count++;
 965                   StatArray[ix].t2_space += (unsigned short)(granule_size>>log2_seg_size);
 966                   StatArray[ix].t2_age    = StatArray[ix].t2_age < compile_id ? compile_id : StatArray[ix].t2_age;
 967                 }
 968                 StatArray[ix].level     = comp_lvl;
 969                 StatArray[ix].compiler  = cType;
 970                 break;
 971               case nMethod_inconstruction: // let's count "in construction" nmethods here.
 972               case nMethod_alive:
 973                 StatArray[ix].tx_count++;
 974                 StatArray[ix].tx_space += (unsigned short)(granule_size>>log2_seg_size);
 975                 StatArray[ix].tx_age    = StatArray[ix].tx_age < compile_id ? compile_id : StatArray[ix].tx_age;
 976                 StatArray[ix].level     = comp_lvl;
 977                 StatArray[ix].compiler  = cType;
 978                 break;
 979               case nMethod_dead:
 980               case nMethod_unloaded:
 981                 StatArray[ix].dead_count++;
 982                 StatArray[ix].dead_space += (unsigned short)(granule_size>>log2_seg_size);
 983                 break;
 984               default:
 985                 // must be a stub, if it's not a dead or alive nMethod
 986                 StatArray[ix].stub_count++;
 987                 StatArray[ix].stub_space += (unsigned short)(granule_size>>log2_seg_size);
 988                 break;
 989             }
 990           }
 991         }
 992       }
 993     }
 994     done = true;
 995 
 996     if (!insane) {
 997       // There is a risk for this block (because it contains many print statements) to get
 998       // interspersed with print data from other threads. We take this risk intentionally.
 999       // Getting stalled waiting for tty_lock while holding the CodeCache_lock is not desirable.
1000       printBox(ast, '-', "Global CodeHeap statistics for segment ", heapName);
1001       ast->print_cr("freeSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_free     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", freeSpace/(size_t)K,     nBlocks_free,     (100.0*freeSpace)/size,     (100.0*freeSpace)/res_size);
1002       ast->print_cr("usedSpace        = " SIZE_FORMAT_W(8) "k, nBlocks_used     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", usedSpace/(size_t)K,     nBlocks_used,     (100.0*usedSpace)/size,     (100.0*usedSpace)/res_size);
1003       ast->print_cr("  Tier1 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t1       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t1Space/(size_t)K,       nBlocks_t1,       (100.0*t1Space)/size,       (100.0*t1Space)/res_size);
1004       ast->print_cr("  Tier2 Space    = " SIZE_FORMAT_W(8) "k, nBlocks_t2       = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", t2Space/(size_t)K,       nBlocks_t2,       (100.0*t2Space)/size,       (100.0*t2Space)/res_size);
1005       ast->print_cr("  Alive Space    = " SIZE_FORMAT_W(8) "k, nBlocks_alive    = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", aliveSpace/(size_t)K,    nBlocks_alive,    (100.0*aliveSpace)/size,    (100.0*aliveSpace)/res_size);
1006       ast->print_cr("    disconnected = " SIZE_FORMAT_W(8) "k, nBlocks_disconn  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", disconnSpace/(size_t)K,  nBlocks_disconn,  (100.0*disconnSpace)/size,  (100.0*disconnSpace)/res_size);
1007       ast->print_cr("    not entrant  = " SIZE_FORMAT_W(8) "k, nBlocks_notentr  = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", notentrSpace/(size_t)K,  nBlocks_notentr,  (100.0*notentrSpace)/size,  (100.0*notentrSpace)/res_size);
1008       ast->print_cr("  inconstrSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_inconstr = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", inconstrSpace/(size_t)K, nBlocks_inconstr, (100.0*inconstrSpace)/size, (100.0*inconstrSpace)/res_size);
1009       ast->print_cr("  unloadedSpace  = " SIZE_FORMAT_W(8) "k, nBlocks_unloaded = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", unloadedSpace/(size_t)K, nBlocks_unloaded, (100.0*unloadedSpace)/size, (100.0*unloadedSpace)/res_size);
1010       ast->print_cr("  deadSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_dead     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", deadSpace/(size_t)K,     nBlocks_dead,     (100.0*deadSpace)/size,     (100.0*deadSpace)/res_size);
1011       ast->print_cr("  stubSpace      = " SIZE_FORMAT_W(8) "k, nBlocks_stub     = %6d, %10.3f%% of capacity, %10.3f%% of max_capacity", stubSpace/(size_t)K,     nBlocks_stub,     (100.0*stubSpace)/size,     (100.0*stubSpace)/res_size);
1012       ast->print_cr("ZombieBlocks     = %8d. These are HeapBlocks which could not be identified as CodeBlobs.", nBlocks_zomb);
1013       ast->cr();
1014       ast->print_cr("Segment start          = " INTPTR_FORMAT ", used space      = " SIZE_FORMAT_W(8)"k", p2i(low_bound), size/K);
1015       ast->print_cr("Segment end (used)     = " INTPTR_FORMAT ", remaining space = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + size, (res_size - size)/K);
1016       ast->print_cr("Segment end (reserved) = " INTPTR_FORMAT ", reserved space  = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + res_size, res_size/K);
1017       ast->cr();
1018       ast->print_cr("latest allocated compilation id = %d", latest_compilation_id);
1019       ast->print_cr("highest observed compilation id = %d", highest_compilation_id);
1020       ast->print_cr("Building TopSizeList iterations = %ld", total_iterations);
1021       ast->cr();
1022 
1023       int             reset_val = NMethodSweeper::hotness_counter_reset_val();
1024       double reverse_free_ratio = (res_size > size) ? (double)res_size/(double)(res_size-size) : (double)res_size;
1025       printBox(ast, '-', "Method hotness information at time of this analysis", NULL);
1026       ast->print_cr("Highest possible method temperature:          %12d", reset_val);
1027       ast->print_cr("Threshold for method to be considered 'cold': %12.3f", -reset_val + reverse_free_ratio * NmethodSweepActivity);
1028       if (n_methods > 0) {
1029         avgTemp = hotnessAccumulator/n_methods;
1030         ast->print_cr("min. hotness = %6d", minTemp);
1031         ast->print_cr("avg. hotness = %6d", avgTemp);
1032         ast->print_cr("max. hotness = %6d", maxTemp);
1033       } else {
1034         avgTemp = 0;
1035         ast->print_cr("No hotness data available");
1036       }
1037       STRINGSTREAM_FLUSH("\n")
1038 
1039       // This loop is intentionally printing directly to "out".
1040       // It should not print anything, anyway.
1041       out->print("Verifying collected data...");
1042       size_t granule_segs = granule_size>>log2_seg_size;
1043       for (unsigned int ix = 0; ix < granules; ix++) {
1044         if (StatArray[ix].t1_count   > granule_segs) {
1045           out->print_cr("t1_count[%d]   = %d", ix, StatArray[ix].t1_count);
1046         }
1047         if (StatArray[ix].t2_count   > granule_segs) {
1048           out->print_cr("t2_count[%d]   = %d", ix, StatArray[ix].t2_count);
1049         }
1050         if (StatArray[ix].tx_count   > granule_segs) {
1051           out->print_cr("tx_count[%d]   = %d", ix, StatArray[ix].tx_count);
1052         }
1053         if (StatArray[ix].stub_count > granule_segs) {
1054           out->print_cr("stub_count[%d] = %d", ix, StatArray[ix].stub_count);
1055         }
1056         if (StatArray[ix].dead_count > granule_segs) {
1057           out->print_cr("dead_count[%d] = %d", ix, StatArray[ix].dead_count);
1058         }
1059         if (StatArray[ix].t1_space   > granule_segs) {
1060           out->print_cr("t1_space[%d]   = %d", ix, StatArray[ix].t1_space);
1061         }
1062         if (StatArray[ix].t2_space   > granule_segs) {
1063           out->print_cr("t2_space[%d]   = %d", ix, StatArray[ix].t2_space);
1064         }
1065         if (StatArray[ix].tx_space   > granule_segs) {
1066           out->print_cr("tx_space[%d]   = %d", ix, StatArray[ix].tx_space);
1067         }
1068         if (StatArray[ix].stub_space > granule_segs) {
1069           out->print_cr("stub_space[%d] = %d", ix, StatArray[ix].stub_space);
1070         }
1071         if (StatArray[ix].dead_space > granule_segs) {
1072           out->print_cr("dead_space[%d] = %d", ix, StatArray[ix].dead_space);
1073         }
1074         //   this cast is awful! I need it because NT/Intel reports a signed/unsigned mismatch.
1075         if ((size_t)(StatArray[ix].t1_count+StatArray[ix].t2_count+StatArray[ix].tx_count+StatArray[ix].stub_count+StatArray[ix].dead_count) > granule_segs) {
1076           out->print_cr("t1_count[%d] = %d, t2_count[%d] = %d, tx_count[%d] = %d, stub_count[%d] = %d", ix, StatArray[ix].t1_count, ix, StatArray[ix].t2_count, ix, StatArray[ix].tx_count, ix, StatArray[ix].stub_count);
1077         }
1078         if ((size_t)(StatArray[ix].t1_space+StatArray[ix].t2_space+StatArray[ix].tx_space+StatArray[ix].stub_space+StatArray[ix].dead_space) > granule_segs) {
1079           out->print_cr("t1_space[%d] = %d, t2_space[%d] = %d, tx_space[%d] = %d, stub_space[%d] = %d", ix, StatArray[ix].t1_space, ix, StatArray[ix].t2_space, ix, StatArray[ix].tx_space, ix, StatArray[ix].stub_space);
1080         }
1081       }
1082 
1083       // This loop is intentionally printing directly to "out".
1084       // It should not print anything, anyway.
1085       if (used_topSizeBlocks > 0) {
1086         unsigned int j = 0;
1087         if (TopSizeArray[0].len != currMax) {
1088           out->print_cr("currMax(%d) differs from TopSizeArray[0].len(%d)", currMax, TopSizeArray[0].len);
1089         }
1090         for (unsigned int i = 0; (TopSizeArray[i].index != tsbStopper) && (j++ < alloc_topSizeBlocks); i = TopSizeArray[i].index) {
1091           if (TopSizeArray[i].len < TopSizeArray[TopSizeArray[i].index].len) {
1092             out->print_cr("sort error at index %d: %d !>= %d", i, TopSizeArray[i].len, TopSizeArray[TopSizeArray[i].index].len);
1093           }
1094         }
1095         if (j >= alloc_topSizeBlocks) {
1096           out->print_cr("Possible loop in TopSizeArray chaining!\n  allocBlocks = %d, usedBlocks = %d", alloc_topSizeBlocks, used_topSizeBlocks);
1097           for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1098             out->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1099           }
1100         }
1101       }
1102       out->print_cr("...done\n\n");
1103     } else {
1104       // insane heap state detected. Analysis data incomplete. Just throw it away.
1105       discard_StatArray(out);
1106       discard_TopSizeArray(out);
1107     }
1108   }
1109 
1110 
1111   done        = false;
1112   while (!done && (nBlocks_free > 0)) {
1113 
1114     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (free blocks) for segment ", heapName);
1115     ast->print_cr("   The aggregate step collects information about all free blocks in CodeHeap.\n"
1116                   "   Subsequent print functions create their output based on this snapshot.\n");
1117     ast->print_cr("   Free space in %s is distributed over %d free blocks.", heapName, nBlocks_free);
1118     ast->print_cr("   Each free block takes " SIZE_FORMAT " bytes of C heap for statistics data, that is " SIZE_FORMAT "K in total.", sizeof(FreeBlk), (sizeof(FreeBlk)*nBlocks_free)/K);
1119     STRINGSTREAM_FLUSH("\n")
1120 
1121     //----------------------------------------
1122     //--  Prepare the FreeArray of FreeBlks --
1123     //----------------------------------------
1124 
1125     //---< discard old array if size does not match  >---
1126     if (nBlocks_free != alloc_freeBlocks) {
1127       discard_FreeArray(out);
1128     }
1129 
1130     prepare_FreeArray(out, nBlocks_free, heapName);
1131     if (FreeArray == NULL) {
1132       done = true;
1133       continue;
1134     }
1135 
1136     //----------------------------------------
1137     //--  Collect all FreeBlks in FreeArray --
1138     //----------------------------------------
1139 
1140     unsigned int ix = 0;
1141     FreeBlock* cur  = heap->freelist();
1142 
1143     while (cur != NULL) {
1144       if (ix < alloc_freeBlocks) { // don't index out of bounds if _freelist has more blocks than anticipated
1145         FreeArray[ix].start = cur;
1146         FreeArray[ix].len   = (unsigned int)(cur->length()<<log2_seg_size);
1147         FreeArray[ix].index = ix;
1148       }
1149       cur  = cur->link();
1150       ix++;
1151     }
1152     if (ix != alloc_freeBlocks) {
1153       ast->print_cr("Free block count mismatch. Expected %d free blocks, but found %d.", alloc_freeBlocks, ix);
1154       ast->print_cr("I will update the counter and retry data collection");
1155       STRINGSTREAM_FLUSH("\n")
1156       nBlocks_free = ix;
1157       continue;
1158     }
1159     done = true;
1160   }
1161 
1162   if (!done || (nBlocks_free == 0)) {
1163     if (nBlocks_free == 0) {
1164       printBox(ast, '-', "no free blocks found in ", heapName);
1165     } else if (!done) {
1166       ast->print_cr("Free block count mismatch could not be resolved.");
1167       ast->print_cr("Try to run \"aggregate\" function to update counters");
1168     }
1169     STRINGSTREAM_FLUSH("")
1170 
1171     //---< discard old array and update global values  >---
1172     discard_FreeArray(out);
1173     set_HeapStatGlobals(out, heapName);
1174     return;
1175   }
1176 
1177   //---<  calculate and fill remaining fields  >---
1178   if (FreeArray != NULL) {
1179     // This loop is intentionally printing directly to "out".
1180     // It should not print anything, anyway.
1181     for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1182       size_t lenSum = 0;
1183       FreeArray[ix].gap = (unsigned int)((address)FreeArray[ix+1].start - ((address)FreeArray[ix].start + FreeArray[ix].len));
1184       for (HeapBlock *h = heap->next_block(FreeArray[ix].start); (h != NULL) && (h != FreeArray[ix+1].start); h = heap->next_block(h)) {
1185         CodeBlob *cb  = (CodeBlob*)(heap->find_start(h));
1186         if ((cb != NULL) && !cb->is_nmethod()) {
1187           FreeArray[ix].stubs_in_gap = true;
1188         }
1189         FreeArray[ix].n_gapBlocks++;
1190         lenSum += h->length()<<log2_seg_size;
1191         if (((address)h < ((address)FreeArray[ix].start+FreeArray[ix].len)) || (h >= FreeArray[ix+1].start)) {
1192           out->print_cr("unsorted occupied CodeHeap block found @ %p, gap interval [%p, %p)", h, (address)FreeArray[ix].start+FreeArray[ix].len, FreeArray[ix+1].start);
1193         }
1194       }
1195       if (lenSum != FreeArray[ix].gap) {
1196         out->print_cr("Length mismatch for gap between FreeBlk[%d] and FreeBlk[%d]. Calculated: %d, accumulated: %d.", ix, ix+1, FreeArray[ix].gap, (unsigned int)lenSum);
1197       }
1198     }
1199   }
1200   set_HeapStatGlobals(out, heapName);
1201 
1202   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   C O M P L E T E   for segment ", heapName);
1203   STRINGSTREAM_FLUSH("\n")
1204 }
1205 
1206 
1207 void CodeHeapState::print_usedSpace(outputStream* out, CodeHeap* heap) {
1208   if (!initialization_complete) {
1209     return;
1210   }
1211 
1212   const char* heapName   = get_heapName(heap);
1213   get_HeapStatGlobals(out, heapName);
1214 
1215   if ((StatArray == NULL) || (TopSizeArray == NULL) || (used_topSizeBlocks == 0)) {
1216     return;
1217   }
1218   STRINGSTREAM_DECL(ast, out)
1219 
1220   {
1221     printBox(ast, '=', "U S E D   S P A C E   S T A T I S T I C S   for ", heapName);
1222     ast->print_cr("Note: The Top%d list of the largest used blocks associates method names\n"
1223                   "      and other identifying information with the block size data.\n"
1224                   "\n"
1225                   "      Method names are dynamically retrieved from the code cache at print time.\n"
1226                   "      Due to the living nature of the code cache and because the CodeCache_lock\n"
1227                   "      is not continuously held, the displayed name might be wrong or no name\n"
1228                   "      might be found at all. The likelihood for that to happen increases\n"
1229                   "      over time passed between analysis and print step.\n", used_topSizeBlocks);
1230     STRINGSTREAM_FLUSH_LOCKED("\n")
1231   }
1232 
1233   //----------------------------
1234   //--  Print Top Used Blocks --
1235   //----------------------------
1236   {
1237     char*     low_bound = heap->low_boundary();
1238     bool      have_CodeCache_lock = CodeCache_lock->owned_by_self();
1239 
1240     printBox(ast, '-', "Largest Used Blocks in ", heapName);
1241     print_blobType_legend(ast);
1242 
1243     ast->fill_to(51);
1244     ast->print("%4s", "blob");
1245     ast->fill_to(56);
1246     ast->print("%9s", "compiler");
1247     ast->fill_to(66);
1248     ast->print_cr("%6s", "method");
1249     ast->print_cr("%18s %13s %17s %4s %9s  %5s %s",      "Addr(module)      ", "offset", "size", "type", " type lvl", " temp", "Name");
1250     STRINGSTREAM_FLUSH_LOCKED("")
1251 
1252     //---<  print Top Ten Used Blocks  >---
1253     if (used_topSizeBlocks > 0) {
1254       unsigned int printed_topSizeBlocks = 0;
1255       for (unsigned int i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
1256         printed_topSizeBlocks++;

1257         nmethod*           nm = NULL;
1258         const char* blob_name = "unnamed blob or blob name unavailable";
1259         // heap->find_start() is safe. Only works on _segmap.
1260         // Returns NULL or void*. Returned CodeBlob may be uninitialized.
1261         HeapBlock* heapBlock = TopSizeArray[i].start;
1262         CodeBlob*  this_blob = (CodeBlob*)(heap->find_start(heapBlock));
1263         bool    blob_is_safe = blob_access_is_safe(this_blob, NULL);
1264         if (blob_is_safe) {
1265           //---<  access these fields only if we own the CodeCache_lock  >---
1266           if (have_CodeCache_lock) {
1267             blob_name = this_blob->name();
1268             nm        = this_blob->as_nmethod_or_null();
1269           }
1270           //---<  blob address  >---
1271           ast->print(INTPTR_FORMAT, p2i(this_blob));
1272           ast->fill_to(19);
1273           //---<  blob offset from CodeHeap begin  >---
1274           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
1275           ast->fill_to(33);
1276         } else {
1277           //---<  block address  >---
1278           ast->print(INTPTR_FORMAT, p2i(TopSizeArray[i].start));
1279           ast->fill_to(19);
1280           //---<  block offset from CodeHeap begin  >---
1281           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)TopSizeArray[i].start-low_bound));
1282           ast->fill_to(33);
1283         }
1284 

1285         //---<  print size, name, and signature (for nMethods)  >---
1286         // access nmethod and Method fields only if we own the CodeCache_lock.
1287         // This fact is implicitly transported via nm != NULL.
1288         if (CompiledMethod::nmethod_access_is_safe(nm)) {
1289           ResourceMark rm;
1290           Method* method = nm->method();
1291           if (nm->is_in_use()) {
1292             blob_name = method->name_and_sig_as_C_string();
1293           }
1294           if (nm->is_not_entrant()) {
1295             blob_name = method->name_and_sig_as_C_string();
1296           }
1297           //---<  nMethod size in hex  >---
1298           unsigned int total_size = nm->total_size();
1299           ast->print(PTR32_FORMAT, total_size);
1300           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
1301           ast->fill_to(51);
1302           ast->print("  %c", blobTypeChar[TopSizeArray[i].type]);
1303           //---<  compiler information  >---
1304           ast->fill_to(56);
1305           ast->print("%5s %3d", compTypeName[TopSizeArray[i].compiler], TopSizeArray[i].level);
1306           //---<  method temperature  >---
1307           ast->fill_to(67);
1308           ast->print("%5d", nm->hotness_counter());
1309           //---<  name and signature  >---
1310           ast->fill_to(67+6);
1311           if (nm->is_not_installed()) {
1312             ast->print(" not (yet) installed method ");
1313           }
1314           if (nm->is_zombie()) {
1315             ast->print(" zombie method ");
1316           }
1317           ast->print("%s", blob_name);
1318         } else {
1319           //---<  block size in hex  >---
1320           ast->print(PTR32_FORMAT, (unsigned int)(TopSizeArray[i].len<<log2_seg_size));
1321           ast->print("(" SIZE_FORMAT_W(4) "K)", (TopSizeArray[i].len<<log2_seg_size)/K);
1322           //---<  no compiler information  >---
1323           ast->fill_to(56);
1324           //---<  name and signature  >---
1325           ast->fill_to(67+6);
1326           ast->print("%s", blob_name);
1327         }
1328         STRINGSTREAM_FLUSH_LOCKED("\n")
1329       }
1330       if (used_topSizeBlocks != printed_topSizeBlocks) {
1331         ast->print_cr("used blocks: %d, printed blocks: %d", used_topSizeBlocks, printed_topSizeBlocks);
1332         STRINGSTREAM_FLUSH("")
1333         for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1334           ast->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1335           STRINGSTREAM_FLUSH("")
1336         }
1337       }
1338       STRINGSTREAM_FLUSH_LOCKED("\n\n")
1339     }
1340   }
1341 
1342   //-----------------------------
1343   //--  Print Usage Histogram  --
1344   //-----------------------------
1345 
1346   if (SizeDistributionArray != NULL) {
1347     unsigned long total_count = 0;
1348     unsigned long total_size  = 0;
1349     const unsigned long pctFactor = 200;
1350 
1351     for (unsigned int i = 0; i < nSizeDistElements; i++) {
1352       total_count += SizeDistributionArray[i].count;
1353       total_size  += SizeDistributionArray[i].lenSum;
1354     }
1355 
1356     if ((total_count > 0) && (total_size > 0)) {
1357       printBox(ast, '-', "Block count histogram for ", heapName);
1358       ast->print_cr("Note: The histogram indicates how many blocks (as a percentage\n"
1359                     "      of all blocks) have a size in the given range.\n"
1360                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1361       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1362       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1363       STRINGSTREAM_FLUSH_LOCKED("")
1364 
1365       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1366       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1367         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1368           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1369                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1370                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1371                     );
1372         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1373           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1374                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1375                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1376                     );
1377         } else {
1378           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1379                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1380                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1381                     );
1382         }
1383         ast->print(" %8d | %8d |",
1384                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1385                    SizeDistributionArray[i].count);
1386 
1387         unsigned int percent = pctFactor*SizeDistributionArray[i].count/total_count;
1388         for (unsigned int j = 1; j <= percent; j++) {
1389           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1390         }
1391         ast->cr();
1392       }
1393       ast->print_cr("----------------------------+----------+\n\n");
1394       STRINGSTREAM_FLUSH_LOCKED("\n")
1395 
1396       printBox(ast, '-', "Contribution per size range to total size for ", heapName);
1397       ast->print_cr("Note: The histogram indicates how much space (as a percentage of all\n"
1398                     "      occupied space) is used by the blocks in the given size range.\n"
1399                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1400       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1401       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1402       STRINGSTREAM_FLUSH_LOCKED("")
1403 
1404       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1405       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1406         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1407           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1408                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1409                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1410                     );
1411         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1412           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1413                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1414                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1415                     );
1416         } else {
1417           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1418                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1419                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1420                     );
1421         }
1422         ast->print(" %8d | %8d |",
1423                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1424                    SizeDistributionArray[i].count);
1425 
1426         unsigned int percent = pctFactor*(unsigned long)SizeDistributionArray[i].lenSum/total_size;
1427         for (unsigned int j = 1; j <= percent; j++) {
1428           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1429         }
1430         ast->cr();
1431       }
1432       ast->print_cr("----------------------------+----------+");
1433       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1434     }
1435   }
1436 }
1437 
1438 
1439 void CodeHeapState::print_freeSpace(outputStream* out, CodeHeap* heap) {
1440   if (!initialization_complete) {
1441     return;
1442   }
1443 
1444   const char* heapName   = get_heapName(heap);
1445   get_HeapStatGlobals(out, heapName);
1446 
1447   if ((StatArray == NULL) || (FreeArray == NULL) || (alloc_granules == 0)) {
1448     return;
1449   }
1450   STRINGSTREAM_DECL(ast, out)
1451 
1452   {
1453     printBox(ast, '=', "F R E E   S P A C E   S T A T I S T I C S   for ", heapName);
1454     ast->print_cr("Note: in this context, a gap is the occupied space between two free blocks.\n"
1455                   "      Those gaps are of interest if there is a chance that they become\n"
1456                   "      unoccupied, e.g. by class unloading. Then, the two adjacent free\n"
1457                   "      blocks, together with the now unoccupied space, form a new, large\n"
1458                   "      free block.");
1459     STRINGSTREAM_FLUSH_LOCKED("\n")
1460   }
1461 
1462   {
1463     printBox(ast, '-', "List of all Free Blocks in ", heapName);
1464     STRINGSTREAM_FLUSH_LOCKED("")
1465 
1466     unsigned int ix = 0;
1467     for (ix = 0; ix < alloc_freeBlocks-1; ix++) {
1468       ast->print(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT ",", p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1469       ast->fill_to(38);
1470       ast->print("Gap[%4d..%4d]: " HEX32_FORMAT " bytes,", ix, ix+1, FreeArray[ix].gap);
1471       ast->fill_to(71);
1472       ast->print("block count: %6d", FreeArray[ix].n_gapBlocks);
1473       if (FreeArray[ix].stubs_in_gap) {
1474         ast->print(" !! permanent gap, contains stubs and/or blobs !!");
1475       }
1476       STRINGSTREAM_FLUSH_LOCKED("\n")
1477     }
1478     ast->print_cr(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT, p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1479     STRINGSTREAM_FLUSH_LOCKED("\n\n")
1480   }
1481 
1482 
1483   //-----------------------------------------
1484   //--  Find and Print Top Ten Free Blocks --
1485   //-----------------------------------------
1486 
1487   //---<  find Top Ten Free Blocks  >---
1488   const unsigned int nTop = 10;
1489   unsigned int  currMax10 = 0;
1490   struct FreeBlk* FreeTopTen[nTop];
1491   memset(FreeTopTen, 0, sizeof(FreeTopTen));
1492 
1493   for (unsigned int ix = 0; ix < alloc_freeBlocks; ix++) {
1494     if (FreeArray[ix].len > currMax10) {  // larger than the ten largest found so far
1495       unsigned int currSize = FreeArray[ix].len;
1496 
1497       unsigned int iy;
1498       for (iy = 0; iy < nTop && FreeTopTen[iy] != NULL; iy++) {
1499         if (FreeTopTen[iy]->len < currSize) {
1500           for (unsigned int iz = nTop-1; iz > iy; iz--) { // make room to insert new free block
1501             FreeTopTen[iz] = FreeTopTen[iz-1];
1502           }
1503           FreeTopTen[iy] = &FreeArray[ix];        // insert new free block
1504           if (FreeTopTen[nTop-1] != NULL) {
1505             currMax10 = FreeTopTen[nTop-1]->len;
1506           }
1507           break; // done with this, check next free block
1508         }
1509       }
1510       if (iy >= nTop) {
1511         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1512                       currSize, currMax10);
1513         continue;
1514       }
1515       if (FreeTopTen[iy] == NULL) {
1516         FreeTopTen[iy] = &FreeArray[ix];
1517         if (iy == (nTop-1)) {
1518           currMax10 = currSize;
1519         }
1520       }
1521     }
1522   }
1523   STRINGSTREAM_FLUSH_LOCKED("")
1524 
1525   {
1526     printBox(ast, '-', "Top Ten Free Blocks in ", heapName);
1527 
1528     //---<  print Top Ten Free Blocks  >---
1529     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTen[iy] != NULL); iy++) {
1530       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTen[iy]->index, FreeTopTen[iy]->len);
1531       ast->fill_to(39);
1532       if (FreeTopTen[iy]->index == (alloc_freeBlocks-1)) {
1533         ast->print("last free block in list.");
1534       } else {
1535         ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTen[iy]->gap);
1536         ast->fill_to(63);
1537         ast->print("#blocks (in gap) %d", FreeTopTen[iy]->n_gapBlocks);
1538       }
1539       ast->cr();
1540     }
1541     STRINGSTREAM_FLUSH_LOCKED("\n\n")
1542   }
1543 
1544 
1545   //--------------------------------------------------------
1546   //--  Find and Print Top Ten Free-Occupied-Free Triples --
1547   //--------------------------------------------------------
1548 
1549   //---<  find and print Top Ten Triples (Free-Occupied-Free)  >---
1550   currMax10 = 0;
1551   struct FreeBlk  *FreeTopTenTriple[nTop];
1552   memset(FreeTopTenTriple, 0, sizeof(FreeTopTenTriple));
1553 
1554   for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1555     // If there are stubs in the gap, this gap will never become completely free.
1556     // The triple will thus never merge to one free block.
1557     unsigned int lenTriple  = FreeArray[ix].len + (FreeArray[ix].stubs_in_gap ? 0 : FreeArray[ix].gap + FreeArray[ix+1].len);
1558     FreeArray[ix].len = lenTriple;
1559     if (lenTriple > currMax10) {  // larger than the ten largest found so far
1560 
1561       unsigned int iy;
1562       for (iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1563         if (FreeTopTenTriple[iy]->len < lenTriple) {
1564           for (unsigned int iz = nTop-1; iz > iy; iz--) {
1565             FreeTopTenTriple[iz] = FreeTopTenTriple[iz-1];
1566           }
1567           FreeTopTenTriple[iy] = &FreeArray[ix];
1568           if (FreeTopTenTriple[nTop-1] != NULL) {
1569             currMax10 = FreeTopTenTriple[nTop-1]->len;
1570           }
1571           break;
1572         }
1573       }
1574       if (iy == nTop) {
1575         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1576                       lenTriple, currMax10);
1577         continue;
1578       }
1579       if (FreeTopTenTriple[iy] == NULL) {
1580         FreeTopTenTriple[iy] = &FreeArray[ix];
1581         if (iy == (nTop-1)) {
1582           currMax10 = lenTriple;
1583         }
1584       }
1585     }
1586   }
1587   STRINGSTREAM_FLUSH_LOCKED("")
1588 
1589   {
1590     printBox(ast, '-', "Top Ten Free-Occupied-Free Triples in ", heapName);
1591     ast->print_cr("  Use this information to judge how likely it is that a large(r) free block\n"
1592                   "  might get created by code cache sweeping.\n"
1593                   "  If all the occupied blocks can be swept, the three free blocks will be\n"
1594                   "  merged into one (much larger) free block. That would reduce free space\n"
1595                   "  fragmentation.\n");
1596 
1597     //---<  print Top Ten Free-Occupied-Free Triples  >---
1598     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1599       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTenTriple[iy]->index, FreeTopTenTriple[iy]->len);
1600       ast->fill_to(39);
1601       ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTenTriple[iy]->gap);
1602       ast->fill_to(63);
1603       ast->print("#blocks (in gap) %d", FreeTopTenTriple[iy]->n_gapBlocks);
1604       ast->cr();
1605     }
1606     STRINGSTREAM_FLUSH_LOCKED("\n\n")
1607   }
1608 }
1609 
1610 
1611 void CodeHeapState::print_count(outputStream* out, CodeHeap* heap) {
1612   if (!initialization_complete) {
1613     return;
1614   }
1615 
1616   const char* heapName   = get_heapName(heap);
1617   get_HeapStatGlobals(out, heapName);
1618 
1619   if ((StatArray == NULL) || (alloc_granules == 0)) {
1620     return;
1621   }
1622   STRINGSTREAM_DECL(ast, out)
1623 
1624   unsigned int granules_per_line = 32;
1625   char*        low_bound         = heap->low_boundary();
1626 
1627   {
1628     printBox(ast, '=', "B L O C K   C O U N T S   for ", heapName);
1629     ast->print_cr("  Each granule contains an individual number of heap blocks. Large blocks\n"
1630                   "  may span multiple granules and are counted for each granule they touch.\n");
1631     if (segment_granules) {
1632       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1633                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1634                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1635                     "  Occupied granules show their BlobType character, see legend.\n");
1636       print_blobType_legend(ast);
1637     }
1638     STRINGSTREAM_FLUSH_LOCKED("")
1639   }
1640 
1641   {
1642     if (segment_granules) {
1643       printBox(ast, '-', "Total (all types) count for granule size == segment size", NULL);
1644       STRINGSTREAM_FLUSH_LOCKED("")
1645 
1646       granules_per_line = 128;
1647       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1648         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1649         print_blobType_single(ast, StatArray[ix].type);
1650       }
1651     } else {
1652       printBox(ast, '-', "Total (all tiers) count, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1653       STRINGSTREAM_FLUSH_LOCKED("")
1654 
1655       granules_per_line = 128;
1656       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1657         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1658         unsigned int count = StatArray[ix].t1_count   + StatArray[ix].t2_count   + StatArray[ix].tx_count
1659                            + StatArray[ix].stub_count + StatArray[ix].dead_count;
1660         print_count_single(ast, count);
1661       }
1662     }
1663     STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1664   }
1665 
1666   {
1667     if (nBlocks_t1 > 0) {
1668       printBox(ast, '-', "Tier1 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1669       STRINGSTREAM_FLUSH_LOCKED("")
1670 
1671       granules_per_line = 128;
1672       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1673         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1674         if (segment_granules && StatArray[ix].t1_count > 0) {
1675           print_blobType_single(ast, StatArray[ix].type);
1676         } else {
1677           print_count_single(ast, StatArray[ix].t1_count);
1678         }
1679       }
1680       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1681     } else {
1682       ast->print("No Tier1 nMethods found in CodeHeap.");
1683       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1684     }
1685   }
1686 
1687   {
1688     if (nBlocks_t2 > 0) {
1689       printBox(ast, '-', "Tier2 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1690       STRINGSTREAM_FLUSH_LOCKED("")
1691 
1692       granules_per_line = 128;
1693       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1694         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1695         if (segment_granules && StatArray[ix].t2_count > 0) {
1696           print_blobType_single(ast, StatArray[ix].type);
1697         } else {
1698           print_count_single(ast, StatArray[ix].t2_count);
1699         }
1700       }
1701       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1702     } else {
1703       ast->print("No Tier2 nMethods found in CodeHeap.");
1704       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1705     }
1706   }
1707 
1708   {
1709     if (nBlocks_alive > 0) {
1710       printBox(ast, '-', "not_used/not_entrant/not_installed nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1711       STRINGSTREAM_FLUSH_LOCKED("")
1712 
1713       granules_per_line = 128;
1714       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1715         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1716         if (segment_granules && StatArray[ix].tx_count > 0) {
1717           print_blobType_single(ast, StatArray[ix].type);
1718         } else {
1719           print_count_single(ast, StatArray[ix].tx_count);
1720         }
1721       }
1722       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1723     } else {
1724       ast->print("No not_used/not_entrant nMethods found in CodeHeap.");
1725       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1726     }
1727   }
1728 
1729   {
1730     if (nBlocks_stub > 0) {
1731       printBox(ast, '-', "Stub & Blob count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1732       STRINGSTREAM_FLUSH_LOCKED("")
1733 
1734       granules_per_line = 128;
1735       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1736         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1737         if (segment_granules && StatArray[ix].stub_count > 0) {
1738           print_blobType_single(ast, StatArray[ix].type);
1739         } else {
1740           print_count_single(ast, StatArray[ix].stub_count);
1741         }
1742       }
1743       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1744     } else {
1745       ast->print("No Stubs and Blobs found in CodeHeap.");
1746       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1747     }
1748   }
1749 
1750   {
1751     if (nBlocks_dead > 0) {
1752       printBox(ast, '-', "Dead nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1753       STRINGSTREAM_FLUSH_LOCKED("")
1754 
1755       granules_per_line = 128;
1756       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1757         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1758         if (segment_granules && StatArray[ix].dead_count > 0) {
1759           print_blobType_single(ast, StatArray[ix].type);
1760         } else {
1761           print_count_single(ast, StatArray[ix].dead_count);
1762         }
1763       }
1764       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1765     } else {
1766       ast->print("No dead nMethods found in CodeHeap.");
1767       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1768     }
1769   }
1770 
1771   {
1772     if (!segment_granules) { // Prevent totally redundant printouts
1773       printBox(ast, '-', "Count by tier (combined, no dead blocks): <#t1>:<#t2>:<#s>, 0x0..0xf. '*' indicates >= 16 blocks", NULL);
1774       STRINGSTREAM_FLUSH_LOCKED("")
1775 
1776       granules_per_line = 24;
1777       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1778         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1779 
1780         print_count_single(ast, StatArray[ix].t1_count);
1781         ast->print(":");
1782         print_count_single(ast, StatArray[ix].t2_count);
1783         ast->print(":");
1784         if (segment_granules && StatArray[ix].stub_count > 0) {
1785           print_blobType_single(ast, StatArray[ix].type);
1786         } else {
1787           print_count_single(ast, StatArray[ix].stub_count);
1788         }
1789         ast->print(" ");
1790       }
1791       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1792     }
1793   }
1794 }
1795 
1796 
1797 void CodeHeapState::print_space(outputStream* out, CodeHeap* heap) {
1798   if (!initialization_complete) {
1799     return;
1800   }
1801 
1802   const char* heapName   = get_heapName(heap);
1803   get_HeapStatGlobals(out, heapName);
1804 
1805   if ((StatArray == NULL) || (alloc_granules == 0)) {
1806     return;
1807   }
1808   STRINGSTREAM_DECL(ast, out)
1809 
1810   unsigned int granules_per_line = 32;
1811   char*        low_bound         = heap->low_boundary();
1812 
1813   {
1814     printBox(ast, '=', "S P A C E   U S A G E  &  F R A G M E N T A T I O N   for ", heapName);
1815     ast->print_cr("  The heap space covered by one granule is occupied to a various extend.\n"
1816                   "  The granule occupancy is displayed by one decimal digit per granule.\n");
1817     if (segment_granules) {
1818       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1819                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1820                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1821                     "  Occupied granules show their BlobType character, see legend.\n");
1822       print_blobType_legend(ast);
1823     } else {
1824       ast->print_cr("  These digits represent a fill percentage range (see legend).\n");
1825       print_space_legend(ast);
1826     }
1827     STRINGSTREAM_FLUSH_LOCKED("")
1828   }
1829 
1830   {
1831     if (segment_granules) {
1832       printBox(ast, '-', "Total (all types) space consumption for granule size == segment size", NULL);
1833       STRINGSTREAM_FLUSH_LOCKED("")
1834 
1835       granules_per_line = 128;
1836       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1837         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1838         print_blobType_single(ast, StatArray[ix].type);
1839       }
1840     } else {
1841       printBox(ast, '-', "Total (all types) space consumption. ' ' indicates empty, '*' indicates full.", NULL);
1842       STRINGSTREAM_FLUSH_LOCKED("")
1843 
1844       granules_per_line = 128;
1845       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1846         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1847         unsigned int space    = StatArray[ix].t1_space   + StatArray[ix].t2_space  + StatArray[ix].tx_space
1848                               + StatArray[ix].stub_space + StatArray[ix].dead_space;
1849         print_space_single(ast, space);
1850       }
1851     }
1852     STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1853   }
1854 
1855   {
1856     if (nBlocks_t1 > 0) {
1857       printBox(ast, '-', "Tier1 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1858       STRINGSTREAM_FLUSH_LOCKED("")
1859 
1860       granules_per_line = 128;
1861       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1862         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1863         if (segment_granules && StatArray[ix].t1_space > 0) {
1864           print_blobType_single(ast, StatArray[ix].type);
1865         } else {
1866           print_space_single(ast, StatArray[ix].t1_space);
1867         }
1868       }
1869       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1870     } else {
1871       ast->print("No Tier1 nMethods found in CodeHeap.");
1872       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1873     }
1874   }
1875 
1876   {
1877     if (nBlocks_t2 > 0) {
1878       printBox(ast, '-', "Tier2 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1879       STRINGSTREAM_FLUSH_LOCKED("")
1880 
1881       granules_per_line = 128;
1882       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1883         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1884         if (segment_granules && StatArray[ix].t2_space > 0) {
1885           print_blobType_single(ast, StatArray[ix].type);
1886         } else {
1887           print_space_single(ast, StatArray[ix].t2_space);
1888         }
1889       }
1890       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1891     } else {
1892       ast->print("No Tier2 nMethods found in CodeHeap.");
1893       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1894     }
1895   }
1896 
1897   {
1898     if (nBlocks_alive > 0) {
1899       printBox(ast, '-', "not_used/not_entrant/not_installed space consumption. ' ' indicates empty, '*' indicates full", NULL);
1900 
1901       granules_per_line = 128;
1902       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1903         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1904         if (segment_granules && StatArray[ix].tx_space > 0) {
1905           print_blobType_single(ast, StatArray[ix].type);
1906         } else {
1907           print_space_single(ast, StatArray[ix].tx_space);
1908         }
1909       }
1910       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1911     } else {
1912       ast->print("No Tier2 nMethods found in CodeHeap.");
1913       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1914     }
1915   }
1916 
1917   {
1918     if (nBlocks_stub > 0) {
1919       printBox(ast, '-', "Stub and Blob space consumption. ' ' indicates empty, '*' indicates full", NULL);
1920       STRINGSTREAM_FLUSH_LOCKED("")
1921 
1922       granules_per_line = 128;
1923       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1924         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1925         if (segment_granules && StatArray[ix].stub_space > 0) {
1926           print_blobType_single(ast, StatArray[ix].type);
1927         } else {
1928           print_space_single(ast, StatArray[ix].stub_space);
1929         }
1930       }
1931       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1932     } else {
1933       ast->print("No Stubs and Blobs found in CodeHeap.");
1934       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1935     }
1936   }
1937 
1938   {
1939     if (nBlocks_dead > 0) {
1940       printBox(ast, '-', "Dead space consumption. ' ' indicates empty, '*' indicates full", NULL);
1941       STRINGSTREAM_FLUSH_LOCKED("")
1942 
1943       granules_per_line = 128;
1944       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1945         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1946         print_space_single(ast, StatArray[ix].dead_space);
1947       }
1948       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1949     } else {
1950       ast->print("No dead nMethods found in CodeHeap.");
1951       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
1952     }
1953   }
1954 
1955   {
1956     if (!segment_granules) { // Prevent totally redundant printouts
1957       printBox(ast, '-', "Space consumption by tier (combined): <t1%>:<t2%>:<s%>. ' ' indicates empty, '*' indicates full", NULL);
1958       STRINGSTREAM_FLUSH_LOCKED("")
1959 
1960       granules_per_line = 24;
1961       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1962         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1963 
1964         if (segment_granules && StatArray[ix].t1_space > 0) {
1965           print_blobType_single(ast, StatArray[ix].type);
1966         } else {
1967           print_space_single(ast, StatArray[ix].t1_space);
1968         }
1969         ast->print(":");
1970         if (segment_granules && StatArray[ix].t2_space > 0) {
1971           print_blobType_single(ast, StatArray[ix].type);
1972         } else {
1973           print_space_single(ast, StatArray[ix].t2_space);
1974         }
1975         ast->print(":");
1976         if (segment_granules && StatArray[ix].stub_space > 0) {
1977           print_blobType_single(ast, StatArray[ix].type);
1978         } else {
1979           print_space_single(ast, StatArray[ix].stub_space);
1980         }
1981         ast->print(" ");
1982       }
1983       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
1984     }
1985   }
1986 }
1987 
1988 void CodeHeapState::print_age(outputStream* out, CodeHeap* heap) {
1989   if (!initialization_complete) {
1990     return;
1991   }
1992 
1993   const char* heapName   = get_heapName(heap);
1994   get_HeapStatGlobals(out, heapName);
1995 
1996   if ((StatArray == NULL) || (alloc_granules == 0)) {
1997     return;
1998   }
1999   STRINGSTREAM_DECL(ast, out)
2000 
2001   unsigned int granules_per_line = 32;
2002   char*        low_bound         = heap->low_boundary();
2003 
2004   {
2005     printBox(ast, '=', "M E T H O D   A G E   by CompileID for ", heapName);
2006     ast->print_cr("  The age of a compiled method in the CodeHeap is not available as a\n"
2007                   "  time stamp. Instead, a relative age is deducted from the method's compilation ID.\n"
2008                   "  Age information is available for tier1 and tier2 methods only. There is no\n"
2009                   "  age information for stubs and blobs, because they have no compilation ID assigned.\n"
2010                   "  Information for the youngest method (highest ID) in the granule is printed.\n"
2011                   "  Refer to the legend to learn how method age is mapped to the displayed digit.");
2012     print_age_legend(ast);
2013     STRINGSTREAM_FLUSH_LOCKED("")
2014   }
2015 
2016   {
2017     printBox(ast, '-', "Age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2018     STRINGSTREAM_FLUSH_LOCKED("")
2019 
2020     granules_per_line = 128;
2021     for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2022       print_line_delim(out, ast, low_bound, ix, granules_per_line);
2023       unsigned int age1      = StatArray[ix].t1_age;
2024       unsigned int age2      = StatArray[ix].t2_age;
2025       unsigned int agex      = StatArray[ix].tx_age;
2026       unsigned int age       = age1 > age2 ? age1 : age2;
2027       age       = age > agex ? age : agex;
2028       print_age_single(ast, age);
2029     }
2030     STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2031   }
2032 
2033   {
2034     if (nBlocks_t1 > 0) {
2035       printBox(ast, '-', "Tier1 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2036       STRINGSTREAM_FLUSH_LOCKED("")
2037 
2038       granules_per_line = 128;
2039       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2040         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2041         print_age_single(ast, StatArray[ix].t1_age);
2042       }
2043       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2044     } else {
2045       ast->print("No Tier1 nMethods found in CodeHeap.");
2046       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
2047     }
2048   }
2049 
2050   {
2051     if (nBlocks_t2 > 0) {
2052       printBox(ast, '-', "Tier2 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2053       STRINGSTREAM_FLUSH_LOCKED("")
2054 
2055       granules_per_line = 128;
2056       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2057         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2058         print_age_single(ast, StatArray[ix].t2_age);
2059       }
2060       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2061     } else {
2062       ast->print("No Tier2 nMethods found in CodeHeap.");
2063       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
2064     }
2065   }
2066 
2067   {
2068     if (nBlocks_alive > 0) {
2069       printBox(ast, '-', "not_used/not_entrant/not_installed age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2070       STRINGSTREAM_FLUSH_LOCKED("")
2071 
2072       granules_per_line = 128;
2073       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2074         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2075         print_age_single(ast, StatArray[ix].tx_age);
2076       }
2077       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2078     } else {
2079       ast->print("No Tier2 nMethods found in CodeHeap.");
2080       STRINGSTREAM_FLUSH_LOCKED("\n\n\n")
2081     }
2082   }
2083 
2084   {
2085     if (!segment_granules) { // Prevent totally redundant printouts
2086       printBox(ast, '-', "age distribution by tier <a1>:<a2>. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2087       STRINGSTREAM_FLUSH_LOCKED("")
2088 
2089       granules_per_line = 32;
2090       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2091         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2092         print_age_single(ast, StatArray[ix].t1_age);
2093         ast->print(":");
2094         print_age_single(ast, StatArray[ix].t2_age);
2095         ast->print(" ");
2096       }
2097       STRINGSTREAM_FLUSH_LOCKED("|\n\n\n")
2098     }
2099   }
2100 }
2101 
2102 
2103 void CodeHeapState::print_names(outputStream* out, CodeHeap* heap) {
2104   if (!initialization_complete) {
2105     return;
2106   }
2107 
2108   const char* heapName   = get_heapName(heap);
2109   get_HeapStatGlobals(out, heapName);
2110 
2111   if ((StatArray == NULL) || (alloc_granules == 0)) {
2112     return;
2113   }
2114   STRINGSTREAM_DECL(ast, out)
2115 
2116   unsigned int granules_per_line   = 128;
2117   char*        low_bound           = heap->low_boundary();
2118   CodeBlob*    last_blob           = NULL;
2119   bool         name_in_addr_range  = true;
2120   bool         have_CodeCache_lock = CodeCache_lock->owned_by_self();
2121 
2122   //---<  print at least 128K per block (i.e. between headers)  >---
2123   if (granules_per_line*granule_size < 128*K) {
2124     granules_per_line = (unsigned int)((128*K)/granule_size);
2125   }
2126 
2127   printBox(ast, '=', "M E T H O D   N A M E S   for ", heapName);
2128   ast->print_cr("  Method names are dynamically retrieved from the code cache at print time.\n"
2129                 "  Due to the living nature of the code heap and because the CodeCache_lock\n"
2130                 "  is not continuously held, the displayed name might be wrong or no name\n"
2131                 "  might be found at all. The likelihood for that to happen increases\n"
2132                 "  over time passed between aggregtion and print steps.\n");
2133   STRINGSTREAM_FLUSH_LOCKED("")
2134 
2135   for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2136     //---<  print a new blob on a new line  >---
2137     if (ix%granules_per_line == 0) {
2138       if (!name_in_addr_range) {
2139         ast->print_cr("No methods, blobs, or stubs found in this address range");
2140       }
2141       name_in_addr_range = false;
2142 
2143       size_t end_ix = (ix+granules_per_line <= alloc_granules) ? ix+granules_per_line : alloc_granules;
2144       ast->cr();
2145       ast->print_cr("--------------------------------------------------------------------");
2146       ast->print_cr("Address range [" INTPTR_FORMAT "," INTPTR_FORMAT "), " SIZE_FORMAT "k", p2i(low_bound+ix*granule_size), p2i(low_bound + end_ix*granule_size), (end_ix - ix)*granule_size/(size_t)K);
2147       ast->print_cr("--------------------------------------------------------------------");
2148       STRINGSTREAM_FLUSH_LOCKED("")
2149     }
2150     // Only check granule if it contains at least one blob.
2151     unsigned int nBlobs  = StatArray[ix].t1_count   + StatArray[ix].t2_count + StatArray[ix].tx_count +
2152                            StatArray[ix].stub_count + StatArray[ix].dead_count;
2153     if (nBlobs > 0 ) {
2154     for (unsigned int is = 0; is < granule_size; is+=(unsigned int)seg_size) {
2155       // heap->find_start() is safe. Only works on _segmap.
2156       // Returns NULL or void*. Returned CodeBlob may be uninitialized.
2157       char*     this_seg  = low_bound + ix*granule_size + is;
2158       CodeBlob* this_blob = (CodeBlob*)(heap->find_start(this_seg));
2159       bool   blob_is_safe = blob_access_is_safe(this_blob, NULL);


2160       // blob could have been flushed, freed, and merged.
2161       // this_blob < last_blob is an indicator for that.
2162       if (blob_is_safe && (this_blob > last_blob)) {
2163         last_blob          = this_blob;
2164 
2165         //---<  get type and name  >---
2166         blobType       cbType = noType;
2167         if (segment_granules) {
2168           cbType = (blobType)StatArray[ix].type;
2169         } else {
2170           //---<  access these fields only if we own the CodeCache_lock  >---
2171           if (have_CodeCache_lock) {
2172             cbType = get_cbType(this_blob);
2173           }
2174         }
2175 
2176         //---<  access these fields only if we own the CodeCache_lock  >---
2177         const char* blob_name = "<unavailable>";
2178         nmethod*           nm = NULL;
2179         if (have_CodeCache_lock) {
2180           blob_name = this_blob->name();
2181           nm        = this_blob->as_nmethod_or_null();
2182           // this_blob->name() could return NULL if no name was given to CTOR. Inlined, maybe invisible on stack

2183           if ((blob_name == NULL) || !os::is_readable_pointer(blob_name)) {
2184             blob_name = "<unavailable>";
2185           }
2186         }
2187 
2188         //---<  print table header for new print range  >---
2189         if (!name_in_addr_range) {
2190           name_in_addr_range = true;
2191           ast->fill_to(51);
2192           ast->print("%9s", "compiler");
2193           ast->fill_to(61);
2194           ast->print_cr("%6s", "method");
2195           ast->print_cr("%18s %13s %17s %9s  %5s %18s  %s", "Addr(module)      ", "offset", "size", " type lvl", " temp", "blobType          ", "Name");
2196           STRINGSTREAM_FLUSH_LOCKED("")
2197         }
2198 
2199         //---<  print line prefix (address and offset from CodeHeap start)  >---
2200         ast->print(INTPTR_FORMAT, p2i(this_blob));
2201         ast->fill_to(19);
2202         ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
2203         ast->fill_to(33);
2204 
2205         // access nmethod and Method fields only if we own the CodeCache_lock.
2206         // This fact is implicitly transported via nm != NULL.
2207         if (CompiledMethod::nmethod_access_is_safe(nm)) {
2208           Method* method = nm->method();
2209           ResourceMark rm;
2210           //---<  collect all data to locals as quickly as possible  >---
2211           unsigned int total_size = nm->total_size();
2212           int          hotness    = nm->hotness_counter();
2213           bool         get_name   = (cbType == nMethod_inuse) || (cbType == nMethod_notused);
2214           //---<  nMethod size in hex  >---
2215           ast->print(PTR32_FORMAT, total_size);
2216           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
2217           //---<  compiler information  >---
2218           ast->fill_to(51);
2219           ast->print("%5s %3d", compTypeName[StatArray[ix].compiler], StatArray[ix].level);
2220           //---<  method temperature  >---
2221           ast->fill_to(62);
2222           ast->print("%5d", hotness);
2223           //---<  name and signature  >---
2224           ast->fill_to(62+6);
2225           ast->print("%s", blobTypeName[cbType]);
2226           ast->fill_to(82+6);
2227           if (cbType == nMethod_dead) {
2228             ast->print("%14s", " zombie method");
2229           }
2230 
2231           if (get_name) {
2232             Symbol* methName  = method->name();
2233             const char*   methNameS = (methName == NULL) ? NULL : methName->as_C_string();
2234             methNameS = (methNameS == NULL) ? "<method name unavailable>" : methNameS;
2235             Symbol* methSig   = method->signature();
2236             const char*   methSigS  = (methSig  == NULL) ? NULL : methSig->as_C_string();
2237             methSigS  = (methSigS  == NULL) ? "<method signature unavailable>" : methSigS;
2238             ast->print("%s", methNameS);
2239             ast->print("%s", methSigS);
2240           } else {
2241             ast->print("%s", blob_name);
2242           }
2243         } else if (blob_is_safe) {
2244           ast->fill_to(62+6);
2245           ast->print("%s", blobTypeName[cbType]);
2246           ast->fill_to(82+6);
2247           ast->print("%s", blob_name);
2248         } else {
2249           ast->fill_to(62+6);
2250           ast->print("<stale blob>");
2251         }
2252         STRINGSTREAM_FLUSH_LOCKED("\n")
2253       } else if (!blob_is_safe && (this_blob != last_blob) && (this_blob != NULL)) {
2254         last_blob          = this_blob;
2255         STRINGSTREAM_FLUSH_LOCKED("\n")
2256       }
2257     }
2258     } // nBlobs > 0
2259   }
2260   STRINGSTREAM_FLUSH_LOCKED("\n\n")
2261 }
2262 
2263 
2264 void CodeHeapState::printBox(outputStream* ast, const char border, const char* text1, const char* text2) {
2265   unsigned int lineLen = 1 + 2 + 2 + 1;
2266   char edge, frame;
2267 
2268   if (text1 != NULL) {
2269     lineLen += (unsigned int)strlen(text1); // text1 is much shorter than MAX_INT chars.
2270   }
2271   if (text2 != NULL) {
2272     lineLen += (unsigned int)strlen(text2); // text2 is much shorter than MAX_INT chars.
2273   }
2274   if (border == '-') {
2275     edge  = '+';
2276     frame = '|';
2277   } else {
2278     edge  = border;
2279     frame = border;
2280   }
2281 
2282   ast->print("%c", edge);
2283   for (unsigned int i = 0; i < lineLen-2; i++) {
2284     ast->print("%c", border);
2285   }
2286   ast->print_cr("%c", edge);
2287 
2288   ast->print("%c  ", frame);
2289   if (text1 != NULL) {
2290     ast->print("%s", text1);
2291   }
2292   if (text2 != NULL) {
2293     ast->print("%s", text2);
2294   }
2295   ast->print_cr("  %c", frame);
2296 
2297   ast->print("%c", edge);
2298   for (unsigned int i = 0; i < lineLen-2; i++) {
2299     ast->print("%c", border);
2300   }
2301   ast->print_cr("%c", edge);
2302 }
2303 
2304 void CodeHeapState::print_blobType_legend(outputStream* out) {
2305   out->cr();
2306   printBox(out, '-', "Block types used in the following CodeHeap dump", NULL);
2307   for (int type = noType; type < lastType; type += 1) {
2308     out->print_cr("  %c - %s", blobTypeChar[type], blobTypeName[type]);
2309   }
2310   out->print_cr("  -----------------------------------------------------");
2311   out->cr();
2312 }
2313 
2314 void CodeHeapState::print_space_legend(outputStream* out) {
2315   unsigned int indicator = 0;
2316   unsigned int age_range = 256;
2317   unsigned int range_beg = latest_compilation_id;
2318   out->cr();
2319   printBox(out, '-', "Space ranges, based on granule occupancy", NULL);
2320   out->print_cr("    -   0%% == occupancy");
2321   for (int i=0; i<=9; i++) {
2322     out->print_cr("  %d - %3d%% < occupancy < %3d%%", i, 10*i, 10*(i+1));
2323   }
2324   out->print_cr("  * - 100%% == occupancy");
2325   out->print_cr("  ----------------------------------------------");
2326   out->cr();
2327 }
2328 
2329 void CodeHeapState::print_age_legend(outputStream* out) {
2330   unsigned int indicator = 0;
2331   unsigned int age_range = 256;
2332   unsigned int range_beg = latest_compilation_id;
2333   out->cr();
2334   printBox(out, '-', "Age ranges, based on compilation id", NULL);
2335   while (age_range > 0) {
2336     out->print_cr("  %d - %6d to %6d", indicator, range_beg, latest_compilation_id - latest_compilation_id/age_range);
2337     range_beg = latest_compilation_id - latest_compilation_id/age_range;
2338     age_range /= 2;
2339     indicator += 1;
2340   }
2341   out->print_cr("  -----------------------------------------");
2342   out->cr();
2343 }
2344 
2345 void CodeHeapState::print_blobType_single(outputStream* out, u2 /* blobType */ type) {
2346   out->print("%c", blobTypeChar[type]);
2347 }
2348 
2349 void CodeHeapState::print_count_single(outputStream* out, unsigned short count) {
2350   if (count >= 16)    out->print("*");
2351   else if (count > 0) out->print("%1.1x", count);
2352   else                out->print(" ");
2353 }
2354 
2355 void CodeHeapState::print_space_single(outputStream* out, unsigned short space) {
2356   size_t  space_in_bytes = ((unsigned int)space)<<log2_seg_size;
2357   char    fraction       = (space == 0) ? ' ' : (space_in_bytes >= granule_size-1) ? '*' : char('0'+10*space_in_bytes/granule_size);
2358   out->print("%c", fraction);
2359 }
2360 
2361 void CodeHeapState::print_age_single(outputStream* out, unsigned int age) {
2362   unsigned int indicator = 0;
2363   unsigned int age_range = 256;
2364   if (age > 0) {
2365     while ((age_range > 0) && (latest_compilation_id-age > latest_compilation_id/age_range)) {
2366       age_range /= 2;
2367       indicator += 1;
2368     }
2369     out->print("%c", char('0'+indicator));
2370   } else {
2371     out->print(" ");
2372   }
2373 }
2374 
2375 void CodeHeapState::print_line_delim(outputStream* out, outputStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2376   if (ix % gpl == 0) {
2377     if (ix > 0) {
2378       ast->print("|");
2379     }
2380     ast->cr();
2381     assert(out == ast, "must use the same stream!");
2382 
2383     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2384     ast->fill_to(19);
2385     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2386   }
2387 }
2388 
2389 void CodeHeapState::print_line_delim(outputStream* out, bufferedStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2390   assert(out != ast, "must not use the same stream!");
2391   if (ix % gpl == 0) {
2392     if (ix > 0) {
2393       ast->print("|");
2394     }
2395     ast->cr();
2396 
2397     { // can't use STRINGSTREAM_FLUSH_LOCKED("") here.
2398       ttyLocker ttyl;
2399       out->print("%s", ast->as_string());
2400       ast->reset();
2401     }
2402 
2403     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2404     ast->fill_to(19);
2405     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2406   }
2407 }
2408 
2409 CodeHeapState::blobType CodeHeapState::get_cbType(CodeBlob* cb) {
2410   if ((cb != NULL) && os::is_readable_pointer(cb)) {
2411     if (cb->is_runtime_stub())                return runtimeStub;
2412     if (cb->is_deoptimization_stub())         return deoptimizationStub;
2413     if (cb->is_uncommon_trap_stub())          return uncommonTrapStub;
2414     if (cb->is_exception_stub())              return exceptionStub;
2415     if (cb->is_safepoint_stub())              return safepointStub;
2416     if (cb->is_adapter_blob())                return adapterBlob;
2417     if (cb->is_method_handles_adapter_blob()) return mh_adapterBlob;
2418     if (cb->is_buffer_blob())                 return bufferBlob;
2419 
2420     //---<  access these fields only if we own the CodeCache_lock  >---
2421     // Should be ensured by caller. aggregate() amd print_names() do that.
2422     if (CodeCache_lock->owned_by_self()) {
2423       nmethod*  nm = cb->as_nmethod_or_null();
2424       if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
2425         if (nm->is_not_installed()) return nMethod_inconstruction;
2426         if (nm->is_zombie())        return nMethod_dead;
2427         if (nm->is_unloaded())      return nMethod_unloaded;
2428         if (nm->is_in_use())        return nMethod_inuse;
2429         if (nm->is_alive() && !(nm->is_not_entrant()))   return nMethod_notused;
2430         if (nm->is_alive())         return nMethod_alive;
2431         return nMethod_dead;
2432       }
2433     }
2434   }
2435   return noType;
2436 }
2437 
2438 bool CodeHeapState::blob_access_is_safe(CodeBlob* this_blob, CodeBlob* prev_blob) {
2439   return (this_blob != NULL) && // a blob must have been found, obviously
2440          ((this_blob == prev_blob) || (prev_blob == NULL)) &&  // when re-checking, the same blob must have been found
2441          (this_blob->header_size() >= 0) &&
2442          (this_blob->relocation_size() >= 0) &&
2443          ((address)this_blob + this_blob->header_size() == (address)(this_blob->relocation_begin())) &&
2444          ((address)this_blob + CodeBlob::align_code_offset(this_blob->header_size() + this_blob->relocation_size()) == (address)(this_blob->content_begin())) &&
2445          os::is_readable_pointer((address)(this_blob->relocation_begin())) &&
2446          os::is_readable_pointer(this_blob->content_begin());
2447 }
--- EOF ---