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/safepoint.hpp"
  30 #include "runtime/sweeper.hpp"
  31 
  32 // -------------------------
  33 // |  General Description  |
  34 // -------------------------
  35 // The CodeHeap state analytics are divided in two parts.
  36 // The first part examines the entire CodeHeap and aggregates all
  37 // information that is believed useful/important.
  38 //
  39 // Aggregation condenses the information of a piece of the CodeHeap
  40 // (4096 bytes by default) into an analysis granule. These granules
  41 // contain enough detail to gain initial insight while keeping the
  42 // internal sttructure sizes in check.
  43 //
  44 // The second part, which consists of several, independent steps,
  45 // prints the previously collected information with emphasis on
  46 // various aspects.
  47 //
  48 // The CodeHeap is a living thing. Therefore, protection against concurrent
  49 // modification (by acquiring the CodeCache_lock) is necessary. It has
  50 // to be provided by the caller of the analysis functions.
  51 // If the CodeCache_lock is not held, the analysis functions may print
  52 // less detailed information or may just do nothing. It is by intention
  53 // that an unprotected invocation is not abnormally terminated.
  54 //
  55 // Data collection and printing is done on an "on request" basis.
  56 // While no request is being processed, there is no impact on performance.
  57 // The CodeHeap state analytics do have some memory footprint.
  58 // The "aggregate" step allocates some data structures to hold the aggregated
  59 // information for later output. These data structures live until they are
  60 // explicitly discarded (function "discard") or until the VM terminates.
  61 // There is one exception: the function "all" does not leave any data
  62 // structures allocated.
  63 //
  64 // Requests for real-time, on-the-fly analysis can be issued via
  65 //   jcmd <pid> Compiler.CodeHeap_Analytics [<function>] [<granularity>]
  66 //
  67 // If you are (only) interested in how the CodeHeap looks like after running
  68 // a sample workload, you can use the command line option
  69 //   -Xlog:codecache=Trace
  70 //
  71 // To see the CodeHeap state in case of a "CodeCache full" condition, start the
  72 // VM with the
  73 //   -Xlog:codecache=Debug
  74 // command line option. It will produce output only for the first time the
  75 // condition is recognized.
  76 //
  77 // Both command line option variants produce output identical to the jcmd function
  78 //   jcmd <pid> Compiler.CodeHeap_Analytics all 4096
  79 // ---------------------------------------------------------------------------------
  80 
  81 // With this declaration macro, it is possible to switch between
  82 //  - direct output into an argument-passed outputStream and
  83 //  - buffered output into a bufferedStream with subsequent flush
  84 //    of the filled buffer to the outputStream.
  85 #define USE_BUFFEREDSTREAM
  86 
  87 // There are instances when composing an output line or a small set of
  88 // output lines out of many tty->print() calls creates significant overhead.
  89 // Writing to a bufferedStream buffer first has a significant advantage:
  90 // It uses noticeably less cpu cycles and reduces (when writing to a
  91 // network file) the required bandwidth by at least a factor of ten. Observed on MacOS.
  92 // That clearly makes up for the increased code complexity.
  93 //
  94 // Conversion of existing code is easy and straightforward, if the code already
  95 // uses a parameterized output destination, e.g. "outputStream st".
  96 //  - rename the formal parameter to any other name, e.g. out_st.
  97 //  - at a suitable place in your code, insert
  98 //      BUFFEREDSTEAM_DECL(buf_st, out_st)
  99 // This will provide all the declarations necessary. After that, all
 100 // buf_st->print() (and the like) calls will be directed to a bufferedStream object.
 101 // Once a block of output (a line or a small set of lines) is composed, insert
 102 //      BUFFEREDSTREAM_FLUSH(termstring)
 103 // to flush the bufferedStream to the final destination out_st. termstring is just
 104 // an arbitrary string (e.g. "\n") which is appended to the bufferedStream before
 105 // being written to out_st. Be aware that the last character written MUST be a '\n'.
 106 // Otherwise, buf_st->position() does not correspond to out_st->position() any longer.
 107 //      BUFFEREDSTREAM_FLUSH_LOCKED(termstring)
 108 // does the same thing, protected by the ttyLocker lock.
 109 //      BUFFEREDSTREAM_FLUSH_IF(termstring, remSize)
 110 // does a flush only if the remaining buffer space is less than remSize.
 111 //
 112 // To activate, #define USE_BUFFERED_STREAM before including this header.
 113 // If not activated, output will directly go to the originally used outputStream
 114 // with no additional overhead.
 115 //
 116 #if defined(USE_BUFFEREDSTREAM)
 117 // All necessary declarations to print via a bufferedStream
 118 // This macro must be placed before any other BUFFEREDSTREAM*
 119 // macro in the function.
 120 #define BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, _capa)       \
 121     ResourceMark         _rm;                                 \
 122     /* _anyst  name of the stream as used in the code */      \
 123     /* _outst  stream where final output will go to   */      \
 124     /* _capa   allocated capacity of stream buffer    */      \
 125     size_t           _nflush = 0;                             \
 126     size_t     _nforcedflush = 0;                             \
 127     size_t      _nsavedflush = 0;                             \
 128     size_t     _nlockedflush = 0;                             \
 129     size_t     _nflush_bytes = 0;                             \
 130     size_t         _capacity = _capa;                         \
 131     bufferedStream   _sstobj(_capa);                          \
 132     bufferedStream*  _sstbuf = &_sstobj;                      \
 133     outputStream*    _outbuf = _outst;                        \
 134     bufferedStream*   _anyst = &_sstobj; /* any stream. Use this to just print - no buffer flush.  */
 135 
 136 // Same as above, but with fixed buffer size.
 137 #define BUFFEREDSTREAM_DECL(_anyst, _outst)                   \
 138     BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, 4*K);
 139 
 140 // Flush the buffer contents unconditionally.
 141 // No action if the buffer is empty.
 142 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 143     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 144       _sstbuf->print("%s", _termString);                      \
 145     }                                                         \
 146     if (_sstbuf != _outbuf) {                                 \
 147       if (_sstbuf->size() != 0) {                             \
 148         _nforcedflush++; _nflush_bytes += _sstbuf->size();    \
 149         _outbuf->print("%s", _sstbuf->as_string());           \
 150         _sstbuf->reset();                                     \
 151       }                                                       \
 152     }
 153 
 154 // Flush the buffer contents if the remaining capacity is
 155 // less than the given threshold.
 156 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 157     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 158       _sstbuf->print("%s", _termString);                      \
 159     }                                                         \
 160     if (_sstbuf != _outbuf) {                                 \
 161       if ((_capacity - _sstbuf->size()) < (size_t)(_remSize)){\
 162         _nflush++; _nforcedflush--;                           \
 163         BUFFEREDSTREAM_FLUSH("")                              \
 164       } else {                                                \
 165         _nsavedflush++;                                       \
 166       }                                                       \
 167     }
 168 
 169 // Flush the buffer contents if the remaining capacity is less
 170 // than the calculated threshold (256 bytes + capacity/16)
 171 // That should suffice for all reasonably sized output lines.
 172 #define BUFFEREDSTREAM_FLUSH_AUTO(_termString)                \
 173     BUFFEREDSTREAM_FLUSH_IF(_termString, 256+(_capacity>>4))
 174 
 175 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 176     { ttyLocker ttyl;/* keep this output block together */    \
 177       _nlockedflush++;                                        \
 178       BUFFEREDSTREAM_FLUSH(_termString)                       \
 179     }
 180 
 181 // #define BUFFEREDSTREAM_FLUSH_STAT()                           \
 182 //     if (_sstbuf != _outbuf) {                                 \
 183 //       _outbuf->print_cr("%ld flushes (buffer full), %ld forced, %ld locked, %ld bytes total, %ld flushes saved", _nflush, _nforcedflush, _nlockedflush, _nflush_bytes, _nsavedflush); \
 184 //    }
 185 
 186 #define BUFFEREDSTREAM_FLUSH_STAT()
 187 #else
 188 #define BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, _capa)       \
 189     size_t       _capacity = _capa;                           \
 190     outputStream*  _outbuf = _outst;                          \
 191     outputStream*  _anyst  = _outst;   /* any stream. Use this to just print - no buffer flush.  */
 192 
 193 #define BUFFEREDSTREAM_DECL(_anyst, _outst)                   \
 194     BUFFEREDSTREAM_DECL_SIZE(_anyst, _outst, 4*K)
 195 
 196 #define BUFFEREDSTREAM_FLUSH(_termString)                     \
 197     if (((_termString) != NULL) && (strlen(_termString) > 0)){\
 198       _outbuf->print("%s", _termString);                      \
 199     }
 200 
 201 #define BUFFEREDSTREAM_FLUSH_IF(_termString, _remSize)        \
 202     BUFFEREDSTREAM_FLUSH(_termString)
 203 
 204 #define BUFFEREDSTREAM_FLUSH_AUTO(_termString)                \
 205     BUFFEREDSTREAM_FLUSH(_termString)
 206 
 207 #define BUFFEREDSTREAM_FLUSH_LOCKED(_termString)              \
 208     BUFFEREDSTREAM_FLUSH(_termString)
 209 
 210 #define BUFFEREDSTREAM_FLUSH_STAT()
 211 #endif
 212 #define HEX32_FORMAT  "0x%x"  // just a helper format string used below multiple times
 213 
 214 const char  blobTypeChar[] = {' ', 'C', 'N', 'I', 'X', 'Z', 'U', 'R', '?', 'D', 'T', 'E', 'S', 'A', 'M', 'B', 'L' };
 215 const char* blobTypeName[] = {"noType"
 216                              ,     "nMethod (under construction), cannot be observed"
 217                              ,          "nMethod (active)"
 218                              ,               "nMethod (inactive)"
 219                              ,                    "nMethod (deopt)"
 220                              ,                         "nMethod (zombie)"
 221                              ,                              "nMethod (unloaded)"
 222                              ,                                   "runtime stub"
 223                              ,                                        "ricochet stub"
 224                              ,                                             "deopt stub"
 225                              ,                                                  "uncommon trap stub"
 226                              ,                                                       "exception stub"
 227                              ,                                                            "safepoint stub"
 228                              ,                                                                 "adapter blob"
 229                              ,                                                                      "MH adapter blob"
 230                              ,                                                                           "buffer blob"
 231                              ,                                                                                "lastType"
 232                              };
 233 const char* compTypeName[] = { "none", "c1", "c2", "jvmci" };
 234 
 235 // Be prepared for ten different CodeHeap segments. Should be enough for a few years.
 236 const  unsigned int        nSizeDistElements = 31;  // logarithmic range growth, max size: 2**32
 237 const  unsigned int        maxTopSizeBlocks  = 100;
 238 const  unsigned int        tsbStopper        = 2 * maxTopSizeBlocks;
 239 const  unsigned int        maxHeaps          = 10;
 240 static unsigned int        nHeaps            = 0;
 241 static struct CodeHeapStat CodeHeapStatArray[maxHeaps];
 242 
 243 // static struct StatElement *StatArray      = NULL;
 244 static StatElement* StatArray             = NULL;
 245 static int          log2_seg_size         = 0;
 246 static size_t       seg_size              = 0;
 247 static size_t       alloc_granules        = 0;
 248 static size_t       granule_size          = 0;
 249 static bool         segment_granules      = false;
 250 static unsigned int nBlocks_t1            = 0;  // counting "in_use" nmethods only.
 251 static unsigned int nBlocks_t2            = 0;  // counting "in_use" nmethods only.
 252 static unsigned int nBlocks_alive         = 0;  // counting "not_used" and "not_entrant" nmethods only.
 253 static unsigned int nBlocks_dead          = 0;  // counting "zombie" and "unloaded" methods only.
 254 static unsigned int nBlocks_unloaded      = 0;  // counting "unloaded" nmethods only. This is a transient state.
 255 static unsigned int nBlocks_stub          = 0;
 256 
 257 static struct FreeBlk*          FreeArray = NULL;
 258 static unsigned int      alloc_freeBlocks = 0;
 259 
 260 static struct TopSizeBlk*    TopSizeArray = NULL;
 261 static unsigned int   alloc_topSizeBlocks = 0;
 262 static unsigned int    used_topSizeBlocks = 0;
 263 
 264 static struct SizeDistributionElement*  SizeDistributionArray = NULL;
 265 
 266 // nMethod temperature (hotness) indicators.
 267 static int                     avgTemp    = 0;
 268 static int                     maxTemp    = 0;
 269 static int                     minTemp    = 0;
 270 
 271 static unsigned int  latest_compilation_id   = 0;
 272 static volatile bool initialization_complete = false;
 273 
 274 const char* CodeHeapState::get_heapName(CodeHeap* heap) {
 275   if (SegmentedCodeCache) {
 276     return heap->name();
 277   } else {
 278     return "CodeHeap";
 279   }
 280 }
 281 
 282 // returns the index for the heap being processed.
 283 unsigned int CodeHeapState::findHeapIndex(outputStream* out, const char* heapName) {
 284   if (heapName == NULL) {
 285     return maxHeaps;
 286   }
 287   if (SegmentedCodeCache) {
 288     // Search for a pre-existing entry. If found, return that index.
 289     for (unsigned int i = 0; i < nHeaps; i++) {
 290       if (CodeHeapStatArray[i].heapName != NULL && strcmp(heapName, CodeHeapStatArray[i].heapName) == 0) {
 291         return i;
 292       }
 293     }
 294 
 295     // check if there are more code heap segments than we can handle.
 296     if (nHeaps == maxHeaps) {
 297       out->print_cr("Too many heap segments for current limit(%d).", maxHeaps);
 298       return maxHeaps;
 299     }
 300 
 301     // allocate new slot in StatArray.
 302     CodeHeapStatArray[nHeaps].heapName = heapName;
 303     return nHeaps++;
 304   } else {
 305     nHeaps = 1;
 306     CodeHeapStatArray[0].heapName = heapName;
 307     return 0; // This is the default index if CodeCache is not segmented.
 308   }
 309 }
 310 
 311 void CodeHeapState::get_HeapStatGlobals(outputStream* out, const char* heapName) {
 312   unsigned int ix = findHeapIndex(out, heapName);
 313   if (ix < maxHeaps) {
 314     StatArray             = CodeHeapStatArray[ix].StatArray;
 315     seg_size              = CodeHeapStatArray[ix].segment_size;
 316     log2_seg_size         = seg_size == 0 ? 0 : exact_log2(seg_size);
 317     alloc_granules        = CodeHeapStatArray[ix].alloc_granules;
 318     granule_size          = CodeHeapStatArray[ix].granule_size;
 319     segment_granules      = CodeHeapStatArray[ix].segment_granules;
 320     nBlocks_t1            = CodeHeapStatArray[ix].nBlocks_t1;
 321     nBlocks_t2            = CodeHeapStatArray[ix].nBlocks_t2;
 322     nBlocks_alive         = CodeHeapStatArray[ix].nBlocks_alive;
 323     nBlocks_dead          = CodeHeapStatArray[ix].nBlocks_dead;
 324     nBlocks_unloaded      = CodeHeapStatArray[ix].nBlocks_unloaded;
 325     nBlocks_stub          = CodeHeapStatArray[ix].nBlocks_stub;
 326     FreeArray             = CodeHeapStatArray[ix].FreeArray;
 327     alloc_freeBlocks      = CodeHeapStatArray[ix].alloc_freeBlocks;
 328     TopSizeArray          = CodeHeapStatArray[ix].TopSizeArray;
 329     alloc_topSizeBlocks   = CodeHeapStatArray[ix].alloc_topSizeBlocks;
 330     used_topSizeBlocks    = CodeHeapStatArray[ix].used_topSizeBlocks;
 331     SizeDistributionArray = CodeHeapStatArray[ix].SizeDistributionArray;
 332     avgTemp               = CodeHeapStatArray[ix].avgTemp;
 333     maxTemp               = CodeHeapStatArray[ix].maxTemp;
 334     minTemp               = CodeHeapStatArray[ix].minTemp;
 335   } else {
 336     StatArray             = NULL;
 337     seg_size              = 0;
 338     log2_seg_size         = 0;
 339     alloc_granules        = 0;
 340     granule_size          = 0;
 341     segment_granules      = false;
 342     nBlocks_t1            = 0;
 343     nBlocks_t2            = 0;
 344     nBlocks_alive         = 0;
 345     nBlocks_dead          = 0;
 346     nBlocks_unloaded      = 0;
 347     nBlocks_stub          = 0;
 348     FreeArray             = NULL;
 349     alloc_freeBlocks      = 0;
 350     TopSizeArray          = NULL;
 351     alloc_topSizeBlocks   = 0;
 352     used_topSizeBlocks    = 0;
 353     SizeDistributionArray = NULL;
 354     avgTemp               = 0;
 355     maxTemp               = 0;
 356     minTemp               = 0;
 357   }
 358 }
 359 
 360 void CodeHeapState::set_HeapStatGlobals(outputStream* out, const char* heapName) {
 361   unsigned int ix = findHeapIndex(out, heapName);
 362   if (ix < maxHeaps) {
 363     CodeHeapStatArray[ix].StatArray             = StatArray;
 364     CodeHeapStatArray[ix].segment_size          = seg_size;
 365     CodeHeapStatArray[ix].alloc_granules        = alloc_granules;
 366     CodeHeapStatArray[ix].granule_size          = granule_size;
 367     CodeHeapStatArray[ix].segment_granules      = segment_granules;
 368     CodeHeapStatArray[ix].nBlocks_t1            = nBlocks_t1;
 369     CodeHeapStatArray[ix].nBlocks_t2            = nBlocks_t2;
 370     CodeHeapStatArray[ix].nBlocks_alive         = nBlocks_alive;
 371     CodeHeapStatArray[ix].nBlocks_dead          = nBlocks_dead;
 372     CodeHeapStatArray[ix].nBlocks_unloaded      = nBlocks_unloaded;
 373     CodeHeapStatArray[ix].nBlocks_stub          = nBlocks_stub;
 374     CodeHeapStatArray[ix].FreeArray             = FreeArray;
 375     CodeHeapStatArray[ix].alloc_freeBlocks      = alloc_freeBlocks;
 376     CodeHeapStatArray[ix].TopSizeArray          = TopSizeArray;
 377     CodeHeapStatArray[ix].alloc_topSizeBlocks   = alloc_topSizeBlocks;
 378     CodeHeapStatArray[ix].used_topSizeBlocks    = used_topSizeBlocks;
 379     CodeHeapStatArray[ix].SizeDistributionArray = SizeDistributionArray;
 380     CodeHeapStatArray[ix].avgTemp               = avgTemp;
 381     CodeHeapStatArray[ix].maxTemp               = maxTemp;
 382     CodeHeapStatArray[ix].minTemp               = minTemp;
 383   }
 384 }
 385 
 386 //---<  get a new statistics array  >---
 387 void CodeHeapState::prepare_StatArray(outputStream* out, size_t nElem, size_t granularity, const char* heapName) {
 388   if (StatArray == NULL) {
 389     StatArray      = new StatElement[nElem];
 390     //---<  reset some counts  >---
 391     alloc_granules = nElem;
 392     granule_size   = granularity;
 393   }
 394 
 395   if (StatArray == NULL) {
 396     //---<  just do nothing if allocation failed  >---
 397     out->print_cr("Statistics could not be collected for %s, probably out of memory.", heapName);
 398     out->print_cr("Current granularity is " SIZE_FORMAT " bytes. Try a coarser granularity.", granularity);
 399     alloc_granules = 0;
 400     granule_size   = 0;
 401   } else {
 402     //---<  initialize statistics array  >---
 403     memset((void*)StatArray, 0, nElem*sizeof(StatElement));
 404   }
 405 }
 406 
 407 //---<  get a new free block array  >---
 408 void CodeHeapState::prepare_FreeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 409   if (FreeArray == NULL) {
 410     FreeArray      = new FreeBlk[nElem];
 411     //---<  reset some counts  >---
 412     alloc_freeBlocks = nElem;
 413   }
 414 
 415   if (FreeArray == NULL) {
 416     //---<  just do nothing if allocation failed  >---
 417     out->print_cr("Free space analysis cannot be done for %s, probably out of memory.", heapName);
 418     alloc_freeBlocks = 0;
 419   } else {
 420     //---<  initialize free block array  >---
 421     memset((void*)FreeArray, 0, alloc_freeBlocks*sizeof(FreeBlk));
 422   }
 423 }
 424 
 425 //---<  get a new TopSizeArray  >---
 426 void CodeHeapState::prepare_TopSizeArray(outputStream* out, unsigned int nElem, const char* heapName) {
 427   if (TopSizeArray == NULL) {
 428     TopSizeArray   = new TopSizeBlk[nElem];
 429     //---<  reset some counts  >---
 430     alloc_topSizeBlocks = nElem;
 431     used_topSizeBlocks  = 0;
 432   }
 433 
 434   if (TopSizeArray == NULL) {
 435     //---<  just do nothing if allocation failed  >---
 436     out->print_cr("Top-%d list of largest CodeHeap blocks can not be collected for %s, probably out of memory.", nElem, heapName);
 437     alloc_topSizeBlocks = 0;
 438   } else {
 439     //---<  initialize TopSizeArray  >---
 440     memset((void*)TopSizeArray, 0, nElem*sizeof(TopSizeBlk));
 441     used_topSizeBlocks  = 0;
 442   }
 443 }
 444 
 445 //---<  get a new SizeDistributionArray  >---
 446 void CodeHeapState::prepare_SizeDistArray(outputStream* out, unsigned int nElem, const char* heapName) {
 447   if (SizeDistributionArray == NULL) {
 448     SizeDistributionArray = new SizeDistributionElement[nElem];
 449   }
 450 
 451   if (SizeDistributionArray == NULL) {
 452     //---<  just do nothing if allocation failed  >---
 453     out->print_cr("Size distribution can not be collected for %s, probably out of memory.", heapName);
 454   } else {
 455     //---<  initialize SizeDistArray  >---
 456     memset((void*)SizeDistributionArray, 0, nElem*sizeof(SizeDistributionElement));
 457     // Logarithmic range growth. First range starts at _segment_size.
 458     SizeDistributionArray[log2_seg_size-1].rangeEnd = 1U;
 459     for (unsigned int i = log2_seg_size; i < nElem; i++) {
 460       SizeDistributionArray[i].rangeStart = 1U << (i     - log2_seg_size);
 461       SizeDistributionArray[i].rangeEnd   = 1U << ((i+1) - log2_seg_size);
 462     }
 463   }
 464 }
 465 
 466 //---<  get a new SizeDistributionArray  >---
 467 void CodeHeapState::update_SizeDistArray(outputStream* out, unsigned int len) {
 468   if (SizeDistributionArray != NULL) {
 469     for (unsigned int i = log2_seg_size-1; i < nSizeDistElements; i++) {
 470       if ((SizeDistributionArray[i].rangeStart <= len) && (len < SizeDistributionArray[i].rangeEnd)) {
 471         SizeDistributionArray[i].lenSum += len;
 472         SizeDistributionArray[i].count++;
 473         break;
 474       }
 475     }
 476   }
 477 }
 478 
 479 void CodeHeapState::discard_StatArray(outputStream* out) {
 480   if (StatArray != NULL) {
 481     delete StatArray;
 482     StatArray        = NULL;
 483     alloc_granules   = 0;
 484     granule_size     = 0;
 485   }
 486 }
 487 
 488 void CodeHeapState::discard_FreeArray(outputStream* out) {
 489   if (FreeArray != NULL) {
 490     delete[] FreeArray;
 491     FreeArray        = NULL;
 492     alloc_freeBlocks = 0;
 493   }
 494 }
 495 
 496 void CodeHeapState::discard_TopSizeArray(outputStream* out) {
 497   if (TopSizeArray != NULL) {
 498     for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
 499       if (TopSizeArray[i].blob_name != NULL) {
 500         os::free((void*)TopSizeArray[i].blob_name);
 501       }
 502     }
 503     delete[] TopSizeArray;
 504     TopSizeArray        = NULL;
 505     alloc_topSizeBlocks = 0;
 506     used_topSizeBlocks  = 0;
 507   }
 508 }
 509 
 510 void CodeHeapState::discard_SizeDistArray(outputStream* out) {
 511   if (SizeDistributionArray != NULL) {
 512     delete[] SizeDistributionArray;
 513     SizeDistributionArray = NULL;
 514   }
 515 }
 516 
 517 // Discard all allocated internal data structures.
 518 // This should be done after an analysis session is completed.
 519 void CodeHeapState::discard(outputStream* out, CodeHeap* heap) {
 520   if (!initialization_complete) {
 521     return;
 522   }
 523 
 524   if (nHeaps > 0) {
 525     for (unsigned int ix = 0; ix < nHeaps; ix++) {
 526       get_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 527       discard_StatArray(out);
 528       discard_FreeArray(out);
 529       discard_TopSizeArray(out);
 530       discard_SizeDistArray(out);
 531       set_HeapStatGlobals(out, CodeHeapStatArray[ix].heapName);
 532       CodeHeapStatArray[ix].heapName = NULL;
 533     }
 534     nHeaps = 0;
 535   }
 536 }
 537 
 538 void CodeHeapState::aggregate(outputStream* out, CodeHeap* heap, size_t granularity) {
 539   unsigned int nBlocks_free    = 0;
 540   unsigned int nBlocks_used    = 0;
 541   unsigned int nBlocks_zomb    = 0;
 542   unsigned int nBlocks_disconn = 0;
 543   unsigned int nBlocks_notentr = 0;
 544 
 545   //---<  max & min of TopSizeArray  >---
 546   //  it is sufficient to have these sizes as 32bit unsigned ints.
 547   //  The CodeHeap is limited in size to 4GB. Furthermore, the sizes
 548   //  are stored in _segment_size units, scaling them down by a factor of 64 (at least).
 549   unsigned int  currMax          = 0;
 550   unsigned int  currMin          = 0;
 551   unsigned int  currMin_ix       = 0;
 552   unsigned long total_iterations = 0;
 553 
 554   bool  done             = false;
 555   const int min_granules = 256;
 556   const int max_granules = 512*K; // limits analyzable CodeHeap (with segment_granules) to 32M..128M
 557                                   // results in StatArray size of 24M (= max_granules * 48 Bytes per element)
 558                                   // For a 1GB CodeHeap, the granule size must be at least 2kB to not violate the max_granles limit.
 559   const char* heapName   = get_heapName(heap);
 560   BUFFEREDSTREAM_DECL(ast, out)
 561 
 562   if (!initialization_complete) {
 563     memset(CodeHeapStatArray, 0, sizeof(CodeHeapStatArray));
 564     initialization_complete = true;
 565 
 566     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (general remarks)", NULL);
 567     ast->print_cr("   The code heap analysis function provides deep insights into\n"
 568                   "   the inner workings and the internal state of the Java VM's\n"
 569                   "   code cache - the place where all the JVM generated machine\n"
 570                   "   code is stored.\n"
 571                   "   \n"
 572                   "   This function is designed and provided for support engineers\n"
 573                   "   to help them understand and solve issues in customer systems.\n"
 574                   "   It is not intended for use and interpretation by other persons.\n"
 575                   "   \n");
 576     BUFFEREDSTREAM_FLUSH("")
 577   }
 578   get_HeapStatGlobals(out, heapName);
 579 
 580 
 581   // Since we are (and must be) analyzing the CodeHeap contents under the CodeCache_lock,
 582   // all heap information is "constant" and can be safely extracted/calculated before we
 583   // enter the while() loop. Actually, the loop will only be iterated once.
 584   char*  low_bound     = heap->low_boundary();
 585   size_t size          = heap->capacity();
 586   size_t res_size      = heap->max_capacity();
 587   seg_size             = heap->segment_size();
 588   log2_seg_size        = seg_size == 0 ? 0 : exact_log2(seg_size);  // This is a global static value.
 589 
 590   if (seg_size == 0) {
 591     printBox(ast, '-', "Heap not fully initialized yet, segment size is zero for segment ", heapName);
 592     BUFFEREDSTREAM_FLUSH("")
 593     return;
 594   }
 595 
 596   if (!holding_required_locks()) {
 597     printBox(ast, '-', "Must be at safepoint or hold Compile_lock and CodeCache_lock when calling aggregate function for ", heapName);
 598     BUFFEREDSTREAM_FLUSH("")
 599     return;
 600   }
 601 
 602   // Calculate granularity of analysis (and output).
 603   //   The CodeHeap is managed (allocated) in segments (units) of CodeCacheSegmentSize.
 604   //   The CodeHeap can become fairly large, in particular in productive real-life systems.
 605   //
 606   //   It is often neither feasible nor desirable to aggregate the data with the highest possible
 607   //   level of detail, i.e. inspecting and printing each segment on its own.
 608   //
 609   //   The granularity parameter allows to specify the level of detail available in the analysis.
 610   //   It must be a positive multiple of the segment size and should be selected such that enough
 611   //   detail is provided while, at the same time, the printed output does not explode.
 612   //
 613   //   By manipulating the granularity value, we enforce that at least min_granules units
 614   //   of analysis are available. We also enforce an upper limit of max_granules units to
 615   //   keep the amount of allocated storage in check.
 616   //
 617   //   Finally, we adjust the granularity such that each granule covers at most 64k-1 segments.
 618   //   This is necessary to prevent an unsigned short overflow while accumulating space information.
 619   //
 620   assert(granularity > 0, "granularity should be positive.");
 621 
 622   if (granularity > size) {
 623     granularity = size;
 624   }
 625   if (size/granularity < min_granules) {
 626     granularity = size/min_granules;                                   // at least min_granules granules
 627   }
 628   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 629   if (granularity < seg_size) {
 630     granularity = seg_size;                                            // must be at least seg_size
 631   }
 632   if (size/granularity > max_granules) {
 633     granularity = size/max_granules;                                   // at most max_granules granules
 634   }
 635   granularity = granularity & (~(seg_size - 1));                       // must be multiple of seg_size
 636   if (granularity>>log2_seg_size >= (1L<<sizeof(unsigned short)*8)) {
 637     granularity = ((1L<<(sizeof(unsigned short)*8))-1)<<log2_seg_size; // Limit: (64k-1) * seg_size
 638   }
 639   segment_granules = granularity == seg_size;
 640   size_t granules  = (size + (granularity-1))/granularity;
 641 
 642   printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (used blocks) for segment ", heapName);
 643   ast->print_cr("   The aggregate step takes an aggregated snapshot of the CodeHeap.\n"
 644                 "   Subsequent print functions create their output based on this snapshot.\n"
 645                 "   The CodeHeap is a living thing, and every effort has been made for the\n"
 646                 "   collected data to be consistent. Only the method names and signatures\n"
 647                 "   are retrieved at print time. That may lead to rare cases where the\n"
 648                 "   name of a method is no longer available, e.g. because it was unloaded.\n");
 649   ast->print_cr("   CodeHeap committed size " SIZE_FORMAT "K (" SIZE_FORMAT "M), reserved size " SIZE_FORMAT "K (" SIZE_FORMAT "M), %d%% occupied.",
 650                 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));
 651   ast->print_cr("   CodeHeap allocation segment size is " SIZE_FORMAT " bytes. This is the smallest possible granularity.", seg_size);
 652   ast->print_cr("   CodeHeap (committed part) is mapped to " SIZE_FORMAT " granules of size " SIZE_FORMAT " bytes.", granules, granularity);
 653   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);
 654   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));
 655   BUFFEREDSTREAM_FLUSH("\n")
 656 
 657 
 658   while (!done) {
 659     //---<  reset counters with every aggregation  >---
 660     nBlocks_t1       = 0;
 661     nBlocks_t2       = 0;
 662     nBlocks_alive    = 0;
 663     nBlocks_dead     = 0;
 664     nBlocks_unloaded = 0;
 665     nBlocks_stub     = 0;
 666 
 667     nBlocks_free     = 0;
 668     nBlocks_used     = 0;
 669     nBlocks_zomb     = 0;
 670     nBlocks_disconn  = 0;
 671     nBlocks_notentr  = 0;
 672 
 673     //---<  discard old arrays if size does not match  >---
 674     if (granules != alloc_granules) {
 675       discard_StatArray(out);
 676       discard_TopSizeArray(out);
 677     }
 678 
 679     //---<  allocate arrays if they don't yet exist, initialize  >---
 680     prepare_StatArray(out, granules, granularity, heapName);
 681     if (StatArray == NULL) {
 682       set_HeapStatGlobals(out, heapName);
 683       return;
 684     }
 685     prepare_TopSizeArray(out, maxTopSizeBlocks, heapName);
 686     prepare_SizeDistArray(out, nSizeDistElements, heapName);
 687 
 688     latest_compilation_id = CompileBroker::get_compilation_id();
 689     unsigned int highest_compilation_id = 0;
 690     size_t       usedSpace     = 0;
 691     size_t       t1Space       = 0;
 692     size_t       t2Space       = 0;
 693     size_t       aliveSpace    = 0;
 694     size_t       disconnSpace  = 0;
 695     size_t       notentrSpace  = 0;
 696     size_t       deadSpace     = 0;
 697     size_t       unloadedSpace = 0;
 698     size_t       stubSpace     = 0;
 699     size_t       freeSpace     = 0;
 700     size_t       maxFreeSize   = 0;
 701     HeapBlock*   maxFreeBlock  = NULL;
 702     bool         insane        = false;
 703 
 704     int64_t hotnessAccumulator = 0;
 705     unsigned int n_methods     = 0;
 706     avgTemp       = 0;
 707     minTemp       = (int)(res_size > M ? (res_size/M)*2 : 1);
 708     maxTemp       = -minTemp;
 709 
 710     for (HeapBlock *h = heap->first_block(); h != NULL && !insane; h = heap->next_block(h)) {
 711       unsigned int hb_len     = (unsigned int)h->length();  // despite being size_t, length can never overflow an unsigned int.
 712       size_t       hb_bytelen = ((size_t)hb_len)<<log2_seg_size;
 713       unsigned int ix_beg     = (unsigned int)(((char*)h-low_bound)/granule_size);
 714       unsigned int ix_end     = (unsigned int)(((char*)h-low_bound+(hb_bytelen-1))/granule_size);
 715       unsigned int compile_id = 0;
 716       CompLevel    comp_lvl   = CompLevel_none;
 717       compType     cType      = noComp;
 718       blobType     cbType     = noType;
 719 
 720       //---<  some sanity checks  >---
 721       // Do not assert here, just check, print error message and return.
 722       // This is a diagnostic function. It is not supposed to tear down the VM.
 723       if ((char*)h <  low_bound) {
 724         insane = true; ast->print_cr("Sanity check: HeapBlock @%p below low bound (%p)", (char*)h, low_bound);
 725       }
 726       if ((char*)h >  (low_bound + res_size)) {
 727         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside reserved range (%p)", (char*)h, low_bound + res_size);
 728       }
 729       if ((char*)h >  (low_bound + size)) {
 730         insane = true; ast->print_cr("Sanity check: HeapBlock @%p outside used range (%p)", (char*)h, low_bound + size);
 731       }
 732       if (ix_end   >= granules) {
 733         insane = true; ast->print_cr("Sanity check: end index (%d) out of bounds (" SIZE_FORMAT ")", ix_end, granules);
 734       }
 735       if (size     != heap->capacity()) {
 736         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);
 737       }
 738       if (ix_beg   >  ix_end) {
 739         insane = true; ast->print_cr("Sanity check: end index (%d) lower than begin index (%d)", ix_end, ix_beg);
 740       }
 741       if (insane) {
 742         BUFFEREDSTREAM_FLUSH("")
 743         continue;
 744       }
 745 
 746       if (h->free()) {
 747         nBlocks_free++;
 748         freeSpace    += hb_bytelen;
 749         if (hb_bytelen > maxFreeSize) {
 750           maxFreeSize   = hb_bytelen;
 751           maxFreeBlock  = h;
 752         }
 753       } else {
 754         update_SizeDistArray(out, hb_len);
 755         nBlocks_used++;
 756         usedSpace    += hb_bytelen;
 757         CodeBlob* cb  = (CodeBlob*)heap->find_start(h);
 758         cbType = get_cbType(cb);  // Will check for cb == NULL and other safety things.
 759         if (cbType != noType) {
 760           const char* blob_name  = os::strdup(cb->name());
 761           unsigned int nm_size   = 0;
 762           int temperature        = 0;
 763           nmethod*  nm = cb->as_nmethod_or_null();
 764           if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
 765             ResourceMark rm;
 766             Method* method = nm->method();
 767             if (nm->is_in_use()) {
 768               blob_name = os::strdup(method->name_and_sig_as_C_string());
 769             }
 770             if (nm->is_not_entrant()) {
 771               blob_name = os::strdup(method->name_and_sig_as_C_string());
 772             }
 773 
 774             nm_size    = nm->total_size();
 775             compile_id = nm->compile_id();
 776             comp_lvl   = (CompLevel)(nm->comp_level());
 777             if (nm->is_compiled_by_c1()) {
 778               cType = c1;
 779             }
 780             if (nm->is_compiled_by_c2()) {
 781               cType = c2;
 782             }
 783             if (nm->is_compiled_by_jvmci()) {
 784               cType = jvmci;
 785             }
 786             switch (cbType) {
 787               case nMethod_inuse: { // only for executable methods!!!
 788                 // space for these cbs is accounted for later.
 789                 temperature = nm->hotness_counter();
 790                 hotnessAccumulator += temperature;
 791                 n_methods++;
 792                 maxTemp = (temperature > maxTemp) ? temperature : maxTemp;
 793                 minTemp = (temperature < minTemp) ? temperature : minTemp;
 794                 break;
 795               }
 796               case nMethod_notused:
 797                 nBlocks_alive++;
 798                 nBlocks_disconn++;
 799                 aliveSpace     += hb_bytelen;
 800                 disconnSpace   += hb_bytelen;
 801                 break;
 802               case nMethod_notentrant:  // equivalent to nMethod_alive
 803                 nBlocks_alive++;
 804                 nBlocks_notentr++;
 805                 aliveSpace     += hb_bytelen;
 806                 notentrSpace   += hb_bytelen;
 807                 break;
 808               case nMethod_unloaded:
 809                 nBlocks_unloaded++;
 810                 unloadedSpace  += hb_bytelen;
 811                 break;
 812               case nMethod_dead:
 813                 nBlocks_dead++;
 814                 deadSpace      += hb_bytelen;
 815                 break;
 816               default:
 817                 break;
 818             }
 819           }
 820 
 821           //------------------------------------------
 822           //---<  register block in TopSizeArray  >---
 823           //------------------------------------------
 824           if (alloc_topSizeBlocks > 0) {
 825             if (used_topSizeBlocks == 0) {
 826               TopSizeArray[0].start       = h;
 827               TopSizeArray[0].blob_name   = blob_name;
 828               TopSizeArray[0].len         = hb_len;
 829               TopSizeArray[0].index       = tsbStopper;
 830               TopSizeArray[0].nm_size     = nm_size;
 831               TopSizeArray[0].temperature = temperature;
 832               TopSizeArray[0].compiler    = cType;
 833               TopSizeArray[0].level       = comp_lvl;
 834               TopSizeArray[0].type        = cbType;
 835               currMax    = hb_len;
 836               currMin    = hb_len;
 837               currMin_ix = 0;
 838               used_topSizeBlocks++;
 839               blob_name  = NULL; // indicate blob_name was consumed
 840             // This check roughly cuts 5000 iterations (JVM98, mixed, dbg, termination stats):
 841             } else if ((used_topSizeBlocks < alloc_topSizeBlocks) && (hb_len < currMin)) {
 842               //---<  all blocks in list are larger, but there is room left in array  >---
 843               TopSizeArray[currMin_ix].index = used_topSizeBlocks;
 844               TopSizeArray[used_topSizeBlocks].start       = h;
 845               TopSizeArray[used_topSizeBlocks].blob_name   = blob_name;
 846               TopSizeArray[used_topSizeBlocks].len         = hb_len;
 847               TopSizeArray[used_topSizeBlocks].index       = tsbStopper;
 848               TopSizeArray[used_topSizeBlocks].nm_size     = nm_size;
 849               TopSizeArray[used_topSizeBlocks].temperature = temperature;
 850               TopSizeArray[used_topSizeBlocks].compiler    = cType;
 851               TopSizeArray[used_topSizeBlocks].level       = comp_lvl;
 852               TopSizeArray[used_topSizeBlocks].type        = cbType;
 853               currMin    = hb_len;
 854               currMin_ix = used_topSizeBlocks;
 855               used_topSizeBlocks++;
 856               blob_name  = NULL; // indicate blob_name was consumed
 857             } else {
 858               // This check cuts total_iterations by a factor of 6 (JVM98, mixed, dbg, termination stats):
 859               //   We don't need to search the list if we know beforehand that the current block size is
 860               //   smaller than the currently recorded minimum and there is no free entry left in the list.
 861               if (!((used_topSizeBlocks == alloc_topSizeBlocks) && (hb_len <= currMin))) {
 862                 if (currMax < hb_len) {
 863                   currMax = hb_len;
 864                 }
 865                 unsigned int i;
 866                 unsigned int prev_i  = tsbStopper;
 867                 unsigned int limit_i =  0;
 868                 for (i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
 869                   if (limit_i++ >= alloc_topSizeBlocks) {
 870                     insane = true; break; // emergency exit
 871                   }
 872                   if (i >= used_topSizeBlocks)  {
 873                     insane = true; break; // emergency exit
 874                   }
 875                   total_iterations++;
 876                   if (TopSizeArray[i].len < hb_len) {
 877                     //---<  We want to insert here, element <i> is smaller than the current one  >---
 878                     if (used_topSizeBlocks < alloc_topSizeBlocks) { // still room for a new entry to insert
 879                       // old entry gets moved to the next free element of the array.
 880                       // That's necessary to keep the entry for the largest block at index 0.
 881                       // This move might cause the current minimum to be moved to another place
 882                       if (i == currMin_ix) {
 883                         assert(TopSizeArray[i].len == currMin, "sort error");
 884                         currMin_ix = used_topSizeBlocks;
 885                       }
 886                       memcpy((void*)&TopSizeArray[used_topSizeBlocks], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 887                       TopSizeArray[i].start       = h;
 888                       TopSizeArray[i].blob_name   = blob_name;
 889                       TopSizeArray[i].len         = hb_len;
 890                       TopSizeArray[i].index       = used_topSizeBlocks;
 891                       TopSizeArray[i].nm_size     = nm_size;
 892                       TopSizeArray[i].temperature = temperature;
 893                       TopSizeArray[i].compiler    = cType;
 894                       TopSizeArray[i].level       = comp_lvl;
 895                       TopSizeArray[i].type        = cbType;
 896                       used_topSizeBlocks++;
 897                       blob_name  = NULL; // indicate blob_name was consumed
 898                     } else { // no room for new entries, current block replaces entry for smallest block
 899                       //---<  Find last entry (entry for smallest remembered block)  >---
 900                       // We either want to insert right before the smallest entry, which is when <i>
 901                       // indexes the smallest entry. We then just overwrite the smallest entry.
 902                       // What's more likely:
 903                       // We want to insert somewhere in the list. The smallest entry (@<j>) then falls off the cliff.
 904                       // The element at the insert point <i> takes it's slot. The second-smallest entry now becomes smallest.
 905                       // Data of the current block is filled in at index <i>.
 906                       unsigned int      j  = i;
 907                       unsigned int prev_j  = tsbStopper;
 908                       unsigned int limit_j = 0;
 909                       while (TopSizeArray[j].index != tsbStopper) {
 910                         if (limit_j++ >= alloc_topSizeBlocks) {
 911                           insane = true; break; // emergency exit
 912                         }
 913                         if (j >= used_topSizeBlocks)  {
 914                           insane = true; break; // emergency exit
 915                         }
 916                         total_iterations++;
 917                         prev_j = j;
 918                         j      = TopSizeArray[j].index;
 919                       }
 920                       if (!insane) {
 921                         if (TopSizeArray[j].blob_name != NULL) {
 922                           os::free((void*)TopSizeArray[j].blob_name);
 923                         }
 924                         if (prev_j == tsbStopper) {
 925                           //---<  Above while loop did not iterate, we already are the min entry  >---
 926                           //---<  We have to just replace the smallest entry                      >---
 927                           currMin    = hb_len;
 928                           currMin_ix = j;
 929                           TopSizeArray[j].start       = h;
 930                           TopSizeArray[j].blob_name   = blob_name;
 931                           TopSizeArray[j].len         = hb_len;
 932                           TopSizeArray[j].index       = tsbStopper; // already set!!
 933                           TopSizeArray[i].nm_size     = nm_size;
 934                           TopSizeArray[i].temperature = temperature;
 935                           TopSizeArray[j].compiler    = cType;
 936                           TopSizeArray[j].level       = comp_lvl;
 937                           TopSizeArray[j].type        = cbType;
 938                         } else {
 939                           //---<  second-smallest entry is now smallest  >---
 940                           TopSizeArray[prev_j].index = tsbStopper;
 941                           currMin    = TopSizeArray[prev_j].len;
 942                           currMin_ix = prev_j;
 943                           //---<  previously smallest entry gets overwritten  >---
 944                           memcpy((void*)&TopSizeArray[j], (void*)&TopSizeArray[i], sizeof(TopSizeBlk));
 945                           TopSizeArray[i].start       = h;
 946                           TopSizeArray[i].blob_name   = blob_name;
 947                           TopSizeArray[i].len         = hb_len;
 948                           TopSizeArray[i].index       = j;
 949                           TopSizeArray[i].nm_size     = nm_size;
 950                           TopSizeArray[i].temperature = temperature;
 951                           TopSizeArray[i].compiler    = cType;
 952                           TopSizeArray[i].level       = comp_lvl;
 953                           TopSizeArray[i].type        = cbType;
 954                         }
 955                         blob_name  = NULL; // indicate blob_name was consumed
 956                       } // insane
 957                     }
 958                     break;
 959                   }
 960                   prev_i = i;
 961                 }
 962                 if (insane) {
 963                   // Note: regular analysis could probably continue by resetting "insane" flag.
 964                   out->print_cr("Possible loop in TopSizeBlocks list detected. Analysis aborted.");
 965                   discard_TopSizeArray(out);
 966                 }
 967               }
 968             }
 969           }
 970           if (blob_name != NULL) {
 971             os::free((void*)blob_name);
 972             blob_name = NULL;
 973           }
 974           //----------------------------------------------
 975           //---<  END register block in TopSizeArray  >---
 976           //----------------------------------------------
 977         } else {
 978           nBlocks_zomb++;
 979         }
 980 
 981         if (ix_beg == ix_end) {
 982           StatArray[ix_beg].type = cbType;
 983           switch (cbType) {
 984             case nMethod_inuse:
 985               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
 986               if (comp_lvl < CompLevel_full_optimization) {
 987                 nBlocks_t1++;
 988                 t1Space   += hb_bytelen;
 989                 StatArray[ix_beg].t1_count++;
 990                 StatArray[ix_beg].t1_space += (unsigned short)hb_len;
 991                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
 992               } else {
 993                 nBlocks_t2++;
 994                 t2Space   += hb_bytelen;
 995                 StatArray[ix_beg].t2_count++;
 996                 StatArray[ix_beg].t2_space += (unsigned short)hb_len;
 997                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
 998               }
 999               StatArray[ix_beg].level     = comp_lvl;
1000               StatArray[ix_beg].compiler  = cType;
1001               break;
1002             case nMethod_alive:
1003               StatArray[ix_beg].tx_count++;
1004               StatArray[ix_beg].tx_space += (unsigned short)hb_len;
1005               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
1006               StatArray[ix_beg].level     = comp_lvl;
1007               StatArray[ix_beg].compiler  = cType;
1008               break;
1009             case nMethod_dead:
1010             case nMethod_unloaded:
1011               StatArray[ix_beg].dead_count++;
1012               StatArray[ix_beg].dead_space += (unsigned short)hb_len;
1013               break;
1014             default:
1015               // must be a stub, if it's not a dead or alive nMethod
1016               nBlocks_stub++;
1017               stubSpace   += hb_bytelen;
1018               StatArray[ix_beg].stub_count++;
1019               StatArray[ix_beg].stub_space += (unsigned short)hb_len;
1020               break;
1021           }
1022         } else {
1023           unsigned int beg_space = (unsigned int)(granule_size - ((char*)h - low_bound - ix_beg*granule_size));
1024           unsigned int end_space = (unsigned int)(hb_bytelen - beg_space - (ix_end-ix_beg-1)*granule_size);
1025           beg_space = beg_space>>log2_seg_size;  // store in units of _segment_size
1026           end_space = end_space>>log2_seg_size;  // store in units of _segment_size
1027           StatArray[ix_beg].type = cbType;
1028           StatArray[ix_end].type = cbType;
1029           switch (cbType) {
1030             case nMethod_inuse:
1031               highest_compilation_id = (highest_compilation_id >= compile_id) ? highest_compilation_id : compile_id;
1032               if (comp_lvl < CompLevel_full_optimization) {
1033                 nBlocks_t1++;
1034                 t1Space   += hb_bytelen;
1035                 StatArray[ix_beg].t1_count++;
1036                 StatArray[ix_beg].t1_space += (unsigned short)beg_space;
1037                 StatArray[ix_beg].t1_age    = StatArray[ix_beg].t1_age < compile_id ? compile_id : StatArray[ix_beg].t1_age;
1038 
1039                 StatArray[ix_end].t1_count++;
1040                 StatArray[ix_end].t1_space += (unsigned short)end_space;
1041                 StatArray[ix_end].t1_age    = StatArray[ix_end].t1_age < compile_id ? compile_id : StatArray[ix_end].t1_age;
1042               } else {
1043                 nBlocks_t2++;
1044                 t2Space   += hb_bytelen;
1045                 StatArray[ix_beg].t2_count++;
1046                 StatArray[ix_beg].t2_space += (unsigned short)beg_space;
1047                 StatArray[ix_beg].t2_age    = StatArray[ix_beg].t2_age < compile_id ? compile_id : StatArray[ix_beg].t2_age;
1048 
1049                 StatArray[ix_end].t2_count++;
1050                 StatArray[ix_end].t2_space += (unsigned short)end_space;
1051                 StatArray[ix_end].t2_age    = StatArray[ix_end].t2_age < compile_id ? compile_id : StatArray[ix_end].t2_age;
1052               }
1053               StatArray[ix_beg].level     = comp_lvl;
1054               StatArray[ix_beg].compiler  = cType;
1055               StatArray[ix_end].level     = comp_lvl;
1056               StatArray[ix_end].compiler  = cType;
1057               break;
1058             case nMethod_alive:
1059               StatArray[ix_beg].tx_count++;
1060               StatArray[ix_beg].tx_space += (unsigned short)beg_space;
1061               StatArray[ix_beg].tx_age    = StatArray[ix_beg].tx_age < compile_id ? compile_id : StatArray[ix_beg].tx_age;
1062 
1063               StatArray[ix_end].tx_count++;
1064               StatArray[ix_end].tx_space += (unsigned short)end_space;
1065               StatArray[ix_end].tx_age    = StatArray[ix_end].tx_age < compile_id ? compile_id : StatArray[ix_end].tx_age;
1066 
1067               StatArray[ix_beg].level     = comp_lvl;
1068               StatArray[ix_beg].compiler  = cType;
1069               StatArray[ix_end].level     = comp_lvl;
1070               StatArray[ix_end].compiler  = cType;
1071               break;
1072             case nMethod_dead:
1073             case nMethod_unloaded:
1074               StatArray[ix_beg].dead_count++;
1075               StatArray[ix_beg].dead_space += (unsigned short)beg_space;
1076               StatArray[ix_end].dead_count++;
1077               StatArray[ix_end].dead_space += (unsigned short)end_space;
1078               break;
1079             default:
1080               // must be a stub, if it's not a dead or alive nMethod
1081               nBlocks_stub++;
1082               stubSpace   += hb_bytelen;
1083               StatArray[ix_beg].stub_count++;
1084               StatArray[ix_beg].stub_space += (unsigned short)beg_space;
1085               StatArray[ix_end].stub_count++;
1086               StatArray[ix_end].stub_space += (unsigned short)end_space;
1087               break;
1088           }
1089           for (unsigned int ix = ix_beg+1; ix < ix_end; ix++) {
1090             StatArray[ix].type = cbType;
1091             switch (cbType) {
1092               case nMethod_inuse:
1093                 if (comp_lvl < CompLevel_full_optimization) {
1094                   StatArray[ix].t1_count++;
1095                   StatArray[ix].t1_space += (unsigned short)(granule_size>>log2_seg_size);
1096                   StatArray[ix].t1_age    = StatArray[ix].t1_age < compile_id ? compile_id : StatArray[ix].t1_age;
1097                 } else {
1098                   StatArray[ix].t2_count++;
1099                   StatArray[ix].t2_space += (unsigned short)(granule_size>>log2_seg_size);
1100                   StatArray[ix].t2_age    = StatArray[ix].t2_age < compile_id ? compile_id : StatArray[ix].t2_age;
1101                 }
1102                 StatArray[ix].level     = comp_lvl;
1103                 StatArray[ix].compiler  = cType;
1104                 break;
1105               case nMethod_alive:
1106                 StatArray[ix].tx_count++;
1107                 StatArray[ix].tx_space += (unsigned short)(granule_size>>log2_seg_size);
1108                 StatArray[ix].tx_age    = StatArray[ix].tx_age < compile_id ? compile_id : StatArray[ix].tx_age;
1109                 StatArray[ix].level     = comp_lvl;
1110                 StatArray[ix].compiler  = cType;
1111                 break;
1112               case nMethod_dead:
1113               case nMethod_unloaded:
1114                 StatArray[ix].dead_count++;
1115                 StatArray[ix].dead_space += (unsigned short)(granule_size>>log2_seg_size);
1116                 break;
1117               default:
1118                 // must be a stub, if it's not a dead or alive nMethod
1119                 StatArray[ix].stub_count++;
1120                 StatArray[ix].stub_space += (unsigned short)(granule_size>>log2_seg_size);
1121                 break;
1122             }
1123           }
1124         }
1125       }
1126     }
1127     done = true;
1128 
1129     if (!insane) {
1130       // There is a risk for this block (because it contains many print statements) to get
1131       // interspersed with print data from other threads. We take this risk intentionally.
1132       // Getting stalled waiting for tty_lock while holding the CodeCache_lock is not desirable.
1133       printBox(ast, '-', "Global CodeHeap statistics for segment ", heapName);
1134       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);
1135       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);
1136       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);
1137       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);
1138       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);
1139       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);
1140       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);
1141       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);
1142       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);
1143       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);
1144       ast->print_cr("ZombieBlocks     = %8d. These are HeapBlocks which could not be identified as CodeBlobs.", nBlocks_zomb);
1145       ast->cr();
1146       ast->print_cr("Segment start          = " INTPTR_FORMAT ", used space      = " SIZE_FORMAT_W(8)"k", p2i(low_bound), size/K);
1147       ast->print_cr("Segment end (used)     = " INTPTR_FORMAT ", remaining space = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + size, (res_size - size)/K);
1148       ast->print_cr("Segment end (reserved) = " INTPTR_FORMAT ", reserved space  = " SIZE_FORMAT_W(8)"k", p2i(low_bound) + res_size, res_size/K);
1149       ast->cr();
1150       ast->print_cr("latest allocated compilation id = %d", latest_compilation_id);
1151       ast->print_cr("highest observed compilation id = %d", highest_compilation_id);
1152       ast->print_cr("Building TopSizeList iterations = %ld", total_iterations);
1153       ast->cr();
1154 
1155       int             reset_val = NMethodSweeper::hotness_counter_reset_val();
1156       double reverse_free_ratio = (res_size > size) ? (double)res_size/(double)(res_size-size) : (double)res_size;
1157       printBox(ast, '-', "Method hotness information at time of this analysis", NULL);
1158       ast->print_cr("Highest possible method temperature:          %12d", reset_val);
1159       ast->print_cr("Threshold for method to be considered 'cold': %12.3f", -reset_val + reverse_free_ratio * NmethodSweepActivity);
1160       if (n_methods > 0) {
1161         avgTemp = hotnessAccumulator/n_methods;
1162         ast->print_cr("min. hotness = %6d", minTemp);
1163         ast->print_cr("avg. hotness = %6d", avgTemp);
1164         ast->print_cr("max. hotness = %6d", maxTemp);
1165       } else {
1166         avgTemp = 0;
1167         ast->print_cr("No hotness data available");
1168       }
1169       BUFFEREDSTREAM_FLUSH("\n")
1170 
1171       // This loop is intentionally printing directly to "out".
1172       // It should not print anything, anyway.
1173       out->print("Verifying collected data...");
1174       size_t granule_segs = granule_size>>log2_seg_size;
1175       for (unsigned int ix = 0; ix < granules; ix++) {
1176         if (StatArray[ix].t1_count   > granule_segs) {
1177           out->print_cr("t1_count[%d]   = %d", ix, StatArray[ix].t1_count);
1178         }
1179         if (StatArray[ix].t2_count   > granule_segs) {
1180           out->print_cr("t2_count[%d]   = %d", ix, StatArray[ix].t2_count);
1181         }
1182         if (StatArray[ix].tx_count   > granule_segs) {
1183           out->print_cr("tx_count[%d]   = %d", ix, StatArray[ix].tx_count);
1184         }
1185         if (StatArray[ix].stub_count > granule_segs) {
1186           out->print_cr("stub_count[%d] = %d", ix, StatArray[ix].stub_count);
1187         }
1188         if (StatArray[ix].dead_count > granule_segs) {
1189           out->print_cr("dead_count[%d] = %d", ix, StatArray[ix].dead_count);
1190         }
1191         if (StatArray[ix].t1_space   > granule_segs) {
1192           out->print_cr("t1_space[%d]   = %d", ix, StatArray[ix].t1_space);
1193         }
1194         if (StatArray[ix].t2_space   > granule_segs) {
1195           out->print_cr("t2_space[%d]   = %d", ix, StatArray[ix].t2_space);
1196         }
1197         if (StatArray[ix].tx_space   > granule_segs) {
1198           out->print_cr("tx_space[%d]   = %d", ix, StatArray[ix].tx_space);
1199         }
1200         if (StatArray[ix].stub_space > granule_segs) {
1201           out->print_cr("stub_space[%d] = %d", ix, StatArray[ix].stub_space);
1202         }
1203         if (StatArray[ix].dead_space > granule_segs) {
1204           out->print_cr("dead_space[%d] = %d", ix, StatArray[ix].dead_space);
1205         }
1206         //   this cast is awful! I need it because NT/Intel reports a signed/unsigned mismatch.
1207         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) {
1208           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);
1209         }
1210         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) {
1211           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);
1212         }
1213       }
1214 
1215       // This loop is intentionally printing directly to "out".
1216       // It should not print anything, anyway.
1217       if (used_topSizeBlocks > 0) {
1218         unsigned int j = 0;
1219         if (TopSizeArray[0].len != currMax) {
1220           out->print_cr("currMax(%d) differs from TopSizeArray[0].len(%d)", currMax, TopSizeArray[0].len);
1221         }
1222         for (unsigned int i = 0; (TopSizeArray[i].index != tsbStopper) && (j++ < alloc_topSizeBlocks); i = TopSizeArray[i].index) {
1223           if (TopSizeArray[i].len < TopSizeArray[TopSizeArray[i].index].len) {
1224             out->print_cr("sort error at index %d: %d !>= %d", i, TopSizeArray[i].len, TopSizeArray[TopSizeArray[i].index].len);
1225           }
1226         }
1227         if (j >= alloc_topSizeBlocks) {
1228           out->print_cr("Possible loop in TopSizeArray chaining!\n  allocBlocks = %d, usedBlocks = %d", alloc_topSizeBlocks, used_topSizeBlocks);
1229           for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1230             out->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1231           }
1232         }
1233       }
1234       out->print_cr("...done\n\n");
1235     } else {
1236       // insane heap state detected. Analysis data incomplete. Just throw it away.
1237       discard_StatArray(out);
1238       discard_TopSizeArray(out);
1239     }
1240   }
1241 
1242 
1243   done        = false;
1244   while (!done && (nBlocks_free > 0)) {
1245 
1246     printBox(ast, '=', "C O D E   H E A P   A N A L Y S I S   (free blocks) for segment ", heapName);
1247     ast->print_cr("   The aggregate step collects information about all free blocks in CodeHeap.\n"
1248                   "   Subsequent print functions create their output based on this snapshot.\n");
1249     ast->print_cr("   Free space in %s is distributed over %d free blocks.", heapName, nBlocks_free);
1250     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);
1251     BUFFEREDSTREAM_FLUSH("\n")
1252 
1253     //----------------------------------------
1254     //--  Prepare the FreeArray of FreeBlks --
1255     //----------------------------------------
1256 
1257     //---< discard old array if size does not match  >---
1258     if (nBlocks_free != alloc_freeBlocks) {
1259       discard_FreeArray(out);
1260     }
1261 
1262     prepare_FreeArray(out, nBlocks_free, heapName);
1263     if (FreeArray == NULL) {
1264       done = true;
1265       continue;
1266     }
1267 
1268     //----------------------------------------
1269     //--  Collect all FreeBlks in FreeArray --
1270     //----------------------------------------
1271 
1272     unsigned int ix = 0;
1273     FreeBlock* cur  = heap->freelist();
1274 
1275     while (cur != NULL) {
1276       if (ix < alloc_freeBlocks) { // don't index out of bounds if _freelist has more blocks than anticipated
1277         FreeArray[ix].start = cur;
1278         FreeArray[ix].len   = (unsigned int)(cur->length()<<log2_seg_size);
1279         FreeArray[ix].index = ix;
1280       }
1281       cur  = cur->link();
1282       ix++;
1283     }
1284     if (ix != alloc_freeBlocks) {
1285       ast->print_cr("Free block count mismatch. Expected %d free blocks, but found %d.", alloc_freeBlocks, ix);
1286       ast->print_cr("I will update the counter and retry data collection");
1287       BUFFEREDSTREAM_FLUSH("\n")
1288       nBlocks_free = ix;
1289       continue;
1290     }
1291     done = true;
1292   }
1293 
1294   if (!done || (nBlocks_free == 0)) {
1295     if (nBlocks_free == 0) {
1296       printBox(ast, '-', "no free blocks found in ", heapName);
1297     } else if (!done) {
1298       ast->print_cr("Free block count mismatch could not be resolved.");
1299       ast->print_cr("Try to run \"aggregate\" function to update counters");
1300     }
1301     BUFFEREDSTREAM_FLUSH("")
1302 
1303     //---< discard old array and update global values  >---
1304     discard_FreeArray(out);
1305     set_HeapStatGlobals(out, heapName);
1306     return;
1307   }
1308 
1309   //---<  calculate and fill remaining fields  >---
1310   if (FreeArray != NULL) {
1311     // This loop is intentionally printing directly to "out".
1312     // It should not print anything, anyway.
1313     for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1314       size_t lenSum = 0;
1315       FreeArray[ix].gap = (unsigned int)((address)FreeArray[ix+1].start - ((address)FreeArray[ix].start + FreeArray[ix].len));
1316       for (HeapBlock *h = heap->next_block(FreeArray[ix].start); (h != NULL) && (h != FreeArray[ix+1].start); h = heap->next_block(h)) {
1317         CodeBlob *cb  = (CodeBlob*)(heap->find_start(h));
1318         if ((cb != NULL) && !cb->is_nmethod()) { // checks equivalent to those in get_cbType()
1319           FreeArray[ix].stubs_in_gap = true;
1320         }
1321         FreeArray[ix].n_gapBlocks++;
1322         lenSum += h->length()<<log2_seg_size;
1323         if (((address)h < ((address)FreeArray[ix].start+FreeArray[ix].len)) || (h >= FreeArray[ix+1].start)) {
1324           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);
1325         }
1326       }
1327       if (lenSum != FreeArray[ix].gap) {
1328         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);
1329       }
1330     }
1331   }
1332   set_HeapStatGlobals(out, heapName);
1333 
1334   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);
1335   BUFFEREDSTREAM_FLUSH("\n")
1336 }
1337 
1338 
1339 void CodeHeapState::print_usedSpace(outputStream* out, CodeHeap* heap) {
1340   if (!initialization_complete) {
1341     return;
1342   }
1343 
1344   const char* heapName   = get_heapName(heap);
1345   get_HeapStatGlobals(out, heapName);
1346 
1347   if ((StatArray == NULL) || (TopSizeArray == NULL) || (used_topSizeBlocks == 0)) {
1348     return;
1349   }
1350   BUFFEREDSTREAM_DECL(ast, out)
1351 
1352   {
1353     printBox(ast, '=', "U S E D   S P A C E   S T A T I S T I C S   for ", heapName);
1354     ast->print_cr("Note: The Top%d list of the largest used blocks associates method names\n"
1355                   "      and other identifying information with the block size data.\n"
1356                   "\n"
1357                   "      Method names are dynamically retrieved from the code cache at print time.\n"
1358                   "      Due to the living nature of the code cache and because the CodeCache_lock\n"
1359                   "      is not continuously held, the displayed name might be wrong or no name\n"
1360                   "      might be found at all. The likelihood for that to happen increases\n"
1361                   "      over time passed between analysis and print step.\n", used_topSizeBlocks);
1362     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1363   }
1364 
1365   //----------------------------
1366   //--  Print Top Used Blocks --
1367   //----------------------------
1368   {
1369     char*     low_bound  = heap->low_boundary();
1370 
1371     printBox(ast, '-', "Largest Used Blocks in ", heapName);
1372     print_blobType_legend(ast);
1373 
1374     ast->fill_to(51);
1375     ast->print("%4s", "blob");
1376     ast->fill_to(56);
1377     ast->print("%9s", "compiler");
1378     ast->fill_to(66);
1379     ast->print_cr("%6s", "method");
1380     ast->print_cr("%18s %13s %17s %4s %9s  %5s %s",      "Addr(module)      ", "offset", "size", "type", " type lvl", " temp", "Name");
1381     BUFFEREDSTREAM_FLUSH_LOCKED("")
1382 
1383     //---<  print Top Ten Used Blocks  >---
1384     if (used_topSizeBlocks > 0) {
1385       unsigned int printed_topSizeBlocks = 0;
1386       for (unsigned int i = 0; i != tsbStopper; i = TopSizeArray[i].index) {
1387         printed_topSizeBlocks++;
1388         if (TopSizeArray[i].blob_name == NULL) {
1389           TopSizeArray[i].blob_name = os::strdup("unnamed blob or blob name unavailable");
1390         }
1391         // heap->find_start() is safe. Only works on _segmap.
1392         // Returns NULL or void*. Returned CodeBlob may be uninitialized.
1393         HeapBlock* heapBlock = TopSizeArray[i].start;
1394         CodeBlob*  this_blob = (CodeBlob*)(heap->find_start(heapBlock));
1395         if (this_blob != NULL) {
1396           //---<  access these fields only if we own the CodeCache_lock  >---
1397           //---<  blob address  >---
1398           ast->print(INTPTR_FORMAT, p2i(this_blob));
1399           ast->fill_to(19);
1400           //---<  blob offset from CodeHeap begin  >---
1401           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
1402           ast->fill_to(33);
1403         } else {
1404           //---<  block address  >---
1405           ast->print(INTPTR_FORMAT, p2i(TopSizeArray[i].start));
1406           ast->fill_to(19);
1407           //---<  block offset from CodeHeap begin  >---
1408           ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)TopSizeArray[i].start-low_bound));
1409           ast->fill_to(33);
1410         }
1411 
1412         //---<  print size, name, and signature (for nMethods)  >---
1413         bool is_nmethod = TopSizeArray[i].nm_size > 0;
1414         if (is_nmethod) {
1415           //---<  nMethod size in hex  >---
1416           ast->print(PTR32_FORMAT, TopSizeArray[i].nm_size);
1417           ast->print("(" SIZE_FORMAT_W(4) "K)", TopSizeArray[i].nm_size/K);
1418           ast->fill_to(51);
1419           ast->print("  %c", blobTypeChar[TopSizeArray[i].type]);
1420           //---<  compiler information  >---
1421           ast->fill_to(56);
1422           ast->print("%5s %3d", compTypeName[TopSizeArray[i].compiler], TopSizeArray[i].level);
1423           //---<  method temperature  >---
1424           ast->fill_to(67);
1425           ast->print("%5d", TopSizeArray[i].temperature);
1426           //---<  name and signature  >---
1427           ast->fill_to(67+6);
1428           if (TopSizeArray[i].type == nMethod_dead) {
1429             ast->print(" zombie method ");
1430           }
1431           ast->print("%s", TopSizeArray[i].blob_name);
1432         } else {
1433           //---<  block size in hex  >---
1434           ast->print(PTR32_FORMAT, (unsigned int)(TopSizeArray[i].len<<log2_seg_size));
1435           ast->print("(" SIZE_FORMAT_W(4) "K)", (TopSizeArray[i].len<<log2_seg_size)/K);
1436           //---<  no compiler information  >---
1437           ast->fill_to(56);
1438           //---<  name and signature  >---
1439           ast->fill_to(67+6);
1440           ast->print("%s", TopSizeArray[i].blob_name);
1441         }
1442         ast->cr();
1443         BUFFEREDSTREAM_FLUSH_AUTO("")
1444       }
1445       if (used_topSizeBlocks != printed_topSizeBlocks) {
1446         ast->print_cr("used blocks: %d, printed blocks: %d", used_topSizeBlocks, printed_topSizeBlocks);
1447         for (unsigned int i = 0; i < alloc_topSizeBlocks; i++) {
1448           ast->print_cr("  TopSizeArray[%d].index = %d, len = %d", i, TopSizeArray[i].index, TopSizeArray[i].len);
1449           BUFFEREDSTREAM_FLUSH_AUTO("")
1450         }
1451       }
1452       BUFFEREDSTREAM_FLUSH("\n\n")
1453     }
1454   }
1455 
1456   //-----------------------------
1457   //--  Print Usage Histogram  --
1458   //-----------------------------
1459 
1460   if (SizeDistributionArray != NULL) {
1461     unsigned long total_count = 0;
1462     unsigned long total_size  = 0;
1463     const unsigned long pctFactor = 200;
1464 
1465     for (unsigned int i = 0; i < nSizeDistElements; i++) {
1466       total_count += SizeDistributionArray[i].count;
1467       total_size  += SizeDistributionArray[i].lenSum;
1468     }
1469 
1470     if ((total_count > 0) && (total_size > 0)) {
1471       printBox(ast, '-', "Block count histogram for ", heapName);
1472       ast->print_cr("Note: The histogram indicates how many blocks (as a percentage\n"
1473                     "      of all blocks) have a size in the given range.\n"
1474                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1475       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1476       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1477       BUFFEREDSTREAM_FLUSH_LOCKED("")
1478 
1479       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1480       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1481         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1482           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1483                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1484                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1485                     );
1486         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1487           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1488                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1489                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1490                     );
1491         } else {
1492           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1493                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1494                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1495                     );
1496         }
1497         ast->print(" %8d | %8d |",
1498                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1499                    SizeDistributionArray[i].count);
1500 
1501         unsigned int percent = pctFactor*SizeDistributionArray[i].count/total_count;
1502         for (unsigned int j = 1; j <= percent; j++) {
1503           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1504         }
1505         ast->cr();
1506         BUFFEREDSTREAM_FLUSH_AUTO("")
1507       }
1508       ast->print_cr("----------------------------+----------+");
1509       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1510 
1511       printBox(ast, '-', "Contribution per size range to total size for ", heapName);
1512       ast->print_cr("Note: The histogram indicates how much space (as a percentage of all\n"
1513                     "      occupied space) is used by the blocks in the given size range.\n"
1514                     "      %ld characters are printed per percentage point.\n", pctFactor/100);
1515       ast->print_cr("total size   of all blocks: %7ldM", (total_size<<log2_seg_size)/M);
1516       ast->print_cr("total number of all blocks: %7ld\n", total_count);
1517       BUFFEREDSTREAM_FLUSH_LOCKED("")
1518 
1519       ast->print_cr("[Size Range)------avg.-size-+----count-+");
1520       for (unsigned int i = 0; i < nSizeDistElements; i++) {
1521         if (SizeDistributionArray[i].rangeStart<<log2_seg_size < K) {
1522           ast->print("[" SIZE_FORMAT_W(5) " .." SIZE_FORMAT_W(5) " ): "
1523                     ,(size_t)(SizeDistributionArray[i].rangeStart<<log2_seg_size)
1524                     ,(size_t)(SizeDistributionArray[i].rangeEnd<<log2_seg_size)
1525                     );
1526         } else if (SizeDistributionArray[i].rangeStart<<log2_seg_size < M) {
1527           ast->print("[" SIZE_FORMAT_W(5) "K.." SIZE_FORMAT_W(5) "K): "
1528                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/K
1529                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/K
1530                     );
1531         } else {
1532           ast->print("[" SIZE_FORMAT_W(5) "M.." SIZE_FORMAT_W(5) "M): "
1533                     ,(SizeDistributionArray[i].rangeStart<<log2_seg_size)/M
1534                     ,(SizeDistributionArray[i].rangeEnd<<log2_seg_size)/M
1535                     );
1536         }
1537         ast->print(" %8d | %8d |",
1538                    SizeDistributionArray[i].count > 0 ? (SizeDistributionArray[i].lenSum<<log2_seg_size)/SizeDistributionArray[i].count : 0,
1539                    SizeDistributionArray[i].count);
1540 
1541         unsigned int percent = pctFactor*(unsigned long)SizeDistributionArray[i].lenSum/total_size;
1542         for (unsigned int j = 1; j <= percent; j++) {
1543           ast->print("%c", (j%((pctFactor/100)*10) == 0) ? ('0'+j/(((unsigned int)pctFactor/100)*10)) : '*');
1544         }
1545         ast->cr();
1546         BUFFEREDSTREAM_FLUSH_AUTO("")
1547       }
1548       ast->print_cr("----------------------------+----------+");
1549       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1550     }
1551   }
1552 }
1553 
1554 
1555 void CodeHeapState::print_freeSpace(outputStream* out, CodeHeap* heap) {
1556   if (!initialization_complete) {
1557     return;
1558   }
1559 
1560   const char* heapName   = get_heapName(heap);
1561   get_HeapStatGlobals(out, heapName);
1562 
1563   if ((StatArray == NULL) || (FreeArray == NULL) || (alloc_granules == 0)) {
1564     return;
1565   }
1566   BUFFEREDSTREAM_DECL(ast, out)
1567 
1568   {
1569     printBox(ast, '=', "F R E E   S P A C E   S T A T I S T I C S   for ", heapName);
1570     ast->print_cr("Note: in this context, a gap is the occupied space between two free blocks.\n"
1571                   "      Those gaps are of interest if there is a chance that they become\n"
1572                   "      unoccupied, e.g. by class unloading. Then, the two adjacent free\n"
1573                   "      blocks, together with the now unoccupied space, form a new, large\n"
1574                   "      free block.");
1575     BUFFEREDSTREAM_FLUSH_LOCKED("\n")
1576   }
1577 
1578   {
1579     printBox(ast, '-', "List of all Free Blocks in ", heapName);
1580 
1581     unsigned int ix = 0;
1582     for (ix = 0; ix < alloc_freeBlocks-1; ix++) {
1583       ast->print(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT ",", p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1584       ast->fill_to(38);
1585       ast->print("Gap[%4d..%4d]: " HEX32_FORMAT " bytes,", ix, ix+1, FreeArray[ix].gap);
1586       ast->fill_to(71);
1587       ast->print("block count: %6d", FreeArray[ix].n_gapBlocks);
1588       if (FreeArray[ix].stubs_in_gap) {
1589         ast->print(" !! permanent gap, contains stubs and/or blobs !!");
1590       }
1591       ast->cr();
1592       BUFFEREDSTREAM_FLUSH_AUTO("")
1593     }
1594     ast->print_cr(INTPTR_FORMAT ": Len[%4d] = " HEX32_FORMAT, p2i(FreeArray[ix].start), ix, FreeArray[ix].len);
1595     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1596   }
1597 
1598 
1599   //-----------------------------------------
1600   //--  Find and Print Top Ten Free Blocks --
1601   //-----------------------------------------
1602 
1603   //---<  find Top Ten Free Blocks  >---
1604   const unsigned int nTop = 10;
1605   unsigned int  currMax10 = 0;
1606   struct FreeBlk* FreeTopTen[nTop];
1607   memset(FreeTopTen, 0, sizeof(FreeTopTen));
1608 
1609   for (unsigned int ix = 0; ix < alloc_freeBlocks; ix++) {
1610     if (FreeArray[ix].len > currMax10) {  // larger than the ten largest found so far
1611       unsigned int currSize = FreeArray[ix].len;
1612 
1613       unsigned int iy;
1614       for (iy = 0; iy < nTop && FreeTopTen[iy] != NULL; iy++) {
1615         if (FreeTopTen[iy]->len < currSize) {
1616           for (unsigned int iz = nTop-1; iz > iy; iz--) { // make room to insert new free block
1617             FreeTopTen[iz] = FreeTopTen[iz-1];
1618           }
1619           FreeTopTen[iy] = &FreeArray[ix];        // insert new free block
1620           if (FreeTopTen[nTop-1] != NULL) {
1621             currMax10 = FreeTopTen[nTop-1]->len;
1622           }
1623           break; // done with this, check next free block
1624         }
1625       }
1626       if (iy >= nTop) {
1627         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1628                       currSize, currMax10);
1629         continue;
1630       }
1631       if (FreeTopTen[iy] == NULL) {
1632         FreeTopTen[iy] = &FreeArray[ix];
1633         if (iy == (nTop-1)) {
1634           currMax10 = currSize;
1635         }
1636       }
1637     }
1638   }
1639   BUFFEREDSTREAM_FLUSH_AUTO("")
1640 
1641   {
1642     printBox(ast, '-', "Top Ten Free Blocks in ", heapName);
1643 
1644     //---<  print Top Ten Free Blocks  >---
1645     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTen[iy] != NULL); iy++) {
1646       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTen[iy]->index, FreeTopTen[iy]->len);
1647       ast->fill_to(39);
1648       if (FreeTopTen[iy]->index == (alloc_freeBlocks-1)) {
1649         ast->print("last free block in list.");
1650       } else {
1651         ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTen[iy]->gap);
1652         ast->fill_to(63);
1653         ast->print("#blocks (in gap) %d", FreeTopTen[iy]->n_gapBlocks);
1654       }
1655       ast->cr();
1656       BUFFEREDSTREAM_FLUSH_AUTO("")
1657     }
1658   }
1659   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1660 
1661 
1662   //--------------------------------------------------------
1663   //--  Find and Print Top Ten Free-Occupied-Free Triples --
1664   //--------------------------------------------------------
1665 
1666   //---<  find and print Top Ten Triples (Free-Occupied-Free)  >---
1667   currMax10 = 0;
1668   struct FreeBlk  *FreeTopTenTriple[nTop];
1669   memset(FreeTopTenTriple, 0, sizeof(FreeTopTenTriple));
1670 
1671   for (unsigned int ix = 0; ix < alloc_freeBlocks-1; ix++) {
1672     // If there are stubs in the gap, this gap will never become completely free.
1673     // The triple will thus never merge to one free block.
1674     unsigned int lenTriple  = FreeArray[ix].len + (FreeArray[ix].stubs_in_gap ? 0 : FreeArray[ix].gap + FreeArray[ix+1].len);
1675     FreeArray[ix].len = lenTriple;
1676     if (lenTriple > currMax10) {  // larger than the ten largest found so far
1677 
1678       unsigned int iy;
1679       for (iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1680         if (FreeTopTenTriple[iy]->len < lenTriple) {
1681           for (unsigned int iz = nTop-1; iz > iy; iz--) {
1682             FreeTopTenTriple[iz] = FreeTopTenTriple[iz-1];
1683           }
1684           FreeTopTenTriple[iy] = &FreeArray[ix];
1685           if (FreeTopTenTriple[nTop-1] != NULL) {
1686             currMax10 = FreeTopTenTriple[nTop-1]->len;
1687           }
1688           break;
1689         }
1690       }
1691       if (iy == nTop) {
1692         ast->print_cr("Internal logic error. New Max10 = %d detected, but could not be merged. Old Max10 = %d",
1693                       lenTriple, currMax10);
1694         continue;
1695       }
1696       if (FreeTopTenTriple[iy] == NULL) {
1697         FreeTopTenTriple[iy] = &FreeArray[ix];
1698         if (iy == (nTop-1)) {
1699           currMax10 = lenTriple;
1700         }
1701       }
1702     }
1703   }
1704   BUFFEREDSTREAM_FLUSH_AUTO("")
1705 
1706   {
1707     printBox(ast, '-', "Top Ten Free-Occupied-Free Triples in ", heapName);
1708     ast->print_cr("  Use this information to judge how likely it is that a large(r) free block\n"
1709                   "  might get created by code cache sweeping.\n"
1710                   "  If all the occupied blocks can be swept, the three free blocks will be\n"
1711                   "  merged into one (much larger) free block. That would reduce free space\n"
1712                   "  fragmentation.\n");
1713 
1714     //---<  print Top Ten Free-Occupied-Free Triples  >---
1715     for (unsigned int iy = 0; (iy < nTop) && (FreeTopTenTriple[iy] != NULL); iy++) {
1716       ast->print("Pos %3d: Block %4d - size " HEX32_FORMAT ",", iy+1, FreeTopTenTriple[iy]->index, FreeTopTenTriple[iy]->len);
1717       ast->fill_to(39);
1718       ast->print("Gap (to next) " HEX32_FORMAT ",", FreeTopTenTriple[iy]->gap);
1719       ast->fill_to(63);
1720       ast->print("#blocks (in gap) %d", FreeTopTenTriple[iy]->n_gapBlocks);
1721       ast->cr();
1722       BUFFEREDSTREAM_FLUSH_AUTO("")
1723     }
1724   }
1725   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
1726 }
1727 
1728 
1729 void CodeHeapState::print_count(outputStream* out, CodeHeap* heap) {
1730   if (!initialization_complete) {
1731     return;
1732   }
1733 
1734   const char* heapName   = get_heapName(heap);
1735   get_HeapStatGlobals(out, heapName);
1736 
1737   if ((StatArray == NULL) || (alloc_granules == 0)) {
1738     return;
1739   }
1740   BUFFEREDSTREAM_DECL(ast, out)
1741 
1742   unsigned int granules_per_line = 32;
1743   char*        low_bound         = heap->low_boundary();
1744 
1745   {
1746     printBox(ast, '=', "B L O C K   C O U N T S   for ", heapName);
1747     ast->print_cr("  Each granule contains an individual number of heap blocks. Large blocks\n"
1748                   "  may span multiple granules and are counted for each granule they touch.\n");
1749     if (segment_granules) {
1750       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1751                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1752                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1753                     "  Occupied granules show their BlobType character, see legend.\n");
1754       print_blobType_legend(ast);
1755     }
1756     BUFFEREDSTREAM_FLUSH_LOCKED("")
1757   }
1758 
1759   {
1760     if (segment_granules) {
1761       printBox(ast, '-', "Total (all types) count for granule size == segment size", NULL);
1762 
1763       granules_per_line = 128;
1764       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1765         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1766         print_blobType_single(ast, StatArray[ix].type);
1767       }
1768     } else {
1769       printBox(ast, '-', "Total (all tiers) count, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1770 
1771       granules_per_line = 128;
1772       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1773         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1774         unsigned int count = StatArray[ix].t1_count   + StatArray[ix].t2_count   + StatArray[ix].tx_count
1775                            + StatArray[ix].stub_count + StatArray[ix].dead_count;
1776         print_count_single(ast, count);
1777       }
1778     }
1779     BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1780   }
1781 
1782   {
1783     if (nBlocks_t1 > 0) {
1784       printBox(ast, '-', "Tier1 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1785 
1786       granules_per_line = 128;
1787       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1788         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1789         if (segment_granules && StatArray[ix].t1_count > 0) {
1790           print_blobType_single(ast, StatArray[ix].type);
1791         } else {
1792           print_count_single(ast, StatArray[ix].t1_count);
1793         }
1794       }
1795       ast->print("|");
1796     } else {
1797       ast->print("No Tier1 nMethods found in CodeHeap.");
1798     }
1799     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1800   }
1801 
1802   {
1803     if (nBlocks_t2 > 0) {
1804       printBox(ast, '-', "Tier2 nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1805 
1806       granules_per_line = 128;
1807       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1808         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1809         if (segment_granules && StatArray[ix].t2_count > 0) {
1810           print_blobType_single(ast, StatArray[ix].type);
1811         } else {
1812           print_count_single(ast, StatArray[ix].t2_count);
1813         }
1814       }
1815       ast->print("|");
1816     } else {
1817       ast->print("No Tier2 nMethods found in CodeHeap.");
1818     }
1819     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1820   }
1821 
1822   {
1823     if (nBlocks_alive > 0) {
1824       printBox(ast, '-', "not_used/not_entrant/not_installed nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1825 
1826       granules_per_line = 128;
1827       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1828         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1829         if (segment_granules && StatArray[ix].tx_count > 0) {
1830           print_blobType_single(ast, StatArray[ix].type);
1831         } else {
1832           print_count_single(ast, StatArray[ix].tx_count);
1833         }
1834       }
1835       ast->print("|");
1836     } else {
1837       ast->print("No not_used/not_entrant nMethods found in CodeHeap.");
1838     }
1839     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1840   }
1841 
1842   {
1843     if (nBlocks_stub > 0) {
1844       printBox(ast, '-', "Stub & Blob count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1845 
1846       granules_per_line = 128;
1847       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1848         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1849         if (segment_granules && StatArray[ix].stub_count > 0) {
1850           print_blobType_single(ast, StatArray[ix].type);
1851         } else {
1852           print_count_single(ast, StatArray[ix].stub_count);
1853         }
1854       }
1855       ast->print("|");
1856     } else {
1857       ast->print("No Stubs and Blobs found in CodeHeap.");
1858     }
1859     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1860   }
1861 
1862   {
1863     if (nBlocks_dead > 0) {
1864       printBox(ast, '-', "Dead nMethod count only, 0x1..0xf. '*' indicates >= 16 blocks, ' ' indicates empty", NULL);
1865 
1866       granules_per_line = 128;
1867       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1868         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1869         if (segment_granules && StatArray[ix].dead_count > 0) {
1870           print_blobType_single(ast, StatArray[ix].type);
1871         } else {
1872           print_count_single(ast, StatArray[ix].dead_count);
1873         }
1874       }
1875       ast->print("|");
1876     } else {
1877       ast->print("No dead nMethods found in CodeHeap.");
1878     }
1879     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1880   }
1881 
1882   {
1883     if (!segment_granules) { // Prevent totally redundant printouts
1884       printBox(ast, '-', "Count by tier (combined, no dead blocks): <#t1>:<#t2>:<#s>, 0x0..0xf. '*' indicates >= 16 blocks", NULL);
1885 
1886       granules_per_line = 24;
1887       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1888         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1889 
1890         print_count_single(ast, StatArray[ix].t1_count);
1891         ast->print(":");
1892         print_count_single(ast, StatArray[ix].t2_count);
1893         ast->print(":");
1894         if (segment_granules && StatArray[ix].stub_count > 0) {
1895           print_blobType_single(ast, StatArray[ix].type);
1896         } else {
1897           print_count_single(ast, StatArray[ix].stub_count);
1898         }
1899         ast->print(" ");
1900       }
1901       BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1902     }
1903   }
1904 }
1905 
1906 
1907 void CodeHeapState::print_space(outputStream* out, CodeHeap* heap) {
1908   if (!initialization_complete) {
1909     return;
1910   }
1911 
1912   const char* heapName   = get_heapName(heap);
1913   get_HeapStatGlobals(out, heapName);
1914 
1915   if ((StatArray == NULL) || (alloc_granules == 0)) {
1916     return;
1917   }
1918   BUFFEREDSTREAM_DECL(ast, out)
1919 
1920   unsigned int granules_per_line = 32;
1921   char*        low_bound         = heap->low_boundary();
1922 
1923   {
1924     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);
1925     ast->print_cr("  The heap space covered by one granule is occupied to a various extend.\n"
1926                   "  The granule occupancy is displayed by one decimal digit per granule.\n");
1927     if (segment_granules) {
1928       ast->print_cr("  You have selected granule size to be as small as segment size.\n"
1929                     "  As a result, each granule contains exactly one block (or a part of one block)\n"
1930                     "  or is displayed as empty (' ') if it's BlobType does not match the selection.\n"
1931                     "  Occupied granules show their BlobType character, see legend.\n");
1932       print_blobType_legend(ast);
1933     } else {
1934       ast->print_cr("  These digits represent a fill percentage range (see legend).\n");
1935       print_space_legend(ast);
1936     }
1937     BUFFEREDSTREAM_FLUSH_LOCKED("")
1938   }
1939 
1940   {
1941     if (segment_granules) {
1942       printBox(ast, '-', "Total (all types) space consumption for granule size == segment size", NULL);
1943 
1944       granules_per_line = 128;
1945       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1946         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1947         print_blobType_single(ast, StatArray[ix].type);
1948       }
1949     } else {
1950       printBox(ast, '-', "Total (all types) space consumption. ' ' indicates empty, '*' indicates full.", NULL);
1951 
1952       granules_per_line = 128;
1953       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1954         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1955         unsigned int space    = StatArray[ix].t1_space   + StatArray[ix].t2_space  + StatArray[ix].tx_space
1956                               + StatArray[ix].stub_space + StatArray[ix].dead_space;
1957         print_space_single(ast, space);
1958       }
1959     }
1960     BUFFEREDSTREAM_FLUSH_LOCKED("|\n\n\n")
1961   }
1962 
1963   {
1964     if (nBlocks_t1 > 0) {
1965       printBox(ast, '-', "Tier1 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1966 
1967       granules_per_line = 128;
1968       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1969         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1970         if (segment_granules && StatArray[ix].t1_space > 0) {
1971           print_blobType_single(ast, StatArray[ix].type);
1972         } else {
1973           print_space_single(ast, StatArray[ix].t1_space);
1974         }
1975       }
1976       ast->print("|");
1977     } else {
1978       ast->print("No Tier1 nMethods found in CodeHeap.");
1979     }
1980     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
1981   }
1982 
1983   {
1984     if (nBlocks_t2 > 0) {
1985       printBox(ast, '-', "Tier2 space consumption. ' ' indicates empty, '*' indicates full", NULL);
1986 
1987       granules_per_line = 128;
1988       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
1989         print_line_delim(out, ast, low_bound, ix, granules_per_line);
1990         if (segment_granules && StatArray[ix].t2_space > 0) {
1991           print_blobType_single(ast, StatArray[ix].type);
1992         } else {
1993           print_space_single(ast, StatArray[ix].t2_space);
1994         }
1995       }
1996       ast->print("|");
1997     } else {
1998       ast->print("No Tier2 nMethods found in CodeHeap.");
1999     }
2000     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2001   }
2002 
2003   {
2004     if (nBlocks_alive > 0) {
2005       printBox(ast, '-', "not_used/not_entrant/not_installed space consumption. ' ' indicates empty, '*' indicates full", NULL);
2006 
2007       granules_per_line = 128;
2008       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2009         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2010         if (segment_granules && StatArray[ix].tx_space > 0) {
2011           print_blobType_single(ast, StatArray[ix].type);
2012         } else {
2013           print_space_single(ast, StatArray[ix].tx_space);
2014         }
2015       }
2016       ast->print("|");
2017     } else {
2018       ast->print("No Tier2 nMethods found in CodeHeap.");
2019     }
2020     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2021   }
2022 
2023   {
2024     if (nBlocks_stub > 0) {
2025       printBox(ast, '-', "Stub and Blob space consumption. ' ' indicates empty, '*' indicates full", NULL);
2026 
2027       granules_per_line = 128;
2028       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2029         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2030         if (segment_granules && StatArray[ix].stub_space > 0) {
2031           print_blobType_single(ast, StatArray[ix].type);
2032         } else {
2033           print_space_single(ast, StatArray[ix].stub_space);
2034         }
2035       }
2036       ast->print("|");
2037     } else {
2038       ast->print("No Stubs and Blobs found in CodeHeap.");
2039     }
2040     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2041   }
2042 
2043   {
2044     if (nBlocks_dead > 0) {
2045       printBox(ast, '-', "Dead space consumption. ' ' indicates empty, '*' indicates full", NULL);
2046 
2047       granules_per_line = 128;
2048       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2049         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2050         print_space_single(ast, StatArray[ix].dead_space);
2051       }
2052       ast->print("|");
2053     } else {
2054       ast->print("No dead nMethods found in CodeHeap.");
2055     }
2056     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2057   }
2058 
2059   {
2060     if (!segment_granules) { // Prevent totally redundant printouts
2061       printBox(ast, '-', "Space consumption by tier (combined): <t1%>:<t2%>:<s%>. ' ' indicates empty, '*' indicates full", NULL);
2062 
2063       granules_per_line = 24;
2064       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2065         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2066 
2067         if (segment_granules && StatArray[ix].t1_space > 0) {
2068           print_blobType_single(ast, StatArray[ix].type);
2069         } else {
2070           print_space_single(ast, StatArray[ix].t1_space);
2071         }
2072         ast->print(":");
2073         if (segment_granules && StatArray[ix].t2_space > 0) {
2074           print_blobType_single(ast, StatArray[ix].type);
2075         } else {
2076           print_space_single(ast, StatArray[ix].t2_space);
2077         }
2078         ast->print(":");
2079         if (segment_granules && StatArray[ix].stub_space > 0) {
2080           print_blobType_single(ast, StatArray[ix].type);
2081         } else {
2082           print_space_single(ast, StatArray[ix].stub_space);
2083         }
2084         ast->print(" ");
2085       }
2086       ast->print("|");
2087       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2088     }
2089   }
2090 }
2091 
2092 void CodeHeapState::print_age(outputStream* out, CodeHeap* heap) {
2093   if (!initialization_complete) {
2094     return;
2095   }
2096 
2097   const char* heapName   = get_heapName(heap);
2098   get_HeapStatGlobals(out, heapName);
2099 
2100   if ((StatArray == NULL) || (alloc_granules == 0)) {
2101     return;
2102   }
2103   BUFFEREDSTREAM_DECL(ast, out)
2104 
2105   unsigned int granules_per_line = 32;
2106   char*        low_bound         = heap->low_boundary();
2107 
2108   {
2109     printBox(ast, '=', "M E T H O D   A G E   by CompileID for ", heapName);
2110     ast->print_cr("  The age of a compiled method in the CodeHeap is not available as a\n"
2111                   "  time stamp. Instead, a relative age is deducted from the method's compilation ID.\n"
2112                   "  Age information is available for tier1 and tier2 methods only. There is no\n"
2113                   "  age information for stubs and blobs, because they have no compilation ID assigned.\n"
2114                   "  Information for the youngest method (highest ID) in the granule is printed.\n"
2115                   "  Refer to the legend to learn how method age is mapped to the displayed digit.");
2116     print_age_legend(ast);
2117     BUFFEREDSTREAM_FLUSH_LOCKED("")
2118   }
2119 
2120   {
2121     printBox(ast, '-', "Age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2122 
2123     granules_per_line = 128;
2124     for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2125       print_line_delim(out, ast, low_bound, ix, granules_per_line);
2126       unsigned int age1      = StatArray[ix].t1_age;
2127       unsigned int age2      = StatArray[ix].t2_age;
2128       unsigned int agex      = StatArray[ix].tx_age;
2129       unsigned int age       = age1 > age2 ? age1 : age2;
2130       age       = age > agex ? age : agex;
2131       print_age_single(ast, age);
2132     }
2133     ast->print("|");
2134     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2135   }
2136 
2137   {
2138     if (nBlocks_t1 > 0) {
2139       printBox(ast, '-', "Tier1 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2140 
2141       granules_per_line = 128;
2142       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2143         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2144         print_age_single(ast, StatArray[ix].t1_age);
2145       }
2146       ast->print("|");
2147     } else {
2148       ast->print("No Tier1 nMethods found in CodeHeap.");
2149     }
2150     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2151   }
2152 
2153   {
2154     if (nBlocks_t2 > 0) {
2155       printBox(ast, '-', "Tier2 age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2156 
2157       granules_per_line = 128;
2158       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2159         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2160         print_age_single(ast, StatArray[ix].t2_age);
2161       }
2162       ast->print("|");
2163     } else {
2164       ast->print("No Tier2 nMethods found in CodeHeap.");
2165     }
2166     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2167   }
2168 
2169   {
2170     if (nBlocks_alive > 0) {
2171       printBox(ast, '-', "not_used/not_entrant/not_installed age distribution. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2172 
2173       granules_per_line = 128;
2174       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2175         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2176         print_age_single(ast, StatArray[ix].tx_age);
2177       }
2178       ast->print("|");
2179     } else {
2180       ast->print("No Tier2 nMethods found in CodeHeap.");
2181     }
2182     BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2183   }
2184 
2185   {
2186     if (!segment_granules) { // Prevent totally redundant printouts
2187       printBox(ast, '-', "age distribution by tier <a1>:<a2>. '0' indicates youngest 1/256, '8': oldest half, ' ': no age information", NULL);
2188 
2189       granules_per_line = 32;
2190       for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2191         print_line_delim(out, ast, low_bound, ix, granules_per_line);
2192         print_age_single(ast, StatArray[ix].t1_age);
2193         ast->print(":");
2194         print_age_single(ast, StatArray[ix].t2_age);
2195         ast->print(" ");
2196       }
2197       ast->print("|");
2198       BUFFEREDSTREAM_FLUSH_LOCKED("\n\n\n")
2199     }
2200   }
2201 }
2202 
2203 
2204 void CodeHeapState::print_names(outputStream* out, CodeHeap* heap) {
2205   if (!initialization_complete) {
2206     return;
2207   }
2208 
2209   const char* heapName   = get_heapName(heap);
2210   get_HeapStatGlobals(out, heapName);
2211 
2212   if ((StatArray == NULL) || (alloc_granules == 0)) {
2213     return;
2214   }
2215   BUFFEREDSTREAM_DECL(ast, out)
2216 
2217   unsigned int granules_per_line   = 128;
2218   char*        low_bound           = heap->low_boundary();
2219   CodeBlob*    last_blob           = NULL;
2220   bool         name_in_addr_range  = true;
2221   bool         have_locks          = holding_required_locks();
2222 
2223   //---<  print at least 128K per block (i.e. between headers)  >---
2224   if (granules_per_line*granule_size < 128*K) {
2225     granules_per_line = (unsigned int)((128*K)/granule_size);
2226   }
2227 
2228   printBox(ast, '=', "M E T H O D   N A M E S   for ", heapName);
2229   ast->print_cr("  Method names are dynamically retrieved from the code cache at print time.\n"
2230                 "  Due to the living nature of the code heap and because the CodeCache_lock\n"
2231                 "  is not continuously held, the displayed name might be wrong or no name\n"
2232                 "  might be found at all. The likelihood for that to happen increases\n"
2233                 "  over time passed between aggregation and print steps.\n");
2234   BUFFEREDSTREAM_FLUSH_LOCKED("")
2235 
2236   for (unsigned int ix = 0; ix < alloc_granules; ix++) {
2237     //---<  print a new blob on a new line  >---
2238     if (ix%granules_per_line == 0) {
2239       if (!name_in_addr_range) {
2240         ast->print_cr("No methods, blobs, or stubs found in this address range");
2241       }
2242       name_in_addr_range = false;
2243 
2244       size_t end_ix = (ix+granules_per_line <= alloc_granules) ? ix+granules_per_line : alloc_granules;
2245       ast->cr();
2246       ast->print_cr("--------------------------------------------------------------------");
2247       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);
2248       ast->print_cr("--------------------------------------------------------------------");
2249       BUFFEREDSTREAM_FLUSH_AUTO("")
2250     }
2251     // Only check granule if it contains at least one blob.
2252     unsigned int nBlobs  = StatArray[ix].t1_count   + StatArray[ix].t2_count + StatArray[ix].tx_count +
2253                            StatArray[ix].stub_count + StatArray[ix].dead_count;
2254     if (nBlobs > 0 ) {
2255     for (unsigned int is = 0; is < granule_size; is+=(unsigned int)seg_size) {
2256       // heap->find_start() is safe. Only works on _segmap.
2257       // Returns NULL or void*. Returned CodeBlob may be uninitialized.
2258       char*     this_seg  = low_bound + ix*granule_size + is;
2259       CodeBlob* this_blob = (CodeBlob*)(heap->find_start(this_seg));
2260       bool   blob_is_safe = blob_access_is_safe(this_blob);
2261       // blob could have been flushed, freed, and merged.
2262       // this_blob < last_blob is an indicator for that.
2263       if (blob_is_safe && (this_blob > last_blob)) {
2264         last_blob          = this_blob;
2265 
2266         //---<  get type and name  >---
2267         blobType       cbType = noType;
2268         if (segment_granules) {
2269           cbType = (blobType)StatArray[ix].type;
2270         } else {
2271           //---<  access these fields only if we own the CodeCache_lock  >---
2272           if (have_locks) {
2273             cbType = get_cbType(this_blob);
2274           }
2275         }
2276 
2277         //---<  access these fields only if we own the CodeCache_lock  >---
2278         const char* blob_name = "<unavailable>";
2279         nmethod*           nm = NULL;
2280         if (have_locks) {
2281           blob_name = this_blob->name();
2282           nm        = this_blob->as_nmethod_or_null();
2283           // this_blob->name() could return NULL if no name was given to CTOR. Inlined, maybe invisible on stack
2284           if (blob_name == NULL) {
2285             blob_name = "<unavailable>";
2286           }
2287         }
2288 
2289         //---<  print table header for new print range  >---
2290         if (!name_in_addr_range) {
2291           name_in_addr_range = true;
2292           ast->fill_to(51);
2293           ast->print("%9s", "compiler");
2294           ast->fill_to(61);
2295           ast->print_cr("%6s", "method");
2296           ast->print_cr("%18s %13s %17s %9s  %5s %18s  %s", "Addr(module)      ", "offset", "size", " type lvl", " temp", "blobType          ", "Name");
2297           BUFFEREDSTREAM_FLUSH_AUTO("")
2298         }
2299 
2300         //---<  print line prefix (address and offset from CodeHeap start)  >---
2301         ast->print(INTPTR_FORMAT, p2i(this_blob));
2302         ast->fill_to(19);
2303         ast->print("(+" PTR32_FORMAT ")", (unsigned int)((char*)this_blob-low_bound));
2304         ast->fill_to(33);
2305 
2306         // access nmethod and Method fields only if we own the CodeCache_lock.
2307         // This fact is implicitly transported via nm != NULL.
2308         if (nmethod_access_is_safe(nm)) {
2309           Method* method = nm->method();
2310           ResourceMark rm;
2311           //---<  collect all data to locals as quickly as possible  >---
2312           unsigned int total_size = nm->total_size();
2313           int          hotness    = nm->hotness_counter();
2314           bool         get_name   = (cbType == nMethod_inuse) || (cbType == nMethod_notused);
2315           //---<  nMethod size in hex  >---
2316           ast->print(PTR32_FORMAT, total_size);
2317           ast->print("(" SIZE_FORMAT_W(4) "K)", total_size/K);
2318           //---<  compiler information  >---
2319           ast->fill_to(51);
2320           ast->print("%5s %3d", compTypeName[StatArray[ix].compiler], StatArray[ix].level);
2321           //---<  method temperature  >---
2322           ast->fill_to(62);
2323           ast->print("%5d", hotness);
2324           //---<  name and signature  >---
2325           ast->fill_to(62+6);
2326           ast->print("%s", blobTypeName[cbType]);
2327           ast->fill_to(82+6);
2328           if (cbType == nMethod_dead) {
2329             ast->print("%14s", " zombie method");
2330           }
2331 
2332           if (get_name) {
2333             Symbol* methName  = method->name();
2334             const char*   methNameS = (methName == NULL) ? NULL : methName->as_C_string();
2335             methNameS = (methNameS == NULL) ? "<method name unavailable>" : methNameS;
2336             Symbol* methSig   = method->signature();
2337             const char*   methSigS  = (methSig  == NULL) ? NULL : methSig->as_C_string();
2338             methSigS  = (methSigS  == NULL) ? "<method signature unavailable>" : methSigS;
2339             ast->print("%s", methNameS);
2340             ast->print("%s", methSigS);
2341           } else {
2342             ast->print("%s", blob_name);
2343           }
2344         } else if (blob_is_safe) {
2345           ast->fill_to(62+6);
2346           ast->print("%s", blobTypeName[cbType]);
2347           ast->fill_to(82+6);
2348           ast->print("%s", blob_name);
2349         } else {
2350           ast->fill_to(62+6);
2351           ast->print("<stale blob>");
2352         }
2353         ast->cr();
2354         BUFFEREDSTREAM_FLUSH_AUTO("")
2355       } else if (!blob_is_safe && (this_blob != last_blob) && (this_blob != NULL)) {
2356         last_blob          = this_blob;
2357       }
2358     }
2359     } // nBlobs > 0
2360   }
2361   BUFFEREDSTREAM_FLUSH_LOCKED("\n\n")
2362 }
2363 
2364 
2365 void CodeHeapState::printBox(outputStream* ast, const char border, const char* text1, const char* text2) {
2366   unsigned int lineLen = 1 + 2 + 2 + 1;
2367   char edge, frame;
2368 
2369   if (text1 != NULL) {
2370     lineLen += (unsigned int)strlen(text1); // text1 is much shorter than MAX_INT chars.
2371   }
2372   if (text2 != NULL) {
2373     lineLen += (unsigned int)strlen(text2); // text2 is much shorter than MAX_INT chars.
2374   }
2375   if (border == '-') {
2376     edge  = '+';
2377     frame = '|';
2378   } else {
2379     edge  = border;
2380     frame = border;
2381   }
2382 
2383   ast->print("%c", edge);
2384   for (unsigned int i = 0; i < lineLen-2; i++) {
2385     ast->print("%c", border);
2386   }
2387   ast->print_cr("%c", edge);
2388 
2389   ast->print("%c  ", frame);
2390   if (text1 != NULL) {
2391     ast->print("%s", text1);
2392   }
2393   if (text2 != NULL) {
2394     ast->print("%s", text2);
2395   }
2396   ast->print_cr("  %c", frame);
2397 
2398   ast->print("%c", edge);
2399   for (unsigned int i = 0; i < lineLen-2; i++) {
2400     ast->print("%c", border);
2401   }
2402   ast->print_cr("%c", edge);
2403 }
2404 
2405 void CodeHeapState::print_blobType_legend(outputStream* out) {
2406   out->cr();
2407   printBox(out, '-', "Block types used in the following CodeHeap dump", NULL);
2408   for (int type = noType; type < lastType; type += 1) {
2409     out->print_cr("  %c - %s", blobTypeChar[type], blobTypeName[type]);
2410   }
2411   out->print_cr("  -----------------------------------------------------");
2412   out->cr();
2413 }
2414 
2415 void CodeHeapState::print_space_legend(outputStream* out) {
2416   unsigned int indicator = 0;
2417   unsigned int age_range = 256;
2418   unsigned int range_beg = latest_compilation_id;
2419   out->cr();
2420   printBox(out, '-', "Space ranges, based on granule occupancy", NULL);
2421   out->print_cr("    -   0%% == occupancy");
2422   for (int i=0; i<=9; i++) {
2423     out->print_cr("  %d - %3d%% < occupancy < %3d%%", i, 10*i, 10*(i+1));
2424   }
2425   out->print_cr("  * - 100%% == occupancy");
2426   out->print_cr("  ----------------------------------------------");
2427   out->cr();
2428 }
2429 
2430 void CodeHeapState::print_age_legend(outputStream* out) {
2431   unsigned int indicator = 0;
2432   unsigned int age_range = 256;
2433   unsigned int range_beg = latest_compilation_id;
2434   out->cr();
2435   printBox(out, '-', "Age ranges, based on compilation id", NULL);
2436   while (age_range > 0) {
2437     out->print_cr("  %d - %6d to %6d", indicator, range_beg, latest_compilation_id - latest_compilation_id/age_range);
2438     range_beg = latest_compilation_id - latest_compilation_id/age_range;
2439     age_range /= 2;
2440     indicator += 1;
2441   }
2442   out->print_cr("  -----------------------------------------");
2443   out->cr();
2444 }
2445 
2446 void CodeHeapState::print_blobType_single(outputStream* out, u2 /* blobType */ type) {
2447   out->print("%c", blobTypeChar[type]);
2448 }
2449 
2450 void CodeHeapState::print_count_single(outputStream* out, unsigned short count) {
2451   if (count >= 16)    out->print("*");
2452   else if (count > 0) out->print("%1.1x", count);
2453   else                out->print(" ");
2454 }
2455 
2456 void CodeHeapState::print_space_single(outputStream* out, unsigned short space) {
2457   size_t  space_in_bytes = ((unsigned int)space)<<log2_seg_size;
2458   char    fraction       = (space == 0) ? ' ' : (space_in_bytes >= granule_size-1) ? '*' : char('0'+10*space_in_bytes/granule_size);
2459   out->print("%c", fraction);
2460 }
2461 
2462 void CodeHeapState::print_age_single(outputStream* out, unsigned int age) {
2463   unsigned int indicator = 0;
2464   unsigned int age_range = 256;
2465   if (age > 0) {
2466     while ((age_range > 0) && (latest_compilation_id-age > latest_compilation_id/age_range)) {
2467       age_range /= 2;
2468       indicator += 1;
2469     }
2470     out->print("%c", char('0'+indicator));
2471   } else {
2472     out->print(" ");
2473   }
2474 }
2475 
2476 void CodeHeapState::print_line_delim(outputStream* out, outputStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2477   if (ix % gpl == 0) {
2478     if (ix > 0) {
2479       ast->print("|");
2480     }
2481     ast->cr();
2482     assert(out == ast, "must use the same stream!");
2483 
2484     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2485     ast->fill_to(19);
2486     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2487   }
2488 }
2489 
2490 void CodeHeapState::print_line_delim(outputStream* out, bufferedStream* ast, char* low_bound, unsigned int ix, unsigned int gpl) {
2491   assert(out != ast, "must not use the same stream!");
2492   if (ix % gpl == 0) {
2493     if (ix > 0) {
2494       ast->print("|");
2495     }
2496     ast->cr();
2497 
2498     // can't use BUFFEREDSTREAM_FLUSH_IF("", 512) here.
2499     // can't use this expression. bufferedStream::capacity() does not exist.
2500     // if ((ast->capacity() - ast->size()) < 512) {
2501     // Assume instead that default bufferedStream capacity (4K) was used.
2502     if (ast->size() > 3*K) {
2503       ttyLocker ttyl;
2504       out->print("%s", ast->as_string());
2505       ast->reset();
2506     }
2507 
2508     ast->print(INTPTR_FORMAT, p2i(low_bound + ix*granule_size));
2509     ast->fill_to(19);
2510     ast->print("(+" PTR32_FORMAT "): |", (unsigned int)(ix*granule_size));
2511   }
2512 }
2513 
2514 // Find out which blob type we have at hand.
2515 // Return "noType" if anything abnormal is detected.
2516 CodeHeapState::blobType CodeHeapState::get_cbType(CodeBlob* cb) {
2517   if (cb != NULL) {
2518     if (cb->is_runtime_stub())                return runtimeStub;
2519     if (cb->is_deoptimization_stub())         return deoptimizationStub;
2520     if (cb->is_uncommon_trap_stub())          return uncommonTrapStub;
2521     if (cb->is_exception_stub())              return exceptionStub;
2522     if (cb->is_safepoint_stub())              return safepointStub;
2523     if (cb->is_adapter_blob())                return adapterBlob;
2524     if (cb->is_method_handles_adapter_blob()) return mh_adapterBlob;
2525     if (cb->is_buffer_blob())                 return bufferBlob;
2526 
2527     //---<  access these fields only if we own CodeCache_lock and Compile_lock  >---
2528     // Should be ensured by caller. aggregate() and print_names() do that.
2529     if (holding_required_locks()) {
2530       nmethod*  nm = cb->as_nmethod_or_null();
2531       if (nm != NULL) { // no is_readable check required, nm = (nmethod*)cb.
2532         if (nm->is_zombie())        return nMethod_dead;
2533         if (nm->is_unloaded())      return nMethod_unloaded;
2534         if (nm->is_in_use())        return nMethod_inuse;
2535         if (nm->is_alive() && !(nm->is_not_entrant()))   return nMethod_notused;
2536         if (nm->is_alive())         return nMethod_alive;
2537         return nMethod_dead;
2538       }
2539     }
2540   }
2541   return noType;
2542 }
2543 
2544 // make sure the blob at hand is not garbage.
2545 bool CodeHeapState::blob_access_is_safe(CodeBlob* this_blob) {
2546   return (this_blob != NULL) && // a blob must have been found, obviously
2547          (this_blob->header_size() >= 0) &&
2548          (this_blob->relocation_size() >= 0) &&
2549          ((address)this_blob + this_blob->header_size() == (address)(this_blob->relocation_begin())) &&
2550          ((address)this_blob + CodeBlob::align_code_offset(this_blob->header_size() + this_blob->relocation_size()) == (address)(this_blob->content_begin()));
2551 }
2552 
2553 // make sure the nmethod at hand (and the linked method) is not garbage.
2554 bool CodeHeapState::nmethod_access_is_safe(nmethod* nm) {
2555   Method* method = (nm == NULL) ? NULL : nm->method(); // nm->method() was found to be uninitialized, i.e. != NULL, but invalid.
2556   return (nm != NULL) && (method != NULL) && nm->is_alive() && (method->signature() != NULL);
2557 }
2558 
2559 bool CodeHeapState::holding_required_locks() {
2560   return SafepointSynchronize::is_at_safepoint() ||
2561         (CodeCache_lock->owned_by_self() && Compile_lock->owned_by_self());
2562 }