allocation.cpp 28.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27
#include "precompiled.hpp"
#include "memory/allocation.hpp"
#include "memory/allocation.inline.hpp"
28 29
#include "memory/genCollectedHeap.hpp"
#include "memory/metaspaceShared.hpp"
30
#include "memory/resourceArea.hpp"
31
#include "memory/universe.hpp"
Z
zgu 已提交
32
#include "runtime/atomic.hpp"
33 34 35
#include "runtime/os.hpp"
#include "runtime/task.hpp"
#include "runtime/threadCritical.hpp"
Z
zgu 已提交
36
#include "services/memTracker.hpp"
37
#include "utilities/ostream.hpp"
Z
zgu 已提交
38

39 40 41 42 43 44 45 46 47
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
48 49 50
#ifdef TARGET_OS_FAMILY_aix
# include "os_aix.inline.hpp"
#endif
N
never 已提交
51 52 53
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
D
duke 已提交
54

55 56 57 58
void* StackObj::operator new(size_t size)     throw() { ShouldNotCallThis(); return 0; }
void  StackObj::operator delete(void* p)              { ShouldNotCallThis(); }
void* StackObj::operator new [](size_t size)  throw() { ShouldNotCallThis(); return 0; }
void  StackObj::operator delete [](void* p)           { ShouldNotCallThis(); }
59

60 61 62 63
void* _ValueObj::operator new(size_t size)    throw() { ShouldNotCallThis(); return 0; }
void  _ValueObj::operator delete(void* p)             { ShouldNotCallThis(); }
void* _ValueObj::operator new [](size_t size) throw() { ShouldNotCallThis(); return 0; }
void  _ValueObj::operator delete [](void* p)          { ShouldNotCallThis(); }
D
duke 已提交
64

65
void* MetaspaceObj::operator new(size_t size, ClassLoaderData* loader_data,
66
                                 size_t word_size, bool read_only,
67
                                 MetaspaceObj::Type type, TRAPS) throw() {
68 69
  // Klass has it's own operator new
  return Metaspace::allocate(loader_data, word_size, read_only,
70
                             type, CHECK_NULL);
71 72 73 74 75 76
}

bool MetaspaceObj::is_shared() const {
  return MetaspaceShared::is_in_shared_space(this);
}

77
bool MetaspaceObj::is_metaspace_object() const {
78
  return Metaspace::contains((void*)this);
79 80
}

81
void MetaspaceObj::print_address_on(outputStream* st) const {
82
  st->print(" {" INTPTR_FORMAT "}", p2i(this));
83 84
}

85
void* ResourceObj::operator new(size_t size, allocation_type type, MEMFLAGS flags) throw() {
D
duke 已提交
86 87 88
  address res;
  switch (type) {
   case C_HEAP:
Z
zgu 已提交
89
    res = (address)AllocateHeap(size, flags, CALLER_PC);
90
    DEBUG_ONLY(set_allocation_type(res, C_HEAP);)
D
duke 已提交
91 92
    break;
   case RESOURCE_AREA:
93
    // new(size) sets allocation type RESOURCE_AREA.
D
duke 已提交
94 95 96 97 98 99 100 101
    res = (address)operator new(size);
    break;
   default:
    ShouldNotReachHere();
  }
  return res;
}

102
void* ResourceObj::operator new [](size_t size, allocation_type type, MEMFLAGS flags) throw() {
103 104 105
  return (address) operator new(size, type, flags);
}

106
void* ResourceObj::operator new(size_t size, const std::nothrow_t&  nothrow_constant,
107
    allocation_type type, MEMFLAGS flags) throw() {
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  //should only call this with std::nothrow, use other operator new() otherwise
  address res;
  switch (type) {
   case C_HEAP:
    res = (address)AllocateHeap(size, flags, CALLER_PC, AllocFailStrategy::RETURN_NULL);
    DEBUG_ONLY(if (res!= NULL) set_allocation_type(res, C_HEAP);)
    break;
   case RESOURCE_AREA:
    // new(size) sets allocation type RESOURCE_AREA.
    res = (address)operator new(size, std::nothrow);
    break;
   default:
    ShouldNotReachHere();
  }
  return res;
}

125
void* ResourceObj::operator new [](size_t size, const std::nothrow_t&  nothrow_constant,
126
    allocation_type type, MEMFLAGS flags) throw() {
127 128
  return (address)operator new(size, nothrow_constant, type, flags);
}
129

