allocation.cpp revision 3602:da91efe96a93
1/*
2 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "memory/allocation.hpp"
27#include "memory/allocation.inline.hpp"
28#include "memory/genCollectedHeap.hpp"
29#include "memory/metaspaceShared.hpp"
30#include "memory/resourceArea.hpp"
31#include "memory/universe.hpp"
32#include "runtime/atomic.hpp"
33#include "runtime/os.hpp"
34#include "runtime/task.hpp"
35#include "runtime/threadCritical.hpp"
36#include "services/memTracker.hpp"
37#include "utilities/ostream.hpp"
38
39#ifdef TARGET_OS_FAMILY_linux
40# include "os_linux.inline.hpp"
41#endif
42#ifdef TARGET_OS_FAMILY_solaris
43# include "os_solaris.inline.hpp"
44#endif
45#ifdef TARGET_OS_FAMILY_windows
46# include "os_windows.inline.hpp"
47#endif
48#ifdef TARGET_OS_FAMILY_bsd
49# include "os_bsd.inline.hpp"
50#endif
51
52void* StackObj::operator new(size_t size)  { ShouldNotCallThis(); return 0; };
53void  StackObj::operator delete(void* p)   { ShouldNotCallThis(); };
54void* _ValueObj::operator new(size_t size)  { ShouldNotCallThis(); return 0; };
55void  _ValueObj::operator delete(void* p)   { ShouldNotCallThis(); };
56
57void* MetaspaceObj::operator new(size_t size, ClassLoaderData* loader_data,
58                                size_t word_size, bool read_only, TRAPS) {
59  // Klass has it's own operator new
60  return Metaspace::allocate(loader_data, word_size, read_only,
61                             Metaspace::NonClassType, CHECK_NULL);
62}
63
64bool MetaspaceObj::is_shared() const {
65  return MetaspaceShared::is_in_shared_space(this);
66}
67
68bool MetaspaceObj::is_metadata() const {
69  // ClassLoaderDataGraph::contains((address)this); has lock inversion problems
70  return !Universe::heap()->is_in_reserved(this);
71}
72
73void MetaspaceObj::print_address_on(outputStream* st) const {
74  st->print(" {"INTPTR_FORMAT"}", this);
75}
76
77
78void* ResourceObj::operator new(size_t size, allocation_type type, MEMFLAGS flags) {
79  address res;
80  switch (type) {
81   case C_HEAP:
82    res = (address)AllocateHeap(size, flags, CALLER_PC);
83    DEBUG_ONLY(set_allocation_type(res, C_HEAP);)
84    break;
85   case RESOURCE_AREA:
86    // new(size) sets allocation type RESOURCE_AREA.
87    res = (address)operator new(size);
88    break;
89   default:
90    ShouldNotReachHere();
91  }
92  return res;
93}
94
95void ResourceObj::operator delete(void* p) {
96  assert(((ResourceObj *)p)->allocated_on_C_heap(),
97         "delete only allowed for C_HEAP objects");
98  DEBUG_ONLY(((ResourceObj *)p)->_allocation_t[0] = (uintptr_t)badHeapOopVal;)
99  FreeHeap(p);
100}
101
102#ifdef ASSERT
103void ResourceObj::set_allocation_type(address res, allocation_type type) {
104    // Set allocation type in the resource object
105    uintptr_t allocation = (uintptr_t)res;
106    assert((allocation & allocation_mask) == 0, "address should be aligned to 4 bytes at least");
107    assert(type <= allocation_mask, "incorrect allocation type");
108    ResourceObj* resobj = (ResourceObj *)res;
109    resobj->_allocation_t[0] = ~(allocation + type);
110    if (type != STACK_OR_EMBEDDED) {
111      // Called from operator new() and CollectionSetChooser(),
112      // set verification value.
113      resobj->_allocation_t[1] = (uintptr_t)&(resobj->_allocation_t[1]) + type;
114    }
115}
116
117ResourceObj::allocation_type ResourceObj::get_allocation_type() const {
118    assert(~(_allocation_t[0] | allocation_mask) == (uintptr_t)this, "lost resource object");
119    return (allocation_type)((~_allocation_t[0]) & allocation_mask);
120}
121
122bool ResourceObj::is_type_set() const {
123    allocation_type type = (allocation_type)(_allocation_t[1] & allocation_mask);
124    return get_allocation_type()  == type &&
125           (_allocation_t[1] - type) == (uintptr_t)(&_allocation_t[1]);
126}
127
128ResourceObj::ResourceObj() { // default constructor
129    if (~(_allocation_t[0] | allocation_mask) != (uintptr_t)this) {
130      // Operator new() is not called for allocations
131      // on stack and for embedded objects.
132      set_allocation_type((address)this, STACK_OR_EMBEDDED);
133    } else if (allocated_on_stack()) { // STACK_OR_EMBEDDED
134      // For some reason we got a value which resembles
135      // an embedded or stack object (operator new() does not
136      // set such type). Keep it since it is valid value
137      // (even if it was garbage).
138      // Ignore garbage in other fields.
139    } else if (is_type_set()) {
140      // Operator new() was called and type was set.
141      assert(!allocated_on_stack(),
142             err_msg("not embedded or stack, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
143                     this, get_allocation_type(), _allocation_t[0], _allocation_t[1]));
144    } else {
145      // Operator new() was not called.
146      // Assume that it is embedded or stack object.
147      set_allocation_type((address)this, STACK_OR_EMBEDDED);
148    }
149    _allocation_t[1] = 0; // Zap verification value
150}
151
152ResourceObj::ResourceObj(const ResourceObj& r) { // default copy constructor
153    // Used in ClassFileParser::parse_constant_pool_entries() for ClassFileStream.
154    // Note: garbage may resembles valid value.
155    assert(~(_allocation_t[0] | allocation_mask) != (uintptr_t)this || !is_type_set(),
156           err_msg("embedded or stack only, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
157                   this, get_allocation_type(), _allocation_t[0], _allocation_t[1]));
158    set_allocation_type((address)this, STACK_OR_EMBEDDED);
159    _allocation_t[1] = 0; // Zap verification value
160}
161
162ResourceObj& ResourceObj::operator=(const ResourceObj& r) { // default copy assignment
163    // Used in InlineTree::ok_to_inline() for WarmCallInfo.
164    assert(allocated_on_stack(),
165           err_msg("copy only into local, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
166                   this, get_allocation_type(), _allocation_t[0], _allocation_t[1]));
167    // Keep current _allocation_t value;
168    return *this;
169}
170
171ResourceObj::~ResourceObj() {
172    // allocated_on_C_heap() also checks that encoded (in _allocation) address == this.
173    if (!allocated_on_C_heap()) { // ResourceObj::delete() will zap _allocation for C_heap.
174      _allocation_t[0] = (uintptr_t)badHeapOopVal; // zap type
175    }
176}
177#endif // ASSERT
178
179
180void trace_heap_malloc(size_t size, const char* name, void* p) {
181  // A lock is not needed here - tty uses a lock internally
182  tty->print_cr("Heap malloc " INTPTR_FORMAT " " SIZE_FORMAT " %s", p, size, name == NULL ? "" : name);
183}
184
185
186void trace_heap_free(void* p) {
187  // A lock is not needed here - tty uses a lock internally
188  tty->print_cr("Heap free   " INTPTR_FORMAT, p);
189}
190
191bool warn_new_operator = false; // see vm_main
192
193//--------------------------------------------------------------------------------------
194// ChunkPool implementation
195
196// MT-safe pool of chunks to reduce malloc/free thrashing
197// NB: not using Mutex because pools are used before Threads are initialized
198class ChunkPool: public CHeapObj<mtInternal> {
199  Chunk*       _first;        // first cached Chunk; its first word points to next chunk
200  size_t       _num_chunks;   // number of unused chunks in pool
201  size_t       _num_used;     // number of chunks currently checked out
202  const size_t _size;         // size of each chunk (must be uniform)
203
204  // Our three static pools
205  static ChunkPool* _large_pool;
206  static ChunkPool* _medium_pool;
207  static ChunkPool* _small_pool;
208
209  // return first element or null
210  void* get_first() {
211    Chunk* c = _first;
212    if (_first) {
213      _first = _first->next();
214      _num_chunks--;
215    }
216    return c;
217  }
218
219 public:
220  // All chunks in a ChunkPool has the same size
221   ChunkPool(size_t size) : _size(size) { _first = NULL; _num_chunks = _num_used = 0; }
222
223  // Allocate a new chunk from the pool (might expand the pool)
224  _NOINLINE_ void* allocate(size_t bytes) {
225    assert(bytes == _size, "bad size");
226    void* p = NULL;
227    // No VM lock can be taken inside ThreadCritical lock, so os::malloc
228    // should be done outside ThreadCritical lock due to NMT
229    { ThreadCritical tc;
230      _num_used++;
231      p = get_first();
232    }
233    if (p == NULL) p = os::malloc(bytes, mtChunk, CURRENT_PC);
234    if (p == NULL)
235      vm_exit_out_of_memory(bytes, "ChunkPool::allocate");
236
237    return p;
238  }
239
240  // Return a chunk to the pool
241  void free(Chunk* chunk) {
242    assert(chunk->length() + Chunk::aligned_overhead_size() == _size, "bad size");
243    ThreadCritical tc;
244    _num_used--;
245
246    // Add chunk to list
247    chunk->set_next(_first);
248    _first = chunk;
249    _num_chunks++;
250  }
251
252  // Prune the pool
253  void free_all_but(size_t n) {
254    Chunk* cur = NULL;
255    Chunk* next;
256    {
257    // if we have more than n chunks, free all of them
258    ThreadCritical tc;
259    if (_num_chunks > n) {
260      // free chunks at end of queue, for better locality
261        cur = _first;
262      for (size_t i = 0; i < (n - 1) && cur != NULL; i++) cur = cur->next();
263
264      if (cur != NULL) {
265          next = cur->next();
266        cur->set_next(NULL);
267        cur = next;
268
269          _num_chunks = n;
270        }
271      }
272    }
273
274    // Free all remaining chunks, outside of ThreadCritical
275    // to avoid deadlock with NMT
276        while(cur != NULL) {
277          next = cur->next();
278      os::free(cur, mtChunk);
279          cur = next;
280        }
281      }
282
283  // Accessors to preallocated pool's
284  static ChunkPool* large_pool()  { assert(_large_pool  != NULL, "must be initialized"); return _large_pool;  }
285  static ChunkPool* medium_pool() { assert(_medium_pool != NULL, "must be initialized"); return _medium_pool; }
286  static ChunkPool* small_pool()  { assert(_small_pool  != NULL, "must be initialized"); return _small_pool;  }
287
288  static void initialize() {
289    _large_pool  = new ChunkPool(Chunk::size        + Chunk::aligned_overhead_size());
290    _medium_pool = new ChunkPool(Chunk::medium_size + Chunk::aligned_overhead_size());
291    _small_pool  = new ChunkPool(Chunk::init_size   + Chunk::aligned_overhead_size());
292  }
293
294  static void clean() {
295    enum { BlocksToKeep = 5 };
296     _small_pool->free_all_but(BlocksToKeep);
297     _medium_pool->free_all_but(BlocksToKeep);
298     _large_pool->free_all_but(BlocksToKeep);
299  }
300};
301
302ChunkPool* ChunkPool::_large_pool  = NULL;
303ChunkPool* ChunkPool::_medium_pool = NULL;
304ChunkPool* ChunkPool::_small_pool  = NULL;
305
306void chunkpool_init() {
307  ChunkPool::initialize();
308}
309
310void
311Chunk::clean_chunk_pool() {
312  ChunkPool::clean();
313}
314
315
316//--------------------------------------------------------------------------------------
317// ChunkPoolCleaner implementation
318//
319
320class ChunkPoolCleaner : public PeriodicTask {
321  enum { CleaningInterval = 5000 };      // cleaning interval in ms
322
323 public:
324   ChunkPoolCleaner() : PeriodicTask(CleaningInterval) {}
325   void task() {
326     ChunkPool::clean();
327   }
328};
329
330//--------------------------------------------------------------------------------------
331// Chunk implementation
332
333void* Chunk::operator new(size_t requested_size, size_t length) {
334  // requested_size is equal to sizeof(Chunk) but in order for the arena
335  // allocations to come out aligned as expected the size must be aligned
336  // to expected arean alignment.
337  // expect requested_size but if sizeof(Chunk) doesn't match isn't proper size we must align it.
338  assert(ARENA_ALIGN(requested_size) == aligned_overhead_size(), "Bad alignment");
339  size_t bytes = ARENA_ALIGN(requested_size) + length;
340  switch (length) {
341   case Chunk::size:        return ChunkPool::large_pool()->allocate(bytes);
342   case Chunk::medium_size: return ChunkPool::medium_pool()->allocate(bytes);
343   case Chunk::init_size:   return ChunkPool::small_pool()->allocate(bytes);
344   default: {
345     void *p =  os::malloc(bytes, mtChunk, CALLER_PC);
346     if (p == NULL)
347       vm_exit_out_of_memory(bytes, "Chunk::new");
348     return p;
349   }
350  }
351}
352
353void Chunk::operator delete(void* p) {
354  Chunk* c = (Chunk*)p;
355  switch (c->length()) {
356   case Chunk::size:        ChunkPool::large_pool()->free(c); break;
357   case Chunk::medium_size: ChunkPool::medium_pool()->free(c); break;
358   case Chunk::init_size:   ChunkPool::small_pool()->free(c); break;
359   default:                 os::free(c, mtChunk);
360  }
361}
362
363Chunk::Chunk(size_t length) : _len(length) {
364  _next = NULL;         // Chain on the linked list
365}
366
367
368void Chunk::chop() {
369  Chunk *k = this;
370  while( k ) {
371    Chunk *tmp = k->next();
372    // clear out this chunk (to detect allocation bugs)
373    if (ZapResourceArea) memset(k->bottom(), badResourceValue, k->length());
374    delete k;                   // Free chunk (was malloc'd)
375    k = tmp;
376  }
377}
378
379void Chunk::next_chop() {
380  _next->chop();
381  _next = NULL;
382}
383
384
385void Chunk::start_chunk_pool_cleaner_task() {
386#ifdef ASSERT
387  static bool task_created = false;
388  assert(!task_created, "should not start chuck pool cleaner twice");
389  task_created = true;
390#endif
391  ChunkPoolCleaner* cleaner = new ChunkPoolCleaner();
392  cleaner->enroll();
393}
394
395//------------------------------Arena------------------------------------------
396NOT_PRODUCT(volatile jint Arena::_instance_count = 0;)
397
398Arena::Arena(size_t init_size) {
399  size_t round_size = (sizeof (char *)) - 1;
400  init_size = (init_size+round_size) & ~round_size;
401  _first = _chunk = new (init_size) Chunk(init_size);
402  _hwm = _chunk->bottom();      // Save the cached hwm, max
403  _max = _chunk->top();
404  set_size_in_bytes(init_size);
405  NOT_PRODUCT(Atomic::inc(&_instance_count);)
406}
407
408Arena::Arena() {
409  _first = _chunk = new (Chunk::init_size) Chunk(Chunk::init_size);
410  _hwm = _chunk->bottom();      // Save the cached hwm, max
411  _max = _chunk->top();
412  set_size_in_bytes(Chunk::init_size);
413  NOT_PRODUCT(Atomic::inc(&_instance_count);)
414}
415
416Arena::Arena(Arena *a) : _chunk(a->_chunk), _hwm(a->_hwm), _max(a->_max), _first(a->_first) {
417  set_size_in_bytes(a->size_in_bytes());
418  NOT_PRODUCT(Atomic::inc(&_instance_count);)
419}
420
421
422Arena *Arena::move_contents(Arena *copy) {
423  copy->destruct_contents();
424  copy->_chunk = _chunk;
425  copy->_hwm   = _hwm;
426  copy->_max   = _max;
427  copy->_first = _first;
428  copy->set_size_in_bytes(size_in_bytes());
429  // Destroy original arena
430  reset();
431  return copy;            // Return Arena with contents
432}
433
434Arena::~Arena() {
435  destruct_contents();
436  NOT_PRODUCT(Atomic::dec(&_instance_count);)
437}
438
439void* Arena::operator new(size_t size) {
440  assert(false, "Use dynamic memory type binding");
441  return NULL;
442}
443
444void* Arena::operator new (size_t size, const std::nothrow_t&  nothrow_constant) {
445  assert(false, "Use dynamic memory type binding");
446  return NULL;
447}
448
449  // dynamic memory type binding
450void* Arena::operator new(size_t size, MEMFLAGS flags) {
451#ifdef ASSERT
452  void* p = (void*)AllocateHeap(size, flags|otArena, CALLER_PC);
453  if (PrintMallocFree) trace_heap_malloc(size, "Arena-new", p);
454  return p;
455#else
456  return (void *) AllocateHeap(size, flags|otArena, CALLER_PC);
457#endif
458}
459
460void* Arena::operator new(size_t size, const std::nothrow_t& nothrow_constant, MEMFLAGS flags) {
461#ifdef ASSERT
462  void* p = os::malloc(size, flags|otArena, CALLER_PC);
463  if (PrintMallocFree) trace_heap_malloc(size, "Arena-new", p);
464  return p;
465#else
466  return os::malloc(size, flags|otArena, CALLER_PC);
467#endif
468}
469
470void Arena::operator delete(void* p) {
471  FreeHeap(p);
472}
473
474// Destroy this arenas contents and reset to empty
475void Arena::destruct_contents() {
476  if (UseMallocOnly && _first != NULL) {
477    char* end = _first->next() ? _first->top() : _hwm;
478    free_malloced_objects(_first, _first->bottom(), end, _hwm);
479  }
480  _first->chop();
481  reset();
482}
483
484// This is high traffic method, but many calls actually don't
485// change the size
486void Arena::set_size_in_bytes(size_t size) {
487  if (_size_in_bytes != size) {
488    _size_in_bytes = size;
489    MemTracker::record_arena_size((address)this, size);
490  }
491}
492
493// Total of all Chunks in arena
494size_t Arena::used() const {
495  size_t sum = _chunk->length() - (_max-_hwm); // Size leftover in this Chunk
496  register Chunk *k = _first;
497  while( k != _chunk) {         // Whilst have Chunks in a row
498    sum += k->length();         // Total size of this Chunk
499    k = k->next();              // Bump along to next Chunk
500  }
501  return sum;                   // Return total consumed space.
502}
503
504void Arena::signal_out_of_memory(size_t sz, const char* whence) const {
505  vm_exit_out_of_memory(sz, whence);
506}
507
508// Grow a new Chunk
509void* Arena::grow( size_t x ) {
510  // Get minimal required size.  Either real big, or even bigger for giant objs
511  size_t len = MAX2(x, (size_t) Chunk::size);
512
513  Chunk *k = _chunk;            // Get filled-up chunk address
514  _chunk = new (len) Chunk(len);
515
516  if (_chunk == NULL) {
517    signal_out_of_memory(len * Chunk::aligned_overhead_size(), "Arena::grow");
518  }
519  if (k) k->set_next(_chunk);   // Append new chunk to end of linked list
520  else _first = _chunk;
521  _hwm  = _chunk->bottom();     // Save the cached hwm, max
522  _max =  _chunk->top();
523  set_size_in_bytes(size_in_bytes() + len);
524  void* result = _hwm;
525  _hwm += x;
526  return result;
527}
528
529
530
531// Reallocate storage in Arena.
532void *Arena::Arealloc(void* old_ptr, size_t old_size, size_t new_size) {
533  assert(new_size >= 0, "bad size");
534  if (new_size == 0) return NULL;
535#ifdef ASSERT
536  if (UseMallocOnly) {
537    // always allocate a new object  (otherwise we'll free this one twice)
538    char* copy = (char*)Amalloc(new_size);
539    size_t n = MIN2(old_size, new_size);
540    if (n > 0) memcpy(copy, old_ptr, n);
541    Afree(old_ptr,old_size);    // Mostly done to keep stats accurate
542    return copy;
543  }
544#endif
545  char *c_old = (char*)old_ptr; // Handy name
546  // Stupid fast special case
547  if( new_size <= old_size ) {  // Shrink in-place
548    if( c_old+old_size == _hwm) // Attempt to free the excess bytes
549      _hwm = c_old+new_size;    // Adjust hwm
550    return c_old;
551  }
552
553  // make sure that new_size is legal
554  size_t corrected_new_size = ARENA_ALIGN(new_size);
555
556  // See if we can resize in-place
557  if( (c_old+old_size == _hwm) &&       // Adjusting recent thing
558      (c_old+corrected_new_size <= _max) ) {      // Still fits where it sits
559    _hwm = c_old+corrected_new_size;      // Adjust hwm
560    return c_old;               // Return old pointer
561  }
562
563  // Oops, got to relocate guts
564  void *new_ptr = Amalloc(new_size);
565  memcpy( new_ptr, c_old, old_size );
566  Afree(c_old,old_size);        // Mostly done to keep stats accurate
567  return new_ptr;
568}
569
570
571// Determine if pointer belongs to this Arena or not.
572bool Arena::contains( const void *ptr ) const {
573#ifdef ASSERT
574  if (UseMallocOnly) {
575    // really slow, but not easy to make fast
576    if (_chunk == NULL) return false;
577    char** bottom = (char**)_chunk->bottom();
578    for (char** p = (char**)_hwm - 1; p >= bottom; p--) {
579      if (*p == ptr) return true;
580    }
581    for (Chunk *c = _first; c != NULL; c = c->next()) {
582      if (c == _chunk) continue;  // current chunk has been processed
583      char** bottom = (char**)c->bottom();
584      for (char** p = (char**)c->top() - 1; p >= bottom; p--) {
585        if (*p == ptr) return true;
586      }
587    }
588    return false;
589  }
590#endif
591  if( (void*)_chunk->bottom() <= ptr && ptr < (void*)_hwm )
592    return true;                // Check for in this chunk
593  for (Chunk *c = _first; c; c = c->next()) {
594    if (c == _chunk) continue;  // current chunk has been processed
595    if ((void*)c->bottom() <= ptr && ptr < (void*)c->top()) {
596      return true;              // Check for every chunk in Arena
597    }
598  }
599  return false;                 // Not in any Chunk, so not in Arena
600}
601
602
603#ifdef ASSERT
604void* Arena::malloc(size_t size) {
605  assert(UseMallocOnly, "shouldn't call");
606  // use malloc, but save pointer in res. area for later freeing
607  char** save = (char**)internal_malloc_4(sizeof(char*));
608  return (*save = (char*)os::malloc(size, mtChunk));
609}
610
611// for debugging with UseMallocOnly
612void* Arena::internal_malloc_4(size_t x) {
613  assert( (x&(sizeof(char*)-1)) == 0, "misaligned size" );
614  check_for_overflow(x, "Arena::internal_malloc_4");
615  if (_hwm + x > _max) {
616    return grow(x);
617  } else {
618    char *old = _hwm;
619    _hwm += x;
620    return old;
621  }
622}
623#endif
624
625
626//--------------------------------------------------------------------------------------
627// Non-product code
628
629#ifndef PRODUCT
630// The global operator new should never be called since it will usually indicate
631// a memory leak.  Use CHeapObj as the base class of such objects to make it explicit
632// that they're allocated on the C heap.
633// Commented out in product version to avoid conflicts with third-party C++ native code.
634// %% note this is causing a problem on solaris debug build. the global
635// new is being called from jdk source and causing data corruption.
636// src/share/native/sun/awt/font/fontmanager/textcache/hsMemory.cpp::hsSoftNew
637// define CATCH_OPERATOR_NEW_USAGE if you want to use this.
638#ifdef CATCH_OPERATOR_NEW_USAGE
639void* operator new(size_t size){
640  static bool warned = false;
641  if (!warned && warn_new_operator)
642    warning("should not call global (default) operator new");
643  warned = true;
644  return (void *) AllocateHeap(size, "global operator new");
645}
646#endif
647
648void AllocatedObj::print() const       { print_on(tty); }
649void AllocatedObj::print_value() const { print_value_on(tty); }
650
651void AllocatedObj::print_on(outputStream* st) const {
652  st->print_cr("AllocatedObj(" INTPTR_FORMAT ")", this);
653}
654
655void AllocatedObj::print_value_on(outputStream* st) const {
656  st->print("AllocatedObj(" INTPTR_FORMAT ")", this);
657}
658
659julong Arena::_bytes_allocated = 0;
660
661void Arena::inc_bytes_allocated(size_t x) { inc_stat_counter(&_bytes_allocated, x); }
662
663AllocStats::AllocStats() {
664  start_mallocs      = os::num_mallocs;
665  start_frees        = os::num_frees;
666  start_malloc_bytes = os::alloc_bytes;
667  start_mfree_bytes  = os::free_bytes;
668  start_res_bytes    = Arena::_bytes_allocated;
669}
670
671julong  AllocStats::num_mallocs() { return os::num_mallocs - start_mallocs; }
672julong  AllocStats::alloc_bytes() { return os::alloc_bytes - start_malloc_bytes; }
673julong  AllocStats::num_frees()   { return os::num_frees - start_frees; }
674julong  AllocStats::free_bytes()  { return os::free_bytes - start_mfree_bytes; }
675julong  AllocStats::resource_bytes() { return Arena::_bytes_allocated - start_res_bytes; }
676void    AllocStats::print() {
677  tty->print_cr(UINT64_FORMAT " mallocs (" UINT64_FORMAT "MB), "
678                UINT64_FORMAT" frees (" UINT64_FORMAT "MB), " UINT64_FORMAT "MB resrc",
679                num_mallocs(), alloc_bytes()/M, num_frees(), free_bytes()/M, resource_bytes()/M);
680}
681
682
683// debugging code
684inline void Arena::free_all(char** start, char** end) {
685  for (char** p = start; p < end; p++) if (*p) os::free(*p);
686}
687
688void Arena::free_malloced_objects(Chunk* chunk, char* hwm, char* max, char* hwm2) {
689  assert(UseMallocOnly, "should not call");
690  // free all objects malloced since resource mark was created; resource area
691  // contains their addresses
692  if (chunk->next()) {
693    // this chunk is full, and some others too
694    for (Chunk* c = chunk->next(); c != NULL; c = c->next()) {
695      char* top = c->top();
696      if (c->next() == NULL) {
697        top = hwm2;     // last junk is only used up to hwm2
698        assert(c->contains(hwm2), "bad hwm2");
699      }
700      free_all((char**)c->bottom(), (char**)top);
701    }
702    assert(chunk->contains(hwm), "bad hwm");
703    assert(chunk->contains(max), "bad max");
704    free_all((char**)hwm, (char**)max);
705  } else {
706    // this chunk was partially used
707    assert(chunk->contains(hwm), "bad hwm");
708    assert(chunk->contains(hwm2), "bad hwm2");
709    free_all((char**)hwm, (char**)hwm2);
710  }
711}
712
713
714ReallocMark::ReallocMark() {
715#ifdef ASSERT
716  Thread *thread = ThreadLocalStorage::get_thread_slow();
717  _nesting = thread->resource_area()->nesting();
718#endif
719}
720
721void ReallocMark::check() {
722#ifdef ASSERT
723  if (_nesting != Thread::current()->resource_area()->nesting()) {
724    fatal("allocation bug: array could grow within nested ResourceMark");
725  }
726#endif
727}
728
729#endif // Non-product
730