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