D
duke 已提交
130 131 132
void ResourceObj::operator delete(void* p) {
  assert(((ResourceObj *)p)->allocated_on_C_heap(),
         "delete only allowed for C_HEAP objects");
133
  DEBUG_ONLY(((ResourceObj *)p)->_allocation_t[0] = (uintptr_t)badHeapOopVal;)
D
duke 已提交
134 135 136
  FreeHeap(p);
}

137 138 139 140
void ResourceObj::operator delete [](void* p) {
  operator delete(p);
}

141 142 143 144
#ifdef ASSERT
void ResourceObj::set_allocation_type(address res, allocation_type type) {
    // Set allocation type in the resource object
    uintptr_t allocation = (uintptr_t)res;
145
    assert((allocation & allocation_mask) == 0, err_msg("address should be aligned to 4 bytes at least: " INTPTR_FORMAT, p2i(res)));
146
    assert(type <= allocation_mask, "incorrect allocation type");
147 148 149 150 151 152 153
    ResourceObj* resobj = (ResourceObj *)res;
    resobj->_allocation_t[0] = ~(allocation + type);
    if (type != STACK_OR_EMBEDDED) {
      // Called from operator new() and CollectionSetChooser(),
      // set verification value.
      resobj->_allocation_t[1] = (uintptr_t)&(resobj->_allocation_t[1]) + type;
    }
154 155
}

156
ResourceObj::allocation_type ResourceObj::get_allocation_type() const {
157 158 159 160 161 162 163 164
    assert(~(_allocation_t[0] | allocation_mask) == (uintptr_t)this, "lost resource object");
    return (allocation_type)((~_allocation_t[0]) & allocation_mask);
}

bool ResourceObj::is_type_set() const {
    allocation_type type = (allocation_type)(_allocation_t[1] & allocation_mask);
    return get_allocation_type()  == type &&
           (_allocation_t[1] - type) == (uintptr_t)(&_allocation_t[1]);
165 166
}

167
ResourceObj::ResourceObj() { // default constructor
168 169 170
    if (~(_allocation_t[0] | allocation_mask) != (uintptr_t)this) {
      // Operator new() is not called for allocations
      // on stack and for embedded objects.
171
      set_allocation_type((address)this, STACK_OR_EMBEDDED);
172 173 174 175 176 177 178 179 180 181
    } else if (allocated_on_stack()) { // STACK_OR_EMBEDDED
      // For some reason we got a value which resembles
      // an embedded or stack object (operator new() does not
      // set such type). Keep it since it is valid value
      // (even if it was garbage).
      // Ignore garbage in other fields.
    } else if (is_type_set()) {
      // Operator new() was called and type was set.
      assert(!allocated_on_stack(),
             err_msg("not embedded or stack, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
182
                     p2i(this), get_allocation_type(), _allocation_t[0], _allocation_t[1]));
183
    } else {
184 185 186
      // Operator new() was not called.
      // Assume that it is embedded or stack object.
      set_allocation_type((address)this, STACK_OR_EMBEDDED);
187
    }
188
    _allocation_t[1] = 0; // Zap verification value
189 190
}

191
ResourceObj::ResourceObj(const ResourceObj& r) { // default copy constructor
192
    // Used in ClassFileParser::parse_constant_pool_entries() for ClassFileStream.
193 194 195
    // Note: garbage may resembles valid value.
    assert(~(_allocation_t[0] | allocation_mask) != (uintptr_t)this || !is_type_set(),
           err_msg("embedded or stack only, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
196
                   p2i(this), get_allocation_type(), _allocation_t[0], _allocation_t[1]));
197
    set_allocation_type((address)this, STACK_OR_EMBEDDED);
198
    _allocation_t[1] = 0; // Zap verification value
199 200 201 202
}

ResourceObj& ResourceObj::operator=(const ResourceObj& r) { // default copy assignment
    // Used in InlineTree::ok_to_inline() for WarmCallInfo.
203 204
    assert(allocated_on_stack(),
           err_msg("copy only into local, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
205
                   p2i(this), get_allocation_type(), _allocation_t[0], _allocation_t[1]));
206
    // Keep current _allocation_t value;
207 208 209 210
    return *this;
}

