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