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