ResourceObj::~ResourceObj() {
211
    // allocated_on_C_heap() also checks that encoded (in _allocation) address == this.
212 213
    if (!allocated_on_C_heap()) { // ResourceObj::delete() will zap _allocation for C_heap.
      _allocation_t[0] = (uintptr_t)badHeapOopVal; // zap type
214 215 216 217 218
    }
}
#endif // ASSERT


D
duke 已提交
219 220
void trace_heap_malloc(size_t size, const char* name, void* p) {
  // A lock is not needed here - tty uses a lock internally
221
  tty->print_cr("Heap malloc " INTPTR_FORMAT " " SIZE_FORMAT " %s", p2i(p), size, name == NULL ? "" : name);
D
duke 已提交
222 223 224 225 226
}


void trace_heap_free(void* p) {
  // A lock is not needed here - tty uses a lock internally
227
  tty->print_cr("Heap free   " INTPTR_FORMAT, p2i(p));
D
duke 已提交
228 229 230 231 232 233 234
}

//--------------------------------------------------------------------------------------
// ChunkPool implementation

// MT-safe pool of chunks to reduce malloc/free thrashing
// NB: not using Mutex because pools are used before Threads are initialized
Z
zgu 已提交
235
class ChunkPool: public CHeapObj<mtInternal> {
D
duke 已提交
236 237 238 239 240
  Chunk*       _first;        // first cached Chunk; its first word points to next chunk
  size_t       _num_chunks;   // number of unused chunks in pool
  size_t       _num_used;     // number of chunks currently checked out
  const size_t _size;         // size of each chunk (must be uniform)

241
  // Our four static pools
D
duke 已提交
242 243 244
  static ChunkPool* _large_pool;
  static ChunkPool* _medium_pool;
  static ChunkPool* _small_pool;
245
  static ChunkPool* _tiny_pool;
D
duke 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

  // return first element or null
  void* get_first() {
    Chunk* c = _first;
    if (_first) {
      _first = _first->next();
      _num_chunks--;
    }
    return c;
  }

 public:
  // All chunks in a ChunkPool has the same size
   ChunkPool(size_t size) : _size(size) { _first = NULL; _num_chunks = _num_used = 0; }

  // Allocate a new chunk from the pool (might expand the pool)
262
  _NOINLINE_ void* allocate(size_t bytes, AllocFailType alloc_failmode) {
D
duke 已提交
263 264
    assert(bytes == _size, "bad size");
    void* p = NULL;
Z
zgu 已提交
265 266
    // No VM lock can be taken inside ThreadCritical lock, so os::malloc
    // should be done outside ThreadCritical lock due to NMT
D
duke 已提交
267 268 269 270
    { ThreadCritical tc;
      _num_used++;
      p = get_first();
    }
Z
zgu 已提交
271
    if (p == NULL) p = os::malloc(bytes, mtChunk, CURRENT_PC);
272
    if (p == NULL && alloc_failmode == AllocFailStrategy::EXIT_OOM) {
273
      vm_exit_out_of_memory(bytes, OOM_MALLOC_ERROR, "ChunkPool::allocate");
274
    }
D
duke 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    return p;
  }

  // Return a chunk to the pool
  void free(Chunk* chunk) {
    assert(chunk->length() + Chunk::aligned_overhead_size() == _size, "bad size");
    ThreadCritical tc;
    _num_used--;

    // Add chunk to list
    chunk->set_next(_first);
    _first = chunk;
    _num_chunks++;
  }

  // Prune the pool
  void free_all_but(size_t n) {
Z
zgu 已提交
292 293 294
    Chunk* cur = NULL;
    Chunk* next;
    {
D
duke 已提交
295 296 297 298
    // if we have more than n chunks, free all of them
    ThreadCritical tc;
    if (_num_chunks > n) {
      // free chunks at end of queue, for better locality
Z
zgu 已提交
299
        cur = _first;
D
duke 已提交
300 301 302
      for (size_t i = 0; i < (n - 1) && cur != NULL; i++) cur = cur->next();

      if (cur != NULL) {
Z
zgu 已提交
303
          next = cur->next();
D
duke 已提交
304 305 306
        cur->set_next(NULL);
        cur = next;

Z
zgu 已提交
307 308 309 310 311 312 313
          _num_chunks = n;
        }
      }
    }

    // Free all remaining chunks, outside of ThreadCritical
    // to avoid deadlock with NMT
D
duke 已提交
314 315
        while(cur != NULL) {
          next = cur->next();
Z
zgu 已提交
316
      os::free(cur, mtChunk);
D
duke 已提交
317 318 319 320 321 322 323 324
          cur = next;
        }
      }

  // Accessors to preallocated pool's
  static ChunkPool* large_pool()  { assert(_large_pool  != NULL, "must be initialized"); return _large_pool;  }
  static ChunkPool* medium_pool() { assert(_medium_pool != NULL, "must be initialized"); return _medium_pool; }
  static ChunkPool* small_pool()  { assert(_small_pool  != NULL, "must be initialized"); return _small_pool;  }
325
  static ChunkPool* tiny_pool()   { assert(_tiny_pool   != NULL, "must be initialized"); return _tiny_pool;   }
D
duke 已提交
326 327 328 329 330

  static void initialize() {
    _large_pool  = new ChunkPool(Chunk::size        + Chunk::aligned_overhead_size());
    _medium_pool = new ChunkPool(Chunk::medium_size + Chunk::aligned_overhead_size());
    _small_pool  = new ChunkPool(Chunk::init_size   + Chunk::aligned_overhead_size());
331
    _tiny_pool   = new ChunkPool(Chunk::tiny_size   + Chunk::aligned_overhead_size());
D
duke 已提交
332
  }
333 334 335

  static void clean() {
    enum { BlocksToKeep = 5 };
336
     _tiny_pool->free_all_but(BlocksToKeep);
337 338 339 340
     _small_pool->free_all_but(BlocksToKeep);
     _medium_pool->free_all_but(BlocksToKeep);
     _large_pool->free_all_but(BlocksToKeep);
  }
D
duke 已提交
341 342 343 344 345
};

ChunkPool* ChunkPool::_large_pool  = NULL;
ChunkPool* ChunkPool::_medium_pool = NULL;
ChunkPool* ChunkPool::_small_pool  = NULL;
346
ChunkPool* ChunkPool::_tiny_pool   = NULL;
D
duke 已提交
347 348 349 350 351

void chunkpool_init() {
  ChunkPool::initialize();
}

352 353 354 355 356
void
Chunk::clean_chunk_pool() {
  ChunkPool::clean();
}

D
duke 已提交
357 358 359

//--------------------------------------------------------------------------------------
// ChunkPoolCleaner implementation
360
//
D
duke 已提交
361 362

class ChunkPoolCleaner : public PeriodicTask {
363
  enum { CleaningInterval = 5000 };      // cleaning interval in ms
D
duke 已提交
364 365 366 367

 public:
   ChunkPoolCleaner() : PeriodicTask(CleaningInterval) {}
   void task() {
368
     ChunkPool::clean();
D
duke 已提交
369 370 371 372 373 374
   }
};

//--------------------------------------------------------------------------------------
// Chunk implementation

375
void* Chunk::operator new (size_t requested_size, AllocFailType alloc_failmode, size_t length) throw() {
D
duke 已提交
376 377
  // requested_size is equal to sizeof(Chunk) but in order for the arena
  // allocations to come out aligned as expected the size must be aligned
378
  // to expected arena alignment.
D
duke 已提交
379 380 381 382
  // expect requested_size but if sizeof(Chunk) doesn't match isn't proper size we must align it.
  assert(ARENA_ALIGN(requested_size) == aligned_overhead_size(), "Bad alignment");
  size_t bytes = ARENA_ALIGN(requested_size) + length;
  switch (length) {
383 384 385
   case Chunk::size:        return ChunkPool::large_pool()->allocate(bytes, alloc_failmode);
   case Chunk::medium_size: return ChunkPool::medium_pool()->allocate(bytes, alloc_failmode);
   case Chunk::init_size:   return ChunkPool::small_pool()->allocate(bytes, alloc_failmode);
386
   case Chunk::tiny_size:   return ChunkPool::tiny_pool()->allocate(bytes, alloc_failmode);
D
duke 已提交
387
   default: {
388 389
     void* p = os::malloc(bytes, mtChunk, CALLER_PC);
     if (p == NULL && alloc_failmode == AllocFailStrategy::EXIT_OOM) {
390
       vm_exit_out_of_memory(bytes, OOM_MALLOC_ERROR, "Chunk::new");
391
     }
D
duke 已提交
392 393 394 395 396 397 398 399 400 401 402
     return p;
   }
  }
}

void Chunk::operator delete(void* p) {
  Chunk* c = (Chunk*)p;
  switch (c->length()) {
   case Chunk::size:        ChunkPool::large_pool()->free(c); break;
   case Chunk::medium_size: ChunkPool::medium_pool()->free(c); break;
   case Chunk::init_size:   ChunkPool::small_pool()->free(c); break;
403
   case Chunk::tiny_size:   ChunkPool::tiny_pool()->free(c); break;
Z
zgu 已提交
404
   default:                 os::free(c, mtChunk);
D
duke 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  }
}

Chunk::Chunk(size_t length) : _len(length) {
  _next = NULL;         // Chain on the linked list
}


void Chunk::chop() {
  Chunk *k = this;
  while( k ) {
    Chunk *tmp = k->next();
    // clear out this chunk (to detect allocation bugs)
    if (ZapResourceArea) memset(k->bottom(), badResourceValue, k->length());
    delete k;                   // Free chunk (was malloc'd)
    k = tmp;
  }
}

void Chunk::next_chop() {
  _next->chop();
  _next = NULL;
}


void Chunk::start_chunk_pool_cleaner_task() {
#ifdef ASSERT
  static bool task_created = false;
  assert(!task_created, "should not start chuck pool cleaner twice");
  task_created = true;
#endif
  ChunkPoolCleaner* cleaner = new ChunkPoolCleaner();
  cleaner->enroll();
}

//------------------------------Arena------------------------------------------
Z
zgu 已提交
441
NOT_PRODUCT(volatile jint Arena::_instance_count = 0;)
D
duke 已提交
442 443 444 445

Arena::Arena(size_t init_size) {
  size_t round_size = (sizeof (char *)) - 1;
  init_size = (init_size+round_size) & ~round_size;
446
  _first = _chunk = new (AllocFailStrategy::EXIT_OOM, init_size) Chunk(init_size);
D
duke 已提交
447 448
  _hwm = _chunk->bottom();      // Save the cached hwm, max
  _max = _chunk->top();
449
  _size_in_bytes = 0;
D
duke 已提交
450
  set_size_in_bytes(init_size);
Z
zgu 已提交
451
  NOT_PRODUCT(Atomic::inc(&_instance_count);)
D
duke 已提交
452 453 454
}

Arena::Arena() {
455
  _first = _chunk = new (AllocFailStrategy::EXIT_OOM, Chunk::init_size) Chunk(Chunk::init_size);
D
duke 已提交
456 457
  _hwm = _chunk->bottom();      // Save the cached hwm, max
  _max = _chunk->top();
458
  _size_in_bytes = 0;
D
duke 已提交
459
  set_size_in_bytes(Chunk::init_size);
Z
zgu 已提交
460
  NOT_PRODUCT(Atomic::inc(&_instance_count);)
D
duke 已提交
461 462 463 464 465 466 467 468
}

Arena *Arena::move_contents(Arena *copy) {
  copy->destruct_contents();
  copy->_chunk = _chunk;
  copy->_hwm   = _hwm;
  copy->_max   = _max;
  copy->_first = _first;
469 470 471 472 473 474

  // workaround rare racing condition, which could double count
  // the arena size by native memory tracking
  size_t size = size_in_bytes();
  set_size_in_bytes(0);
  copy->set_size_in_bytes(size);
D
duke 已提交
475 476 477 478 479 480 481
  // Destroy original arena
  reset();
  return copy;            // Return Arena with contents
}

Arena::~Arena() {
  destruct_contents();
Z
zgu 已提交
482 483 484
  NOT_PRODUCT(Atomic::dec(&_instance_count);)
}

485
void* Arena::operator new(size_t size) throw() {
Z
zgu 已提交
486 487 488 489
  assert(false, "Use dynamic memory type binding");
  return NULL;
}

490
void* Arena::operator new (size_t size, const std::nothrow_t&  nothrow_constant) throw() {
Z
zgu 已提交
491 492 493 494 495
  assert(false, "Use dynamic memory type binding");
  return NULL;
}

  // dynamic memory type binding
496
void* Arena::operator new(size_t size, MEMFLAGS flags) throw() {
Z
zgu 已提交
497 498 499 500 501 502 503 504 505
#ifdef ASSERT
  void* p = (void*)AllocateHeap(size, flags|otArena, CALLER_PC);
  if (PrintMallocFree) trace_heap_malloc(size, "Arena-new", p);
  return p;
#else
  return (void *) AllocateHeap(size, flags|otArena, CALLER_PC);
#endif
}

506
void* Arena::operator new(size_t size, const std::nothrow_t& nothrow_constant, MEMFLAGS flags) throw() {
Z
zgu 已提交
507 508 509 510 511 512 513 514 515 516 517
#ifdef ASSERT
  void* p = os::malloc(size, flags|otArena, CALLER_PC);
  if (PrintMallocFree) trace_heap_malloc(size, "Arena-new", p);
  return p;
#else
  return os::malloc(size, flags|otArena, CALLER_PC);
#endif
}

void Arena::operator delete(void* p) {
  FreeHeap(p);
D
duke 已提交
518 519 520 521 522 523 524 525
}

// Destroy this arenas contents and reset to empty
void Arena::destruct_contents() {
  if (UseMallocOnly && _first != NULL) {
    char* end = _first->next() ? _first->top() : _hwm;
    free_malloced_objects(_first, _first->bottom(), end, _hwm);
  }
526 527 528
  // reset size before chop to avoid a rare racing condition
  // that can have total arena memory exceed total chunk memory
  set_size_in_bytes(0);
D
duke 已提交
529 530 531 532
  _first->chop();
  reset();
}

Z
zgu 已提交
533 534 535 536 537 538 539 540
// This is high traffic method, but many calls actually don't
// change the size
void Arena::set_size_in_bytes(size_t size) {
  if (_size_in_bytes != size) {
    _size_in_bytes = size;
    MemTracker::record_arena_size((address)this, size);
  }
}
D
duke 已提交
541 542 543 544 545 546 547 548 549 550 551 552

// Total of all Chunks in arena
size_t Arena::used() const {
  size_t sum = _chunk->length() - (_max-_hwm); // Size leftover in this Chunk
  register Chunk *k = _first;
  while( k != _chunk) {         // Whilst have Chunks in a row
    sum += k->length();         // Total size of this Chunk
    k = k->next();              // Bump along to next Chunk
  }
  return sum;                   // Return total consumed space.
}

553
void Arena::signal_out_of_memory(size_t sz, const char* whence) const {
554
  vm_exit_out_of_memory(sz, OOM_MALLOC_ERROR, whence);
555
}
D
duke 已提交
556 557

// Grow a new Chunk
558
void* Arena::grow(size_t x, AllocFailType alloc_failmode) {
D
duke 已提交
559 560 561 562
  // Get minimal required size.  Either real big, or even bigger for giant objs
  size_t len = MAX2(x, (size_t) Chunk::size);

  Chunk *k = _chunk;            // Get filled-up chunk address
563
  _chunk = new (alloc_failmode, len) Chunk(len);
D
duke 已提交
564

565
  if (_chunk == NULL) {
566
    return NULL;
567
  }
D
duke 已提交
568 569 570 571 572 573 574 575 576 577 578 579 580
  if (k) k->set_next(_chunk);   // Append new chunk to end of linked list
  else _first = _chunk;
  _hwm  = _chunk->bottom();     // Save the cached hwm, max
  _max =  _chunk->top();
  set_size_in_bytes(size_in_bytes() + len);
  void* result = _hwm;
  _hwm += x;
  return result;
}



// Reallocate storage in Arena.
581
void *Arena::Arealloc(void* old_ptr, size_t old_size, size_t new_size, AllocFailType alloc_failmode) {
D
duke 已提交
582 583 584 585 586
  assert(new_size >= 0, "bad size");
  if (new_size == 0) return NULL;
#ifdef ASSERT
  if (UseMallocOnly) {
    // always allocate a new object  (otherwise we'll free this one twice)
587 588 589 590
    char* copy = (char*)Amalloc(new_size, alloc_failmode);
    if (copy == NULL) {
      return NULL;
    }
D
duke 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
    size_t n = MIN2(old_size, new_size);
    if (n > 0) memcpy(copy, old_ptr, n);
    Afree(old_ptr,old_size);    // Mostly done to keep stats accurate
    return copy;
  }
#endif
  char *c_old = (char*)old_ptr; // Handy name
  // Stupid fast special case
  if( new_size <= old_size ) {  // Shrink in-place
    if( c_old+old_size == _hwm) // Attempt to free the excess bytes
      _hwm = c_old+new_size;    // Adjust hwm
    return c_old;
  }

  // make sure that new_size is legal
  size_t corrected_new_size = ARENA_ALIGN(new_size);

  // See if we can resize in-place
  if( (c_old+old_size == _hwm) &&       // Adjusting recent thing
      (c_old+corrected_new_size <= _max) ) {      // Still fits where it sits
    _hwm = c_old+corrected_new_size;      // Adjust hwm
    return c_old;               // Return old pointer
  }

  // Oops, got to relocate guts
616 617 618 619
  void *new_ptr = Amalloc(new_size, alloc_failmode);
  if (new_ptr == NULL) {
    return NULL;
  }
D
duke 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
  memcpy( new_ptr, c_old, old_size );
  Afree(c_old,old_size);        // Mostly done to keep stats accurate
  return new_ptr;
}


// Determine if pointer belongs to this Arena or not.
bool Arena::contains( const void *ptr ) const {
#ifdef ASSERT
  if (UseMallocOnly) {
    // really slow, but not easy to make fast
    if (_chunk == NULL) return false;
    char** bottom = (char**)_chunk->bottom();
    for (char** p = (char**)_hwm - 1; p >= bottom; p--) {
      if (*p == ptr) return true;
    }
    for (Chunk *c = _first; c != NULL; c = c->next()) {
      if (c == _chunk) continue;  // current chunk has been processed
      char** bottom = (char**)c->bottom();
      for (char** p = (char**)c->top() - 1; p >= bottom; p--) {
        if (*p == ptr) return true;
      }
    }
    return false;
  }
#endif
  if( (void*)_chunk->bottom() <= ptr && ptr < (void*)_hwm )
    return true;                // Check for in this chunk
  for (Chunk *c = _first; c; c = c->next()) {
    if (c == _chunk) continue;  // current chunk has been processed
    if ((void*)c->bottom() <= ptr && ptr < (void*)c->top()) {
      return true;              // Check for every chunk in Arena
    }
  }
  return false;                 // Not in any Chunk, so not in Arena
}


#ifdef ASSERT
void* Arena::malloc(size_t size) {
  assert(UseMallocOnly, "shouldn't call");
  // use malloc, but save pointer in res. area for later freeing
  char** save = (char**)internal_malloc_4(sizeof(char*));
Z
zgu 已提交
663
  return (*save = (char*)os::malloc(size, mtChunk));
D
duke 已提交
664 665 666 667 668
}

// for debugging with UseMallocOnly
void* Arena::internal_malloc_4(size_t x) {
  assert( (x&(sizeof(char*)-1)) == 0, "misaligned size" );
669
  check_for_overflow(x, "Arena::internal_malloc_4");
D
duke 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
  if (_hwm + x > _max) {
    return grow(x);
  } else {
    char *old = _hwm;
    _hwm += x;
    return old;
  }
}
#endif


//--------------------------------------------------------------------------------------
// Non-product code

#ifndef PRODUCT
// The global operator new should never be called since it will usually indicate
// a memory leak.  Use CHeapObj as the base class of such objects to make it explicit
// that they're allocated on the C heap.
// Commented out in product version to avoid conflicts with third-party C++ native code.
689
//
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
// In C++98/03 the throwing new operators are defined with the following signature:
//
// void* operator new(std::size_tsize) throw(std::bad_alloc);
// void* operator new[](std::size_tsize) throw(std::bad_alloc);
//
// while all the other (non-throwing) new and delete operators are defined with an empty
// throw clause (i.e. "operator delete(void* p) throw()") which means that they do not
// throw any exceptions (see section 18.4 of the C++ standard).
//
// In the new C++11/14 standard, the signature of the throwing new operators was changed
// by completely omitting the throw clause (which effectively means they could throw any
// exception) while all the other new/delete operators where changed to have a 'nothrow'
// clause instead of an empty throw clause.
//
// Unfortunately, the support for exception specifications among C++ compilers is still
// very fragile. While some more strict compilers like AIX xlC or HP aCC reject to
// override the default throwing new operator with a user operator with an empty throw()
// clause, the MS Visual C++ compiler warns for every non-empty throw clause like
// throw(std::bad_alloc) that it will ignore the exception specification. The following
// operator definitions have been checked to correctly work with all currently supported
// compilers and they should be upwards compatible with C++11/14. Therefore
// PLEASE BE CAREFUL if you change the signature of the following operators!

void* operator new(size_t size) /* throw(std::bad_alloc) */ {
  fatal("Should not call global operator new");
715
  return 0;
D
duke 已提交
716
}
717

718 719
void* operator new [](size_t size) /* throw(std::bad_alloc) */ {
  fatal("Should not call global operator new[]");
720 721 722
  return 0;
}

723
void* operator new(size_t size, const std::nothrow_t&  nothrow_constant) throw() {
724
  fatal("Should not call global operator new");
725 726 727
  return 0;
}

728
void* operator new [](size_t size, std::nothrow_t&  nothrow_constant) throw() {
729
  fatal("Should not call global operator new[]");
730 731 732
  return 0;
}

733 734
void operator delete(void* p) throw() {
  fatal("Should not call global delete");
735 736
}

737 738
void operator delete [](void* p) throw() {
  fatal("Should not call global delete []");
739
}
D
duke 已提交
740 741 742 743 744

void AllocatedObj::print() const       { print_on(tty); }
void AllocatedObj::print_value() const { print_value_on(tty); }

void AllocatedObj::print_on(outputStream* st) const {
745
  st->print_cr("AllocatedObj(" INTPTR_FORMAT ")", p2i(this));
D
duke 已提交
746 747 748
}

void AllocatedObj::print_value_on(outputStream* st) const {
749
  st->print("AllocatedObj(" INTPTR_FORMAT ")", p2i(this));
D
duke 已提交
750 751
}

752 753 754
julong Arena::_bytes_allocated = 0;

void Arena::inc_bytes_allocated(size_t x) { inc_stat_counter(&_bytes_allocated, x); }
D
duke 已提交
755 756

AllocStats::AllocStats() {
757 758
  start_mallocs      = os::num_mallocs;
  start_frees        = os::num_frees;
D
duke 已提交
759
  start_malloc_bytes = os::alloc_bytes;
760 761
  start_mfree_bytes  = os::free_bytes;
  start_res_bytes    = Arena::_bytes_allocated;
D
duke 已提交
762 763
}

764 765 766 767 768
julong  AllocStats::num_mallocs() { return os::num_mallocs - start_mallocs; }
julong  AllocStats::alloc_bytes() { return os::alloc_bytes - start_malloc_bytes; }
julong  AllocStats::num_frees()   { return os::num_frees - start_frees; }
julong  AllocStats::free_bytes()  { return os::free_bytes - start_mfree_bytes; }
julong  AllocStats::resource_bytes() { return Arena::_bytes_allocated - start_res_bytes; }
D
duke 已提交
769
void    AllocStats::print() {
770 771 772
  tty->print_cr(UINT64_FORMAT " mallocs (" UINT64_FORMAT "MB), "
                UINT64_FORMAT" frees (" UINT64_FORMAT "MB), " UINT64_FORMAT "MB resrc",
                num_mallocs(), alloc_bytes()/M, num_frees(), free_bytes()/M, resource_bytes()/M);
D
duke 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
}


// debugging code
inline void Arena::free_all(char** start, char** end) {
  for (char** p = start; p < end; p++) if (*p) os::free(*p);
}

void Arena::free_malloced_objects(Chunk* chunk, char* hwm, char* max, char* hwm2) {
  assert(UseMallocOnly, "should not call");
  // free all objects malloced since resource mark was created; resource area
  // contains their addresses
  if (chunk->next()) {
    // this chunk is full, and some others too
    for (Chunk* c = chunk->next(); c != NULL; c = c->next()) {
      char* top = c->top();
      if (c->next() == NULL) {
        top = hwm2;     // last junk is only used up to hwm2
        assert(c->contains(hwm2), "bad hwm2");
      }
      free_all((char**)c->bottom(), (char**)top);
    }
    assert(chunk->contains(hwm), "bad hwm");
    assert(chunk->contains(max), "bad max");
    free_all((char**)hwm, (char**)max);
  } else {
    // this chunk was partially used
    assert(chunk->contains(hwm), "bad hwm");
    assert(chunk->contains(hwm2), "bad hwm2");
    free_all((char**)hwm, (char**)hwm2);
  }
}


ReallocMark::ReallocMark() {
#ifdef ASSERT
  Thread *thread = ThreadLocalStorage::get_thread_slow();
  _nesting = thread->resource_area()->nesting();
#endif
}

void ReallocMark::check() {
#ifdef ASSERT
  if (_nesting != Thread::current()->resource_area()->nesting()) {
    fatal("allocation bug: array could grow within nested ResourceMark");
  }
#endif
}

#endif // Non-product